datasketches-cpp
Loading...
Searching...
No Matches
count_min_impl.hpp
1/*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19
20#ifndef COUNT_MIN_IMPL_HPP_
21#define COUNT_MIN_IMPL_HPP_
22
23#include <algorithm>
24#include <iomanip>
25#include <random>
26#include <sstream>
27
28#include "MurmurHash3.h"
29#include "count_min.hpp"
30#include "memory_operations.hpp"
31
32namespace datasketches {
33
34template<typename W, typename A>
35count_min_sketch<W,A>::count_min_sketch(uint8_t num_hashes, uint32_t num_buckets, uint64_t seed, const A& allocator):
36_allocator(allocator),
37_num_hashes(num_hashes),
38_num_buckets(num_buckets),
39_sketch_array((static_cast<uint64_t>(num_hashes) * num_buckets < 1<<30) ? static_cast<size_t>(num_hashes) * num_buckets : 0, 0, _allocator),
40_seed(seed),
41_total_weight(0),
42hash_seeds(_allocator) {
43 if (num_buckets < 3) {
44 throw std::invalid_argument("Using fewer than 3 buckets incurs relative error greater than 1.");
45 }
46
47 // This check is to ensure later compatibility with a Java implementation whose maximum size can only
48 // be 2^31-1. We check only against 2^30 for simplicity.
49 if (static_cast<uint64_t>(num_buckets) * num_hashes >= 1 << 30) {
50 throw std::invalid_argument("These parameters generate a sketch that exceeds 2^30 elements."
51 "Try reducing either the number of buckets or the number of hash functions.");
52 }
53
54 std::default_random_engine rng(_seed);
55 std::uniform_int_distribution<uint64_t> extra_hash_seeds(0, std::numeric_limits<uint64_t>::max());
56 hash_seeds.reserve(num_hashes);
57
58 for (uint64_t i=0; i < num_hashes; ++i) {
59 hash_seeds.push_back(extra_hash_seeds(rng) + _seed); // Adds the global seed to all hash functions.
60 }
61}
62
63template<typename W, typename A>
65 return _num_hashes;
66}
67
68template<typename W, typename A>
70 return _num_buckets;
71}
72
73template<typename W, typename A>
75 return _seed;
76}
77
78template<typename W, typename A>
80 return exp(1.0) / static_cast<double>(_num_buckets);
81}
82
83template<typename W, typename A>
85 return _total_weight;
86}
87
88template<typename W, typename A>
89uint32_t count_min_sketch<W,A>::suggest_num_buckets(double relative_error) {
90 /*
91 * Function to help users select a number of buckets for a given error.
92 * TODO: Change this when we use only power of 2 buckets.
93 */
94 if (relative_error < 0.) {
95 throw std::invalid_argument("Relative error must be at least 0.");
96 }
97 return static_cast<uint32_t>(ceil(exp(1.0) / relative_error));
98}
99
100template<typename W, typename A>
101uint8_t count_min_sketch<W,A>::suggest_num_hashes(double confidence) {
102 /*
103 * Function to help users select a number of hashes for a given confidence
104 * e.g. confidence = 1 - failure probability
105 * failure probability == delta in the literature.
106 */
107 if (confidence < 0. || confidence > 1.0) {
108 throw std::invalid_argument("Confidence must be between 0 and 1.0 (inclusive).");
109 }
110 return std::min<uint8_t>(ceil(log(1.0 / (1.0 - confidence))), UINT8_MAX);
111}
112
113template<typename W, typename A>
114template<typename F>
115void count_min_sketch<W,A>::foreach_hash_location(const void* item, size_t size, F callback) const {
116 /*
117 * Computes the hash locations for the input item using the original hashing
118 * scheme from [1].
119 * Generate _num_hashes separate hashes from calls to murmurmhash.
120 * This could be optimized by keeping both of the 64bit parts of the hash
121 * function, rather than generating a new one for every level.
122 *
123 *
124 * Postscript.
125 * Note that a tradeoff can be achieved over the update time and space
126 * complexity of the sketch by using a combinatorial hashing scheme from
127 * https://github.com/Claudenw/BloomFilter/wiki/Bloom-Filters----An-overview
128 * https://www.eecs.harvard.edu/~michaelm/postscripts/tr-02-05.pdf
129 */
130 uint64_t bucket_index;
131
132 uint64_t hash_seed_index = 0;
133 for (const auto &it: hash_seeds) {
134 HashState hashes;
135 MurmurHash3_x64_128(item, size, it, hashes); // ? BEWARE OVERFLOW.
136 uint64_t hash = hashes.h1;
137 bucket_index = hash % _num_buckets;
138 callback((hash_seed_index * _num_buckets) + bucket_index);
139 hash_seed_index += 1;
140 }
141}
142
143template<typename W, typename A>
144W count_min_sketch<W,A>::get_estimate(uint64_t item) const {return get_estimate(&item, sizeof(item));}
145
146template<typename W, typename A>
147W count_min_sketch<W,A>::get_estimate(int64_t item) const {return get_estimate(&item, sizeof(item));}
148
149template<typename W, typename A>
150W count_min_sketch<W,A>::get_estimate(const std::string& item) const {
151 if (item.empty()) { return 0; } // Empty strings are not inserted into the sketch.
152 return get_estimate(item.c_str(), item.length());
153}
154
155template<typename W, typename A>
156W count_min_sketch<W,A>::get_estimate(const void* item, size_t size) const {
157 /*
158 * Returns the estimated frequency of the item
159 */
160 W estimate = std::numeric_limits<W>::max();
161 foreach_hash_location(item, size, [this, &estimate](uint64_t h) {
162 estimate = std::min(estimate, _sketch_array[h]);
163 });
164 return estimate;
165}
166
167template<typename W, typename A>
168void count_min_sketch<W,A>::update(uint64_t item, W weight) {
169 update(&item, sizeof(item), weight);
170}
171
172template<typename W, typename A>
173void count_min_sketch<W,A>::update(int64_t item, W weight) {
174 update(&item, sizeof(item), weight);
175}
176
177template<typename W, typename A>
178void count_min_sketch<W,A>::update(const std::string& item, W weight) {
179 if (item.empty()) { return; }
180 update(item.c_str(), item.length(), weight);
181}
182
183template<typename W, typename A>
184void count_min_sketch<W,A>::update(const void* item, size_t size, W weight) {
185 /*
186 * Gets the item's hash locations and then increments the sketch in those
187 * locations by the weight.
188 */
189 _total_weight += weight >= 0 ? weight : -weight;
190 foreach_hash_location(item, size, [this, weight](uint64_t h) {
191 _sketch_array[h] += weight;
192 });
193}
194
195template<typename W, typename A>
196W count_min_sketch<W,A>::get_upper_bound(uint64_t item) const {return get_upper_bound(&item, sizeof(item));}
197
198template<typename W, typename A>
199W count_min_sketch<W,A>::get_upper_bound(int64_t item) const {return get_upper_bound(&item, sizeof(item));}
200
201template<typename W, typename A>
202W count_min_sketch<W,A>::get_upper_bound(const std::string& item) const {
203 if (item.empty()) { return 0; } // Empty strings are not inserted into the sketch.
204 return get_upper_bound(item.c_str(), item.length());
205}
206
207template<typename W, typename A>
208W count_min_sketch<W,A>::get_upper_bound(const void* item, size_t size) const {
209 return static_cast<W>(get_estimate(item, size) + get_relative_error() * get_total_weight());
210}
211
212template<typename W, typename A>
213W count_min_sketch<W,A>::get_lower_bound(uint64_t item) const {return get_lower_bound(&item, sizeof(item));}
214
215template<typename W, typename A>
216W count_min_sketch<W,A>::get_lower_bound(int64_t item) const {return get_lower_bound(&item, sizeof(item));}
217
218template<typename W, typename A>
219W count_min_sketch<W,A>::get_lower_bound(const std::string& item) const {
220 if (item.empty()) { return 0; } // Empty strings are not inserted into the sketch.
221 return get_lower_bound(item.c_str(), item.length());
222}
223
224template<typename W, typename A>
225W count_min_sketch<W,A>::get_lower_bound(const void* item, size_t size) const {
226 return get_estimate(item, size);
227}
228
229template<typename W, typename A>
231 /*
232 * Merges this sketch into other_sketch sketch by elementwise summing of buckets
233 */
234 if (this == &other_sketch) { throw std::invalid_argument( "Cannot merge a sketch with itself." ); }
235
236 bool acceptable_config =
237 (get_num_hashes() == other_sketch.get_num_hashes()) &&
238 (get_num_buckets() == other_sketch.get_num_buckets()) &&
239 (get_seed() == other_sketch.get_seed());
240 if (!acceptable_config) { throw std::invalid_argument( "Incompatible sketch configuration." ); }
241
242 // Merge step - iterate over the other vector and add the weights to this sketch
243 auto it = _sketch_array.begin(); // This is a std::vector iterator.
244 auto other_it = other_sketch.begin(); //This is a const iterator over the other sketch.
245 while (it != _sketch_array.end()) {
246 *it += *other_it;
247 ++it;
248 ++other_it;
249 }
250 _total_weight += other_sketch.get_total_weight();
251}
252
253// Iterators
254template<typename W, typename A>
255typename count_min_sketch<W,A>::const_iterator count_min_sketch<W,A>::begin() const {
256 return _sketch_array.begin();
257}
258
259template<typename W, typename A>
260typename count_min_sketch<W,A>::const_iterator count_min_sketch<W,A>::end() const {
261return _sketch_array.end();
262}
263
264template<typename W, typename A>
265void count_min_sketch<W,A>::serialize(std::ostream& os) const {
266 serialize_to([&os](const void* data, size_t size) {
267 os.write(static_cast<const char*>(data), size);
268 });
269}
270
271template<typename Sink, typename T>
272static inline void write_count_min_value(Sink& sink, size_t& bytes_written, const T& value) {
273 sink(&value, sizeof(value));
274 bytes_written += sizeof(value);
275}
276
277template<typename W, typename A>
278template<typename Sink>
279size_t count_min_sketch<W,A>::serialize_to(Sink&& sink) const {
280 size_t bytes_written = 0;
281
282 // Long 0
283 //const uint8_t preamble_longs = is_empty() ? PREAMBLE_LONGS_SHORT : PREAMBLE_LONGS_FULL;
284 const uint8_t preamble_longs = PREAMBLE_LONGS_SHORT;
285 const uint8_t ser_ver = SERIAL_VERSION_1;
286 const uint8_t family_id = FAMILY_ID;
287 const uint8_t flags_byte = (is_empty() ? 1 << flags::IS_EMPTY : 0);
288 const uint32_t unused32 = NULL_32;
289 write_count_min_value(sink, bytes_written, preamble_longs);
290 write_count_min_value(sink, bytes_written, ser_ver);
291 write_count_min_value(sink, bytes_written, family_id);
292 write_count_min_value(sink, bytes_written, flags_byte);
293 write_count_min_value(sink, bytes_written, unused32);
294
295 // Long 1
296 const uint32_t nbuckets = _num_buckets;
297 const uint8_t nhashes = _num_hashes;
298 const uint16_t seed_hash(compute_seed_hash(_seed));
299 const uint8_t unused8 = NULL_8;
300 write_count_min_value(sink, bytes_written, nbuckets);
301 write_count_min_value(sink, bytes_written, nhashes);
302 write_count_min_value(sink, bytes_written, seed_hash);
303 write_count_min_value(sink, bytes_written, unused8);
304 if (is_empty()) { return bytes_written; } // sketch is empty, no need to write further bytes.
305
306 // Long 2
307 const W t_weight = _total_weight;
308 write_count_min_value(sink, bytes_written, t_weight);
309
310 // Long 3 onwards: remaining bytes are consumed by writing the weight and the array values.
311 const size_t sketch_array_bytes = sizeof(W) * _sketch_array.size();
312 if (sketch_array_bytes > 0) {
313 sink(_sketch_array.data(), sketch_array_bytes);
314 bytes_written += sketch_array_bytes;
315 }
316
317 return bytes_written;
318}
319
320template<typename W, typename A>
321auto count_min_sketch<W,A>::deserialize(std::istream& is, uint64_t seed, const A& allocator) -> count_min_sketch {
322
323 // First 8 bytes are 4 bytes of preamble and 4 unused bytes.
324 const auto preamble_longs = read<uint8_t>(is);
325 const auto serial_version = read<uint8_t>(is);
326 const auto family_id = read<uint8_t>(is);
327 const auto flags_byte = read<uint8_t>(is);
328 read<uint32_t>(is); // 4 unused bytes
329
330 check_header_validity(preamble_longs, serial_version, family_id, flags_byte);
331
332 // Sketch parameters
333 const auto nbuckets = read<uint32_t>(is);
334 const auto nhashes = read<uint8_t>(is);
335 const auto seed_hash = read<uint16_t>(is);
336 read<uint8_t>(is); // 1 unused byte
337
338 if (seed_hash != compute_seed_hash(seed)) {
339 throw std::invalid_argument("Incompatible seed hashes: " + std::to_string(seed_hash) + ", "
340 + std::to_string(compute_seed_hash(seed)));
341 }
342 count_min_sketch c(nhashes, nbuckets, seed, allocator);
343 const bool is_empty = (flags_byte & (1 << flags::IS_EMPTY)) > 0;
344 if (is_empty == 1) { return c; } // sketch is empty, no need to read further.
345
346 // Set the sketch weight and read in the sketch values
347 const auto weight = read<W>(is);
348 c._total_weight += weight;
349 read(is, c._sketch_array.data(), sizeof(W) * c._sketch_array.size());
350
351 return c;
352}
353
354template<typename W, typename A>
356 // The header is always 2 longs, whether empty or full
357 const size_t preamble_longs = PREAMBLE_LONGS_SHORT;
358
359 // If the sketch is empty, we're done. Otherwise, we need the total weight
360 // held by the sketch as well as a data table of size (num_buckets * num_hashes)
361 return (preamble_longs * sizeof(uint64_t)) + (is_empty() ? 0 : sizeof(W) * (1 + _num_buckets * _num_hashes));
362}
363
364template<typename W, typename A>
365auto count_min_sketch<W,A>::serialize(unsigned header_size_bytes) const -> vector_bytes {
366 vector_bytes bytes(header_size_bytes + get_serialized_size_bytes(), 0, _allocator);
367 uint8_t *ptr = bytes.data() + header_size_bytes;
368 serialize_to([&ptr](const void* data, size_t size) {
369 ptr += copy_to_mem(data, ptr, size);
370 });
371
372 return bytes;
373}
374
375template<typename W, typename A>
376auto count_min_sketch<W,A>::deserialize(const void* bytes, size_t size, uint64_t seed, const A& allocator) -> count_min_sketch {
377 ensure_minimum_memory(size, PREAMBLE_LONGS_SHORT * sizeof(uint64_t));
378
379 const char* ptr = static_cast<const char*>(bytes);
380
381 // First 8 bytes are 4 bytes of preamble and 4 unused bytes.
382 uint8_t preamble_longs;
383 ptr += copy_from_mem(ptr, preamble_longs);
384 uint8_t serial_version;
385 ptr += copy_from_mem(ptr, serial_version);
386 uint8_t family_id;
387 ptr += copy_from_mem(ptr, family_id);
388 uint8_t flags_byte;
389 ptr += copy_from_mem(ptr, flags_byte);
390 ptr += sizeof(uint32_t);
391
392 check_header_validity(preamble_longs, serial_version, family_id, flags_byte);
393
394 // Second 8 bytes are the sketch parameters with a final, unused byte.
395 uint32_t nbuckets;
396 uint8_t nhashes;
397 uint16_t seed_hash;
398 ptr += copy_from_mem(ptr, nbuckets);
399 ptr += copy_from_mem(ptr, nhashes);
400 ptr += copy_from_mem(ptr, seed_hash);
401 ptr += sizeof(uint8_t);
402
403 if (seed_hash != compute_seed_hash(seed)) {
404 throw std::invalid_argument("Incompatible seed hashes: " + std::to_string(seed_hash) + ", "
405 + std::to_string(compute_seed_hash(seed)));
406 }
407 count_min_sketch c(nhashes, nbuckets, seed, allocator);
408 const bool is_empty = (flags_byte & (1 << flags::IS_EMPTY)) > 0;
409 if (is_empty) { return c; } // sketch is empty, no need to read further.
410
411 // preamble (already read) + total weight + table; nbuckets * nhashes < 2^30 was checked by the constructor
412 ensure_minimum_memory(size, PREAMBLE_LONGS_SHORT * sizeof(uint64_t) + sizeof(W) * (1 + c._sketch_array.size()));
413
414 // Long 2 is the weight.
415 W weight;
416 ptr += copy_from_mem(ptr, weight);
417 c._total_weight += weight;
418
419 // All remaining bytes are the sketch table entries.
420 for (size_t i = 0; i<c._num_buckets*c._num_hashes; ++i) {
421 ptr += copy_from_mem(ptr, c._sketch_array[i]);
422 }
423 return c;
424}
425
426template<typename W, typename A>
428 return _total_weight == 0;
429}
430
431template<typename W, typename A>
433 // count the number of used entries in the sketch
434 uint64_t num_nonzero = 0;
435 for (const auto entry: _sketch_array) {
436 if (entry != static_cast<W>(0.0)) { ++num_nonzero; }
437 }
438
439 // Using a temporary stream for implementation here does not comply with AllocatorAwareContainer requirements.
440 // The stream does not support passing an allocator instance, and alternatives are complicated.
441 std::ostringstream os;
442 os << "### Count Min sketch summary:" << std::endl;
443 os << " num hashes : " << static_cast<uint32_t>(_num_hashes) << std::endl;
444 os << " num buckets : " << _num_buckets << std::endl;
445 os << " capacity bins : " << _sketch_array.size() << std::endl;
446 os << " filled bins : " << num_nonzero << std::endl;
447 os << " pct filled : " << std::setprecision(3) << (num_nonzero * 100.0) / _sketch_array.size() << "%" << std::endl;
448 os << "### End sketch summary" << std::endl;
449
450 return string<A>(os.str().c_str(), _allocator);
451}
452
453template<typename W, typename A>
454void count_min_sketch<W,A>::check_header_validity(uint8_t preamble_longs, uint8_t serial_version, uint8_t family_id, uint8_t flags_byte) {
455 const bool empty = (flags_byte & (1 << flags::IS_EMPTY)) > 0;
456
457 const uint8_t sw = (empty ? 1 : 0) + (2 * serial_version) + (4 * family_id) + (32 * (preamble_longs & 0x3F));
458 bool valid = true;
459
460 switch (sw) { // exhaustive list and description of all valid cases
461 case 138 : break; // !empty, ser_ver==1, family==18, preLongs=2;
462 case 139 : break; // empty, ser_ver==1, family==18, preLongs=2;
463 //case 170 : break; // !empty, ser_ver==1, family==18, preLongs=3;
464 default : // all other case values are invalid
465 valid = false;
466 }
467
468 if (!valid) {
469 std::ostringstream os;
470 os << "Possible sketch corruption. Inconsistent state: "
471 << "preamble_longs = " << static_cast<uint32_t>(preamble_longs)
472 << ", empty = " << (empty ? "true" : "false")
473 << ", serialization_version = " << static_cast<uint32_t>(serial_version);
474 throw std::invalid_argument(os.str());
475 }
476}
477
478} /* namespace datasketches */
479
480#endif
C++ implementation of the CountMin sketch data structure of Cormode and Muthukrishnan.
Definition count_min.hpp:39
static count_min_sketch deserialize(std::istream &is, uint64_t seed=DEFAULT_SEED, const Allocator &allocator=Allocator())
This method deserializes a sketch from a given stream.
void serialize(std::ostream &os) const
This method serializes the sketch into a given stream in a binary form.
Definition count_min_impl.hpp:265
const_iterator end() const
Iterator pointing to the past-the-end item in the sketch.
Definition count_min_impl.hpp:260
double get_relative_error() const
Definition count_min_impl.hpp:79
uint32_t get_num_buckets() const
Definition count_min_impl.hpp:69
size_t serialize_to(Sink &&sink) const
This method serializes the sketch by passing binary fragments to a callback.
Definition count_min_impl.hpp:279
bool is_empty() const
Returns true if this sketch is empty.
Definition count_min_impl.hpp:427
W get_total_weight() const
Definition count_min_impl.hpp:84
uint8_t get_num_hashes() const
Definition count_min_impl.hpp:64
W get_upper_bound(const void *item, size_t size) const
Query the sketch for the upper bound of a given item.
Definition count_min_impl.hpp:208
W get_lower_bound(const void *item, size_t size) const
Query the sketch for the lower bound of a given item.
Definition count_min_impl.hpp:225
W get_estimate(uint64_t item) const
Suggests the number of buckets required to achieve the given relative error.
Definition count_min_impl.hpp:144
count_min_sketch(uint8_t num_hashes, uint32_t num_buckets, uint64_t seed=DEFAULT_SEED, const Allocator &allocator=Allocator())
Creates an instance of the sketch given parameters _num_hashes, _num_buckets and hash seed,...
Definition count_min_impl.hpp:35
uint64_t get_seed() const
Definition count_min_impl.hpp:74
void merge(const count_min_sketch &other_sketch)
Merges another count_min_sketch into this count_min_sketch.
Definition count_min_impl.hpp:230
void update(const void *item, size_t size, W weight)
Update this sketch with given data of any type.
Definition count_min_impl.hpp:184
string< Allocator > to_string() const
Returns a string describing the sketch.
Definition count_min_impl.hpp:432
size_t get_serialized_size_bytes() const
Computes size needed to serialize the current state of the sketch.
Definition count_min_impl.hpp:355
const_iterator begin() const
Iterator pointing to the first item in the sketch.
Definition count_min_impl.hpp:255
DataSketches namespace.
Definition binomial_bounds.hpp:38