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