20#ifndef COUNT_MIN_IMPL_HPP_
21#define COUNT_MIN_IMPL_HPP_
28#include "MurmurHash3.h"
29#include "count_min.hpp"
31#include "memory_operations.hpp"
35template<
typename W,
typename A>
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,
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),
50hash_seeds(_allocator) {
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));
57 if (num_buckets < 3) {
58 throw std::invalid_argument(
"Using fewer than 3 buckets incurs relative error greater than 1.");
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.");
68 hash_seeds.reserve(num_hashes);
69 if (serial_version == SERIAL_VERSION_1) {
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);
78 for (uint64_t i=0; i < num_hashes; ++i) {
84template<
typename W,
typename A>
86 return _serial_version;
89template<
typename W,
typename A>
94template<
typename W,
typename A>
99template<
typename W,
typename A>
104template<
typename W,
typename A>
106 return exp(1.0) /
static_cast<double>(_num_buckets);
109template<
typename W,
typename A>
111 return _total_weight;
114template<
typename W,
typename A>
120 if (relative_error < 0.) {
121 throw std::invalid_argument(
"Relative error must be at least 0.");
123 return static_cast<uint32_t
>(ceil(exp(1.0) / relative_error));
126template<
typename W,
typename A>
127uint8_t count_min_sketch<W,A>::suggest_num_hashes(
double confidence) {
133 if (confidence < 0. || confidence > 1.0) {
134 throw std::invalid_argument(
"Confidence must be between 0 and 1.0 (inclusive).");
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))));
139template<
typename W,
typename A>
141void count_min_sketch<W,A>::foreach_hash_location(
const void* item,
size_t size, F callback)
const {
156 uint64_t bucket_index;
158 uint64_t hash_seed_index = 0;
159 for (
const auto &it: hash_seeds) {
160 if (_serial_version == SERIAL_VERSION_1) {
162 MurmurHash3_x64_128(item, size, it, hashes);
163 bucket_index = hashes.h1 % _num_buckets;
166 bucket_index = (
XXHash64::hash(item, size, it) >> 1) % _num_buckets;
168 callback((hash_seed_index * _num_buckets) + bucket_index);
169 hash_seed_index += 1;
173template<
typename W,
typename A>
176template<
typename W,
typename A>
179template<
typename W,
typename A>
181 if (item.empty()) {
return 0; }
185template<
typename W,
typename A>
190 if (size == 0) {
return 0; }
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]);
198template<
typename W,
typename A>
200 update(&item,
sizeof(item), weight);
203template<
typename W,
typename A>
205 update(&item,
sizeof(item), weight);
208template<
typename W,
typename A>
210 if (item.empty()) {
return; }
211 update(item.c_str(), item.length(), weight);
214template<
typename W,
typename A>
220 if (size == 0) {
return; }
221 _total_weight += weight >= 0 ? weight : -weight;
222 foreach_hash_location(item, size, [
this, weight](uint64_t h) {
223 _sketch_array[h] += weight;
227template<
typename W,
typename A>
230template<
typename W,
typename A>
233template<
typename W,
typename A>
235 if (item.empty()) {
return 0; }
239template<
typename W,
typename A>
241 if (size == 0) {
return 0; }
245template<
typename W,
typename A>
248template<
typename W,
typename A>
251template<
typename W,
typename A>
253 if (item.empty()) {
return 0; }
257template<
typename W,
typename A>
259 if (size == 0) {
return 0; }
263template<
typename W,
typename A>
268 if (
this == &other_sketch) {
throw std::invalid_argument(
"Cannot merge a sketch with itself." ); }
270 bool acceptable_config =
274 if (!acceptable_config) {
throw std::invalid_argument(
"Incompatible sketch configuration." ); }
277 throw std::invalid_argument(
"Cannot merge sketches with different serial versions: "
283 auto it = _sketch_array.begin();
284 auto other_it = other_sketch.
begin();
285 while (it != _sketch_array.end()) {
294template<
typename W,
typename A>
296 return _sketch_array.begin();
299template<
typename W,
typename A>
301return _sketch_array.end();
304template<
typename W,
typename A>
307 os.write(
static_cast<const char*
>(data), size);
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);
317template<
typename W,
typename A>
318template<
typename Sink>
320 size_t bytes_written = 0;
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);
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; }
347 const W t_weight = _total_weight;
348 write_count_min_value(sink, bytes_written, t_weight);
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;
357 return bytes_written;
360template<
typename W,
typename A>
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);
370 check_header_validity(preamble_longs, serial_version, family_id);
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);
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)));
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; }
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());
394template<
typename W,
typename A>
397 const size_t preamble_longs = PREAMBLE_LONGS_SHORT;
401 return (preamble_longs *
sizeof(uint64_t)) + (
is_empty() ? 0 :
sizeof(W) * (1 + _num_buckets * _num_hashes));
404template<
typename W,
typename A>
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);
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));
419 const char* ptr =
static_cast<const char*
>(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);
427 ptr += copy_from_mem(ptr, family_id);
429 ptr += copy_from_mem(ptr, flags_byte);
430 ptr +=
sizeof(uint32_t);
432 check_header_validity(preamble_longs, serial_version, family_id);
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);
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)));
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; }
452 ensure_minimum_memory(size, PREAMBLE_LONGS_SHORT *
sizeof(uint64_t) +
sizeof(W) * (1 + c._sketch_array.size()));
456 ptr += copy_from_mem(ptr, weight);
457 c._total_weight += weight;
460 for (
size_t i = 0; i<c._num_buckets*c._num_hashes; ++i) {
461 ptr += copy_from_mem(ptr, c._sketch_array[i]);
466template<
typename W,
typename A>
468 return _total_weight == 0;
471template<
typename W,
typename A>
474 uint64_t num_nonzero = 0;
475 for (
const auto entry: _sketch_array) {
476 if (entry !=
static_cast<W
>(0.0)) { ++num_nonzero; }
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;
490 return string<A>(os.str().c_str(), _allocator);
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) {
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));
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));
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));
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