20#ifndef FREQUENT_ITEMS_SKETCH_IMPL_HPP_
21#define FREQUENT_ITEMS_SKETCH_IMPL_HPP_
29#include "memory_operations.hpp"
34template<
typename T,
typename W,
typename H,
typename E,
typename A>
35const uint8_t frequent_items_sketch<T, W, H, E, A>::LG_MIN_MAP_SIZE;
37template<
typename T,
typename W,
typename H,
typename E,
typename A>
39 const E& equal,
const A& allocator):
49 if (lg_start_map_size > lg_max_map_size) {
throw std::invalid_argument(
"starting size must not be greater than maximum size"); }
52template<
typename T,
typename W,
typename H,
typename E,
typename A>
55 if (weight == 0) {
return; }
56 total_weight += weight;
57 offset += map.adjust_or_insert(item, weight);
60template<
typename T,
typename W,
typename H,
typename E,
typename A>
63 if (weight == 0) {
return; }
64 total_weight += weight;
65 offset += map.adjust_or_insert(std::move(item), weight);
68template<
typename T,
typename W,
typename H,
typename E,
typename A>
72 for (
auto it: other.map) {
73 update(it.first, it.second);
75 offset += other.offset;
76 total_weight = merged_total_weight;
79template<
typename T,
typename W,
typename H,
typename E,
typename A>
81 if (other.is_empty()) {
return; }
82 const W merged_total_weight = total_weight + other.get_total_weight();
83 for (
auto it: other.map) {
84 update(std::move(it.first), it.second);
86 offset += other.offset;
87 total_weight = merged_total_weight;
90template<
typename T,
typename W,
typename H,
typename E,
typename A>
92 map = reverse_purge_hash_map<T, W, H, E, A>(LG_MIN_MAP_SIZE, map.get_lg_max_size(), map.get_equal(), map.get_allocator());
97template<
typename T,
typename W,
typename H,
typename E,
typename A>
101 return total_weight == 0;
104template<
typename T,
typename W,
typename H,
typename E,
typename A>
106 return map.get_num_active();
109template<
typename T,
typename W,
typename H,
typename E,
typename A>
114template<
typename T,
typename W,
typename H,
typename E,
typename A>
117 const W weight = map.get(item);
118 if (weight > 0) {
return weight + offset; }
122template<
typename T,
typename W,
typename H,
typename E,
typename A>
124 return map.get(item);
127template<
typename T,
typename W,
typename H,
typename E,
typename A>
129 return map.get(item) + offset;
132template<
typename T,
typename W,
typename H,
typename E,
typename A>
137template<
typename T,
typename W,
typename H,
typename E,
typename A>
139 return EPSILON_FACTOR / (1 << map.get_lg_max_size());
142template<
typename T,
typename W,
typename H,
typename E,
typename A>
144 return EPSILON_FACTOR / (1 << lg_max_map_size);
147template<
typename T,
typename W,
typename H,
typename E,
typename A>
149 return get_epsilon(lg_max_map_size) * estimated_total_weight;
153template<
typename T,
typename W,
typename H,
typename E,
typename A>
155 return get_frequent_items(err_type, get_maximum_error());
158template<
typename T,
typename W,
typename H,
typename E,
typename A>
160 vector_row items(map.get_allocator());
162 const W lb = it.second;
163 const W ub = it.second + offset;
165 items.push_back(row(&it.first, it.second, offset));
169 std::sort(items.begin(), items.end(), [](row a, row b){ return a.get_estimate() > b.get_estimate(); });
173template<
typename T,
typename W,
typename H,
typename E,
typename A>
174template<
typename SerDe>
176 const uint8_t preamble_longs =
is_empty() ? PREAMBLE_LONGS_EMPTY : PREAMBLE_LONGS_NONEMPTY;
177 write(os, preamble_longs);
178 const uint8_t serial_version = SERIAL_VERSION;
179 write(os, serial_version);
180 const uint8_t family = FAMILY_ID;
182 const uint8_t lg_max_size = map.get_lg_max_size();
183 write(os, lg_max_size);
184 const uint8_t lg_cur_size = map.get_lg_cur_size();
185 write(os, lg_cur_size);
186 const uint8_t flags_byte(
187 (
is_empty() ? 1 << flags::IS_EMPTY_1 : 0)
188 | (
is_empty() ? 1 << flags::IS_EMPTY_2 : 0)
190 write(os, flags_byte);
191 const uint16_t unused16 = 0;
194 const uint32_t num_items = map.get_num_active();
195 write(os, num_items);
196 const uint32_t unused32 = 0;
198 write(os, total_weight);
205 using AllocW =
typename std::allocator_traits<A>::template rebind_alloc<W>;
206 std::vector<W, AllocW> weights(map.get_allocator());
207 weights.reserve(num_items);
208 std::vector<T, A> items(map.get_allocator());
209 items.reserve(num_items);
211 items.push_back(it.first);
212 weights.push_back(it.second);
214 write(os, weights.data(),
sizeof(W) * num_items);
215 sd.serialize(os, items.data(), num_items);
220template<
typename T,
typename W,
typename H,
typename E,
typename A>
221template<
typename SerDe>
223 if (
is_empty()) {
return PREAMBLE_LONGS_EMPTY *
sizeof(uint64_t); }
224 size_t size = PREAMBLE_LONGS_NONEMPTY *
sizeof(uint64_t) + map.get_num_active() *
sizeof(W);
225 for (
auto it: map) size += sd.size_of_item(it.first);
229template<
typename T,
typename W,
typename H,
typename E,
typename A>
230template<
typename SerDe>
232 const size_t size = header_size_bytes + get_serialized_size_bytes(sd);
233 vector_bytes bytes(size, 0, map.get_allocator());
234 uint8_t* ptr = bytes.data() + header_size_bytes;
235 uint8_t* end_ptr = bytes.data() + size;
237 const uint8_t preamble_longs = is_empty() ? PREAMBLE_LONGS_EMPTY : PREAMBLE_LONGS_NONEMPTY;
238 ptr += copy_to_mem(preamble_longs, ptr);
239 const uint8_t serial_version = SERIAL_VERSION;
240 ptr += copy_to_mem(serial_version, ptr);
241 const uint8_t family = FAMILY_ID;
242 ptr += copy_to_mem(family, ptr);
243 const uint8_t lg_max_size = map.get_lg_max_size();
244 ptr += copy_to_mem(lg_max_size, ptr);
245 const uint8_t lg_cur_size = map.get_lg_cur_size();
246 ptr += copy_to_mem(lg_cur_size, ptr);
247 const uint8_t flags_byte(
248 (is_empty() ? 1 << flags::IS_EMPTY_1 : 0)
249 | (is_empty() ? 1 << flags::IS_EMPTY_2 : 0)
251 ptr += copy_to_mem(flags_byte, ptr);
252 ptr +=
sizeof(uint16_t);
254 const uint32_t num_items = map.get_num_active();
255 ptr += copy_to_mem(num_items, ptr);
256 ptr +=
sizeof(uint32_t);
257 ptr += copy_to_mem(total_weight, ptr);
258 ptr += copy_to_mem(offset, ptr);
264 using AllocW =
typename std::allocator_traits<A>::template rebind_alloc<W>;
265 std::vector<W, AllocW> weights(map.get_allocator());
266 weights.reserve(num_items);
267 std::vector<T, A> items(map.get_allocator());
268 items.reserve(num_items);
270 items.push_back(it.first);
271 weights.push_back(it.second);
273 ptr += copy_to_mem(weights.data(), ptr,
sizeof(W) * num_items);
274 const size_t bytes_remaining = end_ptr - ptr;
275 ptr += sd.serialize(ptr, bytes_remaining, items.data(), num_items);
281template<
typename T,
typename W,
typename H,
typename E,
typename A>
284 items_deleter(uint32_t num,
bool destroy,
const A& allocator):
285 allocator_(allocator), num_(num), destroy_(destroy) {}
286 void set_destroy(
bool destroy) { destroy_ = destroy; }
287 void operator() (T* ptr) {
288 if (ptr !=
nullptr) {
290 for (uint32_t i = 0; i < num_; ++i) ptr[i].~T();
292 allocator_.deallocate(ptr, num_);
301template<
typename T,
typename W,
typename H,
typename E,
typename A>
302template<
typename SerDe>
304 const SerDe& sd,
const E& equal,
const A& allocator) {
305 const auto preamble_longs = read<uint8_t>(is);
306 const auto serial_version = read<uint8_t>(is);
307 const auto family_id = read<uint8_t>(is);
308 const auto lg_max_size = read<uint8_t>(is);
309 const auto lg_cur_size = read<uint8_t>(is);
310 const auto flags_byte = read<uint8_t>(is);
313 check_preamble_longs(preamble_longs, flags_byte);
314 const bool is_empty = preamble_longs == PREAMBLE_LONGS_EMPTY;
315 check_serial_version(serial_version);
316 check_family_id(family_id);
317 check_size(lg_cur_size, lg_max_size);
321 const auto num_items = read<uint32_t>(is);
323 const auto total_weight = read<W>(is);
324 const auto offset = read<W>(is);
325 check_total_weight(total_weight);
328 using AllocW =
typename std::allocator_traits<A>::template rebind_alloc<W>;
329 std::vector<W, AllocW> weights(num_items, 0, allocator);
330 read(is, weights.data(),
sizeof(W) * num_items);
332 std::unique_ptr<T, items_deleter> items(alloc.allocate(num_items), items_deleter(num_items,
false, alloc));
333 sd.deserialize(is, items.get(), num_items);
334 items.get_deleter().set_destroy(
true);
335 for (uint32_t i = 0; i < num_items; i++) {
336 sketch.update(std::move(items.get()[i]), weights[i]);
338 sketch.total_weight = total_weight;
339 sketch.offset = offset;
341 if (!is.good()) {
throw std::runtime_error(
"error reading from std::istream"); }
345template<
typename T,
typename W,
typename H,
typename E,
typename A>
346template<
typename SerDe>
347frequent_items_sketch<T, W, H, E, A> frequent_items_sketch<T, W, H, E, A>::deserialize(
const void* bytes,
size_t size,
348 const SerDe& sd,
const E& equal,
const A& allocator) {
349 ensure_minimum_memory(size, 8);
350 const char* ptr =
static_cast<const char*
>(bytes);
351 const char* base =
static_cast<const char*
>(bytes);
352 uint8_t preamble_longs;
353 ptr += copy_from_mem(ptr, preamble_longs);
354 uint8_t serial_version;
355 ptr += copy_from_mem(ptr, serial_version);
357 ptr += copy_from_mem(ptr, family_id);
359 ptr += copy_from_mem(ptr, lg_max_size);
361 ptr += copy_from_mem(ptr, lg_cur_size);
363 ptr += copy_from_mem(ptr, flags_byte);
364 ptr +=
sizeof(uint16_t);
366 check_preamble_longs(preamble_longs, flags_byte);
367 const bool is_empty = preamble_longs == PREAMBLE_LONGS_EMPTY;
368 check_serial_version(serial_version);
369 check_family_id(family_id);
370 check_size(lg_cur_size, lg_max_size);
371 ensure_minimum_memory(size, preamble_longs *
sizeof(uint64_t));
376 ptr += copy_from_mem(ptr, num_items);
377 ptr +=
sizeof(uint32_t);
379 ptr += copy_from_mem(ptr, total_weight);
381 ptr += copy_from_mem(ptr, offset);
382 check_total_weight(total_weight);
384 ensure_minimum_memory(size, ptr - base + (
sizeof(W) * num_items));
386 using AllocW =
typename std::allocator_traits<A>::template rebind_alloc<W>;
387 std::vector<W, AllocW> weights(num_items, 0, allocator);
388 ptr += copy_from_mem(ptr, weights.data(),
sizeof(W) * num_items);
390 std::unique_ptr<T, items_deleter> items(alloc.allocate(num_items), items_deleter(num_items,
false, alloc));
391 const size_t bytes_remaining = size - (ptr - base);
392 ptr += sd.deserialize(ptr, bytes_remaining, items.get(), num_items);
393 items.get_deleter().set_destroy(
true);
394 for (uint32_t i = 0; i < num_items; i++) {
395 sketch.update(std::move(items.get()[i]), weights[i]);
398 sketch.total_weight = total_weight;
399 sketch.offset = offset;
404template<
typename T,
typename W,
typename H,
typename E,
typename A>
405void frequent_items_sketch<T, W, H, E, A>::check_preamble_longs(uint8_t preamble_longs, uint8_t flags_byte) {
406 if (preamble_longs != PREAMBLE_LONGS_EMPTY && preamble_longs != PREAMBLE_LONGS_NONEMPTY) {
407 throw std::invalid_argument(
"Possible corruption: preamble longs must be " + std::to_string(PREAMBLE_LONGS_EMPTY)
408 +
" or " + std::to_string(PREAMBLE_LONGS_NONEMPTY) +
": " + std::to_string(preamble_longs));
410 const bool empty_flag = (flags_byte & ((1 << flags::IS_EMPTY_1) | (1 << flags::IS_EMPTY_2))) != 0;
411 if (empty_flag != (preamble_longs == PREAMBLE_LONGS_EMPTY)) {
412 throw std::invalid_argument(
"Possible corruption: empty flag does not match preamble longs: flags "
413 + std::to_string(flags_byte) +
", preamble longs " + std::to_string(preamble_longs));
417template<
typename T,
typename W,
typename H,
typename E,
typename A>
418void frequent_items_sketch<T, W, H, E, A>::check_total_weight(W total_weight) {
420 if (!(total_weight > 0)) {
421 throw std::invalid_argument(
"Possible corruption: total weight of a non-empty sketch must be positive");
425template<
typename T,
typename W,
typename H,
typename E,
typename A>
426void frequent_items_sketch<T, W, H, E, A>::check_serial_version(uint8_t serial_version) {
427 if (serial_version != SERIAL_VERSION) {
428 throw std::invalid_argument(
"Possible corruption: serial version must be " + std::to_string(SERIAL_VERSION) +
": " + std::to_string(serial_version));
432template<
typename T,
typename W,
typename H,
typename E,
typename A>
433void frequent_items_sketch<T, W, H, E, A>::check_family_id(uint8_t family_id) {
434 if (family_id != FAMILY_ID) {
435 throw std::invalid_argument(
"Possible corruption: family ID must be " + std::to_string(FAMILY_ID) +
": " + std::to_string(family_id));
439template<
typename T,
typename W,
typename H,
typename E,
typename A>
440void frequent_items_sketch<T, W, H, E, A>::check_size(uint8_t lg_cur_size, uint8_t lg_max_size) {
441 if (lg_cur_size > lg_max_size) {
442 throw std::invalid_argument(
"Possible corruption: expected lg_cur_size <= lg_max_size: " + std::to_string(lg_cur_size) +
" <= " + std::to_string(lg_max_size));
444 if (lg_cur_size < LG_MIN_MAP_SIZE) {
445 throw std::invalid_argument(
"Possible corruption: lg_cur_size must not be less than " + std::to_string(LG_MIN_MAP_SIZE) +
": " + std::to_string(lg_cur_size));
449template<
typename T,
typename W,
typename H,
typename E,
typename A>
453 std::ostringstream os;
454 os <<
"### Frequent items sketch summary:" << std::endl;
455 os <<
" lg cur map size : " << (int) map.get_lg_cur_size() << std::endl;
456 os <<
" lg max map size : " << (int) map.get_lg_max_size() << std::endl;
460 os <<
"### End sketch summary" << std::endl;
464 items.push_back(
row(&it.first, it.second, offset));
467 std::sort(items.begin(), items.end(), [](
row a,
row b){ return a.get_estimate() > b.get_estimate(); });
468 os <<
"### Items in descending order by estimate" << std::endl;
469 os <<
" item, estimate, lower bound, upper bound" << std::endl;
470 for (
auto it: items) {
471 os <<
" " << it.get_item() <<
", " << it.get_estimate() <<
", "
472 << it.get_lower_bound() <<
", " << it.get_upper_bound() << std::endl;
474 os <<
"### End items" << std::endl;
476 return string<A>(os.str().c_str(), map.get_allocator());
480template<
typename T,
typename W,
typename H,
typename E,
typename A>
481template<typename WW, typename std::enable_if<std::is_integral<WW>::value && std::is_signed<WW>::value,
int>::type>
482void frequent_items_sketch<T, W, H, E, A>::check_weight(WW weight) {
484 throw std::invalid_argument(
"weight must be non-negative");
489template<
typename T,
typename W,
typename H,
typename E,
typename A>
490template<typename WW, typename std::enable_if<std::is_integral<WW>::value && std::is_unsigned<WW>::value,
int>::type>
491void frequent_items_sketch<T, W, H, E, A>::check_weight(WW) {}
494template<
typename T,
typename W,
typename H,
typename E,
typename A>
495template<typename WW, typename std::enable_if<std::is_floating_point<WW>::value,
int>::type>
496void frequent_items_sketch<T, W, H, E, A>::check_weight(WW weight) {
498 throw std::invalid_argument(
"weight must be non-negative");
500 if (std::isnan(weight)) {
501 throw std::invalid_argument(
"weight must be a valid number");
503 if (std::isinf(weight)) {
504 throw std::invalid_argument(
"weight must be finite");
Row in the output from get_frequent_items.
Definition frequent_items_sketch.hpp:355
Frequent Items sketch.
Definition frequent_items_sketch.hpp:60
vector_row get_frequent_items(frequent_items_error_type err_type) const
Returns an array of rows that include frequent items, estimates, upper and lower bounds given an erro...
frequent_items_sketch(uint8_t lg_max_map_size, uint8_t lg_start_map_size=LG_MIN_MAP_SIZE, const E &equal=E(), const A &allocator=A())
Construct this sketch with parameters lg_max_map_size and lg_start_map_size.
Definition frequent_items_sketch_impl.hpp:38
W get_upper_bound(const T &item) const
Returns the guaranteed upper bound weight (frequency) of the given item.
Definition frequent_items_sketch_impl.hpp:128
void merge(const frequent_items_sketch &other)
This function merges the other sketch into this one.
Definition frequent_items_sketch_impl.hpp:69
void serialize(std::ostream &os, const SerDe &sd=SerDe()) const
This method serializes the sketch into a given stream in a binary form.
Definition frequent_items_sketch_impl.hpp:175
bool is_empty() const
A sketch is empty if it has not been updated with any positive weight.
Definition frequent_items_sketch_impl.hpp:98
string< A > to_string(bool print_items=false) const
Returns a human readable summary of this sketch.
Definition frequent_items_sketch_impl.hpp:450
void update(const T &item, W weight=1)
Update this sketch with an item and a positive weight (frequency count).
Definition frequent_items_sketch_impl.hpp:53
static double get_apriori_error(uint8_t lg_max_map_size, W estimated_total_weight)
Returns the estimated a priori error given the max_map_size for the sketch and the estimated_total_st...
Definition frequent_items_sketch_impl.hpp:148
W get_total_weight() const
Returns the sum of the weights (frequencies) in the stream seen so far by the sketch.
Definition frequent_items_sketch_impl.hpp:110
double get_epsilon() const
Returns epsilon value of this sketch.
Definition frequent_items_sketch_impl.hpp:138
size_t get_serialized_size_bytes(const SerDe &sd=SerDe()) const
Computes size needed to serialize the current state of the sketch.
Definition frequent_items_sketch_impl.hpp:222
W get_maximum_error() const
Definition frequent_items_sketch_impl.hpp:133
W get_estimate(const T &item) const
Returns the estimate of the weight (frequency) of the given item.
Definition frequent_items_sketch_impl.hpp:115
static frequent_items_sketch deserialize(std::istream &is, const SerDe &sd=SerDe(), const E &equal=E(), const A &allocator=A())
This method deserializes a sketch from a given stream.
void reset()
Resets this sketch to the empty state, as if newly constructed.
Definition frequent_items_sketch_impl.hpp:91
W get_lower_bound(const T &item) const
Returns the guaranteed lower bound weight (frequency) of the given item.
Definition frequent_items_sketch_impl.hpp:123
uint32_t get_num_active_items() const
Definition frequent_items_sketch_impl.hpp:105
DataSketches namespace.
Definition binomial_bounds.hpp:38
frequent_items_error_type
Frequent items error type.
Definition frequent_items_sketch.hpp:36
@ NO_FALSE_NEGATIVES
include an item in the result list if get_upper_bound(item) > threshold
Definition frequent_items_sketch.hpp:38
@ NO_FALSE_POSITIVES
include an item in the result list if get_lower_bound(item) > threshold
Definition frequent_items_sketch.hpp:37