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