Add lean source and binary files (part 47)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- lean/OAI/Combinatorics/LowSpaceSubsetSum.leanAdded+16
- lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/FilteredRow.leanAdded+126
- lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/FilteredStream.leanAdded+187
- lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/JoinOne.leanAdded+219
- lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/JoinReaderMap.leanAdded+269
- lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/JoinUserMap.leanAdded+187
- lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MeasuredDistinctCount.leanAdded+93
- lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MeasuredInitialization.leanAdded+170
- lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MeasuredLog2.leanAdded+60
- lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MeasuredMixerCount.leanAdded+93
- lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MeasuredPivot.leanAdded+80
- lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MeasuredRow.leanAdded+212
- lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MeasuredSort.leanAdded+128
- lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MeasuredSortSpace.leanAdded+128
- lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MeasuredStoredRecords.leanAdded+122
- lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MeasuredSumReader.leanAdded+132
- lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MergeCorrectness.leanAdded+131
- lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MergeOrdering.leanAdded+133
- lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MergedReader.leanAdded+182
- lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/ModularCursor.leanAdded+104
- lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/ModularFilters.leanAdded+62
- lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/ModularRows.leanAdded+137
- lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/PaddedRows.leanAdded+101
- lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/PairCursor.leanAdded+37
- lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/ParentPrefixSearch.leanAdded+144
- lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/PrefixAccounting.leanAdded+210
- lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/PrefixCheckList.leanAdded+90
- lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/PrefixMachine.leanAdded+197
- lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/PrefixMachineRun.leanAdded+85
- lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/PrefixTaskCount.leanAdded+180
- lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/ReaderInitializationMap.leanAdded+171
- lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/ReaderMap.leanAdded+363
- lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/RecordedDictionary.leanAdded+166
- lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/RecordedJoin.leanAdded+120
- lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/ResidueFilters.leanAdded+121
- lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/ResidueSort.leanAdded+81
- lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/RowMerge.leanAdded+199
- lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/SliceCursor.leanAdded+102
- lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/SortedFind.leanAdded+146
- lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/StreamGroupFacts.leanAdded+80
- lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/StreamJoin.leanAdded+100
- lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/StreamJoinBounds.leanAdded+241
- lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/StreamJoinCorrectness.leanAdded+203
- lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/StreamPrimitiveWork.leanAdded+94
- lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/StreamWitness.leanAdded+88
- lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/SumReader.leanAdded+131
- lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/TieBuffer.leanAdded+172
- lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/TieGroup.leanAdded+298
- lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/TieReplay.leanAdded+239
- lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/Tournament.leanAdded+281
12345678910111213141516import OAI.Combinatorics.LowSpaceSubsetSum.Search.BudgetDecisionRoundimport OAI.Combinatorics.LowSpaceSubsetSum.Search.BudgetedParentFillimport OAI.Combinatorics.LowSpaceSubsetSum.Search.BudgetedParentReplayimport OAI.Combinatorics.LowSpaceSubsetSum.Mainimport OAI.Combinatorics.LowSpaceSubsetSum.Streams.PrefixAccountingimport OAI.Combinatorics.LowSpaceSubsetSum.Streams.PrefixMachineRunimport OAI.Combinatorics.LowSpaceSubsetSum.Representation.RepresentationLifetimeimport OAI.Combinatorics.LowSpaceSubsetSum.Counting.SignRandomizationimport OAI.Combinatorics.LowSpaceSubsetSum.Search.StoppedGuardedDecisionimport OAI.Combinatorics.LowSpaceSubsetSum.Storage.StoredNodeCells
/-! # Low-space worst-case Subset Sum
One-sided randomized decision with bounded sampling, counted preprocessing,streamed representations, and all-outcome operation and writable-storage counts.-/123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126import OAI.Combinatorics.LowSpaceSubsetSum.Counting.BinarySliceimport OAI.Combinatorics.LowSpaceSubsetSum.Counting.SliceModularimport OAI.Combinatorics.LowSpaceSubsetSum.Streams.PairCursor
namespace OAI
/-!# The actual filtered modular row
The row searches the shared array by the small residue, searches the largeresidue within that slice, and stores only the first occurrence and cursor.Its sorted output is exactly the eligible occurrences. Positivity of thelarge modulus supplies normalized keys; no coprimality is used.-/
namespace LowSpaceSubsetSumnamespace FilteredRow
variable {α β : Type*}
abbrev PrimarySorted (xs : Array β) (w : β → ℤ) (p : ℤ) : Prop := Monotone (fun i : Fin xs.size => w xs[i.val] % p)
abbrev SecondarySorted (xs : Array β) (w : β → ℤ) (p P : ℤ) : Prop := ∀ i j : Fin xs.size, i ≤ j → w xs[i.val] % p = w xs[j.val] % p → w xs[i.val] % P ≤ w xs[j.val] % P
def range (xs : Array β) (w : β → ℤ) (p c wx : ℤ) (k : ℕ) (hs : PrimarySorted xs w p) (hk : xs.size < 2 ^ k) : SliceCursor.Range xs.size := BinarySlice.range xs (fun y => w y % p) ((c - wx) % p) k hs hk
theorem range_length (xs : Array β) (w : β → ℤ) (p c wx : ℤ) (k : ℕ) (hs : PrimarySorted xs w p) (hk : xs.size < 2 ^ k) : (range xs w p c wx k hs hk).length < 2 ^ k := by have := (range xs w p c wx k hs hk).bounded omega
theorem range_sorted (xs : Array β) (w : β → ℤ) (p P c wx : ℤ) (k : ℕ) (hs : PrimarySorted xs w p) (ht : SecondarySorted xs w p P) (hk : xs.size < 2 ^ k) : Monotone (fun i : Fin (range xs w p c wx k hs hk).length => w (SliceCursor.values xs (range xs w p c wx k hs hk) i) % P) := BinarySlice.slice_sorted xs (fun y => w y % p) (fun y => w y % P) ((c - wx) % p) k hs hk ht
def forward (xs : Array β) (wl : α → ℤ) (wr : β → ℤ) (p P c : ℤ) (k : ℕ) (hs : PrimarySorted xs wr p) (hk : xs.size < 2 ^ k) (x : α) : PairCursor.State α xs.size := ⟨x, SliceModular.forward xs (range xs wr p c (wl x) k hs hk) (fun y => wr y % P) P (wl x % P) k⟩
def reverse (xs : Array β) (wl : α → ℤ) (wr : β → ℤ) (p P c v : ℤ) (k : ℕ) (hs : PrimarySorted xs wr p) (hk : xs.size < 2 ^ k) (x : α) : PairCursor.State α xs.size := ⟨x, SliceModular.reverse xs (range xs wr p c (wl x) k hs hk) (fun y => wr y % P) ((v - wl x) % P) k⟩
theorem eligible (p c x y : ℤ) : (x + y) % p = c % p ↔ y % p = (c - x) % p := by change Int.ModEq p (x + y) c ↔ Int.ModEq p y (c - x) constructor · intro h simpa only [add_sub_cancel_left] using h.sub_right x · intro h simpa only [add_sub_cancel] using h.add_left x
theorem range_slice (xs : Array β) (wr : β → ℤ) (p c wx : ℤ) (k : ℕ) (hs : PrimarySorted xs wr p) (hk : xs.size < 2 ^ k) : SliceCursor.slice xs (range xs wr p c wx k hs hk) = xs.toList.filter (fun y => decide ((wx + wr y) % p = c % p)) := by rw [range, BinarySlice.slice_eq_filter] congr 1 funext y simp only [← eligible p c wx (wr y)]
theorem forward_perm (xs : Array β) (wl : α → ℤ) (wr : β → ℤ) (p P c : ℤ) (k : ℕ) (hs : PrimarySorted xs wr p) (ht : SecondarySorted xs wr p P) (hk : xs.size < 2 ^ k) (x : α) : (PairCursor.output xs (forward xs wl wr p P c k hs hk x)).Perm ((xs.toList.filter (fun y => decide ((wl x + wr y) % p = c % p))).map (fun y => (x, y))) := by have h := SliceModular.forward_perm xs (range xs wr p c (wl x) k hs hk) (fun y => wr y % P) P (wl x % P) k (range_length xs wr p c (wl x) k hs hk) (range_sorted xs wr p P c (wl x) k hs ht hk) rw [range_slice xs wr p c (wl x) k hs hk] at h exact h.map (fun y => (x, y))
theorem reverse_perm (xs : Array β) (wl : α → ℤ) (wr : β → ℤ) (p P c v : ℤ) (k : ℕ) (hs : PrimarySorted xs wr p) (ht : SecondarySorted xs wr p P) (hk : xs.size < 2 ^ k) (x : α) : (PairCursor.output xs (reverse xs wl wr p P c v k hs hk x)).Perm ((xs.toList.filter (fun y => decide ((wl x + wr y) % p = c % p))).map (fun y => (x, y))) := by have h := SliceModular.reverse_perm xs (range xs wr p c (wl x) k hs hk) (fun y => wr y % P) ((v - wl x) % P) k (range_length xs wr p c (wl x) k hs hk) (range_sorted xs wr p P c (wl x) k hs ht hk) rw [range_slice xs wr p c (wl x) k hs hk] at h exact h.map (fun y => (x, y))
theorem forward_sorted (xs : Array β) (wl : α → ℤ) (wr : β → ℤ) (p P c : ℤ) (k : ℕ) (hs : PrimarySorted xs wr p) (ht : SecondarySorted xs wr p P) (hk : xs.size < 2 ^ k) (hP : 0 < P) (x : α) : (PairCursor.output xs (forward xs wl wr p P c k hs hk x)).Pairwise (fun a b => (wl a.1 + wr a.2) % P ≤ (wl b.1 + wr b.2) % P) := by have h := SliceModular.forward_sorted xs (range xs wr p c (wl x) k hs hk) (fun y => wr y % P) P (wl x % P) k (range_length xs wr p c (wl x) k hs hk) (range_sorted xs wr p P c (wl x) k hs ht hk) (Int.emod_nonneg _ hP.ne') (Int.emod_lt_of_pos _ hP) (fun y _ => ⟨Int.emod_nonneg _ hP.ne', Int.emod_lt_of_pos _ hP⟩) change ((SliceCursor.output xs _).map (fun y => (x, y))).Pairwise _ rw [List.pairwise_map] simpa only [forward, Int.add_emod, Int.emod_emod] using h
theorem reverse_sorted (xs : Array β) (wl : α → ℤ) (wr : β → ℤ) (p P c v : ℤ) (k : ℕ) (hs : PrimarySorted xs wr p) (ht : SecondarySorted xs wr p P) (hk : xs.size < 2 ^ k) (hP : 0 < P) (x : α) : (PairCursor.output xs (reverse xs wl wr p P c v k hs hk x)).Pairwise (fun a b => (v - wl a.1 - wr a.2) % P ≤ (v - wl b.1 - wr b.2) % P) := by have h := SliceModular.reverse_sorted xs (range xs wr p c (wl x) k hs hk) (fun y => wr y % P) P ((v - wl x) % P) k (range_length xs wr p c (wl x) k hs hk) (range_sorted xs wr p P c (wl x) k hs ht hk) (Int.emod_nonneg _ hP.ne') (Int.emod_lt_of_pos _ hP) (fun y _ => ⟨Int.emod_nonneg _ hP.ne', Int.emod_lt_of_pos _ hP⟩) change ((SliceCursor.output xs _).map (fun y => (x, y))).Pairwise _ rw [List.pairwise_map] simpa only [reverse, Int.sub_emod, Int.emod_emod] using h
end FilteredRowend LowSpaceSubsetSum
end OAI123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187import OAI.Combinatorics.LowSpaceSubsetSum.Streams.ResidueSortimport OAI.Combinatorics.LowSpaceSubsetSum.Streams.PaddedRows
namespace OAI
/-!# The complete executable modular pair stream
Concrete lexicographic sorting, binary slice/pivot row initialization, emptyleaf padding and tournament merging are composed here. The actual merge statestores only its tree of constant-size row cursors. All Cartesian lists andmultisets in the statements are proof views.-/
namespace LowSpaceSubsetSumnamespace FilteredStream
variable {α β : Type*}
inductive Mode where | direct | complementary (target : ℤ)
def key (wl : α → ℤ) (wr : β → ℤ) (P : ℤ) : Mode → (α × β) → ℤ | .direct, z => (wl z.1 + wr z.2) % P | .complementary v, z => (v - wl z.1 - wr z.2) % P
def steps (n : ℕ) : ℕ := Nat.clog 2 n + 1
theorem steps_sufficient (n : ℕ) : n < 2 ^ steps n := by have h := Nat.le_pow_clog (by decide : 1 < 2) n have hp : 0 < 2 ^ Nat.clog 2 n := by positivity rw [steps, pow_succ] omega
theorem steps_le_index_bits (N n : ℕ) (hN : N ≤ 2 ^ n) : steps N ≤ n + 1 := by exact Nat.add_le_add_right (Nat.clog_le_of_le_pow hN) 1
def row (right : Array β) (wl : α → ℤ) (wr : β → ℤ) (p P c : ℤ) (hs : FilteredRow.PrimarySorted right wr p) (mode : Mode) (x : α) : PairCursor.State α right.size := match mode with | .direct => FilteredRow.forward right wl wr p P c (steps right.size) hs (steps_sufficient right.size) x | .complementary v => FilteredRow.reverse right wl wr p P c v (steps right.size) hs (steps_sufficient right.size) x
theorem row_sorted (right : Array β) (wl : α → ℤ) (wr : β → ℤ) (p P c : ℤ) (hs : FilteredRow.PrimarySorted right wr p) (ht : FilteredRow.SecondarySorted right wr p P) (hP : 0 < P) (mode : Mode) (x : α) : (PairCursor.output right (row right wl wr p P c hs mode x)).Pairwise (fun a b => key wl wr P mode a ≤ key wl wr P mode b) := by cases mode with | direct => exact FilteredRow.forward_sorted right wl wr p P c _ hs ht _ hP x | complementary v => exact FilteredRow.reverse_sorted right wl wr p P c v _ hs ht _ hP x
theorem row_perm (right : Array β) (wl : α → ℤ) (wr : β → ℤ) (p P c : ℤ) (hs : FilteredRow.PrimarySorted right wr p) (ht : FilteredRow.SecondarySorted right wr p P) (mode : Mode) (x : α) : (PairCursor.output right (row right wl wr p P c hs mode x)).Perm ((right.toList.filter (fun y => decide ((wl x + wr y) % p = c % p))).map (fun y => (x, y))) := by cases mode with | direct => exact FilteredRow.forward_perm right wl wr p P c _ hs ht _ x | complementary v => exact FilteredRow.reverse_perm right wl wr p P c v _ hs ht _ x
abbrev Cursor (right : Array β) := Option (PairCursor.State α right.size)
def read (right : Array β) : Cursor (α := α) right → Option ((α × β) × Cursor (α := α) right) := PaddedRows.next (PairCursor.next right)
def view (right : Array β) : Cursor (α := α) right → List (α × β) := PaddedRows.view (PairCursor.output right)
theorem reader (right : Array β) : RowMerge.IsReader (read (α := α) right) (view right) := PaddedRows.reader _ _ (PairCursor.reader right)
def rowArray (left : Array α) (right : Array β) (wl : α → ℤ) (wr : β → ℤ) (p P c : ℤ) (hs : FilteredRow.PrimarySorted right wr p) (mode : Mode) : Array (PairCursor.State α right.size) := left.map (row right wl wr p P c hs mode)
theorem array_sorted (left : Array α) (right : Array β) (wl : α → ℤ) (wr : β → ℤ) (p P c : ℤ) (hs : FilteredRow.PrimarySorted right wr p) (ht : FilteredRow.SecondarySorted right wr p P) (hP : 0 < P) (mode : Mode) (d : ℕ) (path : RowMerge.Path d) : (view right (PaddedRows.rows (rowArray left right wl wr p P c hs mode) d path)).Pairwise (fun a b => key wl wr P mode a ≤ key wl wr P mode b) := by apply PaddedRows.rows_sorted intro s hmem simp only [rowArray, Array.toList_map, List.mem_map] at hmem obtain ⟨x, _, rfl⟩ := hmem exact row_sorted right wl wr p P c hs ht hP mode x
def start (left : Array α) (right : Array β) (wl : α → ℤ) (wr : β → ℤ) (p P c : ℤ) (hs : FilteredRow.PrimarySorted right wr p) (ht : FilteredRow.SecondarySorted right wr p P) (hP : 0 < P) (mode : Mode) : MergedReader.State (key wl wr P mode) (view right) (Nat.clog 2 left.size) := MergedReader.start (key wl wr P mode) (read right) (view right) (reader right) (PaddedRows.rows (rowArray left right wl wr p P c hs mode) _) (array_sorted left right wl wr p P c hs ht hP mode _)
theorem output_bag (left : Array α) (right : Array β) (wl : α → ℤ) (wr : β → ℤ) (p P c : ℤ) (hs : FilteredRow.PrimarySorted right wr p) (ht : FilteredRow.SecondarySorted right wr p P) (hP : 0 < P) (mode : Mode) : (MergedReader.output (key wl wr P mode) (read right) (view right) (start left right wl wr p P c hs ht hP mode) : Multiset (α × β)) = ∑ i : Fin left.size, ((right.toList.filter (fun y => decide ((wl left[i.val] + wr y) % p = c % p))).map (fun y => (left[i.val], y)) : Multiset (α × β)) := by rw [start, MergedReader.start_output_bag] have hd : (rowArray left right wl wr p P c hs mode).size ≤ 2 ^ Nat.clog 2 left.size := by simpa only [rowArray, Array.size_map] using Nat.le_pow_clog (by decide : 1 < 2) left.size change (∑ path : RowMerge.Path (Nat.clog 2 left.size), (PaddedRows.view (PairCursor.output right) (PaddedRows.rows (rowArray left right wl wr p P c hs mode) _ path) : Multiset (α × β))) = _ rw [PaddedRows.row_bag _ _ hd] have hsize : (rowArray left right wl wr p P c hs mode).size = left.size := by simp only [rowArray, Array.size_map] apply Fintype.sum_equiv (finCongr hsize) intro i have hin : i.val < left.size := by rw [← hsize]; exact i.isLt simp only [rowArray, Array.getElem_map] exact Quot.sound (row_perm right wl wr p P c hs ht mode left[i.val])
def sortedStart (left : Array α) (right : Array β) (wl : α → ℤ) (wr : β → ℤ) (p P c : ℤ) (hP : 0 < P) (mode : Mode) : MergedReader.State (key wl wr P mode) (view (ResidueSort.sort right wr p P)) (Nat.clog 2 left.size) := start left (ResidueSort.sort right wr p P) wl wr p P c (ResidueSort.primary right wr p P) (ResidueSort.secondary right wr p P) hP mode
theorem sorted_output_bag (left : Array α) (right : Array β) (wl : α → ℤ) (wr : β → ℤ) (p P c : ℤ) (hP : 0 < P) (mode : Mode) : (MergedReader.output (key wl wr P mode) (read (ResidueSort.sort right wr p P)) (view (ResidueSort.sort right wr p P)) (sortedStart left right wl wr p P c hP mode) : Multiset (α × β)) = ∑ i : Fin left.size, ((right.toList.filter (fun y => decide ((wl left[i.val] + wr y) % p = c % p))).map (fun y => (left[i.val], y)) : Multiset (α × β)) := by rw [sortedStart, output_bag] apply Finset.sum_congr rfl intro i _ exact Quot.sound (((ResidueSort.permutation right wr p P).filter (fun y => decide ((wl left[i.val] + wr y) % p = c % p))).map (fun y => (left[i.val], y)))
theorem sorted_output_sorted (left : Array α) (right : Array β) (wl : α → ℤ) (wr : β → ℤ) (p P c : ℤ) (hP : 0 < P) (mode : Mode) : (MergedReader.output (key wl wr P mode) (read (ResidueSort.sort right wr p P)) (view (ResidueSort.sort right wr p P)) (sortedStart left right wl wr p P c hP mode)).Pairwise (fun a b => key wl wr P mode a ≤ key wl wr P mode b) := MergedReader.output_sorted _ _ _ (reader _) _
theorem state_nodes (left : Array α) (right : Array β) (wl : α → ℤ) (wr : β → ℤ) (p P c : ℤ) (hP : 0 < P) (mode : Mode) : Tournament.nodes (sortedStart left right wl wr p P c hP mode).tree + 1 ≤ 4 * (left.size + 1) := Tournament.padded_nodes_le left.size _
theorem sorted_output_mem (left : Array α) (right : Array β) (wl : α → ℤ) (wr : β → ℤ) (p P c : ℤ) (hP : 0 < P) (mode : Mode) (z : α × β) : z ∈ MergedReader.output (key wl wr P mode) (read (ResidueSort.sort right wr p P)) (view (ResidueSort.sort right wr p P)) (sortedStart left right wl wr p P c hP mode) ↔ z.1 ∈ left.toList ∧ z.2 ∈ right.toList ∧ (wl z.1 + wr z.2) % p = c % p := by change z ∈ (MergedReader.output (key wl wr P mode) (read (ResidueSort.sort right wr p P)) (view (ResidueSort.sort right wr p P)) (sortedStart left right wl wr p P c hP mode) : Multiset (α × β)) ↔ _ rw [sorted_output_bag] simp only [Multiset.mem_sum, Finset.mem_univ, true_and, Multiset.mem_coe, List.mem_map, List.mem_filter, decide_eq_true_eq] constructor · rintro ⟨i, y, ⟨hy, hmod⟩, heq⟩ have hz₁ : left[i.val] = z.1 := congrArg Prod.fst heq have hz₂ : y = z.2 := congrArg Prod.snd heq subst y refine ⟨?_, hy, ?_⟩ · rw [← hz₁] exact List.mem_iff_getElem.mpr ⟨i.val, by simp, by simp⟩ · simpa only [hz₁] using hmod · rintro ⟨hx, hy, hmod⟩ obtain ⟨i, hi, hix⟩ := List.mem_iff_getElem.mp hx have hin : i < left.size := by simpa only [Array.length_toList] using hi rw [Array.getElem_toList] at hix refine ⟨⟨i, hin⟩, z.2, ⟨hy, ?_⟩, ?_⟩ · simpa only [hix] using hmod · exact Prod.ext hix rfl
end FilteredStreamend LowSpaceSubsetSum
end OAI123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219import OAI.Combinatorics.LowSpaceSubsetSum.Streams.BufferReplay
namespace OAI
/-!# Reporting one item's matches against a buffered tie group
The immutable prefix buffer is reused. A generator suffix is restored onlywhen the group was longer than the buffer. The callback may stop in eitherpart; its work and stream queries are bounded on every outcome.-/
namespace LowSpaceSubsetSumnamespace JoinOne
universe u v w
variable {α : Type u} {σ : Type v} {τ : Type w}
def run (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ) (report : α → τ → τ × Bool) (buffer : Array α) (saved : σ) (long : Bool) (fuel : ℕ) (a : τ) : TieReplay.Result σ τ := let first := BufferReplay.run key K report buffer a if first.halted then ⟨saved, first.state, first.queries, first.reports, false, true⟩ else if long then let rest := TieReplay.run read key K report fuel saved first.state ⟨rest.cursor, rest.state, first.queries + rest.queries, first.reports + rest.reports, rest.complete, rest.halted⟩ else ⟨saved, first.state, first.queries, first.reports, true, false⟩
theorem reports_le (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ) (report : α → τ → τ × Bool) (view : σ → List α) (hread : RowMerge.IsReader read view) (buffer : Array α) (saved : σ) (long : Bool) (fuel : ℕ) (a : τ) : (run read key K report buffer saved long fuel a).reports ≤ buffer.size + (TieBuffer.groupView key K view saved).length := by have hb := BufferReplay.reports_le key K report buffer a dsimp only [run] split · exact hb.trans (Nat.le_add_right _ _) · split · have hr := TieReplay.run_reports_le_potential read key K report view hread fuel saved (BufferReplay.run key K report buffer a).state exact Nat.add_le_add hb hr · exact hb.trans (Nat.le_add_right _ _)
theorem queries_le (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ) (report : α → τ → τ × Bool) (view : σ → List α) (hread : RowMerge.IsReader read view) (buffer : Array α) (saved : σ) (long : Bool) (fuel : ℕ) (a : τ) : (run read key K report buffer saved long fuel a).queries ≤ buffer.size + (TieBuffer.groupView key K view saved).length + 1 := by have hb := BufferReplay.queries_le key K report buffer a dsimp only [run] split · dsimp only omega · split · have hr := TieReplay.run_queries_le_potential read key K report view hread fuel saved (BufferReplay.run key K report buffer a).state dsimp only omega · dsimp only omega
theorem halted_false (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ) (report : α → τ → τ × Bool) (hreport : ∀ x a, (report x a).2 = false) (buffer : Array α) (saved : σ) (long : Bool) (fuel : ℕ) (a : τ) : (run read key K report buffer saved long fuel a).halted = false := by have hb : (BufferReplay.run key K report buffer a).halted = false := TieReplay.run_halted_false _ _ _ _ hreport _ _ _ simp only [run, hb, Bool.false_eq_true, ite_false] split · exact TieReplay.run_halted_false _ _ _ _ hreport _ _ _ · rfl
/-- Completed reporting is precisely prefix reporting followed by suffixreporting; a short group has no suffix to restore. -/theorem state_complete (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ) (report : α → τ → τ × Bool) (hreport : ∀ x a, (report x a).2 = false) (view : σ → List α) (hread : RowMerge.IsReader read view) (buffer : Array α) (hkeys : ∀ x ∈ buffer.toList, key x = K) (saved : σ) (fuel : ℕ) (a : τ) (hfuel : (TieBuffer.groupView key K view saved).length ≤ fuel) : (run read key K report buffer saved (TieBuffer.hasKey read key K saved) fuel a).state = (buffer.toList ++ TieBuffer.groupView key K view saved).foldl (fun a x => (report x a).1) a := by have hb : (BufferReplay.run key K report buffer a).halted = false := TieReplay.run_halted_false _ _ _ _ hreport _ _ _ have hs := BufferReplay.state_complete key K report hreport buffer a hkeys simp only [run, hb, Bool.false_eq_true, ite_false] by_cases hl : TieBuffer.hasKey read key K saved = true · simp only [hl, ite_true] rw [TieReplay.run_state_complete read key K report hreport view hread fuel saved _ hfuel, hs, List.foldl_append] · have he : TieBuffer.groupView key K view saved = [] := by by_contra he exact hl ((TieBuffer.hasKey_iff read key K view hread saved).mpr he) have hfalse : TieBuffer.hasKey read key K saved = false := Bool.eq_false_iff.mpr hl simp only [hfalse, Bool.false_eq_true, ite_false, he, List.append_nil] exact hs
theorem suffix_empty (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ) (report : α → τ → τ × Bool) (hreport : ∀ x a, (report x a).2 = false) (view : σ → List α) (hread : RowMerge.IsReader read view) (buffer : Array α) (saved : σ) (fuel : ℕ) (a : τ) (hfuel : (TieBuffer.groupView key K view saved).length ≤ fuel) : TieBuffer.groupView key K view (run read key K report buffer saved (TieBuffer.hasKey read key K saved) fuel a).cursor = [] := by have hb : (BufferReplay.run key K report buffer a).halted = false := TieReplay.run_halted_false _ _ _ _ hreport _ _ _ simp only [run, hb, Bool.false_eq_true, ite_false] by_cases hl : TieBuffer.hasKey read key K saved = true · simp only [hl, ite_true] have h := (TieReplay.runAcc_nonhalting_spec read key K report hreport view hread fuel saved (BufferReplay.run key K report buffer a).state 0 0).2.2.1 exact h.trans (List.drop_eq_nil_of_le hfuel) · simp only [Bool.eq_false_iff.mpr hl, Bool.false_eq_true, ite_false] by_contra he exact hl ((TieBuffer.hasKey_iff read key K view hread saved).mpr he)
theorem view_complete (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ) (report : α → τ → τ × Bool) (hreport : ∀ x a, (report x a).2 = false) (view : σ → List α) (hread : RowMerge.IsReader read view) (buffer : Array α) (saved : σ) (fuel : ℕ) (a : τ) (hfuel : (TieBuffer.groupView key K view saved).length ≤ fuel) : view saved = TieBuffer.groupView key K view saved ++ view (run read key K report buffer saved (TieBuffer.hasKey read key K saved) fuel a).cursor := by have hb : (BufferReplay.run key K report buffer a).halted = false := TieReplay.run_halted_false _ _ _ _ hreport _ _ _ simp only [run, hb, Bool.false_eq_true, ite_false] by_cases hl : TieBuffer.hasKey read key K saved = true · simp only [hl, ite_true] have h := (TieReplay.runAcc_nonhalting_spec read key K report hreport view hread fuel saved (BufferReplay.run key K report buffer a).state 0 0).2.2.2 simpa only [TieReplay.run, List.take_of_length_le hfuel] using h · have he : TieBuffer.groupView key K view saved = [] := by by_contra he exact hl ((TieBuffer.hasKey_iff read key K view hread saved).mpr he) simp only [Bool.eq_false_iff.mpr hl, Bool.false_eq_true, ite_false, he, List.nil_append]
def runFilled (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ) (report : α → τ → τ × Bool) (B fuel : ℕ) (s : σ) (a : τ) : TieReplay.Result σ τ := let filled := TieBuffer.fill read key K B s run read key K report filled.buffer filled.cursor (TieBuffer.hasKey read key K filled.cursor) fuel a
theorem filled_reports_le (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ) (report : α → τ → τ × Bool) (view : σ → List α) (hread : RowMerge.IsReader read view) (B fuel : ℕ) (s : σ) (a : τ) : (runFilled read key K report B fuel s a).reports ≤ (TieBuffer.groupView key K view s).length := by have h := reports_le read key K report view hread (TieBuffer.fill read key K B s).buffer (TieBuffer.fill read key K B s).cursor (TieBuffer.hasKey read key K (TieBuffer.fill read key K B s).cursor) fuel a have hb := congrArg List.length (TieBuffer.fill_buffer read key K view hread B s) rw [TieBuffer.fill_suffix read key K view hread B s] at h simp only [Array.length_toList, List.length_take] at hb simp only [List.length_drop] at h dsimp only [runFilled] omega
theorem filled_queries_le (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ) (report : α → τ → τ × Bool) (view : σ → List α) (hread : RowMerge.IsReader read view) (B fuel : ℕ) (s : σ) (a : τ) : (runFilled read key K report B fuel s a).queries ≤ (TieBuffer.groupView key K view s).length + 1 := by have h := queries_le read key K report view hread (TieBuffer.fill read key K B s).buffer (TieBuffer.fill read key K B s).cursor (TieBuffer.hasKey read key K (TieBuffer.fill read key K B s).cursor) fuel a have hb := congrArg List.length (TieBuffer.fill_buffer read key K view hread B s) rw [TieBuffer.fill_suffix read key K view hread B s] at h simp only [Array.length_toList, List.length_take] at hb simp only [List.length_drop] at h dsimp only [runFilled] omega
theorem filled_state_complete (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ) (report : α → τ → τ × Bool) (hreport : ∀ x a, (report x a).2 = false) (view : σ → List α) (hread : RowMerge.IsReader read view) (B fuel : ℕ) (s : σ) (a : τ) (hfuel : (TieBuffer.groupView key K view s).length ≤ fuel) : (runFilled read key K report B fuel s a).state = (TieBuffer.groupView key K view s).foldl (fun a x => (report x a).1) a := by have hf : (TieBuffer.groupView key K view (TieBuffer.fill read key K B s).cursor).length ≤ fuel := by rw [TieBuffer.fill_suffix read key K view hread B s, List.length_drop] omega have h := state_complete read key K report hreport view hread (TieBuffer.fill read key K B s).buffer (BufferReplay.filled_buffer_keys read key K view hread B s) (TieBuffer.fill read key K B s).cursor fuel a hf rw [TieBuffer.fill_buffer read key K view hread B s, TieBuffer.fill_suffix read key K view hread B s, List.take_append_drop] at h exact h
theorem filled_view_complete (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ) (report : α → τ → τ × Bool) (hreport : ∀ x a, (report x a).2 = false) (view : σ → List α) (hread : RowMerge.IsReader read view) (B fuel : ℕ) (s : σ) (a : τ) (hfuel : (TieBuffer.groupView key K view s).length ≤ fuel) : view s = TieBuffer.groupView key K view s ++ view (runFilled read key K report B fuel s a).cursor := by have hf : (TieBuffer.groupView key K view (TieBuffer.fill read key K B s).cursor).length ≤ fuel := by rw [TieBuffer.fill_suffix read key K view hread B s, List.length_drop] omega have hs := view_complete read key K report hreport view hread (TieBuffer.fill read key K B s).buffer (TieBuffer.fill read key K B s).cursor fuel a hf have h := (TieBuffer.fillAcc_spec read key K view hread B s #[] 0).2.1 change view s = (TieBuffer.groupView key K view s).take B ++ view (TieBuffer.fill read key K B s).cursor at h rw [hs, TieBuffer.fill_suffix read key K view hread B s, ← List.append_assoc, List.take_append_drop] at h exact h
end JoinOneend LowSpaceSubsetSum
end OAI123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269import OAI.Combinatorics.LowSpaceSubsetSum.Streams.JoinUserMap
namespace OAI
/-! # Stored-record erasure through buffered joins
The erasure maps both emitted records and reader cursors. Counters and stopflags are preserved, so the work ledger can be transferred to the sourceparent task without changing the order of equal-weight occurrences.-/
namespace LowSpaceSubsetSum
universe u v s t w zvariable {α : Type u} {β : Type v} {σ : Type s} {σ' : Type t} {τ : Type w} {τ' : Type z}
namespace TieBuffer
def mapAll (f : α → β) (g : σ → σ') (r : Result α σ) : Result β σ' := ⟨r.buffer.map f, g r.cursor, r.queries⟩
theorem fillAcc_map (f : α → β) (g : σ → σ') (read : σ → Option (α × σ)) (read' : σ' → Option (β × σ')) (hr : ∀ s, read' (g s) = (read s).map (Prod.map f g)) (key : β → ℤ) (K : ℤ) (fuel : ℕ) (s : σ) (buf : Array α) (q : ℕ) : mapAll f g (fillAcc read (fun x => key (f x)) K fuel s buf q) = fillAcc read' key K fuel (g s) (buf.map f) q := by induction fuel generalizing s buf q with | zero => rfl | succ fuel ih => cases h : read s with | none => simp only [fillAcc, hr, h, Option.map_none, mapAll] | some p => rcases p with ⟨x, s'⟩ simp only [fillAcc, hr, h, Option.map_some, Prod.map] split · simpa only [Array.map_push] using ih s' (buf.push x) (q + 1) · rfl
theorem fill_map (f : α → β) (g : σ → σ') (read : σ → Option (α × σ)) (read' : σ' → Option (β × σ')) (hr : ∀ s, read' (g s) = (read s).map (Prod.map f g)) (key : β → ℤ) (K : ℤ) (B : ℕ) (s : σ) : mapAll f g (fill read (fun x => key (f x)) K B s) = fill read' key K B (g s) := by simpa only [fill, Array.map_empty] using fillAcc_map f g read read' hr key K B s #[] 0
theorem hasKey_map (f : α → β) (g : σ → σ') (read : σ → Option (α × σ)) (read' : σ' → Option (β × σ')) (hr : ∀ s, read' (g s) = (read s).map (Prod.map f g)) (key : β → ℤ) (K : ℤ) (s : σ) : hasKey read' key K (g s) = hasKey read (fun x => key (f x)) K s := by cases h : read s <;> simp only [hasKey, hr, h, Option.map_none, Option.map_some, Prod.map]
end TieBuffer
namespace TieReplay
def mapAll (g : σ → σ') (h : τ → τ') (r : Result σ τ) : Result σ' τ' := ⟨g r.cursor, h r.state, r.queries, r.reports, r.complete, r.halted⟩
theorem runAcc_map (f : α → β) (g : σ → σ') (h : τ → τ') (read : σ → Option (α × σ)) (read' : σ' → Option (β × σ')) (hr : ∀ s, read' (g s) = (read s).map (Prod.map f g)) (key : β → ℤ) (K : ℤ) (report : α → τ → τ × Bool) (report' : β → τ' → τ' × Bool) (hp : ∀ x a, report' (f x) (h a) = (h (report x a).1, (report x a).2)) (fuel : ℕ) (s : σ) (a : τ) (q r : ℕ) : mapAll g h (runAcc read (fun x => key (f x)) K report fuel s a q r) = runAcc read' key K report' fuel (g s) (h a) q r := by induction fuel generalizing s a q r with | zero => rfl | succ fuel ih => cases hs : read s with | none => simp only [runAcc, hr, hs, Option.map_none, mapAll] | some p => rcases p with ⟨x, s'⟩ simp only [runAcc, hr, hs, Option.map_some, Prod.map] split · rw [hp] split · rfl · exact ih _ _ _ _ · rfl
theorem run_map (f : α → β) (g : σ → σ') (h : τ → τ') (read : σ → Option (α × σ)) (read' : σ' → Option (β × σ')) (hr : ∀ s, read' (g s) = (read s).map (Prod.map f g)) (key : β → ℤ) (K : ℤ) (report : α → τ → τ × Bool) (report' : β → τ' → τ' × Bool) (hp : ∀ x a, report' (f x) (h a) = (h (report x a).1, (report x a).2)) (fuel : ℕ) (s : σ) (a : τ) : mapAll g h (run read (fun x => key (f x)) K report fuel s a) = run read' key K report' fuel (g s) (h a) := runAcc_map f g h read read' hr key K report report' hp fuel s a 0 0
end TieReplay
namespace BufferReplay
theorem read_map (f : α → β) (xs : Array α) (i : ℕ) : read (xs.map f) i = (read xs i).map (Prod.map f id) := by simp only [read, Array.size_map] split <;> simp only [Option.map_some, Option.map_none, Array.getElem_map, Prod.map, id_eq]
theorem run_map (f : α → β) (key : β → ℤ) (K : ℤ) (report : β → τ → τ × Bool) (xs : Array α) (a : τ) : run (fun x => key (f x)) K (fun x => report (f x)) xs a = run key K report (xs.map f) a := by have h := TieReplay.run_map f id id (read xs) (read (xs.map f)) (read_map f xs) key K (fun x => report (f x)) report (fun _ _ => rfl) xs.size 0 a cases he : TieReplay.run (read xs) (fun x => key (f x)) K (fun x => report (f x)) xs.size 0 a simpa only [run, he, TieReplay.mapAll, id_eq, Array.size_map] using h
end BufferReplay
namespace JoinOne
theorem run_map (f : α → β) (g : σ → σ') (read : σ → Option (α × σ)) (read' : σ' ��� Option (β × σ')) (hr : ∀ s, read' (g s) = (read s).map (Prod.map f g)) (key : β → ℤ) (K : ℤ) (report : β → τ → τ × Bool) (buffer : Array α) (saved : σ) (long : Bool) (fuel : ℕ) (a : τ) : TieReplay.mapAll g id (run read (fun x => key (f x)) K (fun x => report (f x)) buffer saved long fuel a) = run read' key K report (buffer.map f) (g saved) long fuel a := by simp only [run, BufferReplay.run_map f key K report] split · rfl · split · have h := TieReplay.run_map f g id read read' hr key K (fun x => report (f x)) report (fun _ _ => rfl) fuel saved (BufferReplay.run key K report (buffer.map f) a).state cases he : TieReplay.run read (fun x => key (f x)) K (fun x => report (f x)) fuel saved (BufferReplay.run key K report (buffer.map f) a).state simp only [he, TieReplay.mapAll, id_eq] at h rw [← h] rfl · rfl
end JoinOne
namespace TieGroup
variable {α' β' σ₁' σ₂' : Type*}
def mapReaders (g : σ → σ') (a : State σ τ) : State σ' τ := ⟨g a.last, a.user, a.queries, a.reports, a.restores⟩
def mapReadersResult (g₁ : σ → σ₁') (g₂ : σ' → σ₂') (r : Result σ σ' τ) : Result σ₁' σ₂' τ := ⟨TieReplay.mapAll g₁ (mapReaders g₂) r.outer, r.fillQueries, r.bufferSize, r.snapshot⟩
theorem step_mapReaders (f₁ : α → α') (f₂ : β → β') (g : σ → σ') (read : σ → Option (β × σ)) (read' : σ' → Option (β' × σ')) (hr : ∀ s, read' (g s) = (read s).map (Prod.map f₂ g)) (key : β' → ℤ) (K : ℤ) (report : α' → β' → τ → τ × Bool) (buffer : Array β) (saved : σ) (long : Bool) (fuel : ℕ) (x : α) (a : State σ τ) : (mapReaders g (step read (fun y => key (f₂ y)) K (fun x y => report (f₁ x) (f₂ y)) buffer saved long fuel x a).1, (step read (fun y => key (f₂ y)) K (fun x y => report (f₁ x) (f₂ y)) buffer saved long fuel x a).2) = step read' key K report (buffer.map f₂) (g saved) long fuel (f₁ x) (mapReaders g a) := by simp only [step, ← JoinOne.run_map f₂ g read read' hr key K (report (f₁ x))] rfl
theorem run_mapReaders (f₁ : α → α') (f₂ : β → β') (g₁ : σ → σ₁') (g₂ : σ' → σ₂') (read₁ : σ → Option (α × σ)) (read₁' : σ₁' → Option (α' × σ₁')) (read₂ : σ' → Option (β × σ')) (read₂' : σ₂' → Option (β' × σ₂')) (hr₁ : ∀ s, read₁' (g₁ s) = (read₁ s).map (Prod.map f₁ g₁)) (hr₂ : ∀ s, read₂' (g₂ s) = (read₂ s).map (Prod.map f₂ g₂)) (key₁ : α' → ℤ) (key₂ : β' → ℤ) (K : ℤ) (report : α' → β' → τ → τ × Bool) (B fuel₁ fuel₂ : ℕ) (s₁ : σ) (s₂ : σ') (a : τ) : mapReadersResult g₁ g₂ (run read₁ (fun x => key₁ (f₁ x)) read₂ (fun y => key₂ (f₂ y)) K (fun x y => report (f₁ x) (f₂ y)) B fuel₁ fuel₂ s₁ s₂ a) = run read₁' key₁ read₂' key₂ K report B fuel₁ fuel₂ (g₁ s₁) (g₂ s₂) a := by let filled := TieBuffer.fill read₂ (fun y => key₂ (f₂ y)) K B s₂ let long := TieBuffer.hasKey read₂ (fun y => key₂ (f₂ y)) K filled.cursor have hp := fun x st => (step_mapReaders f₁ f₂ g₂ read₂ read₂' hr₂ key₂ K report filled.buffer filled.cursor long fuel₂ x st).symm have hm := TieReplay.run_map f₁ g₁ (mapReaders g₂) read₁ read₁' hr₁ key₁ K (step read₂ (fun y => key₂ (f₂ y)) K (fun x y => report (f₁ x) (f₂ y)) filled.buffer filled.cursor long fuel₂) (step read₂' key₂ K report (filled.buffer.map f₂) (g₂ filled.cursor) long fuel₂) hp fuel₁ s₁ ⟨filled.cursor, a, 0, 0, 0⟩ simp only [run, mapReadersResult, ← TieBuffer.fill_map f₂ g₂ read₂ read₂' hr₂ key₂ K B s₂, TieBuffer.mapAll, Array.size_map, TieBuffer.hasKey_map f₂ g₂ read₂ read₂' hr₂ key₂ K, TieBuffer.hasKey_map f₁ g₁ read₁ read₁' hr₁ key₁ K] rw [hm] rfl
end TieGroup
namespace StreamJoin
variable {α' β' σ₁' σ₂' : Type*}
def mapReaders (g₁ : σ → σ₁') (g₂ : σ' → σ₂') (a : State σ σ' τ) : State σ₁' σ₂' τ := ⟨g₁ a.left, g₂ a.right, a.user, a.queries, a.reports, a.copies, a.done⟩
def mapReadersStopped (g₁ : σ → σ₁') (g₂ : σ' → σ₂') (a : StoppedResult σ σ' τ) : StoppedResult σ₁' σ₂' τ := ⟨mapReaders g₁ g₂ a.state, a.steps⟩
theorem step_mapReaders (f₁ : α → α') (f₂ : β → β') (g₁ : σ → σ₁') (g₂ : σ' → σ₂') (read₁ : σ → Option (α × σ)) (read₁' : σ₁' → Option (α' × σ₁')) (read₂ : σ' → Option (β × σ')) (read₂' : σ₂' → Option (β' × σ₂')) (hr₁ : ∀ s, read₁' (g₁ s) = (read₁ s).map (Prod.map f₁ g₁)) (hr₂ : ∀ s, read₂' (g₂ s) = (read₂ s).map (Prod.map f₂ g₂)) (key₁ : α' → ℤ) (key₂ : β' → ℤ) (report : α' → β' → τ → τ × Bool) (B fuel₁ fuel₂ : ℕ) (a : State σ σ' τ) : mapReaders g₁ g₂ (step read₁ (fun x => key₁ (f₁ x)) read₂ (fun y => key₂ (f₂ y)) (fun x y => report (f₁ x) (f₂ y)) B fuel₁ fuel₂ a) = step read₁' key₁ read₂' key₂ report B fuel₁ fuel₂ (mapReaders g₁ g₂ a) := by by_cases hd : a.done = true · simp only [step, mapReaders, hd, ↓reduceIte] · cases h₁ : read₁ a.left with | none => simp only [step, mapReaders, hd, Bool.false_eq_true, ↓reduceIte, hr₁, h₁, Option.map_none] | some p₁ => rcases p₁ with ⟨x, l⟩ cases h₂ : read₂ a.right with | none => simp only [step, mapReaders, hd, Bool.false_eq_true, ↓reduceIte, hr₁, hr₂, h₁, h₂, Option.map_none, Option.map_some, Prod.map] | some p₂ => rcases p₂ with ⟨y, r⟩ simp only [step, mapReaders, hd, Bool.false_eq_true, ↓reduceIte, hr₁, hr₂, h₁, h₂, Option.map_some, Prod.map, ← TieGroup.run_mapReaders f₁ f₂ g₁ g₂ read₁ read₁' read₂ read₂' hr₁ hr₂ key₁ key₂ (key₁ (f₁ x)) report B fuel₁ fuel₂, TieGroup.mapReadersResult, TieReplay.mapAll, TieGroup.mapReaders] split · rfl · split <;> rfl
theorem stoppedAcc_mapReaders (f₁ : α → α') (f₂ : β → β') (g₁ : σ → σ₁') (g₂ : σ' → σ₂') (read₁ : σ → Option (α × σ)) (read₁' : σ₁' → Option (α' × σ₁')) (read₂ : σ' → Option (β × σ')) (read₂' : σ₂' → Option (β' × σ₂')) (hr₁ : ∀ s, read₁' (g₁ s) = (read₁ s).map (Prod.map f₁ g₁)) (hr₂ : ∀ s, read₂' (g₂ s) = (read₂ s).map (Prod.map f₂ g₂)) (key₁ : α' → ℤ) (key₂ : β' → ℤ) (report : α' → β' → τ → τ × Bool) (B fuel₁ fuel₂ fuel : ℕ) (a : State σ σ' τ) : mapReadersStopped g₁ g₂ (stoppedAcc read₁ (fun x => key₁ (f₁ x)) read₂ (fun y => key₂ (f₂ y)) (fun x y => report (f₁ x) (f₂ y)) B fuel₁ fuel₂ fuel a) = stoppedAcc read₁' key₁ read₂' key₂ report B fuel₁ fuel₂ fuel (mapReaders g₁ g₂ a) := by induction fuel generalizing a with | zero => rfl | succ fuel ih => by_cases hd : a.done = true · simp only [stoppedAcc, mapReadersStopped, mapReaders, hd, ↓reduceIte] · have hdone : (mapReaders g₁ g₂ a).done = a.done := rfl have hm := ih (step read₁ (fun x => key₁ (f₁ x)) read₂ (fun y => key₂ (f₂ y)) (fun x y => report (f₁ x) (f₂ y)) B fuel₁ fuel₂ a) simp only [stoppedAcc, hdone, hd, Bool.false_eq_true, ↓reduceIte] rw [← step_mapReaders f₁ f₂ g₁ g₂ read₁ read₁' read₂ read₂' hr₁ hr₂ key₁ key₂ report B fuel₁ fuel₂, ← hm] rfl
end StreamJoin
end LowSpaceSubsetSum
end OAI123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187import OAI.Combinatorics.LowSpaceSubsetSum.Search.StoppedStreamJoin
namespace OAI
/-! # Erasing proof-carrying callback states through the actual join
This refinement lets a counted dictionary carry its invariant intrinsically,while retaining exactly the original join's cursors, counters and halt behavior.-/
namespace LowSpaceSubsetSum
universe u v s t w zvariable {α : Type u} {β : Type v} {σ : Type s} {τ : Type w} {τ' : Type z}
namespace TieReplay
def mapUser (f : τ → τ') (r : Result σ τ) : Result σ τ' := ⟨r.cursor, f r.state, r.queries, r.reports, r.complete, r.halted⟩
theorem runAcc_mapUser (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ) (report : α → τ → τ × Bool) (report' : α → τ' → τ' × Bool) (f : τ → τ') (hf : ∀ x a, report' x (f a) = (f (report x a).1, (report x a).2)) (fuel : ℕ) (s : σ) (a : τ) (q r : ℕ) : mapUser f (runAcc read key K report fuel s a q r) = runAcc read key K report' fuel s (f a) q r := by induction fuel generalizing s a q r with | zero => rfl | succ fuel ih => cases hr : read s with | none => simp only [runAcc, hr, mapUser] | some p => rcases p with ⟨x, s'⟩ simp only [runAcc, hr] split · rw [hf] split · rfl · exact ih _ _ _ _ · rfl
theorem run_mapUser (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ) (report : α → τ → τ × Bool) (report' : α → τ' → τ' × Bool) (f : τ → τ') (hf : ∀ x a, report' x (f a) = (f (report x a).1, (report x a).2)) (fuel : ℕ) (s : σ) (a : τ) : mapUser f (run read key K report fuel s a) = run read key K report' fuel s (f a) := runAcc_mapUser read key K report report' f hf fuel s a 0 0
end TieReplay
namespace JoinOne
theorem run_mapUser (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ) (report : α → τ → τ × Bool) (report' : α → τ' → τ' × Bool) (f : τ → τ') (hf : ∀ x a, report' x (f a) = (f (report x a).1, (report x a).2)) (buffer : Array α) (saved : σ) (long : Bool) (fuel : ℕ) (a : τ) : TieReplay.mapUser f (run read key K report buffer saved long fuel a) = run read key K report' buffer saved long fuel (f a) := by simp only [run, BufferReplay.run, ← TieReplay.run_mapUser (BufferReplay.read buffer) key K report report' f hf, TieReplay.mapUser] split · simp_all only [↓reduceIte] · simp_all only [Bool.false_eq_true, ↓reduceIte] split · simp_all only have h := TieReplay.run_mapUser read key K report report' f hf fuel saved (TieReplay.run (BufferReplay.read buffer) key K report buffer.size 0 a).state cases h₁ : TieReplay.run read key K report fuel saved (TieReplay.run (BufferReplay.read buffer) key K report buffer.size 0 a).state simp only [h₁, TieReplay.mapUser] at h rw [← h] · simp_all only
end JoinOne
namespace TieGroup
variable {σ₂ : Type t}
def mapUser (f : τ → τ') (a : State σ₂ τ) : State σ₂ τ' := ⟨a.last, f a.user, a.queries, a.reports, a.restores⟩
def mapResult (f : τ → τ') (r : Result σ σ₂ τ) : Result σ σ₂ τ' := ⟨TieReplay.mapUser (mapUser f) r.outer, r.fillQueries, r.bufferSize, r.snapshot⟩
theorem step_mapUser (read : σ₂ → Option (β × σ₂)) (key : β → ℤ) (K : ℤ) (report : α → β → τ → τ × Bool) (report' : α → β → τ' → τ' × Bool) (f : τ → τ') (hf : ∀ x y a, report' x y (f a) = (f (report x y a).1, (report x y a).2)) (buffer : Array β) (saved : σ₂) (long : Bool) (fuel : ℕ) (x : α) (a : State σ₂ τ) : (mapUser f (step read key K report buffer saved long fuel x a).1, (step read key K report buffer saved long fuel x a).2) = step read key K report' buffer saved long fuel x (mapUser f a) := by simp only [step, mapUser, ← JoinOne.run_mapUser read key K (report x) (report' x) f (hf x), TieReplay.mapUser]
theorem run_mapUser (read₁ : σ → Option (α × σ)) (key₁ : α → ℤ) (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ) (K : ℤ) (report : α → β → τ → τ × Bool) (report' : α → β → τ' → τ' × Bool) (f : τ → τ') (hf : ∀ x y a, report' x y (f a) = (f (report x y a).1, (report x y a).2)) (B fuel₁ fuel₂ : ℕ) (s₁ : σ) (s₂ : σ₂) (a : τ) : mapResult f (run read₁ key₁ read₂ key₂ K report B fuel₁ fuel₂ s₁ s₂ a) = run read₁ key₁ read₂ key₂ K report' B fuel₁ fuel₂ s₁ s₂ (f a) := by let filled := TieBuffer.fill read₂ key₂ K B s₂ let long := TieBuffer.hasKey read₂ key₂ K filled.cursor have hstep := fun x st => (step_mapUser read₂ key₂ K report report' f hf filled.buffer filled.cursor long fuel₂ x st).symm have h := TieReplay.run_mapUser read₁ key₁ K (step read₂ key₂ K report filled.buffer filled.cursor long fuel₂) (step read₂ key₂ K report' filled.buffer filled.cursor long fuel₂) (mapUser f) hstep fuel₁ s₁ ⟨filled.cursor, a, 0, 0, 0⟩ change mapResult f ⟨_, filled.queries, filled.buffer.size, _⟩ = _ unfold mapResult rw [h] rfl
end TieGroupnamespace StreamJoin
variable {σ₂ : Type t}
def mapUser (f : τ → τ') (a : State σ σ₂ τ) : State σ σ₂ τ' := ⟨a.left, a.right, f a.user, a.queries, a.reports, a.copies, a.done⟩
def mapStopped (f : τ → τ') (a : StoppedResult σ σ₂ τ) : StoppedResult σ σ₂ τ' := ⟨mapUser f a.state, a.steps⟩
theorem step_mapUser (read₁ : σ → Option (α × σ)) (key₁ : α → ℤ) (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ) (report : α → β → τ → τ × Bool) (report' : α → β → τ' → τ' × Bool) (f : τ → τ') (hf : ∀ x y a, report' x y (f a) = (f (report x y a).1, (report x y a).2)) (B fuel₁ fuel₂ : ℕ) (a : State σ σ₂ τ) : mapUser f (step read₁ key₁ read₂ key₂ report B fuel₁ fuel₂ a) = step read₁ key₁ read₂ key₂ report' B fuel₁ fuel₂ (mapUser f a) := by by_cases hd : a.done = true · simp only [step, mapUser, hd, ↓reduceIte] · cases h₁ : read₁ a.left with | none => simp only [step, mapUser, hd, Bool.false_eq_true, ↓reduceIte, h₁] | some p₁ => rcases p₁ with ⟨x, l⟩ cases h₂ : read₂ a.right with | none => simp only [step, mapUser, hd, Bool.false_eq_true, ↓reduceIte, h₁, h₂] | some p₂ => rcases p₂ with ⟨y, r⟩ simp only [step, mapUser, hd, Bool.false_eq_true, ↓reduceIte, h₁, h₂, ← TieGroup.run_mapUser read₁ key₁ read₂ key₂ (key₁ x) report report' f hf, TieGroup.mapResult, TieReplay.mapUser, TieGroup.mapUser] split · simp_all only · split <;> simp_all only
theorem stoppedAcc_mapUser (read₁ : σ → Option (α × σ)) (key₁ : α → ℤ) (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ) (report : α → β → τ → τ × Bool) (report' : α → β → τ' → τ' × Bool) (f : τ → τ') (hf : ∀ x y a, report' x y (f a) = (f (report x y a).1, (report x y a).2)) (B fuel₁ fuel₂ fuel : ℕ) (a : State σ σ₂ τ) : mapStopped f (stoppedAcc read₁ key₁ read₂ key₂ report B fuel₁ fuel₂ fuel a) = stoppedAcc read₁ key₁ read₂ key₂ report' B fuel₁ fuel₂ fuel (mapUser f a) := by induction fuel generalizing a with | zero => rfl | succ fuel ih => by_cases hd : a.done = true · simp only [stoppedAcc, mapStopped, mapUser, hd, ↓reduceIte] · have h := ih (step read₁ key₁ read₂ key₂ report B fuel₁ fuel₂ a) have hdone : (mapUser f a).done = a.done := rfl simp only [stoppedAcc, hdone, hd, Bool.false_eq_true, ↓reduceIte] rw [← step_mapUser read₁ key₁ read₂ key₂ report report' f hf] rw [← h] rfl
theorem run_mapUser (read₁ : σ → Option (α × σ)) (key₁ : α → ℤ) (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ) (report : α → β → τ → τ × Bool) (report' : α → β → τ' → τ' × Bool) (f : τ → τ') (hf : ∀ x y a, report' x y (f a) = (f (report x y a).1, (report x y a).2)) (B fuel₁ fuel₂ fuel : ℕ) (s₁ : σ) (s₂ : σ₂) (a : τ) : mapUser f (run read₁ key₁ read₂ key₂ report B fuel₁ fuel₂ fuel s₁ s₂ a) = run read₁ key₁ read₂ key₂ report' B fuel₁ fuel₂ fuel s₁ s₂ (f a) := by have h := congrArg StoppedResult.state (stoppedAcc_mapUser read₁ key₁ read₂ key₂ report report' f hf B fuel₁ fuel₂ fuel (start s₁ s₂ a)) simpa only [mapStopped, stoppedAcc_eq, mapUser, start, run] using h
end StreamJoin
end LowSpaceSubsetSum
end OAI123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293import OAI.Combinatorics.LowSpaceSubsetSum.Streams.DistinctStreamCount
namespace OAI
/-! # Tail-recursive distinct counting with measured reader calls
Only the current reader state, previous key, count, remaining fuel and workcounter survive each iteration. No list of emitted keys is constructed.-/
namespace LowSpaceSubsetSum.MeasuredDistinctCount
variable {α σ : Type*}
def loop (read : σ → Option (α × σ) × ℕ) (key : α → ℤ × ℕ) : ℕ → σ → Option ℤ → ℕ → ℕ → ℕ × ℕ | 0, _, _, count, work => (count, work + 1) | fuel + 1, state, previous, count, work => let out := read state match out.1 with | none => (count, work + out.2 + 1) | some (x, next) => let k := key x let fresh := match previous with | none => true | some p => decide (p ≠ k.1) loop read key fuel next (some k.1) (count + if fresh then 1 else 0) (work + out.2 + k.2 + 3)
theorem loop_value (read : σ → Option (α × σ) × ℕ) (key : α → ℤ × ℕ) (fuel : ℕ) (s : σ) (previous : Option ℤ) (count work : ℕ) : (loop read key fuel s previous count work).1 = count + match previous with | none => (DistinctStreamCount.run (fun s => (read s).1) (fun x => (key x).1) fuel s).1 | some p => (DistinctStreamCount.tail (fun s => (read s).1) (fun x => (key x).1) fuel s p).1 := by induction fuel generalizing s previous count work with | zero => cases previous <;> simp only [loop, DistinctStreamCount.run, DistinctStreamCount.tail, Nat.add_zero] | succ fuel ih => cases previous with | none => cases hr : (read s).1 with | none => simp only [loop, hr, DistinctStreamCount.run, Nat.add_zero] | some out => rcases out with ⟨x, next⟩ simp only [loop, hr, ↓reduceIte, ih, DistinctStreamCount.run] omega | some p => cases hr : (read s).1 with | none => simp only [loop, hr, DistinctStreamCount.tail, Nat.add_zero] | some out => rcases out with ⟨x, next⟩ by_cases he : p = (key x).1 · subst p simp only [loop, hr, ne_eq, not_true_eq_false, decide_false, Bool.false_eq_true, ↓reduceIte, Nat.add_zero, ih, DistinctStreamCount.tail] · simp only [loop, hr, ne_eq, he, not_false_eq_true, decide_true, ↓reduceIte, ih, DistinctStreamCount.tail] omega
theorem loop_work (read : σ → Option (α × σ) × ℕ) (key : α → ℤ × ℕ) (R K : ℕ) (hread : ∀ s, (read s).2 ≤ R) (hkey : ∀ x, (key x).2 ≤ K) (fuel : ℕ) (s : σ) (previous : Option ℤ) (count work : ℕ) : (loop read key fuel s previous count work).2 ≤ work + (R + K + 4) * fuel + 1 := by induction fuel generalizing s previous count work with | zero => simp only [loop, Nat.mul_zero, Nat.add_zero, le_refl] | succ fuel ih => have hr := hread s simp only [loop] split · dsimp only nlinarith only [hr, Nat.zero_le ((R + K + 4) * fuel)] next x next _ => have hk := hkey x have ht := ih next (some (key x).1) (count + if (match previous with | none => true | some p => decide (p ≠ (key x).1)) then 1 else 0) (work + (read s).2 + (key x).2 + 3) nlinarith only [hr, hk, ht]
def run (read : σ → Option (α × σ) × ℕ) (key : α → ℤ × ℕ) (fuel : ℕ) (s : σ) : ℕ × ℕ := loop read key fuel s none 0 0
theorem run_value (read : σ → Option (α × σ) × ℕ) (key : α → ℤ × ℕ) (fuel : ℕ) (s : σ) : (run read key fuel s).1 = (DistinctStreamCount.run (fun s => (read s).1) (fun x => (key x).1) fuel s).1 := by simpa only [run, Nat.zero_add] using loop_value read key fuel s none 0 0
theorem run_work (read : σ → Option (α × σ) × ℕ) (key : α → ℤ × ℕ) (R K : ℕ) (hread : ∀ s, (read s).2 ≤ R) (hkey : ∀ x, (key x).2 ≤ K) (fuel : ℕ) (s : σ) : (run read key fuel s).2 ≤ (R + K + 4) * fuel + 1 := by simpa only [run, Nat.zero_add] using loop_work read key R K hread hkey fuel s none 0 0
end LowSpaceSubsetSum.MeasuredDistinctCount
end OAI123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170import OAI.Combinatorics.LowSpaceSubsetSum.Representation.RepresentationWeightedReader
namespace OAI
/-! # Measured construction of the row tournament
Each leaf calls its measured initializer once; each internal node evaluatesits two candidate keys. Binary paths are converted to array indices by anexplicit recursive computation. No row array is constructed by this routine.-/
namespace LowSpaceSubsetSum
namespace Tournament
variable {α : Type*}
def measuredBuild (key : α → ℤ × ℕ) : (d : ℕ) → ((Fin d → Bool) → Option α × ℕ) → Tree α d × ℕ | 0, front => let x := front Fin.elim0 (.leaf x.1, x.2 + 1) | d + 1, front => let l := measuredBuild key d (fun p => front (Fin.cons false p)) let r := measuredBuild key d (fun p => front (Fin.cons true p)) let w := measuredPick key (winner l.1) (winner r.1) (.node w.1 l.1 r.1, l.2 + r.2 + w.2 + 5)
theorem measuredBuild_value (key : α → ℤ × ℕ) (d : ℕ) (front : (Fin d → Bool) → Option α × ℕ) : (measuredBuild key d front).1 = build (fun x => (key x).1) d (fun p => (front p).1) := by induction d with | zero => rfl | succ d ih => simp only [measuredBuild, build, measuredPick_value, ih, node]
theorem measuredBuild_work (key : α → ℤ × ℕ) (K R : ℕ) (hk : ∀ x, (key x).2 ≤ K) (d : ℕ) (front : (Fin d → Bool) → Option α × ℕ) (hf : ∀ p, (front p).2 ≤ R) : (measuredBuild key d front).2 ≤ (R + 2 * K + 9) * 2 ^ d - (2 * K + 8) := by induction d with | zero => simp only [measuredBuild, pow_zero, Nat.mul_one]; have := hf Fin.elim0; omega | succ d ih => have hl := ih (fun p => front (Fin.cons false p)) (fun p => hf _) have hr := ih (fun p => front (Fin.cons true p)) (fun p => hf _) have hp := measuredPick_work key K hk (winner (measuredBuild key d (fun p => front (Fin.cons false p))).1) (winner (measuredBuild key d (fun p => front (Fin.cons true p))).1) have hpow : 1 ≤ 2 ^ d := Nat.one_le_pow _ _ (by decide) have hbase : 2 * K + 8 ≤ (R + 2 * K + 9) * 2 ^ d := by nlinarith simp only [measuredBuild, pow_succ, ← Nat.mul_assoc] omega
end Tournament
namespace PaddedRows
/-- Little-endian binary evaluation. The cost includes access to a bit in apath built by at most `d` nested `Fin.cons` nodes. -/def measuredIndex : (d : ℕ) → (RowMerge.Path d) → ℕ × ℕ | 0, _ => (0, 1) | d + 1, p => let t := measuredIndex d (fun i => p i.succ) ((if p 0 then 1 else 0) + 2 * t.1, t.2 + 2 * d + 6)
private theorem index_sum (d : ℕ) (p : RowMerge.Path d) : (index d p).val = ∑ i : Fin d, (if p i then 1 else 0) * 2 ^ i.val := by change (∑ i : Fin d, (finTwoEquiv.symm (p i)).val * 2 ^ i.val) = _ apply Finset.sum_congr rfl intro i _ cases h : p i <;> rfl
theorem measuredIndex_value (d : ℕ) (p : RowMerge.Path d) : (measuredIndex d p).1 = (index d p).val := by induction d with | zero => simp [measuredIndex] | succ d ih => rw [index_sum, Fin.sum_univ_succ] simp only [measuredIndex, ih, index_sum, Fin.val_zero, pow_zero, Nat.mul_one, Fin.val_succ, pow_succ'] rw [Finset.mul_sum] congr 1 apply Finset.sum_congr rfl intro i _ ring
theorem measuredIndex_work (d : ℕ) (p : RowMerge.Path d) : (measuredIndex d p).2 ≤ 4 * (d + 1) ^ 2 := by induction d with | zero => norm_num [measuredIndex] | succ d ih => have h := ih (fun i => p i.succ) change _ + 2 * d + 6 ≤ _ nlinarith
end PaddedRowsend LowSpaceSubsetSum
namespace LowSpaceSubsetSum.FilteredStream
variable {α β : Type*}
/-- Initialize and read one padded row, directly from the shared arrays. -/def measuredFront (left : Array α) (right : Array β) (row : α → PairCursor.State α right.size × ℕ) (d : ℕ) (p : RowMerge.Path d) : Option (RowMerge.Front d (α × β) (Cursor (α := α) right)) × ℕ := let i := PaddedRows.measuredIndex d p if h : i.1 < left.size then let r := row left[i.1] let q := countedRead right (some r.1) (q.1.map (fun z => ⟨p, z.1, z.2⟩), i.2 + r.2 + q.2 + 6) else (none, i.2 + 2)
theorem measuredFront_value (left : Array α) (right : Array β) (row : α → PairCursor.State α right.size × ℕ) (d : ℕ) (p : RowMerge.Path d) : (measuredFront left right row d p).1 = RowMerge.front (read right) p (PaddedRows.rows (left.map (fun x => (row x).1)) d p) := by simp only [measuredFront, PaddedRows.measuredIndex_value, PaddedRows.rows, Array.size_map, RowMerge.front] split_ifs with h · simp only [Array.getElem_map, countedRead_value] · rfl
theorem measuredFront_work (left : Array α) (right : Array β) (row : α → PairCursor.State α right.size × ℕ) (R : ℕ) (hr : ∀ x, (row x).2 ≤ R) (d : ℕ) (p : RowMerge.Path d) : (measuredFront left right row d p).2 ≤ 4 * (d + 1) ^ 2 + R + 30 := by have hi := PaddedRows.measuredIndex_work d p unfold measuredFront dsimp only split · have hr' := hr left[(PaddedRows.measuredIndex d p).1] have hq := countedRead_work right (some (row left[(PaddedRows.measuredIndex d p).1]).1) dsimp only omega · dsimp only omega
def measuredInitialTree (left : Array α) (right : Array β) (key : α × β → ℤ × ℕ) (row : α → PairCursor.State α right.size × ℕ) (d : ℕ) := Tournament.measuredBuild (fun x : RowMerge.Front d (α × β) (Cursor (α := α) right) => key x.value) d (measuredFront left right row d)
theorem measuredInitialTree_value (left : Array α) (right : Array β) (key : α × β → ℤ × ℕ) (row : α → PairCursor.State α right.size × ℕ) (d : ℕ) : (measuredInitialTree left right key row d).1 = RowMerge.start (fun x => (key x).1) (read right) (PaddedRows.rows (left.map (fun x => (row x).1)) d) := by simp only [measuredInitialTree, Tournament.measuredBuild_value, RowMerge.start] congr 1 funext p exact measuredFront_value left right row d p
theorem measuredInitialTree_work (left : Array α) (right : Array β) (key : α × β → ℤ × ℕ) (row : α → PairCursor.State α right.size × ℕ) (K R : ℕ) (hk : ∀ x, (key x).2 ≤ K) (hr : ∀ x, (row x).2 ≤ R) (d : ℕ) : (measuredInitialTree left right key row d).2 ≤ (4 * (d + 1) ^ 2 + R + 2 * K + 39) * 2 ^ d := by have h := Tournament.measuredBuild_work (fun x => key x.value) K (4 * (d + 1) ^ 2 + R + 30) (fun x => hk x.value) d (measuredFront left right row d) (measuredFront_work left right row R hr d) calc _ ≤ (4 * (d + 1) ^ 2 + R + 30 + 2 * K + 9) * 2 ^ d - (2 * K + 8) := h _ ≤ (4 * (d + 1) ^ 2 + R + 30 + 2 * K + 9) * 2 ^ d := Nat.sub_le _ _ _ = _ := by ring
end LowSpaceSubsetSum.FilteredStream
end OAI123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960import Mathlib.Data.Nat.Log
namespace OAI
/-! # A bounded tail-recursive binary logarithm
This is the integer operation needed to turn measured mixer counts intoprime widths. Each iteration divides by two and updates two counters.-/
namespace LowSpaceSubsetSum.MeasuredLog2
def loop : ℕ → ℕ → ℕ → ℕ → ℕ × ℕ | 0, _, value, work => (value, work + 1) | fuel + 1, x, value, work => if 2 ≤ x then loop fuel (x / 2) (value + 1) (work + 3) else (value, work + 1)
theorem loop_value (fuel x value work : ℕ) (hx : Nat.log2 x ≤ fuel) : (loop fuel x value work).1 = value + Nat.log2 x := by induction fuel generalizing x value work with | zero => have hz : Nat.log2 x = 0 := by omega simp [loop, hz] | succ fuel ih => rw [loop] split next h => have he := Nat.log2_def x rw [ite_eq_left h] at he rw [ih _ _ _ (by omega), he] omega next h => simp only [Nat.log2_def x, ite_eq_right h, Nat.add_zero]
theorem loop_work (fuel x value work : ℕ) : (loop fuel x value work).2 ≤ work + 3 * fuel + 1 := by induction fuel generalizing x value work with | zero => simp [loop] | succ fuel ih => rw [loop] split · have h := ih (x / 2) (value + 1) (work + 3); omega · simp only; omega
def run (bits x : ℕ) : ℕ × ℕ := loop bits x 0 0
theorem run_value (bits x : ℕ) (hx : x ≤ 2 ^ bits) : (run bits x).1 = Nat.log2 x := by have hlog : Nat.log2 x ≤ bits := by rw [Nat.log2_eq_log_two] have h := Nat.log_mono_right (b := 2) hx simpa only [Nat.log_pow (by decide : 1 < 2)] using h simpa only [run, Nat.zero_add] using loop_value bits x 0 0 hlog
theorem run_work (bits x : ℕ) : (run bits x).2 ≤ 3 * bits + 1 := by simpa only [run, Nat.zero_add] using loop_work bits x 0 0
end LowSpaceSubsetSum.MeasuredLog2
end OAI123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293import OAI.Combinatorics.LowSpaceSubsetSum.Streams.MeasuredSumReaderimport OAI.Combinatorics.LowSpaceSubsetSum.Counting.MixerParameterCountimport OAI.Combinatorics.LowSpaceSubsetSum.Compression.CompressionWeights
namespace OAI
/-! # Mixer counts from generated and sorted half-sum arrays
All subset weights, comparisons, array copies and streamed sum keys arecharged. The returned natural number is the exact distinct-sum count.-/
namespace LowSpaceSubsetSum.MeasuredMixerCount
variable {n : ℕ}
def sortedWeights (a : Fin n → ℤ) (indices : List (Fin n)) : Array ℤ × ℕ := let raw := CompressionWeights.raw a indices let out := MeasuredSort.sort (fun x y : ℤ => (decide (x ≤ y), 1)) raw.1 (out.1.toArray, raw.2 + out.2 + out.1.length + 1)
theorem sortedWeights_value (a : Fin n → ℤ) (V : Finset (Fin n)) : (sortedWeights a (V.sort (· ≤ ·))).1 = MixerParameterCount.sortedWeights a V := by simp only [sortedWeights, CompressionWeights.raw_source, MeasuredSort.sort_value, MixerParameterCount.sortedWeights, CountedSort.sort_value]
theorem sortedWeights_size (a : Fin n → ℤ) (indices : List (Fin n)) : (sortedWeights a indices).1.size = 2 ^ indices.length := by simp only [sortedWeights, List.size_toArray, MeasuredSort.sort_value, List.length_mergeSort, CompressionWeights.raw_length]
theorem sortedWeights_sorted (a : Fin n → ℤ) (indices : List (Fin n)) : (sortedWeights a indices).1.toList.Pairwise (· ≤ ·) := by simp only [sortedWeights, List.toList_toArray, MeasuredSort.sort_value] simpa only [decide_eq_true_eq] using (List.pairwise_mergeSort (le := fun x y : ℤ => decide (x ≤ y)) (fun x y z hxy hyz => decide_eq_true (le_trans (of_decide_eq_true hxy) (of_decide_eq_true hyz))) (fun x y => by simpa only [Bool.or_eq_true, decide_eq_true_eq] using le_total x y) (CompressionWeights.raw a indices).1)
def coefficient (n : ℕ) : ℕ := (n + 4) * n + 12 * n + 20
theorem sortedWeights_work (a : Fin n → ℤ) (indices : List (Fin n)) (hi : indices.length ≤ n) : (sortedWeights a indices).2 ≤ coefficient n * 2 ^ indices.length := by have hr := CompressionWeights.raw_work a indices hi have hs := MeasuredSort.sort_work (fun x y : ℤ => (decide (x ≤ y), 1)) 1 (fun _ _ => le_rfl) (CompressionWeights.raw a indices).1 n (by rw [CompressionWeights.raw_length]; exact Nat.pow_le_pow_right (by decide) hi) have hp : 1 ≤ 2 ^ indices.length := Nat.one_le_two_pow simp only [CompressionWeights.raw_length] at hs change _ + _ + _ + 1 ≤ _ simp only [MeasuredSort.sort_value, List.length_mergeSort, CompressionWeights.raw_length] unfold coefficient nlinarith only [hr, hs, hp]
def run (a : Fin n → ℤ) (left right : List (Fin n)) : ℕ × ℕ := let xs := sortedWeights a left let ys := sortedWeights a right let out := MeasuredSumReader.count xs.1 ys.1 (sortedWeights_sorted a right) (out.1, xs.2 + ys.2 + out.2 + 3)
theorem run_source (a : Fin n → ℤ) (V W : Finset (Fin n)) (hd : Disjoint V W) : (run a (V.sort (· ≤ ·)) (W.sort (· ≤ ·))).1 = distinctSumCount a (V ∪ W) := by simp only [run, MeasuredSumReader.count_value, sortedWeights_value] exact MixerParameterCount.count_value a V W hd
theorem run_work (a : Fin n → ℤ) (left right : List (Fin n)) (hleft : left.length ≤ n) (hright : right.length ≤ n) : (run a left right).2 ≤ coefficient n * 2 ^ left.length + coefficient n * 2 ^ right.length + (4 * (left.length + 1) ^ 2 + 32) * 2 ^ left.length + (10 * left.length + 21) * 2 ^ (left.length + right.length) + 6 := by have hl := sortedWeights_work a left hleft have hr := sortedWeights_work a right hright have hc := MeasuredSumReader.count_work (sortedWeights a left).1 (sortedWeights a right).1 (sortedWeights_sorted a right) simp only [sortedWeights_size, Nat.clog_pow 2 _ (by decide), ← pow_add] at hc change _ + _ + _ + 3 ≤ _ omega
def mixerCount (a : Fin n → ℤ) (V : Finset (Fin n)) : ℕ × ℕ := run a ((MixerParameterCount.firstHalf V).sort (· ≤ ·)) ((MixerParameterCount.secondHalf V).sort (· ≤ ·))
theorem mixerCount_value (a : Fin n → ℤ) (V : Finset (Fin n)) : (mixerCount a V).1 = distinctSumCount a V := by rw [mixerCount, run_source a _ _ (MixerParameterCount.halves_disjoint V), MixerParameterCount.halves_union]
end LowSpaceSubsetSum.MeasuredMixerCount
end OAI1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980import OAI.Combinatorics.LowSpaceSubsetSum.Representation.RepresentationPivotWork
namespace OAI
/-! # Binary search with counted predicate evaluations
The predicate is evaluated exactly once at each nonempty interval. Thecount includes endpoint arithmetic and the actual predicate callback cost.-/
namespace LowSpaceSubsetSum.BinaryPivot
variable {n : ℕ}
def measuredStep (p : Fin n → Bool × ℕ) (c : Cut n) : Cut n × ℕ := if h : c.lo < c.hi then let mid := (c.lo + c.hi) / 2 have hmid : mid < n := by have := c.bounded; dsimp [mid]; omega let q := p ⟨mid, hmid⟩ (if q.1 then ⟨mid + 1, c.hi, by dsimp [mid]; omega, c.bounded⟩ else ⟨c.lo, mid, by dsimp [mid]; omega, by have := c.bounded; dsimp [mid]; omega⟩, q.2 + 8) else (c, 1)
theorem measuredStep_value (p : Fin n → Bool × ℕ) (c : Cut n) : (measuredStep p c).1 = step (fun i => (p i).1) c := by unfold measuredStep step split <;> rfl
theorem measuredStep_work (p : Fin n → Bool × ℕ) (K : ℕ) (hp : ∀ i, (p i).2 ≤ K) (c : Cut n) : (measuredStep p c).2 ≤ K + 8 := by unfold measuredStep split · rename_i h exact Nat.add_le_add_right (hp ⟨(c.lo + c.hi) / 2, by have := c.bounded; omega⟩) 8 · omega
/-- The accumulator makes the search loop tail recursive. -/def measuredRun (p : Fin n → Bool × ℕ) : ℕ → Cut n → ℕ → Cut n × ℕ | 0, c, work => (c, work) | k + 1, c, work => let q := measuredStep p c measuredRun p k q.1 (work + q.2)
theorem measuredRun_value (p : Fin n → Bool × ℕ) (k : ℕ) (c : Cut n) (work : ℕ) : (measuredRun p k c work).1 = (step (fun i => (p i).1))^[k] c := by induction k generalizing c work with | zero => rfl | succ k ih => rw [measuredRun, ih, measuredStep_value, Function.iterate_succ_apply]
theorem measuredRun_work (p : Fin n → Bool × ℕ) (K : ℕ) (hp : ∀ i, (p i).2 ≤ K) (k : ℕ) (c : Cut n) (work : ℕ) : (measuredRun p k c work).2 ≤ work + (K + 8) * k := by induction k generalizing c work with | zero => simp only [measuredRun, Nat.mul_zero, Nat.add_zero, le_refl] | succ k ih => have hi := ih (measuredStep p c).1 (work + (measuredStep p c).2) have hs := measuredStep_work p K hp c change (measuredRun p k (measuredStep p c).1 (work + (measuredStep p c).2)).2 ≤ _ simp only [Nat.mul_add, Nat.mul_one] omega
def measuredSearch (p : Fin n → Bool × ℕ) (k : ℕ) : Cut n × ℕ := measuredRun p k (initial n) 0
theorem measuredSearch_value (p : Fin n → Bool × ℕ) (k : ℕ) : (measuredSearch p k).1 = search (fun i => (p i).1) k := measuredRun_value _ _ _ _
theorem measuredSearch_work (p : Fin n → Bool × ℕ) (K : ℕ) (hp : ∀ i, (p i).2 ≤ K) (k : ℕ) : (measuredSearch p k).2 ≤ (K + 8) * k := by simpa only [measuredSearch, Nat.zero_add] using measuredRun_work p K hp k (initial n) 0
end LowSpaceSubsetSum.BinaryPivot
end OAI123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212import OAI.Combinatorics.LowSpaceSubsetSum.Streams.MeasuredPivotimport OAI.Combinatorics.LowSpaceSubsetSum.Representation.RepresentationKeys
namespace OAI
/-! # Modular row initialization with measured weight evaluation
Every binary-search predicate executes the stored-record weight routine.The left weight is computed once, and all searches address the shared rightarray directly. The resulting cursor is the original filtered row cursor.-/
namespace LowSpaceSubsetSumnamespace BinarySlice
variable {α : Type*}
def measuredRange (xs : Array α) (key : α → ℤ × ℕ) (r : ℤ) (k : ℕ) (hs : Monotone (fun i : Fin xs.size => (key xs[i.val]).1)) (hk : xs.size < 2 ^ k) : SliceCursor.Range xs.size × ℕ := let lo := BinaryPivot.measuredSearch (fun i : Fin xs.size => let q := key xs[i.val]; (decide (q.1 < r), q.2 + 2)) k let hi := BinaryPivot.measuredSearch (fun i : Fin xs.size => let q := key xs[i.val]; (decide (q.1 ≤ r), q.2 + 2)) k have hlo : lo.1.lo = lower xs (fun x => (key x).1) r k := congrArg BinaryPivot.Cut.lo (BinaryPivot.measuredSearch_value _ _) have hhi : hi.1.lo = upper xs (fun x => (key x).1) r k := congrArg BinaryPivot.Cut.lo (BinaryPivot.measuredSearch_value _ _) (⟨lo.1.lo, hi.1.lo - lo.1.lo, by rw [hlo, hhi] exact (range xs (fun x => (key x).1) r k hs hk).bounded⟩, lo.2 + hi.2 + 4)
theorem measuredRange_value (xs : Array α) (key : α → ℤ × ℕ) (r : ℤ) (k : ℕ) (hs : Monotone (fun i : Fin xs.size => (key xs[i.val]).1)) (hk : xs.size < 2 ^ k) : (measuredRange xs key r k hs hk).1 = range xs (fun x => (key x).1) r k hs hk := by simp only [measuredRange, BinaryPivot.measuredSearch_value, range, lower, upper]
theorem measuredRange_work (xs : Array α) (key : α → ℤ × ℕ) (r : ℤ) (k K : ℕ) (hkey : ∀ x, (key x).2 ≤ K) (hs : Monotone (fun i : Fin xs.size => (key xs[i.val]).1)) (hk : xs.size < 2 ^ k) : (measuredRange xs key r k hs hk).2 ≤ 2 * (K + 10) * k + 4 := by have hl := BinaryPivot.measuredSearch_work (fun i : Fin xs.size => let q := key xs[i.val]; (decide (q.1 < r), q.2 + 2)) (K + 2) (fun i => Nat.add_le_add_right (hkey xs[i.val]) 2) k have hh := BinaryPivot.measuredSearch_work (fun i : Fin xs.size => let q := key xs[i.val]; (decide (q.1 ≤ r), q.2 + 2)) (K + 2) (fun i => Nat.add_le_add_right (hkey xs[i.val]) 2) k change _ + _ + 4 ≤ _ simp only [Nat.add_assoc, Nat.mul_assoc, Nat.reduceAdd] at hl hh ⊢ omega
end BinarySlicenamespace ModularCursor
open scoped Fin.NatCast
variable {n : ℕ} [NeZero n] {α : Type*}
def measuredForward (a : Fin n → α) (key : α → ℤ × ℕ) (P r : ℤ) (k : ℕ) : CyclicCursor.State n × ℕ := let q := BinaryPivot.measuredSearch (fun i => let w := key (a i); (decide (w.1 < P - r), w.2 + 2)) k (⟨Fin.ofNat n q.1.lo, n, false⟩, q.2 + 6)
def measuredReverse (a : Fin n → α) (key : α → ℤ × ℕ) (r : ℤ) (k : ℕ) : CyclicCursor.State n × ℕ := let q := BinaryPivot.measuredSearch (fun i => let w := key (a i); (decide (w.1 ≤ r), w.2 + 2)) k (⟨Fin.ofNat n q.1.lo - 1, n, true⟩, q.2 + 6)
theorem measuredForward_value (a : Fin n → α) (key : α → ℤ × ℕ) (P r : ℤ) (k : ℕ) : (measuredForward a key P r k).1 = forwardStart a (fun x => (key x).1) P r k := by simp only [measuredForward, BinaryPivot.measuredSearch_value, forwardStart]
theorem measuredReverse_value (a : Fin n → α) (key : α → ℤ × ℕ) (r : ℤ) (k : ℕ) : (measuredReverse a key r k).1 = reverseStart a (fun x => (key x).1) r k := by simp only [measuredReverse, BinaryPivot.measuredSearch_value, reverseStart]
theorem measuredForward_work (a : Fin n → α) (key : α → ℤ × ℕ) (P r : ℤ) (k K : ℕ) (hkey : ∀ x, (key x).2 ≤ K) : (measuredForward a key P r k).2 ≤ (K + 10) * k + 6 := by exact Nat.add_le_add_right (BinaryPivot.measuredSearch_work _ (K + 2) (fun i => Nat.add_le_add_right (hkey (a i)) 2) k) 6
theorem measuredReverse_work (a : Fin n → α) (key : α → ℤ × ℕ) (r : ℤ) (k K : ℕ) (hkey : ∀ x, (key x).2 ≤ K) : (measuredReverse a key r k).2 ≤ (K + 10) * k + 6 := by exact Nat.add_le_add_right (BinaryPivot.measuredSearch_work _ (K + 2) (fun i => Nat.add_le_add_right (hkey (a i)) 2) k) 6
end ModularCursornamespace SliceModular
variable {α : Type*}
def measuredForward (xs : Array α) (rr : SliceCursor.Range xs.size) (key : α → ℤ × ℕ) (P r : ℤ) (k : ℕ) : SliceCursor.State xs.size × ℕ := if h : 0 < rr.length then haveI : NeZero rr.length := ⟨by omega⟩ let q := ModularCursor.measuredForward (SliceCursor.values xs rr) key P r k (⟨rr, some q.1⟩, q.2 + 2) else (⟨rr, none⟩, 1)
def measuredReverse (xs : Array α) (rr : SliceCursor.Range xs.size) (key : α → ℤ × ℕ) (r : ℤ) (k : ℕ) : SliceCursor.State xs.size × ℕ := if h : 0 < rr.length then haveI : NeZero rr.length := ⟨by omega⟩ let q := ModularCursor.measuredReverse (SliceCursor.values xs rr) key r k (⟨rr, some q.1⟩, q.2 + 2) else (⟨rr, none⟩, 1)
theorem measuredForward_value (xs : Array α) (rr : SliceCursor.Range xs.size) (key : α → ℤ × ℕ) (P r : ℤ) (k : ℕ) : (measuredForward xs rr key P r k).1 = forward xs rr (fun x => (key x).1) P r k := by unfold measuredForward forward split <;> simp only [ModularCursor.measuredForward_value]
theorem measuredReverse_value (xs : Array α) (rr : SliceCursor.Range xs.size) (key : α → ℤ × ℕ) (r : ℤ) (k : ℕ) : (measuredReverse xs rr key r k).1 = reverse xs rr (fun x => (key x).1) r k := by unfold measuredReverse reverse split <;> simp only [ModularCursor.measuredReverse_value]
theorem measuredForward_work (xs : Array α) (rr : SliceCursor.Range xs.size) (key : α → ℤ × ℕ) (P r : ℤ) (k K : ℕ) (hkey : ∀ x, (key x).2 ≤ K) : (measuredForward xs rr key P r k).2 ≤ (K + 10) * k + 8 := by unfold measuredForward split · rename_i h have : NeZero rr.length := ⟨by omega⟩ exact Nat.add_le_add_right (ModularCursor.measuredForward_work _ key P r k K hkey) 2 · omega
theorem measuredReverse_work (xs : Array α) (rr : SliceCursor.Range xs.size) (key : α → ℤ × ℕ) (r : ℤ) (k K : ℕ) (hkey : ∀ x, (key x).2 ≤ K) : (measuredReverse xs rr key r k).2 ≤ (K + 10) * k + 8 := by unfold measuredReverse split · rename_i h have : NeZero rr.length := ⟨by omega⟩ exact Nat.add_le_add_right (ModularCursor.measuredReverse_work _ key r k K hkey) 2 · omega
end SliceModularend LowSpaceSubsetSumnamespace LowSpaceSubsetSum.FilteredStream
variable {α β : Type*}
def measuredRow (right : Array β) (wl : α → ℤ × ℕ) (wr : β → ℤ × ℕ) (p P c : ℤ) (hs : FilteredRow.PrimarySorted right (fun y => (wr y).1) p) (mode : Mode) (x : α) : PairCursor.State α right.size × ℕ := let wx := wl x let k := steps right.size let low := fun y => let w := wr y; (w.1 % p, w.2 + 2) let high := fun y => let w := wr y; (w.1 % P, w.2 + 2) let rr := BinarySlice.measuredRange right low ((c - wx.1) % p) k hs (steps_sufficient right.size) let q := match mode with | .direct => SliceModular.measuredForward right rr.1 high P (wx.1 % P) k | .complementary v => SliceModular.measuredReverse right rr.1 high ((v - wx.1) % P) k (⟨x, q.1⟩, wx.2 + rr.2 + q.2 + 4)
theorem measuredRow_value (right : Array β) (wl : α → ℤ × ℕ) (wr : β → ℤ × ℕ) (p P c : ℤ) (hs : FilteredRow.PrimarySorted right (fun y => (wr y).1) p) (mode : Mode) (x : α) : (measuredRow right wl wr p P c hs mode x).1 = row right (fun x => (wl x).1) (fun y => (wr y).1) p P c hs mode x := by cases mode <;> simp only [measuredRow, row, FilteredRow.forward, FilteredRow.reverse, BinarySlice.measuredRange_value, SliceModular.measuredForward_value, SliceModular.measuredReverse_value, FilteredRow.range]
theorem measuredRow_work (right : Array β) (wl : α → ℤ × ℕ) (wr : β → ℤ × ℕ) (p P c : ℤ) (hs : FilteredRow.PrimarySorted right (fun y => (wr y).1) p) (mode : Mode) (x : α) (K : ℕ) (hl : ∀ x, (wl x).2 ≤ K) (hr : ∀ y, (wr y).2 ≤ K) : (measuredRow right wl wr p P c hs mode x).2 ≤ 3 * (K + 12) * steps right.size + K + 16 := by let low := fun y => let w := wr y; (w.1 % p, w.2 + 2) let high := fun y => let w := wr y; (w.1 % P, w.2 + 2) let k := steps right.size let rr := BinarySlice.measuredRange right low ((c - (wl x).1) % p) k hs (steps_sufficient right.size) have hrr := BinarySlice.measuredRange_work right low ((c - (wl x).1) % p) k (K + 2) (fun y => Nat.add_le_add_right (hr y) 2) hs (steps_sufficient right.size) have hx := hl x cases mode with | direct => have hq := SliceModular.measuredForward_work right rr.1 high P ((wl x).1 % P) k (K + 2) (fun y => Nat.add_le_add_right (hr y) 2) change (wl x).2 + rr.2 + (SliceModular.measuredForward right rr.1 high P ((wl x).1 % P) k).2 + 4 ≤ _ change rr.2 ≤ 2 * (K + 2 + 10) * k + 4 at hrr change _ ≤ 3 * (K + 12) * k + K + 16 simp only [Nat.add_assoc, Nat.mul_assoc, Nat.reduceAdd] at hrr hq ⊢ omega | complementary v => have hq := SliceModular.measuredReverse_work right rr.1 high ((v - (wl x).1) % P) k (K + 2) (fun y => Nat.add_le_add_right (hr y) 2) change (wl x).2 + rr.2 + (SliceModular.measuredReverse right rr.1 high ((v - (wl x).1) % P) k).2 + 4 ≤ _ change rr.2 ≤ 2 * (K + 2 + 10) * k + 4 at hrr change _ ≤ 3 * (K + 12) * k + K + 16 simp only [Nat.add_assoc, Nat.mul_assoc, Nat.reduceAdd] at hrr hq ⊢ omega
end LowSpaceSubsetSum.FilteredStream
end OAI123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128import OAI.Combinatorics.LowSpaceSubsetSum.Streams.CountedSort
namespace OAI
/-! # Mergesort including every comparator callback
The value agrees exactly with the counted merge and sort. The work theoremscales its structural ledger by a bound on the supplied comparison work.-/
namespace LowSpaceSubsetSum.MeasuredSort
variable {α : Type*}
def merge (cmp : α → α → Bool × ℕ) (xs ys : List α) : List α × ℕ := match xs, ys with | [], ys => (ys, 1) | xs, [] => (xs, 1) | x :: xs, y :: ys => let c := cmp x y if c.1 then let out := merge cmp xs (y :: ys) (x :: out.1, out.2 + c.2 + 1) else let out := merge cmp (x :: xs) ys (y :: out.1, out.2 + c.2 + 1)termination_by xs.length + ys.length
theorem merge_value (cmp : α → α → Bool × ℕ) (xs ys : List α) : (merge cmp xs ys).1 = (CountedSort.merge (fun x y => (cmp x y).1) xs ys).1 := by induction xs generalizing ys with | nil => simp [merge, CountedSort.merge] | cons x xs ih => induction ys with | nil => simp [merge, CountedSort.merge] | cons y ys ihy => cases h : (cmp x y).1 <;> simp [merge, CountedSort.merge, h, ih, ihy]
theorem merge_work (cmp : α → α → Bool × ℕ) (K : ℕ) (hc : ∀ x y, (cmp x y).2 ≤ K) (xs ys : List α) : (merge cmp xs ys).2 ≤ (K + 1) * (CountedSort.merge (fun x y => (cmp x y).1) xs ys).2 := by induction xs generalizing ys with | nil => simp [merge, CountedSort.merge] | cons x xs ih => induction ys with | nil => simp [merge, CountedSort.merge] | cons y ys ihy => have hcost := hc x y cases h : (cmp x y).1 · simp only [merge, CountedSort.merge, h, Bool.false_eq_true, ↓reduceIte] simp only [Nat.mul_add, Nat.mul_one] omega · have hi := ih (y :: ys) simp only [merge, CountedSort.merge, h, ↓reduceIte] simp only [Nat.mul_add, Nat.mul_one] omega
def run (cmp : α → α → Bool × ℕ) : ℕ → List α → List α × ℕ | 0, xs => (xs, 1) | _ + 1, [] => ([], 1) | _ + 1, [x] => ([x], 1) | k + 1, x :: y :: rest => let xs := x :: y :: rest let cut := (xs.length + 1) / 2 let left := run cmp k (xs.take cut) let right := run cmp k (xs.drop cut) let out := merge cmp left.1 right.1 (out.1, left.2 + right.2 + 3 * xs.length + out.2 + 1)
theorem run_value (cmp : α → α → Bool × ℕ) (k : ℕ) (xs : List α) : (run cmp k xs).1 = (CountedSort.run (fun x y => (cmp x y).1) k xs).1 := by induction k generalizing xs with | zero => rfl | succ k ih => cases xs with | nil => rfl | cons x xs => cases xs with | nil => rfl | cons y rest => simp only [run, merge_value, ih, CountedSort.run]
theorem run_work (cmp : α → α → Bool × ℕ) (K : ℕ) (hc : ∀ x y, (cmp x y).2 ≤ K) (k : ℕ) (xs : List α) : (run cmp k xs).2 ≤ (K + 1) * (CountedSort.run (fun x y => (cmp x y).1) k xs).2 := by induction k generalizing xs with | zero => simp only [run, CountedSort.run]; omega | succ k ih => cases xs with | nil => simp only [run, CountedSort.run]; omega | cons x xs => cases xs with | nil => simp only [run, CountedSort.run]; omega | cons y rest => let xs := x :: y :: rest let cut := (xs.length + 1) / 2 have hl := ih (xs.take cut) have hr := ih (xs.drop cut) have hm := merge_work cmp K hc (run cmp k (xs.take cut)).1 (run cmp k (xs.drop cut)).1 rw [run_value, run_value] at hm change (run cmp k (xs.take cut)).2 + (run cmp k (xs.drop cut)).2 + 3 * xs.length + (merge cmp (run cmp k (xs.take cut)).1 (run cmp k (xs.drop cut)).1).2 + 1 ≤ (K + 1) * ((CountedSort.run (fun x y => (cmp x y).1) k (xs.take cut)).2 + (CountedSort.run (fun x y => (cmp x y).1) k (xs.drop cut)).2 + 3 * xs.length + (CountedSort.merge (fun x y => (cmp x y).1) (CountedSort.run (fun x y => (cmp x y).1) k (xs.take cut)).1 (CountedSort.run (fun x y => (cmp x y).1) k (xs.drop cut)).1).2 + 1) rw [run_value, run_value] nlinarith only [hl, hr, hm, Nat.zero_le (K * (3 * xs.length + 1))]
def sort (cmp : α → α → Bool × ℕ) (xs : List α) : List α × ℕ := run cmp (Nat.clog 2 xs.length) xs
theorem sort_value (cmp : α → α → Bool × ℕ) (xs : List α) : (sort cmp xs).1 = xs.mergeSort (fun x y => (cmp x y).1) := by rw [sort, run_value, CountedSort.run_value] exact Nat.le_pow_clog (by decide) _
theorem sort_work (cmp : α → α → Bool × ℕ) (K : ℕ) (hc : ∀ x y, (cmp x y).2 ≤ K) (xs : List α) (n : ℕ) (hn : xs.length ≤ 2 ^ n) : (sort cmp xs).2 ≤ (K + 1) * ((6 * n + 1) * xs.length + 1) := by exact (run_work cmp K hc _ _).trans (Nat.mul_le_mul_left _ (CountedSort.sort_steps_of_index_bits _ xs n hn))
end LowSpaceSubsetSum.MeasuredSort
end OAI123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128import OAI.Combinatorics.LowSpaceSubsetSum.Streams.MeasuredSort
namespace OAI
/-! # Live list and continuation cells of the executed mergesort
The first projection is exactly the measured sort, including its workcounter. The second projection records list and continuation storage;comparison callbacks are scalar operations at the terminal application.Input record payloads are shared and are not copied by a list cons.-/
namespace LowSpaceSubsetSum.MeasuredSortSpace
variable {α : Type*}
/-- The merge retains its input tails, one continuation per selected head,and the newly constructed result spine. -/def merge (cmp : α → α → Bool × ℕ) (xs ys : List α) : (List α × ℕ) × ℕ := match xs, ys with | [], ys => ((ys, 1), ys.length + 2) | xs, [] => ((xs, 1), xs.length + 2) | x :: xs, y :: ys => let c := cmp x y if c.1 then let out := merge cmp xs (y :: ys) ((x :: out.1.1, out.1.2 + c.2 + 1), max ((x :: xs).length + (y :: ys).length + 2) (out.2 + 4)) else let out := merge cmp (x :: xs) ys ((y :: out.1.1, out.1.2 + c.2 + 1), max ((x :: xs).length + (y :: ys).length + 2) (out.2 + 4))termination_by xs.length + ys.length
theorem merge_value (cmp : α → α → Bool × ℕ) (xs ys : List α) : (merge cmp xs ys).1 = MeasuredSort.merge cmp xs ys := by induction xs generalizing ys with | nil => simp [merge, MeasuredSort.merge] | cons x xs ih => induction ys with | nil => simp [merge, MeasuredSort.merge] | cons y ys ihy => cases h : (cmp x y).1 <;> simp [merge, MeasuredSort.merge, h, ih, ihy]
theorem merge_cells (cmp : α → α → Bool × ℕ) (xs ys : List α) : (merge cmp xs ys).2 ≤ 6 * (xs.length + ys.length + 1) := by induction xs generalizing ys with | nil => simp only [merge, List.length_nil]; omega | cons x xs ih => induction ys with | nil => simp only [merge, List.length_nil]; omega | cons y ys ihy => have hx := ih (y :: ys) cases h : (cmp x y).1 <;> simp only [merge, h, Bool.false_eq_true, ↓reduceIte, List.length_cons, max_le_iff] <;> simp only [List.length_cons] at hx ihy <;> constructor <;> omega
/-- One branch runs at a time. The parent input, split spines and completedsibling fit in the eight-cell-per-input local allowance. -/def run (cmp : α → α → Bool × ℕ) : ℕ → List α → (List α × ℕ) × ℕ | 0, xs => ((xs, 1), xs.length + 2) | _ + 1, [] => (([], 1), 2) | _ + 1, [x] => (([x], 1), 3) | k + 1, x :: y :: rest => let xs := x :: y :: rest let cut := (xs.length + 1) / 2 let left := run cmp k (xs.take cut) let right := run cmp k (xs.drop cut) let out := merge cmp left.1.1 right.1.1 ((out.1.1, left.1.2 + right.1.2 + 3 * xs.length + out.1.2 + 1), 8 * (xs.length + 1) + max left.2 (max right.2 out.2))
theorem run_value (cmp : α → α → Bool × ℕ) (k : ℕ) (xs : List α) : (run cmp k xs).1 = MeasuredSort.run cmp k xs := by induction k generalizing xs with | zero => rfl | succ k ih => cases xs with | nil => rfl | cons x xs => cases xs with | nil => rfl | cons y rest => simp only [run, merge_value, ih, MeasuredSort.run]
theorem run_length (cmp : α → α → Bool × ℕ) (k : ℕ) (xs : List α) : (run cmp k xs).1.1.length = xs.length := by rw [run_value, MeasuredSort.run_value] exact CountedSort.run_length _ _ _
theorem run_cells (cmp : α → α → Bool × ℕ) (k : ℕ) (xs : List α) : (run cmp k xs).2 ≤ 32 * (k + 1) * (xs.length + 1) := by induction k generalizing xs with | zero => simp only [run]; omega | succ k ih => cases xs with | nil => simp only [run, List.length_nil]; omega | cons x tail => cases tail with | nil => simp only [run, List.length_cons, List.length_nil]; omega | cons y rest => let xs := x :: y :: rest let cut := (xs.length + 1) / 2 have hl := ih (xs.take cut) have hr := ih (xs.drop cut) have hll : (xs.take cut).length ≤ xs.length := by simp only [List.length_take] exact Nat.min_le_right _ _ have hrl : (xs.drop cut).length ≤ xs.length := by simp only [List.length_drop]; omega have hleft := hl.trans (Nat.mul_le_mul_left (32 * (k + 1)) (by omega : (xs.take cut).length + 1 ≤ xs.length + 1)) have hright := hr.trans (Nat.mul_le_mul_left (32 * (k + 1)) (by omega : (xs.drop cut).length + 1 ≤ xs.length + 1)) have hm := merge_cells cmp (run cmp k (xs.take cut)).1.1 (run cmp k (xs.drop cut)).1.1 rw [run_length, run_length, List.length_take, List.length_drop] at hm have hm' : (merge cmp (run cmp k (xs.take cut)).1.1 (run cmp k (xs.drop cut)).1.1).2 ≤ 6 * (xs.length + 1) := by convert hm using 1 omega have hm'' := hm'.trans (Nat.mul_le_mul_right (xs.length + 1) (show 6 ��� 32 * (k + 1) by omega)) have hmax := max_le hleft (max_le hright hm'') change 8 * (xs.length + 1) + _ ≤ 32 * (k + 1 + 1) * (xs.length + 1) nlinarith only [hmax, Nat.zero_le xs.length]
end LowSpaceSubsetSum.MeasuredSortSpace
end OAI123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122import OAI.Combinatorics.LowSpaceSubsetSum.Representation.RepresentationStoredRecords
namespace OAI
/-! # Executed generation retaining bounded index lists
The subset generators return index lists. Wrapping them as bounded masksretains those lists; finite sets occur only in the semantic specification.The work counter includes wrapping and both Cartesian-product traversals.-/
namespace LowSpaceSubsetSumnamespace IndexedMask
variable {n : ℕ}
private theorem selectedList_length (xs ys : List (Fin n)) (k : ℕ) (h : ys ∈ (CountedSubsets.select k xs).1) : ys.length ≤ xs.length := by rw [CountedSubsets.select_value] at h exact (List.mem_sublistsLen.mp h).1.length_le
private theorem allList_length (xs ys : List (Fin n)) (h : ys ∈ (CountedSubsets.all xs).1) : ys.length ≤ xs.length := by rw [CountedSubsets.all_value] at h exact (List.mem_sublists.mp h).length_le
def measuredSelected (xs : List (Fin n)) (hx : xs.length ≤ n) (k : ℕ) : List (IndexedMask n) × ℕ := let out := CountedSubsets.select k xs (out.1.attach.map (fun y => ⟨y.val, (selectedList_length xs y.val k y.property).trans hx⟩), out.2 + out.1.length)
def measuredAll (xs : List (Fin n)) (hx : xs.length ≤ n) : List (IndexedMask n) × ℕ := let out := CountedSubsets.all xs (out.1.attach.map (fun y => ⟨y.val, (allList_length xs y.val y.property).trans hx⟩), out.2 + out.1.length)
@[simp] theorem measuredSelected_value (xs : List (Fin n)) (hx : xs.length ≤ n) (k : ℕ) : (measuredSelected xs hx k).1 = selected xs hx k := rfl
@[simp] theorem measuredAll_value (xs : List (Fin n)) (hx : xs.length ≤ n) : (measuredAll xs hx).1 = all xs hx := rfl
@[simp] theorem selected_length (xs : List (Fin n)) (hx : xs.length ≤ n) (k : ℕ) : (selected xs hx k).length = xs.length.choose k := by simp only [selected, List.length_map, List.length_attach, CountedSubsets.select_length]
@[simp] theorem all_length (xs : List (Fin n)) (hx : xs.length ≤ n) : (all xs hx).length = 2 ^ xs.length := by simp only [all, List.length_map, List.length_attach, CountedSubsets.all_length]
end IndexedMask
namespace RepresentationLeaf
variable {n : ℕ}
def measuredStoredRecords (L : RepresentationLeaf (Fin n)) : List (LeafRecord n) × ℕ := if L.topCount ≤ L.top.card ∧ L.localCount ≤ L.mixer.card then let dt := domainSort L.top let dm := domainSort L.mixer let db := domainSort L.background let t := IndexedMask.measuredSelected dt.1 (by rw [domainSort_length]; simpa using Finset.card_le_univ L.top) L.topCount let m := IndexedMask.measuredSelected dm.1 (by rw [domainSort_length]; simpa using Finset.card_le_univ L.mixer) L.localCount let b := IndexedMask.measuredAll db.1 (by rw [domainSort_length]; simpa using Finset.card_le_univ L.background) let tm := t.1 ×ˢ m.1 let out := (tm ×ˢ b.1).map (fun y => (⟨y.1.1, y.1.2, y.2⟩ : LeafRecord n)) (out, dt.2 + dm.2 + db.2 + t.2 + m.2 + b.2 + 4 * tm.length + 8 * out.length + 3 * (n + 1)) else ([], 3 * (n + 1))
theorem measuredStoredRecords_value (L : RepresentationLeaf (Fin n)) : L.measuredStoredRecords.1 = L.storedRecords := by simp only [measuredStoredRecords, storedRecords] split <;> simp only [IndexedMask.measuredSelected_value, IndexedMask.measuredAll_value]
theorem measuredStoredRecords_cost (L : RepresentationLeaf (Fin n)) : L.measuredStoredRecords.2 ≤ 3 * L.countedEnumerate.2 := by by_cases hf : L.topCount ≤ L.top.card ∧ L.localCount ≤ L.mixer.card · have hc : 1 ≤ 2 ^ L.background.card := Nat.one_le_two_pow have hp : 1 ≤ (n + 1) ^ 2 := Nat.one_le_pow _ _ (by omega) have htm : L.top.card.choose L.topCount * L.mixer.card.choose L.localCount ≤ L.top.card.choose L.topCount * L.mixer.card.choose L.localCount * 2 ^ L.background.card := by simpa only [Nat.mul_one] using Nat.mul_le_mul_left (L.top.card.choose L.topCount * L.mixer.card.choose L.localCount) hc have hsum : L.top.card.choose L.topCount + L.mixer.card.choose L.localCount + 2 ^ L.background.card ≤ (n + 1) ^ 2 * (L.top.card.choose L.topCount + L.mixer.card.choose L.localCount + 2 ^ L.background.card) := by simpa only [Nat.one_mul] using Nat.mul_le_mul_right (L.top.card.choose L.topCount + L.mixer.card.choose L.localCount + 2 ^ L.background.card) hp simp only [measuredStoredRecords, countedEnumerate, ite_eq_left hf, IndexedMask.measuredSelected, IndexedMask.measuredAll, List.length_product, List.length_map, List.length_attach, CountedSubsets.select_length, CountedSubsets.all_length, domainSort_length] omega · simp only [measuredStoredRecords, countedEnumerate, ite_eq_right hf] omega
theorem measuredStoredRecords_work (L : RepresentationLeaf (Fin n)) : L.measuredStoredRecords.2 ≤ 192 * (n + 1) ^ 2 * (L.occurrences.card + 1) := by have h := Nat.mul_le_mul_left 3 L.countedEnumerate_work exact L.measuredStoredRecords_cost.trans (by nlinarith only [h])
theorem measuredStoredRecords_scale (I : Instance n) (L : RepresentationLeaf (Fin n)) (hn : 10000 ≤ n) : L.measuredStoredRecords.2 ≤ inputScale I ^ 3 * (L.occurrences.card + 1) := by have hnu : n + 1 ≤ inputScale I := by unfold inputScale; omega have hs := Nat.pow_le_pow_left hnu 2 have hm := Nat.mul_le_mul_right (inputScale I ^ 2) (show 192 ≤ inputScale I by omega) have hp : 192 * (n + 1) ^ 2 ≤ inputScale I ^ 3 := by nlinarith only [hs, hm] exact L.measuredStoredRecords_work.trans (Nat.mul_le_mul_right _ hp)
end RepresentationLeafend LowSpaceSubsetSum
end OAI123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132import OAI.Combinatorics.LowSpaceSubsetSum.Streams.SumReaderimport OAI.Combinatorics.LowSpaceSubsetSum.Streams.MeasuredInitializationimport OAI.Combinatorics.LowSpaceSubsetSum.Streams.MeasuredDistinctCount
namespace OAI
/-! # Executed integer-sum counting
The initializer reads the shared half-sum arrays directly. Its tournamentand the tail-recursive counter are the only evolving state; the full outputstream remains a proof view. Work includes initial rows and every key read.-/
namespace LowSpaceSubsetSum.MeasuredSumReader
abbrev key (p : ℤ × ℤ) : ℤ × ℕ := (SumReader.key p, 1)
def read (ys : Array ℤ) (s : Option SumReader.Row) : Option ((ℤ × ℤ) × Option SumReader.Row) × ℕ := (PaddedRows.next (SumReader.read ys) s, 6)
def front (xs ys : Array ℤ) (d : ℕ) (p : RowMerge.Path d) : Option (RowMerge.Front d (ℤ × ℤ) (Option SumReader.Row)) × ℕ := let i := PaddedRows.measuredIndex d p if h : i.1 < xs.size then let q := read ys (some ⟨xs[i.1], 0⟩) (q.1.map (fun z => ⟨p, z.1, z.2⟩), i.2 + q.2 + 5) else (none, i.2 + 2)
theorem front_value (xs ys : Array ℤ) (d : ℕ) (p : RowMerge.Path d) : (front xs ys d p).1 = RowMerge.front (PaddedRows.next (SumReader.read ys)) p (PaddedRows.rows (SumReader.rows xs) d p) := by by_cases h : (PaddedRows.index d p).val < xs.size · simp [front, PaddedRows.measuredIndex_value, PaddedRows.rows, SumReader.rows, RowMerge.front, read, h] · simp [front, PaddedRows.measuredIndex_value, PaddedRows.rows, SumReader.rows, RowMerge.front, h, PaddedRows.next]
theorem front_work (xs ys : Array ℤ) (d : ℕ) (p : RowMerge.Path d) : (front xs ys d p).2 ≤ 4 * (d + 1) ^ 2 + 11 := by have hi := PaddedRows.measuredIndex_work d p unfold front dsimp only split <;> dsimp only [read] <;> omega
def tree (xs ys : Array ℤ) := Tournament.measuredBuild (fun x : RowMerge.Front (Nat.clog 2 xs.size) (ℤ × ℤ) (Option SumReader.Row) => key x.value) (Nat.clog 2 xs.size) (front xs ys (Nat.clog 2 xs.size))
theorem tree_value (xs ys : Array ℤ) (hs : ys.toList.Pairwise (· ≤ ·)) : (tree xs ys).1 = (SumReader.start xs ys hs).tree := by simp only [tree, Tournament.measuredBuild_value, SumReader.start, MergedReader.start, RowMerge.start] congr 1 funext p exact front_value xs ys _ p
def start (xs ys : Array ℤ) (hs : ys.toList.Pairwise (· ≤ ·)) : SumReader.State xs ys × ℕ := let out := tree xs ys let source := SumReader.start xs ys hs have he : out.1 = source.tree := tree_value xs ys hs (⟨out.1, he.symm ▸ source.valid, he.symm ▸ source.aligned, he.symm ▸ source.sorted⟩, out.2)
theorem start_value (xs ys : Array ℤ) (hs : ys.toList.Pairwise (· ≤ ·)) : (start xs ys hs).1 = SumReader.start xs ys hs := by have ext {a b : SumReader.State xs ys} (h : a.tree = b.tree) : a = b := by cases a cases b cases h rfl apply ext exact tree_value xs ys hs
theorem start_work (xs ys : Array ℤ) (hs : ys.toList.Pairwise (· ≤ ·)) : (start xs ys hs).2 ≤ (4 * (Nat.clog 2 xs.size + 1) ^ 2 + 32) * 2 ^ Nat.clog 2 xs.size := by have h := Tournament.measuredBuild_work (fun x : RowMerge.Front (Nat.clog 2 xs.size) (ℤ × ℤ) (Option SumReader.Row) => key x.value) 1 (4 * (Nat.clog 2 xs.size + 1) ^ 2 + 11) (fun _ => le_rfl) (Nat.clog 2 xs.size) (front xs ys (Nat.clog 2 xs.size)) (front_work xs ys (Nat.clog 2 xs.size)) change (tree xs ys).2 ≤ _ exact h.trans ((Nat.sub_le _ _).trans (Nat.mul_le_mul_right _ (by omega)))
def next (xs ys : Array ℤ) (s : SumReader.State xs ys) : Option ((ℤ × ℤ) × SumReader.State xs ys) × ℕ := MergedReader.measuredNext key (read ys) (PaddedRows.view (SumReader.view ys)) (PaddedRows.reader _ _ (SumReader.reader ys)) s
theorem next_value (xs ys : Array ℤ) (s : SumReader.State xs ys) : (next xs ys s).1 = SumReader.next xs ys s := MergedReader.measuredNext_value key (read ys) (PaddedRows.view (SumReader.view ys)) (PaddedRows.reader _ _ (SumReader.reader ys)) s
theorem next_work (xs ys : Array ℤ) (s : SumReader.State xs ys) : (next xs ys s).2 ≤ 10 * Nat.clog 2 xs.size + 16 := by have h := MergedReader.measuredNext_work key (read ys) (PaddedRows.view (SumReader.view ys)) (PaddedRows.reader _ _ (SumReader.reader ys)) s 1 6 (fun _ => le_rfl) (fun _ => le_rfl) change (next xs ys s).2 ≤ _ at h omega
def count (xs ys : Array ℤ) (hs : ys.toList.Pairwise (· ≤ ·)) : ℕ × ℕ := let initial := start xs ys hs let out := MeasuredDistinctCount.run (next xs ys) key (xs.size * ys.size) initial.1 (out.1, initial.2 + out.2 + 2)
theorem count_value (xs ys : Array ℤ) (hs : ys.toList.Pairwise (· ≤ ·)) : (count xs ys hs).1 = (SumReader.count xs ys hs).1 := by simp only [count, MeasuredDistinctCount.run_value, next_value, start_value] rfl
theorem count_work (xs ys : Array ℤ) (hs : ys.toList.Pairwise (· ≤ ·)) : (count xs ys hs).2 ≤ (4 * (Nat.clog 2 xs.size + 1) ^ 2 + 32) * 2 ^ Nat.clog 2 xs.size + (10 * Nat.clog 2 xs.size + 21) * (xs.size * ys.size) + 3 := by have hi := start_work xs ys hs have hc := MeasuredDistinctCount.run_work (next xs ys) key (10 * Nat.clog 2 xs.size + 16) 1 (next_work xs ys) (fun _ => le_rfl) (xs.size * ys.size) (start xs ys hs).1 have hc' : (MeasuredDistinctCount.run (next xs ys) key (xs.size * ys.size) (start xs ys hs).1).2 ≤ (10 * Nat.clog 2 xs.size + 21) * (xs.size * ys.size) + 1 := by convert hc using 1 change _ + _ + 2 ≤ _ omega
end LowSpaceSubsetSum.MeasuredSumReader
end OAI123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131import OAI.Combinatorics.LowSpaceSubsetSum.Streams.RowMergeimport Mathlib.Algebra.BigOperators.Group.Finset.Basicimport Mathlib.Data.Multiset.AddSub
namespace OAI
/-!# Complete and stopped tournament merges
The multiset view counts every row occurrence, even when all item fieldscoincide. Each successful advance removes exactly the reported occurrence.A sufficiently long trace therefore enumerates the whole product stream;the potential also bounds every stopped execution's number of advances.-/
namespace LowSpaceSubsetSumnamespace RowMerge
universe u v
variable {α : Type u} {σ : Type v} {d : ℕ}
def bag (view : σ → List α) (t : Tournament.Tree (Front d α σ) d) : Multiset α := ∑ p : Path d, (remaining view t p : Multiset α)
theorem bag_card (view : σ → List α) (t : Tournament.Tree (Front d α σ) d) : (bag view t).card = potential view t := by simp [bag, potential]
theorem replacement_bag (key : α → ℤ) (read : σ → Option (α × σ)) (view : σ → List α) (hread : IsReader read view) (t : Tournament.Tree (Front d α σ) d) (ht : Tournament.Valid (fun y => key y.value) t) (halign : Aligned t) {x : Front d α σ} (hx : Tournament.winner t = some x) : bag view t = {x.value} + bag view (Tournament.replace (fun y => key y.value) t x.row (front read x.row x.after)) := by have hrow := winner_at_own_row key t ht halign hx let t' := Tournament.replace (fun y => key y.value) t x.row (front read x.row x.after) have hpoint (p : Path d) : (remaining view t p : Multiset α) = (remaining view t' p : Multiset α) + if p = x.row then {x.value} else 0 := by have hnew := replace_remaining key read view hread t x p change remaining view t' p = _ at hnew by_cases hp : p = x.row · subst p rw [ite_eq_left rfl] at hnew rw [hnew] simp only [remaining, hrow, ↓reduceIte] change x.value ::ₘ (view x.after : Multiset α) = (view x.after : Multiset α) + {x.value} rw [← Multiset.singleton_add, add_comm] · rw [ite_eq_right (Ne.symm hp)] at hnew rw [hnew, ite_eq_right hp, add_zero] unfold bag rw [show (∑ p : Path d, (remaining view t p : Multiset α)) = ∑ p : Path d, ((remaining view t' p : Multiset α) + if p = x.row then {x.value} else 0) from Finset.sum_congr rfl (fun p _ => hpoint p)] simp [Finset.sum_add_distrib, t', add_comm]
theorem bag_eq_zero_of_winner_none (key : α → ℤ) (view : σ → List α) (t : Tournament.Tree (Front d α σ) d) (ht : Tournament.Valid (fun y => key y.value) t) (hn : Tournament.winner t = none) : bag view t = 0 := by have hc := (Tournament.winner_none_iff (fun y => key y.value) t ht).mp hn have hlookup (p : Path d) : Tournament.lookup t p = none := by cases h : Tournament.lookup t p with | none => rfl | some x => have hm := (Tournament.mem_candidates_iff t x).mpr ⟨p, h⟩ simp [hc] at hm simp [bag, remaining, hlookup]
/-- Analysis view of repeated advances. The program can stop between them. -/def trace (key : α → ℤ) (read : σ → Option (α × σ)) : ℕ → Tournament.Tree (Front d α σ) d → List α | 0, _ => [] | k + 1, t => match advance key read t with | none => [] | some (a, t') => a :: trace key read k t'
theorem trace_complete (key : α → ℤ) (read : σ → Option (α × σ)) (view : σ → List α) (hread : IsReader read view) (k : ℕ) (t : Tournament.Tree (Front d α σ) d) (ht : Tournament.Valid (fun y => key y.value) t) (halign : Aligned t) (hk : potential view t ≤ k) : (trace key read k t : Multiset α) = bag view t := by induction k generalizing t with | zero => have hz : (bag view t).card = 0 := by rw [bag_card]; omega simpa [trace] using (Multiset.card_eq_zero.mp hz).symm | succ k ih => cases hw : Tournament.winner t with | none => have hb := bag_eq_zero_of_winner_none key view t ht hw simp [trace, advance, hw, hb] | some x => let t' := Tournament.replace (fun y => key y.value) t x.row (front read x.row x.after) have ha : advance key read t = some (x.value, t') := by simp [advance, hw, t'] have ht' := advance_valid key read t ht ha have halign' := advance_aligned key read t halign ha have hdec := replacement_consumes_one key read view hread t ht halign hw change potential view t' + 1 = potential view t at hdec have hk' : potential view t' ≤ k := by omega have hbag := replacement_bag key read view hread t ht halign hw change bag view t = {x.value} + bag view t' at hbag rw [trace, ha] change x.value ::ₘ (trace key read k t' : Multiset α) = bag view t rw [ih t' ht' halign' hk', hbag] simp
theorem trace_length_le (key : α → ℤ) (read : σ → Option (α × σ)) (view : σ → List α) (hread : IsReader read view) (k : ℕ) (t : Tournament.Tree (Front d α σ) d) (ht : Tournament.Valid (fun y => key y.value) t) (halign : Aligned t) : (trace key read k t).length ≤ potential view t := by induction k generalizing t with | zero => simp [trace] | succ k ih => cases hw : Tournament.winner t with | none => simp [trace, advance, hw] | some x => let t' := Tournament.replace (fun y => key y.value) t x.row (front read x.row x.after) have ha : advance key read t = some (x.value, t') := by simp [advance, hw, t'] have ht' := advance_valid key read t ht ha have halign' := advance_aligned key read t halign ha have hdec := replacement_consumes_one key read view hread t ht halign hw have hlen := ih t' ht' halign' rw [trace, ha, List.length_cons] change potential view t' + 1 = potential view t at hdec omega
end RowMergeend LowSpaceSubsetSum
end OAI123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133import OAI.Combinatorics.LowSpaceSubsetSum.Streams.MergeCorrectness
namespace OAI
/-!# Sortedness of complete and stopped row merges
Only each row's individual order is required. The tournament minimum isno larger than every remaining occurrence; replacing its front by itssuccessor preserves this invariant. Every finite trace is therefore sorted,including traces stopped by the operation cap.-/
namespace LowSpaceSubsetSumnamespace RowMerge
universe u v
variable {α : Type u} {σ : Type v} {d : ℕ}
def RowsSorted (key : α → ℤ) (view : σ → List α) (t : Tournament.Tree (Front d α σ) d) : Prop := ∀ p, (remaining view t p).Pairwise (fun x y => key x ≤ key y)
theorem replacement_remaining_subset (key : α → ℤ) (read : σ → Option (α × σ)) (view : σ → List α) (hread : IsReader read view) (t : Tournament.Tree (Front d α σ) d) (ht : Tournament.Valid (fun y => key y.value) t) (halign : Aligned t) {x : Front d α σ} (hx : Tournament.winner t = some x) (p : Path d) : remaining view (Tournament.replace (fun y => key y.value) t x.row (front read x.row x.after)) p ⊆ remaining view t p := by have hnew := replace_remaining key read view hread t x p have hrow := winner_at_own_row key t ht halign hx rw [hnew] by_cases hp : x.row = p · subst p rw [ite_eq_left rfl] simp only [remaining, hrow] intro y hy exact List.mem_cons_of_mem _ hy · rw [ite_eq_right hp]
theorem replacement_rowsSorted (key : α → ℤ) (read : σ → Option (α × σ)) (view : σ → List α) (hread : IsReader read view) (t : Tournament.Tree (Front d α σ) d) (ht : Tournament.Valid (fun y => key y.value) t) (halign : Aligned t) (hsort : RowsSorted key view t) {x : Front d α σ} (hx : Tournament.winner t = some x) : RowsSorted key view (Tournament.replace (fun y => key y.value) t x.row (front read x.row x.after)) := by intro p rw [replace_remaining key read view hread t x p] by_cases hp : x.row = p · subst p rw [ite_eq_left rfl] have hs := hsort x.row have hrow := winner_at_own_row key t ht halign hx simp only [remaining, hrow] at hs exact (List.pairwise_cons.mp hs).2 · rw [ite_eq_right hp] exact hsort p
theorem winner_le_remaining (key : α → ℤ) (view : σ → List α) (t : Tournament.Tree (Front d α σ) d) (ht : Tournament.Valid (fun y => key y.value) t) (hsort : RowsSorted key view t) {x : Front d α σ} (hx : Tournament.winner t = some x) (p : Path d) {y : α} (hy : y ∈ remaining view t p) : key x.value ≤ key y := by cases hp : Tournament.lookup t p with | none => simp [remaining, hp] at hy | some z => have hmin := winner_is_minimum key t ht hx p hp have hs := hsort p simp only [remaining, hp] at hy hs rcases List.mem_cons.mp hy with hy | hy · simpa [hy] using hmin · exact hmin.trans ((List.pairwise_cons.mp hs).1 y hy)
theorem trace_lower_bound (key : α → ℤ) (read : σ → Option (α × σ)) (view : σ → List α) (hread : IsReader read view) (k : ℕ) (t : Tournament.Tree (Front d α σ) d) (ht : Tournament.Valid (fun y => key y.value) t) (halign : Aligned t) (c : ℤ) (hc : ∀ p, ∀ y ∈ remaining view t p, c ≤ key y) : ∀ y ∈ trace key read k t, c ≤ key y := by induction k generalizing t with | zero => simp [trace] | succ k ih => cases hw : Tournament.winner t with | none => simp [trace, advance, hw] | some x => let t' := Tournament.replace (fun y => key y.value) t x.row (front read x.row x.after) have ha : advance key read t = some (x.value, t') := by simp [advance, hw, t'] have ht' := advance_valid key read t ht ha have halign' := advance_aligned key read t halign ha have hrow := winner_at_own_row key t ht halign hw have hfront : c ≤ key x.value := hc x.row x.value (by simp [remaining, hrow]) have hc' : ∀ p, ∀ y ∈ remaining view t' p, c ≤ key y := by intro p y hy exact hc p y (replacement_remaining_subset key read view hread t ht halign hw p hy) rw [trace, ha] intro y hy rcases List.mem_cons.mp hy with hy | hy · simpa [hy] using hfront · exact ih t' ht' halign' hc' y hy
theorem trace_sorted (key : α → ℤ) (read : σ → Option (α × σ)) (view : σ → List α) (hread : IsReader read view) (k : ℕ) (t : Tournament.Tree (Front d α σ) d) (ht : Tournament.Valid (fun y => key y.value) t) (halign : Aligned t) (hsort : RowsSorted key view t) : (trace key read k t).Pairwise (fun x y => key x ≤ key y) := by induction k generalizing t with | zero => simp [trace] | succ k ih => cases hw : Tournament.winner t with | none => simp [trace, advance, hw] | some x => let t' := Tournament.replace (fun y => key y.value) t x.row (front read x.row x.after) have ha : advance key read t = some (x.value, t') := by simp [advance, hw, t'] have ht' := advance_valid key read t ht ha have halign' := advance_aligned key read t halign ha have hsort' := replacement_rowsSorted key read view hread t ht halign hsort hw rw [trace, ha] apply List.pairwise_cons.mpr refine ⟨?_, ih t' ht' halign' hsort'⟩ apply trace_lower_bound key read view hread k t' ht' halign' (key x.value) intro p y hy exact winner_le_remaining key view t ht hsort hw p (replacement_remaining_subset key read view hread t ht halign hw p hy)
end RowMergeend LowSpaceSubsetSum
end OAI123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182import OAI.Combinatorics.LowSpaceSubsetSum.Streams.MergeOrdering
namespace OAI
/-!# The executable tournament merge as a finite reader
Only the tournament and its row cursors are stored. The complete output listis a proof view, defined by the remaining-occurrence potential. The readerlaw connects this actual merge to the stopped joins and bounded dictionaries.-/
namespace LowSpaceSubsetSumnamespace MergedReader
universe u v
variable {α : Type u} {σ : Type v} {d : ℕ}
structure State (key : α → ℤ) (view : σ → List α) (d : ℕ) where tree : Tournament.Tree (RowMerge.Front d α σ) d valid : Tournament.Valid (fun x => key x.value) tree aligned : RowMerge.Aligned tree sorted : RowMerge.RowsSorted key view tree
theorem advance_sorted (key : α → ℤ) (read : σ → Option (α × σ)) (view : σ → List α) (hread : RowMerge.IsReader read view) (s : State key view d) {a : α} {t : Tournament.Tree (RowMerge.Front d α σ) d} (ha : RowMerge.advance key read s.tree = some (a, t)) : RowMerge.RowsSorted key view t := by cases hw : Tournament.winner s.tree with | none => simp [RowMerge.advance, hw] at ha | some x => have heq : (x.value, Tournament.replace (fun y => key y.value) s.tree x.row (RowMerge.front read x.row x.after)) = (a, t) := by simpa [RowMerge.advance, hw] using ha rw [← (Prod.mk.inj heq).2] exact RowMerge.replacement_rowsSorted key read view hread s.tree s.valid s.aligned s.sorted hw
theorem advance_consumes_one (key : α → ℤ) (read : σ → Option (α × σ)) (view : σ → List α) (hread : RowMerge.IsReader read view) (s : State key view d) {a : α} {t : Tournament.Tree (RowMerge.Front d α σ) d} (ha : RowMerge.advance key read s.tree = some (a, t)) : RowMerge.potential view t + 1 = RowMerge.potential view s.tree := by cases hw : Tournament.winner s.tree with | none => simp [RowMerge.advance, hw] at ha | some x => have heq : (x.value, Tournament.replace (fun y => key y.value) s.tree x.row (RowMerge.front read x.row x.after)) = (a, t) := by simpa [RowMerge.advance, hw] using ha rw [← (Prod.mk.inj heq).2] exact RowMerge.replacement_consumes_one key read view hread s.tree s.valid s.aligned hw
def next (key : α → ℤ) (read : σ → Option (α × σ)) (view : σ → List α) (hread : RowMerge.IsReader read view) (s : State key view d) : Option (α × State key view d) := match ha : RowMerge.advance key read s.tree with | none => none | some (a, t) => some (a, ⟨t, RowMerge.advance_valid key read s.tree s.valid ha, RowMerge.advance_aligned key read s.tree s.aligned ha, advance_sorted key read view hread s ha⟩)
/-- The output view is never a field of the executable state. -/def output (key : α → ℤ) (read : σ → Option (α × σ)) (view : σ → List α) (s : State key view d) : List α := RowMerge.trace key read (RowMerge.potential view s.tree) s.tree
theorem next_none (key : α → ℤ) (read : σ → Option (α × σ)) (view : σ → List α) (hread : RowMerge.IsReader read view) (s : State key view d) (ha : RowMerge.advance key read s.tree = none) : next key read view hread s = none := by unfold next split · rfl · rename_i a t ht rw [ha] at ht cases ht
theorem next_some (key : α → ℤ) (read : σ → Option (α × σ)) (view : σ → List α) (hread : RowMerge.IsReader read view) (s : State key view d) {a : α} {t : Tournament.Tree (RowMerge.Front d α σ) d} (ha : RowMerge.advance key read s.tree = some (a, t)) : next key read view hread s = some (a, ⟨t, RowMerge.advance_valid key read s.tree s.valid ha, RowMerge.advance_aligned key read s.tree s.aligned ha, advance_sorted key read view hread s ha⟩) := by unfold next split · rename_i hn rw [ha] at hn cases hn · rename_i b t' ht have heq : (a, t) = (b, t') := Option.some.inj (ha.symm.trans ht) obtain ⟨rfl, rfl⟩ := Prod.mk.inj heq rfl
theorem reader (key : α → ℤ) (read : σ → Option (α × σ)) (view : σ → List α) (hread : RowMerge.IsReader read view) : RowMerge.IsReader (next (d := d) key read view hread) (output key read view) := by intro s cases ha : RowMerge.advance key read s.tree with | none => rw [next_none key read view hread s ha] unfold output cases hp : RowMerge.potential view s.tree with | zero => rfl | succ k => simp only [RowMerge.trace, ha] | some z => obtain ⟨a, t⟩ := z rw [next_some key read view hread s ha] have hdec := advance_consumes_one key read view hread s ha simp only [output, ← hdec, RowMerge.trace, ha]
theorem output_bag (key : α → ℤ) (read : σ → Option (α × σ)) (view : σ → List α) (hread : RowMerge.IsReader read view) (s : State key view d) : (output key read view s : Multiset α) = RowMerge.bag view s.tree := RowMerge.trace_complete key read view hread _ s.tree s.valid s.aligned le_rfl
theorem output_length (key : α → ℤ) (read : σ → Option (α × σ)) (view : σ → List α) (hread : RowMerge.IsReader read view) (s : State key view d) : (output key read view s).length = RowMerge.potential view s.tree := by have h := congrArg Multiset.card (output_bag key read view hread s) simpa only [Multiset.coe_card, RowMerge.bag_card] using h
theorem output_sorted (key : α → ℤ) (read : σ → Option (α × σ)) (view : σ → List α) (hread : RowMerge.IsReader read view) (s : State key view d) : (output key read view s).Pairwise (fun x y => key x ≤ key y) := RowMerge.trace_sorted key read view hread _ s.tree s.valid s.aligned s.sorted
def start (key : α → ℤ) (read : σ → Option (α × σ)) (view : σ → List α) (hread : RowMerge.IsReader read view) (rows : RowMerge.Path d → σ) (hsort : ∀ p, (view (rows p)).Pairwise (fun x y => key x ≤ key y)) : State key view d := ⟨RowMerge.start key read rows, RowMerge.start_valid key read rows, RowMerge.start_aligned key read rows, fun p => by rw [RowMerge.start_remaining key read view hread rows p] exact hsort p⟩
theorem start_output_bag (key : α → ℤ) (read : σ → Option (α × σ)) (view : σ → List α) (hread : RowMerge.IsReader read view) (rows : RowMerge.Path d → σ) (hsort : ∀ p, (view (rows p)).Pairwise (fun x y => key x ≤ key y)) : (output key read view (start key read view hread rows hsort) : Multiset α) = ∑ p : RowMerge.Path d, (view (rows p) : Multiset α) := by rw [output_bag key read view hread] simp only [RowMerge.bag, start, RowMerge.start_remaining key read view hread]
theorem start_output_length (key : α → ℤ) (read : σ → Option (α × σ)) (view : σ → List α) (hread : RowMerge.IsReader read view) (rows : RowMerge.Path d → σ) (hsort : ∀ p, (view (rows p)).Pairwise (fun x y => key x ≤ key y)) : (output key read view (start key read view hread rows hsort)).length = ∑ p : RowMerge.Path d, (view (rows p)).length := by rw [output_length key read view hread] simp only [RowMerge.potential, start, RowMerge.start_remaining key read view hread]
theorem nodes_exact (key : α → ℤ) (view : σ → List α) (s : State key view d) : Tournament.nodes s.tree + 1 = 2 ^ (d + 1) := Tournament.nodes_exact s.tree
def advanceComparisons (key : α → ℤ) (view : σ → List α) (s : State key view d) : ℕ := match Tournament.winner s.tree with | none => 0 | some x => Tournament.replaceComparisons s.tree x.row
theorem advanceComparisons_le (key : α → ℤ) (view : σ → List α) (s : State key view d) : advanceComparisons key view s ≤ d := by unfold advanceComparisons split · exact Nat.zero_le d · exact (Tournament.replaceComparisons_eq _ _).le
end MergedReaderend LowSpaceSubsetSum
end OAI123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104import OAI.Combinatorics.LowSpaceSubsetSum.Streams.CyclicCursorimport OAI.Combinatorics.LowSpaceSubsetSum.Streams.BinaryPivot
namespace OAI
/-!# Executable modular row initialization
Binary search finds the first direct pivot and the position after the lastcomplementary pivot. The resulting constant-state cyclic cursor producesthe corresponding sorted modular row exactly. The cutoff search uses asupplied number of steps; the theorem requires only that the array lengthbe smaller than `2^k`. Equal residues stay separate array occurrences.-/
namespace LowSpaceSubsetSumnamespace ModularCursor
open scoped Fin.NatCast
variable {n : ℕ} [NeZero n] {α : Type*}
def forwardStart (a : Fin n → α) (residue : α → ℤ) (P r : ℤ) (k : ℕ) : CyclicCursor.State n := ⟨Fin.ofNat n (BinaryPivot.search (fun i => decide (residue (a i) < P - r)) k).lo, n, false⟩
def reverseStart (a : Fin n → α) (residue : α → ℤ) (K : ℤ) (k : ℕ) : CyclicCursor.State n := ⟨Fin.ofNat n (BinaryPivot.search (fun i => decide (residue (a i) ≤ K)) k).lo - 1, n, true⟩
theorem forward_trace (a : Fin n → α) (residue : α → ℤ) (P r : ℤ) (k : ℕ) (hk : n < 2 ^ k) (hsort : Monotone (fun i => residue (a i))) : CyclicCursor.trace a n (forwardStart a residue P r k) = ModularRows.direct P r residue (List.ofFn a) := by have hprefix : BinaryPivot.PrefixPredicate (fun i : Fin n => decide (residue (a i) < P - r)) := by intro i j hij hj apply decide_eq_true exact lt_of_le_of_lt (hsort hij) (of_decide_eq_true hj) have hsplit := BinaryPivot.search_split a (fun x => decide (residue x < P - r)) hprefix k hk let c := BinaryPivot.search (fun i : Fin n => decide (residue (a i) < P - r)) k let lo := (List.ofFn a).take c.lo let hi := (List.ofFn a).drop c.lo have hc : c.lo ≤ n := c.ordered.trans c.bounded have hlist : List.ofFn a = lo ++ hi := (List.take_append_drop c.lo _).symm apply CyclicCursor.forward_trace_eq_direct a P r residue lo hi hlist (Fin.ofNat n c.lo) · simp [lo, hc] · simpa only [decide_eq_true_eq] using hsplit.1 · simpa only [decide_eq_false_iff_not, not_lt] using hsplit.2
theorem reverse_trace (a : Fin n → α) (residue : α → ℤ) (K : ℤ) (k : ℕ) (hk : n < 2 ^ k) (hsort : Monotone (fun i => residue (a i))) : CyclicCursor.trace a n (reverseStart a residue K k) = ModularRows.complementary K residue (List.ofFn a) := by have hprefix : BinaryPivot.PrefixPredicate (fun i : Fin n => decide (residue (a i) ≤ K)) := by intro i j hij hj apply decide_eq_true exact (hsort hij).trans (of_decide_eq_true hj) have hsplit := BinaryPivot.search_split a (fun x => decide (residue x ≤ K)) hprefix k hk let c := BinaryPivot.search (fun i : Fin n => decide (residue (a i) ≤ K)) k let lo := (List.ofFn a).take c.lo let hi := (List.ofFn a).drop c.lo have hc : c.lo ≤ n := c.ordered.trans c.bounded have hlist : List.ofFn a = lo ++ hi := (List.take_append_drop c.lo _).symm apply CyclicCursor.reverse_trace_eq_complementary a K residue lo hi hlist (Fin.ofNat n c.lo) · simp [lo, hc] · simpa only [decide_eq_true_eq] using hsplit.1 · simpa only [decide_eq_false_iff_not, not_le] using hsplit.2
theorem forward_sorted (a : Fin n → α) (residue : α → ℤ) (P r : ℤ) (k : ℕ) (hk : n < 2 ^ k) (hsort : Monotone (fun i => residue (a i))) (hr : 0 ≤ r) (hrP : r < P) (hbound : ∀ i, 0 ≤ residue (a i) ∧ residue (a i) < P) : (CyclicCursor.trace a n (forwardStart a residue P r k)).Pairwise (fun x y => (r + residue x) % P ≤ (r + residue y) % P) := by rw [forward_trace a residue P r k hk hsort] apply ModularRows.direct_sorted hr hrP · intro x hx obtain ⟨i, rfl⟩ := List.mem_ofFn.mp hx exact hbound i · exact List.pairwise_ofFn.mpr (fun _ _ h => hsort h.le)
theorem reverse_sorted (a : Fin n → α) (residue : α → ℤ) (P K : ℤ) (k : ℕ) (hk : n < 2 ^ k) (hsort : Monotone (fun i => residue (a i))) (hK : 0 ≤ K) (hKP : K < P) (hbound : ∀ i, 0 ≤ residue (a i) ∧ residue (a i) < P) : (CyclicCursor.trace a n (reverseStart a residue K k)).Pairwise (fun x y => (K - residue x) % P ≤ (K - residue y) % P) := by rw [reverse_trace a residue K k hk hsort] apply ModularRows.complementary_sorted hK hKP · intro x hx obtain ⟨i, rfl⟩ := List.mem_ofFn.mp hx exact hbound i · exact List.pairwise_ofFn.mpr (fun _ _ h => hsort h.le)
end ModularCursorend LowSpaceSubsetSum
end OAI1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162import Mathlib.Data.Int.ModEqimport Mathlib.Tactic
namespace OAI
/-!# Nested filters and enumeration of parent residue classes
The congruence and finite-loop facts used by both trials. No coprimality ofthe low modulus and the additional prime is required.-/
namespace LowSpaceSubsetSum
/-- A passing parent and first child force the second child's low filter. -/theorem nested_second_child_filter {p p0 x1 x2 w rho : ℤ} (hdiv : p ∣ p0) (hparent : x1 + x2 ≡ w [ZMOD p0]) (hchild : x1 ≡ rho [ZMOD p]) : x2 ≡ w - rho [ZMOD p] := by have h := (hparent.of_dvd hdiv).sub hchild convert h using 1 ring
/-- Every lifted class has the prescribed low residue. -/theorem lift_low_residue {p rho z : ℕ} (hrho : rho < p) : (rho + p * z) % p = rho := by simp [Nat.add_mod, Nat.mod_eq_of_lt hrho]
/-- The program's lift lies within the product modulus. -/theorem lift_lt_product {p q rho z : ℕ} (hrho : rho < p) (hz : z < q) : rho + p * z < p * q := by have hz' : z + 1 ≤ q := by omega have hp := Nat.mul_le_mul_left p hz' nlinarith
/-- All product-modulus residues with a given low base occur exactly once inthe loop over `z < q`, including when `q` and `p` have a common factor. -/theorem lift_residue_exists_unique {p q rho r : ℕ} (hp : 0 < p) (hr : r < p * q) (hbase : r % p = rho) : ∃! z : ℕ, z < q ∧ r = rho + p * z := by have hz : r / p < q := (Nat.div_lt_iff_lt_mul hp).mpr (by simpa [mul_comm] using hr) have heq : r = rho + p * (r / p) := by have h := Nat.mod_add_div r p omega refine ⟨r / p, ⟨hz, heq⟩, ?_⟩ intro z hz' have hprod : p * z = p * (r / p) := by omega exact Nat.eq_of_mul_eq_mul_left hp hprod
/-- Complementing the target gives a bijection of the product residue ring. -/theorem complementary_residue_injective {P t : ℤ} {x y : ℤ} (hx : 0 ≤ x ∧ x < P) (hy : 0 ≤ y ∧ y < P) (h : (t - x) % P = (t - y) % P) : x = y := by have hm : t - x ≡ t - y [ZMOD P] := h have hxym := hm.neg.add_left t have hxy : x % P = y % P := by change x ≡ y [ZMOD P] convert hxym using 1 <;> ring rwa [Int.emod_eq_of_lt hx.1 hx.2, Int.emod_eq_of_lt hy.1 hy.2] at hxy
end LowSpaceSubsetSum
end OAI123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137import Mathlib.Data.List.Pairwiseimport Mathlib.Data.List.Perm.Basicimport Mathlib.Data.Int.ModEqimport Mathlib.Tactic
namespace OAI
/-!# The modular pivot order of a pair-stream row
These are the two cyclic orders in `lem:streams`. The list is an analysis viewof one sorted slice: implementation can traverse the slice by its pivot andcursor, rather than allocating the reordered list. The permutation theoremspreserve occurrence multiplicity, including repeated residues.-/
namespace LowSpaceSubsetSumnamespace ModularRows
variable {α : Type*}
def direct (P r : ℤ) (residue : α → ℤ) (xs : List α) : List α := xs.filter (fun x => decide (P - r ≤ residue x)) ++ xs.filter (fun x => decide (residue x < P - r))
def complementary (K : ℤ) (residue : α → ℤ) (xs : List α) : List α := (xs.filter (fun x => decide (residue x ≤ K))).reverse ++ (xs.filter (fun x => decide (K < residue x))).reverse
theorem direct_perm (P r : ℤ) (residue : α → ℤ) (xs : List α) : (direct P r residue xs).Perm xs := by simpa only [direct, ← decide_not, not_le] using List.filter_append_perm (fun x => decide (P - r ≤ residue x)) xs
theorem complementary_perm (K : ℤ) (residue : α → ℤ) (xs : List α) : (complementary K residue xs).Perm xs := by apply ((List.reverse_perm _).append (List.reverse_perm _)).trans simpa only [← decide_not, not_le] using List.filter_append_perm (fun x => decide (residue x ≤ K)) xs
theorem direct_wrapped {P r x : ℤ} (_hr : 0 ≤ r) (hrP : r < P) (_hx : 0 ≤ x) (hxP : x < P) (hwrap : P - r ≤ x) : (r + x) % P = r + x - P := by rw [← Int.sub_emod_right (r + x) P] exact Int.emod_eq_of_lt (by omega) (by omega)
theorem direct_unwrapped {P r x : ℤ} (hr : 0 ≤ r) (hx : 0 ≤ x) (hwrap : x < P - r) : (r + x) % P = r + x := Int.emod_eq_of_lt (by omega) (by omega)
theorem complementary_low {P K x : ℤ} (_hK : 0 ≤ K) (hKP : K < P) (hx : 0 ≤ x) (hsmall : x ≤ K) : (K - x) % P = K - x := Int.emod_eq_of_lt (by omega) (by omega)
theorem complementary_high {P K x : ℤ} (hK : 0 ≤ K) (_hKP : K < P) (hxP : x < P) (hlarge : K < x) : (K - x) % P = K - x + P := by rw [← Int.add_emod_right (K - x) P] exact Int.emod_eq_of_lt (by omega) (by omega)
/-- Direct cyclic traversal is sorted by normalized pair residue. -/theorem direct_sorted {P r : ℤ} (hr : 0 ≤ r) (hrP : r < P) (residue : α → ℤ) (xs : List α) (hbound : ∀ x ∈ xs, 0 ≤ residue x ∧ residue x < P) (hsort : xs.Pairwise (fun x y => residue x ≤ residue y)) : (direct P r residue xs).Pairwise (fun x y => (r + residue x) % P ≤ (r + residue y) % P) := by apply List.pairwise_append.mpr refine ⟨?_, ?_, ?_⟩ · apply (hsort.filter (fun x => decide (P - r ≤ residue x))).imp_of_mem intro x y hx hy hxy obtain ⟨hxmem, hxwrap⟩ := List.mem_filter.mp hx obtain ⟨hymem, hywrap⟩ := List.mem_filter.mp hy have hxw : P - r ≤ residue x := of_decide_eq_true hxwrap have hyw : P - r ≤ residue y := of_decide_eq_true hywrap rw [direct_wrapped hr hrP (hbound x hxmem).1 (hbound x hxmem).2 hxw, direct_wrapped hr hrP (hbound y hymem).1 (hbound y hymem).2 hyw] omega · apply (hsort.filter (fun x => decide (residue x < P - r))).imp_of_mem intro x y hx hy hxy obtain ⟨hxmem, hxwrap⟩ := List.mem_filter.mp hx obtain ⟨hymem, hywrap⟩ := List.mem_filter.mp hy rw [direct_unwrapped hr (hbound x hxmem).1 (of_decide_eq_true hxwrap), direct_unwrapped hr (hbound y hymem).1 (of_decide_eq_true hywrap)] omega · intro x hx y hy obtain ⟨hxmem, hxwrap⟩ := List.mem_filter.mp hx obtain ⟨hymem, hywrap⟩ := List.mem_filter.mp hy rw [direct_wrapped hr hrP (hbound x hxmem).1 (hbound x hxmem).2 (of_decide_eq_true hxwrap), direct_unwrapped hr (hbound y hymem).1 (of_decide_eq_true hywrap)] have := (hbound x hxmem).2 have := (hbound y hymem).1 omega
/-- Reverse cyclic traversal is sorted by the complementary residue. -/theorem complementary_sorted {P K : ℤ} (hK : 0 ≤ K) (hKP : K < P) (residue : α → ℤ) (xs : List α) (hbound : ∀ x ∈ xs, 0 ≤ residue x ∧ residue x < P) (hsort : xs.Pairwise (fun x y => residue x ≤ residue y)) : (complementary K residue xs).Pairwise (fun x y => (K - residue x) % P ≤ (K - residue y) % P) := by apply List.pairwise_append.mpr refine ⟨?_, ?_, ?_⟩ · apply List.pairwise_reverse.mpr apply (hsort.filter (fun x => decide (residue x ≤ K))).imp_of_mem intro x y hx hy hxy obtain ⟨hxmem, hxsmall⟩ := List.mem_filter.mp hx obtain ⟨hymem, hysmall⟩ := List.mem_filter.mp hy rw [complementary_low hK hKP (hbound x hxmem).1 (of_decide_eq_true hxsmall), complementary_low hK hKP (hbound y hymem).1 (of_decide_eq_true hysmall)] omega · apply List.pairwise_reverse.mpr apply (hsort.filter (fun x => decide (K < residue x))).imp_of_mem intro x y hx hy hxy obtain ⟨hxmem, hxlarge⟩ := List.mem_filter.mp hx obtain ⟨hymem, hylarge⟩ := List.mem_filter.mp hy rw [complementary_high hK hKP (hbound x hxmem).2 (of_decide_eq_true hxlarge), complementary_high hK hKP (hbound y hymem).2 (of_decide_eq_true hylarge)] omega · intro x hx y hy obtain ⟨hxmem, hxsmall⟩ := List.mem_filter.mp (List.mem_reverse.mp hx) obtain ⟨hymem, hylarge⟩ := List.mem_filter.mp (List.mem_reverse.mp hy) rw [complementary_low hK hKP (hbound x hxmem).1 (of_decide_eq_true hxsmall), complementary_high hK hKP (hbound y hymem).2 (of_decide_eq_true hylarge)] have := (hbound x hxmem).1 have := (hbound y hymem).2 omega
/-- Filtering a row by the small modulus preserves its residue ordering. -/theorem filtered_sorted (p c : ℤ) (weight residue : α → ℤ) (xs : List α) (hsort : xs.Pairwise (fun x y => residue x ≤ residue y)) : (xs.filter (fun x => decide (weight x % p = c % p))).Pairwise (fun x y => residue x ≤ residue y) := hsort.filter _
end ModularRowsend LowSpaceSubsetSum
end OAI123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101import OAI.Combinatorics.LowSpaceSubsetSum.Streams.MergedReaderimport Mathlib.Algebra.BigOperators.Fin
namespace OAI
/-!# Binary indexing and empty padding for the row tournament
Binary paths index a power-of-two set of leaves. Array indices occupy theinitial segment and all other leaves are empty. The reindexing proof countsexact occurrences; its finite sums and lists are analysis views only.-/
namespace LowSpaceSubsetSumnamespace PaddedRows
variable {α σ : Type*}
def index (d : ℕ) : RowMerge.Path d ≃ Fin (2 ^ d) := (Equiv.piCongrRight (fun _ : Fin d => finTwoEquiv.symm)).trans finFunctionFinEquiv
def next (read : σ → Option (α × σ)) : Option σ → Option (α × Option σ) | none => none | some s => (read s).map (fun z => (z.1, some z.2))
def view (output : σ → List α) : Option σ → List α | none => [] | some s => output s
theorem reader (read : σ → Option (α × σ)) (output : σ → List α) (hread : RowMerge.IsReader read output) : RowMerge.IsReader (next read) (view output) := by intro s cases s with | none => rfl | some s => have h := hread s cases hr : read s with | none => simpa only [next, hr, Option.map_none, view] using h | some z => simpa only [next, hr, Option.map_some, view] using h
def rows (xs : Array σ) (d : ℕ) (p : RowMerge.Path d) : Option σ := if h : (index d p).val < xs.size then some xs[(index d p).val] else none
theorem rows_sorted (xs : Array σ) (d : ℕ) (output : σ → List α) (key : α → ℤ) (hs : ∀ s ∈ xs.toList, (output s).Pairwise (fun x y => key x ≤ key y)) (p : RowMerge.Path d) : (view output (rows xs d p)).Pairwise (fun x y => key x ≤ key y) := by unfold rows split_ifs with h · apply hs exact List.mem_iff_getElem.mpr ⟨(index d p).val, by simpa only [Array.length_toList] using h, by simp⟩ · simp [view]
theorem sum_padding {M : Type*} [AddCommMonoid M] (n m : ℕ) (hnm : n ≤ m) (f : Fin n → M) : (∑ i : Fin m, if h : i.val < n then f ⟨i.val, h⟩ else 0) = ∑ i : Fin n, f i := by induction m with | zero => have hn : n = 0 := by omega subst n simp | succ m ih => by_cases hn : n ≤ m · rw [Fin.sum_univ_castSucc] have hlast : ¬ m < n := by omega simp only [Fin.val_castSucc, Fin.val_last, dite_eq_right hlast, add_zero] exact ih hn · have hn : n = m + 1 := by omega subst n apply Finset.sum_congr rfl intro i _ exact dite_eq_left i.isLt
theorem sum_rows {M : Type*} [AddCommMonoid M] (xs : Array σ) (d : ℕ) (hd : xs.size ≤ 2 ^ d) (f : σ → M) : (∑ p : RowMerge.Path d, match rows xs d p with | none => 0 | some s => f s) = ∑ i : Fin xs.size, f xs[i.val] := by calc _ = ∑ i : Fin (2 ^ d), if h : i.val < xs.size then f xs[i.val] else 0 := by apply Fintype.sum_equiv (index d) intro p dsimp only [rows] split_ifs <;> rfl _ = _ := sum_padding xs.size (2 ^ d) hd (fun i => f xs[i.val])
theorem row_bag (xs : Array σ) (d : ℕ) (hd : xs.size ≤ 2 ^ d) (output : σ → List α) : (∑ p : RowMerge.Path d, (view output (rows xs d p) : Multiset α)) = ∑ i : Fin xs.size, (output xs[i.val] : Multiset α) := by calc _ = ∑ p : RowMerge.Path d, match rows xs d p with | none => 0 | some s => (output s : Multiset α) := by apply Finset.sum_congr rfl intro p _ cases rows xs d p <;> rfl _ = _ := sum_rows xs d hd (fun s => (output s : Multiset α))
end PaddedRowsend LowSpaceSubsetSum
end OAI12345678910111213141516171819202122232425262728293031323334353637import OAI.Combinatorics.LowSpaceSubsetSum.Streams.SliceCursor
namespace OAI
/-! # Attach one fixed first-array occurrence to a shared-array row reader -/
namespace LowSpaceSubsetSumnamespace PairCursor
variable {α β : Type*}
structure State (α : Type*) (n : ℕ) where left : α cursor : SliceCursor.State n
def next (xs : Array β) (s : State α xs.size) : Option ((α × β) × State α xs.size) := (SliceCursor.next xs s.cursor).map (fun z => ((s.left, z.1), ⟨s.left, z.2⟩))
def output (xs : Array β) (s : State α xs.size) : List (α × β) := (SliceCursor.output xs s.cursor).map (fun y => (s.left, y))
theorem reader (xs : Array β) : RowMerge.IsReader (next (α := α) xs) (output xs) := by intro s have hr := SliceCursor.reader xs s.cursor cases h : SliceCursor.next xs s.cursor with | none => simp only [h] at hr simp only [next, h, Option.map_none, output, hr, List.map_nil] | some z => obtain ⟨y, c⟩ := z simp only [h] at hr simp only [next, h, Option.map_some, output, hr, List.map_cons]
end PairCursorend LowSpaceSubsetSum
end OAI123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144import OAI.Combinatorics.LowSpaceSubsetSum.Representation.RepresentationParentCompleteimport OAI.Combinatorics.LowSpaceSubsetSum.Streams.DictionaryCompletedimport OAI.Combinatorics.LowSpaceSubsetSum.Separators.SeparatorEncodedCheck
namespace OAI
/-! # Actual depth-first right-parent prefix recomputation -/
namespace LowSpaceSubsetSum
namespace MaskRestriction
variable {n : ℕ}
def force (P : MaskRestriction n) (i : Fin n) (side : Bool) : MaskRestriction n := if side then { P with ones := Insert.insert i P.ones } else { P with zeros := Insert.insert i P.zeros }
def follow (P : MaskRestriction n) (order : List (Fin n)) (S : Finset (Fin n)) : MaskRestriction n := order.foldl (fun P i => P.force i (decide (i ∈ S))) P
theorem force_compatible (P : MaskRestriction n) (domain S : Finset (Fin n)) (h : P.Compatible domain S) (i : Fin n) : (P.force i (decide (i ∈ S))).Compatible domain S := by by_cases hi : i ∈ S · simp only [hi, decide_true, force, ↓reduceIte, Compatible] refine ⟨?_, h.2⟩ intro j hj obtain ⟨hj, hjD⟩ := Finset.mem_inter.mp hj rcases Finset.mem_insert.mp hj with rfl | hj · exact hi · exact h.1 (Finset.mem_inter.mpr ⟨hj, hjD⟩) · simp only [hi, decide_false, force, Bool.false_eq_true, ↓reduceIte, Compatible] refine ⟨h.1, Finset.disjoint_left.mpr ?_⟩ intro j hj hjS rcases Finset.mem_insert.mp hj with rfl | hj · exact hi hjS · exact Finset.disjoint_left.mp h.2 hj hjS
end MaskRestriction
namespace RepresentationParentData
variable {n : ℕ} (D : RepresentationParentData n)
/-- Each task regenerates its restricted leaves and streams. An overflowingfull prefix is dropped; a completed array is passed to the actual checker.The first YES returns immediately. -/def searchRight (B : ℕ) (check : Array (Entry (Fin n)) → Bool) : List (Fin n) → MaskRestriction n → Bool | order, P => let task := { D with maskRestriction := P } let out := (task.collect B).state.user if out.keys.overflow then match order with | [] => false | i :: rest => if searchRight B check rest (P.force i false) then true else searchRight B check rest (P.force i true) else check out.records
theorem searchRight_sound (B : ℕ) (check : Array (Entry (Fin n)) → Bool) (Q : Prop) (hcheck : ∀ P, check ({ D with maskRestriction := P }.entries B) = true → Q) (order : List (Fin n)) (P : MaskRestriction n) (hyes : D.searchRight B check order P = true) : Q := by induction order generalizing P with | nil => simp only [searchRight] at hyes split at hyes · contradiction · exact hcheck P hyes | cons i order ih => simp only [searchRight] at hyes split at hyes · split at hyes · rename_i hl exact ih _ hl · exact ih _ hyes · exact hcheck P hyes
/-- A fitting task at the end of a designated mask path suffices. Earliercompletion reaches the checker; earlier YES also returns immediately. -/theorem searchRight_complete (B : ℕ) (check : Array (Entry (Fin n)) → Bool) (domain S : Finset (Fin n)) (hfind : ∀ P, P.Compatible domain S → ({ D with maskRestriction := P }.collect B).state.user.keys.overflow = false → check ({ D with maskRestriction := P }.entries B) = true) (order : List (Fin n)) (P : MaskRestriction n) (hP : P.Compatible domain S) (hfull : ({ D with maskRestriction := P.follow order S }.collect B).state.user.keys.overflow = false) : D.searchRight B check order P = true := by induction order generalizing P with | nil => have hc : ({ D with maskRestriction := P }.collect B).state.user.keys.overflow = false := hfull simpa only [searchRight, hc, Bool.false_eq_true, ↓reduceIte, entries] using hfind P hP hc | cons i order ih => by_cases ho : ({ D with maskRestriction := P }.collect B).state.user.keys.overflow = true · have hnext := ih (P.force i (decide (i ∈ S))) (P.force_compatible domain S hP i) hfull cases hb : decide (i ∈ S) with | false => simp only [hb] at hnext simp only [searchRight, ho, ↓reduceIte, hnext] | true => simp only [hb] at hnext simp only [searchRight, ho, ↓reduceIte] split · rfl · exact hnext · have hc : ({ D with maskRestriction := P }.collect B).state.user.keys.overflow = false := Bool.eq_false_iff.mpr ho simpa only [searchRight, hc, Bool.false_eq_true, ↓reduceIte, entries] using hfind P hP hc/-- No prefix task can introduce a false YES. This applies to every familyoutcome and every overflow pattern, rather than just the surviving bucket. -/theorem searchRight_subset_sum_sound {g : ℕ} (B : ℕ) (C : TopCoordinates n g) (families : Fin 4 → Array (Finset (Fin g))) (left : Array (Entry (Fin n))) (order : List (Fin n)) (P : MaskRestriction n) (leftDomain : Finset (Fin n)) (htop : RepresentationUniverse.topDomain D.leaves = C.domain) (htl : Disjoint (RepresentationUniverse.topDomain D.leaves) (RepresentationUniverse.mixerDomain D.leaves)) (htb : Disjoint (RepresentationUniverse.topDomain D.leaves) (RepresentationUniverse.backgroundDomain D.leaves)) (hlb : Disjoint (RepresentationUniverse.mixerDomain D.leaves) (RepresentationUniverse.backgroundDomain D.leaves)) (hshared : leftDomain ∩ RepresentationUniverse.parentDomain D.leaves ⊆ C.domain) (hleft : ∀ e ∈ left.toList, Represents D.weights leftDomain C.domain e) (hsize : left.size + (D.capacity + 1) ≤ 2 ^ n) (hyes : D.searchRight B (fun right => (C.check families ((D.input.target : ℤ) - weight (fun i => (D.input.values i : ℤ)) D.signs) left.toList right.toList).accepted) order P = true) : Solvable D.input := by apply D.searchRight_sound B _ (Solvable D.input) ?_ order P hyes intro P hp let task := { D with maskRestriction := P } apply C.subset_sum_sound D.input D.signs families left.toList (task.entries B).toList (leftDomain := leftDomain) (rightDomain := RepresentationUniverse.parentDomain D.leaves) (by simp only [Array.length_toList] exact (Nat.add_le_add_left (task.storage B).1 _).trans hsize) hshared hleft ?_ hp intro e he rw [← htop] exact task.entry_represents B htl htb hlb e he
end RepresentationParentDataend LowSpaceSubsetSum
end OAI123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210import Mathlib.Data.Finset.Cardimport Mathlib.Data.Finset.Filterimport Mathlib.Tactic
namespace OAI
/-!# Deterministic accounting for right-prefix refinement
The tree depends on distinct entries for overflow, while raw tuple occurrencesare charged separately. The finite sets in this mathematical accounting areambient analysis sets, not arrays that the implementation is allowed to store.The resulting combinatorial bounds give the accounting in `lem:prefix`.-/
namespace LowSpaceSubsetSum
variable {α : Type*}
/-- Labels of the successive mask bits, in the fixed processing order. -/abbrev MaskBits (α : Type*) := ℕ → α → Bool
def bitPart (bits : MaskBits α) (depth : ℕ) (side : Bool) (U : Finset α) : Finset α := U.filter fun x => bits depth x = side
theorem bitPart_card_add (bits : MaskBits α) (depth : ℕ) (U : Finset α) : (bitPart bits depth false U).card + (bitPart bits depth true U).card = U.card := by have h := Finset.card_filter_add_card_filter_not (s := U) (p := fun x => bits depth x = false) simpa [bitPart, Bool.not_eq_false] using h
/-- Overflow count includes an overflowing full-prefix node that is dropped. -/def overflowNodes (C : ℕ) (bits : MaskBits α) (depth : ℕ) : ℕ → Finset α → ℕ | 0, U => if C < U.card then 1 else 0 | fuel + 1, U => if C < U.card then 1 + overflowNodes C bits (depth + 1) fuel (bitPart bits depth false U) + overflowNodes C bits (depth + 1) fuel (bitPart bits depth true U) else 0
/-- The task count includes empty completed tasks and dropped full prefixes. -/def prefixTasks (C : ℕ) (bits : MaskBits α) (depth : ℕ) : ℕ → Finset α → ℕ | 0, _ => 1 | fuel + 1, U => if C < U.card then 1 + prefixTasks C bits (depth + 1) fuel (bitPart bits depth false U) + prefixTasks C bits (depth + 1) fuel (bitPart bits depth true U) else 1
/-- Sum of the lengths of all completed right dictionaries. -/def completedEntries (C : ℕ) (bits : MaskBits α) (depth : ℕ) : ℕ → Finset α → ℕ | 0, U => if C < U.card then 0 else U.card | fuel + 1, U => if C < U.card then completedEntries C bits (depth + 1) fuel (bitPart bits depth false U) + completedEntries C bits (depth + 1) fuel (bitPart bits depth true U) else U.card
/-- The sum of ambient entry counts over all task nodes, for charging by depth. -/def potentialVisits (C : ℕ) (bits : MaskBits α) (depth : ℕ) : ℕ → Finset α → ℕ | 0, U => U.card | fuel + 1, U => if C < U.card then U.card + potentialVisits C bits (depth + 1) fuel (bitPart bits depth false U) + potentialVisits C bits (depth + 1) fuel (bitPart bits depth true U) else U.card
/-- Raw occurrences are a separate type and retain all multiplicities. Taskbranching is decided by `U`, the distinct entries, rather than by `T`. -/def rawVisits {β : Type*} (C : ℕ) (bits : MaskBits α) (rawBits : MaskBits β) (depth : ℕ) : ℕ → Finset α → Finset β → ℕ | 0, _, T => T.card | fuel + 1, U, T => if C < U.card then T.card + rawVisits C bits rawBits (depth + 1) fuel (bitPart bits depth false U) (bitPart rawBits depth false T) + rawVisits C bits rawBits (depth + 1) fuel (bitPart bits depth true U) (bitPart rawBits depth true T) else T.card
/-- The bucket reached by following a designated entry's complete prefix. -/def fullPrefixBucket (bits : MaskBits α) (depth : ℕ) (e : α) : ℕ → Finset α → Finset α | 0, U => U | fuel + 1, U => fullPrefixBucket bits (depth + 1) e fuel (bitPart bits depth (bits depth e) U)
/-- The actual refinement path stops at the first dictionary that fits. -/def reachesCompleted (C : ℕ) (bits : MaskBits α) (depth : ℕ) (e : α) : ℕ → Finset α → Prop | 0, U => U.card ≤ C | fuel + 1, U => U.card ≤ C ∨ reachesCompleted C bits (depth + 1) e fuel (bitPart bits depth (bits depth e) U)
theorem mem_fullPrefixBucket (bits : MaskBits α) (depth fuel : ℕ) {e : α} {U : Finset α} (he : e ∈ U) : e ∈ fullPrefixBucket bits depth e fuel U := by induction fuel generalizing depth U with | zero => exact he | succ fuel ih => apply ih exact Finset.mem_filter.mpr ⟨he, rfl⟩
/-- A fitting full-prefix bucket ensures that the designated path completes,even if larger ancestors overflow. -/theorem reachesCompleted_of_fullPrefix_fits (C : ℕ) (bits : MaskBits α) (depth fuel : ℕ) (e : α) (U : Finset α) (hfit : (fullPrefixBucket bits depth e fuel U).card ≤ C) : reachesCompleted C bits depth e fuel U := by induction fuel generalizing depth U with | zero => exact hfit | succ fuel ih => right exact ih (depth + 1) (bitPart bits depth (bits depth e) U) hfit
theorem overflowNodes_capacity_bound (C : ℕ) (bits : MaskBits α) (depth fuel : ℕ) (U : Finset α) : C * overflowNodes C bits depth fuel U ≤ (fuel + 1) * U.card := by induction fuel generalizing depth U with | zero => simp only [overflowNodes] split_ifs with h <;> simp_all omega | succ fuel ih => simp only [overflowNodes] split_ifs with h · have h0 := ih (depth + 1) (bitPart bits depth false U) have h1 := ih (depth + 1) (bitPart bits depth true U) have hc := bitPart_card_add bits depth U nlinarith · simp
theorem prefixTasks_le_overflowNodes (C : ℕ) (bits : MaskBits α) (depth fuel : ℕ) (U : Finset α) : prefixTasks C bits depth fuel U ≤ 1 + 2 * overflowNodes C bits depth fuel U := by induction fuel generalizing depth U with | zero => simp [prefixTasks, overflowNodes] | succ fuel ih => simp only [prefixTasks, overflowNodes] split_ifs with h · have h0 := ih (depth + 1) (bitPart bits depth false U) have h1 := ih (depth + 1) (bitPart bits depth true U) omega · simp
/-- Division-free version of the right task-start bound. -/theorem prefixTasks_capacity_bound (C : ℕ) (bits : MaskBits α) (depth fuel : ℕ) (U : Finset α) : C * prefixTasks C bits depth fuel U ≤ C + 2 * (fuel + 1) * U.card := by have ht := prefixTasks_le_overflowNodes C bits depth fuel U have ho := overflowNodes_capacity_bound C bits depth fuel U nlinarith
theorem completedEntries_le_card (C : ℕ) (bits : MaskBits α) (depth fuel : ℕ) (U : Finset α) : completedEntries C bits depth fuel U ≤ U.card := by induction fuel generalizing depth U with | zero => simp only [completedEntries]; split_ifs <;> omega | succ fuel ih => simp only [completedEntries] split_ifs with h · have h0 := ih (depth + 1) (bitPart bits depth false U) have h1 := ih (depth + 1) (bitPart bits depth true U) have hc := bitPart_card_add bits depth U omega · rfl
/-- Every occurrence has exactly one prefix at a fixed depth. The totalpotential work is charged by depth, even for occurrences later rejected. -/theorem potentialVisits_le_depth_mul_card (C : ℕ) (bits : MaskBits α) (depth fuel : ℕ) (U : Finset α) : potentialVisits C bits depth fuel U ≤ (fuel + 1) * U.card := by induction fuel generalizing depth U with | zero => simp [potentialVisits] | succ fuel ih => simp only [potentialVisits] split_ifs with h · have h0 := ih (depth + 1) (bitPart bits depth false U) have h1 := ih (depth + 1) (bitPart bits depth true U) have hc := bitPart_card_add bits depth U nlinarith · nlinarith
/-- The occurrence bound is independent of deduplication and validity tests. -/theorem rawVisits_le_depth_mul_card {β : Type*} (C : ℕ) (bits : MaskBits α) (rawBits : MaskBits β) (depth fuel : ℕ) (U : Finset α) (T : Finset β) : rawVisits C bits rawBits depth fuel U T ≤ (fuel + 1) * T.card := by induction fuel generalizing depth U T with | zero => simp [rawVisits] | succ fuel ih => simp only [rawVisits] split_ifs with h · have h0 := ih (depth + 1) (bitPart bits depth false U) (bitPart rawBits depth false T) have h1 := ih (depth + 1) (bitPart bits depth true U) (bitPart rawBits depth true T) have hc := bitPart_card_add rawBits depth T nlinarith · nlinarith
/-- Even charging the left array at every task bounds all actual final-checkinputs. This includes every reuse of the same retained left array. -/theorem checkInputs_le (C L : ℕ) (hL : L ≤ C) (bits : MaskBits α) (depth fuel : ℕ) (U : Finset α) : completedEntries C bits depth fuel U + L * prefixTasks C bits depth fuel U ≤ L + (2 * fuel + 3) * U.card := by have ht := prefixTasks_le_overflowNodes C bits depth fuel U have ho := overflowNodes_capacity_bound C bits depth fuel U have he := completedEntries_le_card C bits depth fuel U have hscale := Nat.mul_le_mul_left (overflowNodes C bits depth fuel U) hL nlinarith
end LowSpaceSubsetSum
end OAI123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990import OAI.Combinatorics.LowSpaceSubsetSum.Representation.RepresentationBucketProgram
namespace OAI
/-! # A family-independent list of the completed prefix checks
These lists describe the hypothetical full traversal for analysis. Theexecutable search regenerates one task at a time and stops at its first YES.-/
namespace LowSpaceSubsetSum.RepresentationParentData
variable {n : ℕ} (D : RepresentationParentData n)
def completedArrays (B : ℕ) : List (Fin n) → MaskRestriction n → List (Array (Entry (Fin n))) | order, P => let task := { D with maskRestriction := P } let out := (task.collect B).state.user if out.keys.overflow then match order with | [] => [] | i :: rest => completedArrays B rest (P.force i false) ++ completedArrays B rest (P.force i true) else [out.records]
theorem searchRight_eq_any (B : ℕ) (check : Array (Entry (Fin n)) → Bool) (order : List (Fin n)) (P : MaskRestriction n) : D.searchRight B check order P = (D.completedArrays B order P).any check := by induction order generalizing P with | nil => simp only [searchRight, completedArrays] split <;> simp | cons i order ih => simp only [searchRight, completedArrays] split · rw [List.any_append, ← ih, ← ih] split <;> simp_all · simp
theorem mem_completedArrays (B : ℕ) (order : List (Fin n)) (P : MaskRestriction n) (a : Array (Entry (Fin n))) (ha : a ∈ D.completedArrays B order P) : ∃ Q : MaskRestriction n, ({ D with maskRestriction := Q }.collect B).state.user.keys.overflow = false ∧ a = { D with maskRestriction := Q }.entries B := by induction order generalizing P with | nil => simp only [completedArrays] at ha split at ha · simp at ha · rename_i hc have he : a = ({ D with maskRestriction := P }.collect B).state.user.records := by simpa only [List.mem_singleton] using ha exact ⟨P, Bool.eq_false_iff.mpr hc, he⟩ | cons i order ih => simp only [completedArrays] at ha split at ha · rcases List.mem_append.mp ha with hl | hr · exact ih (P.force i false) hl · exact ih (P.force i true) hr · rename_i hc have he : a = ({ D with maskRestriction := P }.collect B).state.user.records := by simpa only [List.mem_singleton] using ha exact ⟨P, Bool.eq_false_iff.mpr hc, he⟩
end LowSpaceSubsetSum.RepresentationParentData
namespace LowSpaceSubsetSum.RepresentationBucketData
variable {n g : ℕ} (D : RepresentationBucketData n g)
def checkList (B : ℕ) : List (Array (Entry (Fin n)) × Array (Entry (Fin n))) := let left := (D.left.collect B).state.user if left.keys.overflow then [] else if left.records.isEmpty then [] else (D.right.completedArrays B D.topOrder MaskRestriction.empty).map (left.records, ·)
theorem run_eq_any (B : ℕ) (families : Fin 4 → Array (Finset (Fin g))) : D.run B families = (D.checkList B).any (fun p => D.check families p.1 p.2) := by unfold run checkList dsimp only split · simp split · simp rw [D.right.searchRight_eq_any, List.any_map] rfl
end LowSpaceSubsetSum.RepresentationBucketData
end OAI123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197import OAI.Combinatorics.LowSpaceSubsetSum.Streams.ParentPrefixSearchimport OAI.Combinatorics.LowSpaceSubsetSum.Search.Watchdog
namespace OAI
/-! # Explicit pending-sibling stack for prefix recomputation
A collector result is inspected and discarded in one task action. A framecontains only the next restriction and remaining index order. In particular,no overflowing dictionary or reader state is retained in a frame. Taskexecution inside this action is accounted for separately by the join ledger.-/
namespace LowSpaceSubsetSum.PrefixMachine
variable {n : ℕ}
structure Job (n : ℕ) where order : List (Fin n) restriction : MaskRestriction n
inductive Control (n : ℕ) | eval : Job n → List (Job n) → Control n | ret : Bool → List (Job n) → Control n
namespace Control
def stack : Control n → List (Job n) | .eval _ pending => pending | .ret _ pending => pending
/-- Masks and an order pointer can use fewer cells. Counting every mask bitand every remaining order element still gives this conservative bound. -/def cells (s : Control n) : ℕ := (4 * n + 16) * (s.stack.length + 1)
end Control
def step (D : RepresentationParentData n) (B : ℕ) (check : Array (Entry (Fin n)) → Bool) : Control n → Watchdog.Transition (Control n) | .eval job pending => let out := ({ D with maskRestriction := job.restriction }.collect B).state.user if out.keys.overflow then match job.order with | [] => .next (.ret false pending) | i :: rest => .next (.eval ⟨rest, job.restriction.force i false⟩ (⟨rest, job.restriction.force i true⟩ :: pending)) else .next (.ret (check out.records) pending) | .ret true _ => .halt true | .ret false [] => .halt false | .ret false (job :: pending) => .next (.eval job pending)
def GoodStack (N : ℕ) (pending : List (Job n)) : Prop := pending.Pairwise (fun a b => a.order.length < b.order.length) ∧ ∀ job ∈ pending, job.order.length ≤ N
def Invariant (N : ℕ) : Control n → Prop | .eval job pending => GoodStack N pending ∧ job.order.length ≤ N ∧ ∀ next ∈ pending, job.order.length ≤ next.order.length | .ret _ pending => GoodStack N pending
theorem goodStack_length {N : ℕ} {pending : List (Job n)} (h : GoodStack N pending) : pending.length ≤ N + 1 := by have hpair : (pending.map (fun j => j.order.length)).Pairwise (· < ·) := List.pairwise_map.mpr h.1 have hnd : (pending.map (fun j => j.order.length)).Nodup := hpair.imp (fun hlt => Nat.ne_of_lt hlt) have hsub : (pending.map (fun j => j.order.length)).toFinset ⊆ Finset.range (N + 1) := by intro r hr obtain ⟨job, hj, rfl⟩ := List.mem_map.mp (List.mem_toFinset.mp hr) exact Finset.mem_range.mpr (Nat.lt_succ_of_le (h.2 job hj)) have hc := Finset.card_le_card hsub simpa only [List.toFinset_card_of_nodup hnd, List.length_map, Finset.card_range] using hc
theorem invariant_next (D : RepresentationParentData n) (B : ℕ) (check : Array (Entry (Fin n)) → Bool) (N : ℕ) (s t : Control n) (hs : Invariant N s) (ht : step D B check s = .next t) : Invariant N t := by cases s with | eval job pending => obtain ⟨hstack, hjob, hhead⟩ := hs simp only [step] at ht split at ht · cases ho : job.order with | nil => simp only [ho] at ht cases ht exact hstack | cons i rest => simp only [ho] at ht cases ht have hlen : rest.length + 1 = job.order.length := by simp [ho] refine ⟨⟨List.pairwise_cons.mpr ⟨?_, hstack.1⟩, ?_⟩, ?_, ?_⟩ · intro next hn exact lt_of_lt_of_le (by omega : rest.length < job.order.length) (hhead next hn) · intro next hn rcases List.mem_cons.mp hn with rfl | hn · dsimp only; omega · exact hstack.2 next hn · dsimp only; omega · intro next hn rcases List.mem_cons.mp hn with rfl | hn · exact le_rfl · exact (show rest.length ≤ job.order.length by omega).trans (hhead next hn) · cases ht exact hstack | ret b pending => cases b with | true => simp [step] at ht | false => cases pending with | nil => simp [step] at ht | cons job pending => simp only [step] at ht cases ht obtain ⟨hpair, hbound⟩ := hs obtain ⟨hhead, htail⟩ := List.pairwise_cons.mp hpair refine ⟨⟨htail, fun j hj => hbound j (List.mem_cons_of_mem _ hj)⟩, hbound job (List.mem_cons_self), ?_⟩ exact fun j hj => (hhead j hj).le
theorem cells_le (N : ℕ) (s : Control n) (hs : Invariant N s) : s.cells ≤ (4 * n + 16) * (N + 2) := by have hg : GoodStack N s.stack := by cases s with | eval job pending => exact hs.1 | ret b pending => exact hs have hl := goodStack_length hg exact Nat.mul_le_mul_left _ (by omega)
def jobValue (D : RepresentationParentData n) (B : ℕ) (check : Array (Entry (Fin n)) → Bool) (job : Job n) : Bool := D.searchRight B check job.order job.restriction
def meaning (D : RepresentationParentData n) (B : ℕ) (check : Array (Entry (Fin n)) → Bool) : Control n → Bool | .eval job pending => jobValue D B check job || pending.any (jobValue D B check) | .ret b pending => b || pending.any (jobValue D B check)
theorem step_meaning (D : RepresentationParentData n) (B : ℕ) (check : Array (Entry (Fin n)) → Bool) (s : Control n) : match step D B check s with | .halt b => meaning D B check s = b | .next t => meaning D B check s = meaning D B check t := by cases s with | eval job pending => cases job with | mk order P => by_cases ho : ({ D with maskRestriction := P }.collect B).state.user.keys.overflow = true · cases order with | nil => simp [step, ho, meaning, jobValue, RepresentationParentData.searchRight] | cons i rest => simp only [step, ho, ↓reduceIte, meaning, List.any_cons, jobValue] rw [RepresentationParentData.searchRight] simp only [ho, ↓reduceIte] by_cases hv : D.searchRight B check rest (P.force i false) = true · simp only [hv, ↓reduceIte, Bool.true_or] · have hf : D.searchRight B check rest (P.force i false) = false := Bool.eq_false_iff.mpr hv simp [hf] · have hf : ({ D with maskRestriction := P }.collect B).state.user.keys.overflow = false := Bool.eq_false_iff.mpr ho rw [step] simp only [hf, Bool.false_eq_true, ↓reduceIte, meaning, jobValue] rw [RepresentationParentData.searchRight.eq_def] simp only [hf, Bool.false_eq_true, ↓reduceIte] | ret b pending => cases b <;> cases pending <;> simp [step, meaning]
theorem watchdog_sound (D : RepresentationParentData n) (B : ℕ) (check : Array (Entry (Fin n)) → Bool) (Q : Prop) (hcheck : ∀ P, check ({ D with maskRestriction := P }.entries B) = true → Q) (job : Job n) (budget : ℕ) (hyes : Watchdog.accepted (Watchdog.run (step D B check) Control.cells budget (.eval job [])) = true) : Q := by apply Watchdog.sound (step D B check) Control.cells (fun s => meaning D B check s = true → Q) Q ?_ ?_ budget (.eval job []) ?_ hyes · intro s t hs ht h have hm := step_meaning D B check s rw [ht] at hm exact hs (hm.trans h) · intro s hs ht have hm := step_meaning D B check s rw [ht] at hm exact hs hm · intro h have hj : jobValue D B check job = true := by simpa only [meaning, List.any_nil, Bool.or_false] using h exact D.searchRight_sound B check Q hcheck job.order job.restriction hj
theorem watchdog_stack_peak (D : RepresentationParentData n) (B : ℕ) (check : Array (Entry (Fin n)) → Bool) (job : Job n) (budget : ℕ) : (Watchdog.run (step D B check) Control.cells budget (.eval job [])).peak ≤ (4 * n + 16) * (job.order.length + 2) := by apply Watchdog.peak_le _ _ (Invariant job.order.length) _ (invariant_next D B check job.order.length) (cells_le job.order.length) simp [Invariant, GoodStack]
end LowSpaceSubsetSum.PrefixMachine
end OAI12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485import OAI.Combinatorics.LowSpaceSubsetSum.Streams.PrefixMachineimport OAI.Combinatorics.LowSpaceSubsetSum.Streams.PrefixTaskCountimport OAI.Combinatorics.LowSpaceSubsetSum.Search.WatchdogRanking
namespace OAI
/-! # Termination of the explicit prefix stack
The rank charges all possible task starts, including the sibling skippedafter an early YES. The stack machine terminates in at most three timesthis task count plus two control actions. A collector action is a macro,whose internal primitive operations still need their own watchdog.-/
namespace LowSpaceSubsetSum.PrefixMachine
variable {n : ℕ}
def pendingWeight (D : RepresentationParentData n) (B : ℕ) (pending : List (Job n)) : ℕ := (pending.map (fun job => 3 * D.taskStarts B job.order job.restriction + 2)).sum
def rank (D : RepresentationParentData n) (B : ℕ) : Control n → ℕ | .eval job pending => 3 * D.taskStarts B job.order job.restriction + pendingWeight D B pending + 2 | .ret _ pending => pendingWeight D B pending + 1
theorem rank_pos (D : RepresentationParentData n) (B : ℕ) (s : Control n) : 1 ≤ rank D B s := by cases s <;> simp only [rank] <;> omega
theorem rank_next (D : RepresentationParentData n) (B : ℕ) (check : Array (Entry (Fin n)) → Bool) (s t : Control n) (ht : step D B check s = .next t) : rank D B t < rank D B s := by cases s with | eval job pending => cases job with | mk order P => by_cases ho : ({ D with maskRestriction := P }.collect B).state.user.keys.overflow = true · cases order with | nil => simp only [step, ho, ↓reduceIte] at ht cases ht simp only [rank, RepresentationParentData.taskStarts] omega | cons i rest => simp only [step, ho, ↓reduceIte] at ht cases ht simp only [rank, pendingWeight, List.map_cons, List.sum_cons, RepresentationParentData.taskStarts, ho, ↓reduceIte] omega · have hf : ({ D with maskRestriction := P }.collect B).state.user.keys.overflow = false := Bool.eq_false_iff.mpr ho simp only [step, hf, Bool.false_eq_true, ↓reduceIte] at ht cases ht cases order <;> simp only [rank, RepresentationParentData.taskStarts, hf, Bool.false_eq_true, ↓reduceIte] <;> omega | ret b pending => cases b with | true => simp [step] at ht | false => cases pending with | nil => simp [step] at ht | cons job pending => simp only [step] at ht cases ht simp only [rank, pendingWeight, List.map_cons, List.sum_cons] omega
/-- The explicit stack performs exactly the original prefix search. -/theorem output_eq_searchRight (D : RepresentationParentData n) (B : ℕ) (check : Array (Entry (Fin n)) → Bool) (job : Job n) : (Watchdog.run (step D B check) Control.cells (3 * D.taskStarts B job.order job.restriction + 2) (.eval job [])).output = some (D.searchRight B check job.order job.restriction) := by have h := Watchdog.ranked_complete (step D B check) Control.cells (rank D B) (rank_pos D B) (rank_next D B check) (meaning D B check) (fun s => by have hs := step_meaning D B check s cases ht : step D B check s <;> simp only [ht] at hs ⊢ <;> exact hs) (.eval job []) (3 * D.taskStarts B job.order job.restriction + 2) (by simp [rank, pendingWeight]) simpa only [meaning, List.any_nil, Bool.or_false, jobValue] using h
end LowSpaceSubsetSum.PrefixMachine
end OAI123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180import OAI.Combinatorics.LowSpaceSubsetSum.Counting.ParentRestrictionUniverseimport OAI.Combinatorics.LowSpaceSubsetSum.Streams.PrefixCheckList
namespace OAI
/-! # Task-start bounds for the executable prefix recursion -/
noncomputable section
namespace LowSpaceSubsetSum.RepresentationParentData
variable {n : ℕ} (D : RepresentationParentData n)
def overflowCount (B : ℕ) : List (Fin n) → MaskRestriction n → ℕ | order, P => if ({ D with maskRestriction := P }.collect B).state.user.keys.overflow then match order with | [] => 1 | i :: rest => 1 + overflowCount B rest (P.force i false) + overflowCount B rest (P.force i true) else 0
def taskStarts (B : ℕ) : List (Fin n) → MaskRestriction n → ℕ | [], _ => 1 | i :: rest, P => if ({ D with maskRestriction := P }.collect B).state.user.keys.overflow then 1 + taskStarts B rest (P.force i false) + taskStarts B rest (P.force i true) else 1
theorem taskStarts_le_overflow (B : ℕ) (order : List (Fin n)) (P : MaskRestriction n) : D.taskStarts B order P ≤ 1 + 2 * D.overflowCount B order P := by induction order generalizing P with | nil => simp [taskStarts, overflowCount] | cons i order ih => simp only [taskStarts, overflowCount] split · change 1 + D.taskStarts B order (P.force i false) + D.taskStarts B order (P.force i true) ≤ 1 + 2 * (1 + D.overflowCount B order (P.force i false) + D.overflowCount B order (P.force i true)) have h0 := ih (P.force i false) have h1 := ih (P.force i true) omega · omega
theorem entryUniverse_force_card_add (P : MaskRestriction n) (hd : ∀ i j, i ≠ j → Disjoint (D.leaves i).top (D.leaves j).top) (i : Fin n) (hi : i ∈ RepresentationUniverse.topDomain D.leaves) : ({ D with maskRestriction := P.force i false }).entryUniverse.card + ({ D with maskRestriction := P.force i true }).entryUniverse.card = ({ D with maskRestriction := P }).entryUniverse.card := by classical rw [D.entryUniverse_force P hd i hi false, D.entryUniverse_force P hd i hi true] have h := Finset.card_filter_add_card_filter_not (s := ({ D with maskRestriction := P }).entryUniverse) (p := fun e => i ∈ e.mask) simpa only [decide_eq_false_iff_not, decide_eq_true_eq, add_comm] using h
theorem overflowCount_capacity (B : ℕ) (hd : ∀ i j, i ≠ j → Disjoint (D.leaves i).top (D.leaves j).top) (hbounded : ∀ P, ∀ e ∈ ({ D with maskRestriction := P }).rawEntries, WeightEncoding.BoundedWeight D.input e.value) (order : List (Fin n)) (horder : ∀ i ∈ order, i ∈ RepresentationUniverse.topDomain D.leaves) (P : MaskRestriction n) : D.capacity * D.overflowCount B order P ≤ (order.length + 1) * ({ D with maskRestriction := P }).entryUniverse.card := by induction order generalizing P with | nil => simp only [overflowCount, List.length_nil] split · rename_i ho have hc : D.capacity < ({ D with maskRestriction := P }).entryUniverse.card := (({ D with maskRestriction := P }).collect_overflow_iff_card B (hbounded P)).mp ho simp only [Nat.zero_add, one_mul, mul_one] omega · simp | cons i order ih => simp only [overflowCount, List.length_cons] split · rename_i ho have hc : D.capacity < ({ D with maskRestriction := P }).entryUniverse.card := (({ D with maskRestriction := P }).collect_overflow_iff_card B (hbounded P)).mp ho have h0 := ih (fun j hj => horder j (by simp [hj])) (P.force i false) have h1 := ih (fun j hj => horder j (by simp [hj])) (P.force i true) have hs := D.entryUniverse_force_card_add P hd i (horder i (by simp)) generalize ({ D with maskRestriction := P }).entryUniverse.card = U at hc hs ⊢ generalize ({ D with maskRestriction := P.force i false }).entryUniverse.card = U0 at h0 hs generalize ({ D with maskRestriction := P.force i true }).entryUniverse.card = U1 at h1 hs nlinarith only [hc, h0, h1, hs] · simp
theorem taskStarts_capacity (B : ℕ) (hd : ∀ i j, i ≠ j → Disjoint (D.leaves i).top (D.leaves j).top) (hbounded : ∀ P, ∀ e ∈ ({ D with maskRestriction := P }).rawEntries, WeightEncoding.BoundedWeight D.input e.value) (order : List (Fin n)) (horder : ∀ i ∈ order, i ∈ RepresentationUniverse.topDomain D.leaves) (P : MaskRestriction n) : D.capacity * D.taskStarts B order P ≤ D.capacity + 2 * (order.length + 1) * ({ D with maskRestriction := P }).entryUniverse.card := by have ht := D.taskStarts_le_overflow B order P have ho := D.overflowCount_capacity B hd hbounded order horder P nlinarith
theorem completedArrays_length_le (B : ℕ) (order : List (Fin n)) (P : MaskRestriction n) : (D.completedArrays B order P).length ≤ D.taskStarts B order P := by induction order generalizing P with | nil => simp only [completedArrays, taskStarts] split <;> simp | cons i order ih => simp only [completedArrays, taskStarts] split · change (D.completedArrays B order (P.force i false) ++ D.completedArrays B order (P.force i true)).length ≤ 1 + D.taskStarts B order (P.force i false) + D.taskStarts B order (P.force i true) simp only [List.length_append] have h0 := ih (P.force i false) have h1 := ih (P.force i true) omega · simp
theorem completedArrays_size_sum_le (B : ℕ) (hd : ∀ i j, i ≠ j → Disjoint (D.leaves i).top (D.leaves j).top) (hbounded : ∀ P, ∀ e ∈ ({ D with maskRestriction := P }).rawEntries, WeightEncoding.BoundedWeight D.input e.value) (order : List (Fin n)) (horder : ∀ i ∈ order, i ∈ RepresentationUniverse.topDomain D.leaves) (P : MaskRestriction n) : ((D.completedArrays B order P).map Array.size).sum ≤ ({ D with maskRestriction := P }).entryUniverse.card := by induction order generalizing P with | nil => simp only [completedArrays] split · simp · rename_i hc have hclear := Bool.eq_false_iff.mpr hc simpa only [List.map_singleton, List.sum_singleton, entries] using (({ D with maskRestriction := P }).completed_size_eq_card B (hbounded P) hclear).le | cons i order ih => simp only [completedArrays] split · simp only [List.map_append, List.sum_append] have h0 := ih (fun j hj => horder j (by simp [hj])) (P.force i false) have h1 := ih (fun j hj => horder j (by simp [hj])) (P.force i true) have hs := D.entryUniverse_force_card_add P hd i (horder i (by simp)) omega · rename_i hc have hclear := Bool.eq_false_iff.mpr hc simpa only [List.map_singleton, List.sum_singleton, entries] using (({ D with maskRestriction := P }).completed_size_eq_card B (hbounded P) hclear).le
private theorem input_sum (L : ℕ) (arrays : List (Array (Entry (Fin n)))) : (arrays.map (fun a => L + a.size)).sum = (arrays.map Array.size).sum + L * arrays.length := by induction arrays with | nil => simp | cons a arrays ih => simp only [List.map_cons, List.sum_cons, List.length_cons, ih, Nat.mul_add, Nat.mul_one] omega
/-- Includes every reuse of the retained left array at a completed rightprefix; it is the actual check list's input-occurrence bound. -/theorem completed_check_inputs_le (B L : ℕ) (hL : L ≤ D.capacity) (hd : ∀ i j, i ≠ j → Disjoint (D.leaves i).top (D.leaves j).top) (hbounded : ∀ P, ∀ e ∈ ({ D with maskRestriction := P }).rawEntries, WeightEncoding.BoundedWeight D.input e.value) (order : List (Fin n)) (horder : ∀ i ∈ order, i ∈ RepresentationUniverse.topDomain D.leaves) (P : MaskRestriction n) : ((D.completedArrays B order P).map (fun a => L + a.size)).sum ≤ L + (2 * order.length + 3) * ({ D with maskRestriction := P }).entryUniverse.card := by rw [input_sum] have hn := D.completedArrays_length_le B order P have he := D.completedArrays_size_sum_le B hd hbounded order horder P have ht := D.taskStarts_le_overflow B order P have ho := D.overflowCount_capacity B hd hbounded order horder P have hscale := Nat.mul_le_mul_left (D.overflowCount B order P) hL nlinarith
end LowSpaceSubsetSum.RepresentationParentData
end
end OAI123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171import OAI.Combinatorics.LowSpaceSubsetSum.Streams.ReaderMap
namespace OAI
/-! # Semantic maps commute with the actual binary-search initialization -/
namespace LowSpaceSubsetSumnamespace BinarySlice
variable {α β : Type*}
private theorem search_lo_congr {m n : ℕ} (h : m = n) (p : Fin m → Bool) (q : Fin n → Bool) (hpq : ∀ i j, i.val = j.val → p i = q j) (k : ℕ) : (BinaryPivot.search p k).lo = (BinaryPivot.search q k).lo := by subst n have he : p = q := funext (fun i => hpq i i rfl) rw [he]
theorem lower_map (f : α → β) (xs : Array α) (key : β → ℤ) (r : ℤ) (k : ℕ) : lower (xs.map f) key r k = lower xs (fun x => key (f x)) r k := by unfold lower apply search_lo_congr Array.size_map intro i j hij simp only [Array.getElem_map, hij]
theorem upper_map (f : α → β) (xs : Array α) (key : β → ℤ) (r : ℤ) (k : ℕ) : upper (xs.map f) key r k = upper xs (fun x => key (f x)) r k := by unfold upper apply search_lo_congr Array.size_map intro i j hij simp only [Array.getElem_map, hij]
theorem range_map (f : α → β) (xs : Array α) (key : β → ℤ) (r : ℤ) (k : ℕ) (hs : Monotone (fun i : Fin xs.size => key (f xs[i.val]))) (ht : Monotone (fun i : Fin (xs.map f).size => key (xs.map f)[i.val])) (hk : xs.size < 2 ^ k) (hk' : (xs.map f).size < 2 ^ k) : SliceCursor.mapRange f xs (range xs (fun x => key (f x)) r k hs hk) = range (xs.map f) key r k ht hk' := by simp only [SliceCursor.mapRange, range, lower_map, upper_map]
end BinarySlicenamespace SliceModular
variable {α β : Type*}
theorem forward_map (f : α → β) (xs : Array α) (rr : SliceCursor.Range xs.size) (key : β → ℤ) (P r : ℤ) (k : ℕ) : SliceCursor.mapState f xs (forward xs rr (fun x => key (f x)) P r k) = forward (xs.map f) (SliceCursor.mapRange f xs rr) key P r k := by by_cases h : 0 < rr.length · have : NeZero rr.length := ⟨by omega⟩ rw [forward, dite_eq_left h, forward, dite_eq_left (show 0 < (SliceCursor.mapRange f xs rr).length from h)] simp only [SliceCursor.mapState, SliceCursor.mapRange, ModularCursor.forwardStart, SliceCursor.values, Array.getElem_map] rfl · rw [forward, dite_eq_right h, forward, dite_eq_right (show ¬ 0 < (SliceCursor.mapRange f xs rr).length from h)] rfl
theorem reverse_map (f : α → β) (xs : Array α) (rr : SliceCursor.Range xs.size) (key : β → ℤ) (r : ℤ) (k : ℕ) : SliceCursor.mapState f xs (reverse xs rr (fun x => key (f x)) r k) = reverse (xs.map f) (SliceCursor.mapRange f xs rr) key r k := by by_cases h : 0 < rr.length · have : NeZero rr.length := ⟨by omega⟩ rw [reverse, dite_eq_left h, reverse, dite_eq_left (show 0 < (SliceCursor.mapRange f xs rr).length from h)] simp only [SliceCursor.mapState, SliceCursor.mapRange, ModularCursor.reverseStart, SliceCursor.values, Array.getElem_map] rfl · rw [reverse, dite_eq_right h, reverse, dite_eq_right (show ¬ 0 < (SliceCursor.mapRange f xs rr).length from h)] rfl
end SliceModularnamespace FilteredRow
variable {α β γ δ : Type*}
theorem forward_map (f : α → γ) (g : β → δ) (xs : Array β) (wl : γ → ℤ) (wr : δ → ℤ) (p P c : ℤ) (k : ℕ) (hs : PrimarySorted xs (fun y => wr (g y)) p) (ht : PrimarySorted (xs.map g) wr p) (hk : xs.size < 2 ^ k) (hk' : (xs.map g).size < 2 ^ k) (x : α) : PairCursor.mapState f g xs (forward xs (fun y => wl (f y)) (fun y => wr (g y)) p P c k hs hk x) = forward (xs.map g) wl wr p P c k ht hk' (f x) := by simp only [forward, PairCursor.mapState, range] congr 1 rw [SliceModular.forward_map g xs _ (fun y => wr y % P) P (wl (f x) % P) k] congr 1 exact BinarySlice.range_map g xs (fun y => wr y % p) _ k hs ht hk hk'
theorem reverse_map (f : α → γ) (g : β → δ) (xs : Array β) (wl : γ → ℤ) (wr : δ → ℤ) (p P c v : ℤ) (k : ℕ) (hs : PrimarySorted xs (fun y => wr (g y)) p) (ht : PrimarySorted (xs.map g) wr p) (hk : xs.size < 2 ^ k) (hk' : (xs.map g).size < 2 ^ k) (x : α) : PairCursor.mapState f g xs (reverse xs (fun y => wl (f y)) (fun y => wr (g y)) p P c v k hs hk x) = reverse (xs.map g) wl wr p P c v k ht hk' (f x) := by simp only [reverse, PairCursor.mapState, range] congr 1 rw [SliceModular.reverse_map g xs _ (fun y => wr y % P) ((v - wl (f x)) % P) k] congr 1 exact BinarySlice.range_map g xs (fun y => wr y % p) _ k hs ht hk hk'
end FilteredRownamespace FilteredStream
variable {α β γ δ : Type*}
theorem key_map (f : α → γ) (g : β → δ) (wl : γ → ℤ) (wr : δ → ℤ) (P : ℤ) (mode : Mode) (x : α × β) : key (fun y => wl (f y)) (fun y => wr (g y)) P mode x = key wl wr P mode (Prod.map f g x) := by cases mode <;> rfl
theorem row_map (f : α → γ) (g : β → δ) (right : Array β) (wl : γ → ℤ) (wr : δ → ℤ) (p P c : ℤ) (hs : FilteredRow.PrimarySorted right (fun y => wr (g y)) p) (ht : FilteredRow.PrimarySorted (right.map g) wr p) (mode : Mode) (x : α) : PairCursor.mapState f g right (row right (fun y => wl (f y)) (fun y => wr (g y)) p P c hs mode x) = row (right.map g) wl wr p P c ht mode (f x) := by cases mode with | direct => simpa only [row, Array.size_map] using FilteredRow.forward_map f g right wl wr p P c (steps right.size) hs ht (steps_sufficient right.size) (by simpa using steps_sufficient right.size) x | complementary v => simpa only [row, Array.size_map] using FilteredRow.reverse_map f g right wl wr p P c v (steps right.size) hs ht (steps_sufficient right.size) (by simpa using steps_sufficient right.size) x
theorem rowArray_map (f : α → γ) (g : β → δ) (left : Array α) (right : Array β) (wl : γ → ℤ) (wr : δ → ℤ) (p P c : ℤ) (hs : FilteredRow.PrimarySorted right (fun y => wr (g y)) p) (ht : FilteredRow.PrimarySorted (right.map g) wr p) (mode : Mode) : (rowArray left right (fun y => wl (f y)) (fun y => wr (g y)) p P c hs mode).map (PairCursor.mapState f g right) = rowArray (left.map f) (right.map g) wl wr p P c ht mode := by apply Array.toList_inj.mp simp only [rowArray, Array.toList_map, List.map_map] congr 1 funext x exact row_map f g right wl wr p P c hs ht mode x
theorem initial_tree_map (f : α → γ) (g : β → δ) (left : Array α) (right : Array β) (wl : γ → ℤ) (wr : δ → ℤ) (p P c : ℤ) (hs : FilteredRow.PrimarySorted right (fun y => wr (g y)) p) (ht : FilteredRow.PrimarySorted (right.map g) wr p) (mode : Mode) (d : ℕ) : Tournament.map (RowMerge.mapFront (Prod.map f g) (mapCursor f g right)) (RowMerge.start (key (fun y => wl (f y)) (fun y => wr (g y)) P mode) (read right) (PaddedRows.rows (rowArray left right (fun y => wl (f y)) (fun y => wr (g y)) p P c hs mode) d)) = RowMerge.start (key wl wr P mode) (read (right.map g)) (PaddedRows.rows (rowArray (left.map f) (right.map g) wl wr p P c ht mode) d) := by have he : key (fun y => wl (f y)) (fun y => wr (g y)) P mode = (fun x => key wl wr P mode (Prod.map f g x)) := by cases mode <;> rfl rw [he, RowMerge.start_map (Prod.map f g) (mapCursor f g right) (key wl wr P mode) (read right) (read (right.map g)) (read_map f g right)] congr 1 funext path change (PaddedRows.rows _ d path).map (PairCursor.mapState f g right) = _ rw [PaddedRows.rows_map, rowArray_map f g left right wl wr p P c hs ht mode]
end FilteredStream
end LowSpaceSubsetSum
end OAI123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363import OAI.Combinatorics.LowSpaceSubsetSum.Representation.RepresentationStoredRecords
namespace OAI
/-! # Semantic maps for the mutable reader structures
Mapping records preserves the tournament paths and all cursor coordinates.Immutable backing arrays are mapped once; they are not copied by a read.-/
namespace LowSpaceSubsetSum
namespace Tournament
variable {α β : Type*}
def map (f : α → β) : {d : ℕ} → Tree α d → Tree β d | 0, .leaf v => .leaf (v.map f) | _d + 1, .node w l r => .node (w.map f) (map f l) (map f r)
@[simp] theorem winner_map (f : α → β) {d : ℕ} (t : Tree α d) : winner (map f t) = (winner t).map f := by cases t <;> rfl
@[simp] theorem nodes_map (f : α → β) {d : ℕ} (t : Tree α d) : nodes (map f t) = nodes t := by induction t with | leaf _ => rfl | node _ _ _ ihl ihr => simp only [map, nodes, ihl, ihr]
theorem pick_map (f : α → β) (key : β → ℤ) (a b : Option α) : (pick (fun x => key (f x)) a b).map f = pick key (a.map f) (b.map f) := by cases a <;> cases b <;> simp only [pick, Option.map_none, Option.map_some] split <;> rfl
theorem node_map (f : α → β) (key : β → ℤ) {d : ℕ} (l r : Tree α d) : map f (node (fun x => key (f x)) l r) = node key (map f l) (map f r) := by simp only [node, map, pick_map, winner_map]
theorem valid_map (f : α → β) (key : β → ℤ) {d : ℕ} (t : Tree α d) (h : Valid (fun x => key (f x)) t) : Valid key (map f t) := by induction t with | leaf _ => trivial | node w l r ihl ihr => refine ⟨?_, ihl h.2.1, ihr h.2.2⟩ rw [h.1, pick_map, winner_map, winner_map]
theorem lookup_map (f : α → β) {d : ℕ} (t : Tree α d) (p : Fin d → Bool) : lookup (map f t) p = (lookup t p).map f := by induction t with | leaf _ => rfl | node _ _ _ ihl ihr => simp only [map, lookup] split <;> simp only [ihl, ihr]
theorem replace_map (f : α → β) (key : β → ℤ) {d : ℕ} (t : Tree α d) (p : Fin d → Bool) (v : Option α) : map f (replace (fun x => key (f x)) t p v) = replace key (map f t) p (v.map f) := by induction t with | leaf _ => rfl | node _ _ _ ihl ihr => simp only [map, replace] split <;> simp only [node_map, ihl, ihr]
theorem build_map (f : α → β) (key : β → ℤ) (d : ℕ) (front : (Fin d → Bool) → Option α) : map f (build (fun x => key (f x)) d front) = build key d (fun p => (front p).map f) := by induction d with | zero => rfl | succ d ih => simp only [build, node_map, ih]
end Tournament
namespace CyclicCursor
variable {α β : Type*} {n : ℕ} [NeZero n]
theorem trace_map (f : α → β) (a : Fin n → α) (k : ℕ) (c : State n) : (trace a k c).map f = trace (fun i => f (a i)) k c := by induction k generalizing c with | zero => rfl | succ k ih => simp only [trace] split <;> simp only [List.map_nil, List.map_cons, ih]
end CyclicCursor
namespace SliceCursor
variable {α β : Type*}
def mapRange (f : α → β) (xs : Array α) (r : Range xs.size) : Range (xs.map f).size := ⟨r.lo, r.length, by simpa using r.bounded⟩
def mapState (f : α → β) (xs : Array α) (s : State xs.size) : State (xs.map f).size := ⟨mapRange f xs s.range, s.cursor⟩
theorem values_map (f : α → β) (xs : Array α) (r : Range xs.size) (i : Fin r.length) : values (xs.map f) (mapRange f xs r) i = f (values xs r i) := by simp only [values, mapRange, Array.getElem_map]
theorem next_map (f : α → β) (xs : Array α) (s : State xs.size) : (next xs s).map (fun z => (f z.1, mapState f xs z.2)) = next (xs.map f) (mapState f xs s) := by cases h : s.cursor with | none => simp only [next, mapState, h, Option.map_none] | some c => simp only [next, mapState, h] split <;> simp only [Option.map_none, Option.map_some, values_map] rfl
theorem output_map (f : α → β) (xs : Array α) (s : State xs.size) : (output xs s).map f = output (xs.map f) (mapState f xs s) := by cases h : s.cursor with | none => simp only [output, mapState, h, List.map_nil] | some c => have : NeZero s.range.length := ⟨by have := c.position.isLt; omega⟩ simp only [output, mapState, h, CyclicCursor.trace_map] congr 1 funext i exact (values_map f xs s.range i).symm
end SliceCursor
namespace PairCursor
variable {α β γ δ : Type*}
def mapState (f : α → γ) (g : β → δ) (xs : Array β) (s : State α xs.size) : State γ (xs.map g).size := ⟨f s.left, SliceCursor.mapState g xs s.cursor⟩
theorem next_map (f : α → γ) (g : β → δ) (xs : Array β) (s : State α xs.size) : (next xs s).map (fun z => (Prod.map f g z.1, mapState f g xs z.2)) = next (xs.map g) (mapState f g xs s) := by have h := SliceCursor.next_map g xs s.cursor simp only [next, mapState] rw [← h] simp only [Option.map_map] rfl
theorem output_map (f : α → γ) (g : β → δ) (xs : Array β) (s : State α xs.size) : (output xs s).map (Prod.map f g) = output (xs.map g) (mapState f g xs s) := by change ((SliceCursor.output xs s.cursor).map (fun y => (s.left, y))).map (Prod.map f g) = (SliceCursor.output (xs.map g) (SliceCursor.mapState g xs s.cursor)).map (fun y => (f s.left, y)) rw [← SliceCursor.output_map g xs s.cursor] simp only [List.map_map] rfl
end PairCursor
namespace FilteredStream
variable {α β γ δ : Type*}
def mapCursor (f : α → γ) (g : β → δ) (xs : Array β) : Cursor (α := α) xs → Cursor (α := γ) (xs.map g) := Option.map (PairCursor.mapState f g xs)
theorem read_map (f : α → γ) (g : β → δ) (xs : Array β) (s : Cursor (α := α) xs) : (read xs s).map (fun z => (Prod.map f g z.1, mapCursor f g xs z.2)) = read (xs.map g) (mapCursor f g xs s) := by cases s with | none => rfl | some s => simp only [read, PaddedRows.next, mapCursor, Option.map_some] rw [← PairCursor.next_map f g xs s] simp only [Option.map_map] rfl
theorem view_map (f : α → γ) (g : β → δ) (xs : Array β) (s : Cursor (α := α) xs) : (view xs s).map (Prod.map f g) = view (xs.map g) (mapCursor f g xs s) := by cases s with | none => rfl | some s => exact PairCursor.output_map f g xs s
end FilteredStream
namespace PaddedRows
variable {α β : Type*}
theorem rows_map (f : α → β) (xs : Array α) (d : ℕ) (p : RowMerge.Path d) : (rows xs d p).map f = rows (xs.map f) d p := by simp only [rows, Array.size_map] split <;> simp only [Option.map_some, Option.map_none, Array.getElem_map]
end PaddedRows
namespace RowMerge
variable {α β σ τ : Type*} {d : ℕ}
def mapFront (f : α → β) (g : σ → τ) (x : Front d α σ) : Front d β τ := ⟨x.row, f x.value, g x.after⟩
theorem front_map (f : α → β) (g : σ → τ) (readA : σ → Option (α × σ)) (readB : τ → Option (β × τ)) (hr : ∀ s, (readA s).map (fun z => (f z.1, g z.2)) = readB (g s)) (p : Path d) (s : σ) : (front readA p s).map (mapFront f g) = front readB p (g s) := by unfold front rw [← hr] simp only [Option.map_map] rfl
theorem start_map (f : α → β) (g : σ → τ) (key : β → ℤ) (readA : σ → Option (α × σ)) (readB : τ → Option (β × τ)) (hr : ∀ s, (readA s).map (fun z => (f z.1, g z.2)) = readB (g s)) (rows : Path d → σ) : Tournament.map (mapFront f g) (start (fun x => key (f x)) readA rows) = start key readB (fun p => g (rows p)) := by unfold start change Tournament.map (mapFront f g) (Tournament.build (fun x => (fun y : Front d β τ => key y.value) (mapFront f g x)) d (fun p => front readA p (rows p))) = _ rw [Tournament.build_map (mapFront f g) (fun y : Front d β τ => key y.value) d (fun p => front readA p (rows p))] congr 1 funext p exact front_map f g readA readB hr p (rows p)
theorem advance_map (f : α → β) (g : σ → τ) (key : β → ℤ) (readA : σ → Option (α × σ)) (readB : τ → Option (β × τ)) (hr : ∀ s, (readA s).map (fun z => (f z.1, g z.2)) = readB (g s)) (t : Tournament.Tree (Front d α σ) d) : (advance (fun x => key (f x)) readA t).map (fun z => (f z.1, Tournament.map (mapFront f g) z.2)) = advance key readB (Tournament.map (mapFront f g) t) := by simp only [advance, Tournament.winner_map] cases h : Tournament.winner t with | none => rfl | some x => simp only [Option.map_some] congr 1 apply Prod.ext · rfl change Tournament.map (mapFront f g) (Tournament.replace (fun y => key (mapFront f g y).value) t x.row (front readA x.row x.after)) = Tournament.replace (fun y => key y.value) (Tournament.map (mapFront f g) t) x.row (front readB x.row (g x.after)) rw [Tournament.replace_map (mapFront f g) (fun y : Front d β τ => key y.value) t x.row (front readA x.row x.after), front_map f g readA readB hr]
theorem aligned_map (f : α → β) (g : σ → τ) (t : Tournament.Tree (Front d α σ) d) (h : Aligned t) : Aligned (Tournament.map (mapFront f g) t) := by intro p y hy rw [Tournament.lookup_map] at hy obtain ⟨x, hx, he⟩ := Option.map_eq_some_iff.mp hy rw [← he] exact h p x hx
theorem remaining_map (f : α → β) (g : σ → τ) (viewA : σ → List α) (viewB : τ → List β) (hv : ∀ s, (viewA s).map f = viewB (g s)) (t : Tournament.Tree (Front d α σ) d) (p : Path d) : remaining viewB (Tournament.map (mapFront f g) t) p = (remaining viewA t p).map f := by unfold remaining rw [Tournament.lookup_map] cases ht : Tournament.lookup t p with | none => rfl | some x => simp only [Option.map_some, mapFront, List.map_cons, hv]
theorem rowsSorted_map (f : α → β) (g : σ → τ) (key : β → ℤ) (viewA : σ → List α) (viewB : τ → List β) (hv : ∀ s, (viewA s).map f = viewB (g s)) (t : Tournament.Tree (Front d α σ) d) (h : RowsSorted (fun x => key (f x)) viewA t) : RowsSorted key viewB (Tournament.map (mapFront f g) t) := by intro p rw [remaining_map f g viewA viewB hv, List.pairwise_map] exact h p
theorem potential_map (f : α → β) (g : σ → τ) (viewA : σ → List α) (viewB : τ → List β) (hv : ∀ s, (viewA s).map f = viewB (g s)) (t : Tournament.Tree (Front d α σ) d) : potential viewB (Tournament.map (mapFront f g) t) = potential viewA t := by unfold potential apply Finset.sum_congr rfl intro p _ rw [remaining_map f g viewA viewB hv, List.length_map]
theorem trace_map (f : α → β) (g : σ → τ) (key : β → ℤ) (readA : σ → Option (α × σ)) (readB : τ → Option (β × τ)) (hr : ∀ s, (readA s).map (fun z => (f z.1, g z.2)) = readB (g s)) (k : ℕ) (t : Tournament.Tree (Front d α σ) d) : (trace (fun x => key (f x)) readA k t).map f = trace key readB k (Tournament.map (mapFront f g) t) := by induction k generalizing t with | zero => rfl | succ k ih => have h := advance_map f g key readA readB hr t cases ha : advance (fun x => key (f x)) readA t with | none => have hb : advance key readB (Tournament.map (mapFront f g) t) = none := by simpa only [ha, Option.map_none] using h.symm simp only [trace, ha, hb, List.map_nil] | some z => obtain ⟨a, t'⟩ := z have hb : advance key readB (Tournament.map (mapFront f g) t) = some (f a, Tournament.map (mapFront f g) t') := by simpa only [ha, Option.map_some] using h.symm simp only [trace, ha, hb, List.map_cons, ih]
end RowMerge
namespace MergedReader
variable {α β σ τ : Type*} {d : ℕ}
def mapState (f : α → β) (g : σ → τ) (key : β → ℤ) (viewA : σ → List α) (viewB : τ → List β) (hv : ∀ s, (viewA s).map f = viewB (g s)) (s : State (fun x => key (f x)) viewA d) : State key viewB d := ⟨Tournament.map (RowMerge.mapFront f g) s.tree, Tournament.valid_map (RowMerge.mapFront f g) (fun x => key x.value) s.tree s.valid, RowMerge.aligned_map f g s.tree s.aligned, RowMerge.rowsSorted_map f g key viewA viewB hv s.tree s.sorted⟩
theorem next_map (f : α → β) (g : σ → τ) (key : β → ℤ) (readA : σ → Option (α × σ)) (readB : τ → Option (β × τ)) (hr : ∀ s, (readA s).map (fun z => (f z.1, g z.2)) = readB (g s)) (viewA : σ → List α) (viewB : τ → List β) (hv : ∀ s, (viewA s).map f = viewB (g s)) (ha : RowMerge.IsReader readA viewA) (hb : RowMerge.IsReader readB viewB) (s : State (fun x => key (f x)) viewA d) : (next (fun x => key (f x)) readA viewA ha s).map (fun z => (f z.1, mapState f g key viewA viewB hv z.2)) = next key readB viewB hb (mapState f g key viewA viewB hv s) := by have h := RowMerge.advance_map f g key readA readB hr s.tree cases he : RowMerge.advance (fun x => key (f x)) readA s.tree with | none => have h' : RowMerge.advance key readB (Tournament.map (RowMerge.mapFront f g) s.tree) = none := by simpa only [he, Option.map_none] using h.symm rw [next_none _ _ _ _ _ he, next_none _ _ _ _ _ h'] rfl | some z => obtain ⟨a, t⟩ := z have h' : RowMerge.advance key readB (Tournament.map (RowMerge.mapFront f g) s.tree) = some (f a, Tournament.map (RowMerge.mapFront f g) t) := by simpa only [he, Option.map_some] using h.symm rw [next_some _ _ _ _ _ he, next_some _ _ _ _ _ h'] rfl
theorem output_map (f : α → β) (g : σ → τ) (key : β → ℤ) (readA : σ → Option (α × σ)) (readB : τ → Option (β × τ)) (hr : ∀ s, (readA s).map (fun z => (f z.1, g z.2)) = readB (g s)) (viewA : σ → List α) (viewB : τ → List β) (hv : ∀ s, (viewA s).map f = viewB (g s)) (s : State (fun x => key (f x)) viewA d) : (output (fun x => key (f x)) readA viewA s).map f = output key readB viewB (mapState f g key viewA viewB hv s) := by unfold output rw [show RowMerge.potential viewB (mapState f g key viewA viewB hv s).tree = RowMerge.potential viewA s.tree from RowMerge.potential_map f g viewA viewB hv s.tree] exact RowMerge.trace_map f g key readA readB hr _ _
end MergedReaderend LowSpaceSubsetSum
end OAI123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166import OAI.Combinatorics.LowSpaceSubsetSum.Streams.DictionaryPrefixesimport OAI.Combinatorics.LowSpaceSubsetSum.Streams.DictionaryProvenanceimport OAI.Combinatorics.LowSpaceSubsetSum.Search.StoppedStreamJoin
namespace OAI
/-! # Bounded dictionaries with an actual array of retained records -/
namespace LowSpaceSubsetSum.RecordedDictionary
universe uvariable {α : Type u}
structure State (α : Type u) where keys : BinaryTrie.BuildResult records : Array α
def empty : State α := ⟨⟨.empty, false, 0⟩, #[]⟩
/-- The first rejected record is retained, as is its newly allocated trie key.Further callbacks freeze both structures. -/def feed (C : ℕ) (encode : α → List Bool) (x : α) (r : State α) : State α := ⟨BinaryTrie.feed C (encode x) r.keys, if r.keys.overflow || BinaryTrie.contains r.keys.tree (encode x) then r.records else r.records.push x⟩
@[simp] theorem feed_keys (C : ℕ) (encode : α → List Bool) (x : α) (r : State α) : (feed C encode x r).keys = BinaryTrie.feed C (encode x) r.keys := rfl
structure Invariant (C width : ℕ) (encode : α → List Bool) (r : State α) : Prop where safe : BinaryTrie.Safe C width r.keys keys_eq : BinaryTrie.keySet r.keys.tree = (r.records.toList.map encode).toFinset size_eq : r.records.size = BinaryTrie.entries r.keys.tree
theorem empty_invariant (C width : ℕ) (encode : α → List Bool) : Invariant C width encode empty := by exact ⟨BinaryTrie.empty_safe C width, rfl, rfl⟩
theorem feed_invariant {C width : ℕ} {encode : α → List Bool} {r : State α} (hr : Invariant C width encode r) (x : α) (hx : (encode x).length = width) : Invariant C width encode (feed C encode x r) := by refine ⟨BinaryTrie.feed_safe hr.safe (encode x) hx, ?_, ?_⟩ · by_cases ho : r.keys.overflow = true · simpa only [feed, ho, Bool.true_or, ↓reduceIte, BinaryTrie.feed_frozen C (encode x) r.keys ho] using hr.keys_eq have hoc : r.keys.overflow = false := Bool.eq_false_iff.mpr ho by_cases hd : BinaryTrie.contains r.keys.tree (encode x) = true · simpa only [feed, hoc, hd, Bool.false_or, ↓reduceIte, BinaryTrie.feed, Bool.false_eq_true, BinaryTrie.tick] using hr.keys_eq have hdc : BinaryTrie.contains r.keys.tree (encode x) = false := Bool.eq_false_iff.mpr hd simp only [feed, hoc, hdc, Bool.false_or, Bool.false_eq_true, ↓reduceIte, BinaryTrie.feed, Array.toList_push, List.map_append, List.map_cons, List.map_nil, List.toFinset_append, List.toFinset_cons, List.toFinset_nil] rw [BinaryTrie.keySet_insert hr.safe.hasWidth hx, hr.keys_eq] ext q simp · by_cases ho : r.keys.overflow = true · simpa only [feed, ho, Bool.true_or, ↓reduceIte, BinaryTrie.feed_frozen C (encode x) r.keys ho] using hr.size_eq have hoc : r.keys.overflow = false := Bool.eq_false_iff.mpr ho by_cases hd : BinaryTrie.contains r.keys.tree (encode x) = true · simpa only [feed, hoc, hd, Bool.false_or, ↓reduceIte, BinaryTrie.feed, Bool.false_eq_true, BinaryTrie.tick] using hr.size_eq have hdc : BinaryTrie.contains r.keys.tree (encode x) = false := Bool.eq_false_iff.mpr hd simp only [feed, hoc, hdc, Bool.false_or, Bool.false_eq_true, ↓reduceIte, BinaryTrie.feed, Array.size_push] rw [BinaryTrie.entries_insert hr.safe.hasWidth hx, hdc] simpa using hr.size_eq
/-- Every stopped state stores at most the capacity plus the rejected record. -/theorem storage {C width : ℕ} {encode : α → List Bool} {r : State α} (hr : Invariant C width encode r) : r.records.size ≤ C + 1 ∧ BinaryTrie.nodes r.keys.tree ≤ (width + 1) * (C + 1) := by exact ⟨hr.size_eq.trans_le hr.safe.bound, (BinaryTrie.nodes_le_width_mul_entries hr.safe.hasWidth hr.safe.compact).trans (Nat.mul_le_mul_left _ hr.safe.bound)⟩
theorem contains_iff {C width : ℕ} {encode : α → List Bool} {r : State α} (hr : Invariant C width encode r) (q : List Bool) : BinaryTrie.contains r.keys.tree q = true ↔ ∃ x ∈ r.records.toList, encode x = q := by rw [← BinaryTrie.mem_keySet, hr.keys_eq, List.mem_toFinset, List.mem_map]
theorem feed_provenance (C : ℕ) (encode : α → List Bool) (x : α) (r : State α) (P : α → Prop) (hr : ∀ y ∈ r.records.toList, P y) (hx : P x) : ∀ y ∈ (feed C encode x r).records.toList, P y := by intro y hy simp only [feed] at hy split at hy · exact hr y hy · simp only [Array.toList_push, List.mem_append, List.mem_singleton] at hy rcases hy with hy | rfl · exact hr y hy · exact hx
theorem fold_invariant {C width : ℕ} {encode : α → List Bool} {r : State α} (hr : Invariant C width encode r) (xs : List α) (hw : ∀ x ∈ xs, (encode x).length = width) : Invariant C width encode (xs.foldl (fun r x => feed C encode x r) r) := by induction xs generalizing r with | nil => exact hr | cons x xs ih => exact ih (feed_invariant hr x (hw x (by simp))) (fun y hy => hw y (by simp [hy]))
theorem fold_keys (C : ℕ) (encode : α → List Bool) (xs : List α) (r : State α) : (xs.foldl (fun r x => feed C encode x r) r).keys = (xs.map encode).foldl (fun r key => BinaryTrie.feed C key r) r.keys := by induction xs generalizing r with | nil => rfl | cons x xs ih => exact ih (feed C encode x r)
/-- A cardinality bound concerns distinct keys, rather than repeated callbacks.When it holds, every supplied record has its key retained in the array. -/theorem fold_fits {C width : ℕ} (encode : α → List Bool) (xs : List α) (U : Finset (List Bool)) (hwidth : ∀ q ∈ U, q.length = width) (hcap : U.card ≤ C) (hkeys : ∀ x ∈ xs, encode x ∈ U) : let r := xs.foldl (fun r x => feed C encode x r) empty r.keys.overflow = false ∧ ∀ q, (∃ x ∈ r.records.toList, encode x = q) ↔ ∃ x ∈ xs, encode x = q := by have hw : ∀ x ∈ xs, (encode x).length = width := fun x hx => hwidth _ (hkeys x hx) have hi := fold_invariant (empty_invariant C width encode) xs hw have hf := BinaryTrie.fold_fits (r := ⟨.empty, false, 0⟩) rfl (width := width) (by trivial) hwidth (by simp [BinaryTrie.keySet]) hcap (xs.map encode) (by intro q hq obtain ⟨x, hx, rfl⟩ := List.mem_map.mp hq exact hkeys x hx) dsimp only refine ⟨?_, ?_⟩ · rw [fold_keys] exact hf.1 · intro q rw [← contains_iff hi q, ← BinaryTrie.mem_keySet, fold_keys] dsimp only [empty] rw [hf.2.1] simp only [BinaryTrie.keySet, Finset.empty_union, List.mem_toFinset, List.mem_map]
/-- The option-valued emitter applies local overlap and prefix checks beforean entry is retained. A rejected tuple consumes no dictionary space. -/def callback {β γ : Type*} (C : ℕ) (encode : α → List Bool) (emit : β → γ → Option α) (x : β) (y : γ) (r : State α) : State α × Bool := (match emit x y with | none => r | some z => feed C encode z r, false)
theorem callback_invariant {β γ : Type*} {C width : ℕ} (encode : α → List Bool) (hw : ∀ z, (encode z).length = width) (emit : β → γ → Option α) (x : β) (y : γ) (r : State α) (hr : Invariant C width encode r) : Invariant C width encode (callback C encode emit x y r).1 := by cases h : emit x y with | none => simpa only [callback, h] using hr | some z => simpa only [callback, h] using feed_invariant hr z (hw z)
/-- Array and trie storage are bounded even at incomplete join prefixes. -/theorem stopped_invariant {β γ σ₁ σ₂ : Type*} {C width : ℕ} (read₁ : σ₁ → Option (β × σ₁)) (key₁ : β → ℤ) (read₂ : σ₂ → Option (γ × σ₂)) (key₂ : γ → ℤ) (encode : α → List Bool) (hw : ∀ z, (encode z).length = width) (emit : β → γ → Option α) (B fuel₁ fuel₂ controlFuel : ℕ) (s₁ : σ₁) (s₂ : σ₂) : Invariant C width encode (StreamJoin.stopped read₁ key₁ read₂ key₂ (callback C encode emit) B fuel₁ fuel₂ controlFuel s₁ s₂ empty).state.user := by rw [StreamJoin.stopped_eq] exact DictionaryPrefixes.run_preserves read₁ key₁ read₂ key₂ (callback C encode emit) (Invariant C width encode) (callback_invariant encode hw emit) B fuel₁ fuel₂ controlFuel (StreamJoin.start s₁ s₂ empty) (empty_invariant C width encode)
end LowSpaceSubsetSum.RecordedDictionary
end OAI123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120import OAI.Combinatorics.LowSpaceSubsetSum.Streams.RecordedDictionary
namespace OAI
/-! # Exact retained-record semantics for a filtered stream join -/
namespace LowSpaceSubsetSum.RecordedDictionary
variable {α β γ : Type*}
/-- A proof view; the runtime never constructs this Cartesian list. -/def matchingRecords (key₁ : β → ℤ) (key₂ : γ → ℤ) (emit : β → γ → Option α) (xs : List β) (ys : List γ) : List α := xs.flatMap (fun x => (ys.filter (fun y => decide (key₁ x = key₂ y))).filterMap (emit x))
theorem mem_matchingRecords (key₁ : β → ℤ) (key₂ : γ → ℤ) (emit : β → γ → Option α) (xs : List β) (ys : List γ) (z : α) : z ∈ matchingRecords key₁ key₂ emit xs ys ↔ ∃ x ∈ xs, ∃ y ∈ ys, key₁ x = key₂ y ∧ emit x y = some z := by simp only [matchingRecords, List.mem_flatMap, List.mem_filterMap, List.mem_filter, decide_eq_true_eq] constructor · rintro ⟨x, hx, y, ⟨hy, he⟩, hz⟩ exact ⟨x, hx, y, hy, he, hz⟩ · rintro ⟨x, hx, y, hy, he, hz⟩ exact ⟨x, hx, y, ⟨hy, he⟩, hz⟩
theorem matchFold_eq_records (C : ℕ) (encode : α → List Bool) (key₁ : β → ℤ) (key₂ : γ → ℤ) (emit : β → γ → Option α) (xs : List β) (ys : List γ) (r : State α) : MatchFold.run key₁ key₂ (callback C encode emit) xs ys r = (matchingRecords key₁ key₂ emit xs ys).foldl (fun r z => feed C encode z r) r := by induction xs generalizing r with | nil => rfl | cons x xs ih => simp only [MatchFold.run, matchingRecords, List.flatMap_cons, List.foldl_append, List.foldl_filterMap, callback, ih] congr 2 funext a y cases emit x y <;> rfl
theorem fold_provenance (C : ℕ) (encode : α → List Bool) (xs : List α) (r : State α) (P : α → Prop) (hr : ∀ z ∈ r.records.toList, P z) (hx : ∀ z ∈ xs, P z) : ∀ z ∈ (xs.foldl (fun r z => feed C encode z r) r).records.toList, P z := by induction xs generalizing r with | nil => exact hr | cons x xs ih => exact ih (feed C encode x r) (feed_provenance C encode x r P hr (hx x (by simp))) (fun y hy => hx y (by simp [hy]))
theorem matchFold_fits {C width : ℕ} (encode : α → List Bool) (key₁ : β → ℤ) (key₂ : γ → ℤ) (emit : β → γ → Option α) (xs : List β) (ys : List γ) (U : Finset (List Bool)) (hwidth : ∀ q ∈ U, q.length = width) (hcap : U.card ≤ C) (hkeys : ∀ x ∈ xs, ∀ y ∈ ys, key₁ x = key₂ y → ∀ z, emit x y = some z → encode z ∈ U) : let r := MatchFold.run key₁ key₂ (callback C encode emit) xs ys empty r.keys.overflow = false ∧ ∀ q, (∃ z ∈ r.records.toList, encode z = q) ↔ ∃ x ∈ xs, ∃ y ∈ ys, key₁ x = key₂ y ∧ ∃ z, emit x y = some z ∧ encode z = q := by rw [matchFold_eq_records] have hf := fold_fits (width := width) encode (matchingRecords key₁ key₂ emit xs ys) U hwidth hcap (by intro z hz obtain ⟨x, hx, y, hy, he, hz⟩ := (mem_matchingRecords _ _ _ _ _ _).mp hz exact hkeys x hx y hy he z hz) refine ⟨hf.1, ?_⟩ intro q rw [hf.2] constructor · rintro ⟨z, hz, he⟩ obtain ⟨x, hx, y, hy, hm, hz⟩ := (mem_matchingRecords _ _ _ _ _ _).mp hz exact ⟨x, hx, y, hy, hm, z, hz, he⟩ · rintro ⟨x, hx, y, hy, hm, z, hz, he⟩ exact ⟨z, (mem_matchingRecords _ _ _ _ _ _).mpr ⟨x, hx, y, hy, hm, hz⟩, he⟩
theorem join_eq_records {σ₁ σ₂ : Type*} (C : ℕ) (encode : α → List Bool) (read₁ : σ₁ → Option (β × σ₁)) (key₁ : β → ℤ) (read₂ : σ₂ → Option (γ × σ₂)) (key₂ : γ → ℤ) (emit : β → γ → Option α) (view₁ : σ₁ → List β) (hread₁ : RowMerge.IsReader read₁ view₁) (view₂ : σ₂ → List γ) (hread₂ : RowMerge.IsReader read₂ view₂) (B fuel₁ fuel₂ controlFuel : ℕ) (s₁ : σ₁) (s₂ : σ₂) (r : State α) (hsort₁ : (view₁ s₁).Pairwise (fun x y => key₁ x ≤ key₁ y)) (hsort₂ : (view₂ s₂).Pairwise (fun x y => key₂ x ≤ key₂ y)) (hcap₁ : (view₁ s₁).length ≤ fuel₁) (hcap₂ : (view₂ s₂).length ≤ fuel₂) (hfuel : (view₁ s₁).length + (view₂ s₂).length < controlFuel) : (StreamJoin.stopped read₁ key₁ read₂ key₂ (callback C encode emit) B fuel₁ fuel₂ controlFuel s₁ s₂ r).state.user = (matchingRecords key₁ key₂ emit (view₁ s₁) (view₂ s₂)).foldl (fun r z => feed C encode z r) r := by rw [StreamJoin.stopped_eq, StreamJoin.run_complete read₁ key₁ read₂ key₂ (callback C encode emit) (fun _ _ _ => rfl) view₁ hread₁ view₂ hread₂ B fuel₁ fuel₂ controlFuel s₁ s₂ r hsort₁ hsort₂ hcap₁ hcap₂ hfuel, matchFold_eq_records]
/-- No capacity hypothesis is needed for provenance: overflowing joins retainonly entries emitted by a matching pair. -/theorem join_provenance {σ₁ σ₂ : Type*} (C : ℕ) (encode : α → List Bool) (read₁ : σ₁ → Option (β × σ₁)) (key₁ : β → ℤ) (read₂ : σ₂ → Option (γ × σ₂)) (key₂ : γ → ℤ) (emit : β → γ → Option α) (view₁ : σ₁ → List β) (hread₁ : RowMerge.IsReader read₁ view₁) (view₂ : σ₂ → List γ) (hread₂ : RowMerge.IsReader read₂ view₂) (B fuel₁ fuel₂ controlFuel : ℕ) (s₁ : σ₁) (s₂ : σ₂) (hsort₁ : (view₁ s₁).Pairwise (fun x y => key₁ x ≤ key₁ y)) (hsort₂ : (view₂ s₂).Pairwise (fun x y => key₂ x ≤ key₂ y)) (hcap₁ : (view₁ s₁).length ≤ fuel₁) (hcap₂ : (view₂ s₂).length ≤ fuel₂) (hfuel : (view₁ s₁).length + (view₂ s₂).length < controlFuel) (z : α) (hz : z ∈ (StreamJoin.stopped read₁ key₁ read₂ key₂ (callback C encode emit) B fuel₁ fuel₂ controlFuel s₁ s₂ empty).state.user.records.toList) : ∃ x ∈ view₁ s₁, ∃ y ∈ view₂ s₂, key₁ x = key₂ y ∧ emit x y = some z := by rw [join_eq_records C encode read₁ key₁ read₂ key₂ emit view₁ hread₁ view₂ hread₂ B fuel₁ fuel₂ controlFuel s₁ s₂ empty hsort₁ hsort₂ hcap₁ hcap₂ hfuel] at hz exact (mem_matchingRecords key₁ key₂ emit _ _ z).mp (fold_provenance C encode (matchingRecords key₁ key₂ emit (view₁ s₁) (view₂ s₂)) empty (fun z => z ∈ matchingRecords key₁ key₂ emit (view₁ s₁) (view₂ s₂)) (by simp [empty]) (fun _ h => h) z hz)
end LowSpaceSubsetSum.RecordedDictionary
end OAI123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121import OAI.Combinatorics.LowSpaceSubsetSum.Streams.ModularFiltersimport Mathlib.Algebra.BigOperators.Group.Finset.Basicimport Mathlib.Data.Fintype.Prod
namespace OAI
/-!# Exact counts under uniform low-residue choices
Raw occurrence identities and distinct entry keys may be different types.Neither is deduplicated here: each supplied finite set is partitioned by itsresidue labels. This is the exact uniform-residue calculation for the counts`G`, `J`, and `U` in the resource proof.-/
namespace LowSpaceSubsetSum
open scoped BigOperators
variable {α : Type*}
def normalizedResidue {p : ℕ} (hp : 0 < p) (x : ℤ) : Fin p := ⟨(x % (p : ℤ)).toNat, by have hpZ : (0 : ℤ) < p := by exact_mod_cast hp exact (Int.toNat_lt (Int.emod_nonneg _ hpZ.ne')).mpr (Int.emod_lt_of_pos _ hpZ)⟩
theorem normalizedResidue_eq_iff {p : ℕ} (hp : 0 < p) (x : ℤ) (r : Fin p) : normalizedResidue hp x = r ↔ x % (p : ℤ) = r := by have hpZ : (0 : ℤ) < p := by exact_mod_cast hp have hnonneg := Int.emod_nonneg x hpZ.ne' constructor · intro h have hval := congrArg (fun r : Fin p => (r.val : ℤ)) h simpa only [normalizedResidue, Int.toNat_of_nonneg hnonneg] using hval · intro h apply Fin.ext simp only [normalizedResidue] rw [h] rfl
theorem sum_label_fibers {Ω : Type*} [Fintype Ω] [DecidableEq Ω] (T : Finset α) (label : α → Ω) : ∑ r : Ω, (T.filter fun x => label x = r).card = T.card := by exact (Finset.card_eq_sum_card_fiberwise (s := T) (t := Finset.univ) (f := label) (by simp)).symm
theorem mean_label_fiber {Ω : Type*} [Fintype Ω] [DecidableEq Ω] (T : Finset α) (label : α → Ω) : (∑ r : Ω, ((T.filter fun x => label x = r).card : ℝ)) / Fintype.card Ω = (T.card : ℝ) / Fintype.card Ω := by congr 1 exact_mod_cast sum_label_fibers T label
def residueFiltered {p : ℕ} (hp : 0 < p) (T : Finset α) (w : α → ℤ) (r : Fin p) : Finset α := T.filter fun x => normalizedResidue hp (w x) = r
theorem mean_residueFiltered {p : ℕ} (hp : 0 < p) (T : Finset α) (w : α → ℤ) : (∑ r : Fin p, ((residueFiltered hp T w r).card : ℝ)) / p = (T.card : ℝ) / p := by simpa only [residueFiltered, Fintype.card_fin] using mean_label_fiber T (fun x => normalizedResidue hp (w x))
def twiceResidueFiltered {p q : ℕ} (hp : 0 < p) (hq : 0 < q) (T : Finset α) (parent child : α → ℤ) (r : Fin p × Fin q) : Finset α := T.filter fun x => normalizedResidue hp (parent x) = r.1 ∧ normalizedResidue hq (child x) = r.2
/-- Each raw four-leaf occurrence passes one and only one parent/first-childresidue pair. The second child's required residue follows by nesting. -/theorem mean_twiceResidueFiltered {p q : ℕ} (hp : 0 < p) (hq : 0 < q) (T : Finset α) (parent child : α → ℤ) : (∑ r : Fin p × Fin q, ((twiceResidueFiltered hp hq T parent child r).card : ℝ)) / (p * q : ℕ) = (T.card : ℝ) / (p * q : ℕ) := by simpa only [twiceResidueFiltered, Prod.ext_iff, Fintype.card_prod, Fintype.card_fin] using mean_label_fiber T (fun x => (normalizedResidue hp (parent x), normalizedResidue hq (child x)))
/-- Finite Markov bound for a counted resource. No independence betweendifferent resources is required when these marginal bounds are combined. -/theorem finite_count_markov {Ω : Type*} [Fintype Ω] [DecidableEq Ω] [Nonempty Ω] (count : Ω → ℕ) {T : ℝ} (hT : 0 < T) : (((Finset.univ.filter fun r => T < (count r : ℝ)).card : ℝ) / Fintype.card Ω) ≤ ((∑ r : Ω, (count r : ℝ)) / Fintype.card Ω) / T := by classical have hcard : (0 : ℝ) < Fintype.card Ω := by exact_mod_cast Fintype.card_pos have hind : ∀ r : Ω, (if T < (count r : ℝ) then T else 0) ≤ count r := by intro r split_ifs with h · exact h.le · exact Nat.cast_nonneg _ have hsum := Finset.sum_le_sum (s := (Finset.univ : Finset Ω)) (fun r _ => hind r) rw [← Finset.sum_filter] at hsum simp only [Finset.sum_const, nsmul_eq_mul] at hsum apply (le_div_iff₀ hT).mpr rw [div_mul_eq_mul_div] exact (div_le_div_iff_of_pos_right hcard).mpr hsum
theorem residueFiltered_tail {p : ℕ} (hp : 0 < p) (X : Finset α) (w : α → ℤ) {T : ℝ} (hT : 0 < T) : (((Finset.univ.filter fun r : Fin p => T < (residueFiltered hp X w r).card).card : ℝ) / p) ≤ ((X.card : ℝ) / p) / T := by let : Nonempty (Fin p) := ⟨⟨0, hp⟩⟩ have h := finite_count_markov (fun r => (residueFiltered hp X w r).card) hT simpa only [Fintype.card_fin, mean_residueFiltered] using h
theorem twiceResidueFiltered_tail {p q : ℕ} (hp : 0 < p) (hq : 0 < q) (X : Finset α) (parent child : α → ℤ) {T : ℝ} (hT : 0 < T) : (((Finset.univ.filter fun r : Fin p × Fin q => T < (twiceResidueFiltered hp hq X parent child r).card).card : ℝ) / (p * q : ℕ)) ≤ ((X.card : ℝ) / (p * q : ℕ)) / T := by let : Nonempty (Fin p) := ⟨⟨0, hp⟩⟩ let : Nonempty (Fin q) := ⟨⟨0, hq⟩⟩ have h := finite_count_markov (fun r => (twiceResidueFiltered hp hq X parent child r).card) hT simpa only [Fintype.card_prod, Fintype.card_fin, ← Nat.cast_mul, mean_twiceResidueFiltered] using h
end LowSpaceSubsetSum
end OAI123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081import OAI.Combinatorics.LowSpaceSubsetSum.Streams.FilteredRowimport Mathlib.Data.List.Sort
namespace OAI
/-! # Concrete lexicographic residue sorting of the shared right array -/
namespace LowSpaceSubsetSumnamespace ResidueSort
variable {α : Type*}
def relation (w : α → ℤ) (p P : ℤ) (x y : α) : Prop := w x % p < w y % p ∨ w x % p = w y % p ∧ w x % P ≤ w y % P
instance (w : α → ℤ) (p P : ℤ) : DecidableRel (relation w p P) := fun _ _ => inferInstanceAs (Decidable (_ ∨ _ ∧ _))
theorem transitive (w : α → ℤ) (p P : ℤ) : ∀ {x y z}, relation w p P x y → relation w p P y z → relation w p P x z := by intro x y z hxy hyz dsimp only [relation] at * omega
theorem total (w : α → ℤ) (p P : ℤ) (x y : α) : relation w p P x y ∨ relation w p P y x := by dsimp only [relation] omega
def sort (xs : Array α) (w : α → ℤ) (p P : ℤ) : Array α := (xs.toList.mergeSort (fun x y => decide (relation w p P x y))).toArray
theorem permutation (xs : Array α) (w : α → ℤ) (p P : ℤ) : (sort xs w p P).toList.Perm xs.toList := by simpa only [sort, List.toList_toArray] using List.mergeSort_perm xs.toList (fun x y => decide (relation w p P x y))
theorem size (xs : Array α) (w : α → ℤ) (p P : ℤ) : (sort xs w p P).size = xs.size := by have h := (permutation xs w p P).length_eq simpa only [Array.length_toList] using h
theorem sorted (xs : Array α) (w : α → ℤ) (p P : ℤ) : (sort xs w p P).toList.Pairwise (relation w p P) := by simpa only [sort, List.toList_toArray, decide_eq_true_eq] using List.pairwise_mergeSort (le := fun x y => decide (relation w p P x y)) (fun x y z hxy hyz => by exact decide_eq_true (transitive w p P (of_decide_eq_true hxy) (of_decide_eq_true hyz))) (fun x y => by simpa only [Bool.or_eq_true, decide_eq_true_eq] using total w p P x y) xs.toList
theorem index_order (xs : Array α) (w : α → ℤ) (p P : ℤ) (i j : Fin (sort xs w p P).size) (hij : i ≤ j) : relation w p P (sort xs w p P)[i.val] (sort xs w p P)[j.val] := by rcases lt_or_eq_of_le hij with hlt | heq · have h := (sorted xs w p P).rel_getElem_of_lt (by simpa only [Array.length_toList] using i.isLt) (by simpa only [Array.length_toList] using j.isLt) hlt simpa only [Array.getElem_toList] using h · subst j exact Or.inr ⟨rfl, le_rfl⟩
theorem primary (xs : Array α) (w : α → ℤ) (p P : ℤ) : FilteredRow.PrimarySorted (sort xs w p P) w p := by intro i j hij change w (sort xs w p P)[i.val] % p ≤ w (sort xs w p P)[j.val] % p have h := index_order xs w p P i j hij dsimp only [relation] at h omega
theorem secondary (xs : Array α) (w : α → ℤ) (p P : ℤ) : FilteredRow.SecondarySorted (sort xs w p P) w p P := by intro i j hij heq have h := index_order xs w p P i j hij dsimp only [relation] at h omega
end ResidueSortend LowSpaceSubsetSum
end OAI123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199import OAI.Combinatorics.LowSpaceSubsetSum.Streams.Tournamentimport OAI.Combinatorics.LowSpaceSubsetSum.Streams.CyclicCursor
namespace OAI
/-!# A tournament merge with one current occurrence per row
The shared immutable input arrays are parameters of the row reader. Eachleaf contains a row identifier, its current item, and its cursor after thatitem. Advancing the winning row performs one row read and one tournamentreplacement. The remaining lists below are ghost views used for correctness;the merge state stores no pair-product list.-/
namespace LowSpaceSubsetSumnamespace RowMerge
universe u v
variable {α : Type u} {σ : Type v} {d : ℕ}
abbrev Path (d : ℕ) := Fin d → Bool
structure Front (d : ℕ) (α : Type u) (σ : Type v) where row : Path d value : α after : σ
def front (read : σ → Option (α × σ)) (p : Path d) (s : σ) : Option (Front d α σ) := (read s).map (fun z => ⟨p, z.1, z.2⟩)
def start (key : α → ℤ) (read : σ → Option (α × σ)) (s : Path d → σ) : Tournament.Tree (Front d α σ) d := Tournament.build (fun x => key x.value) d (fun p => front read p (s p))
def Aligned (t : Tournament.Tree (Front d α σ) d) : Prop := ∀ p x, Tournament.lookup t p = some x → x.row = p
theorem front_row (read : σ → Option (α × σ)) (p : Path d) (s : σ) {x : Front d α σ} (hx : front read p s = some x) : x.row = p := by cases hr : read s with | none => simp [front, hr] at hx | some z => have heq : (⟨p, z.1, z.2⟩ : Front d α σ) = x := by simpa [front, hr] using hx rw [← heq]
theorem start_aligned (key : α → ℤ) (read : σ → Option (α × σ)) (s : Path d → σ) : Aligned (start key read s) := by intro p x hx rw [start, Tournament.lookup_build] at hx exact front_row read p (s p) hx
theorem start_valid (key : α → ℤ) (read : σ → Option (α × σ)) (s : Path d → σ) : Tournament.Valid (fun x => key x.value) (start key read s) := Tournament.build_valid _ _ _
def advance (key : α → ℤ) (read : σ → Option (α × σ)) (t : Tournament.Tree (Front d α σ) d) : Option (α × Tournament.Tree (Front d α σ) d) := (Tournament.winner t).map fun x => (x.value, Tournament.replace (fun y => key y.value) t x.row (front read x.row x.after))
theorem advance_valid (key : α → ℤ) (read : σ → Option (α × σ)) (t : Tournament.Tree (Front d α σ) d) (ht : Tournament.Valid (fun x => key x.value) t) {a : α} {t' : Tournament.Tree (Front d α σ) d} (ha : advance key read t = some (a, t')) : Tournament.Valid (fun x => key x.value) t' := by cases hw : Tournament.winner t with | none => simp [advance, hw] at ha | some x => have heq : (x.value, Tournament.replace (fun y => key y.value) t x.row (front read x.row x.after)) = (a, t') := by simpa [advance, hw] using ha rw [← (Prod.mk.inj heq).2] exact Tournament.replace_valid _ t ht _ _
theorem advance_aligned (key : α → ℤ) (read : σ → Option (α × σ)) (t : Tournament.Tree (Front d α σ) d) (ht : Aligned t) {a : α} {t' : Tournament.Tree (Front d α σ) d} (ha : advance key read t = some (a, t')) : Aligned t' := by cases hw : Tournament.winner t with | none => simp [advance, hw] at ha | some x => have heq : (x.value, Tournament.replace (fun y => key y.value) t x.row (front read x.row x.after)) = (a, t') := by simpa [advance, hw] using ha rw [← (Prod.mk.inj heq).2] intro p y hy rw [Tournament.lookup_replace] at hy by_cases hp : x.row = p · rw [ite_eq_left hp] at hy exact (front_row read x.row x.after hy).trans hp · rw [ite_eq_right hp] at hy exact ht p y hy
theorem winner_at_own_row (key : α → ℤ) (t : Tournament.Tree (Front d α σ) d) (ht : Tournament.Valid (fun x => key x.value) t) (halign : Aligned t) {x : Front d α σ} (hx : Tournament.winner t = some x) : Tournament.lookup t x.row = some x := by have hm := (Tournament.winner_best (fun x => key x.value) t ht).1 x hx obtain ⟨p, hp⟩ := (Tournament.mem_candidates_iff t x).mp hm rw [halign p x hp] exact hp
theorem winner_is_minimum (key : α → ℤ) (t : Tournament.Tree (Front d α σ) d) (ht : Tournament.Valid (fun x => key x.value) t) {x : Front d α σ} (hx : Tournament.winner t = some x) (p : Path d) {y : Front d α σ} (hy : Tournament.lookup t p = some y) : key x.value ≤ key y.value := by obtain ⟨w, hw, hwy⟩ := Tournament.winner_le_lookup (fun x => key x.value) t ht p hy have h : w = x := Option.some.inj (hw.symm.trans hx) simpa [h] using hwy
/-- A row reader's finite output law, used only in the correctness proof. -/def IsReader (read : σ → Option (α × σ)) (view : σ → List α) : Prop := ∀ s, match read s with | none => view s = [] | some (a, s') => view s = a :: view s'
theorem cyclic_next_reader (xs : Array α) [NeZero xs.size] : IsReader (CyclicCursor.next xs) (fun c => CyclicCursor.trace (fun i : Fin xs.size => xs[i.val]) c.remaining c) := by intro c cases h : c.remaining with | zero => simp [CyclicCursor.next, CyclicCursor.trace, h] | succ k => simp [CyclicCursor.next, CyclicCursor.trace, h, CyclicCursor.advance_remaining]
def remaining (view : σ → List α) (t : Tournament.Tree (Front d α σ) d) (p : Path d) : List α := match Tournament.lookup t p with | none => [] | some x => x.value :: view x.after
theorem start_remaining (key : α → ℤ) (read : σ → Option (α × σ)) (view : σ → List α) (hread : IsReader read view) (s : Path d → σ) (p : Path d) : remaining view (start key read s) p = view (s p) := by simp only [remaining, start, Tournament.lookup_build, front] have hr := hread (s p) cases h : read (s p) with | none => simp only [h] at hr simpa using hr.symm | some z => simp only [h] at hr simpa using hr.symm
theorem replace_remaining (key : α → ℤ) (read : σ → Option (α × σ)) (view : σ → List α) (hread : IsReader read view) (t : Tournament.Tree (Front d α σ) d) (x : Front d α σ) (q : Path d) : remaining view (Tournament.replace (fun y => key y.value) t x.row (front read x.row x.after)) q = if x.row = q then view x.after else remaining view t q := by unfold remaining rw [Tournament.lookup_replace] by_cases hq : x.row = q · rw [ite_eq_left hq, ite_eq_left hq] have hr := hread x.after cases h : read x.after with | none => simp only [h] at hr simpa [front, h] using hr.symm | some z => simp only [h] at hr simpa [front, h] using hr.symm · rw [ite_eq_right hq, ite_eq_right hq]
def potential (view : σ → List α) (t : Tournament.Tree (Front d α σ) d) : ℕ := ∑ p : Path d, (remaining view t p).length
theorem replacement_consumes_one (key : α → ℤ) (read : σ → Option (α × σ)) (view : σ → List α) (hread : IsReader read view) (t : Tournament.Tree (Front d α σ) d) (ht : Tournament.Valid (fun y => key y.value) t) (halign : Aligned t) {x : Front d α σ} (hx : Tournament.winner t = some x) : potential view (Tournament.replace (fun y => key y.value) t x.row (front read x.row x.after)) + 1 = potential view t := by have hrow := winner_at_own_row key t ht halign hx let t' := Tournament.replace (fun y => key y.value) t x.row (front read x.row x.after) have hpoint (p : Path d) : (remaining view t p).length = (remaining view t' p).length + if p = x.row then 1 else 0 := by have hnew := replace_remaining key read view hread t x p change remaining view t' p = _ at hnew by_cases hp : p = x.row · subst p rw [ite_eq_left rfl] at hnew rw [hnew] simp [remaining, hrow] · rw [ite_eq_right (Ne.symm hp)] at hnew rw [hnew, ite_eq_right hp] omega unfold potential rw [show (∑ p : Path d, (remaining view t p).length) = ∑ p : Path d, ((remaining view t' p).length + if p = x.row then 1 else 0) from Finset.sum_congr rfl (fun p _ => hpoint p)] simp [Finset.sum_add_distrib, t']
end RowMergeend LowSpaceSubsetSum
end OAI123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102import OAI.Combinatorics.LowSpaceSubsetSum.Streams.RowMerge
namespace OAI
/-!# Cyclic row cursors into one shared immutable array
Each cursor stores its slice endpoints and the constant-size cyclic state.Reading a row accesses the original array; it does not allocate a row array.Empty slices have no cursor. The list slice and full trace are proof views.-/
namespace LowSpaceSubsetSumnamespace SliceCursor
variable {α : Type*} {n : ℕ}
structure Range (n : ℕ) where lo : ℕ length : ℕ bounded : lo + length ≤ n deriving DecidableEq
structure State (n : ℕ) where range : Range n cursor : Option (CyclicCursor.State range.length)
def values (xs : Array α) (r : Range xs.size) (i : Fin r.length) : α := xs[r.lo + i.val]'(by have := r.bounded; have := i.isLt; omega)
def next (xs : Array α) (s : State xs.size) : Option (α × State xs.size) := match s.cursor with | none => none | some c => haveI : NeZero s.range.length := ⟨by have := c.position.isLt; omega⟩ if c.remaining = 0 then none else some (values xs s.range c.position, ⟨s.range, some (CyclicCursor.advance c)⟩)
def output (xs : Array α) (s : State xs.size) : List α := match s.cursor with | none => [] | some c => haveI : NeZero s.range.length := ⟨by have := c.position.isLt; omega⟩ CyclicCursor.trace (values xs s.range) c.remaining c
theorem reader (xs : Array α) : RowMerge.IsReader (next xs) (output xs) := by rintro ⟨r, c⟩ cases c with | none => rfl | some c => have : NeZero r.length := ⟨by have := c.position.isLt; omega⟩ cases h : c.remaining with | zero => simp [next, output, h, CyclicCursor.trace] | succ k => simp [next, output, h, CyclicCursor.trace, CyclicCursor.advance_remaining]
def initial (r : Range n) (pivot : ℕ) (reverse : Bool) : State n := if h : 0 < r.length then ⟨r, some ⟨⟨pivot % r.length, Nat.mod_lt _ h⟩, r.length, reverse⟩⟩ else ⟨r, none⟩
/-- A slice is a proof view, not a newly allocated row array. -/def slice (xs : Array α) (r : Range xs.size) : List α := List.ofFn (values xs r)
theorem initial_perm (xs : Array α) (r : Range xs.size) (pivot : ℕ) (reverse : Bool) : (output xs (initial r pivot reverse)).Perm (slice xs r) := by by_cases h : 0 < r.length · have : NeZero r.length := ⟨by omega⟩ rw [initial, dite_eq_left h] exact CyclicCursor.full_trace_perm (values xs r) ⟨pivot % r.length, Nat.mod_lt _ h⟩ reverse · have hz : r.length = 0 := by omega rw [initial, dite_eq_right h] simp [output, slice, hz]
theorem initial_length (xs : Array α) (r : Range xs.size) (pivot : ℕ) (reverse : Bool) : (output xs (initial r pivot reverse)).length = r.length := by rw [(initial_perm xs r pivot reverse).length_eq] simp [slice]
theorem slice_eq_drop_take (xs : Array α) (r : Range xs.size) : slice xs r = (xs.toList.drop r.lo).take r.length := by have hlo : r.lo ≤ xs.size := by have := r.bounded; omega apply List.ext_getElem · simp only [slice, List.length_ofFn, List.length_take, List.length_drop, Array.length_toList] have := r.bounded omega · intro i hi hj simp only [slice, List.getElem_ofFn, List.getElem_take, List.getElem_drop, Array.getElem_toList, values]
theorem initial_occurrences (xs : Array α) (r : Range xs.size) (pivot : ℕ) (reverse : Bool) : (output xs (initial r pivot reverse) : Multiset α) = ((xs.toList.drop r.lo).take r.length : Multiset α) := by rw [← slice_eq_drop_take xs r] exact Quot.sound (initial_perm xs r pivot reverse)
end SliceCursorend LowSpaceSubsetSum
end OAI123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146import OAI.Combinatorics.LowSpaceSubsetSum.Counting.MatchPotential
namespace OAI
/-!# Linear exact-key search for the separator's terminal arrays
At a terminal separator node every left/right pair is disjoint. One equalweight key therefore suffices. This loop stops at the first equal key andnever enumerates its Cartesian tie group. The finite reader law suppliesexactness, and the ledger charges at most two reads per control step.-/
namespace LowSpaceSubsetSumnamespace SortedFind
variable {α β σ₁ σ₂ : Type*}
def runAcc (read₁ : σ₁ → Option (α × σ₁)) (key₁ : α → ℤ) (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ) : ℕ → σ₁ → σ₂ → ℕ → Bool × ℕ | 0, _, _, queries => (false, queries) | fuel + 1, s₁, s₂, queries => match read₁ s₁ with | none => (false, queries + 1) | some (x, s₁') => match read₂ s₂ with | none => (false, queries + 2) | some (y, s₂') => if key₁ x < key₂ y then runAcc read₁ key₁ read₂ key₂ fuel s₁' s₂ (queries + 2) else if key₂ y < key₁ x then runAcc read₁ key₁ read₂ key₂ fuel s₁ s₂' (queries + 2) else (true, queries + 2)
theorem queries_le (read₁ : σ₁ → Option (α × σ₁)) (key₁ : α → ℤ) (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ) (fuel : ℕ) (s₁ : σ₁) (s₂ : σ₂) (queries : ℕ) : (runAcc read₁ key₁ read₂ key₂ fuel s₁ s₂ queries).2 ≤ queries + 2 * fuel := by induction fuel generalizing s₁ s₂ queries with | zero => simp [runAcc] | succ fuel ih => unfold runAcc split · dsimp omega · split · dsimp omega · split · exact (ih _ _ _).trans (by omega) · split · exact (ih _ _ _).trans (by omega) · dsimp omega
theorem sound (read₁ : σ₁ → Option (α × σ₁)) (key₁ : α → ℤ) (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ) (view₁ : σ₁ → List α) (hread₁ : RowMerge.IsReader read₁ view₁) (view₂ : σ₂ → List β) (hread₂ : RowMerge.IsReader read₂ view₂) (fuel : ℕ) (s₁ : σ₁) (s₂ : σ₂) (queries : ℕ) (hyes : (runAcc read₁ key₁ read₂ key₂ fuel s₁ s₂ queries).1 = true) : ∃ x ∈ view₁ s₁, ∃ y ∈ view₂ s₂, key₁ x = key₂ y := by induction fuel generalizing s₁ s₂ queries with | zero => simp [runAcc] at hyes | succ fuel ih => have h₁ := hread₁ s₁ have h₂ := hread₂ s₂ cases hx : read₁ s₁ with | none => simp [runAcc, hx] at hyes | some xp => obtain ⟨x, s₁'⟩ := xp simp only [hx] at h₁ cases hy : read₂ s₂ with | none => simp [runAcc, hx, hy] at hyes | some yp => obtain ⟨y, s₂'⟩ := yp simp only [hy] at h₂ by_cases hlt : key₁ x < key₂ y · simp only [runAcc, hx, hy, hlt, ↓reduceIte] at hyes obtain ⟨a, ha, b, hb, heq⟩ := ih _ _ _ hyes exact ⟨a, by rw [h₁]; exact List.mem_cons_of_mem _ ha, b, hb, heq⟩ · by_cases hgt : key₂ y < key₁ x · simp only [runAcc, hx, hy, hlt, hgt, ↓reduceIte] at hyes obtain ⟨a, ha, b, hb, heq⟩ := ih _ _ _ hyes exact ⟨a, ha, b, by rw [h₂]; exact List.mem_cons_of_mem _ hb, heq⟩ · exact ⟨x, by rw [h₁]; simp, y, by rw [h₂]; simp, by omega⟩
theorem correct (read₁ : σ₁ → Option (α × σ₁)) (key₁ : α → ℤ) (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ) (view₁ : σ₁ → List α) (hread₁ : RowMerge.IsReader read₁ view₁) (view₂ : σ₂ → List β) (hread₂ : RowMerge.IsReader read₂ view₂) (fuel : ℕ) (s₁ : σ₁) (s₂ : σ₂) (queries : ℕ) (hs₁ : (view₁ s₁).Pairwise (fun x y => key₁ x ≤ key₁ y)) (hs₂ : (view₂ s₂).Pairwise (fun x y => key₂ x ≤ key₂ y)) (hfuel : (view₁ s₁).length + (view₂ s₂).length < fuel) : (runAcc read₁ key₁ read₂ key₂ fuel s₁ s₂ queries).1 = true ↔ 0 < MatchPotential.count key₁ key₂ (view₁ s₁) (view₂ s₂) := by induction fuel generalizing s₁ s₂ queries with | zero => omega | succ fuel ih => have h₁ := hread₁ s₁ have h₂ := hread₂ s₂ cases hx : read₁ s₁ with | none => simp only [hx] at h₁ simp [runAcc, hx, h₁, MatchPotential.count] | some xp => obtain ⟨x, s₁'⟩ := xp simp only [hx] at h₁ cases hy : read₂ s₂ with | none => simp only [hy] at h₂ have hz := MatchPotential.eq_zero key₁ key₂ (view₁ s₁) [] (by simp) simp [runAcc, hx, hy, h₂, hz] | some yp => obtain ⟨y, s₂'⟩ := yp simp only [hy] at h₂ have hs₁' := (List.pairwise_cons.mp (h₁ ▸ hs₁)).2 have hs₂' := (List.pairwise_cons.mp (h₂ ▸ hs₂)).2 by_cases hlt : key₁ x < key₂ y · have hskip := MatchPotential.skip_left key₁ key₂ x (view₁ s₁') (view₂ s₂) (by intro z hz rw [h₂] at hz rcases List.mem_cons.mp hz with rfl | hz · exact hlt · exact hlt.trans_le ((List.pairwise_cons.mp (h₂ ▸ hs₂)).1 z hz)) rw [← h₁] at hskip simp only [runAcc, hx, hy, hlt, ↓reduceIte, hskip] exact ih s₁' s₂ _ hs₁' hs₂ (by rw [h₁] at hfuel; simp only [List.length_cons] at hfuel; omega) · by_cases hgt : key₂ y < key₁ x · have hskip := MatchPotential.skip_right key₁ key₂ (view₁ s₁) y (view₂ s₂') (by intro z hz rw [h₁] at hz rcases List.mem_cons.mp hz with rfl | hz · exact hgt · exact hgt.trans_le ((List.pairwise_cons.mp (h₁ ▸ hs₁)).1 z hz)) rw [← h₂] at hskip simp only [runAcc, hx, hy, hlt, hgt, ↓reduceIte, hskip] exact ih s₁ s₂' _ hs₁ hs₂' (by rw [h₂] at hfuel; simp only [List.length_cons] at hfuel; omega) · have heq : key₁ x = key₂ y := by omega have hpos := (MatchPotential.positive_iff key₁ key₂ (view₁ s₁) (view₂ s₂)).mpr ⟨x, by rw [h₁]; simp, y, by rw [h₂]; simp, heq⟩ simp [runAcc, hx, hy, hlt, hgt, hpos]
end SortedFindend LowSpaceSubsetSum
end OAI1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980import OAI.Combinatorics.LowSpaceSubsetSum.Streams.StreamJoin
namespace OAI
/-! The exact potential and cursor facts for one equal-key stream step. -/
namespace LowSpaceSubsetSumnamespace StreamJoin
universe u v s t wvariable {α : Type u} {β : Type v} {σ₁ : Type s} {σ₂ : Type t} {τ : Type w}
theorem equal_group_facts (read₁ : σ₁ → Option (α × σ₁)) (key₁ : α → ℤ) (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ) (report : α → β → τ → τ × Bool) (hreport : ∀ x y a, (report x y a).2 = false) (view₁ : σ₁ → List α) (hread₁ : RowMerge.IsReader read₁ view₁) (view₂ : σ₂ → List β) (hread₂ : RowMerge.IsReader read₂ view₂) (B fuel₁ fuel₂ : ℕ) (st : State σ₁ σ₂ τ) (hst : WellFormed key₁ key₂ view₁ view₂ fuel₁ fuel₂ st) (x : α) (left' : σ₁) (y : β) (right' : σ₂) (hx : read₁ st.left = some (x, left')) (hy : read₂ st.right = some (y, right')) (hkey : key₁ x = key₂ y) : let out := TieGroup.run read₁ key₁ read₂ key₂ (key₁ x) report B fuel₁ fuel₂ st.left st.right st.user let G₁ := TieBuffer.groupView key₁ (key₁ x) view₁ st.left let G₂ := TieBuffer.groupView key₂ (key₁ x) view₂ st.right (view₁ out.outer.cursor).Pairwise (fun x y => key₁ x ≤ key₁ y) ∧ (view₂ out.outer.state.last).Pairwise (fun x y => key₂ x ≤ key₂ y) ∧ (view₁ st.left).length = G₁.length + (view₁ out.outer.cursor).length ∧ (view₂ st.right).length = G₂.length + (view₂ out.outer.state.last).length ∧ 0 < G₁.length ∧ 0 < G₂.length ∧ MatchPotential.count key₁ key₂ (view₁ st.left) (view₂ st.right) = G₁.length * G₂.length + MatchPotential.count key₁ key₂ (view₁ out.outer.cursor) (view₂ out.outer.state.last) := by let out := TieGroup.run read₁ key₁ read₂ key₂ (key₁ x) report B fuel₁ fuel₂ st.left st.right st.user let G₁ := TieBuffer.groupView key₁ (key₁ x) view₁ st.left let G₂ := TieBuffer.groupView key₂ (key₁ x) view₂ st.right have hv₁ : view₁ st.left = x :: view₁ left' := by simpa only [hx] using hread₁ st.left have hv₂ : view₂ st.right = y :: view₂ right' := by simpa only [hy] using hread₂ st.right have hg₁ : G₁ ≠ [] := by simp [G₁, TieBuffer.groupView, hv₁] have hg₂ : G₂ ≠ [] := by simp [G₂, TieBuffer.groupView, hv₂, ← hkey] have hlen₁ : G₁.length ≤ fuel₁ := (List.takeWhile_sublist (fun z => decide (key₁ z = key₁ x))).length_le.trans hst.2.2.1 have hlen₂ : G₂.length ≤ fuel₂ := (List.takeWhile_sublist (fun z => decide (key₂ z = key₁ x))).length_le.trans hst.2.2.2 have hviews := TieGroup.views_complete read₁ key₁ read₂ key₂ (key₁ x) report hreport view₁ hread₁ view₂ hread₂ B fuel₁ fuel₂ st.left st.right st.user hlen₁ hlen₂ hg₁ change view₁ st.left = G₁ ++ view₁ out.outer.cursor ∧ view₂ st.right = G₂ ++ view₂ out.outer.state.last at hviews have hsub₁ := MatchPotential.remaining_sublist _ _ _ hviews.1 have hsub₂ := MatchPotential.remaining_sublist _ _ _ hviews.2 have hlower₁ : ∀ z ∈ view₁ st.left, key₁ x ≤ key₁ z := by have hsort : (x :: view₁ left').Pairwise (fun x y => key₁ x ≤ key₁ y) := by simpa only [hv₁] using hst.1 simpa only [hv₁] using MatchPotential.lower_bound_head key₁ x _ hsort have hlower₂ : ∀ z ∈ view₂ st.right, key₁ x ≤ key₂ z := by rw [hkey, hv₂] exact MatchPotential.lower_bound_head key₂ y _ (by simpa only [hv₂] using hst.2.1) have hr₁ := MatchPotential.remaining_avoids key₁ (key₁ x) _ _ hviews.1 hst.1 hlower₁ have hr₂ := MatchPotential.remaining_avoids key₂ (key₁ x) _ _ hviews.2 hst.2.1 hlower₂ refine ⟨hst.1.sublist hsub₁, hst.2.1.sublist hsub₂, ?_, ?_, List.length_pos_iff.mpr hg₁, List.length_pos_iff.mpr hg₂, ?_⟩ · simpa only [List.length_append] using congrArg List.length hviews.1 · simpa only [List.length_append] using congrArg List.length hviews.2 · have hG₁ : ∀ z ∈ G₁, key₁ z = key₁ x := by intro z hz exact of_decide_eq_true (List.mem_takeWhile_imp (p := fun z => decide (key₁ z = key₁ x)) hz) have hG₂ : ∀ z ∈ G₂, key₂ z = key₁ x := by intro z hz exact of_decide_eq_true (List.mem_takeWhile_imp (p := fun z => decide (key₂ z = key₁ x)) hz) have hsplit := MatchPotential.split_groups key₁ key₂ (key₁ x) G₁ (view₁ out.outer.cursor) G₂ (view₂ out.outer.state.last) hG₁ hG₂ hr₁ hr₂ rw [← hviews.1, ← hviews.2] at hsplit exact hsplit
end StreamJoinend LowSpaceSubsetSum
end OAI123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100import OAI.Combinatorics.LowSpaceSubsetSum.Counting.MatchPotential
namespace OAI
/-!# A finite-state join of two sorted streams
Unequal keys consume one occurrence. Equal keys invoke the bounded-bufferCartesian reporter and continue from its two saved endpoints. The loop keepsonly the two generator states, callback state, and counters. Its finite outputlists and matching potential are analysis objects only.-/
namespace LowSpaceSubsetSumnamespace StreamJoin
universe u v s t w
variable {α : Type u} {β : Type v} {σ₁ : Type s} {σ₂ : Type t} {τ : Type w}
structure State (σ₁ : Type s) (σ₂ : Type t) (τ : Type w) where left : σ₁ right : σ₂ user : τ queries : ℕ reports : ℕ copies : ℕ done : Bool
def start (s₁ : σ₁) (s₂ : σ₂) (a : τ) : State σ₁ σ₂ τ := ⟨s₁, s₂, a, 0, 0, 0, false⟩
def step (read₁ : σ₁ → Option (α × σ₁)) (key₁ : α → ℤ) (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ) (report : α → β → τ → τ × Bool) (B fuel₁ fuel₂ : ℕ) (s : State σ₁ σ₂ τ) : State σ₁ σ₂ τ := if s.done then s else match read₁ s.left with | none => { s with queries := s.queries + 1, done := true } | some (x, left') => match read₂ s.right with | none => { s with queries := s.queries + 2, done := true } | some (y, right') => if key₁ x < key₂ y then { s with left := left', queries := s.queries + 2 } else if key₂ y < key₁ x then { s with right := right', queries := s.queries + 2 } else let out := TieGroup.run read₁ key₁ read₂ key₂ (key₁ x) report B fuel₁ fuel₂ s.left s.right s.user ⟨out.outer.cursor, out.outer.state.last, out.outer.state.user, s.queries + 2 + out.outer.queries + out.fillQueries + out.outer.state.queries, s.reports + out.outer.state.reports, s.copies + (if out.snapshot then 1 else 0) + out.outer.state.restores, out.outer.halted⟩
def runAcc (read₁ : σ₁ → Option (α × σ₁)) (key₁ : α → ℤ) (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ) (report : α → β → τ → τ × Bool) (B fuel₁ fuel₂ : ℕ) : ℕ → State σ₁ σ₂ τ → State σ₁ σ₂ τ | 0, s => s | fuel + 1, s => runAcc read₁ key₁ read₂ key₂ report B fuel₁ fuel₂ fuel (step read₁ key₁ read₂ key₂ report B fuel₁ fuel₂ s)
def run (read₁ : σ₁ → Option (α × σ₁)) (key₁ : α → ℤ) (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ) (report : α → β → τ → τ × Bool) (B fuel₁ fuel₂ controlFuel : ℕ) (s₁ : σ₁) (s₂ : σ₂) (a : τ) : State σ₁ σ₂ τ := runAcc read₁ key₁ read₂ key₂ report B fuel₁ fuel₂ controlFuel (start s₁ s₂ a)
def rank (view₁ : σ₁ → List α) (view₂ : σ₂ → List β) (s : State σ₁ σ₂ τ) : ℕ := (view₁ s.left).length + (view₂ s.right).length
def potential (key₁ : α → ℤ) (key₂ : β → ℤ) (view₁ : σ₁ → List α) (view₂ : σ₂ → List β) (s : State σ₁ σ₂ τ) : ℕ := MatchPotential.count key₁ key₂ (view₁ s.left) (view₂ s.right)
def WellFormed (key₁ : α → ℤ) (key₂ : β → ℤ) (view₁ : σ₁ → List α) (view₂ : σ₂ → List β) (fuel₁ fuel₂ : ℕ) (s : State σ₁ σ₂ τ) : Prop := (view₁ s.left).Pairwise (fun x y => key₁ x ≤ key₁ y) ∧ (view₂ s.right).Pairwise (fun x y => key₂ x ≤ key₂ y) ∧ (view₁ s.left).length ≤ fuel₁ ∧ (view₂ s.right).length ≤ fuel₂
theorem step_done (read₁ : σ₁ → Option (α × σ₁)) (key₁ : α → ℤ) (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ) (report : α → β → τ → τ × Bool) (B fuel₁ fuel₂ : ℕ) (s : State σ₁ σ₂ τ) (hs : s.done = true) : step read₁ key₁ read₂ key₂ report B fuel₁ fuel₂ s = s := by simp only [step, hs, ite_true]
theorem runAcc_done (read₁ : σ₁ → Option (α × σ₁)) (key₁ : α → ℤ) (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ) (report : α → β → τ → τ × Bool) (B fuel₁ fuel₂ fuel : ℕ) (s : State σ₁ σ₂ τ) (hs : s.done = true) : runAcc read₁ key₁ read₂ key₂ report B fuel₁ fuel₂ fuel s = s := by induction fuel with | zero => rfl | succ fuel ih => rw [runAcc, step_done _ _ _ _ _ _ _ _ s hs, ih]
end StreamJoinend LowSpaceSubsetSum
end OAI123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241import OAI.Combinatorics.LowSpaceSubsetSum.Streams.StreamGroupFacts
namespace OAI
/-! Amortized accounts for the executable global stream join. -/
namespace LowSpaceSubsetSumnamespace StreamJoin
universe u v s t wvariable {α : Type u} {β : Type v} {σ₁ : Type s} {σ₂ : Type t} {τ : Type w}
def queryAccount (key₁ : α → ℤ) (key₂ : β → ℤ) (view₁ : σ₁ → List α) (view₂ : σ₂ → List β) (s : State σ₁ σ₂ τ) : ℕ := s.queries + 6 * rank view₁ view₂ s + potential key₁ key₂ view₁ view₂ s + if s.done then 0 else 2
def reportAccount (key₁ : α → ℤ) (key₂ : β → ℤ) (view₁ : σ₁ → List α) (view₂ : σ₂ → List β) (s : State σ₁ σ₂ τ) : ℕ := s.reports + potential key₁ key₂ view₁ view₂ s
def copyAccount (key₁ : α → ℤ) (key₂ : β → ℤ) (view₁ : σ₁ → List α) (view₂ : σ₂ → List β) (B : ℕ) (s : State σ₁ σ₂ τ) : ℕ := B * s.copies + 2 * potential key₁ key₂ view₁ view₂ s
theorem step_accounts (read₁ : σ₁ → Option (α × σ₁)) (key₁ : α → ℤ) (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ) (report : α → β → τ → τ × Bool) (hreport : ∀ x y a, (report x y a).2 = false) (view₁ : σ₁ → List α) (hread₁ : RowMerge.IsReader read₁ view₁) (view₂ : σ₂ → List β) (hread₂ : RowMerge.IsReader read₂ view₂) (B fuel₁ fuel₂ : ℕ) (st : State σ₁ σ₂ τ) (hst : WellFormed key₁ key₂ view₁ view₂ fuel₁ fuel₂ st) : let next := step read₁ key₁ read₂ key₂ report B fuel₁ fuel₂ st WellFormed key₁ key₂ view₁ view₂ fuel₁ fuel₂ next ∧ queryAccount key₁ key₂ view₁ view₂ next ≤ queryAccount key₁ key₂ view₁ view₂ st ∧ reportAccount key₁ key₂ view₁ view₂ next ≤ reportAccount key₁ key₂ view₁ view₂ st ∧ copyAccount key₁ key₂ view₁ view₂ B next ≤ copyAccount key₁ key₂ view₁ view₂ B st ∧ (st.done = false → next.done = true ∨ rank view₁ view₂ next < rank view₁ view₂ st) := by by_cases hd : st.done = true · simp only [step_done _ _ _ _ _ _ _ _ st hd, le_refl, hd, Bool.true_eq_false, false_implies, and_true] exact hst have hdf : st.done = false := Bool.eq_false_iff.mpr hd cases hx : read₁ st.left with | none => simp only [step, hdf, Bool.false_eq_true, ite_false, hx] refine ⟨hst, ?_, le_rfl, le_rfl, ?_⟩ · dsimp only [queryAccount, rank, potential] simp only [hdf, Bool.false_eq_true, ↓reduceIte] omega · simp | some xp => rcases xp with ⟨x, left'⟩ have hv₁ : view₁ st.left = x :: view₁ left' := by simpa only [hx] using hread₁ st.left cases hy : read₂ st.right with | none => simp only [step, hdf, Bool.false_eq_true, ite_false, hx, hy] refine ⟨hst, ?_, le_rfl, le_rfl, ?_⟩ · dsimp only [queryAccount, rank, potential] simp only [hdf, Bool.false_eq_true, ↓reduceIte] omega · simp | some yp => rcases yp with ⟨y, right'⟩ have hv₂ : view₂ st.right = y :: view₂ right' := by simpa only [hy] using hread₂ st.right by_cases hxy : key₁ x < key₂ y · have hsort₁ := hst.1 rw [hv₁] at hsort₁ have hlower₂ := MatchPotential.lower_bound_head key₂ y (view₂ right') (show (y :: view₂ right').Pairwise (fun x y => key₂ x ≤ key₂ y) from by simpa only [hv₂] using hst.2.1) have hp : MatchPotential.count key₁ key₂ (view₁ st.left) (view₂ st.right) = MatchPotential.count key₁ key₂ (view₁ left') (view₂ st.right) := by rw [hv₁] apply MatchPotential.skip_left intro z hz exact hxy.trans_le (hlower₂ z (by simpa only [hv₂] using hz)) simp only [step, hdf, Bool.false_eq_true, ite_false, hx, hy, ite_eq_left hxy] refine ⟨⟨(List.pairwise_cons.mp hsort₁).2, hst.2.1, ?_, hst.2.2.2⟩, ?_, ?_, ?_, ?_⟩ · have hc := hst.2.2.1 rw [hv₁, List.length_cons] at hc dsimp only omega · dsimp only [queryAccount, rank, potential] simp only [hdf, Bool.false_eq_true, ite_false] rw [← hp, hv₁, List.length_cons] omega · dsimp only [reportAccount, potential] rw [hp] · dsimp only [copyAccount, potential] rw [hp] · intro _ right dsimp only [rank] rw [hv₁, List.length_cons] omega · by_cases hyx : key₂ y < key₁ x · have hsort₂ := hst.2.1 rw [hv₂] at hsort₂ have hlower₁ := MatchPotential.lower_bound_head key₁ x (view₁ left') (show (x :: view₁ left').Pairwise (fun x y => key₁ x ≤ key₁ y) from by simpa only [hv₁] using hst.1) have hp : MatchPotential.count key₁ key₂ (view₁ st.left) (view₂ st.right) = MatchPotential.count key₁ key₂ (view₁ st.left) (view₂ right') := by rw [hv₂] apply MatchPotential.skip_right intro z hz exact hyx.trans_le (hlower₁ z (by simpa only [hv₁] using hz)) simp only [step, hdf, Bool.false_eq_true, ite_false, hx, hy, ite_eq_right hxy, ite_eq_left hyx] refine ⟨⟨hst.1, (List.pairwise_cons.mp hsort₂).2, hst.2.2.1, ?_⟩, ?_, ?_, ?_, ?_⟩ · have hc := hst.2.2.2 rw [hv₂, List.length_cons] at hc dsimp only omega · dsimp only [queryAccount, rank, potential] simp only [hdf, Bool.false_eq_true, ite_false] rw [← hp, hv₂, List.length_cons] omega · dsimp only [reportAccount, potential] rw [hp] · dsimp only [copyAccount, potential] rw [hp] · intro _ right dsimp only [rank] rw [hv₂, List.length_cons] omega · have hkey : key₁ x = key₂ y := by omega let out := TieGroup.run read₁ key₁ read₂ key₂ (key₁ x) report B fuel₁ fuel₂ st.left st.right st.user have hg := equal_group_facts read₁ key₁ read₂ key₂ report hreport view₁ hread₁ view₂ hread₂ B fuel₁ fuel₂ st hst x left' y right' hx hy hkey rcases hg with ⟨hs₁, hs₂, hl₁, hl₂, hn₁, hn₂, hp⟩ have hq := TieGroup.query_bound read₁ key₁ read₂ key₂ (key₁ x) report view₁ hread₁ view₂ hread₂ B fuel₁ fuel₂ st.left st.right st.user have hr := (TieGroup.run_bounds read₁ key₁ read₂ key₂ (key₁ x) report view₁ hread₁ view₂ hread₂ B fuel₁ fuel₂ st.left st.right st.user).1 have hc := TieGroup.copies_charged read₁ key₁ read₂ key₂ (key₁ x) report view₁ hread₁ view₂ hread₂ B fuel₁ fuel₂ st.left st.right st.user have hhalt : out.outer.halted = false := TieGroup.halted_false read₁ key₁ read₂ key₂ (key₁ x) report hreport B fuel₁ fuel₂ st.left st.right st.user dsimp only [out] at hhalt simp only [step, hdf, Bool.false_eq_true, ite_false, hx, hy, ite_eq_right hxy, ite_eq_right hyx] change WellFormed key₁ key₂ view₁ view₂ fuel₁ fuel₂ (⟨out.outer.cursor, out.outer.state.last, out.outer.state.user, st.queries + 2 + out.outer.queries + out.fillQueries + out.outer.state.queries, st.reports + out.outer.state.reports, st.copies + (if out.snapshot then 1 else 0) + out.outer.state.restores, out.outer.halted⟩ : State σ₁ σ₂ τ) ∧ _ refine ⟨⟨hs₁, hs₂, ?_, ?_⟩, ?_, ?_, ?_, ?_⟩ · have hcap := hst.2.2.1 dsimp only [out] omega · have hcap := hst.2.2.2 dsimp only [out] omega · dsimp only [queryAccount, rank, potential] simp only [hhalt, hdf, Bool.false_eq_true, ite_false] nlinarith · dsimp only [reportAccount, potential] omega · dsimp only [copyAccount, potential] nlinarith · intro _ right dsimp only [rank] omega
theorem runAcc_accounts (read₁ : σ₁ → Option (α × σ₁)) (key₁ : α → ℤ) (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ) (report : α → β → τ → τ × Bool) (hreport : ∀ x y a, (report x y a).2 = false) (view₁ : σ₁ → List α) (hread₁ : RowMerge.IsReader read₁ view₁) (view₂ : σ₂ → List β) (hread₂ : RowMerge.IsReader read₂ view₂) (B fuel₁ fuel₂ controlFuel : ℕ) (st : State σ₁ σ₂ τ) (hst : WellFormed key₁ key₂ view₁ view₂ fuel₁ fuel₂ st) : let out := runAcc read₁ key₁ read₂ key₂ report B fuel₁ fuel₂ controlFuel st WellFormed key₁ key₂ view₁ view₂ fuel₁ fuel₂ out ∧ queryAccount key₁ key₂ view₁ view₂ out ≤ queryAccount key₁ key₂ view₁ view₂ st ∧ reportAccount key₁ key₂ view₁ view₂ out ≤ reportAccount key₁ key₂ view₁ view₂ st ∧ copyAccount key₁ key₂ view₁ view₂ B out ≤ copyAccount key₁ key₂ view₁ view₂ B st := by induction controlFuel generalizing st with | zero => exact ⟨hst, le_rfl, le_rfl, le_rfl⟩ | succ controlFuel ih => have hs := step_accounts read₁ key₁ read₂ key₂ report hreport view₁ hread₁ view₂ hread₂ B fuel₁ fuel₂ st hst have hi := ih _ hs.1 exact ⟨hi.1, hi.2.1.trans hs.2.1, hi.2.2.1.trans hs.2.2.1, hi.2.2.2.trans hs.2.2.2.1⟩
theorem runAcc_terminates (read₁ : σ₁ → Option (α × σ₁)) (key₁ : α → ℤ) (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ) (report : α → β → τ → τ × Bool) (hreport : ∀ x y a, (report x y a).2 = false) (view₁ : σ₁ → List α) (hread₁ : RowMerge.IsReader read₁ view₁) (view₂ : σ₂ → List β) (hread₂ : RowMerge.IsReader read₂ view₂) (B fuel₁ fuel₂ controlFuel : ℕ) (st : State σ₁ σ₂ τ) (hst : WellFormed key₁ key₂ view₁ view₂ fuel₁ fuel₂ st) (hfuel : rank view₁ view₂ st < controlFuel) : (runAcc read₁ key₁ read₂ key₂ report B fuel₁ fuel₂ controlFuel st).done = true := by induction controlFuel generalizing st with | zero => omega | succ controlFuel ih => by_cases hd : st.done = true · rw [runAcc_done _ _ _ _ _ _ _ _ _ st hd] exact hd have hs := step_accounts read₁ key₁ read₂ key₂ report hreport view₁ hread₁ view₂ hread₂ B fuel₁ fuel₂ st hst rcases hs.2.2.2.2 (Bool.eq_false_iff.mpr hd) with hdone | hprogress · rw [runAcc, runAcc_done _ _ _ _ _ _ _ _ _ _ hdone] exact hdone · rw [runAcc] exact ih _ hs.1 (by omega)
theorem run_bounds (read₁ : σ₁ → Option (α × σ₁)) (key₁ : α → ℤ) (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ) (report : α → β → τ → τ × Bool) (hreport : ∀ x y a, (report x y a).2 = false) (view₁ : σ₁ → List α) (hread₁ : RowMerge.IsReader read₁ view₁) (view₂ : σ₂ → List β) (hread₂ : RowMerge.IsReader read₂ view₂) (B fuel₁ fuel₂ controlFuel : ℕ) (s₁ : σ₁) (s₂ : σ₂) (a : τ) (hsort₁ : (view₁ s₁).Pairwise (fun x y => key₁ x ≤ key₁ y)) (hsort₂ : (view₂ s₂).Pairwise (fun x y => key₂ x ≤ key₂ y)) (hcap₁ : (view₁ s₁).length ≤ fuel₁) (hcap₂ : (view₂ s₂).length ≤ fuel₂) : let out := run read₁ key₁ read₂ key₂ report B fuel₁ fuel₂ controlFuel s₁ s₂ a out.queries ≤ 6 * ((view₁ s₁).length + (view₂ s₂).length) + MatchPotential.count key₁ key₂ (view₁ s₁) (view₂ s₂) + 2 ∧ out.reports ≤ MatchPotential.count key₁ key₂ (view₁ s₁) (view₂ s₂) ∧ B * out.copies ≤ 2 * MatchPotential.count key₁ key₂ (view₁ s₁) (view₂ s₂) := by have h := runAcc_accounts read₁ key₁ read₂ key₂ report hreport view₁ hread₁ view₂ hread₂ B fuel₁ fuel₂ controlFuel (start s₁ s₂ a) ⟨hsort₁, hsort₂, hcap₁, hcap₂⟩ have hq := h.2.1 have hr := h.2.2.1 have hc := h.2.2.2 dsimp only [queryAccount, reportAccount, copyAccount, rank, potential, start] at hq hr hc simp only [Bool.false_eq_true, ite_false, Nat.zero_add, Nat.mul_zero] at hq hr hc dsimp only [run, start] omega
end StreamJoinend LowSpaceSubsetSum
end OAI123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203import OAI.Combinatorics.LowSpaceSubsetSum.Streams.StreamJoinBoundsimport OAI.Combinatorics.LowSpaceSubsetSum.Counting.MatchFold
namespace OAI
/-! Exact callback semantics of the finite-state global join. -/
namespace LowSpaceSubsetSumnamespace StreamJoin
universe u v s t wvariable {α : Type u} {β : Type v} {σ₁ : Type s} {σ₂ : Type t} {τ : Type w}
def semanticAccount (key₁ : α → ℤ) (key₂ : β → ℤ) (report : α → β → τ → τ × Bool) (view₁ : σ₁ → List α) (view₂ : σ₂ → List β) (st : State σ₁ σ₂ τ) : τ := MatchFold.run key₁ key₂ report (view₁ st.left) (view₂ st.right) st.user
theorem step_semantics (read₁ : σ₁ → Option (α × σ₁)) (key₁ : α → ℤ) (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ) (report : α → β → τ → τ × Bool) (hreport : ∀ x y a, (report x y a).2 = false) (view₁ : σ₁ → List α) (hread₁ : RowMerge.IsReader read₁ view₁) (view₂ : σ₂ → List β) (hread₂ : RowMerge.IsReader read₂ view₂) (B fuel₁ fuel₂ : ℕ) (st : State σ₁ σ₂ τ) (hst : WellFormed key₁ key₂ view₁ view₂ fuel₁ fuel₂ st) : semanticAccount key₁ key₂ report view₁ view₂ (step read₁ key₁ read₂ key₂ report B fuel₁ fuel₂ st) = semanticAccount key₁ key₂ report view₁ view₂ st := by by_cases hd : st.done = true · rw [step_done _ _ _ _ _ _ _ _ st hd] have hdf := Bool.eq_false_iff.mpr hd cases hx : read₁ st.left with | none => have hv : view₁ st.left = [] := by simpa only [hx] using hread₁ st.left simp only [step, hdf, Bool.false_eq_true, ite_false, hx, semanticAccount, hv, MatchFold.run] | some xp => rcases xp with ⟨x, left'⟩ have hv₁ : view₁ st.left = x :: view₁ left' := by simpa only [hx] using hread₁ st.left cases hy : read₂ st.right with | none => have hv : view₂ st.right = [] := by simpa only [hy] using hread₂ st.right simp only [step, hdf, Bool.false_eq_true, ite_false, hx, hy, semanticAccount, hv, MatchFold.nil_right] | some yp => rcases yp with ⟨y, right'⟩ have hv₂ : view₂ st.right = y :: view₂ right' := by simpa only [hy] using hread₂ st.right by_cases hxy : key₁ x < key₂ y · have hlower₂ : ∀ z ∈ view₂ st.right, key₂ y ≤ key₂ z := by rw [hv₂] exact MatchPotential.lower_bound_head key₂ y _ (by simpa only [hv₂] using hst.2.1) simp only [step, hdf, Bool.false_eq_true, ite_false, hx, hy, ite_eq_left hxy, semanticAccount] rw [hv₁] exact (MatchFold.skip_left key₁ key₂ report x _ _ st.user (fun z hz => hxy.trans_le (hlower₂ z hz))).symm · by_cases hyx : key₂ y < key₁ x · have hlower₁ : ∀ z ∈ view₁ st.left, key₁ x ≤ key₁ z := by rw [hv₁] exact MatchPotential.lower_bound_head key₁ x _ (by simpa only [hv₁] using hst.1) simp only [step, hdf, Bool.false_eq_true, ite_false, hx, hy, ite_eq_right hxy, ite_eq_left hyx, semanticAccount] rw [hv₂] exact (MatchFold.skip_right key₁ key₂ report _ y _ st.user (fun z hz => hyx.trans_le (hlower₁ z hz))).symm · have hkey : key₁ x = key₂ y := by omega let out := TieGroup.run read₁ key₁ read₂ key₂ (key₁ x) report B fuel₁ fuel₂ st.left st.right st.user let G₁ := TieBuffer.groupView key₁ (key₁ x) view₁ st.left let G₂ := TieBuffer.groupView key₂ (key₁ x) view₂ st.right have hg₁ : G₁ ≠ [] := by simp [G₁, TieBuffer.groupView, hv₁] have hcap₁ : G₁.length ≤ fuel₁ := (List.takeWhile_sublist _).length_le.trans hst.2.2.1 have hcap₂ : G₂.length ≤ fuel₂ := (List.takeWhile_sublist _).length_le.trans hst.2.2.2 have hviews := TieGroup.views_complete read₁ key₁ read₂ key₂ (key₁ x) report hreport view₁ hread₁ view₂ hread₂ B fuel₁ fuel₂ st.left st.right st.user hcap₁ hcap₂ hg₁ change view₁ st.left = G₁ ++ view₁ out.outer.cursor ∧ view₂ st.right = G₂ ++ view₂ out.outer.state.last at hviews have hlower₁ : ∀ z ∈ view₁ st.left, key₁ x ≤ key₁ z := by rw [hv₁] exact MatchPotential.lower_bound_head key₁ x _ (by simpa only [hv₁] using hst.1) have hlower₂ : ∀ z ∈ view₂ st.right, key₁ x ≤ key₂ z := by rw [hkey, hv₂] exact MatchPotential.lower_bound_head key₂ y _ (by simpa only [hv₂] using hst.2.1) have hr₁ := MatchPotential.remaining_avoids key₁ (key₁ x) _ _ hviews.1 hst.1 hlower₁ have hr₂ := MatchPotential.remaining_avoids key₂ (key₁ x) _ _ hviews.2 hst.2.1 hlower₂ have hG₁ : ∀ z ∈ G₁, key₁ z = key₁ x := by intro z hz exact of_decide_eq_true (List.mem_takeWhile_imp (p := fun z => decide (key₁ z = key₁ x)) hz) have hG₂ : ∀ z ∈ G₂, key₂ z = key₁ x := by intro z hz exact of_decide_eq_true (List.mem_takeWhile_imp (p := fun z => decide (key₂ z = key₁ x)) hz) have hsplit := MatchFold.split_groups key₁ key₂ report (key₁ x) G₁ (view₁ out.outer.cursor) G₂ (view₂ out.outer.state.last) st.user hG₁ hG₂ hr₁ hr₂ rw [← hviews.1, ← hviews.2] at hsplit have hstate := TieGroup.state_complete read₁ key₁ read₂ key₂ (key₁ x) report hreport view₁ hread₁ view₂ hread₂ B fuel₁ fuel₂ st.left st.right st.user hcap₁ hcap₂ rw [← hstate] at hsplit simp only [step, hdf, Bool.false_eq_true, ite_false, hx, hy, ite_eq_right hxy, ite_eq_right hyx, semanticAccount] exact hsplit.symm
theorem runAcc_semantics (read₁ : σ₁ → Option (α × σ₁)) (key₁ : α → ℤ) (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ) (report : α → β → τ → τ × Bool) (hreport : ∀ x y a, (report x y a).2 = false) (view₁ : σ₁ → List α) (hread₁ : RowMerge.IsReader read₁ view₁) (view₂ : σ₂ → List β) (hread₂ : RowMerge.IsReader read₂ view₂) (B fuel₁ fuel₂ controlFuel : ℕ) (st : State σ₁ σ₂ τ) (hst : WellFormed key₁ key₂ view₁ view₂ fuel₁ fuel₂ st) : semanticAccount key₁ key₂ report view₁ view₂ (runAcc read₁ key₁ read₂ key₂ report B fuel₁ fuel₂ controlFuel st) = semanticAccount key₁ key₂ report view₁ view₂ st := by induction controlFuel generalizing st with | zero => rfl | succ controlFuel ih => rw [runAcc, ih _ (step_accounts read₁ key₁ read₂ key₂ report hreport view₁ hread₁ view₂ hread₂ B fuel₁ fuel₂ st hst).1] exact step_semantics read₁ key₁ read₂ key₂ report hreport view₁ hread₁ view₂ hread₂ B fuel₁ fuel₂ st hst
def DoneEmpty (view₁ : σ₁ → List α) (view₂ : σ₂ → List β) (st : State σ₁ σ₂ τ) : Prop := st.done = true → view₁ st.left = [] ∨ view₂ st.right = []
theorem step_doneEmpty (read₁ : σ₁ → Option (α × σ₁)) (key₁ : α → ℤ) (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ) (report : α → β → τ → τ × Bool) (hreport : ∀ x y a, (report x y a).2 = false) (view₁ : σ₁ → List α) (hread₁ : RowMerge.IsReader read₁ view₁) (view₂ : σ₂ → List β) (hread₂ : RowMerge.IsReader read₂ view₂) (B fuel₁ fuel₂ : ℕ) (st : State σ₁ σ₂ τ) (hst : DoneEmpty view₁ view₂ st) : DoneEmpty view₁ view₂ (step read₁ key₁ read₂ key₂ report B fuel₁ fuel₂ st) := by by_cases hd : st.done = true · rw [step_done _ _ _ _ _ _ _ _ st hd] exact hst have hdf := Bool.eq_false_iff.mpr hd cases hx : read₁ st.left with | none => have hv : view₁ st.left = [] := by simpa only [hx] using hread₁ st.left simp only [DoneEmpty, step, hdf, Bool.false_eq_true, ite_false, hx] exact fun _ => Or.inl hv | some xp => rcases xp with ⟨x, left'⟩ cases hy : read₂ st.right with | none => have hv : view₂ st.right = [] := by simpa only [hy] using hread₂ st.right simp only [DoneEmpty, step, hdf, Bool.false_eq_true, ite_false, hx, hy] exact fun _ => Or.inr hv | some yp => rcases yp with ⟨y, right'⟩ by_cases hxy : key₁ x < key₂ y · simp only [DoneEmpty, step, hdf, Bool.false_eq_true, ite_false, hx, hy, ite_eq_left hxy, false_implies] · by_cases hyx : key₂ y < key₁ x · simp only [DoneEmpty, step, hdf, Bool.false_eq_true, ite_false, hx, hy, ite_eq_right hxy, ite_eq_left hyx, false_implies] · have hhalt := TieGroup.halted_false read₁ key₁ read₂ key₂ (key₁ x) report hreport B fuel₁ fuel₂ st.left st.right st.user simp only [DoneEmpty, step, hdf, Bool.false_eq_true, ite_false, hx, hy, ite_eq_right hxy, ite_eq_right hyx, hhalt, false_implies]
theorem runAcc_doneEmpty (read₁ : σ₁ → Option (α × σ₁)) (key₁ : α → ℤ) (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ) (report : α → β → τ → τ × Bool) (hreport : ∀ x y a, (report x y a).2 = false) (view₁ : σ₁ → List α) (hread₁ : RowMerge.IsReader read₁ view₁) (view₂ : σ₂ → List β) (hread₂ : RowMerge.IsReader read₂ view₂) (B fuel₁ fuel₂ controlFuel : ℕ) (st : State σ₁ σ₂ τ) (hst : DoneEmpty view₁ view₂ st) : DoneEmpty view₁ view₂ (runAcc read₁ key₁ read₂ key₂ report B fuel₁ fuel₂ controlFuel st) := by induction controlFuel generalizing st with | zero => exact hst | succ controlFuel ih => exact ih _ (step_doneEmpty read₁ key₁ read₂ key₂ report hreport view₁ hread₁ view₂ hread₂ B fuel₁ fuel₂ st hst)
/-- Enough control fuel gives the exact Cartesian-match fold. Occurrenceswith identical fields are still processed separately in this equation. -/theorem run_complete (read₁ : σ₁ → Option (α × σ₁)) (key₁ : α → ℤ) (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ) (report : α → β → τ → τ × Bool) (hreport : ∀ x y a, (report x y a).2 = false) (view₁ : σ₁ → List α) (hread₁ : RowMerge.IsReader read₁ view₁) (view₂ : σ₂ → List β) (hread₂ : RowMerge.IsReader read₂ view₂) (B fuel₁ fuel₂ controlFuel : ℕ) (s₁ : σ₁) (s₂ : σ₂) (a : τ) (hsort₁ : (view₁ s₁).Pairwise (fun x y => key₁ x ≤ key₁ y)) (hsort₂ : (view₂ s₂).Pairwise (fun x y => key₂ x ≤ key₂ y)) (hcap₁ : (view₁ s₁).length ≤ fuel₁) (hcap₂ : (view₂ s₂).length ≤ fuel₂) (hfuel : (view₁ s₁).length + (view₂ s₂).length < controlFuel) : (run read₁ key₁ read₂ key₂ report B fuel₁ fuel₂ controlFuel s₁ s₂ a).user = MatchFold.run key₁ key₂ report (view₁ s₁) (view₂ s₂) a := by have hw : WellFormed key₁ key₂ view₁ view₂ fuel₁ fuel₂ (start s₁ s₂ a) := ⟨hsort₁, hsort₂, hcap₁, hcap₂⟩ have ht := runAcc_terminates read₁ key₁ read₂ key₂ report hreport view₁ hread₁ view₂ hread₂ B fuel₁ fuel₂ controlFuel (start s₁ s₂ a) hw hfuel have he := runAcc_doneEmpty read₁ key₁ read₂ key₂ report hreport view₁ hread₁ view₂ hread₂ B fuel₁ fuel₂ controlFuel (start s₁ s₂ a) (by simp [DoneEmpty, start]) have hs := runAcc_semantics read₁ key₁ read₂ key₂ report hreport view₁ hread₁ view₂ hread₂ B fuel₁ fuel₂ controlFuel (start s₁ s₂ a) hw rcases he ht with hleft | hright · dsimp only [semanticAccount] at hs rw [hleft] at hs exact hs · dsimp only [semanticAccount] at hs rw [hright, MatchFold.nil_right] at hs exact hs
end StreamJoinend LowSpaceSubsetSum
end OAI12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394import OAI.Combinatorics.LowSpaceSubsetSum.Streams.BinaryPivotimport OAI.Combinatorics.LowSpaceSubsetSum.Streams.CountedSortimport OAI.Combinatorics.LowSpaceSubsetSum.Representation.RepresentationLeafSpace
namespace OAI
/-! # Counted binary searches and residue sorting
The counted routines follow the same branches as the executablesearch and sort. Their first components agree exactly with those routines.The counters charge predicate calls and merge/split operations, respectively;word arithmetic and mask access still require separate compilation charges.-/
namespace LowSpaceSubsetSum
namespace BinaryPivot
def counted {n : ℕ} (p : Fin n → Bool) : ℕ → Cut n → Cut n × ℕ | 0, c => (c, 0) | k + 1, c => let queried := if c.lo < c.hi then 1 else 0 let rest := counted p k (step p c) (rest.1, queried + rest.2)
theorem counted_value {n : ℕ} (p : Fin n → Bool) (k : ℕ) (c : Cut n) : (counted p k c).1 = (step p)^[k] c := by induction k generalizing c with | zero => rfl | succ k ih => simpa only [counted, Function.iterate_succ_apply] using ih (step p c)
theorem counted_queries {n : ℕ} (p : Fin n → Bool) (k : ℕ) (c : Cut n) : (counted p k c).2 ≤ k := by induction k generalizing c with | zero => rfl | succ k ih => have h := ih (step p c) simp only [counted] split <;> omega
def countedSearch {n : ℕ} (p : Fin n → Bool) (k : ℕ) : Cut n × ℕ := counted p k (initial n)
theorem countedSearch_value {n : ℕ} (p : Fin n → Bool) (k : ℕ) : (countedSearch p k).1 = search p k := counted_value p k (initial n)
theorem countedSearch_queries {n : ℕ} (p : Fin n → Bool) (k : ℕ) : (countedSearch p k).2 ≤ k := counted_queries p k (initial n)
end BinaryPivot
namespace ResidueSort
variable {α : Type*}
def counted (xs : Array α) (w : α → ℤ) (p P : ℤ) : Array α × ℕ := let r := CountedSort.sort (fun x y => decide (relation w p P x y)) xs.toList (r.1.toArray, r.2)
theorem counted_value (xs : Array α) (w : α → ℤ) (p P : ℤ) : (counted xs w p P).1 = sort xs w p P := by simp only [counted, CountedSort.sort_value, sort]
theorem counted_work (xs : Array α) (w : α → ℤ) (p P : ℤ) (n : ℕ) (hn : xs.size ≤ 2 ^ n) : (counted xs w p P).2 ≤ (6 * n + 1) * xs.size + 1 := by exact CountedSort.sort_steps_of_index_bits _ xs.toList n (by simpa using hn)
end ResidueSort
namespace RepresentationPairData
variable {n : ℕ} (D : RepresentationPairData n)
theorem counted_sort_value : (ResidueSort.counted D.rightArray D.wl D.lowModulus D.modulus).1 = D.storedRight := ResidueSort.counted_value _ _ _ _
theorem counted_sort_work (hR : D.rightArray.size ≤ 2 ^ n) : (ResidueSort.counted D.rightArray D.wl D.lowModulus D.modulus).2 ≤ (6 * n + 1) * D.right.occurrences.card + 1 := by exact (ResidueSort.counted_work _ _ _ _ n hR).trans (Nat.add_le_add_right (Nat.mul_le_mul_left _ D.rightArray_size_le) 1)
theorem any_state_comparisons (hL : D.leftArray.size ≤ 2 ^ n) (s : D.State) : MergedReader.advanceComparisons (FilteredStream.key D.wl D.wl D.modulus D.mode) (FilteredStream.view D.storedRight) s ≤ n := (D.reader_comparisons_le s).trans (Nat.clog_le_of_le_pow hL)
end RepresentationPairDataend LowSpaceSubsetSum
end OAI12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788import OAI.Combinatorics.LowSpaceSubsetSum.Streams.StreamJoinCorrectness
namespace OAI
/-! A concrete Boolean match collector for the finite-state stream join. -/
namespace LowSpaceSubsetSumnamespace StreamWitness
universe u vvariable {α : Type u} {β : Type v}
def remember (hit : α → β → Bool) (x : α) (y : β) (a : Bool) : Bool × Bool := (a || hit x y, false)
theorem foldl_remember (hit : α → β → Bool) (x : α) (ys : List β) (a : Bool) : ys.foldl (fun a y => (remember hit x y a).1) a = true ↔ a = true ∨ ∃ y ∈ ys, hit x y = true := by induction ys generalizing a with | nil => simp | cons y ys ih => rw [List.foldl_cons, ih] simp only [remember, Bool.or_eq_true, List.mem_cons] aesop
theorem matchFold_iff (key₁ : α → ℤ) (key₂ : β → ℤ) (hit : α → β → Bool) (xs : List α) (ys : List β) (a : Bool) : MatchFold.run key₁ key₂ (remember hit) xs ys a = true ↔ a = true ∨ ∃ x ∈ xs, ∃ y ∈ ys, key₁ x = key₂ y ∧ hit x y = true := by induction xs generalizing a with | nil => simp [MatchFold.run] | cons x xs ih => rw [MatchFold.run, ih, foldl_remember] simp only [List.mem_cons, List.mem_filter, decide_eq_true_eq] aesop
theorem matchFold_true (key₁ : α → ℤ) (key₂ : β → ℤ) (hit : α → β → Bool) (xs : List α) (ys : List β) : MatchFold.run key₁ key₂ (remember hit) xs ys true = true := (matchFold_iff key₁ key₂ hit xs ys true).mpr (Or.inl rfl)
/-- The actual finite-state join finds exactly the matching occurrencesaccepted by its pair predicate. The callback retains one Boolean word. -/theorem run_iff {σ₁ σ₂ : Type*} (read₁ : σ₁ → Option (α × σ₁)) (key₁ : α → ℤ) (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ) (hit : α → β → Bool) (view₁ : σ₁ → List α) (hread₁ : RowMerge.IsReader read₁ view₁) (view₂ : σ₂ → List β) (hread₂ : RowMerge.IsReader read₂ view₂) (B fuel₁ fuel₂ controlFuel : ℕ) (s₁ : σ₁) (s₂ : σ₂) (hsort₁ : (view₁ s₁).Pairwise (fun x y => key₁ x ≤ key₁ y)) (hsort₂ : (view₂ s₂).Pairwise (fun x y => key₂ x ≤ key₂ y)) (hcap₁ : (view₁ s₁).length ≤ fuel₁) (hcap₂ : (view₂ s₂).length ≤ fuel₂) (hfuel : (view₁ s₁).length + (view₂ s₂).length < controlFuel) : (StreamJoin.run read₁ key₁ read₂ key₂ (remember hit) B fuel₁ fuel₂ controlFuel s₁ s₂ false).user = true ↔ ∃ x ∈ view₁ s₁, ∃ y ∈ view₂ s₂, key₁ x = key₂ y ∧ hit x y = true := by rw [StreamJoin.run_complete read₁ key₁ read₂ key₂ (remember hit) (fun _ _ _ => rfl) view₁ hread₁ view₂ hread₂ B fuel₁ fuel₂ controlFuel s₁ s₂ false hsort₁ hsort₂ hcap₁ hcap₂ hfuel, matchFold_iff] simp
/-- An arbitrary stopped control prefix also has one-sided soundness. -/theorem stopped_sound {σ₁ σ₂ : Type*} (read₁ : σ₁ → Option (α × σ₁)) (key₁ : α → ℤ) (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ) (hit : α → β → Bool) (view₁ : σ₁ → List α) (hread₁ : RowMerge.IsReader read₁ view₁) (view₂ : σ₂ → List β) (hread₂ : RowMerge.IsReader read₂ view₂) (B fuel₁ fuel₂ controlFuel : ℕ) (s₁ : σ₁) (s₂ : σ₂) (hsort₁ : (view₁ s₁).Pairwise (fun x y => key₁ x ≤ key₁ y)) (hsort₂ : (view₂ s₂).Pairwise (fun x y => key₂ x ≤ key₂ y)) (hcap₁ : (view₁ s₁).length ≤ fuel₁) (hcap₂ : (view₂ s₂).length ≤ fuel₂) (hyes : (StreamJoin.run read₁ key₁ read₂ key₂ (remember hit) B fuel₁ fuel₂ controlFuel s₁ s₂ false).user = true) : ∃ x ∈ view₁ s₁, ∃ y ∈ view₂ s₂, key₁ x = key₂ y ∧ hit x y = true := by let out := StreamJoin.run read₁ key₁ read₂ key₂ (remember hit) B fuel₁ fuel₂ controlFuel s₁ s₂ false have hs := StreamJoin.runAcc_semantics read₁ key₁ read₂ key₂ (remember hit) (fun _ _ _ => rfl) view₁ hread₁ view₂ hread₂ B fuel₁ fuel₂ controlFuel (StreamJoin.start s₁ s₂ false) ⟨hsort₁, hsort₂, hcap₁, hcap₂⟩ change MatchFold.run key₁ key₂ (remember hit) (view₁ out.left) (view₂ out.right) out.user = MatchFold.run key₁ key₂ (remember hit) (view₁ s₁) (view₂ s₂) false at hs have ht : MatchFold.run key₁ key₂ (remember hit) (view₁ s₁) (view₂ s₂) false = true := by rw [← hs, hyes] exact matchFold_true key₁ key₂ hit _ _ exact (matchFold_iff key₁ key₂ hit _ _ false).mp ht |>.resolve_left (by decide)
end StreamWitnessend LowSpaceSubsetSum
end OAI123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131import OAI.Combinatorics.LowSpaceSubsetSum.Streams.PaddedRowsimport OAI.Combinatorics.LowSpaceSubsetSum.Streams.DistinctStreamCountimport OAI.Combinatorics.LowSpaceSubsetSum.Compression.CompressionDictionary
namespace OAI
/-! # Counting a mixer through a tournament of ordinary sum rows
Only the two half-mixer arrays and a tournament of constant-size cursorsare stored. The output lists in the proofs are views, not runtime fields.Sorting and counting use integer sums and require no modulus or real oracle.-/
namespace LowSpaceSubsetSum.SumReader
open scoped BigOperators
structure Row where left : ℤ position : ℕ
def read (ys : Array ℤ) (s : Row) : Option ((ℤ × ℤ) × Row) := if h : s.position < ys.size then some ((s.left, ys[s.position]), ⟨s.left, s.position + 1⟩) else none
def view (ys : Array ℤ) (s : Row) : List (ℤ × ℤ) := (ys.toList.drop s.position).map (fun y => (s.left, y))
theorem reader (ys : Array ℤ) : RowMerge.IsReader (read ys) (view ys) := by intro s by_cases h : s.position < ys.size · have hlist : s.position < ys.toList.length := by simpa using h simp only [read, dite_eq_left h, view] rw [List.drop_eq_getElem_cons hlist, List.map_cons] rfl · have he : ys.toList.drop s.position = [] := List.drop_eq_nil_iff.mpr (by simpa using Nat.le_of_not_gt h) simp [read, h, view, he]
def key (p : ℤ × ℤ) : ℤ := p.1 + p.2
def rows (xs : Array ℤ) : Array Row := xs.map (fun x => ⟨x, 0⟩)
theorem row_sorted (ys : Array ℤ) (hs : ys.toList.Pairwise (· ≤ ·)) (s : Row) : (view ys s).Pairwise (fun x y => key x ≤ key y) := by rw [view, List.pairwise_map] exact (hs.sublist (List.drop_sublist s.position ys.toList)).imp (fun h => by dsimp only [key]; omega)
abbrev State (xs ys : Array ℤ) := MergedReader.State key (PaddedRows.view (view ys)) (Nat.clog 2 xs.size)
def start (xs ys : Array ℤ) (hs : ys.toList.Pairwise (· ≤ ·)) : State xs ys := MergedReader.start key (PaddedRows.next (read ys)) (PaddedRows.view (view ys)) (PaddedRows.reader _ _ (reader ys)) (PaddedRows.rows (rows xs) (Nat.clog 2 xs.size)) (PaddedRows.rows_sorted _ _ _ key (fun s _ => row_sorted ys hs s))
def next (xs ys : Array ℤ) : State xs ys → Option ((ℤ × ℤ) × State xs ys) := MergedReader.next key (PaddedRows.next (read ys)) (PaddedRows.view (view ys)) (PaddedRows.reader _ _ (reader ys))
def output (xs ys : Array ℤ) : State xs ys → List (ℤ × ℤ) := MergedReader.output key (PaddedRows.next (read ys)) (PaddedRows.view (view ys))
theorem next_law (xs ys : Array ℤ) : RowMerge.IsReader (next xs ys) (output xs ys) := MergedReader.reader _ _ _ (PaddedRows.reader _ _ (reader ys))
theorem output_sorted (xs ys : Array ℤ) (s : State xs ys) : ((output xs ys s).map key).Pairwise (· ≤ ·) := by rw [List.pairwise_map] exact MergedReader.output_sorted _ _ _ (PaddedRows.reader _ _ (reader ys)) s
theorem start_bag (xs ys : Array ℤ) (hs : ys.toList.Pairwise (· ≤ ·)) : (output xs ys (start xs ys hs) : Multiset (ℤ × ℤ)) = ∑ i : Fin xs.size, ((ys.toList.map (fun y => (xs[i.val], y))) : Multiset (ℤ × ℤ)) := by rw [output, start, MergedReader.start_output_bag] calc _ = ∑ i : Fin (rows xs).size, (view ys (rows xs)[i.val] : Multiset (ℤ × ℤ)) := PaddedRows.row_bag (rows xs) (Nat.clog 2 xs.size) (by simpa [rows] using Nat.le_pow_clog (by decide : 1 < 2) xs.size) (view ys) _ = _ := by apply Fintype.sum_equiv (finCongr (show (rows xs).size = xs.size by simp [rows])) intro i simp only [rows, Array.getElem_map, view, List.drop_zero] rfl
theorem output_mem (xs ys : Array ℤ) (hs : ys.toList.Pairwise (· ≤ ·)) (p : ℤ × ℤ) : p ∈ output xs ys (start xs ys hs) ↔ p.1 ∈ xs.toList ∧ p.2 ∈ ys.toList := by change p ∈ (output xs ys (start xs ys hs) : Multiset (ℤ × ℤ)) ↔ _ rw [start_bag, Multiset.mem_sum] simp only [Finset.mem_univ, true_and, Multiset.mem_coe, List.mem_map] constructor · rintro ⟨i, y, hy, he⟩ obtain rfl := he exact ⟨List.mem_iff_getElem.mpr ⟨i.val, by simpa only [Array.length_toList] using i.isLt, by simp⟩, hy⟩ · rintro ⟨hx, hy⟩ obtain ⟨i, hi, he⟩ := List.mem_iff_getElem.mp hx refine ⟨⟨i, by simpa using hi⟩, p.2, hy, ?_⟩ simpa using congrArg (fun x => (x, p.2)) he
theorem output_length (xs ys : Array ℤ) (hs : ys.toList.Pairwise (· ≤ ·)) : (output xs ys (start xs ys hs)).length = xs.size * ys.size := by have h := congrArg Multiset.card (start_bag xs ys hs) simpa only [Multiset.coe_card, Multiset.card_sum, List.length_map, Array.length_toList, Finset.sum_const, Finset.card_univ, Fintype.card_fin, smul_eq_mul] using h
def count (xs ys : Array ℤ) (hs : ys.toList.Pairwise (· ≤ ·)) : ℕ × ℕ := DistinctStreamCount.run (next xs ys) key (xs.size * ys.size) (start xs ys hs)
theorem count_value (xs ys : Array ℤ) (hs : ys.toList.Pairwise (· ≤ ·)) : (count xs ys hs).1 = ((output xs ys (start xs ys hs)).map key).toFinset.card := DistinctStreamCount.run_value _ _ _ (next_law xs ys) _ _ (le_of_eq (output_length xs ys hs)) (output_sorted xs ys _)
theorem count_queries (xs ys : Array ℤ) (hs : ys.toList.Pairwise (· ≤ ·)) : (count xs ys hs).2 ≤ xs.size * ys.size := DistinctStreamCount.run_queries _ _ _ _
/-- Every cursor and cached front occupies a constant number of flat cells. -/def footprint (xs ys : Array ℤ) (s : State xs ys) : ℕ := xs.size + ys.size + 10 * (Tournament.nodes s.tree + 1) + 3
theorem footprint_bound (xs ys : Array ℤ) (s : State xs ys) : footprint xs ys s ≤ 41 * xs.size + ys.size + 43 := by have h := Tournament.padded_nodes_le xs.size s.tree unfold footprint omega
end LowSpaceSubsetSum.SumReader
end OAI123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172import OAI.Combinatorics.LowSpaceSubsetSum.Streams.MergeOrdering
namespace OAI
/-!# A bounded tie-group buffer
The tail-recursive collector stores at most the requested number of matchingoccurrences and leaves the first different-key occurrence unconsumed. Itsinstrumented query counter counts every reader call, including the finallookahead. No clearing of unused buffer positions is performed.-/
namespace LowSpaceSubsetSumnamespace TieBuffer
universe u v
variable {α : Type u} {σ : Type v}
def groupView (key : α → ℤ) (K : ℤ) (view : σ → List α) (s : σ) : List α := (view s).takeWhile (fun a => decide (key a = K))
structure Result (α : Type u) (σ : Type v) where buffer : Array α cursor : σ queries : ℕ
def fillAcc (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ) : ℕ → σ → Array α → ℕ → Result α σ | 0, s, buf, q => ⟨buf, s, q⟩ | k + 1, s, buf, q => match read s with | none => ⟨buf, s, q + 1⟩ | some (a, s') => if key a = K then fillAcc read key K k s' (buf.push a) (q + 1) else ⟨buf, s, q + 1⟩
def fill (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ) (B : ℕ) (s : σ) : Result α σ := fillAcc read key K B s #[] 0
theorem fillAcc_spec (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ) (view : σ → List α) (hread : RowMerge.IsReader read view) (fuel : ℕ) (s : σ) (buf : Array α) (q : ℕ) : (fillAcc read key K fuel s buf q).buffer.toList = buf.toList ++ (groupView key K view s).take fuel ∧ view s = (groupView key K view s).take fuel ++ view (fillAcc read key K fuel s buf q).cursor ∧ groupView key K view (fillAcc read key K fuel s buf q).cursor = (groupView key K view s).drop fuel ∧ (fillAcc read key K fuel s buf q).queries ≤ q + fuel := by induction fuel generalizing s buf q with | zero => simp [fillAcc] | succ fuel ih => have hr := hread s cases h : read s with | none => simp only [h] at hr simp [fillAcc, h, groupView, hr] | some z => rcases z with ⟨a, s'⟩ simp only [h] at hr by_cases ha : key a = K · have hg : groupView key K view s = a :: groupView key K view s' := by simp [groupView, hr, ha] have hi := ih s' (buf.push a) (q + 1) simp only [fillAcc, h, ite_eq_left ha] refine ⟨?_, ?_, ?_, ?_⟩ · rw [hi.1, hg] simp [List.append_assoc] · rw [hr, hi.2.1, hg] simp · rw [hi.2.2.1, hg] simp · have := hi.2.2.2 omega · have hg : groupView key K view s = [] := by simp [groupView, hr, ha] simp [fillAcc, h, ha, hg]
theorem fill_buffer (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ) (view : σ → List α) (hread : RowMerge.IsReader read view) (B : ℕ) (s : σ) : (fill read key K B s).buffer.toList = (groupView key K view s).take B := by simpa [fill] using (fillAcc_spec read key K view hread B s #[] 0).1
theorem fill_size_le (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ) (view : σ → List α) (hread : RowMerge.IsReader read view) (B : ℕ) (s : σ) : (fill read key K B s).buffer.size ≤ B := by have h := congrArg List.length (fill_buffer read key K view hread B s) simp only [Array.length_toList, List.length_take] at h omega
theorem fill_suffix (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ) (view : σ → List α) (hread : RowMerge.IsReader read view) (B : ℕ) (s : σ) : groupView key K view (fill read key K B s).cursor = (groupView key K view s).drop B := (fillAcc_spec read key K view hread B s #[] 0).2.2.1
theorem fill_queries_le (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ) (view : σ → List α) (hread : RowMerge.IsReader read view) (B : ℕ) (s : σ) : (fill read key K B s).queries ≤ B := by simpa [fill] using (fillAcc_spec read key K view hread B s #[] 0).2.2.2
/-- The collector reads each stored occurrence once and performs at mostone additional lookahead, irrespective of the chosen buffer capacity. -/theorem fillAcc_queries_le_potential (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ) (view : σ → List α) (hread : RowMerge.IsReader read view) (fuel : ℕ) (s : σ) (buf : Array α) (q : ℕ) : (fillAcc read key K fuel s buf q).queries ≤ q + min fuel ((groupView key K view s).length + 1) := by induction fuel generalizing s buf q with | zero => simp [fillAcc] | succ fuel ih => have hr := hread s cases h : read s with | none => simp only [h] at hr simp [fillAcc, h, groupView, hr] | some z => rcases z with ⟨x, s'⟩ simp only [h] at hr by_cases hx : key x = K · have hg : groupView key K view s = x :: groupView key K view s' := by simp [groupView, hr, hx] have hi := ih s' (buf.push x) (q + 1) simp only [fillAcc, h, ite_eq_left hx, hg, List.length_cons] omega · have hg : groupView key K view s = [] := by simp [groupView, hr, hx] simp [fillAcc, h, hx, hg]
theorem fill_queries_le_potential (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ) (view : σ → List α) (hread : RowMerge.IsReader read view) (B : ℕ) (s : σ) : (fill read key K B s).queries ≤ (groupView key K view s).length + 1 := by have h := fillAcc_queries_le_potential read key K view hread B s #[] 0 simp only [fill, zero_add] at h ⊢ exact h.trans (Nat.min_le_right _ _)
def hasKey (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ) (s : σ) : Bool := match read s with | none => false | some (a, _) => decide (key a = K)
theorem hasKey_iff (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ) (view : σ → List α) (hread : RowMerge.IsReader read view) (s : σ) : hasKey read key K s = true ↔ groupView key K view s ≠ [] := by have hr := hread s cases h : read s with | none => simp only [h] at hr simp [hasKey, h, groupView, hr] | some z => rcases z with ⟨a, s'⟩ simp only [h] at hr by_cases ha : key a = K <;> simp [hasKey, h, groupView, hr, ha]
/-- A snapshot is needed only if more than `B` second-row occurrences havethis key. In particular the buffer is full when a snapshot is taken. -/theorem long_group_full_buffer (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ) (view : σ → List α) (hread : RowMerge.IsReader read view) (B : ℕ) (s : σ) (hlong : hasKey read key K (fill read key K B s).cursor = true) : B < (groupView key K view s).length ∧ (fill read key K B s).buffer.size = B := by have hn := (hasKey_iff read key K view hread _).mp hlong rw [fill_suffix read key K view hread B s] at hn have hB : B < (groupView key K view s).length := by by_contra h apply hn exact List.drop_eq_nil_of_le (by omega) refine ⟨hB, ?_⟩ have h := congrArg List.length (fill_buffer read key K view hread B s) simpa only [Array.length_toList, List.length_take, Nat.min_eq_left hB.le] using h
end TieBufferend LowSpaceSubsetSum
end OAI123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298import OAI.Combinatorics.LowSpaceSubsetSum.Streams.JoinOne
namespace OAI
/-!# A stopped Cartesian tie-group join
A single second-stream prefix buffer and optional suffix snapshot serve everyfirst-stream occurrence with this key. Counters charge every attempted report,including executions halted inside either part of a replay. Lists occur onlyin the correctness specification.-/
namespace LowSpaceSubsetSumnamespace TieGroup
universe u v s t w
variable {α : Type u} {β : Type v} {σ₁ : Type s} {σ₂ : Type t} {τ : Type w}
structure State (σ₂ : Type t) (τ : Type w) where last : σ₂ user : τ queries : ℕ reports : ℕ restores : ℕ
def step (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ) (K : ℤ) (report : α → β → τ → τ × Bool) (buffer : Array β) (saved : σ₂) (long : Bool) (fuel₂ : ℕ) (x : α) (a : State σ₂ τ) : State σ₂ τ × Bool := let out := JoinOne.run read₂ key₂ K (report x) buffer saved long fuel₂ a.user (⟨out.cursor, out.state, a.queries + out.queries, a.reports + out.reports, a.restores + if long then 1 else 0⟩, out.halted)
structure Result (σ₁ : Type s) (σ₂ : Type t) (τ : Type w) where outer : TieReplay.Result σ₁ (State σ₂ τ) fillQueries : ℕ bufferSize : ℕ snapshot : Bool
def run (read₁ : σ₁ → Option (α × σ₁)) (key₁ : α → ℤ) (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ) (K : ℤ) (report : α → β → τ → τ × Bool) (B fuel₁ fuel₂ : ℕ) (s₁ : σ₁) (s₂ : σ₂) (a : τ) : Result σ₁ σ₂ τ := let filled := TieBuffer.fill read₂ key₂ K B s₂ let long := TieBuffer.hasKey read₂ key₂ K filled.cursor let out := TieReplay.run read₁ key₁ K (step read₂ key₂ K report filled.buffer filled.cursor long fuel₂) fuel₁ s₁ ⟨filled.cursor, a, 0, 0, 0⟩ ⟨out, filled.queries, filled.buffer.size, long && TieBuffer.hasKey read₁ key₁ K s₁⟩
/-- Bounds on callbacks follow from the actual suffix reporter, not fromassumed trial or implementation bounds. -/theorem step_bounds (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ) (K : ℤ) (report : α → β → τ → τ × Bool) (view₂ : σ₂ → List β) (hread₂ : RowMerge.IsReader read₂ view₂) (buffer : Array β) (saved : σ₂) (long : Bool) (fuel₂ : ℕ) (x : α) (a : State σ₂ τ) : (step read₂ key₂ K report buffer saved long fuel₂ x a).1.reports ≤ a.reports + (buffer.size + (TieBuffer.groupView key₂ K view₂ saved).length) ∧ (step read₂ key₂ K report buffer saved long fuel₂ x a).1.queries ≤ a.queries + (buffer.size + (TieBuffer.groupView key₂ K view₂ saved).length + 1) ∧ (step read₂ key₂ K report buffer saved long fuel₂ x a).1.restores ≤ a.restores + 1 := by have hr := JoinOne.reports_le read₂ key₂ K (report x) view₂ hread₂ buffer saved long fuel₂ a.user have hq := JoinOne.queries_le read₂ key₂ K (report x) view₂ hread₂ buffer saved long fuel₂ a.user dsimp only [step] refine ⟨Nat.add_le_add_left hr _, Nat.add_le_add_left hq _, ?_⟩ split <;> omega
theorem run_bounds (read₁ : σ₁ → Option (α × σ₁)) (key₁ : α → ℤ) (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ) (K : ℤ) (report : α → β → τ → τ × Bool) (view₁ : σ₁ → List α) (hread₁ : RowMerge.IsReader read₁ view₁) (view₂ : σ₂ → List β) (hread₂ : RowMerge.IsReader read₂ view₂) (B fuel₁ fuel₂ : ℕ) (s₁ : σ₁) (s₂ : σ₂) (a : τ) : (run read₁ key₁ read₂ key₂ K report B fuel₁ fuel₂ s₁ s₂ a).outer.state.reports ≤ (TieBuffer.groupView key₁ K view₁ s₁).length * (TieBuffer.groupView key₂ K view₂ s₂).length ∧ (run read₁ key₁ read₂ key₂ K report B fuel₁ fuel₂ s₁ s₂ a).outer.state.queries ≤ (TieBuffer.groupView key₁ K view₁ s₁).length * ((TieBuffer.groupView key₂ K view₂ s₂).length + 1) ∧ (run read₁ key₁ read₂ key₂ K report B fuel₁ fuel₂ s₁ s₂ a).outer.state.restores ≤ (TieBuffer.groupView key₁ K view₁ s₁).length := by let filled := TieBuffer.fill read₂ key₂ K B s₂ let long := TieBuffer.hasKey read₂ key₂ K filled.cursor let N := (TieBuffer.groupView key₂ K view₂ s₂).length let P := fun (st : State σ₂ τ) (r : ℕ) => st.reports ≤ r * N ∧ st.queries ≤ r * (N + 1) ∧ st.restores ≤ r have hsplit : filled.buffer.size + (TieBuffer.groupView key₂ K view₂ filled.cursor).length = N := by have hb := congrArg List.length (TieBuffer.fill_buffer read₂ key₂ K view₂ hread₂ B s₂) rw [TieBuffer.fill_suffix read₂ key₂ K view₂ hread₂ B s₂] simp only [Array.length_toList, List.length_take] at hb simp only [List.length_drop] dsimp only [filled, N] omega have hstep : ∀ x st r, P st r → P (step read₂ key₂ K report filled.buffer filled.cursor long fuel₂ x st).1 (r + 1) := by intro x st r hr have h := step_bounds read₂ key₂ K report view₂ hread₂ filled.buffer filled.cursor long fuel₂ x st rw [hsplit] at h dsimp only [P] at hr ⊢ rcases hr with ⟨hr, hq, hc⟩ rcases h with ⟨hr', hq', hc'⟩ rw [Nat.add_mul, Nat.add_mul] simp only [one_mul] exact ⟨hr'.trans (Nat.add_le_add_right hr _), hq'.trans (Nat.add_le_add_right hq _), by omega⟩ have h := TieReplay.run_preserves read₁ key₁ K (step read₂ key₂ K report filled.buffer filled.cursor long fuel₂) P hstep fuel₁ s₁ ⟨filled.cursor, a, 0, 0, 0⟩ (by simp [P]) have hr := TieReplay.run_reports_le_potential read₁ key₁ K (step read₂ key₂ K report filled.buffer filled.cursor long fuel₂) view₁ hread₁ fuel₁ s₁ ⟨filled.cursor, a, 0, 0, 0⟩ dsimp only [P] at h refine ⟨h.1.trans (Nat.mul_le_mul_right N hr), h.2.1.trans (Nat.mul_le_mul_right (N + 1) hr), h.2.2.trans hr⟩
/-- On a continuing run every occurrence in the Cartesian tie group isreported, in first-stream order and then second-stream order. -/theorem state_complete (read₁ : σ₁ → Option (α × σ₁)) (key₁ : α → ℤ) (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ) (K : ℤ) (report : α → β → τ → τ × Bool) (hreport : ∀ x y a, (report x y a).2 = false) (view₁ : σ₁ → List α) (hread₁ : RowMerge.IsReader read₁ view₁) (view₂ : σ₂ → List β) (hread₂ : RowMerge.IsReader read₂ view₂) (B fuel₁ fuel₂ : ℕ) (s₁ : σ₁) (s₂ : σ₂) (a : τ) (hfuel₁ : (TieBuffer.groupView key₁ K view₁ s₁).length ≤ fuel₁) (hfuel₂ : (TieBuffer.groupView key₂ K view₂ s₂).length ≤ fuel₂) : (run read₁ key₁ read₂ key₂ K report B fuel₁ fuel₂ s₁ s₂ a).outer.state.user = (TieBuffer.groupView key₁ K view₁ s₁).foldl (fun a x => (TieBuffer.groupView key₂ K view₂ s₂).foldl (fun a y => (report x y a).1) a) a := by let filled := TieBuffer.fill read₂ key₂ K B s₂ let long := TieBuffer.hasKey read₂ key₂ K filled.cursor let f := step read₂ key₂ K report filled.buffer filled.cursor long fuel₂ have hnonhalt : ∀ x st, (f x st).2 = false := by intro x st exact JoinOne.halted_false read₂ key₂ K (report x) (hreport x) filled.buffer filled.cursor long fuel₂ st.user have huser : ∀ x st, (f x st).1.user = (TieBuffer.groupView key₂ K view₂ s₂).foldl (fun a y => (report x y a).1) st.user := by intro x st exact JoinOne.filled_state_complete read₂ key₂ K (report x) (hreport x) view₂ hread₂ B fuel₂ s₂ st.user hfuel₂ have h := TieReplay.run_state_complete read₁ key₁ K f hnonhalt view₁ hread₁ fuel₁ s₁ (⟨filled.cursor, a, 0, 0, 0⟩ : State σ₂ τ) hfuel₁ change (TieReplay.run read₁ key₁ K f fuel₁ s₁ _).state.user = _ rw [h] exact (List.foldl_hom State.user (g₁ := fun st x => (f x st).1) (fun st x => (huser x st).symm)).symm
theorem step_halted_false (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ) (K : ℤ) (report : α → β → τ → τ × Bool) (hreport : ∀ x y a, (report x y a).2 = false) (buffer : Array β) (saved : σ₂) (long : Bool) (fuel₂ : ℕ) (x : α) (a : State σ₂ τ) : (step read₂ key₂ K report buffer saved long fuel₂ x a).2 = false := JoinOne.halted_false read₂ key₂ K (report x) (hreport x) buffer saved long fuel₂ a.user
theorem halted_false (read₁ : σ₁ → Option (α × σ₁)) (key₁ : α → ℤ) (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ) (K : ℤ) (report : α → β → τ → τ × Bool) (hreport : ∀ x y a, (report x y a).2 = false) (B fuel₁ fuel₂ : ℕ) (s₁ : σ₁) (s₂ : σ₂) (a : τ) : (run read₁ key₁ read₂ key₂ K report B fuel₁ fuel₂ s₁ s₂ a).outer.halted = false := TieReplay.run_halted_false read₁ key₁ K _ (step_halted_false read₂ key₂ K report hreport _ _ _ _) _ _ _
/-- Both generator cursors end immediately after this key, so a surroundingmerge join can continue without losing its next different-key occurrences. -/theorem views_complete (read₁ : σ₁ → Option (α × σ₁)) (key₁ : α → ℤ) (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ) (K : ℤ) (report : α → β → τ → τ × Bool) (hreport : ∀ x y a, (report x y a).2 = false) (view₁ : σ₁ → List α) (hread₁ : RowMerge.IsReader read₁ view₁) (view₂ : σ₂ → List β) (hread₂ : RowMerge.IsReader read₂ view₂) (B fuel₁ fuel₂ : ℕ) (s₁ : σ₁) (s₂ : σ₂) (a : τ) (hfuel₁ : (TieBuffer.groupView key₁ K view₁ s₁).length ≤ fuel₁) (hfuel₂ : (TieBuffer.groupView key₂ K view₂ s₂).length ≤ fuel₂) (hne : TieBuffer.groupView key₁ K view₁ s₁ ≠ []) : view₁ s₁ = TieBuffer.groupView key₁ K view₁ s₁ ++ view₁ (run read₁ key₁ read₂ key₂ K report B fuel₁ fuel₂ s₁ s₂ a).outer.cursor ∧ view₂ s₂ = TieBuffer.groupView key₂ K view₂ s₂ ++ view₂ (run read₁ key₁ read₂ key₂ K report B fuel₁ fuel₂ s₁ s₂ a).outer.state.last := by let filled := TieBuffer.fill read₂ key₂ K B s₂ let long := TieBuffer.hasKey read₂ key₂ K filled.cursor let f := step read₂ key₂ K report filled.buffer filled.cursor long fuel₂ have hnonhalt : ∀ x st, (f x st).2 = false := step_halted_false read₂ key₂ K report hreport filled.buffer filled.cursor long fuel₂ have hspec := TieReplay.runAcc_nonhalting_spec read₁ key₁ K f hnonhalt view₁ hread₁ fuel₁ s₁ (⟨filled.cursor, a, 0, 0, 0⟩ : State σ₂ τ) 0 0 have hfirst : view₁ s₁ = TieBuffer.groupView key₁ K view₁ s₁ ++ view₁ (run read₁ key₁ read₂ key₂ K report B fuel₁ fuel₂ s₁ s₂ a).outer.cursor := by simpa only [run, TieReplay.run, f, long, filled, List.take_of_length_le hfuel₁] using hspec.2.2.2 refine ⟨hfirst, ?_⟩ let P := fun (st : State σ₂ τ) (r : ℕ) => r = 0 ∨ view₂ s₂ = TieBuffer.groupView key₂ K view₂ s₂ ++ view₂ st.last have hstep : ∀ x st r, P st r → P (f x st).1 (r + 1) := by intro x st r _ exact Or.inr (JoinOne.filled_view_complete read₂ key₂ K (report x) (hreport x) view₂ hread₂ B fuel₂ s₂ st.user hfuel₂) have hP := TieReplay.run_preserves read₁ key₁ K f P hstep fuel₁ s₁ (⟨filled.cursor, a, 0, 0, 0⟩ : State σ₂ τ) (Or.inl rfl) have hcount : (run read₁ key₁ read₂ key₂ K report B fuel₁ fuel₂ s₁ s₂ a).outer.reports = (TieBuffer.groupView key₁ K view₁ s₁).length := by simpa only [run, TieReplay.run, f, long, filled, Nat.zero_add, Nat.min_eq_right hfuel₁] using hspec.2.1 change (run read₁ key₁ read₂ key₂ K report B fuel₁ fuel₂ s₁ s₂ a).outer.reports = 0 ∨ _ at hP rcases hP with hz | hP · rw [hcount] at hz exact False.elim (hne (List.length_eq_zero_iff.mp hz)) · exact hP
theorem query_bound (read₁ : σ₁ → Option (α × σ₁)) (key₁ : α → ℤ) (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ) (K : ℤ) (report : α → β → τ → τ × Bool) (view₁ : σ₁ → List α) (hread₁ : RowMerge.IsReader read₁ view₁) (view₂ : σ₂ → List β) (hread₂ : RowMerge.IsReader read₂ view₂) (B fuel₁ fuel₂ : ℕ) (s₁ : σ₁) (s₂ : σ₂) (a : τ) : (run read₁ key₁ read₂ key₂ K report B fuel₁ fuel₂ s₁ s₂ a).outer.queries + (run read₁ key₁ read₂ key₂ K report B fuel₁ fuel₂ s₁ s₂ a).fillQueries + (run read₁ key₁ read₂ key₂ K report B fuel₁ fuel₂ s₁ s₂ a).outer.state.queries ≤ 2 * (TieBuffer.groupView key₁ K view₁ s₁).length + (TieBuffer.groupView key₂ K view₂ s₂).length + (TieBuffer.groupView key₁ K view₁ s₁).length * (TieBuffer.groupView key₂ K view₂ s₂).length + 2 := by have hq := (run_bounds read₁ key₁ read₂ key₂ K report view₁ hread₁ view₂ hread₂ B fuel₁ fuel₂ s₁ s₂ a).2.1 have hf := TieBuffer.fill_queries_le_potential read₂ key₂ K view₂ hread₂ B s₂ have ho := TieReplay.run_queries_le_potential read₁ key₁ K (step read₂ key₂ K report (TieBuffer.fill read₂ key₂ K B s₂).buffer (TieBuffer.fill read₂ key₂ K B s₂).cursor (TieBuffer.hasKey read₂ key₂ K (TieBuffer.fill read₂ key₂ K B s₂).cursor) fuel₂) view₁ hread₁ fuel₁ s₁ ⟨(TieBuffer.fill read₂ key₂ K B s₂).cursor, a, 0, 0, 0⟩ change (run read₁ key₁ read₂ key₂ K report B fuel₁ fuel₂ s₁ s₂ a).outer.queries ≤ _ at ho change (run read₁ key₁ read₂ key₂ K report B fuel₁ fuel₂ s₁ s₂ a).fillQueries ≤ _ at hf nlinarith
theorem bufferSize_le (read₁ : σ₁ → Option (α × σ₁)) (key₁ : α → ℤ) (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ) (K : ℤ) (report : α → β → τ → τ × Bool) (view₂ : σ₂ → List β) (hread₂ : RowMerge.IsReader read₂ view₂) (B fuel₁ fuel₂ : ℕ) (s₁ : σ₁) (s₂ : σ₂) (a : τ) : (run read₁ key₁ read₂ key₂ K report B fuel₁ fuel₂ s₁ s₂ a).bufferSize ≤ B := TieBuffer.fill_size_le read₂ key₂ K view₂ hread₂ B s₂
/-- Without a long suffix, there are no generator restores. -/theorem restores_eq_zero_of_short (read₁ : σ₁ → Option (α × σ₁)) (key₁ : α → ℤ) (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ) (K : ℤ) (report : α → β → τ → τ × Bool) (B fuel₁ fuel₂ : ℕ) (s₁ : σ₁) (s₂ : σ₂) (a : τ) (hshort : TieBuffer.hasKey read₂ key₂ K (TieBuffer.fill read₂ key₂ K B s₂).cursor = false) : (run read₁ key₁ read₂ key₂ K report B fuel₁ fuel₂ s₁ s₂ a).outer.state.restores = 0 := by dsimp only [run] apply TieReplay.run_preserves read₁ key₁ K _ (fun (st : State σ₂ τ) (_ : ℕ) => st.restores = 0) _ _ _ _ rfl intro x st r hst simpa only [step, hshort, Bool.false_eq_true, ite_false, Nat.add_zero] using hst
/-- Every snapshot/restore is charged to potential partners, includingpartners not reached when the execution halts. -/theorem copies_charged (read₁ : σ₁ → Option (α × σ₁)) (key₁ : α → ℤ) (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ) (K : ℤ) (report : α → β → τ → τ × Bool) (view₁ : σ₁ → List α) (hread₁ : RowMerge.IsReader read₁ view₁) (view₂ : σ₂ → List β) (hread₂ : RowMerge.IsReader read₂ view₂) (B fuel₁ fuel₂ : ℕ) (s₁ : σ₁) (s₂ : σ₂) (a : τ) : B * ((if (run read₁ key₁ read₂ key₂ K report B fuel₁ fuel₂ s₁ s₂ a).snapshot then 1 else 0) + (run read₁ key₁ read₂ key₂ K report B fuel₁ fuel₂ s₁ s₂ a).outer.state.restores) ≤ 2 * ((TieBuffer.groupView key₁ K view₁ s₁).length * (TieBuffer.groupView key₂ K view₂ s₂).length) := by have hc := (run_bounds read₁ key₁ read₂ key₂ K report view₁ hread₁ view₂ hread₂ B fuel₁ fuel₂ s₁ s₂ a).2.2 by_cases hl : TieBuffer.hasKey read₂ key₂ K (TieBuffer.fill read₂ key₂ K B s₂).cursor = true · have hB := (TieBuffer.long_group_full_buffer read₂ key₂ K view₂ hread₂ B s₂ hl).1.le by_cases hfirst : TieBuffer.hasKey read₁ key₁ K s₁ = true · have hpos : 0 < (TieBuffer.groupView key₁ K view₁ s₁).length := List.length_pos_iff.mpr ((TieBuffer.hasKey_iff read₁ key₁ K view₁ hread₁ s₁).mp hfirst) have hs : (run read₁ key₁ read₂ key₂ K report B fuel₁ fuel₂ s₁ s₂ a).snapshot = true := by simp [run, hl, hfirst] simp only [hs, ↓reduceIte] calc B * (1 + _) ≤ B * (2 * (TieBuffer.groupView key₁ K view₁ s₁).length) := by apply Nat.mul_le_mul_left omega _ ≤ (TieBuffer.groupView key₂ K view₂ s₂).length * (2 * (TieBuffer.groupView key₁ K view₁ s₁).length) := Nat.mul_le_mul_right _ hB _ = _ := by ring · have he : TieBuffer.groupView key₁ K view₁ s₁ = [] := by by_contra he exact hfirst ((TieBuffer.hasKey_iff read₁ key₁ K view₁ hread₁ s₁).mpr he) have hs : (run read₁ key₁ read₂ key₂ K report B fuel₁ fuel₂ s₁ s₂ a).snapshot = false := by simp [run, Bool.eq_false_iff.mpr hfirst] rw [he, List.length_nil] at hc ⊢ simp [hs, Nat.eq_zero_of_le_zero hc] · have hshort := Bool.eq_false_iff.mpr hl have hz := restores_eq_zero_of_short read₁ key₁ read₂ key₂ K report B fuel₁ fuel₂ s₁ s₂ a hshort have hs : (run read₁ key₁ read₂ key₂ K report B fuel₁ fuel₂ s₁ s₂ a).snapshot = false := by simp [run, hshort] simp [hs, hz]
end TieGroupend LowSpaceSubsetSum
end OAI123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239import OAI.Combinatorics.LowSpaceSubsetSum.Streams.TieBuffer
namespace OAI
/-!# Bounded replay of one tie suffix
The reporter can stop after any matching occurrence. The replay retainsonly its cursor, callback state, counters, and fixed key. Its recursion istail recursion. All attempted reports are bounded by the complete suffixlength, even if the callback or fuel stops execution early.-/
namespace LowSpaceSubsetSumnamespace TieReplay
universe u v w
variable {α : Type u} {σ : Type v} {τ : Type w}
structure Result (σ : Type v) (τ : Type w) where cursor : σ state : τ queries : ℕ reports : ℕ complete : Bool halted : Bool
def runAcc (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ) (report : α → τ → τ × Bool) : ℕ → σ → τ → ℕ → ℕ → Result σ τ | 0, s, a, q, r => ⟨s, a, q, r, false, false⟩ | fuel + 1, s, a, q, r => match read s with | none => ⟨s, a, q + 1, r, true, false⟩ | some (x, s') => if key x = K then let out := report x a if out.2 then ⟨s', out.1, q + 1, r + 1, false, true⟩ else runAcc read key K report fuel s' out.1 (q + 1) (r + 1) else ⟨s, a, q + 1, r, true, false⟩
def run (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ) (report : α → τ → τ × Bool) (fuel : ℕ) (s : σ) (a : τ) : Result σ τ := runAcc read key K report fuel s a 0 0
theorem runAcc_bounds (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ) (report : α → τ → τ × Bool) (view : σ → List α) (hread : RowMerge.IsReader read view) (fuel : ℕ) (s : σ) (a : τ) (q r : ℕ) : (runAcc read key K report fuel s a q r).queries ≤ q + fuel ∧ r ≤ (runAcc read key K report fuel s a q r).reports ∧ (runAcc read key K report fuel s a q r).reports ≤ r + min fuel (TieBuffer.groupView key K view s).length := by induction fuel generalizing s a q r with | zero => simp [runAcc] | succ fuel ih => have hr := hread s cases h : read s with | none => simp only [h] at hr simp [runAcc, h, TieBuffer.groupView, hr] | some z => rcases z with ⟨x, s'⟩ simp only [h] at hr by_cases hx : key x = K · have hg : TieBuffer.groupView key K view s = x :: TieBuffer.groupView key K view s' := by simp [TieBuffer.groupView, hr, hx] simp only [runAcc, h, ite_eq_left hx] split · simp only [hg, List.length_cons] omega · have hi := ih s' (report x a).1 (q + 1) (r + 1) simp only [hg, List.length_cons] omega · have hg : TieBuffer.groupView key K view s = [] := by simp [TieBuffer.groupView, hr, hx] simp [runAcc, h, hx, hg]
theorem run_queries_le (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ) (report : α → τ → τ × Bool) (view : σ → List α) (hread : RowMerge.IsReader read view) (fuel : ℕ) (s : σ) (a : τ) : (run read key K report fuel s a).queries ≤ fuel := by simpa [run] using (runAcc_bounds read key K report view hread fuel s a 0 0).1
theorem run_reports_le_potential (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ) (report : α → τ → τ × Bool) (view : σ → List α) (hread : RowMerge.IsReader read view) (fuel : ℕ) (s : σ) (a : τ) : (run read key K report fuel s a).reports ≤ (TieBuffer.groupView key K view s).length := by have h := (runAcc_bounds read key K report view hread fuel s a 0 0).2.2 simp only [run, zero_add] at h ⊢ exact h.trans (Nat.min_le_right _ _)
/-- The one final lookahead is the only read not charged to a reportableoccurrence, even when the fuel is much larger than the tie group. -/theorem runAcc_queries_le_potential (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ) (report : α → τ → τ × Bool) (view : σ → List α) (hread : RowMerge.IsReader read view) (fuel : ℕ) (s : σ) (a : τ) (q r : ℕ) : (runAcc read key K report fuel s a q r).queries ≤ q + min fuel ((TieBuffer.groupView key K view s).length + 1) := by induction fuel generalizing s a q r with | zero => simp [runAcc] | succ fuel ih => have hr := hread s cases h : read s with | none => simp only [h] at hr simp [runAcc, h, TieBuffer.groupView, hr] | some z => rcases z with ⟨x, s'⟩ simp only [h] at hr by_cases hx : key x = K · have hg : TieBuffer.groupView key K view s = x :: TieBuffer.groupView key K view s' := by simp [TieBuffer.groupView, hr, hx] simp only [runAcc, h, ite_eq_left hx, hg, List.length_cons] split · dsimp only omega · have hi := ih s' (report x a).1 (q + 1) (r + 1) omega · have hg : TieBuffer.groupView key K view s = [] := by simp [TieBuffer.groupView, hr, hx] simp [runAcc, h, hx, hg]
theorem run_queries_le_potential (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ) (report : α → τ → τ × Bool) (view : σ → List α) (hread : RowMerge.IsReader read view) (fuel : ℕ) (s : σ) (a : τ) : (run read key K report fuel s a).queries ≤ (TieBuffer.groupView key K view s).length + 1 := by have h := runAcc_queries_le_potential read key K report view hread fuel s a 0 0 simp only [run, zero_add] at h ⊢ exact h.trans (Nat.min_le_right _ _)
theorem runAcc_halted_false (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ) (report : α → τ → τ × Bool) (hreport : ∀ x a, (report x a).2 = false) (fuel : ℕ) (s : σ) (a : τ) (q r : ℕ) : (runAcc read key K report fuel s a q r).halted = false := by induction fuel generalizing s a q r with | zero => rfl | succ fuel ih => cases h : read s with | none => simp [runAcc, h] | some z => rcases z with ⟨x, s'⟩ by_cases hx : key x = K · simp only [runAcc, h, ite_eq_left hx, hreport, Bool.false_eq_true, ite_false] exact ih _ _ _ _ · simp [runAcc, h, hx]
theorem run_halted_false (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ) (report : α → τ → τ × Bool) (hreport : ∀ x a, (report x a).2 = false) (fuel : ℕ) (s : σ) (a : τ) : (run read key K report fuel s a).halted = false := runAcc_halted_false read key K report hreport fuel s a 0 0
/-- A callback invariant can depend on the exact number of reports. Thisalso applies to executions stopped by the callback or by the fuel. -/theorem runAcc_preserves (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ) (report : α → τ → τ × Bool) (P : τ → ℕ → Prop) (hstep : ∀ x a r, P a r → P (report x a).1 (r + 1)) (fuel : ℕ) (s : σ) (a : τ) (q r : ℕ) (ha : P a r) : P (runAcc read key K report fuel s a q r).state (runAcc read key K report fuel s a q r).reports := by induction fuel generalizing s a q r with | zero => exact ha | succ fuel ih => cases h : read s with | none => simpa only [runAcc, h] using ha | some z => rcases z with ⟨x, s'⟩ by_cases hx : key x = K · simp only [runAcc, h, ite_eq_left hx] split · exact hstep x a r ha · exact ih s' (report x a).1 (q + 1) (r + 1) (hstep x a r ha) · simpa only [runAcc, h, ite_eq_right hx] using ha
theorem run_preserves (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ) (report : α → τ → τ × Bool) (P : τ → ℕ → Prop) (hstep : ∀ x a r, P a r → P (report x a).1 (r + 1)) (fuel : ℕ) (s : σ) (a : τ) (ha : P a 0) : P (run read key K report fuel s a).state (run read key K report fuel s a).reports := runAcc_preserves read key K report P hstep fuel s a 0 0 ha
/-- If reporting continues, replay processes exactly the requested prefixof the tie suffix and leaves every following occurrence untouched. -/theorem runAcc_nonhalting_spec (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ) (report : α → τ → τ × Bool) (hreport : ∀ x a, (report x a).2 = false) (view : σ → List α) (hread : RowMerge.IsReader read view) (fuel : ℕ) (s : σ) (a : τ) (q r : ℕ) : (runAcc read key K report fuel s a q r).state = ((TieBuffer.groupView key K view s).take fuel).foldl (fun a x => (report x a).1) a ∧ (runAcc read key K report fuel s a q r).reports = r + min fuel (TieBuffer.groupView key K view s).length ∧ TieBuffer.groupView key K view (runAcc read key K report fuel s a q r).cursor = (TieBuffer.groupView key K view s).drop fuel ∧ view s = (TieBuffer.groupView key K view s).take fuel ++ view (runAcc read key K report fuel s a q r).cursor := by induction fuel generalizing s a q r with | zero => simp [runAcc] | succ fuel ih => have hr := hread s cases h : read s with | none => simp only [h] at hr simp [runAcc, h, TieBuffer.groupView, hr] | some z => rcases z with ⟨x, s'⟩ simp only [h] at hr by_cases hx : key x = K · have hg : TieBuffer.groupView key K view s = x :: TieBuffer.groupView key K view s' := by simp [TieBuffer.groupView, hr, hx] have hi := ih s' (report x a).1 (q + 1) (r + 1) simp only [runAcc, h, ite_eq_left hx, hreport, Bool.false_eq_true, ite_false] refine ⟨?_, ?_, ?_, ?_⟩ · rw [hi.1, hg] simp · rw [hi.2.1, hg] simp only [List.length_cons] omega · rw [hi.2.2.1, hg] simp · rw [hr, hi.2.2.2, hg] simp · have hg : TieBuffer.groupView key K view s = [] := by simp [TieBuffer.groupView, hr, hx] simp [runAcc, h, hx, hg]
theorem run_state_complete (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ) (report : α → τ → τ × Bool) (hreport : ∀ x a, (report x a).2 = false) (view : σ → List α) (hread : RowMerge.IsReader read view) (fuel : ℕ) (s : σ) (a : τ) (hfuel : (TieBuffer.groupView key K view s).length ≤ fuel) : (run read key K report fuel s a).state = (TieBuffer.groupView key K view s).foldl (fun a x => (report x a).1) a := by have h := (runAcc_nonhalting_spec read key K report hreport view hread fuel s a 0 0).1 simpa [run, List.take_of_length_le hfuel] using h
end TieReplayend LowSpaceSubsetSum
end OAI123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281import Mathlib.Data.Fin.Tuple.Basicimport Mathlib.Data.List.Basicimport Mathlib.Data.Nat.Logimport Mathlib.Tactic
namespace OAI
/-!# Cached tournament for merging row fronts
Each leaf holds at most one current occurrence of a row. Internal nodescache the smaller child winner. Reading the winner is constant time;replacing one leaf recomputes just its root path. The candidate list belowis an analysis view and is never stored in the tournament.-/
namespace LowSpaceSubsetSumnamespace Tournament
universe u
variable {α : Type u}
def pick (key : α → ℤ) : Option α → Option α → Option α | none, v => v | u, none => u | some x, some y => if key x ≤ key y then some x else some y
theorem pick_member (key : α → ℤ) (u v : Option α) {x : α} (h : pick key u v = some x) : u = some x ∨ v = some x := by cases u with | none => exact Or.inr h | some a => cases v with | none => exact Or.inl h | some b => by_cases hab : key a ≤ key b · exact Or.inl (by simpa [pick, hab] using h) · exact Or.inr (by simpa [pick, hab] using h)
theorem pick_le_left (key : α → ℤ) (a : α) (v : Option α) : ∃ x, pick key (some a) v = some x ∧ key x ≤ key a := by cases v with | none => exact ⟨a, rfl, le_rfl⟩ | some b => by_cases hab : key a ≤ key b · exact ⟨a, by simp [pick, hab], le_rfl⟩ · exact ⟨b, by simp [pick, hab], (not_le.mp hab).le⟩
theorem pick_le_right (key : α → ℤ) (u : Option α) (b : α) : ∃ x, pick key u (some b) = some x ∧ key x ≤ key b := by cases u with | none => exact ⟨b, rfl, le_rfl⟩ | some a => by_cases hab : key a ≤ key b · exact ⟨a, by simp [pick, hab], hab⟩ · exact ⟨b, by simp [pick, hab], le_rfl⟩
def Best (key : α → ℤ) (v : Option α) (xs : List α) : Prop := (∀ x, v = some x → x ∈ xs) ∧ (∀ y ∈ xs, ∃ x, v = some x ∧ key x ≤ key y)
theorem best_append (key : α → ℤ) {u v : Option α} {xs ys : List α} (hu : Best key u xs) (hv : Best key v ys) : Best key (pick key u v) (xs ++ ys) := by constructor · intro x hx rcases pick_member key u v hx with hx | hx · exact List.mem_append_left _ (hu.1 x hx) · exact List.mem_append_right _ (hv.1 x hx) · intro y hy rcases List.mem_append.mp hy with hy | hy · obtain ⟨z, hz, hzy⟩ := hu.2 y hy obtain ⟨x, hx, hxz⟩ := pick_le_left key z v rw [← hz] at hx exact ⟨x, hx, hxz.trans hzy⟩ · obtain ⟨z, hz, hzy⟩ := hv.2 y hy obtain ⟨x, hx, hxz⟩ := pick_le_right key u z rw [← hz] at hx exact ⟨x, hx, hxz.trans hzy⟩
inductive Tree (α : Type u) : ℕ → Type u | leaf (value : Option α) : Tree α 0 | node {d : ℕ} (winner : Option α) (left right : Tree α d) : Tree α (d + 1)
def winner {d : ℕ} : Tree α d → Option α | .leaf v => v | .node v _ _ => v
def candidates {d : ℕ} : Tree α d → List α | .leaf v => v.toList | .node _ l r => candidates l ++ candidates r
def Valid (key : α → ℤ) {d : ℕ} : Tree α d → Prop | .leaf _ => True | .node v l r => v = pick key (winner l) (winner r) ∧ Valid key l ∧ Valid key r
def node (key : α → ℤ) {d : ℕ} (l r : Tree α d) : Tree α (d + 1) := .node (pick key (winner l) (winner r)) l r
theorem winner_best (key : α → ℤ) {d : ℕ} (t : Tree α d) (ht : Valid key t) : Best key (winner t) (candidates t) := by induction t with | leaf v => cases v <;> simp [winner, candidates, Best] | node v l r ihl ihr => obtain ⟨hv, hl, hr⟩ := ht change Best key v (candidates l ++ candidates r) rw [hv] exact best_append key (ihl hl) (ihr hr)
theorem winner_none_iff (key : α → ℤ) {d : ℕ} (t : Tree α d) (ht : Valid key t) : winner t = none ↔ candidates t = [] := by have hb := winner_best key t ht constructor · intro hn apply List.eq_nil_iff_forall_not_mem.mpr intro y hy obtain ⟨x, hx, _⟩ := hb.2 y hy simp [hn] at hx · intro hn cases hw : winner t with | none => rfl | some x => simpa [hn] using hb.1 x hw
def lookup : {d : ℕ} → Tree α d → (Fin d → Bool) → Option α | 0, .leaf v, _ => v | _d + 1, .node _ l r, path => if path 0 then lookup r (fun i => path i.succ) else lookup l (fun i => path i.succ)
def replace (key : α → ℤ) : {d : ℕ} → Tree α d → (Fin d → Bool) → Option α → Tree α d | 0, .leaf _, _, v => .leaf v | _d + 1, .node _ l r, path, v => if path 0 then node key l (replace key r (fun i => path i.succ) v) else node key (replace key l (fun i => path i.succ) v) r
theorem replace_valid (key : α → ℤ) {d : ℕ} (t : Tree α d) (ht : Valid key t) (path : Fin d → Bool) (v : Option α) : Valid key (replace key t path v) := by induction t with | leaf _ => trivial | node w l r ihl ihr => obtain ⟨_, hl, hr⟩ := ht simp only [replace] split · exact ⟨rfl, hl, ihr hr _⟩ · exact ⟨rfl, ihl hl _, hr⟩
theorem lookup_replace_same (key : α → ℤ) {d : ℕ} (t : Tree α d) (path : Fin d → Bool) (v : Option α) : lookup (replace key t path v) path = v := by induction t with | leaf _ => rfl | node w l r ihl ihr => simp only [replace] split <;> simp_all [node, lookup]
theorem lookup_replace (key : α → ℤ) {d : ℕ} (t : Tree α d) (path q : Fin d → Bool) (v : Option α) : lookup (replace key t path v) q = if path = q then v else lookup t q := by induction t with | leaf _ => have heq : path = q := Subsingleton.elim _ _ simp [replace, lookup, heq] | @node d w l r ihl ihr => have heq : path = q ↔ path 0 = q 0 ∧ (fun i : Fin d => path i.succ) = (fun i : Fin d => q i.succ) := by constructor · intro h subst q exact ⟨rfl, rfl⟩ · rintro ⟨hh, ht⟩ funext i exact Fin.cases hh (fun j => congrFun ht j) i cases hp : path 0 <;> cases hq : q 0 <;> simp [replace, node, lookup, hp, hq, ihl, ihr, heq]
def build (key : α → ℤ) : (d : ℕ) → ((Fin d → Bool) → Option α) → Tree α d | 0, front => .leaf (front Fin.elim0) | d + 1, front => node key (build key d (fun p => front (Fin.cons false p))) (build key d (fun p => front (Fin.cons true p)))
theorem build_valid (key : α → ℤ) (d : ℕ) (front : (Fin d → Bool) → Option α) : Valid key (build key d front) := by induction d with | zero => trivial | succ d ih => exact ⟨rfl, ih _, ih _⟩
theorem lookup_build (key : α → ℤ) (d : ℕ) (front : (Fin d → Bool) → Option α) (path : Fin d → Bool) : lookup (build key d front) path = front path := by induction d with | zero => have hpath : (Fin.elim0 : Fin 0 → Bool) = path := Subsingleton.elim _ _ simpa [build, lookup] using congrArg front hpath | succ d ih => simp only [build, node, lookup] cases hp : path 0 · simp only [Bool.false_eq_true, ↓reduceIte] rw [ih] apply congrArg front funext i exact Fin.cases (by simp [hp]) (fun j => by simp) i · simp only [↓reduceIte] rw [ih] apply congrArg front funext i exact Fin.cases (by simp [hp]) (fun j => by simp) i
theorem mem_candidates_iff {d : ℕ} (t : Tree α d) (v : α) : v ∈ candidates t ↔ ∃ path, lookup t path = some v := by induction t with | leaf w => constructor · intro hv exact ⟨Fin.elim0, by simpa [candidates, lookup] using hv⟩ · rintro ⟨_, hv⟩ simpa [candidates, lookup] using hv | @node d w l r ihl ihr => rw [candidates, List.mem_append, ihl, ihr] constructor · rintro (⟨p, hp⟩ | ⟨p, hp⟩) · exact ⟨Fin.cons false p, by simpa [lookup] using hp⟩ · exact ⟨Fin.cons true p, by simpa [lookup] using hp⟩ · rintro ⟨p, hp⟩ cases h : p 0 · exact Or.inl ⟨fun i => p i.succ, by simpa [lookup, h] using hp⟩ · exact Or.inr ⟨fun i => p i.succ, by simpa [lookup, h] using hp⟩
theorem winner_le_lookup (key : α → ℤ) {d : ℕ} (t : Tree α d) (ht : Valid key t) (path : Fin d → Bool) {v : α} (hv : lookup t path = some v) : ∃ w, winner t = some w ∧ key w ≤ key v := (winner_best key t ht).2 v ((mem_candidates_iff t v).mpr ⟨path, hv⟩)
def nodes : {d : ℕ} → Tree α d → ℕ | 0, .leaf _ => 1 | _ + 1, .node _ l r => 1 + nodes l + nodes r
theorem nodes_exact {d : ℕ} (t : Tree α d) : nodes t + 1 = 2 ^ (d + 1) := by induction t with | leaf _ => norm_num [nodes] | @node d w l r ihl ihr => simp only [nodes] rw [pow_succ] omega
theorem padded_nodes_le (R : ℕ) (t : Tree α (Nat.clog 2 R)) : nodes t + 1 ≤ 4 * (R + 1) := by rw [nodes_exact, pow_succ] by_cases hR : R ≤ 1 · rw [Nat.clog_of_right_le_one hR] norm_num omega · have hR' : 1 < R := by omega have hp := Nat.pow_pred_clog_lt_self (by decide : 1 < 2) hR' have hpos := Nat.clog_pos (by decide : 1 < 2) hR' have hbits : 2 ^ Nat.clog 2 R ≤ 2 * R := by rw [show Nat.clog 2 R = (Nat.clog 2 R).pred + 1 from (Nat.succ_pred_eq_of_pos hpos).symm, pow_succ] omega omega
theorem depth_le_index_bits {R n : ℕ} (hR : R ≤ 2 ^ n) : Nat.clog 2 R ≤ n := Nat.clog_le_of_le_pow hR
/-- Number of cached comparisons made by a leaf replacement. -/def replaceComparisons : {d : ℕ} → Tree α d → (Fin d → Bool) → ℕ | 0, .leaf _, _ => 0 | _d + 1, .node _ l r, path => 1 + if path 0 then replaceComparisons r (fun i => path i.succ) else replaceComparisons l (fun i => path i.succ)
theorem replaceComparisons_eq {d : ℕ} (t : Tree α d) (path : Fin d → Bool) : replaceComparisons t path = d := by induction t with | leaf _ => rfl | @node d w l r ihl ihr => simp only [replaceComparisons] split <;> simp [ihl, ihr, Nat.add_comm]
end Tournamentend LowSpaceSubsetSum
end OAIlean/OAI/Combinatorics/LowSpaceSubsetSum.leanAdded+16
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/FilteredRow.leanAdded+126
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/FilteredStream.leanAdded+187
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/JoinOne.leanAdded+219
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/JoinReaderMap.leanAdded+269
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/JoinUserMap.leanAdded+187
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MeasuredDistinctCount.leanAdded+93
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MeasuredInitialization.leanAdded+170
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MeasuredLog2.leanAdded+60
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MeasuredMixerCount.leanAdded+93
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MeasuredPivot.leanAdded+80
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MeasuredRow.leanAdded+212
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MeasuredSort.leanAdded+128
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MeasuredSortSpace.leanAdded+128
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MeasuredStoredRecords.leanAdded+122
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MeasuredSumReader.leanAdded+132
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MergeCorrectness.leanAdded+131
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MergeOrdering.leanAdded+133
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MergedReader.leanAdded+182
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/ModularCursor.leanAdded+104
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/ModularFilters.leanAdded+62
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/ModularRows.leanAdded+137
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/PaddedRows.leanAdded+101
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/PairCursor.leanAdded+37
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/ParentPrefixSearch.leanAdded+144
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/PrefixAccounting.leanAdded+210
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/PrefixCheckList.leanAdded+90
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/PrefixMachine.leanAdded+197
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/PrefixMachineRun.leanAdded+85
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/PrefixTaskCount.leanAdded+180
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/ReaderInitializationMap.leanAdded+171
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/ReaderMap.leanAdded+363
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/RecordedDictionary.leanAdded+166
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/RecordedJoin.leanAdded+120
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/ResidueFilters.leanAdded+121
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/ResidueSort.leanAdded+81
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/RowMerge.leanAdded+199
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/SliceCursor.leanAdded+102
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/SortedFind.leanAdded+146
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/StreamGroupFacts.leanAdded+80
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/StreamJoin.leanAdded+100
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/StreamJoinBounds.leanAdded+241
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/StreamJoinCorrectness.leanAdded+203
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/StreamPrimitiveWork.leanAdded+94
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/StreamWitness.leanAdded+88
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/SumReader.leanAdded+131
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/TieBuffer.leanAdded+172
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/TieGroup.leanAdded+298
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/TieReplay.leanAdded+239
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/Tournament.leanAdded+281