Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
streaming_algorithms_test.cc
Go to the documentation of this file.
1/*
2 Aleph_w
3
4 Data structures & Algorithms
5 version 2.0.0b
6 https://github.com/lrleon/Aleph-w
7
8 This file is part of Aleph-w library
9
10 Copyright (c) 2002-2026 Leandro Rabindranath Leon
11
12 Permission is hereby granted, free of charge, to any person obtaining a copy
13 of this software and associated documentation files (the "Software"), to deal
14 in the Software without restriction, including without limitation the rights
15 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16 copies of the Software, and to permit persons to whom the Software is
17 furnished to do so, subject to the following conditions:
18
19 The above copyright notice and this permission notice shall be included in all
20 copies or substantial portions of the Software.
21
22 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28 SOFTWARE.
29*/
30
36# include <gtest/gtest.h>
37# include <string>
38# include <random>
39# include <vector>
40
41# include <tpl_dynArray.H>
42# include <tpl_hash.H>
43# include <tpl_dynList.H>
44# include <reservoir-sampling.H>
45# include <count-min-sketch.H>
46# include <hyperloglog.H>
47# include <minhash.H>
48# include <simhash.H>
49
50using namespace Aleph;
51
52TEST(StreamingAlgorithms, ReservoirSampling)
53{
54 DynArray<int> data;
55 for (int i = 0; i < 1000; ++i) data.append(i);
56
57 const size_t k = 50;
58 auto sample = reservoir_sample(data.begin(), data.end(), k, 12345);
59
60 ASSERT_EQ(sample.size(), k);
61
62 // All elements should be in the original range
63 for (size_t i = 0; i < sample.size(); ++i)
64 {
65 EXPECT_GE(sample[i], 0);
66 EXPECT_LT(sample[i], 1000);
67 }
68
69 // Check unique elements (mostly, since it's random sampling without replacement from unique input)
70 DynHashSet<int> unique_vals;
71 for (size_t i = 0; i < sample.size(); ++i)
72 unique_vals.insert(sample[i]);
73 EXPECT_EQ(unique_vals.size(), k);
74}
75
76TEST(StreamingAlgorithms, CountMinSketch)
77{
79
80 cms.update("apple", 10);
81 cms.update("banana", 5);
82 cms.update("cherry", 1);
83
84 for (int i = 0; i < 100; ++i) cms.update("apple"); // total apple = 110
85
86 EXPECT_GE(cms.estimate("apple"), 110u);
87 EXPECT_GE(cms.estimate("banana"), 5u);
88 EXPECT_GE(cms.estimate("cherry"), 1u);
89 // Theoretical bound: f + epsilon * total_count = 1 + 0.01 * 121 = 2.21
90 // We use a safe bound of 10u to account for small total_count noise.
91 EXPECT_LE(cms.estimate("cherry"), 10u);
92
93 // Deterministic property check
94 const size_t before = cms.estimate("dragonfruit");
95 cms.update("dragonfruit", 5);
96 EXPECT_GE(cms.estimate("dragonfruit"), before + 5);
97
98 // Validation tests
99 EXPECT_THROW(Count_Min_Sketch<int>::from_error_bounds(0.0, 0.1), std::domain_error);
100 EXPECT_THROW(Count_Min_Sketch<int>::from_error_bounds(0.1, 0.0), std::domain_error);
101 EXPECT_THROW(Count_Min_Sketch<int>::from_error_bounds(0.1, 1.0), std::domain_error);
102}
103
104TEST(StreamingAlgorithms, HyperLogLog)
105{
106 HyperLogLog<int> hll(10); // 1024 registers, ~3.2% error
107
108 const int n = 5000;
109 for (int i = 0; i < n; ++i)
110 hll.update(i % 1000); // 1000 unique elements
111
112 double est = hll.estimate();
113 EXPECT_NEAR(est, 1000.0, 1000.0 * 0.05); // allow 5% error
114
115 // Validation tests
116 EXPECT_THROW(HyperLogLog<int>(3), std::domain_error);
117 EXPECT_THROW(HyperLogLog<int>(17), std::domain_error);
118}
119
120// A moved-from sketch is an empty one of the same parameters, and a move
121// assignment exchanges the sketches. The implicit moves took the storage
122// but copied the sizes: the moved-from sketches then indexed storage they
123// no longer had (clear() of a HyperLogLog or a MinHash wrote through a null
124// buffer), and after small = std::move(big), big kept its size with the
125// storage of small
126TEST(StreamingAlgorithms, MovedFromSketchesAreEmptyAndUsable)
127{
128 HyperLogLog<int> hll(10);
129 for (int i = 0; i < 1000; ++i)
130 hll.update(i);
131 const double est = hll.estimate();
132 HyperLogLog<int> hll2(std::move(hll));
133 EXPECT_DOUBLE_EQ(hll2.estimate(), est);
134 EXPECT_EQ(hll.num_registers(), 1024u);
135 EXPECT_DOUBLE_EQ(hll.estimate(), 0.0);
136 hll.clear();
137 hll.update(7);
138 EXPECT_GT(hll.estimate(), 0.0);
139 HyperLogLog<int> small_hll(4);
140 small_hll = std::move(hll2); // small_hll takes 2^10 registers, hll2 the 2^4
141 EXPECT_DOUBLE_EQ(small_hll.estimate(), est);
142 EXPECT_EQ(hll2.num_registers(), 16u);
143 hll2.clear();
144 hll2.update(1);
145 hll2.merge(HyperLogLog<int>(4));
146
147 Count_Min_Sketch<int> cms(64, 4);
148 cms.update(7, 5);
149 Count_Min_Sketch<int> cms2(std::move(cms));
150 EXPECT_EQ(cms2.estimate(7), 5u);
151 EXPECT_EQ(cms.width(), 64u);
152 EXPECT_EQ(cms.estimate(7), 0u);
153 cms.update(7);
154 EXPECT_EQ(cms.estimate(7), 1u);
155 Count_Min_Sketch<int> small_cms(2, 1);
156 small_cms = std::move(cms2);
157 EXPECT_EQ(small_cms.estimate(7), 5u);
158 EXPECT_EQ(cms2.width(), 2u);
159 cms2.update(3);
160 EXPECT_GE(cms2.estimate(3), 1u);
161
162 MinHash<int> mh(64);
163 mh.update(7);
164 MinHash<int> mh2(std::move(mh));
165 EXPECT_EQ(mh.size(), 64u);
166 mh.clear();
167 mh.update(7);
168 EXPECT_DOUBLE_EQ(mh.similarity(mh2), 1.0);
169 MinHash<int> small_mh(2);
170 small_mh = std::move(mh2);
171 EXPECT_EQ(small_mh.size(), 64u);
172 EXPECT_EQ(mh2.size(), 2u);
173 mh2.clear();
174 mh2.update(1);
175
176 Reservoir_Sampler<int> rs(8, 1);
177 for (int i = 0; i < 4; ++i)
178 rs.update(i);
179 Reservoir_Sampler<int> rs2(std::move(rs));
180 EXPECT_EQ(rs2.total_seen(), 4u);
181 EXPECT_EQ(rs.sample_size(), 8u);
182 EXPECT_EQ(rs.total_seen(), 0u);
183 for (int i = 0; i < 20; ++i)
184 rs.update(i);
185 EXPECT_EQ(rs.get_sample().size(), 8u);
186 Reservoir_Sampler<int> small_rs(2, 3);
187 small_rs = std::move(rs2);
188 EXPECT_EQ(small_rs.total_seen(), 4u);
189 EXPECT_EQ(rs2.sample_size(), 2u);
190 for (int i = 0; i < 5; ++i)
191 rs2.update(i);
192 EXPECT_EQ(rs2.get_sample().size(), 2u);
193}
194
195static void assertMinHashContracts(MinHash<int> & mh, size_t expected_k)
196{
197 EXPECT_EQ(mh.size(), expected_k);
198 const auto & sig = mh.get_signature();
199 EXPECT_EQ(sig.size(), expected_k);
200
201 // clear() behavior
202 mh.clear();
203 EXPECT_EQ(mh.size(), expected_k);
204 for (size_t i = 0; i < expected_k; ++i)
205 EXPECT_EQ(sig[i], std::numeric_limits<uint64_t>::max());
206}
207
208TEST(StreamingAlgorithms, MinHash)
209{
210 constexpr size_t K = 256;
211 MinHash<int> mh1(K);
212 MinHash<int> mh2(K);
213 MinHash<int> mh3(K);
214 MinHash<int> mh1_range(K);
215
216 // Set 1: [0..99]
217 // Set 2: [50..149] -> Intersection 50, Union 150 -> Jaccard = 1/3
218 // Set 3: [200..299] -> Jaccard with 1 = 0
219 DynArray<int> set1, set2, set3;
220 for (int i = 0; i < 100; ++i)
221 {
222 set1.append(i);
223 set2.append(i + 50);
224 set3.append(i + 200);
225 }
226 ASSERT_EQ(set1.size(), 100u);
227 ASSERT_EQ(set2.size(), 100u);
228 ASSERT_EQ(set3.size(), 100u);
229
230 for (int i = 0; i < 100; ++i) mh1.update(i);
231 for (int i = 50; i < 150; ++i) mh2.update(i);
232 for (int i = 200; i < 300; ++i) mh3.update(i);
233 mh1_range.update(set1.begin(), set1.end()); // range overload
234
235 EXPECT_EQ(mh1.size(), K);
236 EXPECT_EQ(mh2.size(), K);
237 EXPECT_EQ(mh3.size(), K);
238 EXPECT_EQ(mh1_range.size(), K);
239
240 // update(Itor, Itor) must be equivalent to repeated point updates.
241 EXPECT_DOUBLE_EQ(mh1.similarity(mh1_range), 1.0);
242 const auto & sig1 = mh1.get_signature();
243 const auto & sig1_range = mh1_range.get_signature();
244 const auto * sig_ptr = &mh1_range.get_signature();
245 EXPECT_NE(sig_ptr, nullptr);
246 EXPECT_EQ(sig_ptr, &mh1_range.get_signature());
247 ASSERT_EQ(sig1.size(), K);
248 ASSERT_EQ(sig1_range.size(), K);
249
250 bool changed_after_update = false;
251 for (size_t i = 0; i < K; ++i)
252 {
253 EXPECT_EQ(sig1[i], sig1_range[i]);
254 if (sig1_range[i] != std::numeric_limits<uint64_t>::max())
255 changed_after_update = true;
256 }
257 EXPECT_TRUE(changed_after_update);
258
259 double sim12 = mh1.similarity(mh2);
260 double sim13 = mh1.similarity(mh3);
261
262 EXPECT_NEAR(sim12, 1.0/3.0, 0.1);
263 EXPECT_NEAR(sim13, 0.0, 0.05);
264
265 // Merge contract: returns *this and corresponds to union of sets.
266 MinHash<int> mh_union_expected(K);
267 DynArray<int> union12;
268 for (int i = 0; i < 150; ++i)
269 union12.append(i);
270 ASSERT_EQ(union12.size(), 150u);
271 mh_union_expected.update(union12.begin(), union12.end());
272
273 MinHash<int> mh_merged = mh1;
274 MinHash<int> & merge_ret = mh_merged.merge(mh2);
275 EXPECT_EQ(&merge_ret, &mh_merged);
276 EXPECT_EQ(mh_merged.size(), K);
277 EXPECT_DOUBLE_EQ(mh_merged.similarity(mh_union_expected), 1.0);
278
279 const auto & sig2 = mh2.get_signature();
280 const auto & sig_merged = mh_merged.get_signature();
281 const auto & sig_union = mh_union_expected.get_signature();
282 ASSERT_EQ(sig_merged.size(), K);
283 ASSERT_EQ(sig_union.size(), K);
284 for (size_t i = 0; i < K; ++i)
285 {
286 EXPECT_EQ(sig_merged[i], std::min(sig1[i], sig2[i]));
287 EXPECT_EQ(sig_merged[i], sig_union[i]);
288 }
289
290 // Use helper to verify common contracts (size, get_signature, clear).
294 assertMinHashContracts(mh1_range, K);
295}
296
297TEST(StreamingAlgorithms, MinHashNewMethods)
298{
299 // update(Itor, Itor) should produce the same signature as repeated update(val).
300 MinHash<int> mhLoop(64);
301 MinHash<int> mhRange(64);
302
303 DynArray<int> elems;
304 for (int i = 0; i < 50; ++i)
305 elems.append(i);
306
307 for (int i = 0; i < 50; ++i)
308 mhLoop.update(i);
309 mhRange.update(elems.begin(), elems.end());
310
311 EXPECT_DOUBLE_EQ(mhLoop.similarity(mhRange), 1.0);
312
313 assertMinHashContracts(mhLoop, 64);
314 assertMinHashContracts(mhRange, 64);
315
316 // merge() combines two signatures: union of [0..49] and [25..74]
317 // should give same result as building from [0..74] directly.
318 MinHash<int> mhA(64), mhB(64), mhUnion(64);
319 for (int i = 0; i < 50; ++i) mhA.update(i);
320 for (int i = 25; i < 75; ++i) mhB.update(i);
321 for (int i = 0; i < 75; ++i) mhUnion.update(i);
322
323 mhA.merge(mhB);
324 // Merged should be close to union; similarity should be high.
325 EXPECT_GT(mhA.similarity(mhUnion), 0.8);
326
327 // merge() returns *this (chaining works).
328 MinHash<int> mhC(64), mhD(64);
329 mhC.update(1);
330 mhD.update(2);
331 MinHash<int> & ref = mhC.merge(mhD);
332 EXPECT_EQ(&ref, &mhC);
333
334 // size() is stable after merge and clear.
335 EXPECT_EQ(mhA.size(), 64u);
336 mhA.clear();
337 EXPECT_EQ(mhA.size(), 64u);
338}
339
340TEST(StreamingAlgorithms, MinHashPreconditions)
341{
342 // Constructor precondition: k must be > 0.
343 EXPECT_THROW((MinHash<int>(0)), std::domain_error);
344
345 // similarity() and merge() require matching signature sizes.
346 MinHash<int> mh64(64);
347 MinHash<int> mh32(32);
348 mh64.update(1);
349 mh32.update(1);
350
351 EXPECT_THROW((mh64.similarity(mh32)), std::domain_error);
352 EXPECT_THROW((mh32.similarity(mh64)), std::domain_error);
353 EXPECT_THROW(mh64.merge(mh32), std::domain_error);
354 EXPECT_THROW(mh32.merge(mh64), std::domain_error);
355}
356
357TEST(StreamingAlgorithms, SimHash)
358{
359 SimHash<std::string> sh1, sh2, sh3;
360
361 const DynArray<std::string> doc1 = {"this", "is", "a", "test", "document", "with", "some", "words"};
362 const DynArray<std::string> doc2 = {"this", "is", "a", "test", "document", "with", "other", "words"}; // one word diff
363 const DynArray<std::string> doc3 = {"completely", "unrelated", "content", "nothing", "matches", "here", "at", "all"};
364
365 for (size_t i = 0; i < doc1.size(); ++i) sh1.update(doc1[i]);
366 for (size_t i = 0; i < doc2.size(); ++i) sh2.update(doc2[i]);
367 for (size_t i = 0; i < doc3.size(); ++i) sh3.update(doc3[i]);
368
369 uint64_t f1 = sh1.get_fingerprint();
370 uint64_t f2 = sh2.get_fingerprint();
371 uint64_t f3 = sh3.get_fingerprint();
372
373 double sim12 = SimHash<std::string>::similarity(f1, f2);
374 double sim13 = SimHash<std::string>::similarity(f1, f3);
375
376 EXPECT_GT(sim12, 0.8);
377 EXPECT_LT(sim13, 0.7);
378}
379
380TEST(StreamingAlgorithms, EdgeCases)
381{
382 // 1. Reservoir sample with k=0, k=1 and empty input
383 DynList<int> empty_list;
384 EXPECT_EQ(reservoir_sample(empty_list.begin(), empty_list.end(), 0).size(), 0u);
385 EXPECT_EQ(reservoir_sample(empty_list.begin(), empty_list.end(), 5).size(), 0u);
386
387 DynList<int> singleton = {42};
388 auto s1 = reservoir_sample(singleton.begin(), singleton.end(), 1, 123);
389 ASSERT_EQ(s1.size(), 1u);
390 EXPECT_EQ(s1[0], 42);
391
392 // 2. Count-Min Sketch: invalid params and empty/singleton
393 EXPECT_THROW(Count_Min_Sketch<int>::from_error_bounds(0, 0.01), std::domain_error);
394
395 Count_Min_Sketch<int> cms(100, 5);
396 EXPECT_GE(cms.estimate(42), 0u); // empty: 0
397 cms.update(42, 10);
398 EXPECT_EQ(cms.estimate(42), 10u);
399
400 Count_Min_Sketch<int> cms_other(50, 5); // different width
401 EXPECT_THROW(cms.merge(cms_other), std::domain_error);
402
403 // 3. HyperLogLog: empty and singleton
404 HyperLogLog<int> hll(10);
405 EXPECT_NEAR(hll.estimate(), 0.0, 0.1);
406 hll.update(42);
407 EXPECT_NEAR(hll.estimate(), 1.0, 0.5);
408
409 // 4. MinHash: empty and singletons
410 MinHash<int> mh1(64), mh2(64);
411 EXPECT_EQ(mh1.similarity(mh2), 1.0); // empty vs empty
412 mh1.update(100);
413 EXPECT_LT(mh1.similarity(mh2), 0.1); // singleton vs empty
414 mh2.update(100);
415 EXPECT_EQ(mh1.similarity(mh2), 1.0); // same singleton
416
417 // 5. SimHash: empty and singletons
418 SimHash<int> sh1, sh2;
419 EXPECT_EQ(sh1.get_fingerprint(), 0u);
420 EXPECT_EQ(SimHash<int>::similarity(sh1.get_fingerprint(), sh2.get_fingerprint()), 1.0);
421 sh1.update(42);
422 sh2.update(42);
423 EXPECT_EQ(sh1.get_fingerprint(), sh2.get_fingerprint());
424 EXPECT_EQ(SimHash<int>::similarity(sh1.get_fingerprint(), sh2.get_fingerprint()), 1.0);
425}
426
427TEST(ReservoirSampler, overflow_size_t)
428{
429 // Keep internal state consistent: for n_seen_ >= k, the reservoir must be full.
430 Reservoir_Sampler<int> s(5, 42);
431 for (int i = 0; i < 5; ++i)
432 s.update(i);
433 s.set_n_seen_for_testing(std::numeric_limits<size_t>::max());
434 EXPECT_THROW(s.update(1), std::overflow_error);
435
436 // Iterator overload delegates to update(), so the same guard fires.
437 Reservoir_Sampler<int> s2(5, 42);
438 for (int i = 0; i < 5; ++i)
439 s2.update(i);
440 s2.set_n_seen_for_testing(std::numeric_limits<size_t>::max());
441 DynArray<int> one = {99};
442 EXPECT_THROW(s2.update(one.begin(), one.end()), std::overflow_error);
443}
444
445TEST(ReservoirSampler, overflow_rng_range)
446{
447 // RNG range exhaustion fires when n_seen_ >= rng_range_, but only after
448 // the reservoir is already full (n_seen_ >= k). Seed the reservoir first
449 // via legitimate updates, then jump n_seen_ to rng_range_.
450 Reservoir_Sampler<int> s(3, 42);
451 for (int i = 0; i < 3; ++i)
452 s.update(i); // fill reservoir: n_seen_ == 3
453
454 const uint64_t rng_range = s.rng_range();
455 s.set_n_seen_for_testing(rng_range); // n_seen_ == rng_range_ >= k
456 EXPECT_THROW(s.update(99), std::runtime_error);
457
458 // Same path through the iterator overload.
459 Reservoir_Sampler<int> s2(3, 42);
460 for (int i = 0; i < 3; ++i)
461 s2.update(i);
462 s2.set_n_seen_for_testing(rng_range);
463 DynArray<int> one2 = {99};
464 EXPECT_THROW(s2.update(one2.begin(), one2.end()), std::runtime_error);
465}
466
467TEST(StreamingAlgorithms, CMSSketchMerge)
468{
469 Count_Min_Sketch<int> cms1(size_t(100), size_t(5));
470 Count_Min_Sketch<int> cms2(size_t(100), size_t(5));
471
472 cms1.update(42, 10);
473 cms2.update(42, 5);
474 cms2.update(7, 3);
475
476 cms1.merge(cms2);
477 EXPECT_GE(cms1.estimate(42), 15u);
478 EXPECT_GE(cms1.estimate(7), 3u);
479}
Count-Min Sketch frequency estimator.
void merge(const Count_Min_Sketch &other)
Merge another sketch into this one.
CounterT estimate(const T &val) const
Estimate frequency of an element.
static Count_Min_Sketch from_error_bounds(const double epsilon, const double delta)
Create a sketch with target error bounds.
void update(const T &val, CounterT count=1)
Increment count for an element.
size_t width() const noexcept
Number of counter columns (hash buckets per row).
size_t size() const noexcept
Return the current dimension of array.
T & append()
Allocate a new entry to the end of array.
Doubly-linked list (defined in tpl_dynList.H).
Definition htlist.H:1231
HyperLogLog cardinality estimator.
Definition hyperloglog.H:69
double estimate() const noexcept
Estimate current cardinality.
void clear()
Reset all registers to zero.
void merge(const HyperLogLog &other)
Merge another HyperLogLog into this one (union of sets).
void update(const T &val)
Add an element to the set.
size_t num_registers() const noexcept
Number of HyperLogLog registers (2^b).
MinHash signature generator.
Definition minhash.H:65
MinHash & merge(const MinHash &other)
Merge another MinHash signature into this one.
Definition minhash.H:222
size_t size() const noexcept
Number of hash functions used in the signature.
Definition minhash.H:237
void clear()
Reset the signature to the initial all-maximum state.
Definition minhash.H:206
void update(const T &val)
Add an element to the set.
Definition minhash.H:147
double similarity(const MinHash &other) const
Estimate Jaccard similarity with another signature.
Definition minhash.H:179
const Array< uint64_t > & get_signature() const noexcept
Returns the current signature.
Definition minhash.H:197
Incremental reservoir sampler (Algorithm R).
size_t sample_size() const noexcept
Target sample size.
void update(const T &val)
Process a new element from the stream.
const Array< T > & get_sample() const noexcept
Returns the current random sample.
uint64_t rng_range() const noexcept
RNG output range (max - min + 1).
void set_n_seen_for_testing(const size_t n)
Forcibly set the internal stream counter (for testing only).
size_t total_seen() const noexcept
Total elements processed so far.
SimHash fingerprint generator.
Definition simhash.H:66
void update(const T &val, const double weight=1.0)
Add a feature to the set.
Definition simhash.H:107
static double similarity(const uint64_t f1, const uint64_t f2) noexcept
Estimate similarity with another fingerprint.
Definition simhash.H:152
uint64_t get_fingerprint() const noexcept
Returns the fingerprint.
Definition simhash.H:139
iterator end() noexcept
Return an STL-compatible end iterator.
iterator begin() noexcept
Return an STL-compatible iterator to the first element.
Count-Min Sketch for frequency estimation in streams.
#define TEST(name)
HyperLogLog for approximate cardinality estimation.
MinHash for estimating Jaccard similarity between sets.
Main namespace for Aleph-w library functions.
auto reservoir_sample(Itor beg, Sent end, size_t k, unsigned long seed=static_cast< unsigned long >(std::chrono::high_resolution_clock::now().time_since_epoch().count()))
Convenience function to sample k elements from a range.
Reservoir sampling for random selection from data streams.
SimHash for estimating cosine similarity between sets of features.
static void assertMinHashContracts(MinHash< int > &mh, size_t expected_k)
static int * k
Lazy and scalable dynamic array implementation.
Alias for htlist.H (DynList implementation).
Unified hash table interface.