roseking commited on
Commit
e5a97c6
·
verified ·
1 Parent(s): 5d5048e

Add lean source and binary files (part 47)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. lean/OAI/Combinatorics/LowSpaceSubsetSum.lean +16 -0
  2. lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/FilteredRow.lean +126 -0
  3. lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/FilteredStream.lean +187 -0
  4. lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/JoinOne.lean +219 -0
  5. lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/JoinReaderMap.lean +269 -0
  6. lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/JoinUserMap.lean +187 -0
  7. lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MeasuredDistinctCount.lean +93 -0
  8. lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MeasuredInitialization.lean +170 -0
  9. lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MeasuredLog2.lean +60 -0
  10. lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MeasuredMixerCount.lean +93 -0
  11. lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MeasuredPivot.lean +80 -0
  12. lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MeasuredRow.lean +212 -0
  13. lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MeasuredSort.lean +128 -0
  14. lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MeasuredSortSpace.lean +128 -0
  15. lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MeasuredStoredRecords.lean +122 -0
  16. lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MeasuredSumReader.lean +132 -0
  17. lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MergeCorrectness.lean +131 -0
  18. lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MergeOrdering.lean +133 -0
  19. lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MergedReader.lean +182 -0
  20. lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/ModularCursor.lean +104 -0
  21. lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/ModularFilters.lean +62 -0
  22. lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/ModularRows.lean +137 -0
  23. lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/PaddedRows.lean +101 -0
  24. lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/PairCursor.lean +37 -0
  25. lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/ParentPrefixSearch.lean +144 -0
  26. lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/PrefixAccounting.lean +210 -0
  27. lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/PrefixCheckList.lean +90 -0
  28. lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/PrefixMachine.lean +197 -0
  29. lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/PrefixMachineRun.lean +85 -0
  30. lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/PrefixTaskCount.lean +180 -0
  31. lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/ReaderInitializationMap.lean +171 -0
  32. lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/ReaderMap.lean +363 -0
  33. lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/RecordedDictionary.lean +166 -0
  34. lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/RecordedJoin.lean +120 -0
  35. lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/ResidueFilters.lean +121 -0
  36. lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/ResidueSort.lean +81 -0
  37. lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/RowMerge.lean +199 -0
  38. lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/SliceCursor.lean +102 -0
  39. lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/SortedFind.lean +146 -0
  40. lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/StreamGroupFacts.lean +80 -0
  41. lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/StreamJoin.lean +100 -0
  42. lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/StreamJoinBounds.lean +241 -0
  43. lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/StreamJoinCorrectness.lean +203 -0
  44. lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/StreamPrimitiveWork.lean +94 -0
  45. lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/StreamWitness.lean +88 -0
  46. lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/SumReader.lean +131 -0
  47. lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/TieBuffer.lean +172 -0
  48. lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/TieGroup.lean +298 -0
  49. lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/TieReplay.lean +239 -0
  50. lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/Tournament.lean +281 -0
lean/OAI/Combinatorics/LowSpaceSubsetSum.lean ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import OAI.Combinatorics.LowSpaceSubsetSum.Search.BudgetDecisionRound
2
+ import OAI.Combinatorics.LowSpaceSubsetSum.Search.BudgetedParentFill
3
+ import OAI.Combinatorics.LowSpaceSubsetSum.Search.BudgetedParentReplay
4
+ import OAI.Combinatorics.LowSpaceSubsetSum.Main
5
+ import OAI.Combinatorics.LowSpaceSubsetSum.Streams.PrefixAccounting
6
+ import OAI.Combinatorics.LowSpaceSubsetSum.Streams.PrefixMachineRun
7
+ import OAI.Combinatorics.LowSpaceSubsetSum.Representation.RepresentationLifetime
8
+ import OAI.Combinatorics.LowSpaceSubsetSum.Counting.SignRandomization
9
+ import OAI.Combinatorics.LowSpaceSubsetSum.Search.StoppedGuardedDecision
10
+ import OAI.Combinatorics.LowSpaceSubsetSum.Storage.StoredNodeCells
11
+
12
+ /-! # Low-space worst-case Subset Sum
13
+
14
+ One-sided randomized decision with bounded sampling, counted preprocessing,
15
+ streamed representations, and all-outcome operation and writable-storage counts.
16
+ -/
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/FilteredRow.lean ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import OAI.Combinatorics.LowSpaceSubsetSum.Counting.BinarySlice
2
+ import OAI.Combinatorics.LowSpaceSubsetSum.Counting.SliceModular
3
+ import OAI.Combinatorics.LowSpaceSubsetSum.Streams.PairCursor
4
+
5
+ namespace OAI
6
+
7
+ /-!
8
+ # The actual filtered modular row
9
+
10
+ The row searches the shared array by the small residue, searches the large
11
+ residue within that slice, and stores only the first occurrence and cursor.
12
+ Its sorted output is exactly the eligible occurrences. Positivity of the
13
+ large modulus supplies normalized keys; no coprimality is used.
14
+ -/
15
+
16
+ namespace LowSpaceSubsetSum
17
+ namespace FilteredRow
18
+
19
+ variable {α β : Type*}
20
+
21
+ abbrev PrimarySorted (xs : Array β) (w : β → ℤ) (p : ℤ) : Prop :=
22
+ Monotone (fun i : Fin xs.size => w xs[i.val] % p)
23
+
24
+ abbrev SecondarySorted (xs : Array β) (w : β → ℤ) (p P : ℤ) : Prop :=
25
+ ∀ i j : Fin xs.size, i ≤ j → w xs[i.val] % p = w xs[j.val] % p →
26
+ w xs[i.val] % P ≤ w xs[j.val] % P
27
+
28
+ def range (xs : Array β) (w : β → ℤ) (p c wx : ℤ) (k : ℕ)
29
+ (hs : PrimarySorted xs w p) (hk : xs.size < 2 ^ k) : SliceCursor.Range xs.size :=
30
+ BinarySlice.range xs (fun y => w y % p) ((c - wx) % p) k hs hk
31
+
32
+ theorem range_length (xs : Array β) (w : β → ℤ) (p c wx : ℤ) (k : ℕ)
33
+ (hs : PrimarySorted xs w p) (hk : xs.size < 2 ^ k) :
34
+ (range xs w p c wx k hs hk).length < 2 ^ k := by
35
+ have := (range xs w p c wx k hs hk).bounded
36
+ omega
37
+
38
+ theorem range_sorted (xs : Array β) (w : β → ℤ) (p P c wx : ℤ) (k : ℕ)
39
+ (hs : PrimarySorted xs w p) (ht : SecondarySorted xs w p P) (hk : xs.size < 2 ^ k) :
40
+ Monotone (fun i : Fin (range xs w p c wx k hs hk).length =>
41
+ w (SliceCursor.values xs (range xs w p c wx k hs hk) i) % P) :=
42
+ BinarySlice.slice_sorted xs (fun y => w y % p) (fun y => w y % P)
43
+ ((c - wx) % p) k hs hk ht
44
+
45
+ def forward (xs : Array β) (wl : α → ℤ) (wr : β → ℤ) (p P c : ℤ) (k : ℕ)
46
+ (hs : PrimarySorted xs wr p) (hk : xs.size < 2 ^ k) (x : α) : PairCursor.State α xs.size :=
47
+ ⟨x, SliceModular.forward xs (range xs wr p c (wl x) k hs hk)
48
+ (fun y => wr y % P) P (wl x % P) k⟩
49
+
50
+ def reverse (xs : Array β) (wl : α → ℤ) (wr : β → ℤ) (p P c v : ℤ) (k : ℕ)
51
+ (hs : PrimarySorted xs wr p) (hk : xs.size < 2 ^ k) (x : α) : PairCursor.State α xs.size :=
52
+ ⟨x, SliceModular.reverse xs (range xs wr p c (wl x) k hs hk)
53
+ (fun y => wr y % P) ((v - wl x) % P) k⟩
54
+
55
+ theorem eligible (p c x y : ℤ) :
56
+ (x + y) % p = c % p ↔ y % p = (c - x) % p := by
57
+ change Int.ModEq p (x + y) c ↔ Int.ModEq p y (c - x)
58
+ constructor
59
+ · intro h
60
+ simpa only [add_sub_cancel_left] using h.sub_right x
61
+ · intro h
62
+ simpa only [add_sub_cancel] using h.add_left x
63
+
64
+ theorem range_slice (xs : Array β) (wr : β → ℤ) (p c wx : ℤ) (k : ℕ)
65
+ (hs : PrimarySorted xs wr p) (hk : xs.size < 2 ^ k) :
66
+ SliceCursor.slice xs (range xs wr p c wx k hs hk) =
67
+ xs.toList.filter (fun y => decide ((wx + wr y) % p = c % p)) := by
68
+ rw [range, BinarySlice.slice_eq_filter]
69
+ congr 1
70
+ funext y
71
+ simp only [← eligible p c wx (wr y)]
72
+
73
+ theorem forward_perm (xs : Array β) (wl : α → ℤ) (wr : β → ℤ) (p P c : ℤ) (k : ℕ)
74
+ (hs : PrimarySorted xs wr p) (ht : SecondarySorted xs wr p P)
75
+ (hk : xs.size < 2 ^ k) (x : α) :
76
+ (PairCursor.output xs (forward xs wl wr p P c k hs hk x)).Perm
77
+ ((xs.toList.filter (fun y => decide ((wl x + wr y) % p = c % p))).map (fun y => (x, y))) := by
78
+ have h := SliceModular.forward_perm xs (range xs wr p c (wl x) k hs hk)
79
+ (fun y => wr y % P) P (wl x % P) k (range_length xs wr p c (wl x) k hs hk)
80
+ (range_sorted xs wr p P c (wl x) k hs ht hk)
81
+ rw [range_slice xs wr p c (wl x) k hs hk] at h
82
+ exact h.map (fun y => (x, y))
83
+
84
+ theorem reverse_perm (xs : Array β) (wl : α → ℤ) (wr : β → ℤ) (p P c v : ℤ) (k : ℕ)
85
+ (hs : PrimarySorted xs wr p) (ht : SecondarySorted xs wr p P)
86
+ (hk : xs.size < 2 ^ k) (x : α) :
87
+ (PairCursor.output xs (reverse xs wl wr p P c v k hs hk x)).Perm
88
+ ((xs.toList.filter (fun y => decide ((wl x + wr y) % p = c % p))).map (fun y => (x, y))) := by
89
+ have h := SliceModular.reverse_perm xs (range xs wr p c (wl x) k hs hk)
90
+ (fun y => wr y % P) ((v - wl x) % P) k (range_length xs wr p c (wl x) k hs hk)
91
+ (range_sorted xs wr p P c (wl x) k hs ht hk)
92
+ rw [range_slice xs wr p c (wl x) k hs hk] at h
93
+ exact h.map (fun y => (x, y))
94
+
95
+ theorem forward_sorted (xs : Array β) (wl : α → ℤ) (wr : β → ℤ) (p P c : ℤ) (k : ℕ)
96
+ (hs : PrimarySorted xs wr p) (ht : SecondarySorted xs wr p P)
97
+ (hk : xs.size < 2 ^ k) (hP : 0 < P) (x : α) :
98
+ (PairCursor.output xs (forward xs wl wr p P c k hs hk x)).Pairwise
99
+ (fun a b => (wl a.1 + wr a.2) % P ≤ (wl b.1 + wr b.2) % P) := by
100
+ have h := SliceModular.forward_sorted xs (range xs wr p c (wl x) k hs hk)
101
+ (fun y => wr y % P) P (wl x % P) k (range_length xs wr p c (wl x) k hs hk)
102
+ (range_sorted xs wr p P c (wl x) k hs ht hk)
103
+ (Int.emod_nonneg _ hP.ne') (Int.emod_lt_of_pos _ hP)
104
+ (fun y _ => ⟨Int.emod_nonneg _ hP.ne', Int.emod_lt_of_pos _ hP⟩)
105
+ change ((SliceCursor.output xs _).map (fun y => (x, y))).Pairwise _
106
+ rw [List.pairwise_map]
107
+ simpa only [forward, Int.add_emod, Int.emod_emod] using h
108
+
109
+ theorem reverse_sorted (xs : Array β) (wl : α → ℤ) (wr : β → ℤ) (p P c v : ℤ) (k : ℕ)
110
+ (hs : PrimarySorted xs wr p) (ht : SecondarySorted xs wr p P)
111
+ (hk : xs.size < 2 ^ k) (hP : 0 < P) (x : α) :
112
+ (PairCursor.output xs (reverse xs wl wr p P c v k hs hk x)).Pairwise
113
+ (fun a b => (v - wl a.1 - wr a.2) % P ≤ (v - wl b.1 - wr b.2) % P) := by
114
+ have h := SliceModular.reverse_sorted xs (range xs wr p c (wl x) k hs hk)
115
+ (fun y => wr y % P) P ((v - wl x) % P) k (range_length xs wr p c (wl x) k hs hk)
116
+ (range_sorted xs wr p P c (wl x) k hs ht hk)
117
+ (Int.emod_nonneg _ hP.ne') (Int.emod_lt_of_pos _ hP)
118
+ (fun y _ => ⟨Int.emod_nonneg _ hP.ne', Int.emod_lt_of_pos _ hP⟩)
119
+ change ((SliceCursor.output xs _).map (fun y => (x, y))).Pairwise _
120
+ rw [List.pairwise_map]
121
+ simpa only [reverse, Int.sub_emod, Int.emod_emod] using h
122
+
123
+ end FilteredRow
124
+ end LowSpaceSubsetSum
125
+
126
+ end OAI
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/FilteredStream.lean ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import OAI.Combinatorics.LowSpaceSubsetSum.Streams.ResidueSort
2
+ import OAI.Combinatorics.LowSpaceSubsetSum.Streams.PaddedRows
3
+
4
+ namespace OAI
5
+
6
+ /-!
7
+ # The complete executable modular pair stream
8
+
9
+ Concrete lexicographic sorting, binary slice/pivot row initialization, empty
10
+ leaf padding and tournament merging are composed here. The actual merge state
11
+ stores only its tree of constant-size row cursors. All Cartesian lists and
12
+ multisets in the statements are proof views.
13
+ -/
14
+
15
+ namespace LowSpaceSubsetSum
16
+ namespace FilteredStream
17
+
18
+ variable {α β : Type*}
19
+
20
+ inductive Mode where
21
+ | direct
22
+ | complementary (target : ℤ)
23
+
24
+ def key (wl : α → ℤ) (wr : β → ℤ) (P : ℤ) : Mode → (α × β) → ℤ
25
+ | .direct, z => (wl z.1 + wr z.2) % P
26
+ | .complementary v, z => (v - wl z.1 - wr z.2) % P
27
+
28
+ def steps (n : ℕ) : ℕ := Nat.clog 2 n + 1
29
+
30
+ theorem steps_sufficient (n : ℕ) : n < 2 ^ steps n := by
31
+ have h := Nat.le_pow_clog (by decide : 1 < 2) n
32
+ have hp : 0 < 2 ^ Nat.clog 2 n := by positivity
33
+ rw [steps, pow_succ]
34
+ omega
35
+
36
+ theorem steps_le_index_bits (N n : ℕ) (hN : N ≤ 2 ^ n) : steps N ≤ n + 1 := by
37
+ exact Nat.add_le_add_right (Nat.clog_le_of_le_pow hN) 1
38
+
39
+ def row (right : Array β) (wl : α → ℤ) (wr : β → ℤ) (p P c : ℤ)
40
+ (hs : FilteredRow.PrimarySorted right wr p) (mode : Mode) (x : α) :
41
+ PairCursor.State α right.size :=
42
+ match mode with
43
+ | .direct => FilteredRow.forward right wl wr p P c (steps right.size)
44
+ hs (steps_sufficient right.size) x
45
+ | .complementary v => FilteredRow.reverse right wl wr p P c v (steps right.size)
46
+ hs (steps_sufficient right.size) x
47
+
48
+ theorem row_sorted (right : Array β) (wl : α → ℤ) (wr : β → ℤ) (p P c : ℤ)
49
+ (hs : FilteredRow.PrimarySorted right wr p)
50
+ (ht : FilteredRow.SecondarySorted right wr p P) (hP : 0 < P) (mode : Mode) (x : α) :
51
+ (PairCursor.output right (row right wl wr p P c hs mode x)).Pairwise
52
+ (fun a b => key wl wr P mode a ≤ key wl wr P mode b) := by
53
+ cases mode with
54
+ | direct => exact FilteredRow.forward_sorted right wl wr p P c _ hs ht _ hP x
55
+ | complementary v => exact FilteredRow.reverse_sorted right wl wr p P c v _ hs ht _ hP x
56
+
57
+ theorem row_perm (right : Array β) (wl : α → ℤ) (wr : β → ℤ) (p P c : ℤ)
58
+ (hs : FilteredRow.PrimarySorted right wr p)
59
+ (ht : FilteredRow.SecondarySorted right wr p P) (mode : Mode) (x : α) :
60
+ (PairCursor.output right (row right wl wr p P c hs mode x)).Perm
61
+ ((right.toList.filter (fun y => decide ((wl x + wr y) % p = c % p))).map (fun y => (x, y))) := by
62
+ cases mode with
63
+ | direct => exact FilteredRow.forward_perm right wl wr p P c _ hs ht _ x
64
+ | complementary v => exact FilteredRow.reverse_perm right wl wr p P c v _ hs ht _ x
65
+
66
+ abbrev Cursor (right : Array β) := Option (PairCursor.State α right.size)
67
+
68
+ def read (right : Array β) : Cursor (α := α) right → Option ((α × β) × Cursor (α := α) right) :=
69
+ PaddedRows.next (PairCursor.next right)
70
+
71
+ def view (right : Array β) : Cursor (α := α) right → List (α × β) :=
72
+ PaddedRows.view (PairCursor.output right)
73
+
74
+ theorem reader (right : Array β) : RowMerge.IsReader (read (α := α) right) (view right) :=
75
+ PaddedRows.reader _ _ (PairCursor.reader right)
76
+
77
+ def rowArray (left : Array α) (right : Array β) (wl : α → ℤ) (wr : β → ℤ) (p P c : ℤ)
78
+ (hs : FilteredRow.PrimarySorted right wr p) (mode : Mode) : Array (PairCursor.State α right.size) :=
79
+ left.map (row right wl wr p P c hs mode)
80
+
81
+ theorem array_sorted (left : Array α) (right : Array β) (wl : α → ℤ) (wr : β → ℤ) (p P c : ℤ)
82
+ (hs : FilteredRow.PrimarySorted right wr p) (ht : FilteredRow.SecondarySorted right wr p P)
83
+ (hP : 0 < P) (mode : Mode) (d : ℕ) (path : RowMerge.Path d) :
84
+ (view right (PaddedRows.rows (rowArray left right wl wr p P c hs mode) d path)).Pairwise
85
+ (fun a b => key wl wr P mode a ≤ key wl wr P mode b) := by
86
+ apply PaddedRows.rows_sorted
87
+ intro s hmem
88
+ simp only [rowArray, Array.toList_map, List.mem_map] at hmem
89
+ obtain ⟨x, _, rfl⟩ := hmem
90
+ exact row_sorted right wl wr p P c hs ht hP mode x
91
+
92
+ def start (left : Array α) (right : Array β) (wl : α → ℤ) (wr : β → ℤ) (p P c : ℤ)
93
+ (hs : FilteredRow.PrimarySorted right wr p) (ht : FilteredRow.SecondarySorted right wr p P)
94
+ (hP : 0 < P) (mode : Mode) :
95
+ MergedReader.State (key wl wr P mode) (view right) (Nat.clog 2 left.size) :=
96
+ MergedReader.start (key wl wr P mode) (read right) (view right) (reader right)
97
+ (PaddedRows.rows (rowArray left right wl wr p P c hs mode) _)
98
+ (array_sorted left right wl wr p P c hs ht hP mode _)
99
+
100
+ theorem output_bag (left : Array α) (right : Array β) (wl : α → ℤ) (wr : β → ℤ) (p P c : ℤ)
101
+ (hs : FilteredRow.PrimarySorted right wr p) (ht : FilteredRow.SecondarySorted right wr p P)
102
+ (hP : 0 < P) (mode : Mode) :
103
+ (MergedReader.output (key wl wr P mode) (read right) (view right)
104
+ (start left right wl wr p P c hs ht hP mode) : Multiset (α × β)) =
105
+ ∑ i : Fin left.size,
106
+ ((right.toList.filter (fun y => decide ((wl left[i.val] + wr y) % p = c % p))).map
107
+ (fun y => (left[i.val], y)) : Multiset (α × β)) := by
108
+ rw [start, MergedReader.start_output_bag]
109
+ have hd : (rowArray left right wl wr p P c hs mode).size ≤ 2 ^ Nat.clog 2 left.size := by
110
+ simpa only [rowArray, Array.size_map] using Nat.le_pow_clog (by decide : 1 < 2) left.size
111
+ change (∑ path : RowMerge.Path (Nat.clog 2 left.size),
112
+ (PaddedRows.view (PairCursor.output right)
113
+ (PaddedRows.rows (rowArray left right wl wr p P c hs mode) _ path) : Multiset (α × β))) = _
114
+ rw [PaddedRows.row_bag _ _ hd]
115
+ have hsize : (rowArray left right wl wr p P c hs mode).size = left.size := by
116
+ simp only [rowArray, Array.size_map]
117
+ apply Fintype.sum_equiv (finCongr hsize)
118
+ intro i
119
+ have hin : i.val < left.size := by rw [← hsize]; exact i.isLt
120
+ simp only [rowArray, Array.getElem_map]
121
+ exact Quot.sound (row_perm right wl wr p P c hs ht mode left[i.val])
122
+
123
+ def sortedStart (left : Array α) (right : Array β) (wl : α → ℤ) (wr : β → ℤ) (p P c : ℤ)
124
+ (hP : 0 < P) (mode : Mode) :
125
+ MergedReader.State (key wl wr P mode) (view (ResidueSort.sort right wr p P))
126
+ (Nat.clog 2 left.size) :=
127
+ start left (ResidueSort.sort right wr p P) wl wr p P c
128
+ (ResidueSort.primary right wr p P) (ResidueSort.secondary right wr p P) hP mode
129
+
130
+ theorem sorted_output_bag (left : Array α) (right : Array β)
131
+ (wl : α → ℤ) (wr : β → ℤ) (p P c : ℤ) (hP : 0 < P) (mode : Mode) :
132
+ (MergedReader.output (key wl wr P mode) (read (ResidueSort.sort right wr p P))
133
+ (view (ResidueSort.sort right wr p P)) (sortedStart left right wl wr p P c hP mode) :
134
+ Multiset (α × β)) =
135
+ ∑ i : Fin left.size,
136
+ ((right.toList.filter (fun y => decide ((wl left[i.val] + wr y) % p = c % p))).map
137
+ (fun y => (left[i.val], y)) : Multiset (α × β)) := by
138
+ rw [sortedStart, output_bag]
139
+ apply Finset.sum_congr rfl
140
+ intro i _
141
+ exact Quot.sound (((ResidueSort.permutation right wr p P).filter
142
+ (fun y => decide ((wl left[i.val] + wr y) % p = c % p))).map (fun y => (left[i.val], y)))
143
+
144
+ theorem sorted_output_sorted (left : Array α) (right : Array β)
145
+ (wl : α → ℤ) (wr : β → ℤ) (p P c : ℤ) (hP : 0 < P) (mode : Mode) :
146
+ (MergedReader.output (key wl wr P mode) (read (ResidueSort.sort right wr p P))
147
+ (view (ResidueSort.sort right wr p P)) (sortedStart left right wl wr p P c hP mode)).Pairwise
148
+ (fun a b => key wl wr P mode a ≤ key wl wr P mode b) :=
149
+ MergedReader.output_sorted _ _ _ (reader _) _
150
+
151
+ theorem state_nodes (left : Array α) (right : Array β)
152
+ (wl : α → ℤ) (wr : β → ℤ) (p P c : ℤ) (hP : 0 < P) (mode : Mode) :
153
+ Tournament.nodes (sortedStart left right wl wr p P c hP mode).tree + 1 ≤
154
+ 4 * (left.size + 1) := Tournament.padded_nodes_le left.size _
155
+
156
+ theorem sorted_output_mem (left : Array α) (right : Array β)
157
+ (wl : α → ℤ) (wr : β → ℤ) (p P c : ℤ) (hP : 0 < P) (mode : Mode) (z : α × β) :
158
+ z ∈ MergedReader.output (key wl wr P mode) (read (ResidueSort.sort right wr p P))
159
+ (view (ResidueSort.sort right wr p P)) (sortedStart left right wl wr p P c hP mode) ↔
160
+ z.1 ∈ left.toList ∧ z.2 ∈ right.toList ∧ (wl z.1 + wr z.2) % p = c % p := by
161
+ change z ∈ (MergedReader.output (key wl wr P mode) (read (ResidueSort.sort right wr p P))
162
+ (view (ResidueSort.sort right wr p P)) (sortedStart left right wl wr p P c hP mode) :
163
+ Multiset (α × β)) ↔ _
164
+ rw [sorted_output_bag]
165
+ simp only [Multiset.mem_sum, Finset.mem_univ, true_and, Multiset.mem_coe,
166
+ List.mem_map, List.mem_filter, decide_eq_true_eq]
167
+ constructor
168
+ · rintro ⟨i, y, ⟨hy, hmod⟩, heq⟩
169
+ have hz₁ : left[i.val] = z.1 := congrArg Prod.fst heq
170
+ have hz₂ : y = z.2 := congrArg Prod.snd heq
171
+ subst y
172
+ refine ⟨?_, hy, ?_⟩
173
+ · rw [← hz₁]
174
+ exact List.mem_iff_getElem.mpr ⟨i.val, by simp, by simp⟩
175
+ · simpa only [hz₁] using hmod
176
+ · rintro ⟨hx, hy, hmod⟩
177
+ obtain ⟨i, hi, hix⟩ := List.mem_iff_getElem.mp hx
178
+ have hin : i < left.size := by simpa only [Array.length_toList] using hi
179
+ rw [Array.getElem_toList] at hix
180
+ refine ⟨⟨i, hin⟩, z.2, ⟨hy, ?_⟩, ?_⟩
181
+ · simpa only [hix] using hmod
182
+ · exact Prod.ext hix rfl
183
+
184
+ end FilteredStream
185
+ end LowSpaceSubsetSum
186
+
187
+ end OAI
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/JoinOne.lean ADDED
@@ -0,0 +1,219 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import OAI.Combinatorics.LowSpaceSubsetSum.Streams.BufferReplay
2
+
3
+ namespace OAI
4
+
5
+ /-!
6
+ # Reporting one item's matches against a buffered tie group
7
+
8
+ The immutable prefix buffer is reused. A generator suffix is restored only
9
+ when the group was longer than the buffer. The callback may stop in either
10
+ part; its work and stream queries are bounded on every outcome.
11
+ -/
12
+
13
+ namespace LowSpaceSubsetSum
14
+ namespace JoinOne
15
+
16
+ universe u v w
17
+
18
+ variable {α : Type u} {σ : Type v} {τ : Type w}
19
+
20
+ def run (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ)
21
+ (report : α → τ → τ × Bool) (buffer : Array α) (saved : σ)
22
+ (long : Bool) (fuel : ℕ) (a : τ) : TieReplay.Result σ τ :=
23
+ let first := BufferReplay.run key K report buffer a
24
+ if first.halted then
25
+ ⟨saved, first.state, first.queries, first.reports, false, true⟩
26
+ else if long then
27
+ let rest := TieReplay.run read key K report fuel saved first.state
28
+ ⟨rest.cursor, rest.state, first.queries + rest.queries,
29
+ first.reports + rest.reports, rest.complete, rest.halted⟩
30
+ else ⟨saved, first.state, first.queries, first.reports, true, false⟩
31
+
32
+ theorem reports_le (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ)
33
+ (report : α → τ → τ × Bool) (view : σ → List α) (hread : RowMerge.IsReader read view)
34
+ (buffer : Array α) (saved : σ) (long : Bool) (fuel : ℕ) (a : τ) :
35
+ (run read key K report buffer saved long fuel a).reports ≤
36
+ buffer.size + (TieBuffer.groupView key K view saved).length := by
37
+ have hb := BufferReplay.reports_le key K report buffer a
38
+ dsimp only [run]
39
+ split
40
+ · exact hb.trans (Nat.le_add_right _ _)
41
+ · split
42
+ · have hr := TieReplay.run_reports_le_potential read key K report view hread
43
+ fuel saved (BufferReplay.run key K report buffer a).state
44
+ exact Nat.add_le_add hb hr
45
+ · exact hb.trans (Nat.le_add_right _ _)
46
+
47
+ theorem queries_le (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ)
48
+ (report : α → τ → τ × Bool) (view : σ → List α) (hread : RowMerge.IsReader read view)
49
+ (buffer : Array α) (saved : σ) (long : Bool) (fuel : ℕ) (a : τ) :
50
+ (run read key K report buffer saved long fuel a).queries ≤
51
+ buffer.size + (TieBuffer.groupView key K view saved).length + 1 := by
52
+ have hb := BufferReplay.queries_le key K report buffer a
53
+ dsimp only [run]
54
+ split
55
+ · dsimp only
56
+ omega
57
+ · split
58
+ · have hr := TieReplay.run_queries_le_potential read key K report view hread
59
+ fuel saved (BufferReplay.run key K report buffer a).state
60
+ dsimp only
61
+ omega
62
+ · dsimp only
63
+ omega
64
+
65
+ theorem halted_false (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ)
66
+ (report : α → τ → τ × Bool) (hreport : ∀ x a, (report x a).2 = false)
67
+ (buffer : Array α) (saved : σ) (long : Bool) (fuel : ℕ) (a : τ) :
68
+ (run read key K report buffer saved long fuel a).halted = false := by
69
+ have hb : (BufferReplay.run key K report buffer a).halted = false :=
70
+ TieReplay.run_halted_false _ _ _ _ hreport _ _ _
71
+ simp only [run, hb, Bool.false_eq_true, ite_false]
72
+ split
73
+ · exact TieReplay.run_halted_false _ _ _ _ hreport _ _ _
74
+ · rfl
75
+
76
+ /-- Completed reporting is precisely prefix reporting followed by suffix
77
+ reporting; a short group has no suffix to restore. -/
78
+ theorem state_complete (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ)
79
+ (report : α → τ → τ × Bool) (hreport : ∀ x a, (report x a).2 = false)
80
+ (view : σ → List α) (hread : RowMerge.IsReader read view)
81
+ (buffer : Array α) (hkeys : ∀ x ∈ buffer.toList, key x = K)
82
+ (saved : σ) (fuel : ℕ) (a : τ)
83
+ (hfuel : (TieBuffer.groupView key K view saved).length ≤ fuel) :
84
+ (run read key K report buffer saved (TieBuffer.hasKey read key K saved) fuel a).state =
85
+ (buffer.toList ++ TieBuffer.groupView key K view saved).foldl
86
+ (fun a x => (report x a).1) a := by
87
+ have hb : (BufferReplay.run key K report buffer a).halted = false :=
88
+ TieReplay.run_halted_false _ _ _ _ hreport _ _ _
89
+ have hs := BufferReplay.state_complete key K report hreport buffer a hkeys
90
+ simp only [run, hb, Bool.false_eq_true, ite_false]
91
+ by_cases hl : TieBuffer.hasKey read key K saved = true
92
+ · simp only [hl, ite_true]
93
+ rw [TieReplay.run_state_complete read key K report hreport view hread fuel saved _ hfuel,
94
+ hs, List.foldl_append]
95
+ · have he : TieBuffer.groupView key K view saved = [] := by
96
+ by_contra he
97
+ exact hl ((TieBuffer.hasKey_iff read key K view hread saved).mpr he)
98
+ have hfalse : TieBuffer.hasKey read key K saved = false := Bool.eq_false_iff.mpr hl
99
+ simp only [hfalse, Bool.false_eq_true, ite_false, he, List.append_nil]
100
+ exact hs
101
+
102
+ theorem suffix_empty (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ)
103
+ (report : α → τ → τ × Bool) (hreport : ∀ x a, (report x a).2 = false)
104
+ (view : σ → List α) (hread : RowMerge.IsReader read view)
105
+ (buffer : Array α) (saved : σ) (fuel : ℕ) (a : τ)
106
+ (hfuel : (TieBuffer.groupView key K view saved).length ≤ fuel) :
107
+ TieBuffer.groupView key K view
108
+ (run read key K report buffer saved (TieBuffer.hasKey read key K saved) fuel a).cursor = [] := by
109
+ have hb : (BufferReplay.run key K report buffer a).halted = false :=
110
+ TieReplay.run_halted_false _ _ _ _ hreport _ _ _
111
+ simp only [run, hb, Bool.false_eq_true, ite_false]
112
+ by_cases hl : TieBuffer.hasKey read key K saved = true
113
+ · simp only [hl, ite_true]
114
+ have h := (TieReplay.runAcc_nonhalting_spec read key K report hreport view hread
115
+ fuel saved (BufferReplay.run key K report buffer a).state 0 0).2.2.1
116
+ exact h.trans (List.drop_eq_nil_of_le hfuel)
117
+ · simp only [Bool.eq_false_iff.mpr hl, Bool.false_eq_true, ite_false]
118
+ by_contra he
119
+ exact hl ((TieBuffer.hasKey_iff read key K view hread saved).mpr he)
120
+
121
+ theorem view_complete (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ)
122
+ (report : α → τ → τ × Bool) (hreport : ∀ x a, (report x a).2 = false)
123
+ (view : σ → List α) (hread : RowMerge.IsReader read view)
124
+ (buffer : Array α) (saved : σ) (fuel : ℕ) (a : τ)
125
+ (hfuel : (TieBuffer.groupView key K view saved).length ≤ fuel) :
126
+ view saved = TieBuffer.groupView key K view saved ++
127
+ view (run read key K report buffer saved (TieBuffer.hasKey read key K saved) fuel a).cursor := by
128
+ have hb : (BufferReplay.run key K report buffer a).halted = false :=
129
+ TieReplay.run_halted_false _ _ _ _ hreport _ _ _
130
+ simp only [run, hb, Bool.false_eq_true, ite_false]
131
+ by_cases hl : TieBuffer.hasKey read key K saved = true
132
+ · simp only [hl, ite_true]
133
+ have h := (TieReplay.runAcc_nonhalting_spec read key K report hreport view hread
134
+ fuel saved (BufferReplay.run key K report buffer a).state 0 0).2.2.2
135
+ simpa only [TieReplay.run, List.take_of_length_le hfuel] using h
136
+ · have he : TieBuffer.groupView key K view saved = [] := by
137
+ by_contra he
138
+ exact hl ((TieBuffer.hasKey_iff read key K view hread saved).mpr he)
139
+ simp only [Bool.eq_false_iff.mpr hl, Bool.false_eq_true, ite_false, he, List.nil_append]
140
+
141
+ def runFilled (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ)
142
+ (report : α → τ → τ × Bool) (B fuel : ℕ) (s : σ) (a : τ) : TieReplay.Result σ τ :=
143
+ let filled := TieBuffer.fill read key K B s
144
+ run read key K report filled.buffer filled.cursor
145
+ (TieBuffer.hasKey read key K filled.cursor) fuel a
146
+
147
+ theorem filled_reports_le (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ)
148
+ (report : α → τ → τ × Bool) (view : σ → List α) (hread : RowMerge.IsReader read view)
149
+ (B fuel : ℕ) (s : σ) (a : τ) :
150
+ (runFilled read key K report B fuel s a).reports ≤
151
+ (TieBuffer.groupView key K view s).length := by
152
+ have h := reports_le read key K report view hread (TieBuffer.fill read key K B s).buffer
153
+ (TieBuffer.fill read key K B s).cursor
154
+ (TieBuffer.hasKey read key K (TieBuffer.fill read key K B s).cursor) fuel a
155
+ have hb := congrArg List.length (TieBuffer.fill_buffer read key K view hread B s)
156
+ rw [TieBuffer.fill_suffix read key K view hread B s] at h
157
+ simp only [Array.length_toList, List.length_take] at hb
158
+ simp only [List.length_drop] at h
159
+ dsimp only [runFilled]
160
+ omega
161
+
162
+ theorem filled_queries_le (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ)
163
+ (report : α → τ → τ × Bool) (view : σ → List α) (hread : RowMerge.IsReader read view)
164
+ (B fuel : ℕ) (s : σ) (a : τ) :
165
+ (runFilled read key K report B fuel s a).queries ≤
166
+ (TieBuffer.groupView key K view s).length + 1 := by
167
+ have h := queries_le read key K report view hread (TieBuffer.fill read key K B s).buffer
168
+ (TieBuffer.fill read key K B s).cursor
169
+ (TieBuffer.hasKey read key K (TieBuffer.fill read key K B s).cursor) fuel a
170
+ have hb := congrArg List.length (TieBuffer.fill_buffer read key K view hread B s)
171
+ rw [TieBuffer.fill_suffix read key K view hread B s] at h
172
+ simp only [Array.length_toList, List.length_take] at hb
173
+ simp only [List.length_drop] at h
174
+ dsimp only [runFilled]
175
+ omega
176
+
177
+ theorem filled_state_complete (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ)
178
+ (report : α → τ → τ × Bool) (hreport : ∀ x a, (report x a).2 = false)
179
+ (view : σ → List α) (hread : RowMerge.IsReader read view)
180
+ (B fuel : ℕ) (s : σ) (a : τ)
181
+ (hfuel : (TieBuffer.groupView key K view s).length ≤ fuel) :
182
+ (runFilled read key K report B fuel s a).state =
183
+ (TieBuffer.groupView key K view s).foldl (fun a x => (report x a).1) a := by
184
+ have hf : (TieBuffer.groupView key K view (TieBuffer.fill read key K B s).cursor).length ≤
185
+ fuel := by
186
+ rw [TieBuffer.fill_suffix read key K view hread B s, List.length_drop]
187
+ omega
188
+ have h := state_complete read key K report hreport view hread
189
+ (TieBuffer.fill read key K B s).buffer
190
+ (BufferReplay.filled_buffer_keys read key K view hread B s)
191
+ (TieBuffer.fill read key K B s).cursor fuel a hf
192
+ rw [TieBuffer.fill_buffer read key K view hread B s,
193
+ TieBuffer.fill_suffix read key K view hread B s, List.take_append_drop] at h
194
+ exact h
195
+
196
+ theorem filled_view_complete (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ)
197
+ (report : α → τ → τ × Bool) (hreport : ∀ x a, (report x a).2 = false)
198
+ (view : σ → List α) (hread : RowMerge.IsReader read view)
199
+ (B fuel : ℕ) (s : σ) (a : τ)
200
+ (hfuel : (TieBuffer.groupView key K view s).length ≤ fuel) :
201
+ view s = TieBuffer.groupView key K view s ++
202
+ view (runFilled read key K report B fuel s a).cursor := by
203
+ have hf : (TieBuffer.groupView key K view (TieBuffer.fill read key K B s).cursor).length ≤
204
+ fuel := by
205
+ rw [TieBuffer.fill_suffix read key K view hread B s, List.length_drop]
206
+ omega
207
+ have hs := view_complete read key K report hreport view hread
208
+ (TieBuffer.fill read key K B s).buffer (TieBuffer.fill read key K B s).cursor fuel a hf
209
+ have h := (TieBuffer.fillAcc_spec read key K view hread B s #[] 0).2.1
210
+ change view s = (TieBuffer.groupView key K view s).take B ++
211
+ view (TieBuffer.fill read key K B s).cursor at h
212
+ rw [hs, TieBuffer.fill_suffix read key K view hread B s, ← List.append_assoc,
213
+ List.take_append_drop] at h
214
+ exact h
215
+
216
+ end JoinOne
217
+ end LowSpaceSubsetSum
218
+
219
+ end OAI
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/JoinReaderMap.lean ADDED
@@ -0,0 +1,269 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import OAI.Combinatorics.LowSpaceSubsetSum.Streams.JoinUserMap
2
+
3
+ namespace OAI
4
+
5
+ /-! # Stored-record erasure through buffered joins
6
+
7
+ The erasure maps both emitted records and reader cursors. Counters and stop
8
+ flags are preserved, so the work ledger can be transferred to the source
9
+ parent task without changing the order of equal-weight occurrences.
10
+ -/
11
+
12
+ namespace LowSpaceSubsetSum
13
+
14
+ universe u v s t w z
15
+ variable {α : Type u} {β : Type v} {σ : Type s} {σ' : Type t}
16
+ {τ : Type w} {τ' : Type z}
17
+
18
+ namespace TieBuffer
19
+
20
+ def mapAll (f : α → β) (g : σ → σ') (r : Result α σ) : Result β σ' :=
21
+ ⟨r.buffer.map f, g r.cursor, r.queries⟩
22
+
23
+ theorem fillAcc_map (f : α → β) (g : σ → σ')
24
+ (read : σ → Option (α × σ)) (read' : σ' → Option (β × σ'))
25
+ (hr : ∀ s, read' (g s) = (read s).map (Prod.map f g)) (key : β → ℤ) (K : ℤ)
26
+ (fuel : ℕ) (s : σ) (buf : Array α) (q : ℕ) :
27
+ mapAll f g (fillAcc read (fun x => key (f x)) K fuel s buf q) =
28
+ fillAcc read' key K fuel (g s) (buf.map f) q := by
29
+ induction fuel generalizing s buf q with
30
+ | zero => rfl
31
+ | succ fuel ih =>
32
+ cases h : read s with
33
+ | none => simp only [fillAcc, hr, h, Option.map_none, mapAll]
34
+ | some p =>
35
+ rcases p with ⟨x, s'⟩
36
+ simp only [fillAcc, hr, h, Option.map_some, Prod.map]
37
+ split
38
+ · simpa only [Array.map_push] using ih s' (buf.push x) (q + 1)
39
+ · rfl
40
+
41
+ theorem fill_map (f : α → β) (g : σ → σ')
42
+ (read : σ → Option (α × σ)) (read' : σ' → Option (β × σ'))
43
+ (hr : ∀ s, read' (g s) = (read s).map (Prod.map f g)) (key : β → ℤ) (K : ℤ)
44
+ (B : ℕ) (s : σ) :
45
+ mapAll f g (fill read (fun x => key (f x)) K B s) = fill read' key K B (g s) :=
46
+ by simpa only [fill, Array.map_empty] using fillAcc_map f g read read' hr key K B s #[] 0
47
+
48
+ theorem hasKey_map (f : α → β) (g : σ → σ')
49
+ (read : σ → Option (α × σ)) (read' : σ' → Option (β × σ'))
50
+ (hr : ∀ s, read' (g s) = (read s).map (Prod.map f g)) (key : β → ℤ)
51
+ (K : ℤ) (s : σ) :
52
+ hasKey read' key K (g s) = hasKey read (fun x => key (f x)) K s := by
53
+ cases h : read s <;> simp only [hasKey, hr, h, Option.map_none, Option.map_some, Prod.map]
54
+
55
+ end TieBuffer
56
+
57
+ namespace TieReplay
58
+
59
+ def mapAll (g : σ → σ') (h : τ → τ') (r : Result σ τ) : Result σ' τ' :=
60
+ ⟨g r.cursor, h r.state, r.queries, r.reports, r.complete, r.halted⟩
61
+
62
+ theorem runAcc_map (f : α → β) (g : σ → σ') (h : τ → τ')
63
+ (read : σ → Option (α × σ)) (read' : σ' → Option (β × σ'))
64
+ (hr : ∀ s, read' (g s) = (read s).map (Prod.map f g)) (key : β → ℤ) (K : ℤ)
65
+ (report : α → τ → τ × Bool) (report' : β → τ' → τ' × Bool)
66
+ (hp : ∀ x a, report' (f x) (h a) = (h (report x a).1, (report x a).2))
67
+ (fuel : ℕ) (s : σ) (a : τ) (q r : ℕ) :
68
+ mapAll g h (runAcc read (fun x => key (f x)) K report fuel s a q r) =
69
+ runAcc read' key K report' fuel (g s) (h a) q r := by
70
+ induction fuel generalizing s a q r with
71
+ | zero => rfl
72
+ | succ fuel ih =>
73
+ cases hs : read s with
74
+ | none => simp only [runAcc, hr, hs, Option.map_none, mapAll]
75
+ | some p =>
76
+ rcases p with ⟨x, s'⟩
77
+ simp only [runAcc, hr, hs, Option.map_some, Prod.map]
78
+ split
79
+ · rw [hp]
80
+ split
81
+ · rfl
82
+ · exact ih _ _ _ _
83
+ · rfl
84
+
85
+ theorem run_map (f : α → β) (g : σ → σ') (h : τ → τ')
86
+ (read : σ → Option (α × σ)) (read' : σ' → Option (β × σ'))
87
+ (hr : ∀ s, read' (g s) = (read s).map (Prod.map f g)) (key : β → ℤ) (K : ℤ)
88
+ (report : α → τ → τ × Bool) (report' : β → τ' → τ' × Bool)
89
+ (hp : ∀ x a, report' (f x) (h a) = (h (report x a).1, (report x a).2))
90
+ (fuel : ℕ) (s : σ) (a : τ) :
91
+ mapAll g h (run read (fun x => key (f x)) K report fuel s a) =
92
+ run read' key K report' fuel (g s) (h a) :=
93
+ runAcc_map f g h read read' hr key K report report' hp fuel s a 0 0
94
+
95
+ end TieReplay
96
+
97
+ namespace BufferReplay
98
+
99
+ theorem read_map (f : α → β) (xs : Array α) (i : ℕ) :
100
+ read (xs.map f) i = (read xs i).map (Prod.map f id) := by
101
+ simp only [read, Array.size_map]
102
+ split <;> simp only [Option.map_some, Option.map_none, Array.getElem_map, Prod.map, id_eq]
103
+
104
+ theorem run_map (f : α → β) (key : β → ℤ) (K : ℤ)
105
+ (report : β → τ → τ × Bool) (xs : Array α) (a : τ) :
106
+ run (fun x => key (f x)) K (fun x => report (f x)) xs a =
107
+ run key K report (xs.map f) a := by
108
+ have h := TieReplay.run_map f id id (read xs) (read (xs.map f))
109
+ (read_map f xs) key K (fun x => report (f x)) report (fun _ _ => rfl) xs.size 0 a
110
+ cases he : TieReplay.run (read xs) (fun x => key (f x)) K
111
+ (fun x => report (f x)) xs.size 0 a
112
+ simpa only [run, he, TieReplay.mapAll, id_eq, Array.size_map] using h
113
+
114
+ end BufferReplay
115
+
116
+ namespace JoinOne
117
+
118
+ theorem run_map (f : α → β) (g : σ → σ')
119
+ (read : σ → Option (α × σ)) (read' : σ' ��� Option (β × σ'))
120
+ (hr : ∀ s, read' (g s) = (read s).map (Prod.map f g)) (key : β → ℤ) (K : ℤ)
121
+ (report : β → τ → τ × Bool) (buffer : Array α) (saved : σ)
122
+ (long : Bool) (fuel : ℕ) (a : τ) :
123
+ TieReplay.mapAll g id
124
+ (run read (fun x => key (f x)) K (fun x => report (f x)) buffer saved long fuel a) =
125
+ run read' key K report (buffer.map f) (g saved) long fuel a := by
126
+ simp only [run, BufferReplay.run_map f key K report]
127
+ split
128
+ · rfl
129
+ · split
130
+ · have h := TieReplay.run_map f g id read read' hr key K
131
+ (fun x => report (f x)) report (fun _ _ => rfl) fuel saved
132
+ (BufferReplay.run key K report (buffer.map f) a).state
133
+ cases he : TieReplay.run read (fun x => key (f x)) K
134
+ (fun x => report (f x)) fuel saved
135
+ (BufferReplay.run key K report (buffer.map f) a).state
136
+ simp only [he, TieReplay.mapAll, id_eq] at h
137
+ rw [← h]
138
+ rfl
139
+ · rfl
140
+
141
+ end JoinOne
142
+
143
+ namespace TieGroup
144
+
145
+ variable {α' β' σ₁' σ₂' : Type*}
146
+
147
+ def mapReaders (g : σ → σ') (a : State σ τ) : State σ' τ :=
148
+ ⟨g a.last, a.user, a.queries, a.reports, a.restores⟩
149
+
150
+ def mapReadersResult (g₁ : σ → σ₁') (g₂ : σ' → σ₂')
151
+ (r : Result σ σ' τ) : Result σ₁' σ₂' τ :=
152
+ ⟨TieReplay.mapAll g₁ (mapReaders g₂) r.outer,
153
+ r.fillQueries, r.bufferSize, r.snapshot⟩
154
+
155
+ theorem step_mapReaders (f₁ : α → α') (f₂ : β → β') (g : σ → σ')
156
+ (read : σ → Option (β × σ)) (read' : σ' → Option (β' × σ'))
157
+ (hr : ∀ s, read' (g s) = (read s).map (Prod.map f₂ g)) (key : β' → ℤ) (K : ℤ)
158
+ (report : α' → β' → τ → τ × Bool) (buffer : Array β) (saved : σ)
159
+ (long : Bool) (fuel : ℕ) (x : α) (a : State σ τ) :
160
+ (mapReaders g (step read (fun y => key (f₂ y)) K
161
+ (fun x y => report (f₁ x) (f₂ y)) buffer saved long fuel x a).1,
162
+ (step read (fun y => key (f₂ y)) K
163
+ (fun x y => report (f₁ x) (f₂ y)) buffer saved long fuel x a).2) =
164
+ step read' key K report (buffer.map f₂) (g saved) long fuel (f₁ x) (mapReaders g a) := by
165
+ simp only [step, ← JoinOne.run_map f₂ g read read' hr key K (report (f₁ x))]
166
+ rfl
167
+
168
+ theorem run_mapReaders (f₁ : α → α') (f₂ : β → β') (g₁ : σ → σ₁') (g₂ : σ' → σ₂')
169
+ (read₁ : σ → Option (α × σ)) (read₁' : σ₁' → Option (α' × σ₁'))
170
+ (read₂ : σ' → Option (β × σ')) (read₂' : σ₂' → Option (β' × σ₂'))
171
+ (hr₁ : ∀ s, read₁' (g₁ s) = (read₁ s).map (Prod.map f₁ g₁))
172
+ (hr₂ : ∀ s, read₂' (g₂ s) = (read₂ s).map (Prod.map f₂ g₂))
173
+ (key₁ : α' → ℤ) (key₂ : β' → ℤ) (K : ℤ)
174
+ (report : α' → β' → τ → τ × Bool) (B fuel₁ fuel₂ : ℕ)
175
+ (s₁ : σ) (s₂ : σ') (a : τ) :
176
+ mapReadersResult g₁ g₂
177
+ (run read₁ (fun x => key₁ (f₁ x)) read₂ (fun y => key₂ (f₂ y)) K
178
+ (fun x y => report (f₁ x) (f₂ y)) B fuel₁ fuel₂ s₁ s₂ a) =
179
+ run read₁' key₁ read₂' key₂ K report B fuel₁ fuel₂ (g₁ s₁) (g₂ s₂) a := by
180
+ let filled := TieBuffer.fill read₂ (fun y => key₂ (f₂ y)) K B s₂
181
+ let long := TieBuffer.hasKey read₂ (fun y => key₂ (f₂ y)) K filled.cursor
182
+ have hp := fun x st => (step_mapReaders f₁ f₂ g₂ read₂ read₂' hr₂ key₂ K
183
+ report filled.buffer filled.cursor long fuel₂ x st).symm
184
+ have hm := TieReplay.run_map f₁ g₁ (mapReaders g₂) read₁ read₁' hr₁ key₁ K
185
+ (step read₂ (fun y => key₂ (f₂ y)) K (fun x y => report (f₁ x) (f₂ y))
186
+ filled.buffer filled.cursor long fuel₂)
187
+ (step read₂' key₂ K report (filled.buffer.map f₂) (g₂ filled.cursor) long fuel₂)
188
+ hp fuel₁ s₁ ⟨filled.cursor, a, 0, 0, 0⟩
189
+ simp only [run, mapReadersResult,
190
+ ← TieBuffer.fill_map f₂ g₂ read₂ read₂' hr₂ key₂ K B s₂,
191
+ TieBuffer.mapAll, Array.size_map,
192
+ TieBuffer.hasKey_map f₂ g₂ read₂ read₂' hr₂ key₂ K,
193
+ TieBuffer.hasKey_map f₁ g₁ read₁ read₁' hr₁ key₁ K]
194
+ rw [hm]
195
+ rfl
196
+
197
+ end TieGroup
198
+
199
+ namespace StreamJoin
200
+
201
+ variable {α' β' σ₁' σ₂' : Type*}
202
+
203
+ def mapReaders (g₁ : σ → σ₁') (g₂ : σ' → σ₂') (a : State σ σ' τ) : State σ₁' σ₂' τ :=
204
+ ⟨g₁ a.left, g₂ a.right, a.user, a.queries, a.reports, a.copies, a.done⟩
205
+
206
+ def mapReadersStopped (g₁ : σ → σ₁') (g₂ : σ' → σ₂')
207
+ (a : StoppedResult σ σ' τ) : StoppedResult σ₁' σ₂' τ :=
208
+ ⟨mapReaders g₁ g₂ a.state, a.steps⟩
209
+
210
+ theorem step_mapReaders (f₁ : α → α') (f₂ : β → β') (g₁ : σ → σ₁') (g₂ : σ' → σ₂')
211
+ (read₁ : σ → Option (α × σ)) (read₁' : σ₁' → Option (α' × σ₁'))
212
+ (read₂ : σ' → Option (β × σ')) (read₂' : σ₂' → Option (β' × σ₂'))
213
+ (hr₁ : ∀ s, read₁' (g₁ s) = (read₁ s).map (Prod.map f₁ g₁))
214
+ (hr₂ : ∀ s, read₂' (g₂ s) = (read₂ s).map (Prod.map f₂ g₂))
215
+ (key₁ : α' → ℤ) (key₂ : β' → ℤ) (report : α' → β' → τ → τ × Bool)
216
+ (B fuel₁ fuel₂ : ℕ) (a : State σ σ' τ) :
217
+ mapReaders g₁ g₂ (step read₁ (fun x => key₁ (f₁ x)) read₂ (fun y => key₂ (f₂ y))
218
+ (fun x y => report (f₁ x) (f₂ y)) B fuel₁ fuel₂ a) =
219
+ step read₁' key₁ read₂' key₂ report B fuel₁ fuel₂ (mapReaders g₁ g₂ a) := by
220
+ by_cases hd : a.done = true
221
+ · simp only [step, mapReaders, hd, ↓reduceIte]
222
+ · cases h₁ : read₁ a.left with
223
+ | none => simp only [step, mapReaders, hd, Bool.false_eq_true, ↓reduceIte,
224
+ hr₁, h₁, Option.map_none]
225
+ | some p₁ =>
226
+ rcases p₁ with ⟨x, l⟩
227
+ cases h₂ : read₂ a.right with
228
+ | none => simp only [step, mapReaders, hd, Bool.false_eq_true, ↓reduceIte,
229
+ hr₁, hr₂, h₁, h₂, Option.map_none, Option.map_some, Prod.map]
230
+ | some p₂ =>
231
+ rcases p₂ with ⟨y, r⟩
232
+ simp only [step, mapReaders, hd, Bool.false_eq_true, ↓reduceIte,
233
+ hr₁, hr₂, h₁, h₂, Option.map_some, Prod.map,
234
+ ← TieGroup.run_mapReaders f₁ f₂ g₁ g₂ read₁ read₁' read₂ read₂' hr₁ hr₂
235
+ key₁ key₂ (key₁ (f₁ x)) report B fuel₁ fuel₂,
236
+ TieGroup.mapReadersResult, TieReplay.mapAll, TieGroup.mapReaders]
237
+ split
238
+ · rfl
239
+ · split <;> rfl
240
+
241
+ theorem stoppedAcc_mapReaders (f₁ : α → α') (f₂ : β → β')
242
+ (g₁ : σ → σ₁') (g₂ : σ' → σ₂')
243
+ (read₁ : σ → Option (α × σ)) (read₁' : σ₁' → Option (α' × σ₁'))
244
+ (read₂ : σ' → Option (β × σ')) (read₂' : σ₂' → Option (β' × σ₂'))
245
+ (hr₁ : ∀ s, read₁' (g₁ s) = (read₁ s).map (Prod.map f₁ g₁))
246
+ (hr₂ : ∀ s, read₂' (g₂ s) = (read₂ s).map (Prod.map f₂ g₂))
247
+ (key₁ : α' → ℤ) (key₂ : β' → ℤ) (report : α' → β' → τ → τ × Bool)
248
+ (B fuel₁ fuel₂ fuel : ℕ) (a : State σ σ' τ) :
249
+ mapReadersStopped g₁ g₂ (stoppedAcc read₁ (fun x => key₁ (f₁ x))
250
+ read₂ (fun y => key₂ (f₂ y)) (fun x y => report (f₁ x) (f₂ y)) B fuel₁ fuel₂ fuel a) =
251
+ stoppedAcc read₁' key₁ read₂' key₂ report B fuel₁ fuel₂ fuel (mapReaders g₁ g₂ a) := by
252
+ induction fuel generalizing a with
253
+ | zero => rfl
254
+ | succ fuel ih =>
255
+ by_cases hd : a.done = true
256
+ · simp only [stoppedAcc, mapReadersStopped, mapReaders, hd, ↓reduceIte]
257
+ · have hdone : (mapReaders g₁ g₂ a).done = a.done := rfl
258
+ have hm := ih (step read₁ (fun x => key₁ (f₁ x)) read₂ (fun y => key₂ (f₂ y))
259
+ (fun x y => report (f₁ x) (f₂ y)) B fuel₁ fuel₂ a)
260
+ simp only [stoppedAcc, hdone, hd, Bool.false_eq_true, ↓reduceIte]
261
+ rw [← step_mapReaders f₁ f₂ g₁ g₂ read₁ read₁' read₂ read₂' hr₁ hr₂
262
+ key₁ key₂ report B fuel₁ fuel₂, ← hm]
263
+ rfl
264
+
265
+ end StreamJoin
266
+
267
+ end LowSpaceSubsetSum
268
+
269
+ end OAI
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/JoinUserMap.lean ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import OAI.Combinatorics.LowSpaceSubsetSum.Search.StoppedStreamJoin
2
+
3
+ namespace OAI
4
+
5
+ /-! # Erasing proof-carrying callback states through the actual join
6
+
7
+ This refinement lets a counted dictionary carry its invariant intrinsically,
8
+ while retaining exactly the original join's cursors, counters and halt behavior.
9
+ -/
10
+
11
+ namespace LowSpaceSubsetSum
12
+
13
+ universe u v s t w z
14
+ variable {α : Type u} {β : Type v} {σ : Type s} {τ : Type w} {τ' : Type z}
15
+
16
+ namespace TieReplay
17
+
18
+ def mapUser (f : τ → τ') (r : Result σ τ) : Result σ τ' :=
19
+ ⟨r.cursor, f r.state, r.queries, r.reports, r.complete, r.halted⟩
20
+
21
+ theorem runAcc_mapUser (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ)
22
+ (report : α → τ → τ × Bool) (report' : α → τ' → τ' × Bool) (f : τ → τ')
23
+ (hf : ∀ x a, report' x (f a) = (f (report x a).1, (report x a).2))
24
+ (fuel : ℕ) (s : σ) (a : τ) (q r : ℕ) :
25
+ mapUser f (runAcc read key K report fuel s a q r) =
26
+ runAcc read key K report' fuel s (f a) q r := by
27
+ induction fuel generalizing s a q r with
28
+ | zero => rfl
29
+ | succ fuel ih =>
30
+ cases hr : read s with
31
+ | none => simp only [runAcc, hr, mapUser]
32
+ | some p =>
33
+ rcases p with ⟨x, s'⟩
34
+ simp only [runAcc, hr]
35
+ split
36
+ · rw [hf]
37
+ split
38
+ · rfl
39
+ · exact ih _ _ _ _
40
+ · rfl
41
+
42
+ theorem run_mapUser (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ)
43
+ (report : α → τ → τ × Bool) (report' : α → τ' → τ' × Bool) (f : τ → τ')
44
+ (hf : ∀ x a, report' x (f a) = (f (report x a).1, (report x a).2))
45
+ (fuel : ℕ) (s : σ) (a : τ) :
46
+ mapUser f (run read key K report fuel s a) =
47
+ run read key K report' fuel s (f a) :=
48
+ runAcc_mapUser read key K report report' f hf fuel s a 0 0
49
+
50
+ end TieReplay
51
+
52
+ namespace JoinOne
53
+
54
+ theorem run_mapUser (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ)
55
+ (report : α → τ → τ × Bool) (report' : α → τ' → τ' × Bool) (f : τ → τ')
56
+ (hf : ∀ x a, report' x (f a) = (f (report x a).1, (report x a).2))
57
+ (buffer : Array α) (saved : σ) (long : Bool) (fuel : ℕ) (a : τ) :
58
+ TieReplay.mapUser f (run read key K report buffer saved long fuel a) =
59
+ run read key K report' buffer saved long fuel (f a) := by
60
+ simp only [run, BufferReplay.run,
61
+ ← TieReplay.run_mapUser (BufferReplay.read buffer) key K report report' f hf,
62
+ TieReplay.mapUser]
63
+ split
64
+ · simp_all only [↓reduceIte]
65
+ · simp_all only [Bool.false_eq_true, ↓reduceIte]
66
+ split
67
+ · simp_all only
68
+ have h := TieReplay.run_mapUser read key K report report' f hf fuel saved
69
+ (TieReplay.run (BufferReplay.read buffer) key K report buffer.size 0 a).state
70
+ cases h₁ : TieReplay.run read key K report fuel saved
71
+ (TieReplay.run (BufferReplay.read buffer) key K report buffer.size 0 a).state
72
+ simp only [h₁, TieReplay.mapUser] at h
73
+ rw [← h]
74
+ · simp_all only
75
+
76
+ end JoinOne
77
+
78
+ namespace TieGroup
79
+
80
+ variable {σ₂ : Type t}
81
+
82
+ def mapUser (f : τ → τ') (a : State σ₂ τ) : State σ₂ τ' :=
83
+ ⟨a.last, f a.user, a.queries, a.reports, a.restores⟩
84
+
85
+ def mapResult (f : τ → τ') (r : Result σ σ₂ τ) : Result σ σ₂ τ' :=
86
+ ⟨TieReplay.mapUser (mapUser f) r.outer, r.fillQueries, r.bufferSize, r.snapshot⟩
87
+
88
+ theorem step_mapUser (read : σ₂ → Option (β × σ₂)) (key : β → ℤ) (K : ℤ)
89
+ (report : α → β → τ → τ × Bool) (report' : α → β → τ' → τ' × Bool) (f : τ → τ')
90
+ (hf : ∀ x y a, report' x y (f a) = (f (report x y a).1, (report x y a).2))
91
+ (buffer : Array β) (saved : σ₂) (long : Bool) (fuel : ℕ) (x : α) (a : State σ₂ τ) :
92
+ (mapUser f (step read key K report buffer saved long fuel x a).1,
93
+ (step read key K report buffer saved long fuel x a).2) =
94
+ step read key K report' buffer saved long fuel x (mapUser f a) := by
95
+ simp only [step, mapUser,
96
+ ← JoinOne.run_mapUser read key K (report x) (report' x) f (hf x), TieReplay.mapUser]
97
+
98
+ theorem run_mapUser (read₁ : σ → Option (α × σ)) (key₁ : α → ℤ)
99
+ (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ) (K : ℤ)
100
+ (report : α → β → τ → τ × Bool) (report' : α → β → τ' → τ' × Bool) (f : τ → τ')
101
+ (hf : ∀ x y a, report' x y (f a) = (f (report x y a).1, (report x y a).2))
102
+ (B fuel₁ fuel₂ : ℕ) (s₁ : σ) (s₂ : σ₂) (a : τ) :
103
+ mapResult f (run read₁ key₁ read₂ key₂ K report B fuel₁ fuel₂ s₁ s₂ a) =
104
+ run read₁ key₁ read₂ key₂ K report' B fuel₁ fuel₂ s₁ s₂ (f a) := by
105
+ let filled := TieBuffer.fill read₂ key₂ K B s₂
106
+ let long := TieBuffer.hasKey read₂ key₂ K filled.cursor
107
+ have hstep := fun x st => (step_mapUser read₂ key₂ K report report' f hf
108
+ filled.buffer filled.cursor long fuel₂ x st).symm
109
+ have h := TieReplay.run_mapUser read₁ key₁ K
110
+ (step read₂ key₂ K report filled.buffer filled.cursor long fuel₂)
111
+ (step read₂ key₂ K report' filled.buffer filled.cursor long fuel₂)
112
+ (mapUser f) hstep fuel₁ s₁ ⟨filled.cursor, a, 0, 0, 0⟩
113
+ change mapResult f ⟨_, filled.queries, filled.buffer.size, _⟩ = _
114
+ unfold mapResult
115
+ rw [h]
116
+ rfl
117
+
118
+ end TieGroup
119
+ namespace StreamJoin
120
+
121
+ variable {σ₂ : Type t}
122
+
123
+ def mapUser (f : τ → τ') (a : State σ σ₂ τ) : State σ σ₂ τ' :=
124
+ ⟨a.left, a.right, f a.user, a.queries, a.reports, a.copies, a.done⟩
125
+
126
+ def mapStopped (f : τ → τ') (a : StoppedResult σ σ₂ τ) : StoppedResult σ σ₂ τ' :=
127
+ ⟨mapUser f a.state, a.steps⟩
128
+
129
+ theorem step_mapUser (read₁ : σ → Option (α × σ)) (key₁ : α → ℤ)
130
+ (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ)
131
+ (report : α → β → τ → τ × Bool) (report' : α → β → τ' → τ' × Bool) (f : τ → τ')
132
+ (hf : ∀ x y a, report' x y (f a) = (f (report x y a).1, (report x y a).2))
133
+ (B fuel₁ fuel₂ : ℕ) (a : State σ σ₂ τ) :
134
+ mapUser f (step read₁ key₁ read₂ key₂ report B fuel₁ fuel₂ a) =
135
+ step read₁ key₁ read₂ key₂ report' B fuel₁ fuel₂ (mapUser f a) := by
136
+ by_cases hd : a.done = true
137
+ · simp only [step, mapUser, hd, ↓reduceIte]
138
+ · cases h₁ : read₁ a.left with
139
+ | none => simp only [step, mapUser, hd, Bool.false_eq_true, ↓reduceIte, h₁]
140
+ | some p₁ =>
141
+ rcases p₁ with ⟨x, l⟩
142
+ cases h₂ : read₂ a.right with
143
+ | none => simp only [step, mapUser, hd, Bool.false_eq_true, ↓reduceIte, h₁, h₂]
144
+ | some p₂ =>
145
+ rcases p₂ with ⟨y, r⟩
146
+ simp only [step, mapUser, hd, Bool.false_eq_true, ↓reduceIte, h₁, h₂,
147
+ ← TieGroup.run_mapUser read₁ key₁ read₂ key₂ (key₁ x) report report' f hf,
148
+ TieGroup.mapResult, TieReplay.mapUser, TieGroup.mapUser]
149
+ split
150
+ · simp_all only
151
+ · split <;> simp_all only
152
+
153
+ theorem stoppedAcc_mapUser (read₁ : σ → Option (α × σ)) (key₁ : α → ℤ)
154
+ (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ)
155
+ (report : α → β → τ → τ × Bool) (report' : α → β → τ' → τ' × Bool) (f : τ → τ')
156
+ (hf : ∀ x y a, report' x y (f a) = (f (report x y a).1, (report x y a).2))
157
+ (B fuel₁ fuel₂ fuel : ℕ) (a : State σ σ₂ τ) :
158
+ mapStopped f (stoppedAcc read₁ key₁ read₂ key₂ report B fuel₁ fuel₂ fuel a) =
159
+ stoppedAcc read₁ key₁ read₂ key₂ report' B fuel₁ fuel₂ fuel (mapUser f a) := by
160
+ induction fuel generalizing a with
161
+ | zero => rfl
162
+ | succ fuel ih =>
163
+ by_cases hd : a.done = true
164
+ · simp only [stoppedAcc, mapStopped, mapUser, hd, ↓reduceIte]
165
+ · have h := ih (step read₁ key₁ read₂ key₂ report B fuel₁ fuel₂ a)
166
+ have hdone : (mapUser f a).done = a.done := rfl
167
+ simp only [stoppedAcc, hdone, hd, Bool.false_eq_true, ↓reduceIte]
168
+ rw [← step_mapUser read₁ key₁ read₂ key₂ report report' f hf]
169
+ rw [← h]
170
+ rfl
171
+
172
+ theorem run_mapUser (read₁ : σ → Option (α × σ)) (key₁ : α → ℤ)
173
+ (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ)
174
+ (report : α → β → τ → τ × Bool) (report' : α → β → τ' → τ' × Bool) (f : τ → τ')
175
+ (hf : ∀ x y a, report' x y (f a) = (f (report x y a).1, (report x y a).2))
176
+ (B fuel₁ fuel₂ fuel : ℕ) (s₁ : σ) (s₂ : σ₂) (a : τ) :
177
+ mapUser f (run read₁ key₁ read₂ key₂ report B fuel₁ fuel₂ fuel s₁ s₂ a) =
178
+ run read₁ key₁ read₂ key₂ report' B fuel₁ fuel₂ fuel s₁ s₂ (f a) := by
179
+ have h := congrArg StoppedResult.state (stoppedAcc_mapUser read₁ key₁ read₂ key₂
180
+ report report' f hf B fuel₁ fuel₂ fuel (start s₁ s₂ a))
181
+ simpa only [mapStopped, stoppedAcc_eq, mapUser, start, run] using h
182
+
183
+ end StreamJoin
184
+
185
+ end LowSpaceSubsetSum
186
+
187
+ end OAI
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MeasuredDistinctCount.lean ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import OAI.Combinatorics.LowSpaceSubsetSum.Streams.DistinctStreamCount
2
+
3
+ namespace OAI
4
+
5
+ /-! # Tail-recursive distinct counting with measured reader calls
6
+
7
+ Only the current reader state, previous key, count, remaining fuel and work
8
+ counter survive each iteration. No list of emitted keys is constructed.
9
+ -/
10
+
11
+ namespace LowSpaceSubsetSum.MeasuredDistinctCount
12
+
13
+ variable {α σ : Type*}
14
+
15
+ def loop (read : σ → Option (α × σ) × ℕ) (key : α → ℤ × ℕ) :
16
+ ℕ → σ → Option ℤ → ℕ → ℕ → ℕ × ℕ
17
+ | 0, _, _, count, work => (count, work + 1)
18
+ | fuel + 1, state, previous, count, work =>
19
+ let out := read state
20
+ match out.1 with
21
+ | none => (count, work + out.2 + 1)
22
+ | some (x, next) =>
23
+ let k := key x
24
+ let fresh := match previous with | none => true | some p => decide (p ≠ k.1)
25
+ loop read key fuel next (some k.1) (count + if fresh then 1 else 0)
26
+ (work + out.2 + k.2 + 3)
27
+
28
+ theorem loop_value (read : σ → Option (α × σ) × ℕ) (key : α → ℤ × ℕ)
29
+ (fuel : ℕ) (s : σ) (previous : Option ℤ) (count work : ℕ) :
30
+ (loop read key fuel s previous count work).1 = count +
31
+ match previous with
32
+ | none => (DistinctStreamCount.run (fun s => (read s).1) (fun x => (key x).1) fuel s).1
33
+ | some p => (DistinctStreamCount.tail (fun s => (read s).1) (fun x => (key x).1) fuel s p).1 := by
34
+ induction fuel generalizing s previous count work with
35
+ | zero => cases previous <;> simp only [loop, DistinctStreamCount.run, DistinctStreamCount.tail, Nat.add_zero]
36
+ | succ fuel ih =>
37
+ cases previous with
38
+ | none =>
39
+ cases hr : (read s).1 with
40
+ | none => simp only [loop, hr, DistinctStreamCount.run, Nat.add_zero]
41
+ | some out =>
42
+ rcases out with ⟨x, next⟩
43
+ simp only [loop, hr, ↓reduceIte, ih, DistinctStreamCount.run]
44
+ omega
45
+ | some p =>
46
+ cases hr : (read s).1 with
47
+ | none => simp only [loop, hr, DistinctStreamCount.tail, Nat.add_zero]
48
+ | some out =>
49
+ rcases out with ⟨x, next⟩
50
+ by_cases he : p = (key x).1
51
+ · subst p
52
+ simp only [loop, hr, ne_eq, not_true_eq_false, decide_false, Bool.false_eq_true,
53
+ ↓reduceIte, Nat.add_zero, ih, DistinctStreamCount.tail]
54
+ · simp only [loop, hr, ne_eq, he, not_false_eq_true, decide_true, ↓reduceIte,
55
+ ih, DistinctStreamCount.tail]
56
+ omega
57
+
58
+ theorem loop_work (read : σ → Option (α × σ) × ℕ) (key : α → ℤ × ℕ)
59
+ (R K : ℕ) (hread : ∀ s, (read s).2 ≤ R) (hkey : ∀ x, (key x).2 ≤ K)
60
+ (fuel : ℕ) (s : σ) (previous : Option ℤ) (count work : ℕ) :
61
+ (loop read key fuel s previous count work).2 ≤ work + (R + K + 4) * fuel + 1 := by
62
+ induction fuel generalizing s previous count work with
63
+ | zero => simp only [loop, Nat.mul_zero, Nat.add_zero, le_refl]
64
+ | succ fuel ih =>
65
+ have hr := hread s
66
+ simp only [loop]
67
+ split
68
+ · dsimp only
69
+ nlinarith only [hr, Nat.zero_le ((R + K + 4) * fuel)]
70
+ next x next _ =>
71
+ have hk := hkey x
72
+ have ht := ih next (some (key x).1)
73
+ (count + if (match previous with | none => true | some p => decide (p ≠ (key x).1))
74
+ then 1 else 0) (work + (read s).2 + (key x).2 + 3)
75
+ nlinarith only [hr, hk, ht]
76
+
77
+ def run (read : σ → Option (α × σ) × ℕ) (key : α → ℤ × ℕ) (fuel : ℕ) (s : σ) : ℕ × ℕ :=
78
+ loop read key fuel s none 0 0
79
+
80
+ theorem run_value (read : σ → Option (α × σ) × ℕ) (key : α → ℤ × ℕ) (fuel : ℕ) (s : σ) :
81
+ (run read key fuel s).1 =
82
+ (DistinctStreamCount.run (fun s => (read s).1) (fun x => (key x).1) fuel s).1 := by
83
+ simpa only [run, Nat.zero_add] using loop_value read key fuel s none 0 0
84
+
85
+ theorem run_work (read : σ → Option (α × σ) × ℕ) (key : α → ℤ × ℕ)
86
+ (R K : ℕ) (hread : ∀ s, (read s).2 ≤ R) (hkey : ∀ x, (key x).2 ≤ K)
87
+ (fuel : ℕ) (s : σ) :
88
+ (run read key fuel s).2 ≤ (R + K + 4) * fuel + 1 := by
89
+ simpa only [run, Nat.zero_add] using loop_work read key R K hread hkey fuel s none 0 0
90
+
91
+ end LowSpaceSubsetSum.MeasuredDistinctCount
92
+
93
+ end OAI
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MeasuredInitialization.lean ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import OAI.Combinatorics.LowSpaceSubsetSum.Representation.RepresentationWeightedReader
2
+
3
+ namespace OAI
4
+
5
+ /-! # Measured construction of the row tournament
6
+
7
+ Each leaf calls its measured initializer once; each internal node evaluates
8
+ its two candidate keys. Binary paths are converted to array indices by an
9
+ explicit recursive computation. No row array is constructed by this routine.
10
+ -/
11
+
12
+ namespace LowSpaceSubsetSum
13
+
14
+ namespace Tournament
15
+
16
+ variable {α : Type*}
17
+
18
+ def measuredBuild (key : α → ℤ × ℕ) : (d : ℕ) →
19
+ ((Fin d → Bool) → Option α × ℕ) → Tree α d × ℕ
20
+ | 0, front =>
21
+ let x := front Fin.elim0
22
+ (.leaf x.1, x.2 + 1)
23
+ | d + 1, front =>
24
+ let l := measuredBuild key d (fun p => front (Fin.cons false p))
25
+ let r := measuredBuild key d (fun p => front (Fin.cons true p))
26
+ let w := measuredPick key (winner l.1) (winner r.1)
27
+ (.node w.1 l.1 r.1, l.2 + r.2 + w.2 + 5)
28
+
29
+ theorem measuredBuild_value (key : α → ℤ × ℕ) (d : ℕ)
30
+ (front : (Fin d → Bool) → Option α × ℕ) :
31
+ (measuredBuild key d front).1 = build (fun x => (key x).1) d (fun p => (front p).1) := by
32
+ induction d with
33
+ | zero => rfl
34
+ | succ d ih => simp only [measuredBuild, build, measuredPick_value, ih, node]
35
+
36
+ theorem measuredBuild_work (key : α → ℤ × ℕ) (K R : ℕ)
37
+ (hk : ∀ x, (key x).2 ≤ K) (d : ℕ)
38
+ (front : (Fin d → Bool) → Option α × ℕ) (hf : ∀ p, (front p).2 ≤ R) :
39
+ (measuredBuild key d front).2 ≤ (R + 2 * K + 9) * 2 ^ d - (2 * K + 8) := by
40
+ induction d with
41
+ | zero => simp only [measuredBuild, pow_zero, Nat.mul_one]; have := hf Fin.elim0; omega
42
+ | succ d ih =>
43
+ have hl := ih (fun p => front (Fin.cons false p)) (fun p => hf _)
44
+ have hr := ih (fun p => front (Fin.cons true p)) (fun p => hf _)
45
+ have hp := measuredPick_work key K hk
46
+ (winner (measuredBuild key d (fun p => front (Fin.cons false p))).1)
47
+ (winner (measuredBuild key d (fun p => front (Fin.cons true p))).1)
48
+ have hpow : 1 ≤ 2 ^ d := Nat.one_le_pow _ _ (by decide)
49
+ have hbase : 2 * K + 8 ≤ (R + 2 * K + 9) * 2 ^ d := by nlinarith
50
+ simp only [measuredBuild, pow_succ, ← Nat.mul_assoc]
51
+ omega
52
+
53
+ end Tournament
54
+
55
+ namespace PaddedRows
56
+
57
+ /-- Little-endian binary evaluation. The cost includes access to a bit in a
58
+ path built by at most `d` nested `Fin.cons` nodes. -/
59
+ def measuredIndex : (d : ℕ) → (RowMerge.Path d) → ℕ × ℕ
60
+ | 0, _ => (0, 1)
61
+ | d + 1, p =>
62
+ let t := measuredIndex d (fun i => p i.succ)
63
+ ((if p 0 then 1 else 0) + 2 * t.1, t.2 + 2 * d + 6)
64
+
65
+ private theorem index_sum (d : ℕ) (p : RowMerge.Path d) :
66
+ (index d p).val = ∑ i : Fin d, (if p i then 1 else 0) * 2 ^ i.val := by
67
+ change (∑ i : Fin d, (finTwoEquiv.symm (p i)).val * 2 ^ i.val) = _
68
+ apply Finset.sum_congr rfl
69
+ intro i _
70
+ cases h : p i <;> rfl
71
+
72
+ theorem measuredIndex_value (d : ℕ) (p : RowMerge.Path d) :
73
+ (measuredIndex d p).1 = (index d p).val := by
74
+ induction d with
75
+ | zero => simp [measuredIndex]
76
+ | succ d ih =>
77
+ rw [index_sum, Fin.sum_univ_succ]
78
+ simp only [measuredIndex, ih, index_sum, Fin.val_zero, pow_zero, Nat.mul_one,
79
+ Fin.val_succ, pow_succ']
80
+ rw [Finset.mul_sum]
81
+ congr 1
82
+ apply Finset.sum_congr rfl
83
+ intro i _
84
+ ring
85
+
86
+ theorem measuredIndex_work (d : ℕ) (p : RowMerge.Path d) :
87
+ (measuredIndex d p).2 ≤ 4 * (d + 1) ^ 2 := by
88
+ induction d with
89
+ | zero => norm_num [measuredIndex]
90
+ | succ d ih =>
91
+ have h := ih (fun i => p i.succ)
92
+ change _ + 2 * d + 6 ≤ _
93
+ nlinarith
94
+
95
+ end PaddedRows
96
+ end LowSpaceSubsetSum
97
+
98
+ namespace LowSpaceSubsetSum.FilteredStream
99
+
100
+ variable {α β : Type*}
101
+
102
+ /-- Initialize and read one padded row, directly from the shared arrays. -/
103
+ def measuredFront (left : Array α) (right : Array β)
104
+ (row : α → PairCursor.State α right.size × ℕ) (d : ℕ) (p : RowMerge.Path d) :
105
+ Option (RowMerge.Front d (α × β) (Cursor (α := α) right)) × ℕ :=
106
+ let i := PaddedRows.measuredIndex d p
107
+ if h : i.1 < left.size then
108
+ let r := row left[i.1]
109
+ let q := countedRead right (some r.1)
110
+ (q.1.map (fun z => ⟨p, z.1, z.2⟩), i.2 + r.2 + q.2 + 6)
111
+ else (none, i.2 + 2)
112
+
113
+ theorem measuredFront_value (left : Array α) (right : Array β)
114
+ (row : α → PairCursor.State α right.size × ℕ) (d : ℕ) (p : RowMerge.Path d) :
115
+ (measuredFront left right row d p).1 =
116
+ RowMerge.front (read right) p
117
+ (PaddedRows.rows (left.map (fun x => (row x).1)) d p) := by
118
+ simp only [measuredFront, PaddedRows.measuredIndex_value, PaddedRows.rows,
119
+ Array.size_map, RowMerge.front]
120
+ split_ifs with h
121
+ · simp only [Array.getElem_map, countedRead_value]
122
+ · rfl
123
+
124
+ theorem measuredFront_work (left : Array α) (right : Array β)
125
+ (row : α → PairCursor.State α right.size × ℕ) (R : ℕ)
126
+ (hr : ∀ x, (row x).2 ≤ R) (d : ℕ) (p : RowMerge.Path d) :
127
+ (measuredFront left right row d p).2 ≤ 4 * (d + 1) ^ 2 + R + 30 := by
128
+ have hi := PaddedRows.measuredIndex_work d p
129
+ unfold measuredFront
130
+ dsimp only
131
+ split
132
+ · have hr' := hr left[(PaddedRows.measuredIndex d p).1]
133
+ have hq := countedRead_work right (some (row left[(PaddedRows.measuredIndex d p).1]).1)
134
+ dsimp only
135
+ omega
136
+ · dsimp only
137
+ omega
138
+
139
+ def measuredInitialTree (left : Array α) (right : Array β) (key : α × β → ℤ × ℕ)
140
+ (row : α → PairCursor.State α right.size × ℕ) (d : ℕ) :=
141
+ Tournament.measuredBuild
142
+ (fun x : RowMerge.Front d (α × β) (Cursor (α := α) right) => key x.value)
143
+ d (measuredFront left right row d)
144
+
145
+ theorem measuredInitialTree_value (left : Array α) (right : Array β)
146
+ (key : α × β → ℤ × ℕ) (row : α → PairCursor.State α right.size × ℕ) (d : ℕ) :
147
+ (measuredInitialTree left right key row d).1 =
148
+ RowMerge.start (fun x => (key x).1) (read right)
149
+ (PaddedRows.rows (left.map (fun x => (row x).1)) d) := by
150
+ simp only [measuredInitialTree, Tournament.measuredBuild_value, RowMerge.start]
151
+ congr 1
152
+ funext p
153
+ exact measuredFront_value left right row d p
154
+
155
+ theorem measuredInitialTree_work (left : Array α) (right : Array β)
156
+ (key : α × β → ℤ × ℕ) (row : α → PairCursor.State α right.size × ℕ)
157
+ (K R : ℕ) (hk : ∀ x, (key x).2 ≤ K) (hr : ∀ x, (row x).2 ≤ R) (d : ℕ) :
158
+ (measuredInitialTree left right key row d).2 ≤
159
+ (4 * (d + 1) ^ 2 + R + 2 * K + 39) * 2 ^ d := by
160
+ have h := Tournament.measuredBuild_work (fun x => key x.value) K
161
+ (4 * (d + 1) ^ 2 + R + 30) (fun x => hk x.value) d
162
+ (measuredFront left right row d) (measuredFront_work left right row R hr d)
163
+ calc
164
+ _ ≤ (4 * (d + 1) ^ 2 + R + 30 + 2 * K + 9) * 2 ^ d - (2 * K + 8) := h
165
+ _ ≤ (4 * (d + 1) ^ 2 + R + 30 + 2 * K + 9) * 2 ^ d := Nat.sub_le _ _
166
+ _ = _ := by ring
167
+
168
+ end LowSpaceSubsetSum.FilteredStream
169
+
170
+ end OAI
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MeasuredLog2.lean ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Mathlib.Data.Nat.Log
2
+
3
+ namespace OAI
4
+
5
+ /-! # A bounded tail-recursive binary logarithm
6
+
7
+ This is the integer operation needed to turn measured mixer counts into
8
+ prime widths. Each iteration divides by two and updates two counters.
9
+ -/
10
+
11
+ namespace LowSpaceSubsetSum.MeasuredLog2
12
+
13
+ def loop : ℕ → ℕ → ℕ → ℕ → ℕ × ℕ
14
+ | 0, _, value, work => (value, work + 1)
15
+ | fuel + 1, x, value, work =>
16
+ if 2 ≤ x then loop fuel (x / 2) (value + 1) (work + 3)
17
+ else (value, work + 1)
18
+
19
+ theorem loop_value (fuel x value work : ℕ) (hx : Nat.log2 x ≤ fuel) :
20
+ (loop fuel x value work).1 = value + Nat.log2 x := by
21
+ induction fuel generalizing x value work with
22
+ | zero =>
23
+ have hz : Nat.log2 x = 0 := by omega
24
+ simp [loop, hz]
25
+ | succ fuel ih =>
26
+ rw [loop]
27
+ split
28
+ next h =>
29
+ have he := Nat.log2_def x
30
+ rw [ite_eq_left h] at he
31
+ rw [ih _ _ _ (by omega), he]
32
+ omega
33
+ next h => simp only [Nat.log2_def x, ite_eq_right h, Nat.add_zero]
34
+
35
+ theorem loop_work (fuel x value work : ℕ) :
36
+ (loop fuel x value work).2 ≤ work + 3 * fuel + 1 := by
37
+ induction fuel generalizing x value work with
38
+ | zero => simp [loop]
39
+ | succ fuel ih =>
40
+ rw [loop]
41
+ split
42
+ · have h := ih (x / 2) (value + 1) (work + 3); omega
43
+ · simp only; omega
44
+
45
+ def run (bits x : ℕ) : ℕ × ℕ := loop bits x 0 0
46
+
47
+ theorem run_value (bits x : ℕ) (hx : x ≤ 2 ^ bits) :
48
+ (run bits x).1 = Nat.log2 x := by
49
+ have hlog : Nat.log2 x ≤ bits := by
50
+ rw [Nat.log2_eq_log_two]
51
+ have h := Nat.log_mono_right (b := 2) hx
52
+ simpa only [Nat.log_pow (by decide : 1 < 2)] using h
53
+ simpa only [run, Nat.zero_add] using loop_value bits x 0 0 hlog
54
+
55
+ theorem run_work (bits x : ℕ) : (run bits x).2 ≤ 3 * bits + 1 := by
56
+ simpa only [run, Nat.zero_add] using loop_work bits x 0 0
57
+
58
+ end LowSpaceSubsetSum.MeasuredLog2
59
+
60
+ end OAI
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MeasuredMixerCount.lean ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import OAI.Combinatorics.LowSpaceSubsetSum.Streams.MeasuredSumReader
2
+ import OAI.Combinatorics.LowSpaceSubsetSum.Counting.MixerParameterCount
3
+ import OAI.Combinatorics.LowSpaceSubsetSum.Compression.CompressionWeights
4
+
5
+ namespace OAI
6
+
7
+ /-! # Mixer counts from generated and sorted half-sum arrays
8
+
9
+ All subset weights, comparisons, array copies and streamed sum keys are
10
+ charged. The returned natural number is the exact distinct-sum count.
11
+ -/
12
+
13
+ namespace LowSpaceSubsetSum.MeasuredMixerCount
14
+
15
+ variable {n : ℕ}
16
+
17
+ def sortedWeights (a : Fin n → ℤ) (indices : List (Fin n)) : Array ℤ × ℕ :=
18
+ let raw := CompressionWeights.raw a indices
19
+ let out := MeasuredSort.sort (fun x y : ℤ => (decide (x ≤ y), 1)) raw.1
20
+ (out.1.toArray, raw.2 + out.2 + out.1.length + 1)
21
+
22
+ theorem sortedWeights_value (a : Fin n → ℤ) (V : Finset (Fin n)) :
23
+ (sortedWeights a (V.sort (· ≤ ·))).1 = MixerParameterCount.sortedWeights a V := by
24
+ simp only [sortedWeights, CompressionWeights.raw_source, MeasuredSort.sort_value,
25
+ MixerParameterCount.sortedWeights, CountedSort.sort_value]
26
+
27
+ theorem sortedWeights_size (a : Fin n → ℤ) (indices : List (Fin n)) :
28
+ (sortedWeights a indices).1.size = 2 ^ indices.length := by
29
+ simp only [sortedWeights, List.size_toArray, MeasuredSort.sort_value,
30
+ List.length_mergeSort, CompressionWeights.raw_length]
31
+
32
+ theorem sortedWeights_sorted (a : Fin n → ℤ) (indices : List (Fin n)) :
33
+ (sortedWeights a indices).1.toList.Pairwise (· ≤ ·) := by
34
+ simp only [sortedWeights, List.toList_toArray, MeasuredSort.sort_value]
35
+ simpa only [decide_eq_true_eq] using
36
+ (List.pairwise_mergeSort (le := fun x y : ℤ => decide (x ≤ y))
37
+ (fun x y z hxy hyz => decide_eq_true (le_trans (of_decide_eq_true hxy) (of_decide_eq_true hyz)))
38
+ (fun x y => by simpa only [Bool.or_eq_true, decide_eq_true_eq] using le_total x y)
39
+ (CompressionWeights.raw a indices).1)
40
+
41
+ def coefficient (n : ℕ) : ℕ := (n + 4) * n + 12 * n + 20
42
+
43
+ theorem sortedWeights_work (a : Fin n → ℤ) (indices : List (Fin n))
44
+ (hi : indices.length ≤ n) :
45
+ (sortedWeights a indices).2 ≤ coefficient n * 2 ^ indices.length := by
46
+ have hr := CompressionWeights.raw_work a indices hi
47
+ have hs := MeasuredSort.sort_work (fun x y : ℤ => (decide (x ≤ y), 1))
48
+ 1 (fun _ _ => le_rfl) (CompressionWeights.raw a indices).1 n
49
+ (by rw [CompressionWeights.raw_length]; exact Nat.pow_le_pow_right (by decide) hi)
50
+ have hp : 1 ≤ 2 ^ indices.length := Nat.one_le_two_pow
51
+ simp only [CompressionWeights.raw_length] at hs
52
+ change _ + _ + _ + 1 ≤ _
53
+ simp only [MeasuredSort.sort_value, List.length_mergeSort, CompressionWeights.raw_length]
54
+ unfold coefficient
55
+ nlinarith only [hr, hs, hp]
56
+
57
+ def run (a : Fin n → ℤ) (left right : List (Fin n)) : ℕ × ℕ :=
58
+ let xs := sortedWeights a left
59
+ let ys := sortedWeights a right
60
+ let out := MeasuredSumReader.count xs.1 ys.1 (sortedWeights_sorted a right)
61
+ (out.1, xs.2 + ys.2 + out.2 + 3)
62
+
63
+ theorem run_source (a : Fin n → ℤ) (V W : Finset (Fin n)) (hd : Disjoint V W) :
64
+ (run a (V.sort (· ≤ ·)) (W.sort (· ≤ ·))).1 = distinctSumCount a (V ∪ W) := by
65
+ simp only [run, MeasuredSumReader.count_value, sortedWeights_value]
66
+ exact MixerParameterCount.count_value a V W hd
67
+
68
+ theorem run_work (a : Fin n → ℤ) (left right : List (Fin n))
69
+ (hleft : left.length ≤ n) (hright : right.length ≤ n) :
70
+ (run a left right).2 ≤
71
+ coefficient n * 2 ^ left.length + coefficient n * 2 ^ right.length +
72
+ (4 * (left.length + 1) ^ 2 + 32) * 2 ^ left.length +
73
+ (10 * left.length + 21) * 2 ^ (left.length + right.length) + 6 := by
74
+ have hl := sortedWeights_work a left hleft
75
+ have hr := sortedWeights_work a right hright
76
+ have hc := MeasuredSumReader.count_work (sortedWeights a left).1
77
+ (sortedWeights a right).1 (sortedWeights_sorted a right)
78
+ simp only [sortedWeights_size, Nat.clog_pow 2 _ (by decide), ← pow_add] at hc
79
+ change _ + _ + _ + 3 ≤ _
80
+ omega
81
+
82
+ def mixerCount (a : Fin n → ℤ) (V : Finset (Fin n)) : ℕ × ℕ :=
83
+ run a ((MixerParameterCount.firstHalf V).sort (· ≤ ·))
84
+ ((MixerParameterCount.secondHalf V).sort (· ≤ ·))
85
+
86
+ theorem mixerCount_value (a : Fin n → ℤ) (V : Finset (Fin n)) :
87
+ (mixerCount a V).1 = distinctSumCount a V := by
88
+ rw [mixerCount, run_source a _ _ (MixerParameterCount.halves_disjoint V),
89
+ MixerParameterCount.halves_union]
90
+
91
+ end LowSpaceSubsetSum.MeasuredMixerCount
92
+
93
+ end OAI
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MeasuredPivot.lean ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import OAI.Combinatorics.LowSpaceSubsetSum.Representation.RepresentationPivotWork
2
+
3
+ namespace OAI
4
+
5
+ /-! # Binary search with counted predicate evaluations
6
+
7
+ The predicate is evaluated exactly once at each nonempty interval. The
8
+ count includes endpoint arithmetic and the actual predicate callback cost.
9
+ -/
10
+
11
+ namespace LowSpaceSubsetSum.BinaryPivot
12
+
13
+ variable {n : ℕ}
14
+
15
+ def measuredStep (p : Fin n → Bool × ℕ) (c : Cut n) : Cut n × ℕ :=
16
+ if h : c.lo < c.hi then
17
+ let mid := (c.lo + c.hi) / 2
18
+ have hmid : mid < n := by have := c.bounded; dsimp [mid]; omega
19
+ let q := p ⟨mid, hmid⟩
20
+ (if q.1 then
21
+ ⟨mid + 1, c.hi, by dsimp [mid]; omega, c.bounded⟩
22
+ else
23
+ ⟨c.lo, mid, by dsimp [mid]; omega, by have := c.bounded; dsimp [mid]; omega⟩,
24
+ q.2 + 8)
25
+ else (c, 1)
26
+
27
+ theorem measuredStep_value (p : Fin n → Bool × ℕ) (c : Cut n) :
28
+ (measuredStep p c).1 = step (fun i => (p i).1) c := by
29
+ unfold measuredStep step
30
+ split <;> rfl
31
+
32
+ theorem measuredStep_work (p : Fin n → Bool × ℕ) (K : ℕ)
33
+ (hp : ∀ i, (p i).2 ≤ K) (c : Cut n) :
34
+ (measuredStep p c).2 ≤ K + 8 := by
35
+ unfold measuredStep
36
+ split
37
+ · rename_i h
38
+ exact Nat.add_le_add_right (hp ⟨(c.lo + c.hi) / 2, by have := c.bounded; omega⟩) 8
39
+ · omega
40
+
41
+ /-- The accumulator makes the search loop tail recursive. -/
42
+ def measuredRun (p : Fin n → Bool × ℕ) : ℕ → Cut n → ℕ → Cut n × ℕ
43
+ | 0, c, work => (c, work)
44
+ | k + 1, c, work =>
45
+ let q := measuredStep p c
46
+ measuredRun p k q.1 (work + q.2)
47
+
48
+ theorem measuredRun_value (p : Fin n → Bool × ℕ) (k : ℕ) (c : Cut n) (work : ℕ) :
49
+ (measuredRun p k c work).1 = (step (fun i => (p i).1))^[k] c := by
50
+ induction k generalizing c work with
51
+ | zero => rfl
52
+ | succ k ih =>
53
+ rw [measuredRun, ih, measuredStep_value, Function.iterate_succ_apply]
54
+
55
+ theorem measuredRun_work (p : Fin n → Bool × ℕ) (K : ℕ)
56
+ (hp : ∀ i, (p i).2 ≤ K) (k : ℕ) (c : Cut n) (work : ℕ) :
57
+ (measuredRun p k c work).2 ≤ work + (K + 8) * k := by
58
+ induction k generalizing c work with
59
+ | zero => simp only [measuredRun, Nat.mul_zero, Nat.add_zero, le_refl]
60
+ | succ k ih =>
61
+ have hi := ih (measuredStep p c).1 (work + (measuredStep p c).2)
62
+ have hs := measuredStep_work p K hp c
63
+ change (measuredRun p k (measuredStep p c).1 (work + (measuredStep p c).2)).2 ≤ _
64
+ simp only [Nat.mul_add, Nat.mul_one]
65
+ omega
66
+
67
+ def measuredSearch (p : Fin n → Bool × ℕ) (k : ℕ) : Cut n × ℕ :=
68
+ measuredRun p k (initial n) 0
69
+
70
+ theorem measuredSearch_value (p : Fin n → Bool × ℕ) (k : ℕ) :
71
+ (measuredSearch p k).1 = search (fun i => (p i).1) k := measuredRun_value _ _ _ _
72
+
73
+ theorem measuredSearch_work (p : Fin n → Bool × ℕ) (K : ℕ)
74
+ (hp : ∀ i, (p i).2 ≤ K) (k : ℕ) :
75
+ (measuredSearch p k).2 ≤ (K + 8) * k := by
76
+ simpa only [measuredSearch, Nat.zero_add] using measuredRun_work p K hp k (initial n) 0
77
+
78
+ end LowSpaceSubsetSum.BinaryPivot
79
+
80
+ end OAI
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MeasuredRow.lean ADDED
@@ -0,0 +1,212 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import OAI.Combinatorics.LowSpaceSubsetSum.Streams.MeasuredPivot
2
+ import OAI.Combinatorics.LowSpaceSubsetSum.Representation.RepresentationKeys
3
+
4
+ namespace OAI
5
+
6
+ /-! # Modular row initialization with measured weight evaluation
7
+
8
+ Every binary-search predicate executes the stored-record weight routine.
9
+ The left weight is computed once, and all searches address the shared right
10
+ array directly. The resulting cursor is the original filtered row cursor.
11
+ -/
12
+
13
+ namespace LowSpaceSubsetSum
14
+ namespace BinarySlice
15
+
16
+ variable {α : Type*}
17
+
18
+ def measuredRange (xs : Array α) (key : α → ℤ × ℕ) (r : ℤ) (k : ℕ)
19
+ (hs : Monotone (fun i : Fin xs.size => (key xs[i.val]).1))
20
+ (hk : xs.size < 2 ^ k) : SliceCursor.Range xs.size × ℕ :=
21
+ let lo := BinaryPivot.measuredSearch (fun i : Fin xs.size =>
22
+ let q := key xs[i.val]; (decide (q.1 < r), q.2 + 2)) k
23
+ let hi := BinaryPivot.measuredSearch (fun i : Fin xs.size =>
24
+ let q := key xs[i.val]; (decide (q.1 ≤ r), q.2 + 2)) k
25
+ have hlo : lo.1.lo = lower xs (fun x => (key x).1) r k :=
26
+ congrArg BinaryPivot.Cut.lo (BinaryPivot.measuredSearch_value _ _)
27
+ have hhi : hi.1.lo = upper xs (fun x => (key x).1) r k :=
28
+ congrArg BinaryPivot.Cut.lo (BinaryPivot.measuredSearch_value _ _)
29
+ (⟨lo.1.lo, hi.1.lo - lo.1.lo, by
30
+ rw [hlo, hhi]
31
+ exact (range xs (fun x => (key x).1) r k hs hk).bounded⟩,
32
+ lo.2 + hi.2 + 4)
33
+
34
+ theorem measuredRange_value (xs : Array α) (key : α → ℤ × ℕ) (r : ℤ) (k : ℕ)
35
+ (hs : Monotone (fun i : Fin xs.size => (key xs[i.val]).1))
36
+ (hk : xs.size < 2 ^ k) :
37
+ (measuredRange xs key r k hs hk).1 = range xs (fun x => (key x).1) r k hs hk := by
38
+ simp only [measuredRange, BinaryPivot.measuredSearch_value, range, lower, upper]
39
+
40
+ theorem measuredRange_work (xs : Array α) (key : α → ℤ × ℕ) (r : ℤ) (k K : ℕ)
41
+ (hkey : ∀ x, (key x).2 ≤ K)
42
+ (hs : Monotone (fun i : Fin xs.size => (key xs[i.val]).1))
43
+ (hk : xs.size < 2 ^ k) :
44
+ (measuredRange xs key r k hs hk).2 ≤ 2 * (K + 10) * k + 4 := by
45
+ have hl := BinaryPivot.measuredSearch_work
46
+ (fun i : Fin xs.size => let q := key xs[i.val]; (decide (q.1 < r), q.2 + 2))
47
+ (K + 2) (fun i => Nat.add_le_add_right (hkey xs[i.val]) 2) k
48
+ have hh := BinaryPivot.measuredSearch_work
49
+ (fun i : Fin xs.size => let q := key xs[i.val]; (decide (q.1 ≤ r), q.2 + 2))
50
+ (K + 2) (fun i => Nat.add_le_add_right (hkey xs[i.val]) 2) k
51
+ change _ + _ + 4 ≤ _
52
+ simp only [Nat.add_assoc, Nat.mul_assoc, Nat.reduceAdd] at hl hh ⊢
53
+ omega
54
+
55
+ end BinarySlice
56
+ namespace ModularCursor
57
+
58
+ open scoped Fin.NatCast
59
+
60
+ variable {n : ℕ} [NeZero n] {α : Type*}
61
+
62
+ def measuredForward (a : Fin n → α) (key : α → ℤ × ℕ) (P r : ℤ) (k : ℕ) :
63
+ CyclicCursor.State n × ℕ :=
64
+ let q := BinaryPivot.measuredSearch (fun i =>
65
+ let w := key (a i); (decide (w.1 < P - r), w.2 + 2)) k
66
+ (⟨Fin.ofNat n q.1.lo, n, false⟩, q.2 + 6)
67
+
68
+ def measuredReverse (a : Fin n → α) (key : α → ℤ × ℕ) (r : ℤ) (k : ℕ) :
69
+ CyclicCursor.State n × ℕ :=
70
+ let q := BinaryPivot.measuredSearch (fun i =>
71
+ let w := key (a i); (decide (w.1 ≤ r), w.2 + 2)) k
72
+ (⟨Fin.ofNat n q.1.lo - 1, n, true⟩, q.2 + 6)
73
+
74
+ theorem measuredForward_value (a : Fin n → α) (key : α → ℤ × ℕ) (P r : ℤ) (k : ℕ) :
75
+ (measuredForward a key P r k).1 = forwardStart a (fun x => (key x).1) P r k := by
76
+ simp only [measuredForward, BinaryPivot.measuredSearch_value, forwardStart]
77
+
78
+ theorem measuredReverse_value (a : Fin n → α) (key : α → ℤ × ℕ) (r : ℤ) (k : ℕ) :
79
+ (measuredReverse a key r k).1 = reverseStart a (fun x => (key x).1) r k := by
80
+ simp only [measuredReverse, BinaryPivot.measuredSearch_value, reverseStart]
81
+
82
+ theorem measuredForward_work (a : Fin n → α) (key : α → ℤ × ℕ) (P r : ℤ) (k K : ℕ)
83
+ (hkey : ∀ x, (key x).2 ≤ K) :
84
+ (measuredForward a key P r k).2 ≤ (K + 10) * k + 6 := by
85
+ exact Nat.add_le_add_right (BinaryPivot.measuredSearch_work _ (K + 2)
86
+ (fun i => Nat.add_le_add_right (hkey (a i)) 2) k) 6
87
+
88
+ theorem measuredReverse_work (a : Fin n → α) (key : α → ℤ × ℕ) (r : ℤ) (k K : ℕ)
89
+ (hkey : ∀ x, (key x).2 ≤ K) :
90
+ (measuredReverse a key r k).2 ≤ (K + 10) * k + 6 := by
91
+ exact Nat.add_le_add_right (BinaryPivot.measuredSearch_work _ (K + 2)
92
+ (fun i => Nat.add_le_add_right (hkey (a i)) 2) k) 6
93
+
94
+ end ModularCursor
95
+ namespace SliceModular
96
+
97
+ variable {α : Type*}
98
+
99
+ def measuredForward (xs : Array α) (rr : SliceCursor.Range xs.size)
100
+ (key : α → ℤ × ℕ) (P r : ℤ) (k : ℕ) : SliceCursor.State xs.size × ℕ :=
101
+ if h : 0 < rr.length then
102
+ haveI : NeZero rr.length := ⟨by omega⟩
103
+ let q := ModularCursor.measuredForward (SliceCursor.values xs rr) key P r k
104
+ (⟨rr, some q.1⟩, q.2 + 2)
105
+ else (⟨rr, none⟩, 1)
106
+
107
+ def measuredReverse (xs : Array α) (rr : SliceCursor.Range xs.size)
108
+ (key : α → ℤ × ℕ) (r : ℤ) (k : ℕ) : SliceCursor.State xs.size × ℕ :=
109
+ if h : 0 < rr.length then
110
+ haveI : NeZero rr.length := ⟨by omega⟩
111
+ let q := ModularCursor.measuredReverse (SliceCursor.values xs rr) key r k
112
+ (⟨rr, some q.1⟩, q.2 + 2)
113
+ else (⟨rr, none⟩, 1)
114
+
115
+ theorem measuredForward_value (xs : Array α) (rr : SliceCursor.Range xs.size)
116
+ (key : α → ℤ × ℕ) (P r : ℤ) (k : ℕ) :
117
+ (measuredForward xs rr key P r k).1 = forward xs rr (fun x => (key x).1) P r k := by
118
+ unfold measuredForward forward
119
+ split <;> simp only [ModularCursor.measuredForward_value]
120
+
121
+ theorem measuredReverse_value (xs : Array α) (rr : SliceCursor.Range xs.size)
122
+ (key : α → ℤ × ℕ) (r : ℤ) (k : ℕ) :
123
+ (measuredReverse xs rr key r k).1 = reverse xs rr (fun x => (key x).1) r k := by
124
+ unfold measuredReverse reverse
125
+ split <;> simp only [ModularCursor.measuredReverse_value]
126
+
127
+ theorem measuredForward_work (xs : Array α) (rr : SliceCursor.Range xs.size)
128
+ (key : α → ℤ × ℕ) (P r : ℤ) (k K : ℕ) (hkey : ∀ x, (key x).2 ≤ K) :
129
+ (measuredForward xs rr key P r k).2 ≤ (K + 10) * k + 8 := by
130
+ unfold measuredForward
131
+ split
132
+ · rename_i h
133
+ have : NeZero rr.length := ⟨by omega⟩
134
+ exact Nat.add_le_add_right (ModularCursor.measuredForward_work _ key P r k K hkey) 2
135
+ · omega
136
+
137
+ theorem measuredReverse_work (xs : Array α) (rr : SliceCursor.Range xs.size)
138
+ (key : α → ℤ × ℕ) (r : ℤ) (k K : ℕ) (hkey : ∀ x, (key x).2 ≤ K) :
139
+ (measuredReverse xs rr key r k).2 ≤ (K + 10) * k + 8 := by
140
+ unfold measuredReverse
141
+ split
142
+ · rename_i h
143
+ have : NeZero rr.length := ⟨by omega⟩
144
+ exact Nat.add_le_add_right (ModularCursor.measuredReverse_work _ key r k K hkey) 2
145
+ · omega
146
+
147
+ end SliceModular
148
+ end LowSpaceSubsetSum
149
+ namespace LowSpaceSubsetSum.FilteredStream
150
+
151
+ variable {α β : Type*}
152
+
153
+ def measuredRow (right : Array β) (wl : α → ℤ × ℕ) (wr : β → ℤ × ℕ)
154
+ (p P c : ℤ) (hs : FilteredRow.PrimarySorted right (fun y => (wr y).1) p)
155
+ (mode : Mode) (x : α) : PairCursor.State α right.size × ℕ :=
156
+ let wx := wl x
157
+ let k := steps right.size
158
+ let low := fun y => let w := wr y; (w.1 % p, w.2 + 2)
159
+ let high := fun y => let w := wr y; (w.1 % P, w.2 + 2)
160
+ let rr := BinarySlice.measuredRange right low ((c - wx.1) % p) k
161
+ hs (steps_sufficient right.size)
162
+ let q := match mode with
163
+ | .direct => SliceModular.measuredForward right rr.1 high P (wx.1 % P) k
164
+ | .complementary v => SliceModular.measuredReverse right rr.1 high ((v - wx.1) % P) k
165
+ (⟨x, q.1⟩, wx.2 + rr.2 + q.2 + 4)
166
+
167
+ theorem measuredRow_value (right : Array β) (wl : α → ℤ × ℕ) (wr : β → ℤ × ℕ)
168
+ (p P c : ℤ) (hs : FilteredRow.PrimarySorted right (fun y => (wr y).1) p)
169
+ (mode : Mode) (x : α) :
170
+ (measuredRow right wl wr p P c hs mode x).1 =
171
+ row right (fun x => (wl x).1) (fun y => (wr y).1) p P c hs mode x := by
172
+ cases mode <;> simp only [measuredRow, row, FilteredRow.forward, FilteredRow.reverse,
173
+ BinarySlice.measuredRange_value, SliceModular.measuredForward_value,
174
+ SliceModular.measuredReverse_value, FilteredRow.range]
175
+
176
+ theorem measuredRow_work (right : Array β) (wl : α → ℤ × ℕ) (wr : β → ℤ × ℕ)
177
+ (p P c : ℤ) (hs : FilteredRow.PrimarySorted right (fun y => (wr y).1) p)
178
+ (mode : Mode) (x : α) (K : ℕ)
179
+ (hl : ∀ x, (wl x).2 ≤ K) (hr : ∀ y, (wr y).2 ≤ K) :
180
+ (measuredRow right wl wr p P c hs mode x).2 ≤
181
+ 3 * (K + 12) * steps right.size + K + 16 := by
182
+ let low := fun y => let w := wr y; (w.1 % p, w.2 + 2)
183
+ let high := fun y => let w := wr y; (w.1 % P, w.2 + 2)
184
+ let k := steps right.size
185
+ let rr := BinarySlice.measuredRange right low ((c - (wl x).1) % p) k
186
+ hs (steps_sufficient right.size)
187
+ have hrr := BinarySlice.measuredRange_work right low ((c - (wl x).1) % p) k (K + 2)
188
+ (fun y => Nat.add_le_add_right (hr y) 2) hs (steps_sufficient right.size)
189
+ have hx := hl x
190
+ cases mode with
191
+ | direct =>
192
+ have hq := SliceModular.measuredForward_work right rr.1 high P ((wl x).1 % P) k
193
+ (K + 2) (fun y => Nat.add_le_add_right (hr y) 2)
194
+ change (wl x).2 + rr.2 +
195
+ (SliceModular.measuredForward right rr.1 high P ((wl x).1 % P) k).2 + 4 ≤ _
196
+ change rr.2 ≤ 2 * (K + 2 + 10) * k + 4 at hrr
197
+ change _ ≤ 3 * (K + 12) * k + K + 16
198
+ simp only [Nat.add_assoc, Nat.mul_assoc, Nat.reduceAdd] at hrr hq ⊢
199
+ omega
200
+ | complementary v =>
201
+ have hq := SliceModular.measuredReverse_work right rr.1 high ((v - (wl x).1) % P) k
202
+ (K + 2) (fun y => Nat.add_le_add_right (hr y) 2)
203
+ change (wl x).2 + rr.2 +
204
+ (SliceModular.measuredReverse right rr.1 high ((v - (wl x).1) % P) k).2 + 4 ≤ _
205
+ change rr.2 ≤ 2 * (K + 2 + 10) * k + 4 at hrr
206
+ change _ ≤ 3 * (K + 12) * k + K + 16
207
+ simp only [Nat.add_assoc, Nat.mul_assoc, Nat.reduceAdd] at hrr hq ⊢
208
+ omega
209
+
210
+ end LowSpaceSubsetSum.FilteredStream
211
+
212
+ end OAI
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MeasuredSort.lean ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import OAI.Combinatorics.LowSpaceSubsetSum.Streams.CountedSort
2
+
3
+ namespace OAI
4
+
5
+ /-! # Mergesort including every comparator callback
6
+
7
+ The value agrees exactly with the counted merge and sort. The work theorem
8
+ scales its structural ledger by a bound on the supplied comparison work.
9
+ -/
10
+
11
+ namespace LowSpaceSubsetSum.MeasuredSort
12
+
13
+ variable {α : Type*}
14
+
15
+ def merge (cmp : α → α → Bool × ℕ) (xs ys : List α) : List α × ℕ :=
16
+ match xs, ys with
17
+ | [], ys => (ys, 1)
18
+ | xs, [] => (xs, 1)
19
+ | x :: xs, y :: ys =>
20
+ let c := cmp x y
21
+ if c.1 then
22
+ let out := merge cmp xs (y :: ys)
23
+ (x :: out.1, out.2 + c.2 + 1)
24
+ else
25
+ let out := merge cmp (x :: xs) ys
26
+ (y :: out.1, out.2 + c.2 + 1)
27
+ termination_by xs.length + ys.length
28
+
29
+ theorem merge_value (cmp : α → α → Bool × ℕ) (xs ys : List α) :
30
+ (merge cmp xs ys).1 = (CountedSort.merge (fun x y => (cmp x y).1) xs ys).1 := by
31
+ induction xs generalizing ys with
32
+ | nil => simp [merge, CountedSort.merge]
33
+ | cons x xs ih =>
34
+ induction ys with
35
+ | nil => simp [merge, CountedSort.merge]
36
+ | cons y ys ihy =>
37
+ cases h : (cmp x y).1 <;> simp [merge, CountedSort.merge, h, ih, ihy]
38
+
39
+ theorem merge_work (cmp : α → α → Bool × ℕ) (K : ℕ)
40
+ (hc : ∀ x y, (cmp x y).2 ≤ K) (xs ys : List α) :
41
+ (merge cmp xs ys).2 ≤
42
+ (K + 1) * (CountedSort.merge (fun x y => (cmp x y).1) xs ys).2 := by
43
+ induction xs generalizing ys with
44
+ | nil => simp [merge, CountedSort.merge]
45
+ | cons x xs ih =>
46
+ induction ys with
47
+ | nil => simp [merge, CountedSort.merge]
48
+ | cons y ys ihy =>
49
+ have hcost := hc x y
50
+ cases h : (cmp x y).1
51
+ · simp only [merge, CountedSort.merge, h, Bool.false_eq_true, ↓reduceIte]
52
+ simp only [Nat.mul_add, Nat.mul_one]
53
+ omega
54
+ · have hi := ih (y :: ys)
55
+ simp only [merge, CountedSort.merge, h, ↓reduceIte]
56
+ simp only [Nat.mul_add, Nat.mul_one]
57
+ omega
58
+
59
+ def run (cmp : α → α → Bool × ℕ) : ℕ → List α → List α × ℕ
60
+ | 0, xs => (xs, 1)
61
+ | _ + 1, [] => ([], 1)
62
+ | _ + 1, [x] => ([x], 1)
63
+ | k + 1, x :: y :: rest =>
64
+ let xs := x :: y :: rest
65
+ let cut := (xs.length + 1) / 2
66
+ let left := run cmp k (xs.take cut)
67
+ let right := run cmp k (xs.drop cut)
68
+ let out := merge cmp left.1 right.1
69
+ (out.1, left.2 + right.2 + 3 * xs.length + out.2 + 1)
70
+
71
+ theorem run_value (cmp : α → α → Bool × ℕ) (k : ℕ) (xs : List α) :
72
+ (run cmp k xs).1 = (CountedSort.run (fun x y => (cmp x y).1) k xs).1 := by
73
+ induction k generalizing xs with
74
+ | zero => rfl
75
+ | succ k ih =>
76
+ cases xs with
77
+ | nil => rfl
78
+ | cons x xs =>
79
+ cases xs with
80
+ | nil => rfl
81
+ | cons y rest => simp only [run, merge_value, ih, CountedSort.run]
82
+
83
+ theorem run_work (cmp : α → α → Bool × ℕ) (K : ℕ)
84
+ (hc : ∀ x y, (cmp x y).2 ≤ K) (k : ℕ) (xs : List α) :
85
+ (run cmp k xs).2 ≤ (K + 1) * (CountedSort.run (fun x y => (cmp x y).1) k xs).2 := by
86
+ induction k generalizing xs with
87
+ | zero => simp only [run, CountedSort.run]; omega
88
+ | succ k ih =>
89
+ cases xs with
90
+ | nil => simp only [run, CountedSort.run]; omega
91
+ | cons x xs =>
92
+ cases xs with
93
+ | nil => simp only [run, CountedSort.run]; omega
94
+ | cons y rest =>
95
+ let xs := x :: y :: rest
96
+ let cut := (xs.length + 1) / 2
97
+ have hl := ih (xs.take cut)
98
+ have hr := ih (xs.drop cut)
99
+ have hm := merge_work cmp K hc (run cmp k (xs.take cut)).1 (run cmp k (xs.drop cut)).1
100
+ rw [run_value, run_value] at hm
101
+ change (run cmp k (xs.take cut)).2 + (run cmp k (xs.drop cut)).2 +
102
+ 3 * xs.length + (merge cmp (run cmp k (xs.take cut)).1
103
+ (run cmp k (xs.drop cut)).1).2 + 1 ≤
104
+ (K + 1) * ((CountedSort.run (fun x y => (cmp x y).1) k (xs.take cut)).2 +
105
+ (CountedSort.run (fun x y => (cmp x y).1) k (xs.drop cut)).2 + 3 * xs.length +
106
+ (CountedSort.merge (fun x y => (cmp x y).1)
107
+ (CountedSort.run (fun x y => (cmp x y).1) k (xs.take cut)).1
108
+ (CountedSort.run (fun x y => (cmp x y).1) k (xs.drop cut)).1).2 + 1)
109
+ rw [run_value, run_value]
110
+ nlinarith only [hl, hr, hm, Nat.zero_le (K * (3 * xs.length + 1))]
111
+
112
+ def sort (cmp : α → α → Bool × ℕ) (xs : List α) : List α × ℕ :=
113
+ run cmp (Nat.clog 2 xs.length) xs
114
+
115
+ theorem sort_value (cmp : α → α → Bool × ℕ) (xs : List α) :
116
+ (sort cmp xs).1 = xs.mergeSort (fun x y => (cmp x y).1) := by
117
+ rw [sort, run_value, CountedSort.run_value]
118
+ exact Nat.le_pow_clog (by decide) _
119
+
120
+ theorem sort_work (cmp : α → α → Bool × ℕ) (K : ℕ)
121
+ (hc : ∀ x y, (cmp x y).2 ≤ K) (xs : List α) (n : ℕ) (hn : xs.length ≤ 2 ^ n) :
122
+ (sort cmp xs).2 ≤ (K + 1) * ((6 * n + 1) * xs.length + 1) := by
123
+ exact (run_work cmp K hc _ _).trans
124
+ (Nat.mul_le_mul_left _ (CountedSort.sort_steps_of_index_bits _ xs n hn))
125
+
126
+ end LowSpaceSubsetSum.MeasuredSort
127
+
128
+ end OAI
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MeasuredSortSpace.lean ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import OAI.Combinatorics.LowSpaceSubsetSum.Streams.MeasuredSort
2
+
3
+ namespace OAI
4
+
5
+ /-! # Live list and continuation cells of the executed mergesort
6
+
7
+ The first projection is exactly the measured sort, including its work
8
+ counter. The second projection records list and continuation storage;
9
+ comparison callbacks are scalar operations at the terminal application.
10
+ Input record payloads are shared and are not copied by a list cons.
11
+ -/
12
+
13
+ namespace LowSpaceSubsetSum.MeasuredSortSpace
14
+
15
+ variable {α : Type*}
16
+
17
+ /-- The merge retains its input tails, one continuation per selected head,
18
+ and the newly constructed result spine. -/
19
+ def merge (cmp : α → α → Bool × ℕ) (xs ys : List α) : (List α × ℕ) × ℕ :=
20
+ match xs, ys with
21
+ | [], ys => ((ys, 1), ys.length + 2)
22
+ | xs, [] => ((xs, 1), xs.length + 2)
23
+ | x :: xs, y :: ys =>
24
+ let c := cmp x y
25
+ if c.1 then
26
+ let out := merge cmp xs (y :: ys)
27
+ ((x :: out.1.1, out.1.2 + c.2 + 1),
28
+ max ((x :: xs).length + (y :: ys).length + 2) (out.2 + 4))
29
+ else
30
+ let out := merge cmp (x :: xs) ys
31
+ ((y :: out.1.1, out.1.2 + c.2 + 1),
32
+ max ((x :: xs).length + (y :: ys).length + 2) (out.2 + 4))
33
+ termination_by xs.length + ys.length
34
+
35
+ theorem merge_value (cmp : α → α → Bool × ℕ) (xs ys : List α) :
36
+ (merge cmp xs ys).1 = MeasuredSort.merge cmp xs ys := by
37
+ induction xs generalizing ys with
38
+ | nil => simp [merge, MeasuredSort.merge]
39
+ | cons x xs ih =>
40
+ induction ys with
41
+ | nil => simp [merge, MeasuredSort.merge]
42
+ | cons y ys ihy =>
43
+ cases h : (cmp x y).1 <;> simp [merge, MeasuredSort.merge, h, ih, ihy]
44
+
45
+ theorem merge_cells (cmp : α → α → Bool × ℕ) (xs ys : List α) :
46
+ (merge cmp xs ys).2 ≤ 6 * (xs.length + ys.length + 1) := by
47
+ induction xs generalizing ys with
48
+ | nil => simp only [merge, List.length_nil]; omega
49
+ | cons x xs ih =>
50
+ induction ys with
51
+ | nil => simp only [merge, List.length_nil]; omega
52
+ | cons y ys ihy =>
53
+ have hx := ih (y :: ys)
54
+ cases h : (cmp x y).1 <;>
55
+ simp only [merge, h, Bool.false_eq_true, ↓reduceIte, List.length_cons, max_le_iff] <;>
56
+ simp only [List.length_cons] at hx ihy <;> constructor <;> omega
57
+
58
+ /-- One branch runs at a time. The parent input, split spines and completed
59
+ sibling fit in the eight-cell-per-input local allowance. -/
60
+ def run (cmp : α → α → Bool × ℕ) : ℕ → List α → (List α × ℕ) × ℕ
61
+ | 0, xs => ((xs, 1), xs.length + 2)
62
+ | _ + 1, [] => (([], 1), 2)
63
+ | _ + 1, [x] => (([x], 1), 3)
64
+ | k + 1, x :: y :: rest =>
65
+ let xs := x :: y :: rest
66
+ let cut := (xs.length + 1) / 2
67
+ let left := run cmp k (xs.take cut)
68
+ let right := run cmp k (xs.drop cut)
69
+ let out := merge cmp left.1.1 right.1.1
70
+ ((out.1.1, left.1.2 + right.1.2 + 3 * xs.length + out.1.2 + 1),
71
+ 8 * (xs.length + 1) + max left.2 (max right.2 out.2))
72
+
73
+ theorem run_value (cmp : α → α → Bool × ℕ) (k : ℕ) (xs : List α) :
74
+ (run cmp k xs).1 = MeasuredSort.run cmp k xs := by
75
+ induction k generalizing xs with
76
+ | zero => rfl
77
+ | succ k ih =>
78
+ cases xs with
79
+ | nil => rfl
80
+ | cons x xs =>
81
+ cases xs with
82
+ | nil => rfl
83
+ | cons y rest => simp only [run, merge_value, ih, MeasuredSort.run]
84
+
85
+ theorem run_length (cmp : α → α → Bool × ℕ) (k : ℕ) (xs : List α) :
86
+ (run cmp k xs).1.1.length = xs.length := by
87
+ rw [run_value, MeasuredSort.run_value]
88
+ exact CountedSort.run_length _ _ _
89
+
90
+ theorem run_cells (cmp : α → α → Bool × ℕ) (k : ℕ) (xs : List α) :
91
+ (run cmp k xs).2 ≤ 32 * (k + 1) * (xs.length + 1) := by
92
+ induction k generalizing xs with
93
+ | zero => simp only [run]; omega
94
+ | succ k ih =>
95
+ cases xs with
96
+ | nil => simp only [run, List.length_nil]; omega
97
+ | cons x tail =>
98
+ cases tail with
99
+ | nil => simp only [run, List.length_cons, List.length_nil]; omega
100
+ | cons y rest =>
101
+ let xs := x :: y :: rest
102
+ let cut := (xs.length + 1) / 2
103
+ have hl := ih (xs.take cut)
104
+ have hr := ih (xs.drop cut)
105
+ have hll : (xs.take cut).length ≤ xs.length := by
106
+ simp only [List.length_take]
107
+ exact Nat.min_le_right _ _
108
+ have hrl : (xs.drop cut).length ≤ xs.length := by simp only [List.length_drop]; omega
109
+ have hleft := hl.trans (Nat.mul_le_mul_left (32 * (k + 1)) (by omega :
110
+ (xs.take cut).length + 1 ≤ xs.length + 1))
111
+ have hright := hr.trans (Nat.mul_le_mul_left (32 * (k + 1)) (by omega :
112
+ (xs.drop cut).length + 1 ≤ xs.length + 1))
113
+ have hm := merge_cells cmp (run cmp k (xs.take cut)).1.1
114
+ (run cmp k (xs.drop cut)).1.1
115
+ rw [run_length, run_length, List.length_take, List.length_drop] at hm
116
+ have hm' : (merge cmp (run cmp k (xs.take cut)).1.1
117
+ (run cmp k (xs.drop cut)).1.1).2 ≤ 6 * (xs.length + 1) := by
118
+ convert hm using 1
119
+ omega
120
+ have hm'' := hm'.trans (Nat.mul_le_mul_right (xs.length + 1)
121
+ (show 6 ��� 32 * (k + 1) by omega))
122
+ have hmax := max_le hleft (max_le hright hm'')
123
+ change 8 * (xs.length + 1) + _ ≤ 32 * (k + 1 + 1) * (xs.length + 1)
124
+ nlinarith only [hmax, Nat.zero_le xs.length]
125
+
126
+ end LowSpaceSubsetSum.MeasuredSortSpace
127
+
128
+ end OAI
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MeasuredStoredRecords.lean ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import OAI.Combinatorics.LowSpaceSubsetSum.Representation.RepresentationStoredRecords
2
+
3
+ namespace OAI
4
+
5
+ /-! # Executed generation retaining bounded index lists
6
+
7
+ The subset generators return index lists. Wrapping them as bounded masks
8
+ retains those lists; finite sets occur only in the semantic specification.
9
+ The work counter includes wrapping and both Cartesian-product traversals.
10
+ -/
11
+
12
+ namespace LowSpaceSubsetSum
13
+ namespace IndexedMask
14
+
15
+ variable {n : ℕ}
16
+
17
+ private theorem selectedList_length (xs ys : List (Fin n)) (k : ℕ)
18
+ (h : ys ∈ (CountedSubsets.select k xs).1) : ys.length ≤ xs.length := by
19
+ rw [CountedSubsets.select_value] at h
20
+ exact (List.mem_sublistsLen.mp h).1.length_le
21
+
22
+ private theorem allList_length (xs ys : List (Fin n))
23
+ (h : ys ∈ (CountedSubsets.all xs).1) : ys.length ≤ xs.length := by
24
+ rw [CountedSubsets.all_value] at h
25
+ exact (List.mem_sublists.mp h).length_le
26
+
27
+ def measuredSelected (xs : List (Fin n)) (hx : xs.length ≤ n) (k : ℕ) :
28
+ List (IndexedMask n) × ℕ :=
29
+ let out := CountedSubsets.select k xs
30
+ (out.1.attach.map (fun y => ⟨y.val,
31
+ (selectedList_length xs y.val k y.property).trans hx⟩), out.2 + out.1.length)
32
+
33
+ def measuredAll (xs : List (Fin n)) (hx : xs.length ≤ n) : List (IndexedMask n) × ℕ :=
34
+ let out := CountedSubsets.all xs
35
+ (out.1.attach.map (fun y => ⟨y.val,
36
+ (allList_length xs y.val y.property).trans hx⟩), out.2 + out.1.length)
37
+
38
+ @[simp] theorem measuredSelected_value (xs : List (Fin n)) (hx : xs.length ≤ n) (k : ℕ) :
39
+ (measuredSelected xs hx k).1 = selected xs hx k := rfl
40
+
41
+ @[simp] theorem measuredAll_value (xs : List (Fin n)) (hx : xs.length ≤ n) :
42
+ (measuredAll xs hx).1 = all xs hx := rfl
43
+
44
+ @[simp] theorem selected_length (xs : List (Fin n)) (hx : xs.length ≤ n) (k : ℕ) :
45
+ (selected xs hx k).length = xs.length.choose k := by
46
+ simp only [selected, List.length_map, List.length_attach, CountedSubsets.select_length]
47
+
48
+ @[simp] theorem all_length (xs : List (Fin n)) (hx : xs.length ≤ n) :
49
+ (all xs hx).length = 2 ^ xs.length := by
50
+ simp only [all, List.length_map, List.length_attach, CountedSubsets.all_length]
51
+
52
+ end IndexedMask
53
+
54
+ namespace RepresentationLeaf
55
+
56
+ variable {n : ℕ}
57
+
58
+ def measuredStoredRecords (L : RepresentationLeaf (Fin n)) : List (LeafRecord n) × ℕ :=
59
+ if L.topCount ≤ L.top.card ∧ L.localCount ≤ L.mixer.card then
60
+ let dt := domainSort L.top
61
+ let dm := domainSort L.mixer
62
+ let db := domainSort L.background
63
+ let t := IndexedMask.measuredSelected dt.1
64
+ (by rw [domainSort_length]; simpa using Finset.card_le_univ L.top) L.topCount
65
+ let m := IndexedMask.measuredSelected dm.1
66
+ (by rw [domainSort_length]; simpa using Finset.card_le_univ L.mixer) L.localCount
67
+ let b := IndexedMask.measuredAll db.1
68
+ (by rw [domainSort_length]; simpa using Finset.card_le_univ L.background)
69
+ let tm := t.1 ×ˢ m.1
70
+ let out := (tm ×ˢ b.1).map (fun y => (⟨y.1.1, y.1.2, y.2⟩ : LeafRecord n))
71
+ (out, dt.2 + dm.2 + db.2 + t.2 + m.2 + b.2 +
72
+ 4 * tm.length + 8 * out.length + 3 * (n + 1))
73
+ else ([], 3 * (n + 1))
74
+
75
+ theorem measuredStoredRecords_value (L : RepresentationLeaf (Fin n)) :
76
+ L.measuredStoredRecords.1 = L.storedRecords := by
77
+ simp only [measuredStoredRecords, storedRecords]
78
+ split <;> simp only [IndexedMask.measuredSelected_value, IndexedMask.measuredAll_value]
79
+
80
+ theorem measuredStoredRecords_cost (L : RepresentationLeaf (Fin n)) :
81
+ L.measuredStoredRecords.2 ≤ 3 * L.countedEnumerate.2 := by
82
+ by_cases hf : L.topCount ≤ L.top.card ∧ L.localCount ≤ L.mixer.card
83
+ · have hc : 1 ≤ 2 ^ L.background.card := Nat.one_le_two_pow
84
+ have hp : 1 ≤ (n + 1) ^ 2 := Nat.one_le_pow _ _ (by omega)
85
+ have htm : L.top.card.choose L.topCount * L.mixer.card.choose L.localCount ≤
86
+ L.top.card.choose L.topCount * L.mixer.card.choose L.localCount *
87
+ 2 ^ L.background.card := by
88
+ simpa only [Nat.mul_one] using Nat.mul_le_mul_left
89
+ (L.top.card.choose L.topCount * L.mixer.card.choose L.localCount) hc
90
+ have hsum : L.top.card.choose L.topCount + L.mixer.card.choose L.localCount +
91
+ 2 ^ L.background.card ≤ (n + 1) ^ 2 *
92
+ (L.top.card.choose L.topCount + L.mixer.card.choose L.localCount +
93
+ 2 ^ L.background.card) := by
94
+ simpa only [Nat.one_mul] using Nat.mul_le_mul_right
95
+ (L.top.card.choose L.topCount + L.mixer.card.choose L.localCount + 2 ^ L.background.card) hp
96
+ simp only [measuredStoredRecords, countedEnumerate, ite_eq_left hf,
97
+ IndexedMask.measuredSelected, IndexedMask.measuredAll, List.length_product,
98
+ List.length_map, List.length_attach, CountedSubsets.select_length,
99
+ CountedSubsets.all_length, domainSort_length]
100
+ omega
101
+ · simp only [measuredStoredRecords, countedEnumerate, ite_eq_right hf]
102
+ omega
103
+
104
+ theorem measuredStoredRecords_work (L : RepresentationLeaf (Fin n)) :
105
+ L.measuredStoredRecords.2 ≤ 192 * (n + 1) ^ 2 * (L.occurrences.card + 1) := by
106
+ have h := Nat.mul_le_mul_left 3 L.countedEnumerate_work
107
+ exact L.measuredStoredRecords_cost.trans (by nlinarith only [h])
108
+
109
+ theorem measuredStoredRecords_scale (I : Instance n) (L : RepresentationLeaf (Fin n))
110
+ (hn : 10000 ≤ n) :
111
+ L.measuredStoredRecords.2 ≤ inputScale I ^ 3 * (L.occurrences.card + 1) := by
112
+ have hnu : n + 1 ≤ inputScale I := by unfold inputScale; omega
113
+ have hs := Nat.pow_le_pow_left hnu 2
114
+ have hm := Nat.mul_le_mul_right (inputScale I ^ 2)
115
+ (show 192 ≤ inputScale I by omega)
116
+ have hp : 192 * (n + 1) ^ 2 ≤ inputScale I ^ 3 := by nlinarith only [hs, hm]
117
+ exact L.measuredStoredRecords_work.trans (Nat.mul_le_mul_right _ hp)
118
+
119
+ end RepresentationLeaf
120
+ end LowSpaceSubsetSum
121
+
122
+ end OAI
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MeasuredSumReader.lean ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import OAI.Combinatorics.LowSpaceSubsetSum.Streams.SumReader
2
+ import OAI.Combinatorics.LowSpaceSubsetSum.Streams.MeasuredInitialization
3
+ import OAI.Combinatorics.LowSpaceSubsetSum.Streams.MeasuredDistinctCount
4
+
5
+ namespace OAI
6
+
7
+ /-! # Executed integer-sum counting
8
+
9
+ The initializer reads the shared half-sum arrays directly. Its tournament
10
+ and the tail-recursive counter are the only evolving state; the full output
11
+ stream remains a proof view. Work includes initial rows and every key read.
12
+ -/
13
+
14
+ namespace LowSpaceSubsetSum.MeasuredSumReader
15
+
16
+ abbrev key (p : ℤ × ℤ) : ℤ × ℕ := (SumReader.key p, 1)
17
+
18
+ def read (ys : Array ℤ) (s : Option SumReader.Row) :
19
+ Option ((ℤ × ℤ) × Option SumReader.Row) × ℕ :=
20
+ (PaddedRows.next (SumReader.read ys) s, 6)
21
+
22
+ def front (xs ys : Array ℤ) (d : ℕ) (p : RowMerge.Path d) :
23
+ Option (RowMerge.Front d (ℤ × ℤ) (Option SumReader.Row)) × ℕ :=
24
+ let i := PaddedRows.measuredIndex d p
25
+ if h : i.1 < xs.size then
26
+ let q := read ys (some ⟨xs[i.1], 0⟩)
27
+ (q.1.map (fun z => ⟨p, z.1, z.2⟩), i.2 + q.2 + 5)
28
+ else (none, i.2 + 2)
29
+
30
+ theorem front_value (xs ys : Array ℤ) (d : ℕ) (p : RowMerge.Path d) :
31
+ (front xs ys d p).1 = RowMerge.front (PaddedRows.next (SumReader.read ys)) p
32
+ (PaddedRows.rows (SumReader.rows xs) d p) := by
33
+ by_cases h : (PaddedRows.index d p).val < xs.size
34
+ · simp [front, PaddedRows.measuredIndex_value, PaddedRows.rows, SumReader.rows,
35
+ RowMerge.front, read, h]
36
+ · simp [front, PaddedRows.measuredIndex_value, PaddedRows.rows, SumReader.rows,
37
+ RowMerge.front, h, PaddedRows.next]
38
+
39
+ theorem front_work (xs ys : Array ℤ) (d : ℕ) (p : RowMerge.Path d) :
40
+ (front xs ys d p).2 ≤ 4 * (d + 1) ^ 2 + 11 := by
41
+ have hi := PaddedRows.measuredIndex_work d p
42
+ unfold front
43
+ dsimp only
44
+ split <;> dsimp only [read] <;> omega
45
+
46
+ def tree (xs ys : Array ℤ) :=
47
+ Tournament.measuredBuild
48
+ (fun x : RowMerge.Front (Nat.clog 2 xs.size) (ℤ × ℤ) (Option SumReader.Row) => key x.value)
49
+ (Nat.clog 2 xs.size) (front xs ys (Nat.clog 2 xs.size))
50
+
51
+ theorem tree_value (xs ys : Array ℤ) (hs : ys.toList.Pairwise (· ≤ ·)) :
52
+ (tree xs ys).1 = (SumReader.start xs ys hs).tree := by
53
+ simp only [tree, Tournament.measuredBuild_value, SumReader.start,
54
+ MergedReader.start, RowMerge.start]
55
+ congr 1
56
+ funext p
57
+ exact front_value xs ys _ p
58
+
59
+ def start (xs ys : Array ℤ) (hs : ys.toList.Pairwise (· ≤ ·)) :
60
+ SumReader.State xs ys × ℕ :=
61
+ let out := tree xs ys
62
+ let source := SumReader.start xs ys hs
63
+ have he : out.1 = source.tree := tree_value xs ys hs
64
+ (⟨out.1, he.symm ▸ source.valid, he.symm ▸ source.aligned, he.symm ▸ source.sorted⟩, out.2)
65
+
66
+ theorem start_value (xs ys : Array ℤ) (hs : ys.toList.Pairwise (· ≤ ·)) :
67
+ (start xs ys hs).1 = SumReader.start xs ys hs := by
68
+ have ext {a b : SumReader.State xs ys} (h : a.tree = b.tree) : a = b := by
69
+ cases a
70
+ cases b
71
+ cases h
72
+ rfl
73
+ apply ext
74
+ exact tree_value xs ys hs
75
+
76
+ theorem start_work (xs ys : Array ℤ) (hs : ys.toList.Pairwise (· ≤ ·)) :
77
+ (start xs ys hs).2 ≤ (4 * (Nat.clog 2 xs.size + 1) ^ 2 + 32) *
78
+ 2 ^ Nat.clog 2 xs.size := by
79
+ have h := Tournament.measuredBuild_work
80
+ (fun x : RowMerge.Front (Nat.clog 2 xs.size) (ℤ × ℤ) (Option SumReader.Row) => key x.value)
81
+ 1 (4 * (Nat.clog 2 xs.size + 1) ^ 2 + 11) (fun _ => le_rfl)
82
+ (Nat.clog 2 xs.size) (front xs ys (Nat.clog 2 xs.size))
83
+ (front_work xs ys (Nat.clog 2 xs.size))
84
+ change (tree xs ys).2 ≤ _
85
+ exact h.trans ((Nat.sub_le _ _).trans (Nat.mul_le_mul_right _ (by omega)))
86
+
87
+ def next (xs ys : Array ℤ) (s : SumReader.State xs ys) :
88
+ Option ((ℤ × ℤ) × SumReader.State xs ys) × ℕ :=
89
+ MergedReader.measuredNext key (read ys) (PaddedRows.view (SumReader.view ys))
90
+ (PaddedRows.reader _ _ (SumReader.reader ys)) s
91
+
92
+ theorem next_value (xs ys : Array ℤ) (s : SumReader.State xs ys) :
93
+ (next xs ys s).1 = SumReader.next xs ys s :=
94
+ MergedReader.measuredNext_value key (read ys) (PaddedRows.view (SumReader.view ys))
95
+ (PaddedRows.reader _ _ (SumReader.reader ys)) s
96
+
97
+ theorem next_work (xs ys : Array ℤ) (s : SumReader.State xs ys) :
98
+ (next xs ys s).2 ≤ 10 * Nat.clog 2 xs.size + 16 := by
99
+ have h := MergedReader.measuredNext_work key (read ys)
100
+ (PaddedRows.view (SumReader.view ys)) (PaddedRows.reader _ _ (SumReader.reader ys))
101
+ s 1 6 (fun _ => le_rfl) (fun _ => le_rfl)
102
+ change (next xs ys s).2 ≤ _ at h
103
+ omega
104
+
105
+ def count (xs ys : Array ℤ) (hs : ys.toList.Pairwise (· ≤ ·)) : ℕ × ℕ :=
106
+ let initial := start xs ys hs
107
+ let out := MeasuredDistinctCount.run (next xs ys) key (xs.size * ys.size) initial.1
108
+ (out.1, initial.2 + out.2 + 2)
109
+
110
+ theorem count_value (xs ys : Array ℤ) (hs : ys.toList.Pairwise (· ≤ ·)) :
111
+ (count xs ys hs).1 = (SumReader.count xs ys hs).1 := by
112
+ simp only [count, MeasuredDistinctCount.run_value, next_value, start_value]
113
+ rfl
114
+
115
+ theorem count_work (xs ys : Array ℤ) (hs : ys.toList.Pairwise (· ≤ ·)) :
116
+ (count xs ys hs).2 ≤ (4 * (Nat.clog 2 xs.size + 1) ^ 2 + 32) *
117
+ 2 ^ Nat.clog 2 xs.size + (10 * Nat.clog 2 xs.size + 21) *
118
+ (xs.size * ys.size) + 3 := by
119
+ have hi := start_work xs ys hs
120
+ have hc := MeasuredDistinctCount.run_work (next xs ys) key
121
+ (10 * Nat.clog 2 xs.size + 16) 1 (next_work xs ys) (fun _ => le_rfl)
122
+ (xs.size * ys.size) (start xs ys hs).1
123
+ have hc' : (MeasuredDistinctCount.run (next xs ys) key (xs.size * ys.size)
124
+ (start xs ys hs).1).2 ≤
125
+ (10 * Nat.clog 2 xs.size + 21) * (xs.size * ys.size) + 1 := by
126
+ convert hc using 1
127
+ change _ + _ + 2 ≤ _
128
+ omega
129
+
130
+ end LowSpaceSubsetSum.MeasuredSumReader
131
+
132
+ end OAI
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MergeCorrectness.lean ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import OAI.Combinatorics.LowSpaceSubsetSum.Streams.RowMerge
2
+ import Mathlib.Algebra.BigOperators.Group.Finset.Basic
3
+ import Mathlib.Data.Multiset.AddSub
4
+
5
+ namespace OAI
6
+
7
+ /-!
8
+ # Complete and stopped tournament merges
9
+
10
+ The multiset view counts every row occurrence, even when all item fields
11
+ coincide. Each successful advance removes exactly the reported occurrence.
12
+ A sufficiently long trace therefore enumerates the whole product stream;
13
+ the potential also bounds every stopped execution's number of advances.
14
+ -/
15
+
16
+ namespace LowSpaceSubsetSum
17
+ namespace RowMerge
18
+
19
+ universe u v
20
+
21
+ variable {α : Type u} {σ : Type v} {d : ℕ}
22
+
23
+ def bag (view : σ → List α) (t : Tournament.Tree (Front d α σ) d) : Multiset α :=
24
+ ∑ p : Path d, (remaining view t p : Multiset α)
25
+
26
+ theorem bag_card (view : σ → List α) (t : Tournament.Tree (Front d α σ) d) :
27
+ (bag view t).card = potential view t := by simp [bag, potential]
28
+
29
+ theorem replacement_bag (key : α → ℤ) (read : σ → Option (α × σ))
30
+ (view : σ → List α) (hread : IsReader read view)
31
+ (t : Tournament.Tree (Front d α σ) d)
32
+ (ht : Tournament.Valid (fun y => key y.value) t) (halign : Aligned t)
33
+ {x : Front d α σ} (hx : Tournament.winner t = some x) :
34
+ bag view t = {x.value} + bag view (Tournament.replace (fun y => key y.value) t
35
+ x.row (front read x.row x.after)) := by
36
+ have hrow := winner_at_own_row key t ht halign hx
37
+ let t' := Tournament.replace (fun y => key y.value) t x.row (front read x.row x.after)
38
+ have hpoint (p : Path d) : (remaining view t p : Multiset α) =
39
+ (remaining view t' p : Multiset α) + if p = x.row then {x.value} else 0 := by
40
+ have hnew := replace_remaining key read view hread t x p
41
+ change remaining view t' p = _ at hnew
42
+ by_cases hp : p = x.row
43
+ · subst p
44
+ rw [ite_eq_left rfl] at hnew
45
+ rw [hnew]
46
+ simp only [remaining, hrow, ↓reduceIte]
47
+ change x.value ::ₘ (view x.after : Multiset α) = (view x.after : Multiset α) + {x.value}
48
+ rw [← Multiset.singleton_add, add_comm]
49
+ · rw [ite_eq_right (Ne.symm hp)] at hnew
50
+ rw [hnew, ite_eq_right hp, add_zero]
51
+ unfold bag
52
+ rw [show (∑ p : Path d, (remaining view t p : Multiset α)) =
53
+ ∑ p : Path d, ((remaining view t' p : Multiset α) + if p = x.row then {x.value} else 0)
54
+ from Finset.sum_congr rfl (fun p _ => hpoint p)]
55
+ simp [Finset.sum_add_distrib, t', add_comm]
56
+
57
+ theorem bag_eq_zero_of_winner_none (key : α → ℤ)
58
+ (view : σ → List α) (t : Tournament.Tree (Front d α σ) d)
59
+ (ht : Tournament.Valid (fun y => key y.value) t) (hn : Tournament.winner t = none) :
60
+ bag view t = 0 := by
61
+ have hc := (Tournament.winner_none_iff (fun y => key y.value) t ht).mp hn
62
+ have hlookup (p : Path d) : Tournament.lookup t p = none := by
63
+ cases h : Tournament.lookup t p with
64
+ | none => rfl
65
+ | some x =>
66
+ have hm := (Tournament.mem_candidates_iff t x).mpr ⟨p, h⟩
67
+ simp [hc] at hm
68
+ simp [bag, remaining, hlookup]
69
+
70
+ /-- Analysis view of repeated advances. The program can stop between them. -/
71
+ def trace (key : α → ℤ) (read : σ → Option (α × σ)) :
72
+ ℕ → Tournament.Tree (Front d α σ) d → List α
73
+ | 0, _ => []
74
+ | k + 1, t => match advance key read t with
75
+ | none => []
76
+ | some (a, t') => a :: trace key read k t'
77
+
78
+ theorem trace_complete (key : α → ℤ) (read : σ → Option (α × σ))
79
+ (view : σ → List α) (hread : IsReader read view) (k : ℕ)
80
+ (t : Tournament.Tree (Front d α σ) d)
81
+ (ht : Tournament.Valid (fun y => key y.value) t) (halign : Aligned t)
82
+ (hk : potential view t ≤ k) : (trace key read k t : Multiset α) = bag view t := by
83
+ induction k generalizing t with
84
+ | zero =>
85
+ have hz : (bag view t).card = 0 := by rw [bag_card]; omega
86
+ simpa [trace] using (Multiset.card_eq_zero.mp hz).symm
87
+ | succ k ih =>
88
+ cases hw : Tournament.winner t with
89
+ | none =>
90
+ have hb := bag_eq_zero_of_winner_none key view t ht hw
91
+ simp [trace, advance, hw, hb]
92
+ | some x =>
93
+ let t' := Tournament.replace (fun y => key y.value) t x.row (front read x.row x.after)
94
+ have ha : advance key read t = some (x.value, t') := by simp [advance, hw, t']
95
+ have ht' := advance_valid key read t ht ha
96
+ have halign' := advance_aligned key read t halign ha
97
+ have hdec := replacement_consumes_one key read view hread t ht halign hw
98
+ change potential view t' + 1 = potential view t at hdec
99
+ have hk' : potential view t' ≤ k := by omega
100
+ have hbag := replacement_bag key read view hread t ht halign hw
101
+ change bag view t = {x.value} + bag view t' at hbag
102
+ rw [trace, ha]
103
+ change x.value ::ₘ (trace key read k t' : Multiset α) = bag view t
104
+ rw [ih t' ht' halign' hk', hbag]
105
+ simp
106
+
107
+ theorem trace_length_le (key : α → ℤ) (read : σ → Option (α × σ))
108
+ (view : σ → List α) (hread : IsReader read view) (k : ℕ)
109
+ (t : Tournament.Tree (Front d α σ) d)
110
+ (ht : Tournament.Valid (fun y => key y.value) t) (halign : Aligned t) :
111
+ (trace key read k t).length ≤ potential view t := by
112
+ induction k generalizing t with
113
+ | zero => simp [trace]
114
+ | succ k ih =>
115
+ cases hw : Tournament.winner t with
116
+ | none => simp [trace, advance, hw]
117
+ | some x =>
118
+ let t' := Tournament.replace (fun y => key y.value) t x.row (front read x.row x.after)
119
+ have ha : advance key read t = some (x.value, t') := by simp [advance, hw, t']
120
+ have ht' := advance_valid key read t ht ha
121
+ have halign' := advance_aligned key read t halign ha
122
+ have hdec := replacement_consumes_one key read view hread t ht halign hw
123
+ have hlen := ih t' ht' halign'
124
+ rw [trace, ha, List.length_cons]
125
+ change potential view t' + 1 = potential view t at hdec
126
+ omega
127
+
128
+ end RowMerge
129
+ end LowSpaceSubsetSum
130
+
131
+ end OAI
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MergeOrdering.lean ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import OAI.Combinatorics.LowSpaceSubsetSum.Streams.MergeCorrectness
2
+
3
+ namespace OAI
4
+
5
+ /-!
6
+ # Sortedness of complete and stopped row merges
7
+
8
+ Only each row's individual order is required. The tournament minimum is
9
+ no larger than every remaining occurrence; replacing its front by its
10
+ successor preserves this invariant. Every finite trace is therefore sorted,
11
+ including traces stopped by the operation cap.
12
+ -/
13
+
14
+ namespace LowSpaceSubsetSum
15
+ namespace RowMerge
16
+
17
+ universe u v
18
+
19
+ variable {α : Type u} {σ : Type v} {d : ℕ}
20
+
21
+ def RowsSorted (key : α → ℤ) (view : σ → List α)
22
+ (t : Tournament.Tree (Front d α σ) d) : Prop :=
23
+ ∀ p, (remaining view t p).Pairwise (fun x y => key x ≤ key y)
24
+
25
+ theorem replacement_remaining_subset (key : α → ℤ) (read : σ → Option (α × σ))
26
+ (view : σ → List α) (hread : IsReader read view)
27
+ (t : Tournament.Tree (Front d α σ) d)
28
+ (ht : Tournament.Valid (fun y => key y.value) t) (halign : Aligned t)
29
+ {x : Front d α σ} (hx : Tournament.winner t = some x) (p : Path d) :
30
+ remaining view (Tournament.replace (fun y => key y.value) t x.row
31
+ (front read x.row x.after)) p ⊆ remaining view t p := by
32
+ have hnew := replace_remaining key read view hread t x p
33
+ have hrow := winner_at_own_row key t ht halign hx
34
+ rw [hnew]
35
+ by_cases hp : x.row = p
36
+ · subst p
37
+ rw [ite_eq_left rfl]
38
+ simp only [remaining, hrow]
39
+ intro y hy
40
+ exact List.mem_cons_of_mem _ hy
41
+ · rw [ite_eq_right hp]
42
+
43
+ theorem replacement_rowsSorted (key : α → ℤ) (read : σ → Option (α × σ))
44
+ (view : σ → List α) (hread : IsReader read view)
45
+ (t : Tournament.Tree (Front d α σ) d)
46
+ (ht : Tournament.Valid (fun y => key y.value) t) (halign : Aligned t)
47
+ (hsort : RowsSorted key view t) {x : Front d α σ}
48
+ (hx : Tournament.winner t = some x) :
49
+ RowsSorted key view (Tournament.replace (fun y => key y.value) t x.row
50
+ (front read x.row x.after)) := by
51
+ intro p
52
+ rw [replace_remaining key read view hread t x p]
53
+ by_cases hp : x.row = p
54
+ · subst p
55
+ rw [ite_eq_left rfl]
56
+ have hs := hsort x.row
57
+ have hrow := winner_at_own_row key t ht halign hx
58
+ simp only [remaining, hrow] at hs
59
+ exact (List.pairwise_cons.mp hs).2
60
+ · rw [ite_eq_right hp]
61
+ exact hsort p
62
+
63
+ theorem winner_le_remaining (key : α → ℤ) (view : σ → List α)
64
+ (t : Tournament.Tree (Front d α σ) d)
65
+ (ht : Tournament.Valid (fun y => key y.value) t) (hsort : RowsSorted key view t)
66
+ {x : Front d α σ} (hx : Tournament.winner t = some x)
67
+ (p : Path d) {y : α} (hy : y ∈ remaining view t p) : key x.value ≤ key y := by
68
+ cases hp : Tournament.lookup t p with
69
+ | none => simp [remaining, hp] at hy
70
+ | some z =>
71
+ have hmin := winner_is_minimum key t ht hx p hp
72
+ have hs := hsort p
73
+ simp only [remaining, hp] at hy hs
74
+ rcases List.mem_cons.mp hy with hy | hy
75
+ · simpa [hy] using hmin
76
+ · exact hmin.trans ((List.pairwise_cons.mp hs).1 y hy)
77
+
78
+ theorem trace_lower_bound (key : α → ℤ) (read : σ → Option (α × σ))
79
+ (view : σ → List α) (hread : IsReader read view) (k : ℕ)
80
+ (t : Tournament.Tree (Front d α σ) d)
81
+ (ht : Tournament.Valid (fun y => key y.value) t) (halign : Aligned t)
82
+ (c : ℤ) (hc : ∀ p, ∀ y ∈ remaining view t p, c ≤ key y) :
83
+ ∀ y ∈ trace key read k t, c ≤ key y := by
84
+ induction k generalizing t with
85
+ | zero => simp [trace]
86
+ | succ k ih =>
87
+ cases hw : Tournament.winner t with
88
+ | none => simp [trace, advance, hw]
89
+ | some x =>
90
+ let t' := Tournament.replace (fun y => key y.value) t x.row (front read x.row x.after)
91
+ have ha : advance key read t = some (x.value, t') := by simp [advance, hw, t']
92
+ have ht' := advance_valid key read t ht ha
93
+ have halign' := advance_aligned key read t halign ha
94
+ have hrow := winner_at_own_row key t ht halign hw
95
+ have hfront : c ≤ key x.value := hc x.row x.value (by simp [remaining, hrow])
96
+ have hc' : ∀ p, ∀ y ∈ remaining view t' p, c ≤ key y := by
97
+ intro p y hy
98
+ exact hc p y (replacement_remaining_subset key read view hread t ht halign hw p hy)
99
+ rw [trace, ha]
100
+ intro y hy
101
+ rcases List.mem_cons.mp hy with hy | hy
102
+ · simpa [hy] using hfront
103
+ · exact ih t' ht' halign' hc' y hy
104
+
105
+ theorem trace_sorted (key : α → ℤ) (read : σ → Option (α × σ))
106
+ (view : σ → List α) (hread : IsReader read view) (k : ℕ)
107
+ (t : Tournament.Tree (Front d α σ) d)
108
+ (ht : Tournament.Valid (fun y => key y.value) t) (halign : Aligned t)
109
+ (hsort : RowsSorted key view t) :
110
+ (trace key read k t).Pairwise (fun x y => key x ≤ key y) := by
111
+ induction k generalizing t with
112
+ | zero => simp [trace]
113
+ | succ k ih =>
114
+ cases hw : Tournament.winner t with
115
+ | none => simp [trace, advance, hw]
116
+ | some x =>
117
+ let t' := Tournament.replace (fun y => key y.value) t x.row (front read x.row x.after)
118
+ have ha : advance key read t = some (x.value, t') := by simp [advance, hw, t']
119
+ have ht' := advance_valid key read t ht ha
120
+ have halign' := advance_aligned key read t halign ha
121
+ have hsort' := replacement_rowsSorted key read view hread t ht halign hsort hw
122
+ rw [trace, ha]
123
+ apply List.pairwise_cons.mpr
124
+ refine ⟨?_, ih t' ht' halign' hsort'⟩
125
+ apply trace_lower_bound key read view hread k t' ht' halign' (key x.value)
126
+ intro p y hy
127
+ exact winner_le_remaining key view t ht hsort hw p
128
+ (replacement_remaining_subset key read view hread t ht halign hw p hy)
129
+
130
+ end RowMerge
131
+ end LowSpaceSubsetSum
132
+
133
+ end OAI
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/MergedReader.lean ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import OAI.Combinatorics.LowSpaceSubsetSum.Streams.MergeOrdering
2
+
3
+ namespace OAI
4
+
5
+ /-!
6
+ # The executable tournament merge as a finite reader
7
+
8
+ Only the tournament and its row cursors are stored. The complete output list
9
+ is a proof view, defined by the remaining-occurrence potential. The reader
10
+ law connects this actual merge to the stopped joins and bounded dictionaries.
11
+ -/
12
+
13
+ namespace LowSpaceSubsetSum
14
+ namespace MergedReader
15
+
16
+ universe u v
17
+
18
+ variable {α : Type u} {σ : Type v} {d : ℕ}
19
+
20
+ structure State (key : α → ℤ) (view : σ → List α) (d : ℕ) where
21
+ tree : Tournament.Tree (RowMerge.Front d α σ) d
22
+ valid : Tournament.Valid (fun x => key x.value) tree
23
+ aligned : RowMerge.Aligned tree
24
+ sorted : RowMerge.RowsSorted key view tree
25
+
26
+ theorem advance_sorted (key : α → ℤ) (read : σ → Option (α × σ))
27
+ (view : σ → List α) (hread : RowMerge.IsReader read view)
28
+ (s : State key view d) {a : α} {t : Tournament.Tree (RowMerge.Front d α σ) d}
29
+ (ha : RowMerge.advance key read s.tree = some (a, t)) :
30
+ RowMerge.RowsSorted key view t := by
31
+ cases hw : Tournament.winner s.tree with
32
+ | none => simp [RowMerge.advance, hw] at ha
33
+ | some x =>
34
+ have heq : (x.value, Tournament.replace (fun y => key y.value) s.tree x.row
35
+ (RowMerge.front read x.row x.after)) = (a, t) := by
36
+ simpa [RowMerge.advance, hw] using ha
37
+ rw [← (Prod.mk.inj heq).2]
38
+ exact RowMerge.replacement_rowsSorted key read view hread s.tree
39
+ s.valid s.aligned s.sorted hw
40
+
41
+ theorem advance_consumes_one (key : α → ℤ) (read : σ → Option (α × σ))
42
+ (view : σ → List α) (hread : RowMerge.IsReader read view)
43
+ (s : State key view d) {a : α} {t : Tournament.Tree (RowMerge.Front d α σ) d}
44
+ (ha : RowMerge.advance key read s.tree = some (a, t)) :
45
+ RowMerge.potential view t + 1 = RowMerge.potential view s.tree := by
46
+ cases hw : Tournament.winner s.tree with
47
+ | none => simp [RowMerge.advance, hw] at ha
48
+ | some x =>
49
+ have heq : (x.value, Tournament.replace (fun y => key y.value) s.tree x.row
50
+ (RowMerge.front read x.row x.after)) = (a, t) := by
51
+ simpa [RowMerge.advance, hw] using ha
52
+ rw [← (Prod.mk.inj heq).2]
53
+ exact RowMerge.replacement_consumes_one key read view hread s.tree
54
+ s.valid s.aligned hw
55
+
56
+ def next (key : α → ℤ) (read : σ → Option (α × σ))
57
+ (view : σ → List α) (hread : RowMerge.IsReader read view)
58
+ (s : State key view d) : Option (α × State key view d) :=
59
+ match ha : RowMerge.advance key read s.tree with
60
+ | none => none
61
+ | some (a, t) => some (a, ⟨t,
62
+ RowMerge.advance_valid key read s.tree s.valid ha,
63
+ RowMerge.advance_aligned key read s.tree s.aligned ha,
64
+ advance_sorted key read view hread s ha⟩)
65
+
66
+ /-- The output view is never a field of the executable state. -/
67
+ def output (key : α → ℤ) (read : σ → Option (α × σ))
68
+ (view : σ → List α) (s : State key view d) : List α :=
69
+ RowMerge.trace key read (RowMerge.potential view s.tree) s.tree
70
+
71
+ theorem next_none (key : α → ℤ) (read : σ → Option (α × σ))
72
+ (view : σ → List α) (hread : RowMerge.IsReader read view)
73
+ (s : State key view d) (ha : RowMerge.advance key read s.tree = none) :
74
+ next key read view hread s = none := by
75
+ unfold next
76
+ split
77
+ · rfl
78
+ · rename_i a t ht
79
+ rw [ha] at ht
80
+ cases ht
81
+
82
+ theorem next_some (key : α → ℤ) (read : σ → Option (α × σ))
83
+ (view : σ → List α) (hread : RowMerge.IsReader read view)
84
+ (s : State key view d) {a : α} {t : Tournament.Tree (RowMerge.Front d α σ) d}
85
+ (ha : RowMerge.advance key read s.tree = some (a, t)) :
86
+ next key read view hread s = some (a, ⟨t,
87
+ RowMerge.advance_valid key read s.tree s.valid ha,
88
+ RowMerge.advance_aligned key read s.tree s.aligned ha,
89
+ advance_sorted key read view hread s ha⟩) := by
90
+ unfold next
91
+ split
92
+ · rename_i hn
93
+ rw [ha] at hn
94
+ cases hn
95
+ · rename_i b t' ht
96
+ have heq : (a, t) = (b, t') := Option.some.inj (ha.symm.trans ht)
97
+ obtain ⟨rfl, rfl⟩ := Prod.mk.inj heq
98
+ rfl
99
+
100
+ theorem reader (key : α → ℤ) (read : σ → Option (α × σ))
101
+ (view : σ → List α) (hread : RowMerge.IsReader read view) :
102
+ RowMerge.IsReader (next (d := d) key read view hread) (output key read view) := by
103
+ intro s
104
+ cases ha : RowMerge.advance key read s.tree with
105
+ | none =>
106
+ rw [next_none key read view hread s ha]
107
+ unfold output
108
+ cases hp : RowMerge.potential view s.tree with
109
+ | zero => rfl
110
+ | succ k => simp only [RowMerge.trace, ha]
111
+ | some z =>
112
+ obtain ⟨a, t⟩ := z
113
+ rw [next_some key read view hread s ha]
114
+ have hdec := advance_consumes_one key read view hread s ha
115
+ simp only [output, ← hdec, RowMerge.trace, ha]
116
+
117
+ theorem output_bag (key : α → ℤ) (read : σ → Option (α × σ))
118
+ (view : σ → List α) (hread : RowMerge.IsReader read view)
119
+ (s : State key view d) :
120
+ (output key read view s : Multiset α) = RowMerge.bag view s.tree :=
121
+ RowMerge.trace_complete key read view hread _ s.tree s.valid s.aligned le_rfl
122
+
123
+ theorem output_length (key : α → ℤ) (read : σ → Option (α × σ))
124
+ (view : σ → List α) (hread : RowMerge.IsReader read view)
125
+ (s : State key view d) :
126
+ (output key read view s).length = RowMerge.potential view s.tree := by
127
+ have h := congrArg Multiset.card (output_bag key read view hread s)
128
+ simpa only [Multiset.coe_card, RowMerge.bag_card] using h
129
+
130
+ theorem output_sorted (key : α → ℤ) (read : σ → Option (α × σ))
131
+ (view : σ → List α) (hread : RowMerge.IsReader read view)
132
+ (s : State key view d) :
133
+ (output key read view s).Pairwise (fun x y => key x ≤ key y) :=
134
+ RowMerge.trace_sorted key read view hread _ s.tree s.valid s.aligned s.sorted
135
+
136
+ def start (key : α → ℤ) (read : σ → Option (α × σ))
137
+ (view : σ → List α) (hread : RowMerge.IsReader read view)
138
+ (rows : RowMerge.Path d → σ)
139
+ (hsort : ∀ p, (view (rows p)).Pairwise (fun x y => key x ≤ key y)) :
140
+ State key view d :=
141
+ ⟨RowMerge.start key read rows, RowMerge.start_valid key read rows,
142
+ RowMerge.start_aligned key read rows, fun p => by
143
+ rw [RowMerge.start_remaining key read view hread rows p]
144
+ exact hsort p⟩
145
+
146
+ theorem start_output_bag (key : α → ℤ) (read : σ → Option (α × σ))
147
+ (view : σ → List α) (hread : RowMerge.IsReader read view)
148
+ (rows : RowMerge.Path d → σ)
149
+ (hsort : ∀ p, (view (rows p)).Pairwise (fun x y => key x ≤ key y)) :
150
+ (output key read view (start key read view hread rows hsort) : Multiset α) =
151
+ ∑ p : RowMerge.Path d, (view (rows p) : Multiset α) := by
152
+ rw [output_bag key read view hread]
153
+ simp only [RowMerge.bag, start, RowMerge.start_remaining key read view hread]
154
+
155
+ theorem start_output_length (key : α → ℤ) (read : σ → Option (α × σ))
156
+ (view : σ → List α) (hread : RowMerge.IsReader read view)
157
+ (rows : RowMerge.Path d → σ)
158
+ (hsort : ∀ p, (view (rows p)).Pairwise (fun x y => key x ≤ key y)) :
159
+ (output key read view (start key read view hread rows hsort)).length =
160
+ ∑ p : RowMerge.Path d, (view (rows p)).length := by
161
+ rw [output_length key read view hread]
162
+ simp only [RowMerge.potential, start, RowMerge.start_remaining key read view hread]
163
+
164
+ theorem nodes_exact (key : α → ℤ) (view : σ → List α) (s : State key view d) :
165
+ Tournament.nodes s.tree + 1 = 2 ^ (d + 1) := Tournament.nodes_exact s.tree
166
+
167
+ def advanceComparisons (key : α → ℤ) (view : σ → List α) (s : State key view d) : ℕ :=
168
+ match Tournament.winner s.tree with
169
+ | none => 0
170
+ | some x => Tournament.replaceComparisons s.tree x.row
171
+
172
+ theorem advanceComparisons_le (key : α → ℤ) (view : σ → List α) (s : State key view d) :
173
+ advanceComparisons key view s ≤ d := by
174
+ unfold advanceComparisons
175
+ split
176
+ · exact Nat.zero_le d
177
+ · exact (Tournament.replaceComparisons_eq _ _).le
178
+
179
+ end MergedReader
180
+ end LowSpaceSubsetSum
181
+
182
+ end OAI
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/ModularCursor.lean ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import OAI.Combinatorics.LowSpaceSubsetSum.Streams.CyclicCursor
2
+ import OAI.Combinatorics.LowSpaceSubsetSum.Streams.BinaryPivot
3
+
4
+ namespace OAI
5
+
6
+ /-!
7
+ # Executable modular row initialization
8
+
9
+ Binary search finds the first direct pivot and the position after the last
10
+ complementary pivot. The resulting constant-state cyclic cursor produces
11
+ the corresponding sorted modular row exactly. The cutoff search uses a
12
+ supplied number of steps; the theorem requires only that the array length
13
+ be smaller than `2^k`. Equal residues stay separate array occurrences.
14
+ -/
15
+
16
+ namespace LowSpaceSubsetSum
17
+ namespace ModularCursor
18
+
19
+ open scoped Fin.NatCast
20
+
21
+ variable {n : ℕ} [NeZero n] {α : Type*}
22
+
23
+ def forwardStart (a : Fin n → α) (residue : α → ℤ) (P r : ℤ) (k : ℕ) :
24
+ CyclicCursor.State n :=
25
+ ⟨Fin.ofNat n (BinaryPivot.search (fun i => decide (residue (a i) < P - r)) k).lo,
26
+ n, false⟩
27
+
28
+ def reverseStart (a : Fin n → α) (residue : α → ℤ) (K : ℤ) (k : ℕ) :
29
+ CyclicCursor.State n :=
30
+ ⟨Fin.ofNat n (BinaryPivot.search (fun i => decide (residue (a i) ≤ K)) k).lo - 1,
31
+ n, true⟩
32
+
33
+ theorem forward_trace (a : Fin n → α) (residue : α → ℤ) (P r : ℤ) (k : ℕ)
34
+ (hk : n < 2 ^ k) (hsort : Monotone (fun i => residue (a i))) :
35
+ CyclicCursor.trace a n (forwardStart a residue P r k) =
36
+ ModularRows.direct P r residue (List.ofFn a) := by
37
+ have hprefix : BinaryPivot.PrefixPredicate
38
+ (fun i : Fin n => decide (residue (a i) < P - r)) := by
39
+ intro i j hij hj
40
+ apply decide_eq_true
41
+ exact lt_of_le_of_lt (hsort hij) (of_decide_eq_true hj)
42
+ have hsplit := BinaryPivot.search_split a
43
+ (fun x => decide (residue x < P - r)) hprefix k hk
44
+ let c := BinaryPivot.search (fun i : Fin n => decide (residue (a i) < P - r)) k
45
+ let lo := (List.ofFn a).take c.lo
46
+ let hi := (List.ofFn a).drop c.lo
47
+ have hc : c.lo ≤ n := c.ordered.trans c.bounded
48
+ have hlist : List.ofFn a = lo ++ hi := (List.take_append_drop c.lo _).symm
49
+ apply CyclicCursor.forward_trace_eq_direct a P r residue lo hi hlist
50
+ (Fin.ofNat n c.lo)
51
+ · simp [lo, hc]
52
+ · simpa only [decide_eq_true_eq] using hsplit.1
53
+ · simpa only [decide_eq_false_iff_not, not_lt] using hsplit.2
54
+
55
+ theorem reverse_trace (a : Fin n → α) (residue : α → ℤ) (K : ℤ) (k : ℕ)
56
+ (hk : n < 2 ^ k) (hsort : Monotone (fun i => residue (a i))) :
57
+ CyclicCursor.trace a n (reverseStart a residue K k) =
58
+ ModularRows.complementary K residue (List.ofFn a) := by
59
+ have hprefix : BinaryPivot.PrefixPredicate
60
+ (fun i : Fin n => decide (residue (a i) ≤ K)) := by
61
+ intro i j hij hj
62
+ apply decide_eq_true
63
+ exact (hsort hij).trans (of_decide_eq_true hj)
64
+ have hsplit := BinaryPivot.search_split a
65
+ (fun x => decide (residue x ≤ K)) hprefix k hk
66
+ let c := BinaryPivot.search (fun i : Fin n => decide (residue (a i) ≤ K)) k
67
+ let lo := (List.ofFn a).take c.lo
68
+ let hi := (List.ofFn a).drop c.lo
69
+ have hc : c.lo ≤ n := c.ordered.trans c.bounded
70
+ have hlist : List.ofFn a = lo ++ hi := (List.take_append_drop c.lo _).symm
71
+ apply CyclicCursor.reverse_trace_eq_complementary a K residue lo hi hlist
72
+ (Fin.ofNat n c.lo)
73
+ · simp [lo, hc]
74
+ · simpa only [decide_eq_true_eq] using hsplit.1
75
+ · simpa only [decide_eq_false_iff_not, not_le] using hsplit.2
76
+
77
+ theorem forward_sorted (a : Fin n → α) (residue : α → ℤ) (P r : ℤ) (k : ℕ)
78
+ (hk : n < 2 ^ k) (hsort : Monotone (fun i => residue (a i)))
79
+ (hr : 0 ≤ r) (hrP : r < P) (hbound : ∀ i, 0 ≤ residue (a i) ∧ residue (a i) < P) :
80
+ (CyclicCursor.trace a n (forwardStart a residue P r k)).Pairwise
81
+ (fun x y => (r + residue x) % P ≤ (r + residue y) % P) := by
82
+ rw [forward_trace a residue P r k hk hsort]
83
+ apply ModularRows.direct_sorted hr hrP
84
+ · intro x hx
85
+ obtain ⟨i, rfl⟩ := List.mem_ofFn.mp hx
86
+ exact hbound i
87
+ · exact List.pairwise_ofFn.mpr (fun _ _ h => hsort h.le)
88
+
89
+ theorem reverse_sorted (a : Fin n → α) (residue : α → ℤ) (P K : ℤ) (k : ℕ)
90
+ (hk : n < 2 ^ k) (hsort : Monotone (fun i => residue (a i)))
91
+ (hK : 0 ≤ K) (hKP : K < P) (hbound : ∀ i, 0 ≤ residue (a i) ∧ residue (a i) < P) :
92
+ (CyclicCursor.trace a n (reverseStart a residue K k)).Pairwise
93
+ (fun x y => (K - residue x) % P ≤ (K - residue y) % P) := by
94
+ rw [reverse_trace a residue K k hk hsort]
95
+ apply ModularRows.complementary_sorted hK hKP
96
+ · intro x hx
97
+ obtain ⟨i, rfl⟩ := List.mem_ofFn.mp hx
98
+ exact hbound i
99
+ · exact List.pairwise_ofFn.mpr (fun _ _ h => hsort h.le)
100
+
101
+ end ModularCursor
102
+ end LowSpaceSubsetSum
103
+
104
+ end OAI
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/ModularFilters.lean ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Mathlib.Data.Int.ModEq
2
+ import Mathlib.Tactic
3
+
4
+ namespace OAI
5
+
6
+ /-!
7
+ # Nested filters and enumeration of parent residue classes
8
+
9
+ The congruence and finite-loop facts used by both trials. No coprimality of
10
+ the low modulus and the additional prime is required.
11
+ -/
12
+
13
+ namespace LowSpaceSubsetSum
14
+
15
+ /-- A passing parent and first child force the second child's low filter. -/
16
+ theorem nested_second_child_filter {p p0 x1 x2 w rho : ℤ}
17
+ (hdiv : p ∣ p0) (hparent : x1 + x2 ≡ w [ZMOD p0])
18
+ (hchild : x1 ≡ rho [ZMOD p]) : x2 ≡ w - rho [ZMOD p] := by
19
+ have h := (hparent.of_dvd hdiv).sub hchild
20
+ convert h using 1
21
+ ring
22
+
23
+ /-- Every lifted class has the prescribed low residue. -/
24
+ theorem lift_low_residue {p rho z : ℕ} (hrho : rho < p) :
25
+ (rho + p * z) % p = rho := by
26
+ simp [Nat.add_mod, Nat.mod_eq_of_lt hrho]
27
+
28
+ /-- The program's lift lies within the product modulus. -/
29
+ theorem lift_lt_product {p q rho z : ℕ} (hrho : rho < p) (hz : z < q) :
30
+ rho + p * z < p * q := by
31
+ have hz' : z + 1 ≤ q := by omega
32
+ have hp := Nat.mul_le_mul_left p hz'
33
+ nlinarith
34
+
35
+ /-- All product-modulus residues with a given low base occur exactly once in
36
+ the loop over `z < q`, including when `q` and `p` have a common factor. -/
37
+ theorem lift_residue_exists_unique {p q rho r : ℕ}
38
+ (hp : 0 < p) (hr : r < p * q) (hbase : r % p = rho) :
39
+ ∃! z : ℕ, z < q ∧ r = rho + p * z := by
40
+ have hz : r / p < q := (Nat.div_lt_iff_lt_mul hp).mpr (by simpa [mul_comm] using hr)
41
+ have heq : r = rho + p * (r / p) := by
42
+ have h := Nat.mod_add_div r p
43
+ omega
44
+ refine ⟨r / p, ⟨hz, heq⟩, ?_⟩
45
+ intro z hz'
46
+ have hprod : p * z = p * (r / p) := by omega
47
+ exact Nat.eq_of_mul_eq_mul_left hp hprod
48
+
49
+ /-- Complementing the target gives a bijection of the product residue ring. -/
50
+ theorem complementary_residue_injective {P t : ℤ} {x y : ℤ}
51
+ (hx : 0 ≤ x ∧ x < P) (hy : 0 ≤ y ∧ y < P)
52
+ (h : (t - x) % P = (t - y) % P) : x = y := by
53
+ have hm : t - x ≡ t - y [ZMOD P] := h
54
+ have hxym := hm.neg.add_left t
55
+ have hxy : x % P = y % P := by
56
+ change x ≡ y [ZMOD P]
57
+ convert hxym using 1 <;> ring
58
+ rwa [Int.emod_eq_of_lt hx.1 hx.2, Int.emod_eq_of_lt hy.1 hy.2] at hxy
59
+
60
+ end LowSpaceSubsetSum
61
+
62
+ end OAI
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/ModularRows.lean ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Mathlib.Data.List.Pairwise
2
+ import Mathlib.Data.List.Perm.Basic
3
+ import Mathlib.Data.Int.ModEq
4
+ import Mathlib.Tactic
5
+
6
+ namespace OAI
7
+
8
+ /-!
9
+ # The modular pivot order of a pair-stream row
10
+
11
+ These are the two cyclic orders in `lem:streams`. The list is an analysis view
12
+ of one sorted slice: implementation can traverse the slice by its pivot and
13
+ cursor, rather than allocating the reordered list. The permutation theorems
14
+ preserve occurrence multiplicity, including repeated residues.
15
+ -/
16
+
17
+ namespace LowSpaceSubsetSum
18
+ namespace ModularRows
19
+
20
+ variable {α : Type*}
21
+
22
+ def direct (P r : ℤ) (residue : α → ℤ) (xs : List α) : List α :=
23
+ xs.filter (fun x => decide (P - r ≤ residue x)) ++
24
+ xs.filter (fun x => decide (residue x < P - r))
25
+
26
+ def complementary (K : ℤ) (residue : α → ℤ) (xs : List α) : List α :=
27
+ (xs.filter (fun x => decide (residue x ≤ K))).reverse ++
28
+ (xs.filter (fun x => decide (K < residue x))).reverse
29
+
30
+ theorem direct_perm (P r : ℤ) (residue : α → ℤ) (xs : List α) :
31
+ (direct P r residue xs).Perm xs := by
32
+ simpa only [direct, ← decide_not, not_le] using
33
+ List.filter_append_perm (fun x => decide (P - r ≤ residue x)) xs
34
+
35
+ theorem complementary_perm (K : ℤ) (residue : α → ℤ) (xs : List α) :
36
+ (complementary K residue xs).Perm xs := by
37
+ apply ((List.reverse_perm _).append (List.reverse_perm _)).trans
38
+ simpa only [← decide_not, not_le] using List.filter_append_perm (fun x => decide (residue x ≤ K)) xs
39
+
40
+ theorem direct_wrapped {P r x : ℤ} (_hr : 0 ≤ r) (hrP : r < P)
41
+ (_hx : 0 ≤ x) (hxP : x < P) (hwrap : P - r ≤ x) :
42
+ (r + x) % P = r + x - P := by
43
+ rw [← Int.sub_emod_right (r + x) P]
44
+ exact Int.emod_eq_of_lt (by omega) (by omega)
45
+
46
+ theorem direct_unwrapped {P r x : ℤ} (hr : 0 ≤ r)
47
+ (hx : 0 ≤ x) (hwrap : x < P - r) : (r + x) % P = r + x :=
48
+ Int.emod_eq_of_lt (by omega) (by omega)
49
+
50
+ theorem complementary_low {P K x : ℤ} (_hK : 0 ≤ K) (hKP : K < P)
51
+ (hx : 0 ≤ x) (hsmall : x ≤ K) : (K - x) % P = K - x :=
52
+ Int.emod_eq_of_lt (by omega) (by omega)
53
+
54
+ theorem complementary_high {P K x : ℤ} (hK : 0 ≤ K) (_hKP : K < P)
55
+ (hxP : x < P) (hlarge : K < x) : (K - x) % P = K - x + P := by
56
+ rw [← Int.add_emod_right (K - x) P]
57
+ exact Int.emod_eq_of_lt (by omega) (by omega)
58
+
59
+ /-- Direct cyclic traversal is sorted by normalized pair residue. -/
60
+ theorem direct_sorted {P r : ℤ} (hr : 0 ≤ r) (hrP : r < P)
61
+ (residue : α → ℤ) (xs : List α)
62
+ (hbound : ∀ x ∈ xs, 0 ≤ residue x ∧ residue x < P)
63
+ (hsort : xs.Pairwise (fun x y => residue x ≤ residue y)) :
64
+ (direct P r residue xs).Pairwise
65
+ (fun x y => (r + residue x) % P ≤ (r + residue y) % P) := by
66
+ apply List.pairwise_append.mpr
67
+ refine ⟨?_, ?_, ?_⟩
68
+ · apply (hsort.filter (fun x => decide (P - r ≤ residue x))).imp_of_mem
69
+ intro x y hx hy hxy
70
+ obtain ⟨hxmem, hxwrap⟩ := List.mem_filter.mp hx
71
+ obtain ⟨hymem, hywrap⟩ := List.mem_filter.mp hy
72
+ have hxw : P - r ≤ residue x := of_decide_eq_true hxwrap
73
+ have hyw : P - r ≤ residue y := of_decide_eq_true hywrap
74
+ rw [direct_wrapped hr hrP (hbound x hxmem).1 (hbound x hxmem).2 hxw,
75
+ direct_wrapped hr hrP (hbound y hymem).1 (hbound y hymem).2 hyw]
76
+ omega
77
+ · apply (hsort.filter (fun x => decide (residue x < P - r))).imp_of_mem
78
+ intro x y hx hy hxy
79
+ obtain ⟨hxmem, hxwrap⟩ := List.mem_filter.mp hx
80
+ obtain ⟨hymem, hywrap⟩ := List.mem_filter.mp hy
81
+ rw [direct_unwrapped hr (hbound x hxmem).1 (of_decide_eq_true hxwrap),
82
+ direct_unwrapped hr (hbound y hymem).1 (of_decide_eq_true hywrap)]
83
+ omega
84
+ · intro x hx y hy
85
+ obtain ⟨hxmem, hxwrap⟩ := List.mem_filter.mp hx
86
+ obtain ⟨hymem, hywrap⟩ := List.mem_filter.mp hy
87
+ rw [direct_wrapped hr hrP (hbound x hxmem).1 (hbound x hxmem).2
88
+ (of_decide_eq_true hxwrap),
89
+ direct_unwrapped hr (hbound y hymem).1 (of_decide_eq_true hywrap)]
90
+ have := (hbound x hxmem).2
91
+ have := (hbound y hymem).1
92
+ omega
93
+
94
+ /-- Reverse cyclic traversal is sorted by the complementary residue. -/
95
+ theorem complementary_sorted {P K : ℤ} (hK : 0 ≤ K) (hKP : K < P)
96
+ (residue : α → ℤ) (xs : List α)
97
+ (hbound : ∀ x ∈ xs, 0 ≤ residue x ∧ residue x < P)
98
+ (hsort : xs.Pairwise (fun x y => residue x ≤ residue y)) :
99
+ (complementary K residue xs).Pairwise
100
+ (fun x y => (K - residue x) % P ≤ (K - residue y) % P) := by
101
+ apply List.pairwise_append.mpr
102
+ refine ⟨?_, ?_, ?_⟩
103
+ · apply List.pairwise_reverse.mpr
104
+ apply (hsort.filter (fun x => decide (residue x ≤ K))).imp_of_mem
105
+ intro x y hx hy hxy
106
+ obtain ⟨hxmem, hxsmall⟩ := List.mem_filter.mp hx
107
+ obtain ⟨hymem, hysmall⟩ := List.mem_filter.mp hy
108
+ rw [complementary_low hK hKP (hbound x hxmem).1 (of_decide_eq_true hxsmall),
109
+ complementary_low hK hKP (hbound y hymem).1 (of_decide_eq_true hysmall)]
110
+ omega
111
+ · apply List.pairwise_reverse.mpr
112
+ apply (hsort.filter (fun x => decide (K < residue x))).imp_of_mem
113
+ intro x y hx hy hxy
114
+ obtain ⟨hxmem, hxlarge⟩ := List.mem_filter.mp hx
115
+ obtain ⟨hymem, hylarge⟩ := List.mem_filter.mp hy
116
+ rw [complementary_high hK hKP (hbound x hxmem).2 (of_decide_eq_true hxlarge),
117
+ complementary_high hK hKP (hbound y hymem).2 (of_decide_eq_true hylarge)]
118
+ omega
119
+ · intro x hx y hy
120
+ obtain ⟨hxmem, hxsmall⟩ := List.mem_filter.mp (List.mem_reverse.mp hx)
121
+ obtain ⟨hymem, hylarge⟩ := List.mem_filter.mp (List.mem_reverse.mp hy)
122
+ rw [complementary_low hK hKP (hbound x hxmem).1 (of_decide_eq_true hxsmall),
123
+ complementary_high hK hKP (hbound y hymem).2 (of_decide_eq_true hylarge)]
124
+ have := (hbound x hxmem).1
125
+ have := (hbound y hymem).2
126
+ omega
127
+
128
+ /-- Filtering a row by the small modulus preserves its residue ordering. -/
129
+ theorem filtered_sorted (p c : ℤ) (weight residue : α → ℤ) (xs : List α)
130
+ (hsort : xs.Pairwise (fun x y => residue x ≤ residue y)) :
131
+ (xs.filter (fun x => decide (weight x % p = c % p))).Pairwise
132
+ (fun x y => residue x ≤ residue y) := hsort.filter _
133
+
134
+ end ModularRows
135
+ end LowSpaceSubsetSum
136
+
137
+ end OAI
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/PaddedRows.lean ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import OAI.Combinatorics.LowSpaceSubsetSum.Streams.MergedReader
2
+ import Mathlib.Algebra.BigOperators.Fin
3
+
4
+ namespace OAI
5
+
6
+ /-!
7
+ # Binary indexing and empty padding for the row tournament
8
+
9
+ Binary paths index a power-of-two set of leaves. Array indices occupy the
10
+ initial segment and all other leaves are empty. The reindexing proof counts
11
+ exact occurrences; its finite sums and lists are analysis views only.
12
+ -/
13
+
14
+ namespace LowSpaceSubsetSum
15
+ namespace PaddedRows
16
+
17
+ variable {α σ : Type*}
18
+
19
+ def index (d : ℕ) : RowMerge.Path d ≃ Fin (2 ^ d) :=
20
+ (Equiv.piCongrRight (fun _ : Fin d => finTwoEquiv.symm)).trans finFunctionFinEquiv
21
+
22
+ def next (read : σ → Option (α × σ)) : Option σ → Option (α × Option σ)
23
+ | none => none
24
+ | some s => (read s).map (fun z => (z.1, some z.2))
25
+
26
+ def view (output : σ → List α) : Option σ → List α
27
+ | none => []
28
+ | some s => output s
29
+
30
+ theorem reader (read : σ → Option (α × σ)) (output : σ → List α)
31
+ (hread : RowMerge.IsReader read output) : RowMerge.IsReader (next read) (view output) := by
32
+ intro s
33
+ cases s with
34
+ | none => rfl
35
+ | some s =>
36
+ have h := hread s
37
+ cases hr : read s with
38
+ | none => simpa only [next, hr, Option.map_none, view] using h
39
+ | some z => simpa only [next, hr, Option.map_some, view] using h
40
+
41
+ def rows (xs : Array σ) (d : ℕ) (p : RowMerge.Path d) : Option σ :=
42
+ if h : (index d p).val < xs.size then some xs[(index d p).val] else none
43
+
44
+ theorem rows_sorted (xs : Array σ) (d : ℕ) (output : σ → List α) (key : α → ℤ)
45
+ (hs : ∀ s ∈ xs.toList, (output s).Pairwise (fun x y => key x ≤ key y))
46
+ (p : RowMerge.Path d) :
47
+ (view output (rows xs d p)).Pairwise (fun x y => key x ≤ key y) := by
48
+ unfold rows
49
+ split_ifs with h
50
+ · apply hs
51
+ exact List.mem_iff_getElem.mpr ⟨(index d p).val,
52
+ by simpa only [Array.length_toList] using h, by simp⟩
53
+ · simp [view]
54
+
55
+ theorem sum_padding {M : Type*} [AddCommMonoid M] (n m : ℕ) (hnm : n ≤ m)
56
+ (f : Fin n → M) :
57
+ (∑ i : Fin m, if h : i.val < n then f ⟨i.val, h⟩ else 0) = ∑ i : Fin n, f i := by
58
+ induction m with
59
+ | zero =>
60
+ have hn : n = 0 := by omega
61
+ subst n
62
+ simp
63
+ | succ m ih =>
64
+ by_cases hn : n ≤ m
65
+ · rw [Fin.sum_univ_castSucc]
66
+ have hlast : ¬ m < n := by omega
67
+ simp only [Fin.val_castSucc, Fin.val_last, dite_eq_right hlast, add_zero]
68
+ exact ih hn
69
+ · have hn : n = m + 1 := by omega
70
+ subst n
71
+ apply Finset.sum_congr rfl
72
+ intro i _
73
+ exact dite_eq_left i.isLt
74
+
75
+ theorem sum_rows {M : Type*} [AddCommMonoid M] (xs : Array σ) (d : ℕ)
76
+ (hd : xs.size ≤ 2 ^ d) (f : σ → M) :
77
+ (∑ p : RowMerge.Path d, match rows xs d p with | none => 0 | some s => f s) =
78
+ ∑ i : Fin xs.size, f xs[i.val] := by
79
+ calc
80
+ _ = ∑ i : Fin (2 ^ d), if h : i.val < xs.size then f xs[i.val] else 0 := by
81
+ apply Fintype.sum_equiv (index d)
82
+ intro p
83
+ dsimp only [rows]
84
+ split_ifs <;> rfl
85
+ _ = _ := sum_padding xs.size (2 ^ d) hd (fun i => f xs[i.val])
86
+
87
+ theorem row_bag (xs : Array σ) (d : ℕ) (hd : xs.size ≤ 2 ^ d) (output : σ → List α) :
88
+ (∑ p : RowMerge.Path d, (view output (rows xs d p) : Multiset α)) =
89
+ ∑ i : Fin xs.size, (output xs[i.val] : Multiset α) := by
90
+ calc
91
+ _ = ∑ p : RowMerge.Path d,
92
+ match rows xs d p with | none => 0 | some s => (output s : Multiset α) := by
93
+ apply Finset.sum_congr rfl
94
+ intro p _
95
+ cases rows xs d p <;> rfl
96
+ _ = _ := sum_rows xs d hd (fun s => (output s : Multiset α))
97
+
98
+ end PaddedRows
99
+ end LowSpaceSubsetSum
100
+
101
+ end OAI
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/PairCursor.lean ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import OAI.Combinatorics.LowSpaceSubsetSum.Streams.SliceCursor
2
+
3
+ namespace OAI
4
+
5
+ /-! # Attach one fixed first-array occurrence to a shared-array row reader -/
6
+
7
+ namespace LowSpaceSubsetSum
8
+ namespace PairCursor
9
+
10
+ variable {α β : Type*}
11
+
12
+ structure State (α : Type*) (n : ℕ) where
13
+ left : α
14
+ cursor : SliceCursor.State n
15
+
16
+ def next (xs : Array β) (s : State α xs.size) : Option ((α × β) × State α xs.size) :=
17
+ (SliceCursor.next xs s.cursor).map (fun z => ((s.left, z.1), ⟨s.left, z.2⟩))
18
+
19
+ def output (xs : Array β) (s : State α xs.size) : List (α × β) :=
20
+ (SliceCursor.output xs s.cursor).map (fun y => (s.left, y))
21
+
22
+ theorem reader (xs : Array β) : RowMerge.IsReader (next (α := α) xs) (output xs) := by
23
+ intro s
24
+ have hr := SliceCursor.reader xs s.cursor
25
+ cases h : SliceCursor.next xs s.cursor with
26
+ | none =>
27
+ simp only [h] at hr
28
+ simp only [next, h, Option.map_none, output, hr, List.map_nil]
29
+ | some z =>
30
+ obtain ⟨y, c⟩ := z
31
+ simp only [h] at hr
32
+ simp only [next, h, Option.map_some, output, hr, List.map_cons]
33
+
34
+ end PairCursor
35
+ end LowSpaceSubsetSum
36
+
37
+ end OAI
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/ParentPrefixSearch.lean ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import OAI.Combinatorics.LowSpaceSubsetSum.Representation.RepresentationParentComplete
2
+ import OAI.Combinatorics.LowSpaceSubsetSum.Streams.DictionaryCompleted
3
+ import OAI.Combinatorics.LowSpaceSubsetSum.Separators.SeparatorEncodedCheck
4
+
5
+ namespace OAI
6
+
7
+ /-! # Actual depth-first right-parent prefix recomputation -/
8
+
9
+ namespace LowSpaceSubsetSum
10
+
11
+ namespace MaskRestriction
12
+
13
+ variable {n : ℕ}
14
+
15
+ def force (P : MaskRestriction n) (i : Fin n) (side : Bool) : MaskRestriction n :=
16
+ if side then { P with ones := Insert.insert i P.ones }
17
+ else { P with zeros := Insert.insert i P.zeros }
18
+
19
+ def follow (P : MaskRestriction n) (order : List (Fin n)) (S : Finset (Fin n)) : MaskRestriction n :=
20
+ order.foldl (fun P i => P.force i (decide (i ∈ S))) P
21
+
22
+ theorem force_compatible (P : MaskRestriction n) (domain S : Finset (Fin n))
23
+ (h : P.Compatible domain S) (i : Fin n) :
24
+ (P.force i (decide (i ∈ S))).Compatible domain S := by
25
+ by_cases hi : i ∈ S
26
+ · simp only [hi, decide_true, force, ↓reduceIte, Compatible]
27
+ refine ⟨?_, h.2⟩
28
+ intro j hj
29
+ obtain ⟨hj, hjD⟩ := Finset.mem_inter.mp hj
30
+ rcases Finset.mem_insert.mp hj with rfl | hj
31
+ · exact hi
32
+ · exact h.1 (Finset.mem_inter.mpr ⟨hj, hjD⟩)
33
+ · simp only [hi, decide_false, force, Bool.false_eq_true, ↓reduceIte, Compatible]
34
+ refine ⟨h.1, Finset.disjoint_left.mpr ?_⟩
35
+ intro j hj hjS
36
+ rcases Finset.mem_insert.mp hj with rfl | hj
37
+ · exact hi hjS
38
+ · exact Finset.disjoint_left.mp h.2 hj hjS
39
+
40
+ end MaskRestriction
41
+
42
+ namespace RepresentationParentData
43
+
44
+ variable {n : ℕ} (D : RepresentationParentData n)
45
+
46
+ /-- Each task regenerates its restricted leaves and streams. An overflowing
47
+ full prefix is dropped; a completed array is passed to the actual checker.
48
+ The first YES returns immediately. -/
49
+ def searchRight (B : ℕ) (check : Array (Entry (Fin n)) → Bool) :
50
+ List (Fin n) → MaskRestriction n → Bool
51
+ | order, P =>
52
+ let task := { D with maskRestriction := P }
53
+ let out := (task.collect B).state.user
54
+ if out.keys.overflow then
55
+ match order with
56
+ | [] => false
57
+ | i :: rest =>
58
+ if searchRight B check rest (P.force i false) then true
59
+ else searchRight B check rest (P.force i true)
60
+ else check out.records
61
+
62
+ theorem searchRight_sound (B : ℕ) (check : Array (Entry (Fin n)) → Bool)
63
+ (Q : Prop) (hcheck : ∀ P, check ({ D with maskRestriction := P }.entries B) = true → Q)
64
+ (order : List (Fin n)) (P : MaskRestriction n) (hyes : D.searchRight B check order P = true) : Q := by
65
+ induction order generalizing P with
66
+ | nil =>
67
+ simp only [searchRight] at hyes
68
+ split at hyes
69
+ · contradiction
70
+ · exact hcheck P hyes
71
+ | cons i order ih =>
72
+ simp only [searchRight] at hyes
73
+ split at hyes
74
+ · split at hyes
75
+ · rename_i hl
76
+ exact ih _ hl
77
+ · exact ih _ hyes
78
+ · exact hcheck P hyes
79
+
80
+ /-- A fitting task at the end of a designated mask path suffices. Earlier
81
+ completion reaches the checker; earlier YES also returns immediately. -/
82
+ theorem searchRight_complete (B : ℕ) (check : Array (Entry (Fin n)) → Bool)
83
+ (domain S : Finset (Fin n))
84
+ (hfind : ∀ P, P.Compatible domain S →
85
+ ({ D with maskRestriction := P }.collect B).state.user.keys.overflow = false →
86
+ check ({ D with maskRestriction := P }.entries B) = true)
87
+ (order : List (Fin n)) (P : MaskRestriction n) (hP : P.Compatible domain S)
88
+ (hfull : ({ D with maskRestriction := P.follow order S }.collect B).state.user.keys.overflow = false) :
89
+ D.searchRight B check order P = true := by
90
+ induction order generalizing P with
91
+ | nil =>
92
+ have hc : ({ D with maskRestriction := P }.collect B).state.user.keys.overflow = false := hfull
93
+ simpa only [searchRight, hc, Bool.false_eq_true, ↓reduceIte, entries] using hfind P hP hc
94
+ | cons i order ih =>
95
+ by_cases ho : ({ D with maskRestriction := P }.collect B).state.user.keys.overflow = true
96
+ · have hnext := ih (P.force i (decide (i ∈ S))) (P.force_compatible domain S hP i) hfull
97
+ cases hb : decide (i ∈ S) with
98
+ | false =>
99
+ simp only [hb] at hnext
100
+ simp only [searchRight, ho, ↓reduceIte, hnext]
101
+ | true =>
102
+ simp only [hb] at hnext
103
+ simp only [searchRight, ho, ↓reduceIte]
104
+ split
105
+ · rfl
106
+ · exact hnext
107
+ · have hc : ({ D with maskRestriction := P }.collect B).state.user.keys.overflow = false :=
108
+ Bool.eq_false_iff.mpr ho
109
+ simpa only [searchRight, hc, Bool.false_eq_true, ↓reduceIte, entries] using hfind P hP hc
110
+ /-- No prefix task can introduce a false YES. This applies to every family
111
+ outcome and every overflow pattern, rather than just the surviving bucket. -/
112
+ theorem searchRight_subset_sum_sound {g : ℕ} (B : ℕ) (C : TopCoordinates n g)
113
+ (families : Fin 4 → Array (Finset (Fin g))) (left : Array (Entry (Fin n)))
114
+ (order : List (Fin n)) (P : MaskRestriction n) (leftDomain : Finset (Fin n))
115
+ (htop : RepresentationUniverse.topDomain D.leaves = C.domain)
116
+ (htl : Disjoint (RepresentationUniverse.topDomain D.leaves)
117
+ (RepresentationUniverse.mixerDomain D.leaves))
118
+ (htb : Disjoint (RepresentationUniverse.topDomain D.leaves)
119
+ (RepresentationUniverse.backgroundDomain D.leaves))
120
+ (hlb : Disjoint (RepresentationUniverse.mixerDomain D.leaves)
121
+ (RepresentationUniverse.backgroundDomain D.leaves))
122
+ (hshared : leftDomain ∩ RepresentationUniverse.parentDomain D.leaves ⊆ C.domain)
123
+ (hleft : ∀ e ∈ left.toList, Represents D.weights leftDomain C.domain e)
124
+ (hsize : left.size + (D.capacity + 1) ≤ 2 ^ n)
125
+ (hyes : D.searchRight B (fun right => (C.check families
126
+ ((D.input.target : ℤ) - weight (fun i => (D.input.values i : ℤ)) D.signs)
127
+ left.toList right.toList).accepted) order P = true) : Solvable D.input := by
128
+ apply D.searchRight_sound B _ (Solvable D.input) ?_ order P hyes
129
+ intro P hp
130
+ let task := { D with maskRestriction := P }
131
+ apply C.subset_sum_sound D.input D.signs families left.toList (task.entries B).toList
132
+ (leftDomain := leftDomain) (rightDomain := RepresentationUniverse.parentDomain D.leaves)
133
+ (by
134
+ simp only [Array.length_toList]
135
+ exact (Nat.add_le_add_left (task.storage B).1 _).trans hsize)
136
+ hshared hleft ?_ hp
137
+ intro e he
138
+ rw [← htop]
139
+ exact task.entry_represents B htl htb hlb e he
140
+
141
+ end RepresentationParentData
142
+ end LowSpaceSubsetSum
143
+
144
+ end OAI
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/PrefixAccounting.lean ADDED
@@ -0,0 +1,210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Mathlib.Data.Finset.Card
2
+ import Mathlib.Data.Finset.Filter
3
+ import Mathlib.Tactic
4
+
5
+ namespace OAI
6
+
7
+ /-!
8
+ # Deterministic accounting for right-prefix refinement
9
+
10
+ The tree depends on distinct entries for overflow, while raw tuple occurrences
11
+ are charged separately. The finite sets in this mathematical accounting are
12
+ ambient analysis sets, not arrays that the implementation is allowed to store.
13
+ The resulting combinatorial bounds give the accounting in `lem:prefix`.
14
+ -/
15
+
16
+ namespace LowSpaceSubsetSum
17
+
18
+ variable {α : Type*}
19
+
20
+ /-- Labels of the successive mask bits, in the fixed processing order. -/
21
+ abbrev MaskBits (α : Type*) := ℕ → α → Bool
22
+
23
+ def bitPart (bits : MaskBits α) (depth : ℕ) (side : Bool) (U : Finset α) : Finset α :=
24
+ U.filter fun x => bits depth x = side
25
+
26
+ theorem bitPart_card_add (bits : MaskBits α) (depth : ℕ) (U : Finset α) :
27
+ (bitPart bits depth false U).card + (bitPart bits depth true U).card = U.card := by
28
+ have h := Finset.card_filter_add_card_filter_not (s := U)
29
+ (p := fun x => bits depth x = false)
30
+ simpa [bitPart, Bool.not_eq_false] using h
31
+
32
+ /-- Overflow count includes an overflowing full-prefix node that is dropped. -/
33
+ def overflowNodes (C : ℕ) (bits : MaskBits α) (depth : ℕ) : ℕ → Finset α → ℕ
34
+ | 0, U => if C < U.card then 1 else 0
35
+ | fuel + 1, U => if C < U.card then
36
+ 1 + overflowNodes C bits (depth + 1) fuel (bitPart bits depth false U) +
37
+ overflowNodes C bits (depth + 1) fuel (bitPart bits depth true U)
38
+ else 0
39
+
40
+ /-- The task count includes empty completed tasks and dropped full prefixes. -/
41
+ def prefixTasks (C : ℕ) (bits : MaskBits α) (depth : ℕ) : ℕ → Finset α → ℕ
42
+ | 0, _ => 1
43
+ | fuel + 1, U => if C < U.card then
44
+ 1 + prefixTasks C bits (depth + 1) fuel (bitPart bits depth false U) +
45
+ prefixTasks C bits (depth + 1) fuel (bitPart bits depth true U)
46
+ else 1
47
+
48
+ /-- Sum of the lengths of all completed right dictionaries. -/
49
+ def completedEntries (C : ℕ) (bits : MaskBits α) (depth : ℕ) : ℕ → Finset α → ℕ
50
+ | 0, U => if C < U.card then 0 else U.card
51
+ | fuel + 1, U => if C < U.card then
52
+ completedEntries C bits (depth + 1) fuel (bitPart bits depth false U) +
53
+ completedEntries C bits (depth + 1) fuel (bitPart bits depth true U)
54
+ else U.card
55
+
56
+ /-- The sum of ambient entry counts over all task nodes, for charging by depth. -/
57
+ def potentialVisits (C : ℕ) (bits : MaskBits α) (depth : ℕ) : ℕ → Finset α → ℕ
58
+ | 0, U => U.card
59
+ | fuel + 1, U => if C < U.card then
60
+ U.card + potentialVisits C bits (depth + 1) fuel (bitPart bits depth false U) +
61
+ potentialVisits C bits (depth + 1) fuel (bitPart bits depth true U)
62
+ else U.card
63
+
64
+ /-- Raw occurrences are a separate type and retain all multiplicities. Task
65
+ branching is decided by `U`, the distinct entries, rather than by `T`. -/
66
+ def rawVisits {β : Type*} (C : ℕ) (bits : MaskBits α) (rawBits : MaskBits β)
67
+ (depth : ℕ) : ℕ → Finset α → Finset β → ℕ
68
+ | 0, _, T => T.card
69
+ | fuel + 1, U, T => if C < U.card then
70
+ T.card + rawVisits C bits rawBits (depth + 1) fuel
71
+ (bitPart bits depth false U) (bitPart rawBits depth false T) +
72
+ rawVisits C bits rawBits (depth + 1) fuel
73
+ (bitPart bits depth true U) (bitPart rawBits depth true T)
74
+ else T.card
75
+
76
+ /-- The bucket reached by following a designated entry's complete prefix. -/
77
+ def fullPrefixBucket (bits : MaskBits α) (depth : ℕ) (e : α) : ℕ → Finset α → Finset α
78
+ | 0, U => U
79
+ | fuel + 1, U => fullPrefixBucket bits (depth + 1) e fuel
80
+ (bitPart bits depth (bits depth e) U)
81
+
82
+ /-- The actual refinement path stops at the first dictionary that fits. -/
83
+ def reachesCompleted (C : ℕ) (bits : MaskBits α) (depth : ℕ) (e : α) :
84
+ ℕ → Finset α → Prop
85
+ | 0, U => U.card ≤ C
86
+ | fuel + 1, U => U.card ≤ C ∨ reachesCompleted C bits (depth + 1) e fuel
87
+ (bitPart bits depth (bits depth e) U)
88
+
89
+ theorem mem_fullPrefixBucket (bits : MaskBits α) (depth fuel : ℕ)
90
+ {e : α} {U : Finset α} (he : e ∈ U) :
91
+ e ∈ fullPrefixBucket bits depth e fuel U := by
92
+ induction fuel generalizing depth U with
93
+ | zero => exact he
94
+ | succ fuel ih =>
95
+ apply ih
96
+ exact Finset.mem_filter.mpr ⟨he, rfl⟩
97
+
98
+ /-- A fitting full-prefix bucket ensures that the designated path completes,
99
+ even if larger ancestors overflow. -/
100
+ theorem reachesCompleted_of_fullPrefix_fits (C : ℕ) (bits : MaskBits α)
101
+ (depth fuel : ℕ) (e : α) (U : Finset α)
102
+ (hfit : (fullPrefixBucket bits depth e fuel U).card ≤ C) :
103
+ reachesCompleted C bits depth e fuel U := by
104
+ induction fuel generalizing depth U with
105
+ | zero => exact hfit
106
+ | succ fuel ih =>
107
+ right
108
+ exact ih (depth + 1) (bitPart bits depth (bits depth e) U) hfit
109
+
110
+ theorem overflowNodes_capacity_bound (C : ℕ) (bits : MaskBits α)
111
+ (depth fuel : ℕ) (U : Finset α) :
112
+ C * overflowNodes C bits depth fuel U ≤ (fuel + 1) * U.card := by
113
+ induction fuel generalizing depth U with
114
+ | zero =>
115
+ simp only [overflowNodes]
116
+ split_ifs with h <;> simp_all
117
+ omega
118
+ | succ fuel ih =>
119
+ simp only [overflowNodes]
120
+ split_ifs with h
121
+ · have h0 := ih (depth + 1) (bitPart bits depth false U)
122
+ have h1 := ih (depth + 1) (bitPart bits depth true U)
123
+ have hc := bitPart_card_add bits depth U
124
+ nlinarith
125
+ · simp
126
+
127
+ theorem prefixTasks_le_overflowNodes (C : ℕ) (bits : MaskBits α)
128
+ (depth fuel : ℕ) (U : Finset α) :
129
+ prefixTasks C bits depth fuel U ≤ 1 + 2 * overflowNodes C bits depth fuel U := by
130
+ induction fuel generalizing depth U with
131
+ | zero => simp [prefixTasks, overflowNodes]
132
+ | succ fuel ih =>
133
+ simp only [prefixTasks, overflowNodes]
134
+ split_ifs with h
135
+ · have h0 := ih (depth + 1) (bitPart bits depth false U)
136
+ have h1 := ih (depth + 1) (bitPart bits depth true U)
137
+ omega
138
+ · simp
139
+
140
+ /-- Division-free version of the right task-start bound. -/
141
+ theorem prefixTasks_capacity_bound (C : ℕ) (bits : MaskBits α)
142
+ (depth fuel : ℕ) (U : Finset α) :
143
+ C * prefixTasks C bits depth fuel U ≤ C + 2 * (fuel + 1) * U.card := by
144
+ have ht := prefixTasks_le_overflowNodes C bits depth fuel U
145
+ have ho := overflowNodes_capacity_bound C bits depth fuel U
146
+ nlinarith
147
+
148
+ theorem completedEntries_le_card (C : ℕ) (bits : MaskBits α)
149
+ (depth fuel : ℕ) (U : Finset α) :
150
+ completedEntries C bits depth fuel U ≤ U.card := by
151
+ induction fuel generalizing depth U with
152
+ | zero => simp only [completedEntries]; split_ifs <;> omega
153
+ | succ fuel ih =>
154
+ simp only [completedEntries]
155
+ split_ifs with h
156
+ · have h0 := ih (depth + 1) (bitPart bits depth false U)
157
+ have h1 := ih (depth + 1) (bitPart bits depth true U)
158
+ have hc := bitPart_card_add bits depth U
159
+ omega
160
+ · rfl
161
+
162
+ /-- Every occurrence has exactly one prefix at a fixed depth. The total
163
+ potential work is charged by depth, even for occurrences later rejected. -/
164
+ theorem potentialVisits_le_depth_mul_card (C : ℕ) (bits : MaskBits α)
165
+ (depth fuel : ℕ) (U : Finset α) :
166
+ potentialVisits C bits depth fuel U ≤ (fuel + 1) * U.card := by
167
+ induction fuel generalizing depth U with
168
+ | zero => simp [potentialVisits]
169
+ | succ fuel ih =>
170
+ simp only [potentialVisits]
171
+ split_ifs with h
172
+ · have h0 := ih (depth + 1) (bitPart bits depth false U)
173
+ have h1 := ih (depth + 1) (bitPart bits depth true U)
174
+ have hc := bitPart_card_add bits depth U
175
+ nlinarith
176
+ · nlinarith
177
+
178
+ /-- The occurrence bound is independent of deduplication and validity tests. -/
179
+ theorem rawVisits_le_depth_mul_card {β : Type*}
180
+ (C : ℕ) (bits : MaskBits α) (rawBits : MaskBits β)
181
+ (depth fuel : ℕ) (U : Finset α) (T : Finset β) :
182
+ rawVisits C bits rawBits depth fuel U T ≤ (fuel + 1) * T.card := by
183
+ induction fuel generalizing depth U T with
184
+ | zero => simp [rawVisits]
185
+ | succ fuel ih =>
186
+ simp only [rawVisits]
187
+ split_ifs with h
188
+ · have h0 := ih (depth + 1) (bitPart bits depth false U)
189
+ (bitPart rawBits depth false T)
190
+ have h1 := ih (depth + 1) (bitPart bits depth true U)
191
+ (bitPart rawBits depth true T)
192
+ have hc := bitPart_card_add rawBits depth T
193
+ nlinarith
194
+ · nlinarith
195
+
196
+ /-- Even charging the left array at every task bounds all actual final-check
197
+ inputs. This includes every reuse of the same retained left array. -/
198
+ theorem checkInputs_le (C L : ℕ) (hL : L ≤ C) (bits : MaskBits α)
199
+ (depth fuel : ℕ) (U : Finset α) :
200
+ completedEntries C bits depth fuel U + L * prefixTasks C bits depth fuel U ≤
201
+ L + (2 * fuel + 3) * U.card := by
202
+ have ht := prefixTasks_le_overflowNodes C bits depth fuel U
203
+ have ho := overflowNodes_capacity_bound C bits depth fuel U
204
+ have he := completedEntries_le_card C bits depth fuel U
205
+ have hscale := Nat.mul_le_mul_left (overflowNodes C bits depth fuel U) hL
206
+ nlinarith
207
+
208
+ end LowSpaceSubsetSum
209
+
210
+ end OAI
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/PrefixCheckList.lean ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import OAI.Combinatorics.LowSpaceSubsetSum.Representation.RepresentationBucketProgram
2
+
3
+ namespace OAI
4
+
5
+ /-! # A family-independent list of the completed prefix checks
6
+
7
+ These lists describe the hypothetical full traversal for analysis. The
8
+ executable search regenerates one task at a time and stops at its first YES.
9
+ -/
10
+
11
+ namespace LowSpaceSubsetSum.RepresentationParentData
12
+
13
+ variable {n : ℕ} (D : RepresentationParentData n)
14
+
15
+ def completedArrays (B : ℕ) : List (Fin n) → MaskRestriction n → List (Array (Entry (Fin n)))
16
+ | order, P =>
17
+ let task := { D with maskRestriction := P }
18
+ let out := (task.collect B).state.user
19
+ if out.keys.overflow then
20
+ match order with
21
+ | [] => []
22
+ | i :: rest => completedArrays B rest (P.force i false) ++
23
+ completedArrays B rest (P.force i true)
24
+ else [out.records]
25
+
26
+ theorem searchRight_eq_any (B : ℕ) (check : Array (Entry (Fin n)) → Bool)
27
+ (order : List (Fin n)) (P : MaskRestriction n) :
28
+ D.searchRight B check order P = (D.completedArrays B order P).any check := by
29
+ induction order generalizing P with
30
+ | nil =>
31
+ simp only [searchRight, completedArrays]
32
+ split <;> simp
33
+ | cons i order ih =>
34
+ simp only [searchRight, completedArrays]
35
+ split
36
+ · rw [List.any_append, ← ih, ← ih]
37
+ split <;> simp_all
38
+ · simp
39
+
40
+ theorem mem_completedArrays (B : ℕ) (order : List (Fin n)) (P : MaskRestriction n)
41
+ (a : Array (Entry (Fin n))) (ha : a ∈ D.completedArrays B order P) :
42
+ ∃ Q : MaskRestriction n,
43
+ ({ D with maskRestriction := Q }.collect B).state.user.keys.overflow = false ∧
44
+ a = { D with maskRestriction := Q }.entries B := by
45
+ induction order generalizing P with
46
+ | nil =>
47
+ simp only [completedArrays] at ha
48
+ split at ha
49
+ · simp at ha
50
+ · rename_i hc
51
+ have he : a = ({ D with maskRestriction := P }.collect B).state.user.records := by
52
+ simpa only [List.mem_singleton] using ha
53
+ exact ⟨P, Bool.eq_false_iff.mpr hc, he⟩
54
+ | cons i order ih =>
55
+ simp only [completedArrays] at ha
56
+ split at ha
57
+ · rcases List.mem_append.mp ha with hl | hr
58
+ · exact ih (P.force i false) hl
59
+ · exact ih (P.force i true) hr
60
+ · rename_i hc
61
+ have he : a = ({ D with maskRestriction := P }.collect B).state.user.records := by
62
+ simpa only [List.mem_singleton] using ha
63
+ exact ⟨P, Bool.eq_false_iff.mpr hc, he⟩
64
+
65
+ end LowSpaceSubsetSum.RepresentationParentData
66
+
67
+ namespace LowSpaceSubsetSum.RepresentationBucketData
68
+
69
+ variable {n g : ℕ} (D : RepresentationBucketData n g)
70
+
71
+ def checkList (B : ℕ) : List (Array (Entry (Fin n)) × Array (Entry (Fin n))) :=
72
+ let left := (D.left.collect B).state.user
73
+ if left.keys.overflow then []
74
+ else if left.records.isEmpty then []
75
+ else (D.right.completedArrays B D.topOrder MaskRestriction.empty).map (left.records, ·)
76
+
77
+ theorem run_eq_any (B : ℕ) (families : Fin 4 → Array (Finset (Fin g))) :
78
+ D.run B families = (D.checkList B).any (fun p => D.check families p.1 p.2) := by
79
+ unfold run checkList
80
+ dsimp only
81
+ split
82
+ · simp
83
+ split
84
+ · simp
85
+ rw [D.right.searchRight_eq_any, List.any_map]
86
+ rfl
87
+
88
+ end LowSpaceSubsetSum.RepresentationBucketData
89
+
90
+ end OAI
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/PrefixMachine.lean ADDED
@@ -0,0 +1,197 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import OAI.Combinatorics.LowSpaceSubsetSum.Streams.ParentPrefixSearch
2
+ import OAI.Combinatorics.LowSpaceSubsetSum.Search.Watchdog
3
+
4
+ namespace OAI
5
+
6
+ /-! # Explicit pending-sibling stack for prefix recomputation
7
+
8
+ A collector result is inspected and discarded in one task action. A frame
9
+ contains only the next restriction and remaining index order. In particular,
10
+ no overflowing dictionary or reader state is retained in a frame. Task
11
+ execution inside this action is accounted for separately by the join ledger.
12
+ -/
13
+
14
+ namespace LowSpaceSubsetSum.PrefixMachine
15
+
16
+ variable {n : ℕ}
17
+
18
+ structure Job (n : ℕ) where
19
+ order : List (Fin n)
20
+ restriction : MaskRestriction n
21
+
22
+ inductive Control (n : ℕ)
23
+ | eval : Job n → List (Job n) → Control n
24
+ | ret : Bool → List (Job n) → Control n
25
+
26
+ namespace Control
27
+
28
+ def stack : Control n → List (Job n)
29
+ | .eval _ pending => pending
30
+ | .ret _ pending => pending
31
+
32
+ /-- Masks and an order pointer can use fewer cells. Counting every mask bit
33
+ and every remaining order element still gives this conservative bound. -/
34
+ def cells (s : Control n) : ℕ := (4 * n + 16) * (s.stack.length + 1)
35
+
36
+ end Control
37
+
38
+ def step (D : RepresentationParentData n) (B : ℕ)
39
+ (check : Array (Entry (Fin n)) → Bool) : Control n → Watchdog.Transition (Control n)
40
+ | .eval job pending =>
41
+ let out := ({ D with maskRestriction := job.restriction }.collect B).state.user
42
+ if out.keys.overflow then
43
+ match job.order with
44
+ | [] => .next (.ret false pending)
45
+ | i :: rest => .next (.eval ⟨rest, job.restriction.force i false⟩
46
+ (⟨rest, job.restriction.force i true⟩ :: pending))
47
+ else .next (.ret (check out.records) pending)
48
+ | .ret true _ => .halt true
49
+ | .ret false [] => .halt false
50
+ | .ret false (job :: pending) => .next (.eval job pending)
51
+
52
+ def GoodStack (N : ℕ) (pending : List (Job n)) : Prop :=
53
+ pending.Pairwise (fun a b => a.order.length < b.order.length) ∧
54
+ ∀ job ∈ pending, job.order.length ≤ N
55
+
56
+ def Invariant (N : ℕ) : Control n → Prop
57
+ | .eval job pending => GoodStack N pending ∧ job.order.length ≤ N ∧
58
+ ∀ next ∈ pending, job.order.length ≤ next.order.length
59
+ | .ret _ pending => GoodStack N pending
60
+
61
+ theorem goodStack_length {N : ℕ} {pending : List (Job n)} (h : GoodStack N pending) :
62
+ pending.length ≤ N + 1 := by
63
+ have hpair : (pending.map (fun j => j.order.length)).Pairwise (· < ·) :=
64
+ List.pairwise_map.mpr h.1
65
+ have hnd : (pending.map (fun j => j.order.length)).Nodup :=
66
+ hpair.imp (fun hlt => Nat.ne_of_lt hlt)
67
+ have hsub : (pending.map (fun j => j.order.length)).toFinset ⊆ Finset.range (N + 1) := by
68
+ intro r hr
69
+ obtain ⟨job, hj, rfl⟩ := List.mem_map.mp (List.mem_toFinset.mp hr)
70
+ exact Finset.mem_range.mpr (Nat.lt_succ_of_le (h.2 job hj))
71
+ have hc := Finset.card_le_card hsub
72
+ simpa only [List.toFinset_card_of_nodup hnd, List.length_map, Finset.card_range] using hc
73
+
74
+ theorem invariant_next (D : RepresentationParentData n) (B : ℕ)
75
+ (check : Array (Entry (Fin n)) → Bool) (N : ℕ) (s t : Control n)
76
+ (hs : Invariant N s) (ht : step D B check s = .next t) : Invariant N t := by
77
+ cases s with
78
+ | eval job pending =>
79
+ obtain ⟨hstack, hjob, hhead⟩ := hs
80
+ simp only [step] at ht
81
+ split at ht
82
+ · cases ho : job.order with
83
+ | nil =>
84
+ simp only [ho] at ht
85
+ cases ht
86
+ exact hstack
87
+ | cons i rest =>
88
+ simp only [ho] at ht
89
+ cases ht
90
+ have hlen : rest.length + 1 = job.order.length := by simp [ho]
91
+ refine ⟨⟨List.pairwise_cons.mpr ⟨?_, hstack.1⟩, ?_⟩, ?_, ?_⟩
92
+ · intro next hn
93
+ exact lt_of_lt_of_le (by omega : rest.length < job.order.length) (hhead next hn)
94
+ · intro next hn
95
+ rcases List.mem_cons.mp hn with rfl | hn
96
+ · dsimp only; omega
97
+ · exact hstack.2 next hn
98
+ · dsimp only; omega
99
+ · intro next hn
100
+ rcases List.mem_cons.mp hn with rfl | hn
101
+ · exact le_rfl
102
+ · exact (show rest.length ≤ job.order.length by omega).trans (hhead next hn)
103
+ · cases ht
104
+ exact hstack
105
+ | ret b pending =>
106
+ cases b with
107
+ | true => simp [step] at ht
108
+ | false =>
109
+ cases pending with
110
+ | nil => simp [step] at ht
111
+ | cons job pending =>
112
+ simp only [step] at ht
113
+ cases ht
114
+ obtain ⟨hpair, hbound⟩ := hs
115
+ obtain ⟨hhead, htail⟩ := List.pairwise_cons.mp hpair
116
+ refine ⟨⟨htail, fun j hj => hbound j (List.mem_cons_of_mem _ hj)⟩,
117
+ hbound job (List.mem_cons_self), ?_⟩
118
+ exact fun j hj => (hhead j hj).le
119
+
120
+ theorem cells_le (N : ℕ) (s : Control n) (hs : Invariant N s) :
121
+ s.cells ≤ (4 * n + 16) * (N + 2) := by
122
+ have hg : GoodStack N s.stack := by
123
+ cases s with
124
+ | eval job pending => exact hs.1
125
+ | ret b pending => exact hs
126
+ have hl := goodStack_length hg
127
+ exact Nat.mul_le_mul_left _ (by omega)
128
+
129
+ def jobValue (D : RepresentationParentData n) (B : ℕ)
130
+ (check : Array (Entry (Fin n)) → Bool) (job : Job n) : Bool :=
131
+ D.searchRight B check job.order job.restriction
132
+
133
+ def meaning (D : RepresentationParentData n) (B : ℕ)
134
+ (check : Array (Entry (Fin n)) → Bool) : Control n → Bool
135
+ | .eval job pending => jobValue D B check job || pending.any (jobValue D B check)
136
+ | .ret b pending => b || pending.any (jobValue D B check)
137
+
138
+ theorem step_meaning (D : RepresentationParentData n) (B : ℕ)
139
+ (check : Array (Entry (Fin n)) → Bool) (s : Control n) :
140
+ match step D B check s with
141
+ | .halt b => meaning D B check s = b
142
+ | .next t => meaning D B check s = meaning D B check t := by
143
+ cases s with
144
+ | eval job pending =>
145
+ cases job with
146
+ | mk order P =>
147
+ by_cases ho : ({ D with maskRestriction := P }.collect B).state.user.keys.overflow = true
148
+ · cases order with
149
+ | nil => simp [step, ho, meaning, jobValue, RepresentationParentData.searchRight]
150
+ | cons i rest =>
151
+ simp only [step, ho, ↓reduceIte, meaning, List.any_cons, jobValue]
152
+ rw [RepresentationParentData.searchRight]
153
+ simp only [ho, ↓reduceIte]
154
+ by_cases hv : D.searchRight B check rest (P.force i false) = true
155
+ · simp only [hv, ↓reduceIte, Bool.true_or]
156
+ · have hf : D.searchRight B check rest (P.force i false) = false := Bool.eq_false_iff.mpr hv
157
+ simp [hf]
158
+ · have hf : ({ D with maskRestriction := P }.collect B).state.user.keys.overflow = false :=
159
+ Bool.eq_false_iff.mpr ho
160
+ rw [step]
161
+ simp only [hf, Bool.false_eq_true, ↓reduceIte, meaning, jobValue]
162
+ rw [RepresentationParentData.searchRight.eq_def]
163
+ simp only [hf, Bool.false_eq_true, ↓reduceIte]
164
+ | ret b pending =>
165
+ cases b <;> cases pending <;> simp [step, meaning]
166
+
167
+ theorem watchdog_sound (D : RepresentationParentData n) (B : ℕ)
168
+ (check : Array (Entry (Fin n)) → Bool) (Q : Prop)
169
+ (hcheck : ∀ P, check ({ D with maskRestriction := P }.entries B) = true → Q)
170
+ (job : Job n) (budget : ℕ)
171
+ (hyes : Watchdog.accepted (Watchdog.run (step D B check) Control.cells
172
+ budget (.eval job [])) = true) : Q := by
173
+ apply Watchdog.sound (step D B check) Control.cells
174
+ (fun s => meaning D B check s = true → Q) Q ?_ ?_ budget (.eval job []) ?_ hyes
175
+ · intro s t hs ht h
176
+ have hm := step_meaning D B check s
177
+ rw [ht] at hm
178
+ exact hs (hm.trans h)
179
+ · intro s hs ht
180
+ have hm := step_meaning D B check s
181
+ rw [ht] at hm
182
+ exact hs hm
183
+ · intro h
184
+ have hj : jobValue D B check job = true := by simpa only [meaning, List.any_nil, Bool.or_false] using h
185
+ exact D.searchRight_sound B check Q hcheck job.order job.restriction hj
186
+
187
+ theorem watchdog_stack_peak (D : RepresentationParentData n) (B : ℕ)
188
+ (check : Array (Entry (Fin n)) → Bool) (job : Job n) (budget : ℕ) :
189
+ (Watchdog.run (step D B check) Control.cells budget (.eval job [])).peak ≤
190
+ (4 * n + 16) * (job.order.length + 2) := by
191
+ apply Watchdog.peak_le _ _ (Invariant job.order.length) _
192
+ (invariant_next D B check job.order.length) (cells_le job.order.length)
193
+ simp [Invariant, GoodStack]
194
+
195
+ end LowSpaceSubsetSum.PrefixMachine
196
+
197
+ end OAI
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/PrefixMachineRun.lean ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import OAI.Combinatorics.LowSpaceSubsetSum.Streams.PrefixMachine
2
+ import OAI.Combinatorics.LowSpaceSubsetSum.Streams.PrefixTaskCount
3
+ import OAI.Combinatorics.LowSpaceSubsetSum.Search.WatchdogRanking
4
+
5
+ namespace OAI
6
+
7
+ /-! # Termination of the explicit prefix stack
8
+
9
+ The rank charges all possible task starts, including the sibling skipped
10
+ after an early YES. The stack machine terminates in at most three times
11
+ this task count plus two control actions. A collector action is a macro,
12
+ whose internal primitive operations still need their own watchdog.
13
+ -/
14
+
15
+ namespace LowSpaceSubsetSum.PrefixMachine
16
+
17
+ variable {n : ℕ}
18
+
19
+ def pendingWeight (D : RepresentationParentData n) (B : ℕ) (pending : List (Job n)) : ℕ :=
20
+ (pending.map (fun job => 3 * D.taskStarts B job.order job.restriction + 2)).sum
21
+
22
+ def rank (D : RepresentationParentData n) (B : ℕ) : Control n → ℕ
23
+ | .eval job pending =>
24
+ 3 * D.taskStarts B job.order job.restriction + pendingWeight D B pending + 2
25
+ | .ret _ pending => pendingWeight D B pending + 1
26
+
27
+ theorem rank_pos (D : RepresentationParentData n) (B : ℕ) (s : Control n) :
28
+ 1 ≤ rank D B s := by cases s <;> simp only [rank] <;> omega
29
+
30
+ theorem rank_next (D : RepresentationParentData n) (B : ℕ)
31
+ (check : Array (Entry (Fin n)) → Bool) (s t : Control n)
32
+ (ht : step D B check s = .next t) : rank D B t < rank D B s := by
33
+ cases s with
34
+ | eval job pending =>
35
+ cases job with
36
+ | mk order P =>
37
+ by_cases ho : ({ D with maskRestriction := P }.collect B).state.user.keys.overflow = true
38
+ · cases order with
39
+ | nil =>
40
+ simp only [step, ho, ↓reduceIte] at ht
41
+ cases ht
42
+ simp only [rank, RepresentationParentData.taskStarts]
43
+ omega
44
+ | cons i rest =>
45
+ simp only [step, ho, ↓reduceIte] at ht
46
+ cases ht
47
+ simp only [rank, pendingWeight, List.map_cons, List.sum_cons,
48
+ RepresentationParentData.taskStarts, ho, ↓reduceIte]
49
+ omega
50
+ · have hf : ({ D with maskRestriction := P }.collect B).state.user.keys.overflow = false :=
51
+ Bool.eq_false_iff.mpr ho
52
+ simp only [step, hf, Bool.false_eq_true, ↓reduceIte] at ht
53
+ cases ht
54
+ cases order <;>
55
+ simp only [rank, RepresentationParentData.taskStarts, hf, Bool.false_eq_true, ↓reduceIte] <;>
56
+ omega
57
+ | ret b pending =>
58
+ cases b with
59
+ | true => simp [step] at ht
60
+ | false =>
61
+ cases pending with
62
+ | nil => simp [step] at ht
63
+ | cons job pending =>
64
+ simp only [step] at ht
65
+ cases ht
66
+ simp only [rank, pendingWeight, List.map_cons, List.sum_cons]
67
+ omega
68
+
69
+ /-- The explicit stack performs exactly the original prefix search. -/
70
+ theorem output_eq_searchRight (D : RepresentationParentData n) (B : ℕ)
71
+ (check : Array (Entry (Fin n)) → Bool) (job : Job n) :
72
+ (Watchdog.run (step D B check) Control.cells
73
+ (3 * D.taskStarts B job.order job.restriction + 2) (.eval job [])).output =
74
+ some (D.searchRight B check job.order job.restriction) := by
75
+ have h := Watchdog.ranked_complete (step D B check) Control.cells (rank D B)
76
+ (rank_pos D B) (rank_next D B check) (meaning D B check) (fun s => by
77
+ have hs := step_meaning D B check s
78
+ cases ht : step D B check s <;> simp only [ht] at hs ⊢ <;> exact hs)
79
+ (.eval job []) (3 * D.taskStarts B job.order job.restriction + 2)
80
+ (by simp [rank, pendingWeight])
81
+ simpa only [meaning, List.any_nil, Bool.or_false, jobValue] using h
82
+
83
+ end LowSpaceSubsetSum.PrefixMachine
84
+
85
+ end OAI
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/PrefixTaskCount.lean ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import OAI.Combinatorics.LowSpaceSubsetSum.Counting.ParentRestrictionUniverse
2
+ import OAI.Combinatorics.LowSpaceSubsetSum.Streams.PrefixCheckList
3
+
4
+ namespace OAI
5
+
6
+ /-! # Task-start bounds for the executable prefix recursion -/
7
+
8
+ noncomputable section
9
+
10
+ namespace LowSpaceSubsetSum.RepresentationParentData
11
+
12
+ variable {n : ℕ} (D : RepresentationParentData n)
13
+
14
+ def overflowCount (B : ℕ) : List (Fin n) → MaskRestriction n → ℕ
15
+ | order, P =>
16
+ if ({ D with maskRestriction := P }.collect B).state.user.keys.overflow then
17
+ match order with
18
+ | [] => 1
19
+ | i :: rest => 1 + overflowCount B rest (P.force i false) + overflowCount B rest (P.force i true)
20
+ else 0
21
+
22
+ def taskStarts (B : ℕ) : List (Fin n) → MaskRestriction n → ℕ
23
+ | [], _ => 1
24
+ | i :: rest, P =>
25
+ if ({ D with maskRestriction := P }.collect B).state.user.keys.overflow then
26
+ 1 + taskStarts B rest (P.force i false) + taskStarts B rest (P.force i true)
27
+ else 1
28
+
29
+ theorem taskStarts_le_overflow (B : ℕ) (order : List (Fin n)) (P : MaskRestriction n) :
30
+ D.taskStarts B order P ≤ 1 + 2 * D.overflowCount B order P := by
31
+ induction order generalizing P with
32
+ | nil => simp [taskStarts, overflowCount]
33
+ | cons i order ih =>
34
+ simp only [taskStarts, overflowCount]
35
+ split
36
+ · change 1 + D.taskStarts B order (P.force i false) +
37
+ D.taskStarts B order (P.force i true) ≤
38
+ 1 + 2 * (1 + D.overflowCount B order (P.force i false) +
39
+ D.overflowCount B order (P.force i true))
40
+ have h0 := ih (P.force i false)
41
+ have h1 := ih (P.force i true)
42
+ omega
43
+ · omega
44
+
45
+ theorem entryUniverse_force_card_add (P : MaskRestriction n)
46
+ (hd : ∀ i j, i ≠ j → Disjoint (D.leaves i).top (D.leaves j).top)
47
+ (i : Fin n) (hi : i ∈ RepresentationUniverse.topDomain D.leaves) :
48
+ ({ D with maskRestriction := P.force i false }).entryUniverse.card +
49
+ ({ D with maskRestriction := P.force i true }).entryUniverse.card =
50
+ ({ D with maskRestriction := P }).entryUniverse.card := by
51
+ classical
52
+ rw [D.entryUniverse_force P hd i hi false, D.entryUniverse_force P hd i hi true]
53
+ have h := Finset.card_filter_add_card_filter_not
54
+ (s := ({ D with maskRestriction := P }).entryUniverse) (p := fun e => i ∈ e.mask)
55
+ simpa only [decide_eq_false_iff_not, decide_eq_true_eq, add_comm] using h
56
+
57
+ theorem overflowCount_capacity (B : ℕ)
58
+ (hd : ∀ i j, i ≠ j → Disjoint (D.leaves i).top (D.leaves j).top)
59
+ (hbounded : ∀ P, ∀ e ∈ ({ D with maskRestriction := P }).rawEntries,
60
+ WeightEncoding.BoundedWeight D.input e.value)
61
+ (order : List (Fin n)) (horder : ∀ i ∈ order, i ∈ RepresentationUniverse.topDomain D.leaves)
62
+ (P : MaskRestriction n) :
63
+ D.capacity * D.overflowCount B order P ≤
64
+ (order.length + 1) * ({ D with maskRestriction := P }).entryUniverse.card := by
65
+ induction order generalizing P with
66
+ | nil =>
67
+ simp only [overflowCount, List.length_nil]
68
+ split
69
+ · rename_i ho
70
+ have hc : D.capacity < ({ D with maskRestriction := P }).entryUniverse.card :=
71
+ (({ D with maskRestriction := P }).collect_overflow_iff_card B (hbounded P)).mp ho
72
+ simp only [Nat.zero_add, one_mul, mul_one]
73
+ omega
74
+ · simp
75
+ | cons i order ih =>
76
+ simp only [overflowCount, List.length_cons]
77
+ split
78
+ · rename_i ho
79
+ have hc : D.capacity < ({ D with maskRestriction := P }).entryUniverse.card :=
80
+ (({ D with maskRestriction := P }).collect_overflow_iff_card B (hbounded P)).mp ho
81
+ have h0 := ih (fun j hj => horder j (by simp [hj])) (P.force i false)
82
+ have h1 := ih (fun j hj => horder j (by simp [hj])) (P.force i true)
83
+ have hs := D.entryUniverse_force_card_add P hd i (horder i (by simp))
84
+ generalize ({ D with maskRestriction := P }).entryUniverse.card = U at hc hs ⊢
85
+ generalize ({ D with maskRestriction := P.force i false }).entryUniverse.card = U0 at h0 hs
86
+ generalize ({ D with maskRestriction := P.force i true }).entryUniverse.card = U1 at h1 hs
87
+ nlinarith only [hc, h0, h1, hs]
88
+ · simp
89
+
90
+ theorem taskStarts_capacity (B : ℕ)
91
+ (hd : ∀ i j, i ≠ j → Disjoint (D.leaves i).top (D.leaves j).top)
92
+ (hbounded : ∀ P, ∀ e ∈ ({ D with maskRestriction := P }).rawEntries,
93
+ WeightEncoding.BoundedWeight D.input e.value)
94
+ (order : List (Fin n)) (horder : ∀ i ∈ order, i ∈ RepresentationUniverse.topDomain D.leaves)
95
+ (P : MaskRestriction n) :
96
+ D.capacity * D.taskStarts B order P ≤ D.capacity +
97
+ 2 * (order.length + 1) * ({ D with maskRestriction := P }).entryUniverse.card := by
98
+ have ht := D.taskStarts_le_overflow B order P
99
+ have ho := D.overflowCount_capacity B hd hbounded order horder P
100
+ nlinarith
101
+
102
+ theorem completedArrays_length_le (B : ℕ) (order : List (Fin n)) (P : MaskRestriction n) :
103
+ (D.completedArrays B order P).length ≤ D.taskStarts B order P := by
104
+ induction order generalizing P with
105
+ | nil =>
106
+ simp only [completedArrays, taskStarts]
107
+ split <;> simp
108
+ | cons i order ih =>
109
+ simp only [completedArrays, taskStarts]
110
+ split
111
+ · change (D.completedArrays B order (P.force i false) ++
112
+ D.completedArrays B order (P.force i true)).length ≤
113
+ 1 + D.taskStarts B order (P.force i false) + D.taskStarts B order (P.force i true)
114
+ simp only [List.length_append]
115
+ have h0 := ih (P.force i false)
116
+ have h1 := ih (P.force i true)
117
+ omega
118
+ · simp
119
+
120
+ theorem completedArrays_size_sum_le (B : ℕ)
121
+ (hd : ∀ i j, i ≠ j → Disjoint (D.leaves i).top (D.leaves j).top)
122
+ (hbounded : ∀ P, ∀ e ∈ ({ D with maskRestriction := P }).rawEntries,
123
+ WeightEncoding.BoundedWeight D.input e.value)
124
+ (order : List (Fin n)) (horder : ∀ i ∈ order, i ∈ RepresentationUniverse.topDomain D.leaves)
125
+ (P : MaskRestriction n) :
126
+ ((D.completedArrays B order P).map Array.size).sum ≤
127
+ ({ D with maskRestriction := P }).entryUniverse.card := by
128
+ induction order generalizing P with
129
+ | nil =>
130
+ simp only [completedArrays]
131
+ split
132
+ · simp
133
+ · rename_i hc
134
+ have hclear := Bool.eq_false_iff.mpr hc
135
+ simpa only [List.map_singleton, List.sum_singleton, entries] using
136
+ (({ D with maskRestriction := P }).completed_size_eq_card B (hbounded P) hclear).le
137
+ | cons i order ih =>
138
+ simp only [completedArrays]
139
+ split
140
+ · simp only [List.map_append, List.sum_append]
141
+ have h0 := ih (fun j hj => horder j (by simp [hj])) (P.force i false)
142
+ have h1 := ih (fun j hj => horder j (by simp [hj])) (P.force i true)
143
+ have hs := D.entryUniverse_force_card_add P hd i (horder i (by simp))
144
+ omega
145
+ · rename_i hc
146
+ have hclear := Bool.eq_false_iff.mpr hc
147
+ simpa only [List.map_singleton, List.sum_singleton, entries] using
148
+ (({ D with maskRestriction := P }).completed_size_eq_card B (hbounded P) hclear).le
149
+
150
+ private theorem input_sum (L : ℕ) (arrays : List (Array (Entry (Fin n)))) :
151
+ (arrays.map (fun a => L + a.size)).sum = (arrays.map Array.size).sum + L * arrays.length := by
152
+ induction arrays with
153
+ | nil => simp
154
+ | cons a arrays ih =>
155
+ simp only [List.map_cons, List.sum_cons, List.length_cons, ih, Nat.mul_add, Nat.mul_one]
156
+ omega
157
+
158
+ /-- Includes every reuse of the retained left array at a completed right
159
+ prefix; it is the actual check list's input-occurrence bound. -/
160
+ theorem completed_check_inputs_le (B L : ℕ) (hL : L ≤ D.capacity)
161
+ (hd : ∀ i j, i ≠ j → Disjoint (D.leaves i).top (D.leaves j).top)
162
+ (hbounded : ∀ P, ∀ e ∈ ({ D with maskRestriction := P }).rawEntries,
163
+ WeightEncoding.BoundedWeight D.input e.value)
164
+ (order : List (Fin n)) (horder : ∀ i ∈ order, i ∈ RepresentationUniverse.topDomain D.leaves)
165
+ (P : MaskRestriction n) :
166
+ ((D.completedArrays B order P).map (fun a => L + a.size)).sum ≤
167
+ L + (2 * order.length + 3) * ({ D with maskRestriction := P }).entryUniverse.card := by
168
+ rw [input_sum]
169
+ have hn := D.completedArrays_length_le B order P
170
+ have he := D.completedArrays_size_sum_le B hd hbounded order horder P
171
+ have ht := D.taskStarts_le_overflow B order P
172
+ have ho := D.overflowCount_capacity B hd hbounded order horder P
173
+ have hscale := Nat.mul_le_mul_left (D.overflowCount B order P) hL
174
+ nlinarith
175
+
176
+ end LowSpaceSubsetSum.RepresentationParentData
177
+
178
+ end
179
+
180
+ end OAI
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/ReaderInitializationMap.lean ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import OAI.Combinatorics.LowSpaceSubsetSum.Streams.ReaderMap
2
+
3
+ namespace OAI
4
+
5
+ /-! # Semantic maps commute with the actual binary-search initialization -/
6
+
7
+ namespace LowSpaceSubsetSum
8
+ namespace BinarySlice
9
+
10
+ variable {α β : Type*}
11
+
12
+ private theorem search_lo_congr {m n : ℕ} (h : m = n)
13
+ (p : Fin m → Bool) (q : Fin n → Bool)
14
+ (hpq : ∀ i j, i.val = j.val → p i = q j) (k : ℕ) :
15
+ (BinaryPivot.search p k).lo = (BinaryPivot.search q k).lo := by
16
+ subst n
17
+ have he : p = q := funext (fun i => hpq i i rfl)
18
+ rw [he]
19
+
20
+ theorem lower_map (f : α → β) (xs : Array α) (key : β → ℤ) (r : ℤ) (k : ℕ) :
21
+ lower (xs.map f) key r k = lower xs (fun x => key (f x)) r k := by
22
+ unfold lower
23
+ apply search_lo_congr Array.size_map
24
+ intro i j hij
25
+ simp only [Array.getElem_map, hij]
26
+
27
+ theorem upper_map (f : α → β) (xs : Array α) (key : β → ℤ) (r : ℤ) (k : ℕ) :
28
+ upper (xs.map f) key r k = upper xs (fun x => key (f x)) r k := by
29
+ unfold upper
30
+ apply search_lo_congr Array.size_map
31
+ intro i j hij
32
+ simp only [Array.getElem_map, hij]
33
+
34
+ theorem range_map (f : α → β) (xs : Array α) (key : β → ℤ) (r : ℤ) (k : ℕ)
35
+ (hs : Monotone (fun i : Fin xs.size => key (f xs[i.val])))
36
+ (ht : Monotone (fun i : Fin (xs.map f).size => key (xs.map f)[i.val]))
37
+ (hk : xs.size < 2 ^ k) (hk' : (xs.map f).size < 2 ^ k) :
38
+ SliceCursor.mapRange f xs (range xs (fun x => key (f x)) r k hs hk) =
39
+ range (xs.map f) key r k ht hk' := by
40
+ simp only [SliceCursor.mapRange, range, lower_map, upper_map]
41
+
42
+ end BinarySlice
43
+ namespace SliceModular
44
+
45
+ variable {α β : Type*}
46
+
47
+ theorem forward_map (f : α → β) (xs : Array α) (rr : SliceCursor.Range xs.size)
48
+ (key : β → ℤ) (P r : ℤ) (k : ℕ) :
49
+ SliceCursor.mapState f xs (forward xs rr (fun x => key (f x)) P r k) =
50
+ forward (xs.map f) (SliceCursor.mapRange f xs rr) key P r k := by
51
+ by_cases h : 0 < rr.length
52
+ · have : NeZero rr.length := ⟨by omega⟩
53
+ rw [forward, dite_eq_left h, forward, dite_eq_left (show 0 < (SliceCursor.mapRange f xs rr).length from h)]
54
+ simp only [SliceCursor.mapState, SliceCursor.mapRange,
55
+ ModularCursor.forwardStart, SliceCursor.values, Array.getElem_map]
56
+ rfl
57
+ · rw [forward, dite_eq_right h, forward, dite_eq_right (show ¬ 0 < (SliceCursor.mapRange f xs rr).length from h)]
58
+ rfl
59
+
60
+ theorem reverse_map (f : α → β) (xs : Array α) (rr : SliceCursor.Range xs.size)
61
+ (key : β → ℤ) (r : ℤ) (k : ℕ) :
62
+ SliceCursor.mapState f xs (reverse xs rr (fun x => key (f x)) r k) =
63
+ reverse (xs.map f) (SliceCursor.mapRange f xs rr) key r k := by
64
+ by_cases h : 0 < rr.length
65
+ · have : NeZero rr.length := ⟨by omega⟩
66
+ rw [reverse, dite_eq_left h, reverse, dite_eq_left (show 0 < (SliceCursor.mapRange f xs rr).length from h)]
67
+ simp only [SliceCursor.mapState, SliceCursor.mapRange,
68
+ ModularCursor.reverseStart, SliceCursor.values, Array.getElem_map]
69
+ rfl
70
+ · rw [reverse, dite_eq_right h, reverse, dite_eq_right (show ¬ 0 < (SliceCursor.mapRange f xs rr).length from h)]
71
+ rfl
72
+
73
+ end SliceModular
74
+ namespace FilteredRow
75
+
76
+ variable {α β γ δ : Type*}
77
+
78
+ theorem forward_map (f : α → γ) (g : β → δ) (xs : Array β)
79
+ (wl : γ → ℤ) (wr : δ → ℤ) (p P c : ℤ) (k : ℕ)
80
+ (hs : PrimarySorted xs (fun y => wr (g y)) p)
81
+ (ht : PrimarySorted (xs.map g) wr p)
82
+ (hk : xs.size < 2 ^ k) (hk' : (xs.map g).size < 2 ^ k) (x : α) :
83
+ PairCursor.mapState f g xs
84
+ (forward xs (fun y => wl (f y)) (fun y => wr (g y)) p P c k hs hk x) =
85
+ forward (xs.map g) wl wr p P c k ht hk' (f x) := by
86
+ simp only [forward, PairCursor.mapState, range]
87
+ congr 1
88
+ rw [SliceModular.forward_map g xs _ (fun y => wr y % P) P (wl (f x) % P) k]
89
+ congr 1
90
+ exact BinarySlice.range_map g xs (fun y => wr y % p) _ k hs ht hk hk'
91
+
92
+ theorem reverse_map (f : α → γ) (g : β → δ) (xs : Array β)
93
+ (wl : γ → ℤ) (wr : δ → ℤ) (p P c v : ℤ) (k : ℕ)
94
+ (hs : PrimarySorted xs (fun y => wr (g y)) p)
95
+ (ht : PrimarySorted (xs.map g) wr p)
96
+ (hk : xs.size < 2 ^ k) (hk' : (xs.map g).size < 2 ^ k) (x : α) :
97
+ PairCursor.mapState f g xs
98
+ (reverse xs (fun y => wl (f y)) (fun y => wr (g y)) p P c v k hs hk x) =
99
+ reverse (xs.map g) wl wr p P c v k ht hk' (f x) := by
100
+ simp only [reverse, PairCursor.mapState, range]
101
+ congr 1
102
+ rw [SliceModular.reverse_map g xs _ (fun y => wr y % P) ((v - wl (f x)) % P) k]
103
+ congr 1
104
+ exact BinarySlice.range_map g xs (fun y => wr y % p) _ k hs ht hk hk'
105
+
106
+ end FilteredRow
107
+ namespace FilteredStream
108
+
109
+ variable {α β γ δ : Type*}
110
+
111
+ theorem key_map (f : α → γ) (g : β → δ) (wl : γ → ℤ) (wr : δ → ℤ)
112
+ (P : ℤ) (mode : Mode) (x : α × β) :
113
+ key (fun y => wl (f y)) (fun y => wr (g y)) P mode x =
114
+ key wl wr P mode (Prod.map f g x) := by
115
+ cases mode <;> rfl
116
+
117
+ theorem row_map (f : α → γ) (g : β → δ) (right : Array β)
118
+ (wl : γ → ℤ) (wr : δ → ℤ) (p P c : ℤ)
119
+ (hs : FilteredRow.PrimarySorted right (fun y => wr (g y)) p)
120
+ (ht : FilteredRow.PrimarySorted (right.map g) wr p) (mode : Mode) (x : α) :
121
+ PairCursor.mapState f g right
122
+ (row right (fun y => wl (f y)) (fun y => wr (g y)) p P c hs mode x) =
123
+ row (right.map g) wl wr p P c ht mode (f x) := by
124
+ cases mode with
125
+ | direct =>
126
+ simpa only [row, Array.size_map] using
127
+ FilteredRow.forward_map f g right wl wr p P c (steps right.size) hs ht
128
+ (steps_sufficient right.size) (by simpa using steps_sufficient right.size) x
129
+ | complementary v =>
130
+ simpa only [row, Array.size_map] using
131
+ FilteredRow.reverse_map f g right wl wr p P c v (steps right.size) hs ht
132
+ (steps_sufficient right.size) (by simpa using steps_sufficient right.size) x
133
+
134
+ theorem rowArray_map (f : α → γ) (g : β → δ) (left : Array α) (right : Array β)
135
+ (wl : γ → ℤ) (wr : δ → ℤ) (p P c : ℤ)
136
+ (hs : FilteredRow.PrimarySorted right (fun y => wr (g y)) p)
137
+ (ht : FilteredRow.PrimarySorted (right.map g) wr p) (mode : Mode) :
138
+ (rowArray left right (fun y => wl (f y)) (fun y => wr (g y)) p P c hs mode).map
139
+ (PairCursor.mapState f g right) =
140
+ rowArray (left.map f) (right.map g) wl wr p P c ht mode := by
141
+ apply Array.toList_inj.mp
142
+ simp only [rowArray, Array.toList_map, List.map_map]
143
+ congr 1
144
+ funext x
145
+ exact row_map f g right wl wr p P c hs ht mode x
146
+
147
+ theorem initial_tree_map (f : α → γ) (g : β → δ) (left : Array α) (right : Array β)
148
+ (wl : γ → ℤ) (wr : δ → ℤ) (p P c : ℤ)
149
+ (hs : FilteredRow.PrimarySorted right (fun y => wr (g y)) p)
150
+ (ht : FilteredRow.PrimarySorted (right.map g) wr p) (mode : Mode) (d : ℕ) :
151
+ Tournament.map (RowMerge.mapFront (Prod.map f g) (mapCursor f g right))
152
+ (RowMerge.start (key (fun y => wl (f y)) (fun y => wr (g y)) P mode)
153
+ (read right)
154
+ (PaddedRows.rows (rowArray left right (fun y => wl (f y))
155
+ (fun y => wr (g y)) p P c hs mode) d)) =
156
+ RowMerge.start (key wl wr P mode) (read (right.map g))
157
+ (PaddedRows.rows (rowArray (left.map f) (right.map g) wl wr p P c ht mode) d) := by
158
+ have he : key (fun y => wl (f y)) (fun y => wr (g y)) P mode =
159
+ (fun x => key wl wr P mode (Prod.map f g x)) := by cases mode <;> rfl
160
+ rw [he, RowMerge.start_map (Prod.map f g) (mapCursor f g right)
161
+ (key wl wr P mode) (read right) (read (right.map g)) (read_map f g right)]
162
+ congr 1
163
+ funext path
164
+ change (PaddedRows.rows _ d path).map (PairCursor.mapState f g right) = _
165
+ rw [PaddedRows.rows_map, rowArray_map f g left right wl wr p P c hs ht mode]
166
+
167
+ end FilteredStream
168
+
169
+ end LowSpaceSubsetSum
170
+
171
+ end OAI
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/ReaderMap.lean ADDED
@@ -0,0 +1,363 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import OAI.Combinatorics.LowSpaceSubsetSum.Representation.RepresentationStoredRecords
2
+
3
+ namespace OAI
4
+
5
+ /-! # Semantic maps for the mutable reader structures
6
+
7
+ Mapping records preserves the tournament paths and all cursor coordinates.
8
+ Immutable backing arrays are mapped once; they are not copied by a read.
9
+ -/
10
+
11
+ namespace LowSpaceSubsetSum
12
+
13
+ namespace Tournament
14
+
15
+ variable {α β : Type*}
16
+
17
+ def map (f : α → β) : {d : ℕ} → Tree α d → Tree β d
18
+ | 0, .leaf v => .leaf (v.map f)
19
+ | _d + 1, .node w l r => .node (w.map f) (map f l) (map f r)
20
+
21
+ @[simp] theorem winner_map (f : α → β) {d : ℕ} (t : Tree α d) :
22
+ winner (map f t) = (winner t).map f := by cases t <;> rfl
23
+
24
+ @[simp] theorem nodes_map (f : α → β) {d : ℕ} (t : Tree α d) :
25
+ nodes (map f t) = nodes t := by
26
+ induction t with
27
+ | leaf _ => rfl
28
+ | node _ _ _ ihl ihr => simp only [map, nodes, ihl, ihr]
29
+
30
+ theorem pick_map (f : α → β) (key : β → ℤ) (a b : Option α) :
31
+ (pick (fun x => key (f x)) a b).map f = pick key (a.map f) (b.map f) := by
32
+ cases a <;> cases b <;> simp only [pick, Option.map_none, Option.map_some]
33
+ split <;> rfl
34
+
35
+ theorem node_map (f : α → β) (key : β → ℤ) {d : ℕ} (l r : Tree α d) :
36
+ map f (node (fun x => key (f x)) l r) = node key (map f l) (map f r) := by
37
+ simp only [node, map, pick_map, winner_map]
38
+
39
+ theorem valid_map (f : α → β) (key : β → ℤ) {d : ℕ} (t : Tree α d)
40
+ (h : Valid (fun x => key (f x)) t) : Valid key (map f t) := by
41
+ induction t with
42
+ | leaf _ => trivial
43
+ | node w l r ihl ihr =>
44
+ refine ⟨?_, ihl h.2.1, ihr h.2.2⟩
45
+ rw [h.1, pick_map, winner_map, winner_map]
46
+
47
+ theorem lookup_map (f : α → β) {d : ℕ} (t : Tree α d) (p : Fin d → Bool) :
48
+ lookup (map f t) p = (lookup t p).map f := by
49
+ induction t with
50
+ | leaf _ => rfl
51
+ | node _ _ _ ihl ihr =>
52
+ simp only [map, lookup]
53
+ split <;> simp only [ihl, ihr]
54
+
55
+ theorem replace_map (f : α → β) (key : β → ℤ) {d : ℕ} (t : Tree α d)
56
+ (p : Fin d → Bool) (v : Option α) :
57
+ map f (replace (fun x => key (f x)) t p v) = replace key (map f t) p (v.map f) := by
58
+ induction t with
59
+ | leaf _ => rfl
60
+ | node _ _ _ ihl ihr =>
61
+ simp only [map, replace]
62
+ split <;> simp only [node_map, ihl, ihr]
63
+
64
+ theorem build_map (f : α → β) (key : β → ℤ) (d : ℕ)
65
+ (front : (Fin d → Bool) → Option α) :
66
+ map f (build (fun x => key (f x)) d front) =
67
+ build key d (fun p => (front p).map f) := by
68
+ induction d with
69
+ | zero => rfl
70
+ | succ d ih => simp only [build, node_map, ih]
71
+
72
+ end Tournament
73
+
74
+ namespace CyclicCursor
75
+
76
+ variable {α β : Type*} {n : ℕ} [NeZero n]
77
+
78
+ theorem trace_map (f : α → β) (a : Fin n → α) (k : ℕ) (c : State n) :
79
+ (trace a k c).map f = trace (fun i => f (a i)) k c := by
80
+ induction k generalizing c with
81
+ | zero => rfl
82
+ | succ k ih =>
83
+ simp only [trace]
84
+ split <;> simp only [List.map_nil, List.map_cons, ih]
85
+
86
+ end CyclicCursor
87
+
88
+ namespace SliceCursor
89
+
90
+ variable {α β : Type*}
91
+
92
+ def mapRange (f : α → β) (xs : Array α) (r : Range xs.size) : Range (xs.map f).size :=
93
+ ⟨r.lo, r.length, by simpa using r.bounded⟩
94
+
95
+ def mapState (f : α → β) (xs : Array α) (s : State xs.size) : State (xs.map f).size :=
96
+ ⟨mapRange f xs s.range, s.cursor⟩
97
+
98
+ theorem values_map (f : α → β) (xs : Array α) (r : Range xs.size) (i : Fin r.length) :
99
+ values (xs.map f) (mapRange f xs r) i = f (values xs r i) := by
100
+ simp only [values, mapRange, Array.getElem_map]
101
+
102
+ theorem next_map (f : α → β) (xs : Array α) (s : State xs.size) :
103
+ (next xs s).map (fun z => (f z.1, mapState f xs z.2)) =
104
+ next (xs.map f) (mapState f xs s) := by
105
+ cases h : s.cursor with
106
+ | none => simp only [next, mapState, h, Option.map_none]
107
+ | some c =>
108
+ simp only [next, mapState, h]
109
+ split <;> simp only [Option.map_none, Option.map_some, values_map]
110
+ rfl
111
+
112
+ theorem output_map (f : α → β) (xs : Array α) (s : State xs.size) :
113
+ (output xs s).map f = output (xs.map f) (mapState f xs s) := by
114
+ cases h : s.cursor with
115
+ | none => simp only [output, mapState, h, List.map_nil]
116
+ | some c =>
117
+ have : NeZero s.range.length := ⟨by have := c.position.isLt; omega⟩
118
+ simp only [output, mapState, h, CyclicCursor.trace_map]
119
+ congr 1
120
+ funext i
121
+ exact (values_map f xs s.range i).symm
122
+
123
+ end SliceCursor
124
+
125
+ namespace PairCursor
126
+
127
+ variable {α β γ δ : Type*}
128
+
129
+ def mapState (f : α → γ) (g : β → δ) (xs : Array β) (s : State α xs.size) :
130
+ State γ (xs.map g).size := ⟨f s.left, SliceCursor.mapState g xs s.cursor⟩
131
+
132
+ theorem next_map (f : α → γ) (g : β → δ) (xs : Array β) (s : State α xs.size) :
133
+ (next xs s).map (fun z => (Prod.map f g z.1, mapState f g xs z.2)) =
134
+ next (xs.map g) (mapState f g xs s) := by
135
+ have h := SliceCursor.next_map g xs s.cursor
136
+ simp only [next, mapState]
137
+ rw [← h]
138
+ simp only [Option.map_map]
139
+ rfl
140
+
141
+ theorem output_map (f : α → γ) (g : β → δ) (xs : Array β) (s : State α xs.size) :
142
+ (output xs s).map (Prod.map f g) = output (xs.map g) (mapState f g xs s) := by
143
+ change ((SliceCursor.output xs s.cursor).map (fun y => (s.left, y))).map (Prod.map f g) =
144
+ (SliceCursor.output (xs.map g) (SliceCursor.mapState g xs s.cursor)).map
145
+ (fun y => (f s.left, y))
146
+ rw [← SliceCursor.output_map g xs s.cursor]
147
+ simp only [List.map_map]
148
+ rfl
149
+
150
+ end PairCursor
151
+
152
+ namespace FilteredStream
153
+
154
+ variable {α β γ δ : Type*}
155
+
156
+ def mapCursor (f : α → γ) (g : β → δ) (xs : Array β) :
157
+ Cursor (α := α) xs → Cursor (α := γ) (xs.map g) :=
158
+ Option.map (PairCursor.mapState f g xs)
159
+
160
+ theorem read_map (f : α → γ) (g : β → δ) (xs : Array β) (s : Cursor (α := α) xs) :
161
+ (read xs s).map (fun z => (Prod.map f g z.1, mapCursor f g xs z.2)) =
162
+ read (xs.map g) (mapCursor f g xs s) := by
163
+ cases s with
164
+ | none => rfl
165
+ | some s =>
166
+ simp only [read, PaddedRows.next, mapCursor, Option.map_some]
167
+ rw [← PairCursor.next_map f g xs s]
168
+ simp only [Option.map_map]
169
+ rfl
170
+
171
+ theorem view_map (f : α → γ) (g : β → δ) (xs : Array β) (s : Cursor (α := α) xs) :
172
+ (view xs s).map (Prod.map f g) = view (xs.map g) (mapCursor f g xs s) := by
173
+ cases s with
174
+ | none => rfl
175
+ | some s => exact PairCursor.output_map f g xs s
176
+
177
+ end FilteredStream
178
+
179
+ namespace PaddedRows
180
+
181
+ variable {α β : Type*}
182
+
183
+ theorem rows_map (f : α → β) (xs : Array α) (d : ℕ) (p : RowMerge.Path d) :
184
+ (rows xs d p).map f = rows (xs.map f) d p := by
185
+ simp only [rows, Array.size_map]
186
+ split <;> simp only [Option.map_some, Option.map_none, Array.getElem_map]
187
+
188
+ end PaddedRows
189
+
190
+ namespace RowMerge
191
+
192
+ variable {α β σ τ : Type*} {d : ℕ}
193
+
194
+ def mapFront (f : α → β) (g : σ → τ) (x : Front d α σ) : Front d β τ :=
195
+ ⟨x.row, f x.value, g x.after⟩
196
+
197
+ theorem front_map (f : α → β) (g : σ → τ)
198
+ (readA : σ → Option (α × σ)) (readB : τ → Option (β × τ))
199
+ (hr : ∀ s, (readA s).map (fun z => (f z.1, g z.2)) = readB (g s))
200
+ (p : Path d) (s : σ) :
201
+ (front readA p s).map (mapFront f g) = front readB p (g s) := by
202
+ unfold front
203
+ rw [← hr]
204
+ simp only [Option.map_map]
205
+ rfl
206
+
207
+ theorem start_map (f : α → β) (g : σ → τ) (key : β → ℤ)
208
+ (readA : σ → Option (α × σ)) (readB : τ → Option (β × τ))
209
+ (hr : ∀ s, (readA s).map (fun z => (f z.1, g z.2)) = readB (g s))
210
+ (rows : Path d → σ) :
211
+ Tournament.map (mapFront f g) (start (fun x => key (f x)) readA rows) =
212
+ start key readB (fun p => g (rows p)) := by
213
+ unfold start
214
+ change Tournament.map (mapFront f g)
215
+ (Tournament.build (fun x => (fun y : Front d β τ => key y.value) (mapFront f g x))
216
+ d (fun p => front readA p (rows p))) = _
217
+ rw [Tournament.build_map (mapFront f g) (fun y : Front d β τ => key y.value) d
218
+ (fun p => front readA p (rows p))]
219
+ congr 1
220
+ funext p
221
+ exact front_map f g readA readB hr p (rows p)
222
+
223
+ theorem advance_map (f : α → β) (g : σ → τ) (key : β → ℤ)
224
+ (readA : σ → Option (α × σ)) (readB : τ → Option (β × τ))
225
+ (hr : ∀ s, (readA s).map (fun z => (f z.1, g z.2)) = readB (g s))
226
+ (t : Tournament.Tree (Front d α σ) d) :
227
+ (advance (fun x => key (f x)) readA t).map
228
+ (fun z => (f z.1, Tournament.map (mapFront f g) z.2)) =
229
+ advance key readB (Tournament.map (mapFront f g) t) := by
230
+ simp only [advance, Tournament.winner_map]
231
+ cases h : Tournament.winner t with
232
+ | none => rfl
233
+ | some x =>
234
+ simp only [Option.map_some]
235
+ congr 1
236
+ apply Prod.ext
237
+ · rfl
238
+ change Tournament.map (mapFront f g)
239
+ (Tournament.replace (fun y => key (mapFront f g y).value) t x.row
240
+ (front readA x.row x.after)) =
241
+ Tournament.replace (fun y => key y.value) (Tournament.map (mapFront f g) t)
242
+ x.row (front readB x.row (g x.after))
243
+ rw [Tournament.replace_map (mapFront f g) (fun y : Front d β τ => key y.value)
244
+ t x.row (front readA x.row x.after), front_map f g readA readB hr]
245
+
246
+ theorem aligned_map (f : α → β) (g : σ → τ)
247
+ (t : Tournament.Tree (Front d α σ) d) (h : Aligned t) :
248
+ Aligned (Tournament.map (mapFront f g) t) := by
249
+ intro p y hy
250
+ rw [Tournament.lookup_map] at hy
251
+ obtain ⟨x, hx, he⟩ := Option.map_eq_some_iff.mp hy
252
+ rw [← he]
253
+ exact h p x hx
254
+
255
+ theorem remaining_map (f : α → β) (g : σ → τ)
256
+ (viewA : σ → List α) (viewB : τ → List β)
257
+ (hv : ∀ s, (viewA s).map f = viewB (g s))
258
+ (t : Tournament.Tree (Front d α σ) d) (p : Path d) :
259
+ remaining viewB (Tournament.map (mapFront f g) t) p = (remaining viewA t p).map f := by
260
+ unfold remaining
261
+ rw [Tournament.lookup_map]
262
+ cases ht : Tournament.lookup t p with
263
+ | none => rfl
264
+ | some x => simp only [Option.map_some, mapFront, List.map_cons, hv]
265
+
266
+ theorem rowsSorted_map (f : α → β) (g : σ → τ) (key : β → ℤ)
267
+ (viewA : σ → List α) (viewB : τ → List β)
268
+ (hv : ∀ s, (viewA s).map f = viewB (g s))
269
+ (t : Tournament.Tree (Front d α σ) d) (h : RowsSorted (fun x => key (f x)) viewA t) :
270
+ RowsSorted key viewB (Tournament.map (mapFront f g) t) := by
271
+ intro p
272
+ rw [remaining_map f g viewA viewB hv, List.pairwise_map]
273
+ exact h p
274
+
275
+ theorem potential_map (f : α → β) (g : σ → τ)
276
+ (viewA : σ → List α) (viewB : τ → List β)
277
+ (hv : ∀ s, (viewA s).map f = viewB (g s))
278
+ (t : Tournament.Tree (Front d α σ) d) :
279
+ potential viewB (Tournament.map (mapFront f g) t) = potential viewA t := by
280
+ unfold potential
281
+ apply Finset.sum_congr rfl
282
+ intro p _
283
+ rw [remaining_map f g viewA viewB hv, List.length_map]
284
+
285
+ theorem trace_map (f : α → β) (g : σ → τ) (key : β → ℤ)
286
+ (readA : σ → Option (α × σ)) (readB : τ → Option (β × τ))
287
+ (hr : ∀ s, (readA s).map (fun z => (f z.1, g z.2)) = readB (g s))
288
+ (k : ℕ) (t : Tournament.Tree (Front d α σ) d) :
289
+ (trace (fun x => key (f x)) readA k t).map f =
290
+ trace key readB k (Tournament.map (mapFront f g) t) := by
291
+ induction k generalizing t with
292
+ | zero => rfl
293
+ | succ k ih =>
294
+ have h := advance_map f g key readA readB hr t
295
+ cases ha : advance (fun x => key (f x)) readA t with
296
+ | none =>
297
+ have hb : advance key readB (Tournament.map (mapFront f g) t) = none := by
298
+ simpa only [ha, Option.map_none] using h.symm
299
+ simp only [trace, ha, hb, List.map_nil]
300
+ | some z =>
301
+ obtain ⟨a, t'⟩ := z
302
+ have hb : advance key readB (Tournament.map (mapFront f g) t) =
303
+ some (f a, Tournament.map (mapFront f g) t') := by
304
+ simpa only [ha, Option.map_some] using h.symm
305
+ simp only [trace, ha, hb, List.map_cons, ih]
306
+
307
+ end RowMerge
308
+
309
+ namespace MergedReader
310
+
311
+ variable {α β σ τ : Type*} {d : ℕ}
312
+
313
+ def mapState (f : α → β) (g : σ → τ) (key : β → ℤ)
314
+ (viewA : σ → List α) (viewB : τ → List β)
315
+ (hv : ∀ s, (viewA s).map f = viewB (g s))
316
+ (s : State (fun x => key (f x)) viewA d) : State key viewB d :=
317
+ ⟨Tournament.map (RowMerge.mapFront f g) s.tree,
318
+ Tournament.valid_map (RowMerge.mapFront f g) (fun x => key x.value) s.tree s.valid,
319
+ RowMerge.aligned_map f g s.tree s.aligned,
320
+ RowMerge.rowsSorted_map f g key viewA viewB hv s.tree s.sorted⟩
321
+
322
+ theorem next_map (f : α → β) (g : σ → τ) (key : β → ℤ)
323
+ (readA : σ → Option (α × σ)) (readB : τ → Option (β × τ))
324
+ (hr : ∀ s, (readA s).map (fun z => (f z.1, g z.2)) = readB (g s))
325
+ (viewA : σ → List α) (viewB : τ → List β)
326
+ (hv : ∀ s, (viewA s).map f = viewB (g s))
327
+ (ha : RowMerge.IsReader readA viewA) (hb : RowMerge.IsReader readB viewB)
328
+ (s : State (fun x => key (f x)) viewA d) :
329
+ (next (fun x => key (f x)) readA viewA ha s).map
330
+ (fun z => (f z.1, mapState f g key viewA viewB hv z.2)) =
331
+ next key readB viewB hb (mapState f g key viewA viewB hv s) := by
332
+ have h := RowMerge.advance_map f g key readA readB hr s.tree
333
+ cases he : RowMerge.advance (fun x => key (f x)) readA s.tree with
334
+ | none =>
335
+ have h' : RowMerge.advance key readB (Tournament.map (RowMerge.mapFront f g) s.tree) = none := by
336
+ simpa only [he, Option.map_none] using h.symm
337
+ rw [next_none _ _ _ _ _ he, next_none _ _ _ _ _ h']
338
+ rfl
339
+ | some z =>
340
+ obtain ⟨a, t⟩ := z
341
+ have h' : RowMerge.advance key readB (Tournament.map (RowMerge.mapFront f g) s.tree) =
342
+ some (f a, Tournament.map (RowMerge.mapFront f g) t) := by
343
+ simpa only [he, Option.map_some] using h.symm
344
+ rw [next_some _ _ _ _ _ he, next_some _ _ _ _ _ h']
345
+ rfl
346
+
347
+ theorem output_map (f : α → β) (g : σ → τ) (key : β → ℤ)
348
+ (readA : σ → Option (α × σ)) (readB : τ → Option (β × τ))
349
+ (hr : ∀ s, (readA s).map (fun z => (f z.1, g z.2)) = readB (g s))
350
+ (viewA : σ → List α) (viewB : τ → List β)
351
+ (hv : ∀ s, (viewA s).map f = viewB (g s))
352
+ (s : State (fun x => key (f x)) viewA d) :
353
+ (output (fun x => key (f x)) readA viewA s).map f =
354
+ output key readB viewB (mapState f g key viewA viewB hv s) := by
355
+ unfold output
356
+ rw [show RowMerge.potential viewB (mapState f g key viewA viewB hv s).tree =
357
+ RowMerge.potential viewA s.tree from RowMerge.potential_map f g viewA viewB hv s.tree]
358
+ exact RowMerge.trace_map f g key readA readB hr _ _
359
+
360
+ end MergedReader
361
+ end LowSpaceSubsetSum
362
+
363
+ end OAI
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/RecordedDictionary.lean ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import OAI.Combinatorics.LowSpaceSubsetSum.Streams.DictionaryPrefixes
2
+ import OAI.Combinatorics.LowSpaceSubsetSum.Streams.DictionaryProvenance
3
+ import OAI.Combinatorics.LowSpaceSubsetSum.Search.StoppedStreamJoin
4
+
5
+ namespace OAI
6
+
7
+ /-! # Bounded dictionaries with an actual array of retained records -/
8
+
9
+ namespace LowSpaceSubsetSum.RecordedDictionary
10
+
11
+ universe u
12
+ variable {α : Type u}
13
+
14
+ structure State (α : Type u) where
15
+ keys : BinaryTrie.BuildResult
16
+ records : Array α
17
+
18
+ def empty : State α := ⟨⟨.empty, false, 0⟩, #[]⟩
19
+
20
+ /-- The first rejected record is retained, as is its newly allocated trie key.
21
+ Further callbacks freeze both structures. -/
22
+ def feed (C : ℕ) (encode : α → List Bool) (x : α) (r : State α) : State α :=
23
+ ⟨BinaryTrie.feed C (encode x) r.keys,
24
+ if r.keys.overflow || BinaryTrie.contains r.keys.tree (encode x)
25
+ then r.records else r.records.push x⟩
26
+
27
+ @[simp] theorem feed_keys (C : ℕ) (encode : α → List Bool) (x : α) (r : State α) :
28
+ (feed C encode x r).keys = BinaryTrie.feed C (encode x) r.keys := rfl
29
+
30
+ structure Invariant (C width : ℕ) (encode : α → List Bool) (r : State α) : Prop where
31
+ safe : BinaryTrie.Safe C width r.keys
32
+ keys_eq : BinaryTrie.keySet r.keys.tree = (r.records.toList.map encode).toFinset
33
+ size_eq : r.records.size = BinaryTrie.entries r.keys.tree
34
+
35
+ theorem empty_invariant (C width : ℕ) (encode : α → List Bool) :
36
+ Invariant C width encode empty := by
37
+ exact ⟨BinaryTrie.empty_safe C width, rfl, rfl⟩
38
+
39
+ theorem feed_invariant {C width : ℕ} {encode : α → List Bool} {r : State α}
40
+ (hr : Invariant C width encode r) (x : α) (hx : (encode x).length = width) :
41
+ Invariant C width encode (feed C encode x r) := by
42
+ refine ⟨BinaryTrie.feed_safe hr.safe (encode x) hx, ?_, ?_⟩
43
+ · by_cases ho : r.keys.overflow = true
44
+ · simpa only [feed, ho, Bool.true_or, ↓reduceIte,
45
+ BinaryTrie.feed_frozen C (encode x) r.keys ho] using hr.keys_eq
46
+ have hoc : r.keys.overflow = false := Bool.eq_false_iff.mpr ho
47
+ by_cases hd : BinaryTrie.contains r.keys.tree (encode x) = true
48
+ · simpa only [feed, hoc, hd, Bool.false_or, ↓reduceIte,
49
+ BinaryTrie.feed, Bool.false_eq_true, BinaryTrie.tick] using hr.keys_eq
50
+ have hdc : BinaryTrie.contains r.keys.tree (encode x) = false := Bool.eq_false_iff.mpr hd
51
+ simp only [feed, hoc, hdc, Bool.false_or, Bool.false_eq_true, ↓reduceIte,
52
+ BinaryTrie.feed, Array.toList_push, List.map_append, List.map_cons,
53
+ List.map_nil, List.toFinset_append, List.toFinset_cons, List.toFinset_nil]
54
+ rw [BinaryTrie.keySet_insert hr.safe.hasWidth hx, hr.keys_eq]
55
+ ext q
56
+ simp
57
+ · by_cases ho : r.keys.overflow = true
58
+ · simpa only [feed, ho, Bool.true_or, ↓reduceIte,
59
+ BinaryTrie.feed_frozen C (encode x) r.keys ho] using hr.size_eq
60
+ have hoc : r.keys.overflow = false := Bool.eq_false_iff.mpr ho
61
+ by_cases hd : BinaryTrie.contains r.keys.tree (encode x) = true
62
+ · simpa only [feed, hoc, hd, Bool.false_or, ↓reduceIte,
63
+ BinaryTrie.feed, Bool.false_eq_true, BinaryTrie.tick] using hr.size_eq
64
+ have hdc : BinaryTrie.contains r.keys.tree (encode x) = false := Bool.eq_false_iff.mpr hd
65
+ simp only [feed, hoc, hdc, Bool.false_or, Bool.false_eq_true, ↓reduceIte,
66
+ BinaryTrie.feed, Array.size_push]
67
+ rw [BinaryTrie.entries_insert hr.safe.hasWidth hx, hdc]
68
+ simpa using hr.size_eq
69
+
70
+ /-- Every stopped state stores at most the capacity plus the rejected record. -/
71
+ theorem storage {C width : ℕ} {encode : α → List Bool} {r : State α}
72
+ (hr : Invariant C width encode r) :
73
+ r.records.size ≤ C + 1 ∧ BinaryTrie.nodes r.keys.tree ≤ (width + 1) * (C + 1) := by
74
+ exact ⟨hr.size_eq.trans_le hr.safe.bound,
75
+ (BinaryTrie.nodes_le_width_mul_entries hr.safe.hasWidth hr.safe.compact).trans
76
+ (Nat.mul_le_mul_left _ hr.safe.bound)⟩
77
+
78
+ theorem contains_iff {C width : ℕ} {encode : α → List Bool} {r : State α}
79
+ (hr : Invariant C width encode r) (q : List Bool) :
80
+ BinaryTrie.contains r.keys.tree q = true ↔ ∃ x ∈ r.records.toList, encode x = q := by
81
+ rw [← BinaryTrie.mem_keySet, hr.keys_eq, List.mem_toFinset, List.mem_map]
82
+
83
+ theorem feed_provenance (C : ℕ) (encode : α → List Bool) (x : α) (r : State α)
84
+ (P : α → Prop) (hr : ∀ y ∈ r.records.toList, P y) (hx : P x) :
85
+ ∀ y ∈ (feed C encode x r).records.toList, P y := by
86
+ intro y hy
87
+ simp only [feed] at hy
88
+ split at hy
89
+ · exact hr y hy
90
+ · simp only [Array.toList_push, List.mem_append, List.mem_singleton] at hy
91
+ rcases hy with hy | rfl
92
+ · exact hr y hy
93
+ · exact hx
94
+
95
+ theorem fold_invariant {C width : ℕ} {encode : α → List Bool} {r : State α}
96
+ (hr : Invariant C width encode r) (xs : List α)
97
+ (hw : ∀ x ∈ xs, (encode x).length = width) :
98
+ Invariant C width encode (xs.foldl (fun r x => feed C encode x r) r) := by
99
+ induction xs generalizing r with
100
+ | nil => exact hr
101
+ | cons x xs ih =>
102
+ exact ih (feed_invariant hr x (hw x (by simp))) (fun y hy => hw y (by simp [hy]))
103
+
104
+ theorem fold_keys (C : ℕ) (encode : α → List Bool) (xs : List α) (r : State α) :
105
+ (xs.foldl (fun r x => feed C encode x r) r).keys =
106
+ (xs.map encode).foldl (fun r key => BinaryTrie.feed C key r) r.keys := by
107
+ induction xs generalizing r with
108
+ | nil => rfl
109
+ | cons x xs ih => exact ih (feed C encode x r)
110
+
111
+ /-- A cardinality bound concerns distinct keys, rather than repeated callbacks.
112
+ When it holds, every supplied record has its key retained in the array. -/
113
+ theorem fold_fits {C width : ℕ} (encode : α → List Bool) (xs : List α)
114
+ (U : Finset (List Bool)) (hwidth : ∀ q ∈ U, q.length = width)
115
+ (hcap : U.card ≤ C) (hkeys : ∀ x ∈ xs, encode x ∈ U) :
116
+ let r := xs.foldl (fun r x => feed C encode x r) empty
117
+ r.keys.overflow = false ∧
118
+ ∀ q, (∃ x ∈ r.records.toList, encode x = q) ↔ ∃ x ∈ xs, encode x = q := by
119
+ have hw : ∀ x ∈ xs, (encode x).length = width := fun x hx => hwidth _ (hkeys x hx)
120
+ have hi := fold_invariant (empty_invariant C width encode) xs hw
121
+ have hf := BinaryTrie.fold_fits (r := ⟨.empty, false, 0⟩) rfl
122
+ (width := width) (by trivial) hwidth (by simp [BinaryTrie.keySet]) hcap
123
+ (xs.map encode) (by
124
+ intro q hq
125
+ obtain ⟨x, hx, rfl⟩ := List.mem_map.mp hq
126
+ exact hkeys x hx)
127
+ dsimp only
128
+ refine ⟨?_, ?_⟩
129
+ · rw [fold_keys]
130
+ exact hf.1
131
+ · intro q
132
+ rw [← contains_iff hi q, ← BinaryTrie.mem_keySet, fold_keys]
133
+ dsimp only [empty]
134
+ rw [hf.2.1]
135
+ simp only [BinaryTrie.keySet, Finset.empty_union, List.mem_toFinset, List.mem_map]
136
+
137
+ /-- The option-valued emitter applies local overlap and prefix checks before
138
+ an entry is retained. A rejected tuple consumes no dictionary space. -/
139
+ def callback {β γ : Type*} (C : ℕ) (encode : α → List Bool)
140
+ (emit : β → γ → Option α) (x : β) (y : γ) (r : State α) : State α × Bool :=
141
+ (match emit x y with | none => r | some z => feed C encode z r, false)
142
+
143
+ theorem callback_invariant {β γ : Type*} {C width : ℕ} (encode : α → List Bool)
144
+ (hw : ∀ z, (encode z).length = width) (emit : β → γ → Option α)
145
+ (x : β) (y : γ) (r : State α) (hr : Invariant C width encode r) :
146
+ Invariant C width encode (callback C encode emit x y r).1 := by
147
+ cases h : emit x y with
148
+ | none => simpa only [callback, h] using hr
149
+ | some z => simpa only [callback, h] using feed_invariant hr z (hw z)
150
+
151
+ /-- Array and trie storage are bounded even at incomplete join prefixes. -/
152
+ theorem stopped_invariant {β γ σ₁ σ₂ : Type*} {C width : ℕ}
153
+ (read₁ : σ₁ → Option (β × σ₁)) (key₁ : β → ℤ)
154
+ (read₂ : σ₂ → Option (γ × σ₂)) (key₂ : γ → ℤ)
155
+ (encode : α → List Bool) (hw : ∀ z, (encode z).length = width)
156
+ (emit : β → γ → Option α) (B fuel₁ fuel₂ controlFuel : ℕ) (s₁ : σ₁) (s₂ : σ₂) :
157
+ Invariant C width encode (StreamJoin.stopped read₁ key₁ read₂ key₂
158
+ (callback C encode emit) B fuel₁ fuel₂ controlFuel s₁ s₂ empty).state.user := by
159
+ rw [StreamJoin.stopped_eq]
160
+ exact DictionaryPrefixes.run_preserves read₁ key₁ read₂ key₂ (callback C encode emit)
161
+ (Invariant C width encode) (callback_invariant encode hw emit) B fuel₁ fuel₂ controlFuel
162
+ (StreamJoin.start s₁ s₂ empty) (empty_invariant C width encode)
163
+
164
+ end LowSpaceSubsetSum.RecordedDictionary
165
+
166
+ end OAI
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/RecordedJoin.lean ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import OAI.Combinatorics.LowSpaceSubsetSum.Streams.RecordedDictionary
2
+
3
+ namespace OAI
4
+
5
+ /-! # Exact retained-record semantics for a filtered stream join -/
6
+
7
+ namespace LowSpaceSubsetSum.RecordedDictionary
8
+
9
+ variable {α β γ : Type*}
10
+
11
+ /-- A proof view; the runtime never constructs this Cartesian list. -/
12
+ def matchingRecords (key₁ : β → ℤ) (key₂ : γ → ℤ) (emit : β → γ → Option α)
13
+ (xs : List β) (ys : List γ) : List α :=
14
+ xs.flatMap (fun x => (ys.filter (fun y => decide (key₁ x = key₂ y))).filterMap (emit x))
15
+
16
+ theorem mem_matchingRecords (key₁ : β → ℤ) (key₂ : γ → ℤ) (emit : β → γ → Option α)
17
+ (xs : List β) (ys : List γ) (z : α) :
18
+ z ∈ matchingRecords key₁ key₂ emit xs ys ↔
19
+ ∃ x ∈ xs, ∃ y ∈ ys, key₁ x = key₂ y ∧ emit x y = some z := by
20
+ simp only [matchingRecords, List.mem_flatMap, List.mem_filterMap, List.mem_filter,
21
+ decide_eq_true_eq]
22
+ constructor
23
+ · rintro ⟨x, hx, y, ⟨hy, he⟩, hz⟩
24
+ exact ⟨x, hx, y, hy, he, hz⟩
25
+ · rintro ⟨x, hx, y, hy, he, hz⟩
26
+ exact ⟨x, hx, y, ⟨hy, he⟩, hz⟩
27
+
28
+ theorem matchFold_eq_records (C : ℕ) (encode : α → List Bool)
29
+ (key₁ : β → ℤ) (key₂ : γ → ℤ) (emit : β → γ → Option α)
30
+ (xs : List β) (ys : List γ) (r : State α) :
31
+ MatchFold.run key₁ key₂ (callback C encode emit) xs ys r =
32
+ (matchingRecords key₁ key₂ emit xs ys).foldl (fun r z => feed C encode z r) r := by
33
+ induction xs generalizing r with
34
+ | nil => rfl
35
+ | cons x xs ih =>
36
+ simp only [MatchFold.run, matchingRecords, List.flatMap_cons, List.foldl_append,
37
+ List.foldl_filterMap, callback, ih]
38
+ congr 2
39
+ funext a y
40
+ cases emit x y <;> rfl
41
+
42
+ theorem fold_provenance (C : ℕ) (encode : α → List Bool) (xs : List α) (r : State α)
43
+ (P : α → Prop) (hr : ∀ z ∈ r.records.toList, P z) (hx : ∀ z ∈ xs, P z) :
44
+ ∀ z ∈ (xs.foldl (fun r z => feed C encode z r) r).records.toList, P z := by
45
+ induction xs generalizing r with
46
+ | nil => exact hr
47
+ | cons x xs ih =>
48
+ exact ih (feed C encode x r) (feed_provenance C encode x r P hr (hx x (by simp)))
49
+ (fun y hy => hx y (by simp [hy]))
50
+
51
+ theorem matchFold_fits {C width : ℕ} (encode : α → List Bool)
52
+ (key₁ : β → ℤ) (key₂ : γ → ℤ) (emit : β → γ → Option α)
53
+ (xs : List β) (ys : List γ) (U : Finset (List Bool))
54
+ (hwidth : ∀ q ∈ U, q.length = width) (hcap : U.card ≤ C)
55
+ (hkeys : ∀ x ∈ xs, ∀ y ∈ ys, key₁ x = key₂ y →
56
+ ∀ z, emit x y = some z → encode z ∈ U) :
57
+ let r := MatchFold.run key₁ key₂ (callback C encode emit) xs ys empty
58
+ r.keys.overflow = false ∧ ∀ q,
59
+ (∃ z ∈ r.records.toList, encode z = q) ↔
60
+ ∃ x ∈ xs, ∃ y ∈ ys, key₁ x = key₂ y ∧
61
+ ∃ z, emit x y = some z ∧ encode z = q := by
62
+ rw [matchFold_eq_records]
63
+ have hf := fold_fits (width := width) encode (matchingRecords key₁ key₂ emit xs ys)
64
+ U hwidth hcap (by
65
+ intro z hz
66
+ obtain ⟨x, hx, y, hy, he, hz⟩ := (mem_matchingRecords _ _ _ _ _ _).mp hz
67
+ exact hkeys x hx y hy he z hz)
68
+ refine ⟨hf.1, ?_⟩
69
+ intro q
70
+ rw [hf.2]
71
+ constructor
72
+ · rintro ⟨z, hz, he⟩
73
+ obtain ⟨x, hx, y, hy, hm, hz⟩ := (mem_matchingRecords _ _ _ _ _ _).mp hz
74
+ exact ⟨x, hx, y, hy, hm, z, hz, he⟩
75
+ · rintro ⟨x, hx, y, hy, hm, z, hz, he⟩
76
+ exact ⟨z, (mem_matchingRecords _ _ _ _ _ _).mpr ⟨x, hx, y, hy, hm, hz⟩, he⟩
77
+
78
+ theorem join_eq_records {σ₁ σ₂ : Type*} (C : ℕ) (encode : α → List Bool)
79
+ (read₁ : σ₁ → Option (β × σ₁)) (key₁ : β → ℤ)
80
+ (read₂ : σ₂ → Option (γ × σ₂)) (key₂ : γ → ℤ) (emit : β → γ → Option α)
81
+ (view₁ : σ₁ → List β) (hread₁ : RowMerge.IsReader read₁ view₁)
82
+ (view₂ : σ₂ → List γ) (hread₂ : RowMerge.IsReader read₂ view₂)
83
+ (B fuel₁ fuel₂ controlFuel : ℕ) (s₁ : σ₁) (s₂ : σ₂) (r : State α)
84
+ (hsort₁ : (view₁ s₁).Pairwise (fun x y => key₁ x ≤ key₁ y))
85
+ (hsort₂ : (view₂ s₂).Pairwise (fun x y => key₂ x ≤ key₂ y))
86
+ (hcap₁ : (view₁ s₁).length ≤ fuel₁) (hcap₂ : (view₂ s₂).length ≤ fuel₂)
87
+ (hfuel : (view₁ s₁).length + (view₂ s₂).length < controlFuel) :
88
+ (StreamJoin.stopped read₁ key₁ read₂ key₂ (callback C encode emit)
89
+ B fuel₁ fuel₂ controlFuel s₁ s₂ r).state.user =
90
+ (matchingRecords key₁ key₂ emit (view₁ s₁) (view₂ s₂)).foldl
91
+ (fun r z => feed C encode z r) r := by
92
+ rw [StreamJoin.stopped_eq, StreamJoin.run_complete read₁ key₁ read₂ key₂
93
+ (callback C encode emit) (fun _ _ _ => rfl) view₁ hread₁ view₂ hread₂ B fuel₁ fuel₂
94
+ controlFuel s₁ s₂ r hsort₁ hsort₂ hcap₁ hcap₂ hfuel, matchFold_eq_records]
95
+
96
+ /-- No capacity hypothesis is needed for provenance: overflowing joins retain
97
+ only entries emitted by a matching pair. -/
98
+ theorem join_provenance {σ₁ σ₂ : Type*} (C : ℕ) (encode : α → List Bool)
99
+ (read₁ : σ₁ → Option (β × σ₁)) (key₁ : β → ℤ)
100
+ (read₂ : σ₂ → Option (γ × σ₂)) (key₂ : γ → ℤ) (emit : β → γ → Option α)
101
+ (view₁ : σ₁ → List β) (hread₁ : RowMerge.IsReader read₁ view₁)
102
+ (view₂ : σ₂ → List γ) (hread₂ : RowMerge.IsReader read₂ view₂)
103
+ (B fuel₁ fuel₂ controlFuel : ℕ) (s₁ : σ₁) (s₂ : σ₂)
104
+ (hsort₁ : (view₁ s₁).Pairwise (fun x y => key₁ x ≤ key₁ y))
105
+ (hsort₂ : (view₂ s₂).Pairwise (fun x y => key₂ x ≤ key₂ y))
106
+ (hcap₁ : (view₁ s₁).length ≤ fuel₁) (hcap₂ : (view₂ s₂).length ≤ fuel₂)
107
+ (hfuel : (view₁ s₁).length + (view₂ s₂).length < controlFuel)
108
+ (z : α) (hz : z ∈ (StreamJoin.stopped read₁ key₁ read₂ key₂ (callback C encode emit)
109
+ B fuel₁ fuel₂ controlFuel s₁ s₂ empty).state.user.records.toList) :
110
+ ∃ x ∈ view₁ s₁, ∃ y ∈ view₂ s₂, key₁ x = key₂ y ∧ emit x y = some z := by
111
+ rw [join_eq_records C encode read₁ key₁ read₂ key₂ emit view₁ hread₁ view₂ hread₂
112
+ B fuel₁ fuel₂ controlFuel s₁ s₂ empty hsort₁ hsort₂ hcap₁ hcap₂ hfuel] at hz
113
+ exact (mem_matchingRecords key₁ key₂ emit _ _ z).mp
114
+ (fold_provenance C encode (matchingRecords key₁ key₂ emit (view₁ s₁) (view₂ s₂))
115
+ empty (fun z => z ∈ matchingRecords key₁ key₂ emit (view₁ s₁) (view₂ s₂))
116
+ (by simp [empty]) (fun _ h => h) z hz)
117
+
118
+ end LowSpaceSubsetSum.RecordedDictionary
119
+
120
+ end OAI
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/ResidueFilters.lean ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import OAI.Combinatorics.LowSpaceSubsetSum.Streams.ModularFilters
2
+ import Mathlib.Algebra.BigOperators.Group.Finset.Basic
3
+ import Mathlib.Data.Fintype.Prod
4
+
5
+ namespace OAI
6
+
7
+ /-!
8
+ # Exact counts under uniform low-residue choices
9
+
10
+ Raw occurrence identities and distinct entry keys may be different types.
11
+ Neither is deduplicated here: each supplied finite set is partitioned by its
12
+ residue labels. This is the exact uniform-residue calculation for the counts
13
+ `G`, `J`, and `U` in the resource proof.
14
+ -/
15
+
16
+ namespace LowSpaceSubsetSum
17
+
18
+ open scoped BigOperators
19
+
20
+ variable {α : Type*}
21
+
22
+ def normalizedResidue {p : ℕ} (hp : 0 < p) (x : ℤ) : Fin p :=
23
+ ⟨(x % (p : ℤ)).toNat, by
24
+ have hpZ : (0 : ℤ) < p := by exact_mod_cast hp
25
+ exact (Int.toNat_lt (Int.emod_nonneg _ hpZ.ne')).mpr
26
+ (Int.emod_lt_of_pos _ hpZ)⟩
27
+
28
+ theorem normalizedResidue_eq_iff {p : ℕ} (hp : 0 < p) (x : ℤ) (r : Fin p) :
29
+ normalizedResidue hp x = r ↔ x % (p : ℤ) = r := by
30
+ have hpZ : (0 : ℤ) < p := by exact_mod_cast hp
31
+ have hnonneg := Int.emod_nonneg x hpZ.ne'
32
+ constructor
33
+ · intro h
34
+ have hval := congrArg (fun r : Fin p => (r.val : ℤ)) h
35
+ simpa only [normalizedResidue, Int.toNat_of_nonneg hnonneg] using hval
36
+ · intro h
37
+ apply Fin.ext
38
+ simp only [normalizedResidue]
39
+ rw [h]
40
+ rfl
41
+
42
+ theorem sum_label_fibers {Ω : Type*} [Fintype Ω] [DecidableEq Ω]
43
+ (T : Finset α) (label : α → Ω) :
44
+ ∑ r : Ω, (T.filter fun x => label x = r).card = T.card := by
45
+ exact (Finset.card_eq_sum_card_fiberwise
46
+ (s := T) (t := Finset.univ) (f := label) (by simp)).symm
47
+
48
+ theorem mean_label_fiber {Ω : Type*} [Fintype Ω] [DecidableEq Ω]
49
+ (T : Finset α) (label : α → Ω) :
50
+ (∑ r : Ω, ((T.filter fun x => label x = r).card : ℝ)) / Fintype.card Ω =
51
+ (T.card : ℝ) / Fintype.card Ω := by
52
+ congr 1
53
+ exact_mod_cast sum_label_fibers T label
54
+
55
+ def residueFiltered {p : ℕ} (hp : 0 < p) (T : Finset α) (w : α → ℤ)
56
+ (r : Fin p) : Finset α := T.filter fun x => normalizedResidue hp (w x) = r
57
+
58
+ theorem mean_residueFiltered {p : ℕ} (hp : 0 < p) (T : Finset α) (w : α → ℤ) :
59
+ (∑ r : Fin p, ((residueFiltered hp T w r).card : ℝ)) / p = (T.card : ℝ) / p := by
60
+ simpa only [residueFiltered, Fintype.card_fin] using
61
+ mean_label_fiber T (fun x => normalizedResidue hp (w x))
62
+
63
+ def twiceResidueFiltered {p q : ℕ} (hp : 0 < p) (hq : 0 < q)
64
+ (T : Finset α) (parent child : α → ℤ) (r : Fin p × Fin q) : Finset α :=
65
+ T.filter fun x => normalizedResidue hp (parent x) = r.1 ∧
66
+ normalizedResidue hq (child x) = r.2
67
+
68
+ /-- Each raw four-leaf occurrence passes one and only one parent/first-child
69
+ residue pair. The second child's required residue follows by nesting. -/
70
+ theorem mean_twiceResidueFiltered {p q : ℕ} (hp : 0 < p) (hq : 0 < q)
71
+ (T : Finset α) (parent child : α → ℤ) :
72
+ (∑ r : Fin p × Fin q, ((twiceResidueFiltered hp hq T parent child r).card : ℝ)) /
73
+ (p * q : ℕ) = (T.card : ℝ) / (p * q : ℕ) := by
74
+ simpa only [twiceResidueFiltered, Prod.ext_iff, Fintype.card_prod,
75
+ Fintype.card_fin] using mean_label_fiber T
76
+ (fun x => (normalizedResidue hp (parent x), normalizedResidue hq (child x)))
77
+
78
+ /-- Finite Markov bound for a counted resource. No independence between
79
+ different resources is required when these marginal bounds are combined. -/
80
+ theorem finite_count_markov {Ω : Type*} [Fintype Ω] [DecidableEq Ω] [Nonempty Ω]
81
+ (count : Ω → ℕ) {T : ℝ} (hT : 0 < T) :
82
+ (((Finset.univ.filter fun r => T < (count r : ℝ)).card : ℝ) / Fintype.card Ω) ≤
83
+ ((∑ r : Ω, (count r : ℝ)) / Fintype.card Ω) / T := by
84
+ classical
85
+ have hcard : (0 : ℝ) < Fintype.card Ω := by exact_mod_cast Fintype.card_pos
86
+ have hind : ∀ r : Ω, (if T < (count r : ℝ) then T else 0) ≤ count r := by
87
+ intro r
88
+ split_ifs with h
89
+ · exact h.le
90
+ · exact Nat.cast_nonneg _
91
+ have hsum := Finset.sum_le_sum (s := (Finset.univ : Finset Ω))
92
+ (fun r _ => hind r)
93
+ rw [← Finset.sum_filter] at hsum
94
+ simp only [Finset.sum_const, nsmul_eq_mul] at hsum
95
+ apply (le_div_iff₀ hT).mpr
96
+ rw [div_mul_eq_mul_div]
97
+ exact (div_le_div_iff_of_pos_right hcard).mpr hsum
98
+
99
+ theorem residueFiltered_tail {p : ℕ} (hp : 0 < p) (X : Finset α) (w : α → ℤ)
100
+ {T : ℝ} (hT : 0 < T) :
101
+ (((Finset.univ.filter fun r : Fin p => T < (residueFiltered hp X w r).card).card : ℝ) /
102
+ p) ≤ ((X.card : ℝ) / p) / T := by
103
+ let : Nonempty (Fin p) := ⟨⟨0, hp⟩⟩
104
+ have h := finite_count_markov (fun r => (residueFiltered hp X w r).card) hT
105
+ simpa only [Fintype.card_fin, mean_residueFiltered] using h
106
+
107
+ theorem twiceResidueFiltered_tail {p q : ℕ} (hp : 0 < p) (hq : 0 < q)
108
+ (X : Finset α) (parent child : α → ℤ) {T : ℝ} (hT : 0 < T) :
109
+ (((Finset.univ.filter fun r : Fin p × Fin q =>
110
+ T < (twiceResidueFiltered hp hq X parent child r).card).card : ℝ) /
111
+ (p * q : ℕ)) ≤ ((X.card : ℝ) / (p * q : ℕ)) / T := by
112
+ let : Nonempty (Fin p) := ⟨⟨0, hp⟩⟩
113
+ let : Nonempty (Fin q) := ⟨⟨0, hq⟩⟩
114
+ have h := finite_count_markov
115
+ (fun r => (twiceResidueFiltered hp hq X parent child r).card) hT
116
+ simpa only [Fintype.card_prod, Fintype.card_fin, ← Nat.cast_mul,
117
+ mean_twiceResidueFiltered] using h
118
+
119
+ end LowSpaceSubsetSum
120
+
121
+ end OAI
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/ResidueSort.lean ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import OAI.Combinatorics.LowSpaceSubsetSum.Streams.FilteredRow
2
+ import Mathlib.Data.List.Sort
3
+
4
+ namespace OAI
5
+
6
+ /-! # Concrete lexicographic residue sorting of the shared right array -/
7
+
8
+ namespace LowSpaceSubsetSum
9
+ namespace ResidueSort
10
+
11
+ variable {α : Type*}
12
+
13
+ def relation (w : α → ℤ) (p P : ℤ) (x y : α) : Prop :=
14
+ w x % p < w y % p ∨ w x % p = w y % p ∧ w x % P ≤ w y % P
15
+
16
+ instance (w : α → ℤ) (p P : ℤ) : DecidableRel (relation w p P) :=
17
+ fun _ _ => inferInstanceAs (Decidable (_ ∨ _ ∧ _))
18
+
19
+ theorem transitive (w : α → ℤ) (p P : ℤ) :
20
+ ∀ {x y z}, relation w p P x y → relation w p P y z → relation w p P x z := by
21
+ intro x y z hxy hyz
22
+ dsimp only [relation] at *
23
+ omega
24
+
25
+ theorem total (w : α → ℤ) (p P : ℤ) (x y : α) :
26
+ relation w p P x y ∨ relation w p P y x := by
27
+ dsimp only [relation]
28
+ omega
29
+
30
+ def sort (xs : Array α) (w : α → ℤ) (p P : ℤ) : Array α :=
31
+ (xs.toList.mergeSort (fun x y => decide (relation w p P x y))).toArray
32
+
33
+ theorem permutation (xs : Array α) (w : α → ℤ) (p P : ℤ) :
34
+ (sort xs w p P).toList.Perm xs.toList := by
35
+ simpa only [sort, List.toList_toArray] using
36
+ List.mergeSort_perm xs.toList (fun x y => decide (relation w p P x y))
37
+
38
+ theorem size (xs : Array α) (w : α → ℤ) (p P : ℤ) :
39
+ (sort xs w p P).size = xs.size := by
40
+ have h := (permutation xs w p P).length_eq
41
+ simpa only [Array.length_toList] using h
42
+
43
+ theorem sorted (xs : Array α) (w : α → ℤ) (p P : ℤ) :
44
+ (sort xs w p P).toList.Pairwise (relation w p P) := by
45
+ simpa only [sort, List.toList_toArray, decide_eq_true_eq] using
46
+ List.pairwise_mergeSort (le := fun x y => decide (relation w p P x y))
47
+ (fun x y z hxy hyz => by
48
+ exact decide_eq_true (transitive w p P (of_decide_eq_true hxy) (of_decide_eq_true hyz)))
49
+ (fun x y => by simpa only [Bool.or_eq_true, decide_eq_true_eq] using total w p P x y)
50
+ xs.toList
51
+
52
+ theorem index_order (xs : Array α) (w : α → ℤ) (p P : ℤ)
53
+ (i j : Fin (sort xs w p P).size) (hij : i ≤ j) :
54
+ relation w p P (sort xs w p P)[i.val] (sort xs w p P)[j.val] := by
55
+ rcases lt_or_eq_of_le hij with hlt | heq
56
+ · have h := (sorted xs w p P).rel_getElem_of_lt
57
+ (by simpa only [Array.length_toList] using i.isLt)
58
+ (by simpa only [Array.length_toList] using j.isLt) hlt
59
+ simpa only [Array.getElem_toList] using h
60
+ · subst j
61
+ exact Or.inr ⟨rfl, le_rfl⟩
62
+
63
+ theorem primary (xs : Array α) (w : α → ℤ) (p P : ℤ) :
64
+ FilteredRow.PrimarySorted (sort xs w p P) w p := by
65
+ intro i j hij
66
+ change w (sort xs w p P)[i.val] % p ≤ w (sort xs w p P)[j.val] % p
67
+ have h := index_order xs w p P i j hij
68
+ dsimp only [relation] at h
69
+ omega
70
+
71
+ theorem secondary (xs : Array α) (w : α → ℤ) (p P : ℤ) :
72
+ FilteredRow.SecondarySorted (sort xs w p P) w p P := by
73
+ intro i j hij heq
74
+ have h := index_order xs w p P i j hij
75
+ dsimp only [relation] at h
76
+ omega
77
+
78
+ end ResidueSort
79
+ end LowSpaceSubsetSum
80
+
81
+ end OAI
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/RowMerge.lean ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import OAI.Combinatorics.LowSpaceSubsetSum.Streams.Tournament
2
+ import OAI.Combinatorics.LowSpaceSubsetSum.Streams.CyclicCursor
3
+
4
+ namespace OAI
5
+
6
+ /-!
7
+ # A tournament merge with one current occurrence per row
8
+
9
+ The shared immutable input arrays are parameters of the row reader. Each
10
+ leaf contains a row identifier, its current item, and its cursor after that
11
+ item. Advancing the winning row performs one row read and one tournament
12
+ replacement. The remaining lists below are ghost views used for correctness;
13
+ the merge state stores no pair-product list.
14
+ -/
15
+
16
+ namespace LowSpaceSubsetSum
17
+ namespace RowMerge
18
+
19
+ universe u v
20
+
21
+ variable {α : Type u} {σ : Type v} {d : ℕ}
22
+
23
+ abbrev Path (d : ℕ) := Fin d → Bool
24
+
25
+ structure Front (d : ℕ) (α : Type u) (σ : Type v) where
26
+ row : Path d
27
+ value : α
28
+ after : σ
29
+
30
+ def front (read : σ → Option (α × σ)) (p : Path d) (s : σ) : Option (Front d α σ) :=
31
+ (read s).map (fun z => ⟨p, z.1, z.2⟩)
32
+
33
+ def start (key : α → ℤ) (read : σ → Option (α × σ)) (s : Path d → σ) :
34
+ Tournament.Tree (Front d α σ) d :=
35
+ Tournament.build (fun x => key x.value) d (fun p => front read p (s p))
36
+
37
+ def Aligned (t : Tournament.Tree (Front d α σ) d) : Prop :=
38
+ ∀ p x, Tournament.lookup t p = some x → x.row = p
39
+
40
+ theorem front_row (read : σ → Option (α × σ)) (p : Path d) (s : σ)
41
+ {x : Front d α σ} (hx : front read p s = some x) : x.row = p := by
42
+ cases hr : read s with
43
+ | none => simp [front, hr] at hx
44
+ | some z =>
45
+ have heq : (⟨p, z.1, z.2⟩ : Front d α σ) = x := by simpa [front, hr] using hx
46
+ rw [← heq]
47
+
48
+ theorem start_aligned (key : α → ℤ) (read : σ → Option (α × σ)) (s : Path d → σ) :
49
+ Aligned (start key read s) := by
50
+ intro p x hx
51
+ rw [start, Tournament.lookup_build] at hx
52
+ exact front_row read p (s p) hx
53
+
54
+ theorem start_valid (key : α → ℤ) (read : σ → Option (α × σ)) (s : Path d → σ) :
55
+ Tournament.Valid (fun x => key x.value) (start key read s) :=
56
+ Tournament.build_valid _ _ _
57
+
58
+ def advance (key : α → ℤ) (read : σ → Option (α × σ))
59
+ (t : Tournament.Tree (Front d α σ) d) :
60
+ Option (α × Tournament.Tree (Front d α σ) d) :=
61
+ (Tournament.winner t).map fun x =>
62
+ (x.value, Tournament.replace (fun y => key y.value) t x.row (front read x.row x.after))
63
+
64
+ theorem advance_valid (key : α → ℤ) (read : σ → Option (α × σ))
65
+ (t : Tournament.Tree (Front d α σ) d)
66
+ (ht : Tournament.Valid (fun x => key x.value) t) {a : α}
67
+ {t' : Tournament.Tree (Front d α σ) d} (ha : advance key read t = some (a, t')) :
68
+ Tournament.Valid (fun x => key x.value) t' := by
69
+ cases hw : Tournament.winner t with
70
+ | none => simp [advance, hw] at ha
71
+ | some x =>
72
+ have heq : (x.value, Tournament.replace (fun y => key y.value) t x.row
73
+ (front read x.row x.after)) = (a, t') := by simpa [advance, hw] using ha
74
+ rw [← (Prod.mk.inj heq).2]
75
+ exact Tournament.replace_valid _ t ht _ _
76
+
77
+ theorem advance_aligned (key : α → ℤ) (read : σ → Option (α × σ))
78
+ (t : Tournament.Tree (Front d α σ) d) (ht : Aligned t) {a : α}
79
+ {t' : Tournament.Tree (Front d α σ) d} (ha : advance key read t = some (a, t')) :
80
+ Aligned t' := by
81
+ cases hw : Tournament.winner t with
82
+ | none => simp [advance, hw] at ha
83
+ | some x =>
84
+ have heq : (x.value, Tournament.replace (fun y => key y.value) t x.row
85
+ (front read x.row x.after)) = (a, t') := by simpa [advance, hw] using ha
86
+ rw [← (Prod.mk.inj heq).2]
87
+ intro p y hy
88
+ rw [Tournament.lookup_replace] at hy
89
+ by_cases hp : x.row = p
90
+ · rw [ite_eq_left hp] at hy
91
+ exact (front_row read x.row x.after hy).trans hp
92
+ · rw [ite_eq_right hp] at hy
93
+ exact ht p y hy
94
+
95
+ theorem winner_at_own_row (key : α → ℤ) (t : Tournament.Tree (Front d α σ) d)
96
+ (ht : Tournament.Valid (fun x => key x.value) t) (halign : Aligned t)
97
+ {x : Front d α σ} (hx : Tournament.winner t = some x) :
98
+ Tournament.lookup t x.row = some x := by
99
+ have hm := (Tournament.winner_best (fun x => key x.value) t ht).1 x hx
100
+ obtain ⟨p, hp⟩ := (Tournament.mem_candidates_iff t x).mp hm
101
+ rw [halign p x hp]
102
+ exact hp
103
+
104
+ theorem winner_is_minimum (key : α → ℤ) (t : Tournament.Tree (Front d α σ) d)
105
+ (ht : Tournament.Valid (fun x => key x.value) t) {x : Front d α σ}
106
+ (hx : Tournament.winner t = some x) (p : Path d) {y : Front d α σ}
107
+ (hy : Tournament.lookup t p = some y) : key x.value ≤ key y.value := by
108
+ obtain ⟨w, hw, hwy⟩ := Tournament.winner_le_lookup (fun x => key x.value) t ht p hy
109
+ have h : w = x := Option.some.inj (hw.symm.trans hx)
110
+ simpa [h] using hwy
111
+
112
+ /-- A row reader's finite output law, used only in the correctness proof. -/
113
+ def IsReader (read : σ → Option (α × σ)) (view : σ → List α) : Prop :=
114
+ ∀ s, match read s with
115
+ | none => view s = []
116
+ | some (a, s') => view s = a :: view s'
117
+
118
+ theorem cyclic_next_reader (xs : Array α) [NeZero xs.size] :
119
+ IsReader (CyclicCursor.next xs)
120
+ (fun c => CyclicCursor.trace (fun i : Fin xs.size => xs[i.val]) c.remaining c) := by
121
+ intro c
122
+ cases h : c.remaining with
123
+ | zero => simp [CyclicCursor.next, CyclicCursor.trace, h]
124
+ | succ k =>
125
+ simp [CyclicCursor.next, CyclicCursor.trace, h, CyclicCursor.advance_remaining]
126
+
127
+ def remaining (view : σ → List α) (t : Tournament.Tree (Front d α σ) d)
128
+ (p : Path d) : List α :=
129
+ match Tournament.lookup t p with
130
+ | none => []
131
+ | some x => x.value :: view x.after
132
+
133
+ theorem start_remaining (key : α → ℤ) (read : σ → Option (α × σ))
134
+ (view : σ → List α) (hread : IsReader read view) (s : Path d → σ) (p : Path d) :
135
+ remaining view (start key read s) p = view (s p) := by
136
+ simp only [remaining, start, Tournament.lookup_build, front]
137
+ have hr := hread (s p)
138
+ cases h : read (s p) with
139
+ | none =>
140
+ simp only [h] at hr
141
+ simpa using hr.symm
142
+ | some z =>
143
+ simp only [h] at hr
144
+ simpa using hr.symm
145
+
146
+ theorem replace_remaining (key : α → ℤ) (read : σ → Option (α × σ))
147
+ (view : σ → List α) (hread : IsReader read view)
148
+ (t : Tournament.Tree (Front d α σ) d) (x : Front d α σ) (q : Path d) :
149
+ remaining view (Tournament.replace (fun y => key y.value) t x.row
150
+ (front read x.row x.after)) q =
151
+ if x.row = q then view x.after else remaining view t q := by
152
+ unfold remaining
153
+ rw [Tournament.lookup_replace]
154
+ by_cases hq : x.row = q
155
+ · rw [ite_eq_left hq, ite_eq_left hq]
156
+ have hr := hread x.after
157
+ cases h : read x.after with
158
+ | none =>
159
+ simp only [h] at hr
160
+ simpa [front, h] using hr.symm
161
+ | some z =>
162
+ simp only [h] at hr
163
+ simpa [front, h] using hr.symm
164
+ · rw [ite_eq_right hq, ite_eq_right hq]
165
+
166
+ def potential (view : σ → List α) (t : Tournament.Tree (Front d α σ) d) : ℕ :=
167
+ ∑ p : Path d, (remaining view t p).length
168
+
169
+ theorem replacement_consumes_one (key : α → ℤ) (read : σ → Option (α × σ))
170
+ (view : σ → List α) (hread : IsReader read view)
171
+ (t : Tournament.Tree (Front d α σ) d)
172
+ (ht : Tournament.Valid (fun y => key y.value) t) (halign : Aligned t)
173
+ {x : Front d α σ} (hx : Tournament.winner t = some x) :
174
+ potential view (Tournament.replace (fun y => key y.value) t x.row
175
+ (front read x.row x.after)) + 1 = potential view t := by
176
+ have hrow := winner_at_own_row key t ht halign hx
177
+ let t' := Tournament.replace (fun y => key y.value) t x.row (front read x.row x.after)
178
+ have hpoint (p : Path d) : (remaining view t p).length =
179
+ (remaining view t' p).length + if p = x.row then 1 else 0 := by
180
+ have hnew := replace_remaining key read view hread t x p
181
+ change remaining view t' p = _ at hnew
182
+ by_cases hp : p = x.row
183
+ · subst p
184
+ rw [ite_eq_left rfl] at hnew
185
+ rw [hnew]
186
+ simp [remaining, hrow]
187
+ · rw [ite_eq_right (Ne.symm hp)] at hnew
188
+ rw [hnew, ite_eq_right hp]
189
+ omega
190
+ unfold potential
191
+ rw [show (∑ p : Path d, (remaining view t p).length) =
192
+ ∑ p : Path d, ((remaining view t' p).length + if p = x.row then 1 else 0) from
193
+ Finset.sum_congr rfl (fun p _ => hpoint p)]
194
+ simp [Finset.sum_add_distrib, t']
195
+
196
+ end RowMerge
197
+ end LowSpaceSubsetSum
198
+
199
+ end OAI
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/SliceCursor.lean ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import OAI.Combinatorics.LowSpaceSubsetSum.Streams.RowMerge
2
+
3
+ namespace OAI
4
+
5
+ /-!
6
+ # Cyclic row cursors into one shared immutable array
7
+
8
+ Each cursor stores its slice endpoints and the constant-size cyclic state.
9
+ Reading a row accesses the original array; it does not allocate a row array.
10
+ Empty slices have no cursor. The list slice and full trace are proof views.
11
+ -/
12
+
13
+ namespace LowSpaceSubsetSum
14
+ namespace SliceCursor
15
+
16
+ variable {α : Type*} {n : ℕ}
17
+
18
+ structure Range (n : ℕ) where
19
+ lo : ℕ
20
+ length : ℕ
21
+ bounded : lo + length ≤ n
22
+ deriving DecidableEq
23
+
24
+ structure State (n : ℕ) where
25
+ range : Range n
26
+ cursor : Option (CyclicCursor.State range.length)
27
+
28
+ def values (xs : Array α) (r : Range xs.size) (i : Fin r.length) : α :=
29
+ xs[r.lo + i.val]'(by have := r.bounded; have := i.isLt; omega)
30
+
31
+ def next (xs : Array α) (s : State xs.size) : Option (α × State xs.size) :=
32
+ match s.cursor with
33
+ | none => none
34
+ | some c =>
35
+ haveI : NeZero s.range.length := ⟨by have := c.position.isLt; omega⟩
36
+ if c.remaining = 0 then none
37
+ else some (values xs s.range c.position, ⟨s.range, some (CyclicCursor.advance c)⟩)
38
+
39
+ def output (xs : Array α) (s : State xs.size) : List α :=
40
+ match s.cursor with
41
+ | none => []
42
+ | some c =>
43
+ haveI : NeZero s.range.length := ⟨by have := c.position.isLt; omega⟩
44
+ CyclicCursor.trace (values xs s.range) c.remaining c
45
+
46
+ theorem reader (xs : Array α) : RowMerge.IsReader (next xs) (output xs) := by
47
+ rintro ⟨r, c⟩
48
+ cases c with
49
+ | none => rfl
50
+ | some c =>
51
+ have : NeZero r.length := ⟨by have := c.position.isLt; omega⟩
52
+ cases h : c.remaining with
53
+ | zero => simp [next, output, h, CyclicCursor.trace]
54
+ | succ k =>
55
+ simp [next, output, h, CyclicCursor.trace, CyclicCursor.advance_remaining]
56
+
57
+ def initial (r : Range n) (pivot : ℕ) (reverse : Bool) : State n :=
58
+ if h : 0 < r.length then
59
+ ⟨r, some ⟨⟨pivot % r.length, Nat.mod_lt _ h⟩, r.length, reverse⟩⟩
60
+ else ⟨r, none⟩
61
+
62
+ /-- A slice is a proof view, not a newly allocated row array. -/
63
+ def slice (xs : Array α) (r : Range xs.size) : List α := List.ofFn (values xs r)
64
+
65
+ theorem initial_perm (xs : Array α) (r : Range xs.size) (pivot : ℕ) (reverse : Bool) :
66
+ (output xs (initial r pivot reverse)).Perm (slice xs r) := by
67
+ by_cases h : 0 < r.length
68
+ · have : NeZero r.length := ⟨by omega⟩
69
+ rw [initial, dite_eq_left h]
70
+ exact
71
+ CyclicCursor.full_trace_perm (values xs r) ⟨pivot % r.length, Nat.mod_lt _ h⟩ reverse
72
+ · have hz : r.length = 0 := by omega
73
+ rw [initial, dite_eq_right h]
74
+ simp [output, slice, hz]
75
+
76
+ theorem initial_length (xs : Array α) (r : Range xs.size) (pivot : ℕ) (reverse : Bool) :
77
+ (output xs (initial r pivot reverse)).length = r.length := by
78
+ rw [(initial_perm xs r pivot reverse).length_eq]
79
+ simp [slice]
80
+
81
+ theorem slice_eq_drop_take (xs : Array α) (r : Range xs.size) :
82
+ slice xs r = (xs.toList.drop r.lo).take r.length := by
83
+ have hlo : r.lo ≤ xs.size := by have := r.bounded; omega
84
+ apply List.ext_getElem
85
+ · simp only [slice, List.length_ofFn, List.length_take, List.length_drop, Array.length_toList]
86
+ have := r.bounded
87
+ omega
88
+ · intro i hi hj
89
+ simp only [slice, List.getElem_ofFn, List.getElem_take, List.getElem_drop,
90
+ Array.getElem_toList, values]
91
+
92
+ theorem initial_occurrences (xs : Array α) (r : Range xs.size)
93
+ (pivot : ℕ) (reverse : Bool) :
94
+ (output xs (initial r pivot reverse) : Multiset α) =
95
+ ((xs.toList.drop r.lo).take r.length : Multiset α) := by
96
+ rw [← slice_eq_drop_take xs r]
97
+ exact Quot.sound (initial_perm xs r pivot reverse)
98
+
99
+ end SliceCursor
100
+ end LowSpaceSubsetSum
101
+
102
+ end OAI
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/SortedFind.lean ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import OAI.Combinatorics.LowSpaceSubsetSum.Counting.MatchPotential
2
+
3
+ namespace OAI
4
+
5
+ /-!
6
+ # Linear exact-key search for the separator's terminal arrays
7
+
8
+ At a terminal separator node every left/right pair is disjoint. One equal
9
+ weight key therefore suffices. This loop stops at the first equal key and
10
+ never enumerates its Cartesian tie group. The finite reader law supplies
11
+ exactness, and the ledger charges at most two reads per control step.
12
+ -/
13
+
14
+ namespace LowSpaceSubsetSum
15
+ namespace SortedFind
16
+
17
+ variable {α β σ₁ σ₂ : Type*}
18
+
19
+ def runAcc (read₁ : σ₁ → Option (α × σ₁)) (key₁ : α → ℤ)
20
+ (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ) :
21
+ ℕ → σ₁ → σ₂ → ℕ → Bool × ℕ
22
+ | 0, _, _, queries => (false, queries)
23
+ | fuel + 1, s₁, s₂, queries =>
24
+ match read₁ s₁ with
25
+ | none => (false, queries + 1)
26
+ | some (x, s₁') => match read₂ s₂ with
27
+ | none => (false, queries + 2)
28
+ | some (y, s₂') =>
29
+ if key₁ x < key₂ y then runAcc read₁ key₁ read₂ key₂ fuel s₁' s₂ (queries + 2)
30
+ else if key₂ y < key₁ x then runAcc read₁ key₁ read₂ key₂ fuel s₁ s₂' (queries + 2)
31
+ else (true, queries + 2)
32
+
33
+ theorem queries_le (read₁ : σ₁ → Option (α × σ₁)) (key₁ : α → ℤ)
34
+ (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ)
35
+ (fuel : ℕ) (s₁ : σ₁) (s₂ : σ₂) (queries : ℕ) :
36
+ (runAcc read₁ key₁ read₂ key₂ fuel s₁ s₂ queries).2 ≤ queries + 2 * fuel := by
37
+ induction fuel generalizing s₁ s₂ queries with
38
+ | zero => simp [runAcc]
39
+ | succ fuel ih =>
40
+ unfold runAcc
41
+ split
42
+ · dsimp
43
+ omega
44
+ · split
45
+ · dsimp
46
+ omega
47
+ · split
48
+ · exact (ih _ _ _).trans (by omega)
49
+ · split
50
+ · exact (ih _ _ _).trans (by omega)
51
+ · dsimp
52
+ omega
53
+
54
+ theorem sound (read₁ : σ₁ → Option (α × σ₁)) (key₁ : α → ℤ)
55
+ (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ)
56
+ (view₁ : σ₁ → List α) (hread₁ : RowMerge.IsReader read₁ view₁)
57
+ (view₂ : σ₂ → List β) (hread₂ : RowMerge.IsReader read₂ view₂)
58
+ (fuel : ℕ) (s₁ : σ₁) (s₂ : σ₂) (queries : ℕ)
59
+ (hyes : (runAcc read₁ key₁ read₂ key₂ fuel s₁ s₂ queries).1 = true) :
60
+ ∃ x ∈ view₁ s₁, ∃ y ∈ view₂ s₂, key₁ x = key₂ y := by
61
+ induction fuel generalizing s₁ s₂ queries with
62
+ | zero => simp [runAcc] at hyes
63
+ | succ fuel ih =>
64
+ have h₁ := hread₁ s₁
65
+ have h₂ := hread₂ s₂
66
+ cases hx : read₁ s₁ with
67
+ | none => simp [runAcc, hx] at hyes
68
+ | some xp =>
69
+ obtain ⟨x, s₁'⟩ := xp
70
+ simp only [hx] at h₁
71
+ cases hy : read₂ s₂ with
72
+ | none => simp [runAcc, hx, hy] at hyes
73
+ | some yp =>
74
+ obtain ⟨y, s₂'⟩ := yp
75
+ simp only [hy] at h₂
76
+ by_cases hlt : key₁ x < key₂ y
77
+ · simp only [runAcc, hx, hy, hlt, ↓reduceIte] at hyes
78
+ obtain ⟨a, ha, b, hb, heq⟩ := ih _ _ _ hyes
79
+ exact ⟨a, by rw [h₁]; exact List.mem_cons_of_mem _ ha, b, hb, heq⟩
80
+ · by_cases hgt : key₂ y < key₁ x
81
+ · simp only [runAcc, hx, hy, hlt, hgt, ↓reduceIte] at hyes
82
+ obtain ⟨a, ha, b, hb, heq⟩ := ih _ _ _ hyes
83
+ exact ⟨a, ha, b, by rw [h₂]; exact List.mem_cons_of_mem _ hb, heq⟩
84
+ · exact ⟨x, by rw [h₁]; simp, y, by rw [h₂]; simp, by omega⟩
85
+
86
+ theorem correct (read₁ : σ₁ → Option (α × σ₁)) (key₁ : α → ℤ)
87
+ (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ)
88
+ (view₁ : σ₁ → List α) (hread₁ : RowMerge.IsReader read₁ view₁)
89
+ (view₂ : σ₂ → List β) (hread₂ : RowMerge.IsReader read₂ view₂)
90
+ (fuel : ℕ) (s₁ : σ₁) (s₂ : σ₂) (queries : ℕ)
91
+ (hs₁ : (view₁ s₁).Pairwise (fun x y => key₁ x ≤ key₁ y))
92
+ (hs₂ : (view₂ s₂).Pairwise (fun x y => key₂ x ≤ key₂ y))
93
+ (hfuel : (view₁ s₁).length + (view₂ s₂).length < fuel) :
94
+ (runAcc read₁ key₁ read₂ key₂ fuel s₁ s₂ queries).1 = true ↔
95
+ 0 < MatchPotential.count key₁ key₂ (view₁ s₁) (view₂ s₂) := by
96
+ induction fuel generalizing s₁ s₂ queries with
97
+ | zero => omega
98
+ | succ fuel ih =>
99
+ have h₁ := hread₁ s₁
100
+ have h₂ := hread₂ s₂
101
+ cases hx : read₁ s₁ with
102
+ | none =>
103
+ simp only [hx] at h₁
104
+ simp [runAcc, hx, h₁, MatchPotential.count]
105
+ | some xp =>
106
+ obtain ⟨x, s₁'⟩ := xp
107
+ simp only [hx] at h₁
108
+ cases hy : read₂ s₂ with
109
+ | none =>
110
+ simp only [hy] at h₂
111
+ have hz := MatchPotential.eq_zero key₁ key₂ (view₁ s₁) [] (by simp)
112
+ simp [runAcc, hx, hy, h₂, hz]
113
+ | some yp =>
114
+ obtain ⟨y, s₂'⟩ := yp
115
+ simp only [hy] at h₂
116
+ have hs₁' := (List.pairwise_cons.mp (h₁ ▸ hs₁)).2
117
+ have hs₂' := (List.pairwise_cons.mp (h₂ ▸ hs₂)).2
118
+ by_cases hlt : key₁ x < key₂ y
119
+ · have hskip := MatchPotential.skip_left key₁ key₂ x (view₁ s₁') (view₂ s₂) (by
120
+ intro z hz
121
+ rw [h₂] at hz
122
+ rcases List.mem_cons.mp hz with rfl | hz
123
+ · exact hlt
124
+ · exact hlt.trans_le ((List.pairwise_cons.mp (h₂ ▸ hs₂)).1 z hz))
125
+ rw [← h₁] at hskip
126
+ simp only [runAcc, hx, hy, hlt, ↓reduceIte, hskip]
127
+ exact ih s₁' s₂ _ hs₁' hs₂ (by rw [h₁] at hfuel; simp only [List.length_cons] at hfuel; omega)
128
+ · by_cases hgt : key₂ y < key₁ x
129
+ · have hskip := MatchPotential.skip_right key₁ key₂ (view₁ s₁) y (view₂ s₂') (by
130
+ intro z hz
131
+ rw [h₁] at hz
132
+ rcases List.mem_cons.mp hz with rfl | hz
133
+ · exact hgt
134
+ · exact hgt.trans_le ((List.pairwise_cons.mp (h₁ ▸ hs₁)).1 z hz))
135
+ rw [← h₂] at hskip
136
+ simp only [runAcc, hx, hy, hlt, hgt, ↓reduceIte, hskip]
137
+ exact ih s₁ s₂' _ hs₁ hs₂' (by rw [h₂] at hfuel; simp only [List.length_cons] at hfuel; omega)
138
+ · have heq : key₁ x = key₂ y := by omega
139
+ have hpos := (MatchPotential.positive_iff key₁ key₂ (view₁ s₁) (view₂ s₂)).mpr
140
+ ⟨x, by rw [h₁]; simp, y, by rw [h₂]; simp, heq⟩
141
+ simp [runAcc, hx, hy, hlt, hgt, hpos]
142
+
143
+ end SortedFind
144
+ end LowSpaceSubsetSum
145
+
146
+ end OAI
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/StreamGroupFacts.lean ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import OAI.Combinatorics.LowSpaceSubsetSum.Streams.StreamJoin
2
+
3
+ namespace OAI
4
+
5
+ /-! The exact potential and cursor facts for one equal-key stream step. -/
6
+
7
+ namespace LowSpaceSubsetSum
8
+ namespace StreamJoin
9
+
10
+ universe u v s t w
11
+ variable {α : Type u} {β : Type v} {σ₁ : Type s} {σ₂ : Type t} {τ : Type w}
12
+
13
+ theorem equal_group_facts (read₁ : σ₁ → Option (α × σ₁)) (key₁ : α → ℤ)
14
+ (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ)
15
+ (report : α → β → τ → τ × Bool) (hreport : ∀ x y a, (report x y a).2 = false)
16
+ (view₁ : σ₁ → List α) (hread₁ : RowMerge.IsReader read₁ view₁)
17
+ (view₂ : σ₂ → List β) (hread₂ : RowMerge.IsReader read₂ view₂)
18
+ (B fuel₁ fuel₂ : ℕ) (st : State σ₁ σ₂ τ)
19
+ (hst : WellFormed key₁ key₂ view₁ view₂ fuel₁ fuel₂ st)
20
+ (x : α) (left' : σ₁) (y : β) (right' : σ₂)
21
+ (hx : read₁ st.left = some (x, left')) (hy : read₂ st.right = some (y, right'))
22
+ (hkey : key₁ x = key₂ y) :
23
+ let out := TieGroup.run read₁ key₁ read₂ key₂ (key₁ x) report B fuel₁ fuel₂
24
+ st.left st.right st.user
25
+ let G₁ := TieBuffer.groupView key₁ (key₁ x) view₁ st.left
26
+ let G₂ := TieBuffer.groupView key₂ (key₁ x) view₂ st.right
27
+ (view₁ out.outer.cursor).Pairwise (fun x y => key₁ x ≤ key₁ y) ∧
28
+ (view₂ out.outer.state.last).Pairwise (fun x y => key₂ x ≤ key₂ y) ∧
29
+ (view₁ st.left).length = G₁.length + (view₁ out.outer.cursor).length ∧
30
+ (view₂ st.right).length = G₂.length + (view₂ out.outer.state.last).length ∧
31
+ 0 < G₁.length ∧ 0 < G₂.length ∧
32
+ MatchPotential.count key₁ key₂ (view₁ st.left) (view₂ st.right) =
33
+ G₁.length * G₂.length +
34
+ MatchPotential.count key₁ key₂ (view₁ out.outer.cursor) (view₂ out.outer.state.last) := by
35
+ let out := TieGroup.run read₁ key₁ read₂ key₂ (key₁ x) report B fuel₁ fuel₂
36
+ st.left st.right st.user
37
+ let G₁ := TieBuffer.groupView key₁ (key₁ x) view₁ st.left
38
+ let G₂ := TieBuffer.groupView key₂ (key₁ x) view₂ st.right
39
+ have hv₁ : view₁ st.left = x :: view₁ left' := by simpa only [hx] using hread₁ st.left
40
+ have hv₂ : view₂ st.right = y :: view₂ right' := by simpa only [hy] using hread₂ st.right
41
+ have hg₁ : G₁ ≠ [] := by simp [G₁, TieBuffer.groupView, hv₁]
42
+ have hg₂ : G₂ ≠ [] := by simp [G₂, TieBuffer.groupView, hv₂, ← hkey]
43
+ have hlen₁ : G₁.length ≤ fuel₁ :=
44
+ (List.takeWhile_sublist (fun z => decide (key₁ z = key₁ x))).length_le.trans hst.2.2.1
45
+ have hlen₂ : G₂.length ≤ fuel₂ :=
46
+ (List.takeWhile_sublist (fun z => decide (key₂ z = key₁ x))).length_le.trans hst.2.2.2
47
+ have hviews := TieGroup.views_complete read₁ key₁ read₂ key₂ (key₁ x) report hreport
48
+ view₁ hread₁ view₂ hread₂ B fuel₁ fuel₂ st.left st.right st.user hlen₁ hlen₂ hg₁
49
+ change view₁ st.left = G₁ ++ view₁ out.outer.cursor ∧
50
+ view₂ st.right = G₂ ++ view₂ out.outer.state.last at hviews
51
+ have hsub₁ := MatchPotential.remaining_sublist _ _ _ hviews.1
52
+ have hsub₂ := MatchPotential.remaining_sublist _ _ _ hviews.2
53
+ have hlower₁ : ∀ z ∈ view₁ st.left, key₁ x ≤ key₁ z := by
54
+ have hsort : (x :: view₁ left').Pairwise (fun x y => key₁ x ≤ key₁ y) :=
55
+ by simpa only [hv₁] using hst.1
56
+ simpa only [hv₁] using MatchPotential.lower_bound_head key₁ x _ hsort
57
+ have hlower₂ : ∀ z ∈ view₂ st.right, key₁ x ≤ key₂ z := by
58
+ rw [hkey, hv₂]
59
+ exact MatchPotential.lower_bound_head key₂ y _ (by simpa only [hv₂] using hst.2.1)
60
+ have hr₁ := MatchPotential.remaining_avoids key₁ (key₁ x) _ _ hviews.1 hst.1 hlower₁
61
+ have hr₂ := MatchPotential.remaining_avoids key₂ (key₁ x) _ _ hviews.2 hst.2.1 hlower₂
62
+ refine ⟨hst.1.sublist hsub₁, hst.2.1.sublist hsub₂, ?_, ?_,
63
+ List.length_pos_iff.mpr hg₁, List.length_pos_iff.mpr hg₂, ?_⟩
64
+ · simpa only [List.length_append] using congrArg List.length hviews.1
65
+ · simpa only [List.length_append] using congrArg List.length hviews.2
66
+ · have hG₁ : ∀ z ∈ G₁, key₁ z = key₁ x := by
67
+ intro z hz
68
+ exact of_decide_eq_true (List.mem_takeWhile_imp (p := fun z => decide (key₁ z = key₁ x)) hz)
69
+ have hG₂ : ∀ z ∈ G₂, key₂ z = key₁ x := by
70
+ intro z hz
71
+ exact of_decide_eq_true (List.mem_takeWhile_imp (p := fun z => decide (key₂ z = key₁ x)) hz)
72
+ have hsplit := MatchPotential.split_groups key₁ key₂ (key₁ x) G₁
73
+ (view₁ out.outer.cursor) G₂ (view₂ out.outer.state.last) hG₁ hG₂ hr₁ hr₂
74
+ rw [← hviews.1, ← hviews.2] at hsplit
75
+ exact hsplit
76
+
77
+ end StreamJoin
78
+ end LowSpaceSubsetSum
79
+
80
+ end OAI
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/StreamJoin.lean ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import OAI.Combinatorics.LowSpaceSubsetSum.Counting.MatchPotential
2
+
3
+ namespace OAI
4
+
5
+ /-!
6
+ # A finite-state join of two sorted streams
7
+
8
+ Unequal keys consume one occurrence. Equal keys invoke the bounded-buffer
9
+ Cartesian reporter and continue from its two saved endpoints. The loop keeps
10
+ only the two generator states, callback state, and counters. Its finite output
11
+ lists and matching potential are analysis objects only.
12
+ -/
13
+
14
+ namespace LowSpaceSubsetSum
15
+ namespace StreamJoin
16
+
17
+ universe u v s t w
18
+
19
+ variable {α : Type u} {β : Type v} {σ₁ : Type s} {σ₂ : Type t} {τ : Type w}
20
+
21
+ structure State (σ₁ : Type s) (σ₂ : Type t) (τ : Type w) where
22
+ left : σ₁
23
+ right : σ₂
24
+ user : τ
25
+ queries : ℕ
26
+ reports : ℕ
27
+ copies : ℕ
28
+ done : Bool
29
+
30
+ def start (s₁ : σ₁) (s₂ : σ₂) (a : τ) : State σ₁ σ₂ τ := ⟨s₁, s₂, a, 0, 0, 0, false⟩
31
+
32
+ def step (read₁ : σ₁ → Option (α × σ₁)) (key₁ : α → ℤ)
33
+ (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ)
34
+ (report : α → β → τ → τ × Bool) (B fuel₁ fuel₂ : ℕ)
35
+ (s : State σ₁ σ₂ τ) : State σ₁ σ₂ τ :=
36
+ if s.done then s else
37
+ match read₁ s.left with
38
+ | none => { s with queries := s.queries + 1, done := true }
39
+ | some (x, left') => match read₂ s.right with
40
+ | none => { s with queries := s.queries + 2, done := true }
41
+ | some (y, right') =>
42
+ if key₁ x < key₂ y then { s with left := left', queries := s.queries + 2 }
43
+ else if key₂ y < key₁ x then { s with right := right', queries := s.queries + 2 }
44
+ else
45
+ let out := TieGroup.run read₁ key₁ read₂ key₂ (key₁ x) report B fuel₁ fuel₂
46
+ s.left s.right s.user
47
+ ⟨out.outer.cursor, out.outer.state.last, out.outer.state.user,
48
+ s.queries + 2 + out.outer.queries + out.fillQueries + out.outer.state.queries,
49
+ s.reports + out.outer.state.reports,
50
+ s.copies + (if out.snapshot then 1 else 0) + out.outer.state.restores,
51
+ out.outer.halted⟩
52
+
53
+ def runAcc (read₁ : σ₁ → Option (α × σ₁)) (key₁ : α → ℤ)
54
+ (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ)
55
+ (report : α → β → τ → τ × Bool) (B fuel₁ fuel₂ : ℕ) :
56
+ ℕ → State σ₁ σ₂ τ → State σ₁ σ₂ τ
57
+ | 0, s => s
58
+ | fuel + 1, s => runAcc read₁ key₁ read₂ key₂ report B fuel₁ fuel₂ fuel
59
+ (step read₁ key₁ read₂ key₂ report B fuel₁ fuel₂ s)
60
+
61
+ def run (read₁ : σ₁ → Option (α × σ₁)) (key₁ : α → ℤ)
62
+ (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ)
63
+ (report : α → β → τ → τ × Bool) (B fuel₁ fuel₂ controlFuel : ℕ)
64
+ (s₁ : σ₁) (s₂ : σ₂) (a : τ) : State σ₁ σ₂ τ :=
65
+ runAcc read₁ key₁ read₂ key₂ report B fuel₁ fuel₂ controlFuel (start s₁ s₂ a)
66
+
67
+ def rank (view₁ : σ₁ → List α) (view₂ : σ₂ → List β) (s : State σ₁ σ₂ τ) : ℕ :=
68
+ (view₁ s.left).length + (view₂ s.right).length
69
+
70
+ def potential (key₁ : α → ℤ) (key₂ : β → ℤ)
71
+ (view₁ : σ₁ → List α) (view₂ : σ₂ → List β) (s : State σ₁ σ₂ τ) : ℕ :=
72
+ MatchPotential.count key₁ key₂ (view₁ s.left) (view₂ s.right)
73
+
74
+ def WellFormed (key₁ : α → ℤ) (key₂ : β → ℤ)
75
+ (view₁ : σ₁ → List α) (view₂ : σ₂ → List β) (fuel₁ fuel₂ : ℕ)
76
+ (s : State σ₁ σ₂ τ) : Prop :=
77
+ (view₁ s.left).Pairwise (fun x y => key₁ x ≤ key₁ y) ∧
78
+ (view₂ s.right).Pairwise (fun x y => key₂ x ≤ key₂ y) ∧
79
+ (view₁ s.left).length ≤ fuel₁ ∧ (view₂ s.right).length ≤ fuel₂
80
+
81
+ theorem step_done (read₁ : σ₁ → Option (α × σ₁)) (key₁ : α → ℤ)
82
+ (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ)
83
+ (report : α → β → τ → τ × Bool) (B fuel₁ fuel₂ : ℕ)
84
+ (s : State σ₁ σ₂ τ) (hs : s.done = true) :
85
+ step read₁ key₁ read₂ key₂ report B fuel₁ fuel₂ s = s := by
86
+ simp only [step, hs, ite_true]
87
+
88
+ theorem runAcc_done (read₁ : σ₁ → Option (α × σ₁)) (key₁ : α → ℤ)
89
+ (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ)
90
+ (report : α → β → τ → τ × Bool) (B fuel₁ fuel₂ fuel : ℕ)
91
+ (s : State σ₁ σ₂ τ) (hs : s.done = true) :
92
+ runAcc read₁ key₁ read₂ key₂ report B fuel₁ fuel₂ fuel s = s := by
93
+ induction fuel with
94
+ | zero => rfl
95
+ | succ fuel ih => rw [runAcc, step_done _ _ _ _ _ _ _ _ s hs, ih]
96
+
97
+ end StreamJoin
98
+ end LowSpaceSubsetSum
99
+
100
+ end OAI
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/StreamJoinBounds.lean ADDED
@@ -0,0 +1,241 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import OAI.Combinatorics.LowSpaceSubsetSum.Streams.StreamGroupFacts
2
+
3
+ namespace OAI
4
+
5
+ /-! Amortized accounts for the executable global stream join. -/
6
+
7
+ namespace LowSpaceSubsetSum
8
+ namespace StreamJoin
9
+
10
+ universe u v s t w
11
+ variable {α : Type u} {β : Type v} {σ₁ : Type s} {σ₂ : Type t} {τ : Type w}
12
+
13
+ def queryAccount (key₁ : α → ℤ) (key₂ : β → ℤ)
14
+ (view₁ : σ₁ → List α) (view₂ : σ₂ → List β) (s : State σ₁ σ₂ τ) : ℕ :=
15
+ s.queries + 6 * rank view₁ view₂ s + potential key₁ key₂ view₁ view₂ s + if s.done then 0 else 2
16
+
17
+ def reportAccount (key₁ : α → ℤ) (key₂ : β → ℤ)
18
+ (view₁ : σ₁ → List α) (view₂ : σ₂ → List β) (s : State σ₁ σ₂ τ) : ℕ :=
19
+ s.reports + potential key₁ key₂ view₁ view₂ s
20
+
21
+ def copyAccount (key₁ : α → ℤ) (key₂ : β → ℤ)
22
+ (view₁ : σ₁ → List α) (view₂ : σ₂ → List β) (B : ℕ) (s : State σ₁ σ₂ τ) : ℕ :=
23
+ B * s.copies + 2 * potential key₁ key₂ view₁ view₂ s
24
+
25
+ theorem step_accounts (read₁ : σ₁ → Option (α × σ₁)) (key₁ : α → ℤ)
26
+ (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ)
27
+ (report : α → β → τ → τ × Bool) (hreport : ∀ x y a, (report x y a).2 = false)
28
+ (view₁ : σ₁ → List α) (hread₁ : RowMerge.IsReader read₁ view₁)
29
+ (view₂ : σ₂ → List β) (hread₂ : RowMerge.IsReader read₂ view₂)
30
+ (B fuel₁ fuel₂ : ℕ) (st : State σ₁ σ₂ τ)
31
+ (hst : WellFormed key₁ key₂ view₁ view₂ fuel₁ fuel₂ st) :
32
+ let next := step read₁ key₁ read₂ key₂ report B fuel₁ fuel₂ st
33
+ WellFormed key₁ key₂ view₁ view₂ fuel₁ fuel₂ next ∧
34
+ queryAccount key₁ key₂ view₁ view₂ next ≤ queryAccount key₁ key₂ view₁ view₂ st ∧
35
+ reportAccount key₁ key₂ view₁ view₂ next ≤ reportAccount key₁ key₂ view₁ view₂ st ∧
36
+ copyAccount key₁ key₂ view₁ view₂ B next ≤ copyAccount key₁ key₂ view₁ view₂ B st ∧
37
+ (st.done = false → next.done = true ∨ rank view₁ view₂ next < rank view₁ view₂ st) := by
38
+ by_cases hd : st.done = true
39
+ · simp only [step_done _ _ _ _ _ _ _ _ st hd, le_refl, hd, Bool.true_eq_false,
40
+ false_implies, and_true]
41
+ exact hst
42
+ have hdf : st.done = false := Bool.eq_false_iff.mpr hd
43
+ cases hx : read₁ st.left with
44
+ | none =>
45
+ simp only [step, hdf, Bool.false_eq_true, ite_false, hx]
46
+ refine ⟨hst, ?_, le_rfl, le_rfl, ?_⟩
47
+ · dsimp only [queryAccount, rank, potential]
48
+ simp only [hdf, Bool.false_eq_true, ↓reduceIte]
49
+ omega
50
+ · simp
51
+ | some xp =>
52
+ rcases xp with ⟨x, left'⟩
53
+ have hv₁ : view₁ st.left = x :: view₁ left' := by simpa only [hx] using hread₁ st.left
54
+ cases hy : read₂ st.right with
55
+ | none =>
56
+ simp only [step, hdf, Bool.false_eq_true, ite_false, hx, hy]
57
+ refine ⟨hst, ?_, le_rfl, le_rfl, ?_⟩
58
+ · dsimp only [queryAccount, rank, potential]
59
+ simp only [hdf, Bool.false_eq_true, ↓reduceIte]
60
+ omega
61
+ · simp
62
+ | some yp =>
63
+ rcases yp with ⟨y, right'⟩
64
+ have hv₂ : view₂ st.right = y :: view₂ right' := by simpa only [hy] using hread₂ st.right
65
+ by_cases hxy : key₁ x < key₂ y
66
+ · have hsort₁ := hst.1
67
+ rw [hv₁] at hsort₁
68
+ have hlower₂ := MatchPotential.lower_bound_head key₂ y (view₂ right')
69
+ (show (y :: view₂ right').Pairwise (fun x y => key₂ x ≤ key₂ y) from
70
+ by simpa only [hv₂] using hst.2.1)
71
+ have hp : MatchPotential.count key₁ key₂ (view₁ st.left) (view₂ st.right) =
72
+ MatchPotential.count key₁ key₂ (view₁ left') (view₂ st.right) := by
73
+ rw [hv₁]
74
+ apply MatchPotential.skip_left
75
+ intro z hz
76
+ exact hxy.trans_le (hlower₂ z (by simpa only [hv₂] using hz))
77
+ simp only [step, hdf, Bool.false_eq_true, ite_false, hx, hy, ite_eq_left hxy]
78
+ refine ⟨⟨(List.pairwise_cons.mp hsort₁).2, hst.2.1, ?_, hst.2.2.2⟩, ?_, ?_, ?_, ?_⟩
79
+ · have hc := hst.2.2.1
80
+ rw [hv₁, List.length_cons] at hc
81
+ dsimp only
82
+ omega
83
+ · dsimp only [queryAccount, rank, potential]
84
+ simp only [hdf, Bool.false_eq_true, ite_false]
85
+ rw [← hp, hv₁, List.length_cons]
86
+ omega
87
+ · dsimp only [reportAccount, potential]
88
+ rw [hp]
89
+ · dsimp only [copyAccount, potential]
90
+ rw [hp]
91
+ · intro _
92
+ right
93
+ dsimp only [rank]
94
+ rw [hv₁, List.length_cons]
95
+ omega
96
+ · by_cases hyx : key₂ y < key₁ x
97
+ · have hsort₂ := hst.2.1
98
+ rw [hv₂] at hsort₂
99
+ have hlower₁ := MatchPotential.lower_bound_head key₁ x (view₁ left')
100
+ (show (x :: view₁ left').Pairwise (fun x y => key₁ x ≤ key₁ y) from
101
+ by simpa only [hv₁] using hst.1)
102
+ have hp : MatchPotential.count key₁ key₂ (view₁ st.left) (view₂ st.right) =
103
+ MatchPotential.count key₁ key₂ (view₁ st.left) (view₂ right') := by
104
+ rw [hv₂]
105
+ apply MatchPotential.skip_right
106
+ intro z hz
107
+ exact hyx.trans_le (hlower₁ z (by simpa only [hv₁] using hz))
108
+ simp only [step, hdf, Bool.false_eq_true, ite_false, hx, hy,
109
+ ite_eq_right hxy, ite_eq_left hyx]
110
+ refine ⟨⟨hst.1, (List.pairwise_cons.mp hsort₂).2, hst.2.2.1, ?_⟩, ?_, ?_, ?_, ?_⟩
111
+ · have hc := hst.2.2.2
112
+ rw [hv₂, List.length_cons] at hc
113
+ dsimp only
114
+ omega
115
+ · dsimp only [queryAccount, rank, potential]
116
+ simp only [hdf, Bool.false_eq_true, ite_false]
117
+ rw [← hp, hv₂, List.length_cons]
118
+ omega
119
+ · dsimp only [reportAccount, potential]
120
+ rw [hp]
121
+ · dsimp only [copyAccount, potential]
122
+ rw [hp]
123
+ · intro _
124
+ right
125
+ dsimp only [rank]
126
+ rw [hv₂, List.length_cons]
127
+ omega
128
+ · have hkey : key₁ x = key₂ y := by omega
129
+ let out := TieGroup.run read₁ key₁ read₂ key₂ (key₁ x) report B fuel₁ fuel₂
130
+ st.left st.right st.user
131
+ have hg := equal_group_facts read₁ key₁ read₂ key₂ report hreport
132
+ view₁ hread₁ view₂ hread₂ B fuel₁ fuel₂ st hst x left' y right' hx hy hkey
133
+ rcases hg with ⟨hs₁, hs₂, hl₁, hl₂, hn₁, hn₂, hp⟩
134
+ have hq := TieGroup.query_bound read₁ key₁ read₂ key₂ (key₁ x) report
135
+ view₁ hread₁ view₂ hread₂ B fuel₁ fuel₂ st.left st.right st.user
136
+ have hr := (TieGroup.run_bounds read₁ key₁ read₂ key₂ (key₁ x) report
137
+ view₁ hread₁ view₂ hread₂ B fuel₁ fuel₂ st.left st.right st.user).1
138
+ have hc := TieGroup.copies_charged read₁ key₁ read₂ key₂ (key₁ x) report
139
+ view₁ hread₁ view₂ hread₂ B fuel₁ fuel₂ st.left st.right st.user
140
+ have hhalt : out.outer.halted = false := TieGroup.halted_false
141
+ read₁ key₁ read₂ key₂ (key₁ x) report hreport B fuel₁ fuel₂ st.left st.right st.user
142
+ dsimp only [out] at hhalt
143
+ simp only [step, hdf, Bool.false_eq_true, ite_false, hx, hy,
144
+ ite_eq_right hxy, ite_eq_right hyx]
145
+ change WellFormed key₁ key₂ view₁ view₂ fuel₁ fuel₂
146
+ (⟨out.outer.cursor, out.outer.state.last, out.outer.state.user,
147
+ st.queries + 2 + out.outer.queries + out.fillQueries + out.outer.state.queries,
148
+ st.reports + out.outer.state.reports,
149
+ st.copies + (if out.snapshot then 1 else 0) + out.outer.state.restores,
150
+ out.outer.halted⟩ : State σ₁ σ₂ τ) ∧ _
151
+ refine ⟨⟨hs₁, hs₂, ?_, ?_⟩, ?_, ?_, ?_, ?_⟩
152
+ · have hcap := hst.2.2.1
153
+ dsimp only [out]
154
+ omega
155
+ · have hcap := hst.2.2.2
156
+ dsimp only [out]
157
+ omega
158
+ · dsimp only [queryAccount, rank, potential]
159
+ simp only [hhalt, hdf, Bool.false_eq_true, ite_false]
160
+ nlinarith
161
+ · dsimp only [reportAccount, potential]
162
+ omega
163
+ · dsimp only [copyAccount, potential]
164
+ nlinarith
165
+ · intro _
166
+ right
167
+ dsimp only [rank]
168
+ omega
169
+
170
+ theorem runAcc_accounts (read₁ : σ₁ → Option (α × σ₁)) (key₁ : α → ℤ)
171
+ (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ)
172
+ (report : α → β → τ → τ × Bool) (hreport : ∀ x y a, (report x y a).2 = false)
173
+ (view₁ : σ₁ → List α) (hread₁ : RowMerge.IsReader read₁ view₁)
174
+ (view₂ : σ₂ → List β) (hread₂ : RowMerge.IsReader read₂ view₂)
175
+ (B fuel₁ fuel₂ controlFuel : ℕ) (st : State σ₁ σ₂ τ)
176
+ (hst : WellFormed key₁ key₂ view₁ view₂ fuel₁ fuel₂ st) :
177
+ let out := runAcc read₁ key₁ read₂ key₂ report B fuel₁ fuel₂ controlFuel st
178
+ WellFormed key₁ key₂ view₁ view₂ fuel₁ fuel₂ out ∧
179
+ queryAccount key₁ key₂ view₁ view₂ out ≤ queryAccount key₁ key₂ view₁ view₂ st ∧
180
+ reportAccount key₁ key₂ view₁ view₂ out ≤ reportAccount key₁ key₂ view₁ view₂ st ∧
181
+ copyAccount key₁ key₂ view₁ view₂ B out ≤ copyAccount key₁ key₂ view₁ view₂ B st := by
182
+ induction controlFuel generalizing st with
183
+ | zero => exact ⟨hst, le_rfl, le_rfl, le_rfl⟩
184
+ | succ controlFuel ih =>
185
+ have hs := step_accounts read₁ key₁ read₂ key₂ report hreport view₁ hread₁ view₂ hread₂
186
+ B fuel₁ fuel₂ st hst
187
+ have hi := ih _ hs.1
188
+ exact ⟨hi.1, hi.2.1.trans hs.2.1, hi.2.2.1.trans hs.2.2.1,
189
+ hi.2.2.2.trans hs.2.2.2.1⟩
190
+
191
+ theorem runAcc_terminates (read₁ : σ₁ → Option (α × σ₁)) (key₁ : α → ℤ)
192
+ (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ)
193
+ (report : α → β → τ → τ × Bool) (hreport : ∀ x y a, (report x y a).2 = false)
194
+ (view₁ : σ₁ → List α) (hread₁ : RowMerge.IsReader read₁ view₁)
195
+ (view₂ : σ₂ → List β) (hread₂ : RowMerge.IsReader read₂ view₂)
196
+ (B fuel₁ fuel₂ controlFuel : ℕ) (st : State σ₁ σ₂ τ)
197
+ (hst : WellFormed key₁ key₂ view₁ view₂ fuel₁ fuel₂ st)
198
+ (hfuel : rank view₁ view₂ st < controlFuel) :
199
+ (runAcc read₁ key₁ read₂ key₂ report B fuel₁ fuel₂ controlFuel st).done = true := by
200
+ induction controlFuel generalizing st with
201
+ | zero => omega
202
+ | succ controlFuel ih =>
203
+ by_cases hd : st.done = true
204
+ · rw [runAcc_done _ _ _ _ _ _ _ _ _ st hd]
205
+ exact hd
206
+ have hs := step_accounts read₁ key₁ read₂ key₂ report hreport view₁ hread₁ view₂ hread₂
207
+ B fuel₁ fuel₂ st hst
208
+ rcases hs.2.2.2.2 (Bool.eq_false_iff.mpr hd) with hdone | hprogress
209
+ · rw [runAcc, runAcc_done _ _ _ _ _ _ _ _ _ _ hdone]
210
+ exact hdone
211
+ · rw [runAcc]
212
+ exact ih _ hs.1 (by omega)
213
+
214
+ theorem run_bounds (read₁ : σ₁ → Option (α × σ₁)) (key₁ : α → ℤ)
215
+ (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ)
216
+ (report : α → β → τ → τ × Bool) (hreport : ∀ x y a, (report x y a).2 = false)
217
+ (view₁ : σ₁ → List α) (hread₁ : RowMerge.IsReader read₁ view₁)
218
+ (view₂ : σ₂ → List β) (hread₂ : RowMerge.IsReader read₂ view₂)
219
+ (B fuel₁ fuel₂ controlFuel : ℕ) (s₁ : σ₁) (s₂ : σ₂) (a : τ)
220
+ (hsort₁ : (view₁ s₁).Pairwise (fun x y => key₁ x ≤ key₁ y))
221
+ (hsort₂ : (view₂ s₂).Pairwise (fun x y => key₂ x ≤ key₂ y))
222
+ (hcap₁ : (view₁ s₁).length ≤ fuel₁) (hcap₂ : (view₂ s₂).length ≤ fuel₂) :
223
+ let out := run read₁ key₁ read₂ key₂ report B fuel₁ fuel₂ controlFuel s₁ s₂ a
224
+ out.queries ≤ 6 * ((view₁ s₁).length + (view₂ s₂).length) +
225
+ MatchPotential.count key₁ key₂ (view₁ s₁) (view₂ s₂) + 2 ∧
226
+ out.reports ≤ MatchPotential.count key₁ key₂ (view₁ s₁) (view₂ s₂) ∧
227
+ B * out.copies ≤ 2 * MatchPotential.count key₁ key₂ (view₁ s₁) (view₂ s₂) := by
228
+ have h := runAcc_accounts read₁ key₁ read₂ key₂ report hreport view₁ hread₁ view₂ hread₂
229
+ B fuel₁ fuel₂ controlFuel (start s₁ s₂ a) ⟨hsort₁, hsort₂, hcap₁, hcap₂⟩
230
+ have hq := h.2.1
231
+ have hr := h.2.2.1
232
+ have hc := h.2.2.2
233
+ dsimp only [queryAccount, reportAccount, copyAccount, rank, potential, start] at hq hr hc
234
+ simp only [Bool.false_eq_true, ite_false, Nat.zero_add, Nat.mul_zero] at hq hr hc
235
+ dsimp only [run, start]
236
+ omega
237
+
238
+ end StreamJoin
239
+ end LowSpaceSubsetSum
240
+
241
+ end OAI
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/StreamJoinCorrectness.lean ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import OAI.Combinatorics.LowSpaceSubsetSum.Streams.StreamJoinBounds
2
+ import OAI.Combinatorics.LowSpaceSubsetSum.Counting.MatchFold
3
+
4
+ namespace OAI
5
+
6
+ /-! Exact callback semantics of the finite-state global join. -/
7
+
8
+ namespace LowSpaceSubsetSum
9
+ namespace StreamJoin
10
+
11
+ universe u v s t w
12
+ variable {α : Type u} {β : Type v} {σ₁ : Type s} {σ₂ : Type t} {τ : Type w}
13
+
14
+ def semanticAccount (key₁ : α → ℤ) (key₂ : β → ℤ)
15
+ (report : α → β → τ → τ × Bool) (view₁ : σ₁ → List α) (view₂ : σ₂ → List β)
16
+ (st : State σ₁ σ₂ τ) : τ := MatchFold.run key₁ key₂ report (view₁ st.left) (view₂ st.right) st.user
17
+
18
+ theorem step_semantics (read₁ : σ₁ → Option (α × σ₁)) (key₁ : α → ℤ)
19
+ (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ)
20
+ (report : α → β → τ → τ × Bool) (hreport : ∀ x y a, (report x y a).2 = false)
21
+ (view₁ : σ₁ → List α) (hread₁ : RowMerge.IsReader read₁ view₁)
22
+ (view₂ : σ₂ → List β) (hread₂ : RowMerge.IsReader read₂ view₂)
23
+ (B fuel₁ fuel₂ : ℕ) (st : State σ₁ σ₂ τ)
24
+ (hst : WellFormed key₁ key₂ view₁ view₂ fuel₁ fuel₂ st) :
25
+ semanticAccount key₁ key₂ report view₁ view₂
26
+ (step read₁ key₁ read₂ key₂ report B fuel₁ fuel₂ st) =
27
+ semanticAccount key₁ key₂ report view₁ view₂ st := by
28
+ by_cases hd : st.done = true
29
+ · rw [step_done _ _ _ _ _ _ _ _ st hd]
30
+ have hdf := Bool.eq_false_iff.mpr hd
31
+ cases hx : read₁ st.left with
32
+ | none =>
33
+ have hv : view₁ st.left = [] := by simpa only [hx] using hread₁ st.left
34
+ simp only [step, hdf, Bool.false_eq_true, ite_false, hx, semanticAccount, hv, MatchFold.run]
35
+ | some xp =>
36
+ rcases xp with ⟨x, left'⟩
37
+ have hv₁ : view₁ st.left = x :: view₁ left' := by simpa only [hx] using hread₁ st.left
38
+ cases hy : read₂ st.right with
39
+ | none =>
40
+ have hv : view₂ st.right = [] := by simpa only [hy] using hread₂ st.right
41
+ simp only [step, hdf, Bool.false_eq_true, ite_false, hx, hy, semanticAccount, hv,
42
+ MatchFold.nil_right]
43
+ | some yp =>
44
+ rcases yp with ⟨y, right'⟩
45
+ have hv₂ : view₂ st.right = y :: view₂ right' := by simpa only [hy] using hread₂ st.right
46
+ by_cases hxy : key₁ x < key₂ y
47
+ · have hlower₂ : ∀ z ∈ view₂ st.right, key₂ y ≤ key₂ z := by
48
+ rw [hv₂]
49
+ exact MatchPotential.lower_bound_head key₂ y _ (by simpa only [hv₂] using hst.2.1)
50
+ simp only [step, hdf, Bool.false_eq_true, ite_false, hx, hy, ite_eq_left hxy, semanticAccount]
51
+ rw [hv₁]
52
+ exact (MatchFold.skip_left key₁ key₂ report x _ _ st.user
53
+ (fun z hz => hxy.trans_le (hlower₂ z hz))).symm
54
+ · by_cases hyx : key₂ y < key₁ x
55
+ · have hlower₁ : ∀ z ∈ view₁ st.left, key₁ x ≤ key₁ z := by
56
+ rw [hv₁]
57
+ exact MatchPotential.lower_bound_head key₁ x _ (by simpa only [hv₁] using hst.1)
58
+ simp only [step, hdf, Bool.false_eq_true, ite_false, hx, hy,
59
+ ite_eq_right hxy, ite_eq_left hyx, semanticAccount]
60
+ rw [hv₂]
61
+ exact (MatchFold.skip_right key₁ key₂ report _ y _ st.user
62
+ (fun z hz => hyx.trans_le (hlower₁ z hz))).symm
63
+ · have hkey : key₁ x = key₂ y := by omega
64
+ let out := TieGroup.run read₁ key₁ read₂ key₂ (key₁ x) report B fuel₁ fuel₂
65
+ st.left st.right st.user
66
+ let G₁ := TieBuffer.groupView key₁ (key₁ x) view₁ st.left
67
+ let G₂ := TieBuffer.groupView key₂ (key₁ x) view₂ st.right
68
+ have hg₁ : G₁ ≠ [] := by simp [G₁, TieBuffer.groupView, hv₁]
69
+ have hcap₁ : G₁.length ≤ fuel₁ :=
70
+ (List.takeWhile_sublist _).length_le.trans hst.2.2.1
71
+ have hcap₂ : G₂.length ≤ fuel₂ :=
72
+ (List.takeWhile_sublist _).length_le.trans hst.2.2.2
73
+ have hviews := TieGroup.views_complete read₁ key₁ read₂ key₂ (key₁ x) report hreport
74
+ view₁ hread₁ view₂ hread₂ B fuel₁ fuel₂ st.left st.right st.user hcap₁ hcap₂ hg₁
75
+ change view₁ st.left = G₁ ++ view₁ out.outer.cursor ∧
76
+ view₂ st.right = G₂ ++ view₂ out.outer.state.last at hviews
77
+ have hlower₁ : ∀ z ∈ view₁ st.left, key₁ x ≤ key₁ z := by
78
+ rw [hv₁]
79
+ exact MatchPotential.lower_bound_head key₁ x _ (by simpa only [hv₁] using hst.1)
80
+ have hlower₂ : ∀ z ∈ view₂ st.right, key₁ x ≤ key₂ z := by
81
+ rw [hkey, hv₂]
82
+ exact MatchPotential.lower_bound_head key₂ y _ (by simpa only [hv₂] using hst.2.1)
83
+ have hr₁ := MatchPotential.remaining_avoids key₁ (key₁ x) _ _ hviews.1 hst.1 hlower₁
84
+ have hr₂ := MatchPotential.remaining_avoids key₂ (key₁ x) _ _ hviews.2 hst.2.1 hlower₂
85
+ have hG₁ : ∀ z ∈ G₁, key₁ z = key₁ x := by
86
+ intro z hz
87
+ exact of_decide_eq_true (List.mem_takeWhile_imp (p := fun z => decide (key₁ z = key₁ x)) hz)
88
+ have hG₂ : ∀ z ∈ G₂, key₂ z = key₁ x := by
89
+ intro z hz
90
+ exact of_decide_eq_true (List.mem_takeWhile_imp (p := fun z => decide (key₂ z = key₁ x)) hz)
91
+ have hsplit := MatchFold.split_groups key₁ key₂ report (key₁ x) G₁
92
+ (view₁ out.outer.cursor) G₂ (view₂ out.outer.state.last) st.user hG₁ hG₂ hr₁ hr₂
93
+ rw [← hviews.1, ← hviews.2] at hsplit
94
+ have hstate := TieGroup.state_complete read₁ key₁ read₂ key₂ (key₁ x) report hreport
95
+ view₁ hread₁ view₂ hread₂ B fuel₁ fuel₂ st.left st.right st.user hcap₁ hcap₂
96
+ rw [← hstate] at hsplit
97
+ simp only [step, hdf, Bool.false_eq_true, ite_false, hx, hy,
98
+ ite_eq_right hxy, ite_eq_right hyx, semanticAccount]
99
+ exact hsplit.symm
100
+
101
+ theorem runAcc_semantics (read₁ : σ₁ → Option (α × σ₁)) (key₁ : α → ℤ)
102
+ (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ)
103
+ (report : α → β → τ → τ × Bool) (hreport : ∀ x y a, (report x y a).2 = false)
104
+ (view₁ : σ₁ → List α) (hread₁ : RowMerge.IsReader read₁ view₁)
105
+ (view₂ : σ₂ → List β) (hread₂ : RowMerge.IsReader read₂ view₂)
106
+ (B fuel₁ fuel₂ controlFuel : ℕ) (st : State σ₁ σ₂ τ)
107
+ (hst : WellFormed key₁ key₂ view₁ view₂ fuel₁ fuel₂ st) :
108
+ semanticAccount key₁ key₂ report view₁ view₂
109
+ (runAcc read₁ key₁ read₂ key₂ report B fuel₁ fuel₂ controlFuel st) =
110
+ semanticAccount key₁ key₂ report view₁ view₂ st := by
111
+ induction controlFuel generalizing st with
112
+ | zero => rfl
113
+ | succ controlFuel ih =>
114
+ rw [runAcc, ih _ (step_accounts read₁ key₁ read₂ key₂ report hreport view₁ hread₁
115
+ view₂ hread₂ B fuel₁ fuel₂ st hst).1]
116
+ exact step_semantics read₁ key₁ read₂ key₂ report hreport view₁ hread₁ view₂ hread₂ B fuel₁ fuel₂ st hst
117
+
118
+ def DoneEmpty (view₁ : σ₁ → List α) (view₂ : σ₂ → List β) (st : State σ₁ σ₂ τ) : Prop :=
119
+ st.done = true → view₁ st.left = [] ∨ view₂ st.right = []
120
+
121
+ theorem step_doneEmpty (read₁ : σ₁ → Option (α × σ₁)) (key₁ : α → ℤ)
122
+ (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ)
123
+ (report : α → β → τ → τ × Bool) (hreport : ∀ x y a, (report x y a).2 = false)
124
+ (view₁ : σ₁ → List α) (hread₁ : RowMerge.IsReader read₁ view₁)
125
+ (view₂ : σ₂ → List β) (hread₂ : RowMerge.IsReader read₂ view₂)
126
+ (B fuel₁ fuel₂ : ℕ) (st : State σ₁ σ₂ τ) (hst : DoneEmpty view₁ view₂ st) :
127
+ DoneEmpty view₁ view₂ (step read₁ key₁ read₂ key₂ report B fuel₁ fuel₂ st) := by
128
+ by_cases hd : st.done = true
129
+ · rw [step_done _ _ _ _ _ _ _ _ st hd]
130
+ exact hst
131
+ have hdf := Bool.eq_false_iff.mpr hd
132
+ cases hx : read₁ st.left with
133
+ | none =>
134
+ have hv : view₁ st.left = [] := by simpa only [hx] using hread₁ st.left
135
+ simp only [DoneEmpty, step, hdf, Bool.false_eq_true, ite_false, hx]
136
+ exact fun _ => Or.inl hv
137
+ | some xp =>
138
+ rcases xp with ⟨x, left'⟩
139
+ cases hy : read₂ st.right with
140
+ | none =>
141
+ have hv : view₂ st.right = [] := by simpa only [hy] using hread₂ st.right
142
+ simp only [DoneEmpty, step, hdf, Bool.false_eq_true, ite_false, hx, hy]
143
+ exact fun _ => Or.inr hv
144
+ | some yp =>
145
+ rcases yp with ⟨y, right'⟩
146
+ by_cases hxy : key₁ x < key₂ y
147
+ · simp only [DoneEmpty, step, hdf, Bool.false_eq_true, ite_false, hx, hy, ite_eq_left hxy,
148
+ false_implies]
149
+ · by_cases hyx : key₂ y < key₁ x
150
+ · simp only [DoneEmpty, step, hdf, Bool.false_eq_true, ite_false, hx, hy,
151
+ ite_eq_right hxy, ite_eq_left hyx, false_implies]
152
+ · have hhalt := TieGroup.halted_false read₁ key₁ read₂ key₂ (key₁ x) report hreport
153
+ B fuel₁ fuel₂ st.left st.right st.user
154
+ simp only [DoneEmpty, step, hdf, Bool.false_eq_true, ite_false, hx, hy,
155
+ ite_eq_right hxy, ite_eq_right hyx, hhalt, false_implies]
156
+
157
+ theorem runAcc_doneEmpty (read₁ : σ₁ → Option (α × σ₁)) (key₁ : α → ℤ)
158
+ (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ)
159
+ (report : α → β → τ → τ × Bool) (hreport : ∀ x y a, (report x y a).2 = false)
160
+ (view₁ : σ₁ → List α) (hread₁ : RowMerge.IsReader read₁ view₁)
161
+ (view₂ : σ₂ → List β) (hread₂ : RowMerge.IsReader read₂ view₂)
162
+ (B fuel₁ fuel₂ controlFuel : ℕ) (st : State σ₁ σ₂ τ) (hst : DoneEmpty view₁ view₂ st) :
163
+ DoneEmpty view₁ view₂ (runAcc read₁ key₁ read₂ key₂ report B fuel₁ fuel₂ controlFuel st) := by
164
+ induction controlFuel generalizing st with
165
+ | zero => exact hst
166
+ | succ controlFuel ih =>
167
+ exact ih _ (step_doneEmpty read₁ key₁ read₂ key₂ report hreport
168
+ view₁ hread₁ view₂ hread₂ B fuel₁ fuel₂ st hst)
169
+
170
+ /-- Enough control fuel gives the exact Cartesian-match fold. Occurrences
171
+ with identical fields are still processed separately in this equation. -/
172
+ theorem run_complete (read₁ : σ₁ → Option (α × σ₁)) (key₁ : α → ℤ)
173
+ (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ)
174
+ (report : α → β → τ → τ × Bool) (hreport : ∀ x y a, (report x y a).2 = false)
175
+ (view₁ : σ₁ → List α) (hread₁ : RowMerge.IsReader read₁ view₁)
176
+ (view₂ : σ₂ → List β) (hread₂ : RowMerge.IsReader read₂ view₂)
177
+ (B fuel₁ fuel₂ controlFuel : ℕ) (s₁ : σ₁) (s₂ : σ₂) (a : τ)
178
+ (hsort₁ : (view₁ s₁).Pairwise (fun x y => key₁ x ≤ key₁ y))
179
+ (hsort₂ : (view₂ s₂).Pairwise (fun x y => key₂ x ≤ key₂ y))
180
+ (hcap₁ : (view₁ s₁).length ≤ fuel₁) (hcap₂ : (view₂ s₂).length ≤ fuel₂)
181
+ (hfuel : (view₁ s₁).length + (view₂ s₂).length < controlFuel) :
182
+ (run read₁ key₁ read₂ key₂ report B fuel₁ fuel₂ controlFuel s₁ s₂ a).user =
183
+ MatchFold.run key₁ key₂ report (view₁ s₁) (view₂ s₂) a := by
184
+ have hw : WellFormed key₁ key₂ view₁ view₂ fuel₁ fuel₂ (start s₁ s₂ a) :=
185
+ ⟨hsort₁, hsort₂, hcap₁, hcap₂⟩
186
+ have ht := runAcc_terminates read₁ key₁ read₂ key₂ report hreport view₁ hread₁ view₂ hread₂
187
+ B fuel₁ fuel₂ controlFuel (start s₁ s₂ a) hw hfuel
188
+ have he := runAcc_doneEmpty read₁ key₁ read₂ key₂ report hreport view₁ hread₁ view₂ hread₂
189
+ B fuel₁ fuel₂ controlFuel (start s₁ s₂ a) (by simp [DoneEmpty, start])
190
+ have hs := runAcc_semantics read₁ key₁ read₂ key₂ report hreport view₁ hread₁ view₂ hread₂
191
+ B fuel₁ fuel₂ controlFuel (start s₁ s₂ a) hw
192
+ rcases he ht with hleft | hright
193
+ · dsimp only [semanticAccount] at hs
194
+ rw [hleft] at hs
195
+ exact hs
196
+ · dsimp only [semanticAccount] at hs
197
+ rw [hright, MatchFold.nil_right] at hs
198
+ exact hs
199
+
200
+ end StreamJoin
201
+ end LowSpaceSubsetSum
202
+
203
+ end OAI
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/StreamPrimitiveWork.lean ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import OAI.Combinatorics.LowSpaceSubsetSum.Streams.BinaryPivot
2
+ import OAI.Combinatorics.LowSpaceSubsetSum.Streams.CountedSort
3
+ import OAI.Combinatorics.LowSpaceSubsetSum.Representation.RepresentationLeafSpace
4
+
5
+ namespace OAI
6
+
7
+ /-! # Counted binary searches and residue sorting
8
+
9
+ The counted routines follow the same branches as the executable
10
+ search and sort. Their first components agree exactly with those routines.
11
+ The counters charge predicate calls and merge/split operations, respectively;
12
+ word arithmetic and mask access still require separate compilation charges.
13
+ -/
14
+
15
+ namespace LowSpaceSubsetSum
16
+
17
+ namespace BinaryPivot
18
+
19
+ def counted {n : ℕ} (p : Fin n → Bool) : ℕ → Cut n → Cut n × ℕ
20
+ | 0, c => (c, 0)
21
+ | k + 1, c =>
22
+ let queried := if c.lo < c.hi then 1 else 0
23
+ let rest := counted p k (step p c)
24
+ (rest.1, queried + rest.2)
25
+
26
+ theorem counted_value {n : ℕ} (p : Fin n → Bool) (k : ℕ) (c : Cut n) :
27
+ (counted p k c).1 = (step p)^[k] c := by
28
+ induction k generalizing c with
29
+ | zero => rfl
30
+ | succ k ih => simpa only [counted, Function.iterate_succ_apply] using ih (step p c)
31
+
32
+ theorem counted_queries {n : ℕ} (p : Fin n → Bool) (k : ℕ) (c : Cut n) :
33
+ (counted p k c).2 ≤ k := by
34
+ induction k generalizing c with
35
+ | zero => rfl
36
+ | succ k ih =>
37
+ have h := ih (step p c)
38
+ simp only [counted]
39
+ split <;> omega
40
+
41
+ def countedSearch {n : ℕ} (p : Fin n → Bool) (k : ℕ) : Cut n × ℕ :=
42
+ counted p k (initial n)
43
+
44
+ theorem countedSearch_value {n : ℕ} (p : Fin n → Bool) (k : ℕ) :
45
+ (countedSearch p k).1 = search p k := counted_value p k (initial n)
46
+
47
+ theorem countedSearch_queries {n : ℕ} (p : Fin n → Bool) (k : ℕ) :
48
+ (countedSearch p k).2 ≤ k := counted_queries p k (initial n)
49
+
50
+ end BinaryPivot
51
+
52
+ namespace ResidueSort
53
+
54
+ variable {α : Type*}
55
+
56
+ def counted (xs : Array α) (w : α → ℤ) (p P : ℤ) : Array α × ℕ :=
57
+ let r := CountedSort.sort (fun x y => decide (relation w p P x y)) xs.toList
58
+ (r.1.toArray, r.2)
59
+
60
+ theorem counted_value (xs : Array α) (w : α → ℤ) (p P : ℤ) :
61
+ (counted xs w p P).1 = sort xs w p P := by
62
+ simp only [counted, CountedSort.sort_value, sort]
63
+
64
+ theorem counted_work (xs : Array α) (w : α → ℤ) (p P : ℤ) (n : ℕ)
65
+ (hn : xs.size ≤ 2 ^ n) :
66
+ (counted xs w p P).2 ≤ (6 * n + 1) * xs.size + 1 := by
67
+ exact CountedSort.sort_steps_of_index_bits _ xs.toList n (by simpa using hn)
68
+
69
+ end ResidueSort
70
+
71
+ namespace RepresentationPairData
72
+
73
+ variable {n : ℕ} (D : RepresentationPairData n)
74
+
75
+ theorem counted_sort_value :
76
+ (ResidueSort.counted D.rightArray D.wl D.lowModulus D.modulus).1 = D.storedRight :=
77
+ ResidueSort.counted_value _ _ _ _
78
+
79
+ theorem counted_sort_work (hR : D.rightArray.size ≤ 2 ^ n) :
80
+ (ResidueSort.counted D.rightArray D.wl D.lowModulus D.modulus).2 ≤
81
+ (6 * n + 1) * D.right.occurrences.card + 1 := by
82
+ exact (ResidueSort.counted_work _ _ _ _ n hR).trans
83
+ (Nat.add_le_add_right (Nat.mul_le_mul_left _ D.rightArray_size_le) 1)
84
+
85
+ theorem any_state_comparisons (hL : D.leftArray.size ≤ 2 ^ n) (s : D.State) :
86
+ MergedReader.advanceComparisons
87
+ (FilteredStream.key D.wl D.wl D.modulus D.mode)
88
+ (FilteredStream.view D.storedRight) s ≤ n :=
89
+ (D.reader_comparisons_le s).trans (Nat.clog_le_of_le_pow hL)
90
+
91
+ end RepresentationPairData
92
+ end LowSpaceSubsetSum
93
+
94
+ end OAI
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/StreamWitness.lean ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import OAI.Combinatorics.LowSpaceSubsetSum.Streams.StreamJoinCorrectness
2
+
3
+ namespace OAI
4
+
5
+ /-! A concrete Boolean match collector for the finite-state stream join. -/
6
+
7
+ namespace LowSpaceSubsetSum
8
+ namespace StreamWitness
9
+
10
+ universe u v
11
+ variable {α : Type u} {β : Type v}
12
+
13
+ def remember (hit : α → β → Bool) (x : α) (y : β) (a : Bool) : Bool × Bool :=
14
+ (a || hit x y, false)
15
+
16
+ theorem foldl_remember (hit : α → β → Bool) (x : α) (ys : List β) (a : Bool) :
17
+ ys.foldl (fun a y => (remember hit x y a).1) a = true ↔
18
+ a = true ∨ ∃ y ∈ ys, hit x y = true := by
19
+ induction ys generalizing a with
20
+ | nil => simp
21
+ | cons y ys ih =>
22
+ rw [List.foldl_cons, ih]
23
+ simp only [remember, Bool.or_eq_true, List.mem_cons]
24
+ aesop
25
+
26
+ theorem matchFold_iff (key₁ : α → ℤ) (key₂ : β → ℤ) (hit : α → β → Bool)
27
+ (xs : List α) (ys : List β) (a : Bool) :
28
+ MatchFold.run key₁ key₂ (remember hit) xs ys a = true ↔
29
+ a = true ∨ ∃ x ∈ xs, ∃ y ∈ ys, key₁ x = key₂ y ∧ hit x y = true := by
30
+ induction xs generalizing a with
31
+ | nil => simp [MatchFold.run]
32
+ | cons x xs ih =>
33
+ rw [MatchFold.run, ih, foldl_remember]
34
+ simp only [List.mem_cons, List.mem_filter, decide_eq_true_eq]
35
+ aesop
36
+
37
+ theorem matchFold_true (key₁ : α → ℤ) (key₂ : β → ℤ) (hit : α → β → Bool)
38
+ (xs : List α) (ys : List β) :
39
+ MatchFold.run key₁ key₂ (remember hit) xs ys true = true :=
40
+ (matchFold_iff key₁ key₂ hit xs ys true).mpr (Or.inl rfl)
41
+
42
+ /-- The actual finite-state join finds exactly the matching occurrences
43
+ accepted by its pair predicate. The callback retains one Boolean word. -/
44
+ theorem run_iff {σ₁ σ₂ : Type*}
45
+ (read₁ : σ₁ → Option (α × σ₁)) (key₁ : α → ℤ)
46
+ (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ) (hit : α → β → Bool)
47
+ (view₁ : σ₁ → List α) (hread₁ : RowMerge.IsReader read₁ view₁)
48
+ (view₂ : σ₂ → List β) (hread₂ : RowMerge.IsReader read₂ view₂)
49
+ (B fuel₁ fuel₂ controlFuel : ℕ) (s₁ : σ₁) (s₂ : σ₂)
50
+ (hsort₁ : (view₁ s₁).Pairwise (fun x y => key₁ x ≤ key₁ y))
51
+ (hsort₂ : (view₂ s₂).Pairwise (fun x y => key₂ x ≤ key₂ y))
52
+ (hcap₁ : (view₁ s₁).length ≤ fuel₁) (hcap₂ : (view₂ s₂).length ≤ fuel₂)
53
+ (hfuel : (view₁ s₁).length + (view₂ s₂).length < controlFuel) :
54
+ (StreamJoin.run read₁ key₁ read₂ key₂ (remember hit) B fuel₁ fuel₂ controlFuel s₁ s₂ false).user = true ↔
55
+ ∃ x ∈ view₁ s₁, ∃ y ∈ view₂ s₂, key₁ x = key₂ y ∧ hit x y = true := by
56
+ rw [StreamJoin.run_complete read₁ key₁ read₂ key₂ (remember hit) (fun _ _ _ => rfl)
57
+ view₁ hread₁ view₂ hread₂ B fuel₁ fuel₂ controlFuel s₁ s₂ false
58
+ hsort₁ hsort₂ hcap₁ hcap₂ hfuel, matchFold_iff]
59
+ simp
60
+
61
+ /-- An arbitrary stopped control prefix also has one-sided soundness. -/
62
+ theorem stopped_sound {σ₁ σ₂ : Type*}
63
+ (read₁ : σ₁ → Option (α × σ₁)) (key₁ : α → ℤ)
64
+ (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ) (hit : α → β → Bool)
65
+ (view₁ : σ₁ → List α) (hread₁ : RowMerge.IsReader read₁ view₁)
66
+ (view₂ : σ₂ → List β) (hread₂ : RowMerge.IsReader read₂ view₂)
67
+ (B fuel₁ fuel₂ controlFuel : ℕ) (s₁ : σ₁) (s₂ : σ₂)
68
+ (hsort₁ : (view₁ s₁).Pairwise (fun x y => key₁ x ≤ key₁ y))
69
+ (hsort₂ : (view₂ s₂).Pairwise (fun x y => key₂ x ≤ key₂ y))
70
+ (hcap₁ : (view₁ s₁).length ≤ fuel₁) (hcap₂ : (view₂ s₂).length ≤ fuel₂)
71
+ (hyes : (StreamJoin.run read₁ key₁ read₂ key₂ (remember hit) B fuel₁ fuel₂
72
+ controlFuel s₁ s₂ false).user = true) :
73
+ ∃ x ∈ view₁ s₁, ∃ y ∈ view₂ s₂, key₁ x = key₂ y ∧ hit x y = true := by
74
+ let out := StreamJoin.run read₁ key₁ read₂ key₂ (remember hit) B fuel₁ fuel₂ controlFuel s₁ s₂ false
75
+ have hs := StreamJoin.runAcc_semantics read₁ key₁ read₂ key₂ (remember hit) (fun _ _ _ => rfl)
76
+ view₁ hread₁ view₂ hread₂ B fuel₁ fuel₂ controlFuel (StreamJoin.start s₁ s₂ false)
77
+ ⟨hsort₁, hsort₂, hcap₁, hcap₂⟩
78
+ change MatchFold.run key₁ key₂ (remember hit) (view₁ out.left) (view₂ out.right) out.user =
79
+ MatchFold.run key₁ key₂ (remember hit) (view₁ s₁) (view₂ s₂) false at hs
80
+ have ht : MatchFold.run key₁ key₂ (remember hit) (view₁ s₁) (view₂ s₂) false = true := by
81
+ rw [← hs, hyes]
82
+ exact matchFold_true key₁ key₂ hit _ _
83
+ exact (matchFold_iff key₁ key₂ hit _ _ false).mp ht |>.resolve_left (by decide)
84
+
85
+ end StreamWitness
86
+ end LowSpaceSubsetSum
87
+
88
+ end OAI
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/SumReader.lean ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import OAI.Combinatorics.LowSpaceSubsetSum.Streams.PaddedRows
2
+ import OAI.Combinatorics.LowSpaceSubsetSum.Streams.DistinctStreamCount
3
+ import OAI.Combinatorics.LowSpaceSubsetSum.Compression.CompressionDictionary
4
+
5
+ namespace OAI
6
+
7
+ /-! # Counting a mixer through a tournament of ordinary sum rows
8
+
9
+ Only the two half-mixer arrays and a tournament of constant-size cursors
10
+ are stored. The output lists in the proofs are views, not runtime fields.
11
+ Sorting and counting use integer sums and require no modulus or real oracle.
12
+ -/
13
+
14
+ namespace LowSpaceSubsetSum.SumReader
15
+
16
+ open scoped BigOperators
17
+
18
+ structure Row where
19
+ left : ℤ
20
+ position : ℕ
21
+
22
+ def read (ys : Array ℤ) (s : Row) : Option ((ℤ × ℤ) × Row) :=
23
+ if h : s.position < ys.size then
24
+ some ((s.left, ys[s.position]), ⟨s.left, s.position + 1⟩)
25
+ else none
26
+
27
+ def view (ys : Array ℤ) (s : Row) : List (ℤ × ℤ) :=
28
+ (ys.toList.drop s.position).map (fun y => (s.left, y))
29
+
30
+ theorem reader (ys : Array ℤ) : RowMerge.IsReader (read ys) (view ys) := by
31
+ intro s
32
+ by_cases h : s.position < ys.size
33
+ · have hlist : s.position < ys.toList.length := by simpa using h
34
+ simp only [read, dite_eq_left h, view]
35
+ rw [List.drop_eq_getElem_cons hlist, List.map_cons]
36
+ rfl
37
+ · have he : ys.toList.drop s.position = [] := List.drop_eq_nil_iff.mpr (by simpa using Nat.le_of_not_gt h)
38
+ simp [read, h, view, he]
39
+
40
+ def key (p : ℤ × ℤ) : ℤ := p.1 + p.2
41
+
42
+ def rows (xs : Array ℤ) : Array Row := xs.map (fun x => ⟨x, 0⟩)
43
+
44
+ theorem row_sorted (ys : Array ℤ) (hs : ys.toList.Pairwise (· ≤ ·)) (s : Row) :
45
+ (view ys s).Pairwise (fun x y => key x ≤ key y) := by
46
+ rw [view, List.pairwise_map]
47
+ exact (hs.sublist (List.drop_sublist s.position ys.toList)).imp
48
+ (fun h => by dsimp only [key]; omega)
49
+
50
+ abbrev State (xs ys : Array ℤ) :=
51
+ MergedReader.State key (PaddedRows.view (view ys)) (Nat.clog 2 xs.size)
52
+
53
+ def start (xs ys : Array ℤ) (hs : ys.toList.Pairwise (· ≤ ·)) : State xs ys :=
54
+ MergedReader.start key (PaddedRows.next (read ys)) (PaddedRows.view (view ys))
55
+ (PaddedRows.reader _ _ (reader ys))
56
+ (PaddedRows.rows (rows xs) (Nat.clog 2 xs.size))
57
+ (PaddedRows.rows_sorted _ _ _ key (fun s _ => row_sorted ys hs s))
58
+
59
+ def next (xs ys : Array ℤ) : State xs ys → Option ((ℤ × ℤ) × State xs ys) :=
60
+ MergedReader.next key (PaddedRows.next (read ys)) (PaddedRows.view (view ys))
61
+ (PaddedRows.reader _ _ (reader ys))
62
+
63
+ def output (xs ys : Array ℤ) : State xs ys → List (ℤ × ℤ) :=
64
+ MergedReader.output key (PaddedRows.next (read ys)) (PaddedRows.view (view ys))
65
+
66
+ theorem next_law (xs ys : Array ℤ) : RowMerge.IsReader (next xs ys) (output xs ys) :=
67
+ MergedReader.reader _ _ _ (PaddedRows.reader _ _ (reader ys))
68
+
69
+ theorem output_sorted (xs ys : Array ℤ) (s : State xs ys) :
70
+ ((output xs ys s).map key).Pairwise (· ≤ ·) := by
71
+ rw [List.pairwise_map]
72
+ exact MergedReader.output_sorted _ _ _ (PaddedRows.reader _ _ (reader ys)) s
73
+
74
+ theorem start_bag (xs ys : Array ℤ) (hs : ys.toList.Pairwise (· ≤ ·)) :
75
+ (output xs ys (start xs ys hs) : Multiset (ℤ × ℤ)) =
76
+ ∑ i : Fin xs.size, ((ys.toList.map (fun y => (xs[i.val], y))) : Multiset (ℤ × ℤ)) := by
77
+ rw [output, start, MergedReader.start_output_bag]
78
+ calc
79
+ _ = ∑ i : Fin (rows xs).size, (view ys (rows xs)[i.val] : Multiset (ℤ × ℤ)) :=
80
+ PaddedRows.row_bag (rows xs) (Nat.clog 2 xs.size)
81
+ (by simpa [rows] using Nat.le_pow_clog (by decide : 1 < 2) xs.size) (view ys)
82
+ _ = _ := by
83
+ apply Fintype.sum_equiv (finCongr (show (rows xs).size = xs.size by simp [rows]))
84
+ intro i
85
+ simp only [rows, Array.getElem_map, view, List.drop_zero]
86
+ rfl
87
+
88
+ theorem output_mem (xs ys : Array ℤ) (hs : ys.toList.Pairwise (· ≤ ·)) (p : ℤ × ℤ) :
89
+ p ∈ output xs ys (start xs ys hs) ↔ p.1 ∈ xs.toList ∧ p.2 ∈ ys.toList := by
90
+ change p ∈ (output xs ys (start xs ys hs) : Multiset (ℤ × ℤ)) ↔ _
91
+ rw [start_bag, Multiset.mem_sum]
92
+ simp only [Finset.mem_univ, true_and, Multiset.mem_coe, List.mem_map]
93
+ constructor
94
+ · rintro ⟨i, y, hy, he⟩
95
+ obtain rfl := he
96
+ exact ⟨List.mem_iff_getElem.mpr ⟨i.val, by simpa only [Array.length_toList] using i.isLt, by simp⟩, hy⟩
97
+ · rintro ⟨hx, hy⟩
98
+ obtain ⟨i, hi, he⟩ := List.mem_iff_getElem.mp hx
99
+ refine ⟨⟨i, by simpa using hi⟩, p.2, hy, ?_⟩
100
+ simpa using congrArg (fun x => (x, p.2)) he
101
+
102
+ theorem output_length (xs ys : Array ℤ) (hs : ys.toList.Pairwise (· ≤ ·)) :
103
+ (output xs ys (start xs ys hs)).length = xs.size * ys.size := by
104
+ have h := congrArg Multiset.card (start_bag xs ys hs)
105
+ simpa only [Multiset.coe_card, Multiset.card_sum, List.length_map,
106
+ Array.length_toList, Finset.sum_const, Finset.card_univ, Fintype.card_fin, smul_eq_mul] using h
107
+
108
+ def count (xs ys : Array ℤ) (hs : ys.toList.Pairwise (· ≤ ·)) : ℕ × ℕ :=
109
+ DistinctStreamCount.run (next xs ys) key (xs.size * ys.size) (start xs ys hs)
110
+
111
+ theorem count_value (xs ys : Array ℤ) (hs : ys.toList.Pairwise (· ≤ ·)) :
112
+ (count xs ys hs).1 = ((output xs ys (start xs ys hs)).map key).toFinset.card :=
113
+ DistinctStreamCount.run_value _ _ _ (next_law xs ys) _ _
114
+ (le_of_eq (output_length xs ys hs)) (output_sorted xs ys _)
115
+
116
+ theorem count_queries (xs ys : Array ℤ) (hs : ys.toList.Pairwise (· ≤ ·)) :
117
+ (count xs ys hs).2 ≤ xs.size * ys.size := DistinctStreamCount.run_queries _ _ _ _
118
+
119
+ /-- Every cursor and cached front occupies a constant number of flat cells. -/
120
+ def footprint (xs ys : Array ℤ) (s : State xs ys) : ℕ :=
121
+ xs.size + ys.size + 10 * (Tournament.nodes s.tree + 1) + 3
122
+
123
+ theorem footprint_bound (xs ys : Array ℤ) (s : State xs ys) :
124
+ footprint xs ys s ≤ 41 * xs.size + ys.size + 43 := by
125
+ have h := Tournament.padded_nodes_le xs.size s.tree
126
+ unfold footprint
127
+ omega
128
+
129
+ end LowSpaceSubsetSum.SumReader
130
+
131
+ end OAI
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/TieBuffer.lean ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import OAI.Combinatorics.LowSpaceSubsetSum.Streams.MergeOrdering
2
+
3
+ namespace OAI
4
+
5
+ /-!
6
+ # A bounded tie-group buffer
7
+
8
+ The tail-recursive collector stores at most the requested number of matching
9
+ occurrences and leaves the first different-key occurrence unconsumed. Its
10
+ instrumented query counter counts every reader call, including the final
11
+ lookahead. No clearing of unused buffer positions is performed.
12
+ -/
13
+
14
+ namespace LowSpaceSubsetSum
15
+ namespace TieBuffer
16
+
17
+ universe u v
18
+
19
+ variable {α : Type u} {σ : Type v}
20
+
21
+ def groupView (key : α → ℤ) (K : ℤ) (view : σ → List α) (s : σ) : List α :=
22
+ (view s).takeWhile (fun a => decide (key a = K))
23
+
24
+ structure Result (α : Type u) (σ : Type v) where
25
+ buffer : Array α
26
+ cursor : σ
27
+ queries : ℕ
28
+
29
+ def fillAcc (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ) :
30
+ ℕ → σ → Array α → ℕ → Result α σ
31
+ | 0, s, buf, q => ⟨buf, s, q⟩
32
+ | k + 1, s, buf, q => match read s with
33
+ | none => ⟨buf, s, q + 1⟩
34
+ | some (a, s') => if key a = K then fillAcc read key K k s' (buf.push a) (q + 1)
35
+ else ⟨buf, s, q + 1⟩
36
+
37
+ def fill (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ) (B : ℕ) (s : σ) :
38
+ Result α σ := fillAcc read key K B s #[] 0
39
+
40
+ theorem fillAcc_spec (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ)
41
+ (view : σ → List α) (hread : RowMerge.IsReader read view)
42
+ (fuel : ℕ) (s : σ) (buf : Array α) (q : ℕ) :
43
+ (fillAcc read key K fuel s buf q).buffer.toList =
44
+ buf.toList ++ (groupView key K view s).take fuel ∧
45
+ view s = (groupView key K view s).take fuel ++
46
+ view (fillAcc read key K fuel s buf q).cursor ∧
47
+ groupView key K view (fillAcc read key K fuel s buf q).cursor =
48
+ (groupView key K view s).drop fuel ∧
49
+ (fillAcc read key K fuel s buf q).queries ≤ q + fuel := by
50
+ induction fuel generalizing s buf q with
51
+ | zero => simp [fillAcc]
52
+ | succ fuel ih =>
53
+ have hr := hread s
54
+ cases h : read s with
55
+ | none =>
56
+ simp only [h] at hr
57
+ simp [fillAcc, h, groupView, hr]
58
+ | some z =>
59
+ rcases z with ⟨a, s'⟩
60
+ simp only [h] at hr
61
+ by_cases ha : key a = K
62
+ · have hg : groupView key K view s = a :: groupView key K view s' := by
63
+ simp [groupView, hr, ha]
64
+ have hi := ih s' (buf.push a) (q + 1)
65
+ simp only [fillAcc, h, ite_eq_left ha]
66
+ refine ⟨?_, ?_, ?_, ?_⟩
67
+ · rw [hi.1, hg]
68
+ simp [List.append_assoc]
69
+ · rw [hr, hi.2.1, hg]
70
+ simp
71
+ · rw [hi.2.2.1, hg]
72
+ simp
73
+ · have := hi.2.2.2
74
+ omega
75
+ · have hg : groupView key K view s = [] := by simp [groupView, hr, ha]
76
+ simp [fillAcc, h, ha, hg]
77
+
78
+ theorem fill_buffer (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ)
79
+ (view : σ → List α) (hread : RowMerge.IsReader read view) (B : ℕ) (s : σ) :
80
+ (fill read key K B s).buffer.toList = (groupView key K view s).take B := by
81
+ simpa [fill] using (fillAcc_spec read key K view hread B s #[] 0).1
82
+
83
+ theorem fill_size_le (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ)
84
+ (view : σ → List α) (hread : RowMerge.IsReader read view) (B : ℕ) (s : σ) :
85
+ (fill read key K B s).buffer.size ≤ B := by
86
+ have h := congrArg List.length (fill_buffer read key K view hread B s)
87
+ simp only [Array.length_toList, List.length_take] at h
88
+ omega
89
+
90
+ theorem fill_suffix (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ)
91
+ (view : σ → List α) (hread : RowMerge.IsReader read view) (B : ℕ) (s : σ) :
92
+ groupView key K view (fill read key K B s).cursor =
93
+ (groupView key K view s).drop B :=
94
+ (fillAcc_spec read key K view hread B s #[] 0).2.2.1
95
+
96
+ theorem fill_queries_le (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ)
97
+ (view : σ → List α) (hread : RowMerge.IsReader read view) (B : ℕ) (s : σ) :
98
+ (fill read key K B s).queries ≤ B := by
99
+ simpa [fill] using (fillAcc_spec read key K view hread B s #[] 0).2.2.2
100
+
101
+ /-- The collector reads each stored occurrence once and performs at most
102
+ one additional lookahead, irrespective of the chosen buffer capacity. -/
103
+ theorem fillAcc_queries_le_potential (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ)
104
+ (view : σ → List α) (hread : RowMerge.IsReader read view)
105
+ (fuel : ℕ) (s : σ) (buf : Array α) (q : ℕ) :
106
+ (fillAcc read key K fuel s buf q).queries ≤
107
+ q + min fuel ((groupView key K view s).length + 1) := by
108
+ induction fuel generalizing s buf q with
109
+ | zero => simp [fillAcc]
110
+ | succ fuel ih =>
111
+ have hr := hread s
112
+ cases h : read s with
113
+ | none =>
114
+ simp only [h] at hr
115
+ simp [fillAcc, h, groupView, hr]
116
+ | some z =>
117
+ rcases z with ⟨x, s'⟩
118
+ simp only [h] at hr
119
+ by_cases hx : key x = K
120
+ · have hg : groupView key K view s = x :: groupView key K view s' := by
121
+ simp [groupView, hr, hx]
122
+ have hi := ih s' (buf.push x) (q + 1)
123
+ simp only [fillAcc, h, ite_eq_left hx, hg, List.length_cons]
124
+ omega
125
+ · have hg : groupView key K view s = [] := by simp [groupView, hr, hx]
126
+ simp [fillAcc, h, hx, hg]
127
+
128
+ theorem fill_queries_le_potential (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ)
129
+ (view : σ → List α) (hread : RowMerge.IsReader read view) (B : ℕ) (s : σ) :
130
+ (fill read key K B s).queries ≤ (groupView key K view s).length + 1 := by
131
+ have h := fillAcc_queries_le_potential read key K view hread B s #[] 0
132
+ simp only [fill, zero_add] at h ⊢
133
+ exact h.trans (Nat.min_le_right _ _)
134
+
135
+ def hasKey (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ) (s : σ) : Bool :=
136
+ match read s with
137
+ | none => false
138
+ | some (a, _) => decide (key a = K)
139
+
140
+ theorem hasKey_iff (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ)
141
+ (view : σ → List α) (hread : RowMerge.IsReader read view) (s : σ) :
142
+ hasKey read key K s = true ↔ groupView key K view s ≠ [] := by
143
+ have hr := hread s
144
+ cases h : read s with
145
+ | none =>
146
+ simp only [h] at hr
147
+ simp [hasKey, h, groupView, hr]
148
+ | some z =>
149
+ rcases z with ⟨a, s'⟩
150
+ simp only [h] at hr
151
+ by_cases ha : key a = K <;> simp [hasKey, h, groupView, hr, ha]
152
+
153
+ /-- A snapshot is needed only if more than `B` second-row occurrences have
154
+ this key. In particular the buffer is full when a snapshot is taken. -/
155
+ theorem long_group_full_buffer (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ)
156
+ (view : σ → List α) (hread : RowMerge.IsReader read view) (B : ℕ) (s : σ)
157
+ (hlong : hasKey read key K (fill read key K B s).cursor = true) :
158
+ B < (groupView key K view s).length ∧ (fill read key K B s).buffer.size = B := by
159
+ have hn := (hasKey_iff read key K view hread _).mp hlong
160
+ rw [fill_suffix read key K view hread B s] at hn
161
+ have hB : B < (groupView key K view s).length := by
162
+ by_contra h
163
+ apply hn
164
+ exact List.drop_eq_nil_of_le (by omega)
165
+ refine ⟨hB, ?_⟩
166
+ have h := congrArg List.length (fill_buffer read key K view hread B s)
167
+ simpa only [Array.length_toList, List.length_take, Nat.min_eq_left hB.le] using h
168
+
169
+ end TieBuffer
170
+ end LowSpaceSubsetSum
171
+
172
+ end OAI
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/TieGroup.lean ADDED
@@ -0,0 +1,298 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import OAI.Combinatorics.LowSpaceSubsetSum.Streams.JoinOne
2
+
3
+ namespace OAI
4
+
5
+ /-!
6
+ # A stopped Cartesian tie-group join
7
+
8
+ A single second-stream prefix buffer and optional suffix snapshot serve every
9
+ first-stream occurrence with this key. Counters charge every attempted report,
10
+ including executions halted inside either part of a replay. Lists occur only
11
+ in the correctness specification.
12
+ -/
13
+
14
+ namespace LowSpaceSubsetSum
15
+ namespace TieGroup
16
+
17
+ universe u v s t w
18
+
19
+ variable {α : Type u} {β : Type v} {σ₁ : Type s} {σ₂ : Type t} {τ : Type w}
20
+
21
+ structure State (σ₂ : Type t) (τ : Type w) where
22
+ last : σ₂
23
+ user : τ
24
+ queries : ℕ
25
+ reports : ℕ
26
+ restores : ℕ
27
+
28
+ def step (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ) (K : ℤ)
29
+ (report : α → β → τ → τ × Bool) (buffer : Array β) (saved : σ₂)
30
+ (long : Bool) (fuel₂ : ℕ) (x : α) (a : State σ₂ τ) : State σ₂ τ × Bool :=
31
+ let out := JoinOne.run read₂ key₂ K (report x) buffer saved long fuel₂ a.user
32
+ (⟨out.cursor, out.state, a.queries + out.queries, a.reports + out.reports,
33
+ a.restores + if long then 1 else 0⟩, out.halted)
34
+
35
+ structure Result (σ₁ : Type s) (σ₂ : Type t) (τ : Type w) where
36
+ outer : TieReplay.Result σ₁ (State σ₂ τ)
37
+ fillQueries : ℕ
38
+ bufferSize : ℕ
39
+ snapshot : Bool
40
+
41
+ def run (read₁ : σ₁ → Option (α × σ₁)) (key₁ : α → ℤ)
42
+ (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ) (K : ℤ)
43
+ (report : α → β → τ → τ × Bool) (B fuel₁ fuel₂ : ℕ)
44
+ (s₁ : σ₁) (s₂ : σ₂) (a : τ) : Result σ₁ σ₂ τ :=
45
+ let filled := TieBuffer.fill read₂ key₂ K B s₂
46
+ let long := TieBuffer.hasKey read₂ key₂ K filled.cursor
47
+ let out := TieReplay.run read₁ key₁ K
48
+ (step read₂ key₂ K report filled.buffer filled.cursor long fuel₂)
49
+ fuel₁ s₁ ⟨filled.cursor, a, 0, 0, 0⟩
50
+ ⟨out, filled.queries, filled.buffer.size, long && TieBuffer.hasKey read₁ key₁ K s₁⟩
51
+
52
+ /-- Bounds on callbacks follow from the actual suffix reporter, not from
53
+ assumed trial or implementation bounds. -/
54
+ theorem step_bounds (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ) (K : ℤ)
55
+ (report : α → β → τ → τ × Bool) (view₂ : σ₂ → List β)
56
+ (hread₂ : RowMerge.IsReader read₂ view₂) (buffer : Array β) (saved : σ₂)
57
+ (long : Bool) (fuel₂ : ℕ) (x : α) (a : State σ₂ τ) :
58
+ (step read₂ key₂ K report buffer saved long fuel₂ x a).1.reports ≤
59
+ a.reports + (buffer.size + (TieBuffer.groupView key₂ K view₂ saved).length) ∧
60
+ (step read₂ key₂ K report buffer saved long fuel₂ x a).1.queries ≤
61
+ a.queries + (buffer.size + (TieBuffer.groupView key₂ K view₂ saved).length + 1) ∧
62
+ (step read₂ key₂ K report buffer saved long fuel₂ x a).1.restores ≤ a.restores + 1 := by
63
+ have hr := JoinOne.reports_le read₂ key₂ K (report x) view₂ hread₂ buffer saved long fuel₂ a.user
64
+ have hq := JoinOne.queries_le read₂ key₂ K (report x) view₂ hread₂ buffer saved long fuel₂ a.user
65
+ dsimp only [step]
66
+ refine ⟨Nat.add_le_add_left hr _, Nat.add_le_add_left hq _, ?_⟩
67
+ split <;> omega
68
+
69
+ theorem run_bounds (read₁ : σ₁ → Option (α × σ₁)) (key₁ : α → ℤ)
70
+ (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ) (K : ℤ)
71
+ (report : α → β → τ → τ × Bool)
72
+ (view₁ : σ₁ → List α) (hread₁ : RowMerge.IsReader read₁ view₁)
73
+ (view₂ : σ₂ → List β) (hread₂ : RowMerge.IsReader read₂ view₂)
74
+ (B fuel₁ fuel₂ : ℕ) (s₁ : σ₁) (s₂ : σ₂) (a : τ) :
75
+ (run read₁ key₁ read₂ key₂ K report B fuel₁ fuel₂ s₁ s₂ a).outer.state.reports ≤
76
+ (TieBuffer.groupView key₁ K view₁ s₁).length *
77
+ (TieBuffer.groupView key₂ K view₂ s₂).length ∧
78
+ (run read₁ key₁ read₂ key₂ K report B fuel₁ fuel₂ s₁ s₂ a).outer.state.queries ≤
79
+ (TieBuffer.groupView key₁ K view₁ s₁).length *
80
+ ((TieBuffer.groupView key₂ K view₂ s₂).length + 1) ∧
81
+ (run read₁ key₁ read₂ key₂ K report B fuel₁ fuel₂ s₁ s₂ a).outer.state.restores ≤
82
+ (TieBuffer.groupView key₁ K view₁ s₁).length := by
83
+ let filled := TieBuffer.fill read₂ key₂ K B s₂
84
+ let long := TieBuffer.hasKey read₂ key₂ K filled.cursor
85
+ let N := (TieBuffer.groupView key₂ K view₂ s₂).length
86
+ let P := fun (st : State σ₂ τ) (r : ℕ) =>
87
+ st.reports ≤ r * N ∧ st.queries ≤ r * (N + 1) ∧ st.restores ≤ r
88
+ have hsplit : filled.buffer.size +
89
+ (TieBuffer.groupView key₂ K view₂ filled.cursor).length = N := by
90
+ have hb := congrArg List.length (TieBuffer.fill_buffer read₂ key₂ K view₂ hread₂ B s₂)
91
+ rw [TieBuffer.fill_suffix read₂ key₂ K view₂ hread₂ B s₂]
92
+ simp only [Array.length_toList, List.length_take] at hb
93
+ simp only [List.length_drop]
94
+ dsimp only [filled, N]
95
+ omega
96
+ have hstep : ∀ x st r, P st r →
97
+ P (step read₂ key₂ K report filled.buffer filled.cursor long fuel₂ x st).1 (r + 1) := by
98
+ intro x st r hr
99
+ have h := step_bounds read₂ key₂ K report view₂ hread₂ filled.buffer filled.cursor long fuel₂ x st
100
+ rw [hsplit] at h
101
+ dsimp only [P] at hr ⊢
102
+ rcases hr with ⟨hr, hq, hc⟩
103
+ rcases h with ⟨hr', hq', hc'⟩
104
+ rw [Nat.add_mul, Nat.add_mul]
105
+ simp only [one_mul]
106
+ exact ⟨hr'.trans (Nat.add_le_add_right hr _), hq'.trans (Nat.add_le_add_right hq _), by omega⟩
107
+ have h := TieReplay.run_preserves read₁ key₁ K
108
+ (step read₂ key₂ K report filled.buffer filled.cursor long fuel₂) P hstep fuel₁ s₁
109
+ ⟨filled.cursor, a, 0, 0, 0⟩ (by simp [P])
110
+ have hr := TieReplay.run_reports_le_potential read₁ key₁ K
111
+ (step read₂ key₂ K report filled.buffer filled.cursor long fuel₂)
112
+ view₁ hread₁ fuel₁ s₁ ⟨filled.cursor, a, 0, 0, 0⟩
113
+ dsimp only [P] at h
114
+ refine ⟨h.1.trans (Nat.mul_le_mul_right N hr),
115
+ h.2.1.trans (Nat.mul_le_mul_right (N + 1) hr), h.2.2.trans hr⟩
116
+
117
+ /-- On a continuing run every occurrence in the Cartesian tie group is
118
+ reported, in first-stream order and then second-stream order. -/
119
+ theorem state_complete (read₁ : σ₁ → Option (α × σ₁)) (key₁ : α → ℤ)
120
+ (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ) (K : ℤ)
121
+ (report : α → β → τ → τ × Bool) (hreport : ∀ x y a, (report x y a).2 = false)
122
+ (view₁ : σ₁ → List α) (hread₁ : RowMerge.IsReader read₁ view₁)
123
+ (view₂ : σ₂ → List β) (hread₂ : RowMerge.IsReader read₂ view₂)
124
+ (B fuel₁ fuel₂ : ℕ) (s₁ : σ₁) (s₂ : σ₂) (a : τ)
125
+ (hfuel₁ : (TieBuffer.groupView key₁ K view₁ s₁).length ≤ fuel₁)
126
+ (hfuel₂ : (TieBuffer.groupView key₂ K view₂ s₂).length ≤ fuel₂) :
127
+ (run read₁ key₁ read₂ key₂ K report B fuel₁ fuel₂ s₁ s₂ a).outer.state.user =
128
+ (TieBuffer.groupView key₁ K view₁ s₁).foldl
129
+ (fun a x => (TieBuffer.groupView key₂ K view₂ s₂).foldl
130
+ (fun a y => (report x y a).1) a) a := by
131
+ let filled := TieBuffer.fill read₂ key₂ K B s₂
132
+ let long := TieBuffer.hasKey read₂ key₂ K filled.cursor
133
+ let f := step read₂ key₂ K report filled.buffer filled.cursor long fuel₂
134
+ have hnonhalt : ∀ x st, (f x st).2 = false := by
135
+ intro x st
136
+ exact JoinOne.halted_false read₂ key₂ K (report x) (hreport x)
137
+ filled.buffer filled.cursor long fuel₂ st.user
138
+ have huser : ∀ x st, (f x st).1.user =
139
+ (TieBuffer.groupView key₂ K view₂ s₂).foldl (fun a y => (report x y a).1) st.user := by
140
+ intro x st
141
+ exact JoinOne.filled_state_complete read₂ key₂ K (report x) (hreport x)
142
+ view₂ hread₂ B fuel₂ s₂ st.user hfuel₂
143
+ have h := TieReplay.run_state_complete read₁ key₁ K f hnonhalt view₁ hread₁ fuel₁ s₁
144
+ (⟨filled.cursor, a, 0, 0, 0⟩ : State σ₂ τ) hfuel₁
145
+ change (TieReplay.run read₁ key₁ K f fuel₁ s₁ _).state.user = _
146
+ rw [h]
147
+ exact (List.foldl_hom State.user (g₁ := fun st x => (f x st).1)
148
+ (fun st x => (huser x st).symm)).symm
149
+
150
+ theorem step_halted_false (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ) (K : ℤ)
151
+ (report : α → β → τ → τ × Bool) (hreport : ∀ x y a, (report x y a).2 = false)
152
+ (buffer : Array β) (saved : σ₂) (long : Bool) (fuel₂ : ℕ) (x : α) (a : State σ₂ τ) :
153
+ (step read₂ key₂ K report buffer saved long fuel₂ x a).2 = false :=
154
+ JoinOne.halted_false read₂ key₂ K (report x) (hreport x) buffer saved long fuel₂ a.user
155
+
156
+ theorem halted_false (read₁ : σ₁ → Option (α × σ₁)) (key₁ : α → ℤ)
157
+ (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ) (K : ℤ)
158
+ (report : α → β → τ → τ × Bool) (hreport : ∀ x y a, (report x y a).2 = false)
159
+ (B fuel₁ fuel₂ : ℕ) (s₁ : σ₁) (s₂ : σ₂) (a : τ) :
160
+ (run read₁ key₁ read₂ key₂ K report B fuel₁ fuel₂ s₁ s₂ a).outer.halted = false :=
161
+ TieReplay.run_halted_false read₁ key₁ K _
162
+ (step_halted_false read₂ key₂ K report hreport _ _ _ _) _ _ _
163
+
164
+ /-- Both generator cursors end immediately after this key, so a surrounding
165
+ merge join can continue without losing its next different-key occurrences. -/
166
+ theorem views_complete (read₁ : σ₁ → Option (α × σ₁)) (key₁ : α → ℤ)
167
+ (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ) (K : ℤ)
168
+ (report : α → β → τ → τ × Bool) (hreport : ∀ x y a, (report x y a).2 = false)
169
+ (view₁ : σ₁ → List α) (hread₁ : RowMerge.IsReader read₁ view₁)
170
+ (view₂ : σ₂ → List β) (hread₂ : RowMerge.IsReader read₂ view₂)
171
+ (B fuel₁ fuel₂ : ℕ) (s₁ : σ₁) (s₂ : σ₂) (a : τ)
172
+ (hfuel₁ : (TieBuffer.groupView key₁ K view₁ s₁).length ≤ fuel₁)
173
+ (hfuel₂ : (TieBuffer.groupView key₂ K view₂ s₂).length ≤ fuel₂)
174
+ (hne : TieBuffer.groupView key₁ K view₁ s₁ ≠ []) :
175
+ view₁ s₁ = TieBuffer.groupView key₁ K view₁ s₁ ++
176
+ view₁ (run read₁ key₁ read₂ key₂ K report B fuel₁ fuel₂ s₁ s₂ a).outer.cursor ∧
177
+ view₂ s₂ = TieBuffer.groupView key₂ K view₂ s₂ ++
178
+ view₂ (run read₁ key₁ read₂ key₂ K report B fuel₁ fuel₂ s₁ s₂ a).outer.state.last := by
179
+ let filled := TieBuffer.fill read₂ key₂ K B s₂
180
+ let long := TieBuffer.hasKey read₂ key₂ K filled.cursor
181
+ let f := step read₂ key₂ K report filled.buffer filled.cursor long fuel₂
182
+ have hnonhalt : ∀ x st, (f x st).2 = false :=
183
+ step_halted_false read₂ key₂ K report hreport filled.buffer filled.cursor long fuel₂
184
+ have hspec := TieReplay.runAcc_nonhalting_spec read₁ key₁ K f hnonhalt view₁ hread₁ fuel₁ s₁
185
+ (⟨filled.cursor, a, 0, 0, 0⟩ : State σ₂ τ) 0 0
186
+ have hfirst : view₁ s₁ = TieBuffer.groupView key₁ K view₁ s₁ ++
187
+ view₁ (run read₁ key₁ read₂ key₂ K report B fuel₁ fuel₂ s₁ s₂ a).outer.cursor := by
188
+ simpa only [run, TieReplay.run, f, long, filled, List.take_of_length_le hfuel₁] using hspec.2.2.2
189
+ refine ⟨hfirst, ?_⟩
190
+ let P := fun (st : State σ₂ τ) (r : ℕ) => r = 0 ∨
191
+ view₂ s₂ = TieBuffer.groupView key₂ K view₂ s₂ ++ view₂ st.last
192
+ have hstep : ∀ x st r, P st r → P (f x st).1 (r + 1) := by
193
+ intro x st r _
194
+ exact Or.inr (JoinOne.filled_view_complete read₂ key₂ K (report x) (hreport x)
195
+ view₂ hread₂ B fuel₂ s₂ st.user hfuel₂)
196
+ have hP := TieReplay.run_preserves read₁ key₁ K f P hstep fuel₁ s₁
197
+ (⟨filled.cursor, a, 0, 0, 0⟩ : State σ₂ τ) (Or.inl rfl)
198
+ have hcount : (run read₁ key₁ read₂ key₂ K report B fuel₁ fuel₂ s₁ s₂ a).outer.reports =
199
+ (TieBuffer.groupView key₁ K view₁ s₁).length := by
200
+ simpa only [run, TieReplay.run, f, long, filled, Nat.zero_add, Nat.min_eq_right hfuel₁] using hspec.2.1
201
+ change (run read₁ key₁ read₂ key₂ K report B fuel₁ fuel₂ s₁ s₂ a).outer.reports = 0 ∨ _ at hP
202
+ rcases hP with hz | hP
203
+ · rw [hcount] at hz
204
+ exact False.elim (hne (List.length_eq_zero_iff.mp hz))
205
+ · exact hP
206
+
207
+ theorem query_bound (read₁ : σ₁ → Option (α × σ₁)) (key₁ : α → ℤ)
208
+ (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ) (K : ℤ)
209
+ (report : α → β → τ → τ × Bool)
210
+ (view₁ : σ₁ → List α) (hread₁ : RowMerge.IsReader read₁ view₁)
211
+ (view₂ : σ₂ → List β) (hread₂ : RowMerge.IsReader read₂ view₂)
212
+ (B fuel₁ fuel₂ : ℕ) (s₁ : σ₁) (s₂ : σ₂) (a : τ) :
213
+ (run read₁ key₁ read₂ key₂ K report B fuel₁ fuel₂ s₁ s₂ a).outer.queries +
214
+ (run read₁ key₁ read₂ key₂ K report B fuel₁ fuel₂ s₁ s₂ a).fillQueries +
215
+ (run read₁ key₁ read₂ key₂ K report B fuel₁ fuel₂ s₁ s₂ a).outer.state.queries ≤
216
+ 2 * (TieBuffer.groupView key₁ K view₁ s₁).length +
217
+ (TieBuffer.groupView key₂ K view₂ s₂).length +
218
+ (TieBuffer.groupView key₁ K view₁ s₁).length *
219
+ (TieBuffer.groupView key₂ K view₂ s₂).length + 2 := by
220
+ have hq := (run_bounds read₁ key₁ read₂ key₂ K report view₁ hread₁ view₂ hread₂
221
+ B fuel₁ fuel₂ s₁ s₂ a).2.1
222
+ have hf := TieBuffer.fill_queries_le_potential read₂ key₂ K view₂ hread₂ B s₂
223
+ have ho := TieReplay.run_queries_le_potential read₁ key₁ K
224
+ (step read₂ key₂ K report (TieBuffer.fill read₂ key₂ K B s₂).buffer
225
+ (TieBuffer.fill read₂ key₂ K B s₂).cursor
226
+ (TieBuffer.hasKey read₂ key₂ K (TieBuffer.fill read₂ key₂ K B s₂).cursor) fuel₂)
227
+ view₁ hread₁ fuel₁ s₁ ⟨(TieBuffer.fill read₂ key₂ K B s₂).cursor, a, 0, 0, 0⟩
228
+ change (run read₁ key₁ read₂ key₂ K report B fuel₁ fuel₂ s₁ s₂ a).outer.queries ≤ _ at ho
229
+ change (run read₁ key₁ read₂ key₂ K report B fuel₁ fuel₂ s₁ s₂ a).fillQueries ≤ _ at hf
230
+ nlinarith
231
+
232
+ theorem bufferSize_le (read₁ : σ₁ → Option (α × σ₁)) (key₁ : α → ℤ)
233
+ (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ) (K : ℤ)
234
+ (report : α → β → τ → τ × Bool)
235
+ (view₂ : σ₂ → List β) (hread₂ : RowMerge.IsReader read₂ view₂)
236
+ (B fuel₁ fuel₂ : ℕ) (s₁ : σ₁) (s₂ : σ₂) (a : τ) :
237
+ (run read₁ key₁ read₂ key₂ K report B fuel₁ fuel₂ s₁ s₂ a).bufferSize ≤ B :=
238
+ TieBuffer.fill_size_le read₂ key₂ K view₂ hread₂ B s₂
239
+
240
+ /-- Without a long suffix, there are no generator restores. -/
241
+ theorem restores_eq_zero_of_short (read₁ : σ₁ → Option (α × σ₁)) (key₁ : α → ℤ)
242
+ (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ) (K : ℤ)
243
+ (report : α → β → τ → τ × Bool) (B fuel₁ fuel₂ : ℕ)
244
+ (s₁ : σ₁) (s₂ : σ₂) (a : τ)
245
+ (hshort : TieBuffer.hasKey read₂ key₂ K (TieBuffer.fill read₂ key₂ K B s₂).cursor = false) :
246
+ (run read₁ key₁ read₂ key₂ K report B fuel₁ fuel₂ s₁ s₂ a).outer.state.restores = 0 := by
247
+ dsimp only [run]
248
+ apply TieReplay.run_preserves read₁ key₁ K _
249
+ (fun (st : State σ₂ τ) (_ : ℕ) => st.restores = 0) _ _ _ _ rfl
250
+ intro x st r hst
251
+ simpa only [step, hshort, Bool.false_eq_true, ite_false, Nat.add_zero] using hst
252
+
253
+ /-- Every snapshot/restore is charged to potential partners, including
254
+ partners not reached when the execution halts. -/
255
+ theorem copies_charged (read₁ : σ₁ → Option (α × σ₁)) (key₁ : α → ℤ)
256
+ (read₂ : σ₂ → Option (β × σ₂)) (key₂ : β → ℤ) (K : ℤ)
257
+ (report : α → β → τ → τ × Bool)
258
+ (view₁ : σ₁ → List α) (hread₁ : RowMerge.IsReader read₁ view₁)
259
+ (view₂ : σ₂ → List β) (hread₂ : RowMerge.IsReader read₂ view₂)
260
+ (B fuel₁ fuel₂ : ℕ) (s₁ : σ₁) (s₂ : σ₂) (a : τ) :
261
+ B * ((if (run read₁ key₁ read₂ key₂ K report B fuel₁ fuel₂ s₁ s₂ a).snapshot then 1 else 0) +
262
+ (run read₁ key₁ read₂ key₂ K report B fuel₁ fuel₂ s₁ s₂ a).outer.state.restores) ≤
263
+ 2 * ((TieBuffer.groupView key₁ K view₁ s₁).length *
264
+ (TieBuffer.groupView key₂ K view₂ s₂).length) := by
265
+ have hc := (run_bounds read₁ key₁ read₂ key₂ K report view₁ hread₁ view₂ hread₂
266
+ B fuel₁ fuel₂ s₁ s₂ a).2.2
267
+ by_cases hl : TieBuffer.hasKey read₂ key₂ K (TieBuffer.fill read₂ key₂ K B s₂).cursor = true
268
+ · have hB := (TieBuffer.long_group_full_buffer read₂ key₂ K view₂ hread₂ B s₂ hl).1.le
269
+ by_cases hfirst : TieBuffer.hasKey read₁ key₁ K s₁ = true
270
+ · have hpos : 0 < (TieBuffer.groupView key₁ K view₁ s₁).length :=
271
+ List.length_pos_iff.mpr ((TieBuffer.hasKey_iff read₁ key₁ K view₁ hread₁ s₁).mp hfirst)
272
+ have hs : (run read₁ key₁ read₂ key₂ K report B fuel₁ fuel₂ s₁ s₂ a).snapshot = true := by
273
+ simp [run, hl, hfirst]
274
+ simp only [hs, ↓reduceIte]
275
+ calc
276
+ B * (1 + _) ≤ B * (2 * (TieBuffer.groupView key₁ K view₁ s₁).length) := by
277
+ apply Nat.mul_le_mul_left
278
+ omega
279
+ _ ≤ (TieBuffer.groupView key₂ K view₂ s₂).length *
280
+ (2 * (TieBuffer.groupView key₁ K view₁ s₁).length) := Nat.mul_le_mul_right _ hB
281
+ _ = _ := by ring
282
+ · have he : TieBuffer.groupView key₁ K view₁ s₁ = [] := by
283
+ by_contra he
284
+ exact hfirst ((TieBuffer.hasKey_iff read₁ key₁ K view₁ hread₁ s₁).mpr he)
285
+ have hs : (run read₁ key₁ read₂ key₂ K report B fuel₁ fuel₂ s₁ s₂ a).snapshot = false := by
286
+ simp [run, Bool.eq_false_iff.mpr hfirst]
287
+ rw [he, List.length_nil] at hc ⊢
288
+ simp [hs, Nat.eq_zero_of_le_zero hc]
289
+ · have hshort := Bool.eq_false_iff.mpr hl
290
+ have hz := restores_eq_zero_of_short read₁ key₁ read₂ key₂ K report B fuel₁ fuel₂ s₁ s₂ a hshort
291
+ have hs : (run read₁ key₁ read₂ key₂ K report B fuel₁ fuel₂ s₁ s₂ a).snapshot = false := by
292
+ simp [run, hshort]
293
+ simp [hs, hz]
294
+
295
+ end TieGroup
296
+ end LowSpaceSubsetSum
297
+
298
+ end OAI
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/TieReplay.lean ADDED
@@ -0,0 +1,239 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import OAI.Combinatorics.LowSpaceSubsetSum.Streams.TieBuffer
2
+
3
+ namespace OAI
4
+
5
+ /-!
6
+ # Bounded replay of one tie suffix
7
+
8
+ The reporter can stop after any matching occurrence. The replay retains
9
+ only its cursor, callback state, counters, and fixed key. Its recursion is
10
+ tail recursion. All attempted reports are bounded by the complete suffix
11
+ length, even if the callback or fuel stops execution early.
12
+ -/
13
+
14
+ namespace LowSpaceSubsetSum
15
+ namespace TieReplay
16
+
17
+ universe u v w
18
+
19
+ variable {α : Type u} {σ : Type v} {τ : Type w}
20
+
21
+ structure Result (σ : Type v) (τ : Type w) where
22
+ cursor : σ
23
+ state : τ
24
+ queries : ℕ
25
+ reports : ℕ
26
+ complete : Bool
27
+ halted : Bool
28
+
29
+ def runAcc (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ)
30
+ (report : α → τ → τ × Bool) : ℕ → σ → τ → ℕ → ℕ → Result σ τ
31
+ | 0, s, a, q, r => ⟨s, a, q, r, false, false⟩
32
+ | fuel + 1, s, a, q, r => match read s with
33
+ | none => ⟨s, a, q + 1, r, true, false⟩
34
+ | some (x, s') => if key x = K then
35
+ let out := report x a
36
+ if out.2 then ⟨s', out.1, q + 1, r + 1, false, true⟩
37
+ else runAcc read key K report fuel s' out.1 (q + 1) (r + 1)
38
+ else ⟨s, a, q + 1, r, true, false⟩
39
+
40
+ def run (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ)
41
+ (report : α → τ → τ × Bool) (fuel : ℕ) (s : σ) (a : τ) : Result σ τ :=
42
+ runAcc read key K report fuel s a 0 0
43
+
44
+ theorem runAcc_bounds (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ)
45
+ (report : α → τ → τ × Bool) (view : σ → List α) (hread : RowMerge.IsReader read view)
46
+ (fuel : ℕ) (s : σ) (a : τ) (q r : ℕ) :
47
+ (runAcc read key K report fuel s a q r).queries ≤ q + fuel ∧
48
+ r ≤ (runAcc read key K report fuel s a q r).reports ∧
49
+ (runAcc read key K report fuel s a q r).reports ≤
50
+ r + min fuel (TieBuffer.groupView key K view s).length := by
51
+ induction fuel generalizing s a q r with
52
+ | zero => simp [runAcc]
53
+ | succ fuel ih =>
54
+ have hr := hread s
55
+ cases h : read s with
56
+ | none =>
57
+ simp only [h] at hr
58
+ simp [runAcc, h, TieBuffer.groupView, hr]
59
+ | some z =>
60
+ rcases z with ⟨x, s'⟩
61
+ simp only [h] at hr
62
+ by_cases hx : key x = K
63
+ · have hg : TieBuffer.groupView key K view s =
64
+ x :: TieBuffer.groupView key K view s' := by
65
+ simp [TieBuffer.groupView, hr, hx]
66
+ simp only [runAcc, h, ite_eq_left hx]
67
+ split
68
+ · simp only [hg, List.length_cons]
69
+ omega
70
+ · have hi := ih s' (report x a).1 (q + 1) (r + 1)
71
+ simp only [hg, List.length_cons]
72
+ omega
73
+ · have hg : TieBuffer.groupView key K view s = [] := by
74
+ simp [TieBuffer.groupView, hr, hx]
75
+ simp [runAcc, h, hx, hg]
76
+
77
+ theorem run_queries_le (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ)
78
+ (report : α → τ → τ × Bool) (view : σ → List α) (hread : RowMerge.IsReader read view)
79
+ (fuel : ℕ) (s : σ) (a : τ) : (run read key K report fuel s a).queries ≤ fuel := by
80
+ simpa [run] using (runAcc_bounds read key K report view hread fuel s a 0 0).1
81
+
82
+ theorem run_reports_le_potential (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ)
83
+ (report : α → τ → τ × Bool) (view : σ → List α) (hread : RowMerge.IsReader read view)
84
+ (fuel : ℕ) (s : σ) (a : τ) :
85
+ (run read key K report fuel s a).reports ≤ (TieBuffer.groupView key K view s).length := by
86
+ have h := (runAcc_bounds read key K report view hread fuel s a 0 0).2.2
87
+ simp only [run, zero_add] at h ⊢
88
+ exact h.trans (Nat.min_le_right _ _)
89
+
90
+ /-- The one final lookahead is the only read not charged to a reportable
91
+ occurrence, even when the fuel is much larger than the tie group. -/
92
+ theorem runAcc_queries_le_potential (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ)
93
+ (report : α → τ → τ × Bool) (view : σ → List α) (hread : RowMerge.IsReader read view)
94
+ (fuel : ℕ) (s : σ) (a : τ) (q r : ℕ) :
95
+ (runAcc read key K report fuel s a q r).queries ≤
96
+ q + min fuel ((TieBuffer.groupView key K view s).length + 1) := by
97
+ induction fuel generalizing s a q r with
98
+ | zero => simp [runAcc]
99
+ | succ fuel ih =>
100
+ have hr := hread s
101
+ cases h : read s with
102
+ | none =>
103
+ simp only [h] at hr
104
+ simp [runAcc, h, TieBuffer.groupView, hr]
105
+ | some z =>
106
+ rcases z with ⟨x, s'⟩
107
+ simp only [h] at hr
108
+ by_cases hx : key x = K
109
+ · have hg : TieBuffer.groupView key K view s =
110
+ x :: TieBuffer.groupView key K view s' := by
111
+ simp [TieBuffer.groupView, hr, hx]
112
+ simp only [runAcc, h, ite_eq_left hx, hg, List.length_cons]
113
+ split
114
+ · dsimp only
115
+ omega
116
+ · have hi := ih s' (report x a).1 (q + 1) (r + 1)
117
+ omega
118
+ · have hg : TieBuffer.groupView key K view s = [] := by
119
+ simp [TieBuffer.groupView, hr, hx]
120
+ simp [runAcc, h, hx, hg]
121
+
122
+ theorem run_queries_le_potential (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ)
123
+ (report : α → τ → τ × Bool) (view : σ → List α) (hread : RowMerge.IsReader read view)
124
+ (fuel : ℕ) (s : σ) (a : τ) :
125
+ (run read key K report fuel s a).queries ≤ (TieBuffer.groupView key K view s).length + 1 := by
126
+ have h := runAcc_queries_le_potential read key K report view hread fuel s a 0 0
127
+ simp only [run, zero_add] at h ⊢
128
+ exact h.trans (Nat.min_le_right _ _)
129
+
130
+ theorem runAcc_halted_false (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ)
131
+ (report : α → τ → τ × Bool) (hreport : ∀ x a, (report x a).2 = false)
132
+ (fuel : ℕ) (s : σ) (a : τ) (q r : ℕ) :
133
+ (runAcc read key K report fuel s a q r).halted = false := by
134
+ induction fuel generalizing s a q r with
135
+ | zero => rfl
136
+ | succ fuel ih =>
137
+ cases h : read s with
138
+ | none => simp [runAcc, h]
139
+ | some z =>
140
+ rcases z with ⟨x, s'⟩
141
+ by_cases hx : key x = K
142
+ · simp only [runAcc, h, ite_eq_left hx, hreport, Bool.false_eq_true, ite_false]
143
+ exact ih _ _ _ _
144
+ · simp [runAcc, h, hx]
145
+
146
+ theorem run_halted_false (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ)
147
+ (report : α → τ → τ × Bool) (hreport : ∀ x a, (report x a).2 = false)
148
+ (fuel : ℕ) (s : σ) (a : τ) :
149
+ (run read key K report fuel s a).halted = false :=
150
+ runAcc_halted_false read key K report hreport fuel s a 0 0
151
+
152
+ /-- A callback invariant can depend on the exact number of reports. This
153
+ also applies to executions stopped by the callback or by the fuel. -/
154
+ theorem runAcc_preserves (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ)
155
+ (report : α → τ → τ × Bool) (P : τ → ℕ → Prop)
156
+ (hstep : ∀ x a r, P a r → P (report x a).1 (r + 1))
157
+ (fuel : ℕ) (s : σ) (a : τ) (q r : ℕ) (ha : P a r) :
158
+ P (runAcc read key K report fuel s a q r).state
159
+ (runAcc read key K report fuel s a q r).reports := by
160
+ induction fuel generalizing s a q r with
161
+ | zero => exact ha
162
+ | succ fuel ih =>
163
+ cases h : read s with
164
+ | none => simpa only [runAcc, h] using ha
165
+ | some z =>
166
+ rcases z with ⟨x, s'⟩
167
+ by_cases hx : key x = K
168
+ · simp only [runAcc, h, ite_eq_left hx]
169
+ split
170
+ · exact hstep x a r ha
171
+ · exact ih s' (report x a).1 (q + 1) (r + 1) (hstep x a r ha)
172
+ · simpa only [runAcc, h, ite_eq_right hx] using ha
173
+
174
+ theorem run_preserves (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ)
175
+ (report : α → τ → τ × Bool) (P : τ → ℕ → Prop)
176
+ (hstep : ∀ x a r, P a r → P (report x a).1 (r + 1))
177
+ (fuel : ℕ) (s : σ) (a : τ) (ha : P a 0) :
178
+ P (run read key K report fuel s a).state (run read key K report fuel s a).reports :=
179
+ runAcc_preserves read key K report P hstep fuel s a 0 0 ha
180
+
181
+ /-- If reporting continues, replay processes exactly the requested prefix
182
+ of the tie suffix and leaves every following occurrence untouched. -/
183
+ theorem runAcc_nonhalting_spec (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ)
184
+ (report : α → τ → τ × Bool) (hreport : ∀ x a, (report x a).2 = false)
185
+ (view : σ → List α) (hread : RowMerge.IsReader read view)
186
+ (fuel : ℕ) (s : σ) (a : τ) (q r : ℕ) :
187
+ (runAcc read key K report fuel s a q r).state =
188
+ ((TieBuffer.groupView key K view s).take fuel).foldl (fun a x => (report x a).1) a ∧
189
+ (runAcc read key K report fuel s a q r).reports =
190
+ r + min fuel (TieBuffer.groupView key K view s).length ∧
191
+ TieBuffer.groupView key K view (runAcc read key K report fuel s a q r).cursor =
192
+ (TieBuffer.groupView key K view s).drop fuel ∧
193
+ view s = (TieBuffer.groupView key K view s).take fuel ++
194
+ view (runAcc read key K report fuel s a q r).cursor := by
195
+ induction fuel generalizing s a q r with
196
+ | zero => simp [runAcc]
197
+ | succ fuel ih =>
198
+ have hr := hread s
199
+ cases h : read s with
200
+ | none =>
201
+ simp only [h] at hr
202
+ simp [runAcc, h, TieBuffer.groupView, hr]
203
+ | some z =>
204
+ rcases z with ⟨x, s'⟩
205
+ simp only [h] at hr
206
+ by_cases hx : key x = K
207
+ · have hg : TieBuffer.groupView key K view s =
208
+ x :: TieBuffer.groupView key K view s' := by
209
+ simp [TieBuffer.groupView, hr, hx]
210
+ have hi := ih s' (report x a).1 (q + 1) (r + 1)
211
+ simp only [runAcc, h, ite_eq_left hx, hreport, Bool.false_eq_true, ite_false]
212
+ refine ⟨?_, ?_, ?_, ?_⟩
213
+ · rw [hi.1, hg]
214
+ simp
215
+ · rw [hi.2.1, hg]
216
+ simp only [List.length_cons]
217
+ omega
218
+ · rw [hi.2.2.1, hg]
219
+ simp
220
+ · rw [hr, hi.2.2.2, hg]
221
+ simp
222
+ · have hg : TieBuffer.groupView key K view s = [] := by
223
+ simp [TieBuffer.groupView, hr, hx]
224
+ simp [runAcc, h, hx, hg]
225
+
226
+ theorem run_state_complete (read : σ → Option (α × σ)) (key : α → ℤ) (K : ℤ)
227
+ (report : α → τ → τ × Bool) (hreport : ∀ x a, (report x a).2 = false)
228
+ (view : σ → List α) (hread : RowMerge.IsReader read view)
229
+ (fuel : ℕ) (s : σ) (a : τ)
230
+ (hfuel : (TieBuffer.groupView key K view s).length ≤ fuel) :
231
+ (run read key K report fuel s a).state =
232
+ (TieBuffer.groupView key K view s).foldl (fun a x => (report x a).1) a := by
233
+ have h := (runAcc_nonhalting_spec read key K report hreport view hread fuel s a 0 0).1
234
+ simpa [run, List.take_of_length_le hfuel] using h
235
+
236
+ end TieReplay
237
+ end LowSpaceSubsetSum
238
+
239
+ end OAI
lean/OAI/Combinatorics/LowSpaceSubsetSum/Streams/Tournament.lean ADDED
@@ -0,0 +1,281 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import Mathlib.Data.Fin.Tuple.Basic
2
+ import Mathlib.Data.List.Basic
3
+ import Mathlib.Data.Nat.Log
4
+ import Mathlib.Tactic
5
+
6
+ namespace OAI
7
+
8
+ /-!
9
+ # Cached tournament for merging row fronts
10
+
11
+ Each leaf holds at most one current occurrence of a row. Internal nodes
12
+ cache the smaller child winner. Reading the winner is constant time;
13
+ replacing one leaf recomputes just its root path. The candidate list below
14
+ is an analysis view and is never stored in the tournament.
15
+ -/
16
+
17
+ namespace LowSpaceSubsetSum
18
+ namespace Tournament
19
+
20
+ universe u
21
+
22
+ variable {α : Type u}
23
+
24
+ def pick (key : α → ℤ) : Option α → Option α → Option α
25
+ | none, v => v
26
+ | u, none => u
27
+ | some x, some y => if key x ≤ key y then some x else some y
28
+
29
+ theorem pick_member (key : α → ℤ) (u v : Option α) {x : α}
30
+ (h : pick key u v = some x) : u = some x ∨ v = some x := by
31
+ cases u with
32
+ | none => exact Or.inr h
33
+ | some a =>
34
+ cases v with
35
+ | none => exact Or.inl h
36
+ | some b =>
37
+ by_cases hab : key a ≤ key b
38
+ · exact Or.inl (by simpa [pick, hab] using h)
39
+ · exact Or.inr (by simpa [pick, hab] using h)
40
+
41
+ theorem pick_le_left (key : α → ℤ) (a : α) (v : Option α) :
42
+ ∃ x, pick key (some a) v = some x ∧ key x ≤ key a := by
43
+ cases v with
44
+ | none => exact ⟨a, rfl, le_rfl⟩
45
+ | some b =>
46
+ by_cases hab : key a ≤ key b
47
+ · exact ⟨a, by simp [pick, hab], le_rfl⟩
48
+ · exact ⟨b, by simp [pick, hab], (not_le.mp hab).le⟩
49
+
50
+ theorem pick_le_right (key : α → ℤ) (u : Option α) (b : α) :
51
+ ∃ x, pick key u (some b) = some x ∧ key x ≤ key b := by
52
+ cases u with
53
+ | none => exact ⟨b, rfl, le_rfl⟩
54
+ | some a =>
55
+ by_cases hab : key a ≤ key b
56
+ · exact ⟨a, by simp [pick, hab], hab⟩
57
+ · exact ⟨b, by simp [pick, hab], le_rfl⟩
58
+
59
+ def Best (key : α → ℤ) (v : Option α) (xs : List α) : Prop :=
60
+ (∀ x, v = some x → x ∈ xs) ∧ (∀ y ∈ xs, ∃ x, v = some x ∧ key x ≤ key y)
61
+
62
+ theorem best_append (key : α → ℤ) {u v : Option α} {xs ys : List α}
63
+ (hu : Best key u xs) (hv : Best key v ys) :
64
+ Best key (pick key u v) (xs ++ ys) := by
65
+ constructor
66
+ · intro x hx
67
+ rcases pick_member key u v hx with hx | hx
68
+ · exact List.mem_append_left _ (hu.1 x hx)
69
+ · exact List.mem_append_right _ (hv.1 x hx)
70
+ · intro y hy
71
+ rcases List.mem_append.mp hy with hy | hy
72
+ · obtain ⟨z, hz, hzy⟩ := hu.2 y hy
73
+ obtain ⟨x, hx, hxz⟩ := pick_le_left key z v
74
+ rw [← hz] at hx
75
+ exact ⟨x, hx, hxz.trans hzy⟩
76
+ · obtain ⟨z, hz, hzy⟩ := hv.2 y hy
77
+ obtain ⟨x, hx, hxz⟩ := pick_le_right key u z
78
+ rw [← hz] at hx
79
+ exact ⟨x, hx, hxz.trans hzy⟩
80
+
81
+ inductive Tree (α : Type u) : ℕ → Type u
82
+ | leaf (value : Option α) : Tree α 0
83
+ | node {d : ℕ} (winner : Option α) (left right : Tree α d) : Tree α (d + 1)
84
+
85
+ def winner {d : ℕ} : Tree α d → Option α
86
+ | .leaf v => v
87
+ | .node v _ _ => v
88
+
89
+ def candidates {d : ℕ} : Tree α d → List α
90
+ | .leaf v => v.toList
91
+ | .node _ l r => candidates l ++ candidates r
92
+
93
+ def Valid (key : α → ℤ) {d : ℕ} : Tree α d → Prop
94
+ | .leaf _ => True
95
+ | .node v l r => v = pick key (winner l) (winner r) ∧ Valid key l ∧ Valid key r
96
+
97
+ def node (key : α → ℤ) {d : ℕ} (l r : Tree α d) : Tree α (d + 1) :=
98
+ .node (pick key (winner l) (winner r)) l r
99
+
100
+ theorem winner_best (key : α → ℤ) {d : ℕ} (t : Tree α d) (ht : Valid key t) :
101
+ Best key (winner t) (candidates t) := by
102
+ induction t with
103
+ | leaf v => cases v <;> simp [winner, candidates, Best]
104
+ | node v l r ihl ihr =>
105
+ obtain ⟨hv, hl, hr⟩ := ht
106
+ change Best key v (candidates l ++ candidates r)
107
+ rw [hv]
108
+ exact best_append key (ihl hl) (ihr hr)
109
+
110
+ theorem winner_none_iff (key : α → ℤ) {d : ℕ} (t : Tree α d) (ht : Valid key t) :
111
+ winner t = none ↔ candidates t = [] := by
112
+ have hb := winner_best key t ht
113
+ constructor
114
+ · intro hn
115
+ apply List.eq_nil_iff_forall_not_mem.mpr
116
+ intro y hy
117
+ obtain ⟨x, hx, _⟩ := hb.2 y hy
118
+ simp [hn] at hx
119
+ · intro hn
120
+ cases hw : winner t with
121
+ | none => rfl
122
+ | some x => simpa [hn] using hb.1 x hw
123
+
124
+ def lookup : {d : ℕ} → Tree α d → (Fin d → Bool) → Option α
125
+ | 0, .leaf v, _ => v
126
+ | _d + 1, .node _ l r, path =>
127
+ if path 0 then lookup r (fun i => path i.succ) else lookup l (fun i => path i.succ)
128
+
129
+ def replace (key : α → ℤ) : {d : ℕ} → Tree α d → (Fin d → Bool) → Option α → Tree α d
130
+ | 0, .leaf _, _, v => .leaf v
131
+ | _d + 1, .node _ l r, path, v =>
132
+ if path 0 then node key l (replace key r (fun i => path i.succ) v)
133
+ else node key (replace key l (fun i => path i.succ) v) r
134
+
135
+ theorem replace_valid (key : α → ℤ) {d : ℕ} (t : Tree α d)
136
+ (ht : Valid key t) (path : Fin d → Bool) (v : Option α) :
137
+ Valid key (replace key t path v) := by
138
+ induction t with
139
+ | leaf _ => trivial
140
+ | node w l r ihl ihr =>
141
+ obtain ⟨_, hl, hr⟩ := ht
142
+ simp only [replace]
143
+ split
144
+ · exact ⟨rfl, hl, ihr hr _⟩
145
+ · exact ⟨rfl, ihl hl _, hr⟩
146
+
147
+ theorem lookup_replace_same (key : α → ℤ) {d : ℕ} (t : Tree α d)
148
+ (path : Fin d → Bool) (v : Option α) : lookup (replace key t path v) path = v := by
149
+ induction t with
150
+ | leaf _ => rfl
151
+ | node w l r ihl ihr =>
152
+ simp only [replace]
153
+ split <;> simp_all [node, lookup]
154
+
155
+ theorem lookup_replace (key : α → ℤ) {d : ℕ} (t : Tree α d)
156
+ (path q : Fin d → Bool) (v : Option α) :
157
+ lookup (replace key t path v) q = if path = q then v else lookup t q := by
158
+ induction t with
159
+ | leaf _ =>
160
+ have heq : path = q := Subsingleton.elim _ _
161
+ simp [replace, lookup, heq]
162
+ | @node d w l r ihl ihr =>
163
+ have heq : path = q ↔ path 0 = q 0 ∧
164
+ (fun i : Fin d => path i.succ) = (fun i : Fin d => q i.succ) := by
165
+ constructor
166
+ · intro h
167
+ subst q
168
+ exact ⟨rfl, rfl⟩
169
+ · rintro ⟨hh, ht⟩
170
+ funext i
171
+ exact Fin.cases hh (fun j => congrFun ht j) i
172
+ cases hp : path 0 <;> cases hq : q 0 <;>
173
+ simp [replace, node, lookup, hp, hq, ihl, ihr, heq]
174
+
175
+ def build (key : α → ℤ) : (d : ℕ) → ((Fin d → Bool) → Option α) → Tree α d
176
+ | 0, front => .leaf (front Fin.elim0)
177
+ | d + 1, front => node key
178
+ (build key d (fun p => front (Fin.cons false p)))
179
+ (build key d (fun p => front (Fin.cons true p)))
180
+
181
+ theorem build_valid (key : α → ℤ) (d : ℕ) (front : (Fin d → Bool) → Option α) :
182
+ Valid key (build key d front) := by
183
+ induction d with
184
+ | zero => trivial
185
+ | succ d ih => exact ⟨rfl, ih _, ih _⟩
186
+
187
+ theorem lookup_build (key : α → ℤ) (d : ℕ) (front : (Fin d → Bool) → Option α)
188
+ (path : Fin d → Bool) : lookup (build key d front) path = front path := by
189
+ induction d with
190
+ | zero =>
191
+ have hpath : (Fin.elim0 : Fin 0 → Bool) = path := Subsingleton.elim _ _
192
+ simpa [build, lookup] using congrArg front hpath
193
+ | succ d ih =>
194
+ simp only [build, node, lookup]
195
+ cases hp : path 0
196
+ · simp only [Bool.false_eq_true, ↓reduceIte]
197
+ rw [ih]
198
+ apply congrArg front
199
+ funext i
200
+ exact Fin.cases (by simp [hp]) (fun j => by simp) i
201
+ · simp only [↓reduceIte]
202
+ rw [ih]
203
+ apply congrArg front
204
+ funext i
205
+ exact Fin.cases (by simp [hp]) (fun j => by simp) i
206
+
207
+ theorem mem_candidates_iff {d : ℕ} (t : Tree α d) (v : α) :
208
+ v ∈ candidates t ↔ ∃ path, lookup t path = some v := by
209
+ induction t with
210
+ | leaf w =>
211
+ constructor
212
+ · intro hv
213
+ exact ⟨Fin.elim0, by simpa [candidates, lookup] using hv⟩
214
+ · rintro ⟨_, hv⟩
215
+ simpa [candidates, lookup] using hv
216
+ | @node d w l r ihl ihr =>
217
+ rw [candidates, List.mem_append, ihl, ihr]
218
+ constructor
219
+ · rintro (⟨p, hp⟩ | ⟨p, hp⟩)
220
+ · exact ⟨Fin.cons false p, by simpa [lookup] using hp⟩
221
+ · exact ⟨Fin.cons true p, by simpa [lookup] using hp⟩
222
+ · rintro ⟨p, hp⟩
223
+ cases h : p 0
224
+ · exact Or.inl ⟨fun i => p i.succ, by simpa [lookup, h] using hp⟩
225
+ · exact Or.inr ⟨fun i => p i.succ, by simpa [lookup, h] using hp⟩
226
+
227
+ theorem winner_le_lookup (key : α → ℤ) {d : ℕ} (t : Tree α d) (ht : Valid key t)
228
+ (path : Fin d → Bool) {v : α} (hv : lookup t path = some v) :
229
+ ∃ w, winner t = some w ∧ key w ≤ key v :=
230
+ (winner_best key t ht).2 v ((mem_candidates_iff t v).mpr ⟨path, hv⟩)
231
+
232
+ def nodes : {d : ℕ} → Tree α d → ℕ
233
+ | 0, .leaf _ => 1
234
+ | _ + 1, .node _ l r => 1 + nodes l + nodes r
235
+
236
+ theorem nodes_exact {d : ℕ} (t : Tree α d) : nodes t + 1 = 2 ^ (d + 1) := by
237
+ induction t with
238
+ | leaf _ => norm_num [nodes]
239
+ | @node d w l r ihl ihr =>
240
+ simp only [nodes]
241
+ rw [pow_succ]
242
+ omega
243
+
244
+ theorem padded_nodes_le (R : ℕ) (t : Tree α (Nat.clog 2 R)) :
245
+ nodes t + 1 ≤ 4 * (R + 1) := by
246
+ rw [nodes_exact, pow_succ]
247
+ by_cases hR : R ≤ 1
248
+ · rw [Nat.clog_of_right_le_one hR]
249
+ norm_num
250
+ omega
251
+ · have hR' : 1 < R := by omega
252
+ have hp := Nat.pow_pred_clog_lt_self (by decide : 1 < 2) hR'
253
+ have hpos := Nat.clog_pos (by decide : 1 < 2) hR'
254
+ have hbits : 2 ^ Nat.clog 2 R ≤ 2 * R := by
255
+ rw [show Nat.clog 2 R = (Nat.clog 2 R).pred + 1 from
256
+ (Nat.succ_pred_eq_of_pos hpos).symm, pow_succ]
257
+ omega
258
+ omega
259
+
260
+ theorem depth_le_index_bits {R n : ℕ} (hR : R ≤ 2 ^ n) : Nat.clog 2 R ≤ n :=
261
+ Nat.clog_le_of_le_pow hR
262
+
263
+ /-- Number of cached comparisons made by a leaf replacement. -/
264
+ def replaceComparisons : {d : ℕ} → Tree α d → (Fin d → Bool) → ℕ
265
+ | 0, .leaf _, _ => 0
266
+ | _d + 1, .node _ l r, path =>
267
+ 1 + if path 0 then replaceComparisons r (fun i => path i.succ)
268
+ else replaceComparisons l (fun i => path i.succ)
269
+
270
+ theorem replaceComparisons_eq {d : ℕ} (t : Tree α d) (path : Fin d → Bool) :
271
+ replaceComparisons t path = d := by
272
+ induction t with
273
+ | leaf _ => rfl
274
+ | @node d w l r ihl ihr =>
275
+ simp only [replaceComparisons]
276
+ split <;> simp [ihl, ihr, Nat.add_comm]
277
+
278
+ end Tournament
279
+ end LowSpaceSubsetSum
280
+
281
+ end OAI