20 #ifndef _QUANTILES_SKETCH_IMPL_HPP_
21 #define _QUANTILES_SKETCH_IMPL_HPP_
29 #include "count_zeros.hpp"
30 #include "conditional_forward.hpp"
34 template<
typename T,
typename C,
typename A>
35 quantiles_sketch<T, C, A>::quantiles_sketch(uint16_t k,
const C& comparator,
const A& allocator):
36 comparator_(comparator),
37 allocator_(allocator),
38 is_base_buffer_sorted_(true),
42 base_buffer_(allocator_),
49 base_buffer_.reserve(2 * std::min(quantiles_constants::MIN_K, k));
52 template<
typename T,
typename C,
typename A>
54 comparator_(other.comparator_),
55 allocator_(other.allocator_),
56 is_base_buffer_sorted_(other.is_base_buffer_sorted_),
59 bit_pattern_(other.bit_pattern_),
60 base_buffer_(other.base_buffer_),
61 levels_(other.levels_),
62 min_item_(other.min_item_),
63 max_item_(other.max_item_),
66 for (
size_t i = 0; i < levels_.size(); ++i) {
67 if (levels_[i].capacity() != other.levels_[i].capacity()) {
68 levels_[i].reserve(other.levels_[i].capacity());
73 template<
typename T,
typename C,
typename A>
75 comparator_(other.comparator_),
76 allocator_(other.allocator_),
77 is_base_buffer_sorted_(other.is_base_buffer_sorted_),
80 bit_pattern_(other.bit_pattern_),
81 base_buffer_(std::move(other.base_buffer_)),
82 levels_(std::move(other.levels_)),
83 min_item_(std::move(other.min_item_)),
84 max_item_(std::move(other.max_item_)),
88 template<
typename T,
typename C,
typename A>
91 std::swap(comparator_, copy.comparator_);
92 std::swap(allocator_, copy.allocator_);
93 std::swap(is_base_buffer_sorted_, copy.is_base_buffer_sorted_);
94 std::swap(k_, copy.k_);
95 std::swap(n_, copy.n_);
96 std::swap(bit_pattern_, copy.bit_pattern_);
97 std::swap(base_buffer_, copy.base_buffer_);
98 std::swap(levels_, copy.levels_);
99 std::swap(min_item_, copy.min_item_);
100 std::swap(max_item_, copy.max_item_);
105 template<
typename T,
typename C,
typename A>
107 std::swap(comparator_, other.comparator_);
108 std::swap(allocator_, other.allocator_);
109 std::swap(is_base_buffer_sorted_, other.is_base_buffer_sorted_);
110 std::swap(k_, other.k_);
111 std::swap(n_, other.n_);
112 std::swap(bit_pattern_, other.bit_pattern_);
113 std::swap(base_buffer_, other.base_buffer_);
114 std::swap(levels_, other.levels_);
115 std::swap(min_item_, other.min_item_);
116 std::swap(max_item_, other.max_item_);
121 template<
typename T,
typename C,
typename A>
123 Level&& base_buffer, VectorLevels&& levels,
124 optional<T>&& min_item, optional<T>&& max_item,
125 bool is_sorted,
const C& comparator,
const A& allocator):
126 comparator_(comparator),
127 allocator_(allocator),
128 is_base_buffer_sorted_(is_sorted),
131 bit_pattern_(bit_pattern),
132 base_buffer_(std::move(base_buffer)),
133 levels_(std::move(levels)),
134 min_item_(std::move(min_item)),
135 max_item_(std::move(max_item)),
136 sorted_view_(nullptr)
138 uint32_t item_count =
static_cast<uint32_t
>(base_buffer_.size());
139 for (Level& lvl : levels_) {
140 item_count +=
static_cast<uint32_t
>(lvl.size());
142 if (item_count != compute_retained_items(k_, n_))
143 throw std::logic_error(
"Item count does not match value computed from k, n");
146 template<
typename T,
typename C,
typename A>
147 template<
typename From,
typename FC,
typename FA>
148 quantiles_sketch<T, C, A>::quantiles_sketch(
const quantiles_sketch<From, FC, FA>& other,
149 const C& comparator,
const A& allocator):
150 comparator_(comparator),
151 allocator_(allocator),
152 is_base_buffer_sorted_(false),
155 bit_pattern_(compute_bit_pattern(other.get_k(), other.get_n())),
156 base_buffer_(allocator),
158 min_item_(other.min_item_),
159 max_item_(other.max_item_),
160 sorted_view_(nullptr)
162 static_assert(std::is_constructible<T, From>::value,
163 "Type converting constructor requires new type to be constructible from existing type");
167 if (!other.is_empty()) {
169 const uint8_t num_levels = compute_levels_needed(k_, n_);
170 levels_.reserve(num_levels);
171 for (
int i = 0; i < num_levels; ++i) {
172 Level level(allocator);
174 levels_.push_back(std::move(level));
178 for (
auto pair : other) {
179 const uint64_t wt = pair.second;
181 base_buffer_.push_back(T(pair.first));
183 if (base_buffer_.size() + 1 > base_buffer_.capacity()) {
184 const size_t new_size = std::max(std::min(
static_cast<size_t>(2 * k_), 2 * base_buffer_.size()),
static_cast<size_t>(1));
185 base_buffer_.reserve(new_size);
189 const uint8_t idx = count_trailing_zeros_in_u64(pair.second) - 1;
190 levels_[idx].push_back(T(pair.first));
196 for (
int i = 0; i < num_levels; ++i) {
197 if (!std::is_sorted(levels_[i].
begin(), levels_[i].
end(), comparator_)) {
198 throw std::logic_error(
"Copy construction across types produces invalid sorting");
205 template<
typename T,
typename C,
typename A>
206 quantiles_sketch<T, C, A>::~quantiles_sketch() {
210 template<
typename T,
typename C,
typename A>
211 template<
typename FwdT>
213 if (!check_update_item(item)) {
return; }
215 min_item_.emplace(item);
216 max_item_.emplace(item);
218 if (comparator_(item, *min_item_)) *min_item_ = item;
219 if (comparator_(*max_item_, item)) *max_item_ = item;
223 if (base_buffer_.size() + 1 > base_buffer_.capacity()) grow_base_buffer();
225 base_buffer_.push_back(std::forward<FwdT>(item));
228 if (base_buffer_.size() > 1) is_base_buffer_sorted_ =
false;
229 if (base_buffer_.size() == 2 * k_) process_full_base_buffer();
233 template<
typename T,
typename C,
typename A>
234 template<
typename FwdSk>
236 if (other.is_empty()) {
238 }
else if (!other.is_estimation_mode()) {
240 for (
auto item : other.base_buffer_) {
241 update(conditional_forward<FwdSk>(item));
248 if (is_estimation_mode()) {
249 if (k_ == other.get_k()) {
250 standard_merge(*
this, std::forward<FwdSk>(other));
251 }
else if (k_ > other.get_k()) {
253 downsampling_merge(sk_copy, std::move(*
this));
254 *
this = std::move(sk_copy);
256 downsampling_merge(*
this, std::forward<FwdSk>(other));
261 if (k_ <= other.get_k()) {
263 for (uint16_t i = 0; i < base_buffer_.size(); ++i) {
264 sk_copy.
update(std::move(base_buffer_[i]));
268 downsampling_merge(sk_copy, std::move(*
this));
270 *
this = std::move(sk_copy);
275 template<
typename T,
typename C,
typename A>
276 template<
typename SerDe>
278 const uint8_t preamble_longs = is_empty() ? PREAMBLE_LONGS_SHORT : PREAMBLE_LONGS_FULL;
279 write(os, preamble_longs);
280 const uint8_t ser_ver = SERIAL_VERSION;
282 const uint8_t family = FAMILY;
286 std::sort(
const_cast<Level&
>(base_buffer_).begin(),
const_cast<Level&
>(base_buffer_).end(), comparator_);
290 const uint8_t flags_byte(
291 (is_empty() ? 1 << flags::IS_EMPTY : 0)
292 | (1 << flags::IS_SORTED)
293 | (1 << flags::IS_COMPACT)
295 write(os, flags_byte);
297 const uint16_t unused = 0;
308 serde.
serialize(os, base_buffer_.data(),
static_cast<unsigned>(base_buffer_.size()));
311 for (Level lvl : levels_) {
313 serde.
serialize(os, lvl.data(),
static_cast<unsigned>(lvl.size()));
318 template<
typename T,
typename C,
typename A>
319 template<
typename SerDe>
321 const size_t size = get_serialized_size_bytes(
serde) + header_size_bytes;
322 vector_bytes bytes(size, 0, allocator_);
323 uint8_t* ptr = bytes.data() + header_size_bytes;
324 const uint8_t* end_ptr = ptr + size;
326 const uint8_t preamble_longs = is_empty() ? PREAMBLE_LONGS_SHORT : PREAMBLE_LONGS_FULL;
327 ptr += copy_to_mem(preamble_longs, ptr);
328 const uint8_t ser_ver = SERIAL_VERSION;
329 ptr += copy_to_mem(ser_ver, ptr);
330 const uint8_t family = FAMILY;
331 ptr += copy_to_mem(family, ptr);
334 std::sort(
const_cast<Level&
>(base_buffer_).begin(),
const_cast<Level&
>(base_buffer_).end(), comparator_);
338 const uint8_t flags_byte(
339 (is_empty() ? 1 << flags::IS_EMPTY : 0)
340 | (1 << flags::IS_SORTED)
341 | (1 << flags::IS_COMPACT)
343 ptr += copy_to_mem(flags_byte, ptr);
344 ptr += copy_to_mem(k_, ptr);
345 ptr +=
sizeof(uint16_t);
349 ptr += copy_to_mem(n_, ptr);
356 if (base_buffer_.size() > 0)
357 ptr +=
serde.
serialize(ptr, end_ptr - ptr, base_buffer_.data(),
static_cast<unsigned>(base_buffer_.size()));
360 for (Level lvl : levels_) {
362 ptr +=
serde.
serialize(ptr, end_ptr - ptr, lvl.data(),
static_cast<unsigned>(lvl.size()));
369 template<
typename T,
typename C,
typename A>
370 template<
typename SerDe>
372 const C& comparator,
const A &allocator) -> quantiles_sketch {
373 const auto preamble_longs = read<uint8_t>(is);
374 const auto serial_version = read<uint8_t>(is);
375 const auto family_id = read<uint8_t>(is);
376 const auto flags_byte = read<uint8_t>(is);
377 const auto k = read<uint16_t>(is);
381 check_serial_version(serial_version);
382 check_family_id(family_id);
383 check_header_validity(preamble_longs, flags_byte, serial_version);
385 if (!is.good())
throw std::runtime_error(
"error reading from std::istream");
386 const bool is_empty = (flags_byte & (1 << flags::IS_EMPTY)) > 0;
388 return quantiles_sketch(k, comparator, allocator);
391 const auto items_seen = read<uint64_t>(is);
393 const bool is_compact = (serial_version == 2) | ((flags_byte & (1 << flags::IS_COMPACT)) > 0);
394 const bool is_sorted = (flags_byte & (1 << flags::IS_SORTED)) > 0;
397 optional<T> min_item;
398 optional<T> max_item;
400 serde.deserialize(is, &*tmp, 1);
402 min_item.emplace(*tmp);
404 serde.deserialize(is, &*tmp, 1);
406 max_item.emplace(*tmp);
409 if (serial_version == 1) {
414 const uint8_t levels_needed = compute_levels_needed(k, items_seen);
415 const uint64_t bit_pattern = compute_bit_pattern(k, items_seen);
423 const uint32_t bb_items = compute_base_buffer_items(k, items_seen);
424 uint32_t items_to_read = (levels_needed == 0 || is_compact) ? bb_items : 2 * k;
425 Level base_buffer = deserialize_array(is, bb_items, 2 * k, serde, allocator);
426 if (items_to_read > bb_items) {
428 deserialize_array(is, items_to_read - bb_items, items_to_read - bb_items, serde, allocator);
432 VectorLevels levels(allocator);
433 levels.reserve(levels_needed);
434 if (levels_needed > 0) {
435 uint64_t working_pattern = bit_pattern;
436 for (
size_t i = 0; i < levels_needed; ++i, working_pattern >>= 1) {
437 if ((working_pattern & 0x01) == 1) {
438 Level level = deserialize_array(is, k, k, serde, allocator);
439 levels.push_back(std::move(level));
441 Level level(allocator);
443 levels.push_back(std::move(level));
448 return quantiles_sketch(k, items_seen, bit_pattern,
449 std::move(base_buffer), std::move(levels), std::move(min_item), std::move(max_item), is_sorted,
450 comparator, allocator);
453 template<
typename T,
typename C,
typename A>
454 template<
typename SerDe>
455 auto quantiles_sketch<T, C, A>::deserialize_array(std::istream& is, uint32_t num_items, uint32_t capacity,
const SerDe& serde,
const A& allocator) -> Level {
457 std::unique_ptr<T, items_deleter> items(alloc.allocate(num_items), items_deleter(allocator,
false, num_items));
458 serde.deserialize(is, items.get(), num_items);
460 items.get_deleter().set_destroy(
true);
461 if (!is.good())
throw std::runtime_error(
"error reading from std::istream");
464 Level level(allocator);
465 level.reserve(capacity);
466 level.insert(level.begin(),
467 std::make_move_iterator(items.get()),
468 std::make_move_iterator(items.get() + num_items));
472 template<
typename T,
typename C,
typename A>
473 template<
typename SerDe>
475 const C& comparator,
const A &allocator) -> quantiles_sketch {
476 ensure_minimum_memory(size, 8);
477 const char* ptr =
static_cast<const char*
>(bytes);
478 const char* end_ptr =
static_cast<const char*
>(bytes) + size;
480 uint8_t preamble_longs;
481 ptr += copy_from_mem(ptr, preamble_longs);
482 uint8_t serial_version;
483 ptr += copy_from_mem(ptr, serial_version);
485 ptr += copy_from_mem(ptr, family_id);
487 ptr += copy_from_mem(ptr, flags_byte);
489 ptr += copy_from_mem(ptr, k);
491 ptr += copy_from_mem(ptr, unused);
494 check_serial_version(serial_version);
495 check_family_id(family_id);
496 check_header_validity(preamble_longs, flags_byte, serial_version);
498 const bool is_empty = (flags_byte & (1 << flags::IS_EMPTY)) > 0;
500 return quantiles_sketch(k, comparator, allocator);
503 ensure_minimum_memory(size, 16);
505 ptr += copy_from_mem(ptr, items_seen);
507 const bool is_compact = (serial_version == 2) | ((flags_byte & (1 << flags::IS_COMPACT)) > 0);
508 const bool is_sorted = (flags_byte & (1 << flags::IS_SORTED)) > 0;
511 optional<T> min_item;
512 optional<T> max_item;
514 ptr += serde.deserialize(ptr, end_ptr - ptr, &*tmp, 1);
516 min_item.emplace(*tmp);
518 ptr += serde.deserialize(ptr, end_ptr - ptr, &*tmp, 1);
520 max_item.emplace(*tmp);
523 if (serial_version == 1) {
524 uint64_t unused_long;
525 ptr += copy_from_mem(ptr, unused_long);
529 const uint8_t levels_needed = compute_levels_needed(k, items_seen);
530 const uint64_t bit_pattern = compute_bit_pattern(k, items_seen);
538 const uint32_t bb_items = compute_base_buffer_items(k, items_seen);
539 uint32_t items_to_read = (levels_needed == 0 || is_compact) ? bb_items : 2 * k;
540 auto base_buffer_pair = deserialize_array(ptr, end_ptr - ptr, bb_items, 2 * k, serde, allocator);
541 ptr += base_buffer_pair.second;
542 if (items_to_read > bb_items) {
544 auto extras = deserialize_array(ptr, end_ptr - ptr, items_to_read - bb_items, items_to_read - bb_items, serde, allocator);
545 ptr += extras.second;
549 VectorLevels levels(allocator);
550 levels.reserve(levels_needed);
551 if (levels_needed > 0) {
552 uint64_t working_pattern = bit_pattern;
553 for (
size_t i = 0; i < levels_needed; ++i, working_pattern >>= 1) {
555 if ((working_pattern & 0x01) == 1) {
556 auto pair = deserialize_array(ptr, end_ptr - ptr, k, k, serde, allocator);
558 levels.push_back(std::move(pair.first));
560 Level level(allocator);
562 levels.push_back(std::move(level));
567 return quantiles_sketch(k, items_seen, bit_pattern,
568 std::move(base_buffer_pair.first), std::move(levels), std::move(min_item), std::move(max_item), is_sorted,
569 comparator, allocator);
572 template<
typename T,
typename C,
typename A>
573 template<
typename SerDe>
574 auto quantiles_sketch<T, C, A>::deserialize_array(
const void* bytes,
size_t size, uint32_t num_items, uint32_t capacity,
const SerDe& serde,
const A& allocator)
575 -> std::pair<Level, size_t> {
576 const char* ptr =
static_cast<const char*
>(bytes);
577 const char* end_ptr =
static_cast<const char*
>(bytes) + size;
579 std::unique_ptr<T, items_deleter> items(alloc.allocate(num_items), items_deleter(allocator,
false, num_items));
580 ptr += serde.deserialize(ptr, end_ptr - ptr, items.get(), num_items);
582 items.get_deleter().set_destroy(
true);
585 Level level(allocator);
586 level.reserve(capacity);
587 level.insert(level.begin(),
588 std::make_move_iterator(items.get()),
589 std::make_move_iterator(items.get() + num_items));
591 return std::pair<Level, size_t>(std::move(level), ptr -
static_cast<const char*
>(bytes));
594 template<
typename T,
typename C,
typename A>
598 std::ostringstream os;
599 os <<
"### Quantiles Sketch summary:" << std::endl;
600 os <<
" K : " << k_ << std::endl;
601 os <<
" N : " << n_ << std::endl;
602 os <<
" Epsilon : " << std::setprecision(3) << get_normalized_rank_error(
false) * 100 <<
"%" << std::endl;
603 os <<
" Epsilon PMF : " << get_normalized_rank_error(
true) * 100 <<
"%" << std::endl;
604 os <<
" Empty : " << (is_empty() ?
"true" :
"false") << std::endl;
605 os <<
" Estimation mode: " << (is_estimation_mode() ?
"true" :
"false") << std::endl;
606 os <<
" Levels (w/o BB): " << levels_.size() << std::endl;
607 os <<
" Used Levels : " << count_valid_levels(bit_pattern_) << std::endl;
608 os <<
" Retained items : " << get_num_retained() << std::endl;
610 os <<
" Min item : " << *min_item_ << std::endl;
611 os <<
" Max item : " << *max_item_ << std::endl;
613 os <<
"### End sketch summary" << std::endl;
616 os <<
"### Quantiles Sketch levels:" << std::endl;
617 os <<
" index: items in use" << std::endl;
618 os <<
" BB: " << base_buffer_.size() << std::endl;
619 for (uint8_t i = 0; i < levels_.size(); i++) {
620 os <<
" " <<
static_cast<unsigned int>(i) <<
": " << levels_[i].size() << std::endl;
622 os <<
"### End sketch levels" << std::endl;
626 os <<
"### Quantiles Sketch data:" << std::endl;
628 os <<
" BB:" << std::endl;
629 for (
const T& item : base_buffer_) {
630 os <<
" " << item << std::endl;
632 for (uint8_t i = 0; i < levels_.size(); ++i) {
633 os <<
" level " <<
static_cast<unsigned int>(level) <<
":" << std::endl;
634 for (
const T& item : levels_[i]) {
635 os <<
" " << item << std::endl;
638 os <<
"### End sketch data" << std::endl;
640 return string<A>(os.str().c_str(), allocator_);
643 template<
typename T,
typename C,
typename A>
648 template<
typename T,
typename C,
typename A>
653 template<
typename T,
typename C,
typename A>
658 template<
typename T,
typename C,
typename A>
660 return bit_pattern_ != 0;
663 template<
typename T,
typename C,
typename A>
665 return compute_retained_items(k_, n_);
668 template<
typename T,
typename C,
typename A>
670 if (is_empty())
throw std::runtime_error(
"operation is undefined for an empty sketch");
674 template<
typename T,
typename C,
typename A>
676 if (is_empty())
throw std::runtime_error(
"operation is undefined for an empty sketch");
680 template<
typename T,
typename C,
typename A>
685 template<
typename T,
typename C,
typename A>
691 template<
typename T,
typename C,
typename A>
692 template<typename SerDe, typename TT, typename std::enable_if<std::is_arithmetic<TT>::value,
int>::type>
694 if (is_empty()) {
return EMPTY_SIZE_BYTES; }
695 return DATA_START + ((get_num_retained() + 2) *
sizeof(TT));
699 template<
typename T,
typename C,
typename A>
700 template<typename SerDe, typename TT, typename std::enable_if<!std::is_arithmetic<TT>::value,
int>::type>
702 if (is_empty()) {
return EMPTY_SIZE_BYTES; }
703 size_t size = DATA_START;
704 size += serde.size_of_item(*min_item_);
705 size += serde.size_of_item(*max_item_);
706 for (
auto it: *
this) size += serde.size_of_item(it.first);
710 template<
typename T,
typename C,
typename A>
712 return get_normalized_rank_error(k_, is_pmf);
715 template<
typename T,
typename C,
typename A>
718 ? 1.854 / std::pow(k, 0.9657)
719 : 1.576 / std::pow(k, 0.9726);
722 template<
typename T,
typename C,
typename A>
725 if (!is_base_buffer_sorted_) {
726 std::sort(
const_cast<Level&
>(base_buffer_).begin(),
const_cast<Level&
>(base_buffer_).end(), comparator_);
732 view.add(base_buffer_.begin(), base_buffer_.end(), weight);
733 for (
const auto& level: levels_) {
735 if (level.empty()) {
continue; }
736 view.add(level.begin(), level.end(), weight);
739 view.convert_to_cummulative();
743 template<
typename T,
typename C,
typename A>
745 if (is_empty())
throw std::runtime_error(
"operation is undefined for an empty sketch");
746 if ((rank < 0.0) || (rank > 1.0)) {
747 throw std::invalid_argument(
"Normalized rank cannot be less than 0 or greater than 1");
751 return sorted_view_->get_quantile(rank, inclusive);
754 template<
typename T,
typename C,
typename A>
756 if (is_empty())
throw std::runtime_error(
"operation is undefined for an empty sketch");
758 return sorted_view_->get_rank(item, inclusive);
761 template<
typename T,
typename C,
typename A>
763 if (is_empty())
throw std::runtime_error(
"operation is undefined for an empty sketch");
765 return sorted_view_->get_PMF(split_points, size, inclusive);
768 template<
typename T,
typename C,
typename A>
770 if (is_empty())
throw std::runtime_error(
"operation is undefined for an empty sketch");
772 return sorted_view_->get_CDF(split_points, size, inclusive);
775 template<
typename T,
typename C,
typename A>
777 const uint32_t bb_count = compute_base_buffer_items(k, n);
778 const uint64_t bit_pattern = compute_bit_pattern(k, n);
779 const uint32_t valid_levels = count_valid_levels(bit_pattern);
780 return bb_count + (k * valid_levels);
783 template<
typename T,
typename C,
typename A>
784 uint32_t quantiles_sketch<T, C, A>::compute_base_buffer_items(uint16_t k, uint64_t n) {
785 return n % (
static_cast<uint64_t
>(2) * k);
788 template<
typename T,
typename C,
typename A>
789 uint64_t quantiles_sketch<T, C, A>::compute_bit_pattern(uint16_t k, uint64_t n) {
790 return n / (
static_cast<uint64_t
>(2) * k);
793 template<
typename T,
typename C,
typename A>
794 uint32_t quantiles_sketch<T, C, A>::count_valid_levels(uint64_t bit_pattern) {
796 for (; bit_pattern > 0; ++count) bit_pattern &= bit_pattern - 1;
800 template<
typename T,
typename C,
typename A>
801 uint8_t quantiles_sketch<T, C, A>::compute_levels_needed(uint16_t k, uint64_t n) {
802 return static_cast<uint8_t
>(64U) - count_leading_zeros_in_u64(n / (2 * k));
805 template<
typename T,
typename C,
typename A>
806 void quantiles_sketch<T, C, A>::check_k(uint16_t k) {
808 throw std::invalid_argument(
"k must be a power of 2 that is >= "
814 template<
typename T,
typename C,
typename A>
815 void quantiles_sketch<T, C, A>::check_serial_version(uint8_t serial_version) {
816 if (serial_version == SERIAL_VERSION || serial_version == SERIAL_VERSION_1 || serial_version == SERIAL_VERSION_2)
819 throw std::invalid_argument(
"Possible corruption. Unrecognized serialization version: " + std::to_string(serial_version));
822 template<
typename T,
typename C,
typename A>
823 void quantiles_sketch<T, C, A>::check_family_id(uint8_t family_id) {
824 if (family_id == FAMILY)
827 throw std::invalid_argument(
"Possible corruption. Family id does not indicate quantiles sketch: " + std::to_string(family_id));
830 template<
typename T,
typename C,
typename A>
831 void quantiles_sketch<T, C, A>::check_header_validity(uint8_t preamble_longs, uint8_t flags_byte, uint8_t serial_version) {
832 const bool empty = (flags_byte & (1 << flags::IS_EMPTY)) > 0;
833 const bool compact = (flags_byte & (1 << flags::IS_COMPACT)) > 0;
835 const uint8_t sw = (compact ? 1 : 0) + (2 * (empty ? 1 : 0))
836 + (4 * (serial_version & 0xF)) + (32 * (preamble_longs & 0x3F));
855 std::ostringstream os;
856 os <<
"Possible sketch corruption. Inconsistent state: "
857 <<
"preamble_longs = " << preamble_longs
858 <<
", empty = " << (empty ?
"true" :
"false")
859 <<
", serialization_version = " << serial_version
860 <<
", compact = " << (compact ?
"true" :
"false");
861 throw std::invalid_argument(os.str());
865 template <
typename T,
typename C,
typename A>
870 template <
typename T,
typename C,
typename A>
875 template<
typename T,
typename C,
typename A>
877 const size_t new_size = std::max(std::min(
static_cast<size_t>(2 * k_), 2 * base_buffer_.size()),
static_cast<size_t>(1));
878 base_buffer_.reserve(new_size);
881 template<
typename T,
typename C,
typename A>
882 void quantiles_sketch<T, C, A>::process_full_base_buffer() {
884 grow_levels_if_needed();
886 std::sort(base_buffer_.begin(), base_buffer_.end(), comparator_);
887 in_place_propagate_carry(0,
891 base_buffer_.clear();
892 is_base_buffer_sorted_ =
true;
893 if (n_ / (2 * k_) != bit_pattern_) {
894 throw std::logic_error(
"Internal error: n / 2k (" + std::to_string(n_ / 2 * k_)
895 +
" != bit_pattern " + std::to_string(bit_pattern_));
899 template<
typename T,
typename C,
typename A>
900 bool quantiles_sketch<T, C, A>::grow_levels_if_needed() {
901 const uint8_t levels_needed = compute_levels_needed(k_, n_);
902 if (levels_needed == 0)
906 if (levels_needed <= levels_.size())
909 Level empty_level(allocator_);
910 empty_level.reserve(k_);
911 levels_.push_back(std::move(empty_level));
915 template<
typename T,
typename C,
typename A>
916 template<
typename FwdV>
917 void quantiles_sketch<T, C, A>::in_place_propagate_carry(uint8_t starting_level,
918 FwdV&& buf_size_k, Level& buf_size_2k,
919 bool apply_as_update,
920 quantiles_sketch& sketch) {
921 const uint64_t bit_pattern = sketch.bit_pattern_;
922 const int k = sketch.k_;
924 uint8_t ending_level = lowest_zero_bit_starting_at(bit_pattern, starting_level);
926 if (apply_as_update) {
929 zip_buffer(buf_size_2k, sketch.levels_[ending_level]);
932 for (uint16_t i = 0; i < k; ++i) {
933 sketch.levels_[ending_level].push_back(conditional_forward<FwdV>(buf_size_k[i]));
937 for (uint64_t lvl = starting_level; lvl < ending_level; lvl++) {
938 if ((bit_pattern & (
static_cast<uint64_t
>(1) << lvl)) == 0) {
939 throw std::logic_error(
"unexpected empty level in bit_pattern");
941 merge_two_size_k_buffers(
943 sketch.levels_[ending_level],
944 buf_size_2k, sketch.get_comparator());
945 sketch.levels_[lvl].clear();
946 sketch.levels_[ending_level].clear();
947 zip_buffer(buf_size_2k, sketch.levels_[ending_level]);
951 sketch.bit_pattern_ = bit_pattern + (
static_cast<uint64_t
>(1) << starting_level);
954 template<
typename T,
typename C,
typename A>
955 void quantiles_sketch<T, C, A>::zip_buffer(Level& buf_in, Level& buf_out) {
956 #ifdef QUANTILES_VALIDATION
957 static uint32_t next_offset = 0;
958 uint32_t rand_offset = next_offset;
959 next_offset = 1 - next_offset;
961 uint32_t rand_offset = random_utils::random_bit();
963 if ((buf_in.size() != 2 * buf_out.capacity())
964 || (buf_out.size() > 0)) {
965 throw std::logic_error(
"zip_buffer requires buf_in.size() == "
966 "2*buf_out.capacity() and empty buf_out");
969 size_t k = buf_out.capacity();
970 for (uint32_t i = rand_offset, o = 0; o < k; i += 2, ++o) {
971 buf_out.push_back(std::move(buf_in[i]));
976 template<
typename T,
typename C,
typename A>
977 template<
typename FwdV>
978 void quantiles_sketch<T, C, A>::zip_buffer_with_stride(FwdV&& buf_in, Level& buf_out, uint16_t stride) {
980 std::uniform_int_distribution<uint16_t> dist(0, stride - 1);
981 const uint16_t rand_offset = dist(random_utils::rand);
983 if ((buf_in.size() != stride * buf_out.capacity())
984 || (buf_out.size() > 0)) {
985 throw std::logic_error(
"zip_buffer_with_stride requires buf_in.size() == "
986 "stride*buf_out.capacity() and empty buf_out");
989 const size_t k = buf_out.capacity();
990 for (uint16_t i = rand_offset, o = 0; o < k; i += stride, ++o) {
991 buf_out.push_back(conditional_forward<FwdV>(buf_in[i]));
996 template<
typename T,
typename C,
typename A>
997 void quantiles_sketch<T, C, A>::merge_two_size_k_buffers(Level& src_1, Level& src_2,
998 Level& dst,
const C& comparator) {
999 if (src_1.size() != src_2.size()
1000 || src_1.size() * 2 != dst.capacity()
1001 || dst.size() != 0) {
1002 throw std::logic_error(
"Input invariants violated in merge_two_size_k_buffers()");
1005 auto end1 = src_1.end(), end2 = src_2.end();
1006 auto it1 = src_1.begin(), it2 = src_2.begin();
1009 while (it1 != end1 && it2 != end2) {
1010 if (comparator(*it1, *it2)) {
1011 dst.push_back(std::move(*it1++));
1013 dst.push_back(std::move(*it2++));
1018 dst.insert(dst.end(), it1, end1);
1020 if (it2 == end2) {
throw std::logic_error(
"it2 unexpectedly already at end of range"); }
1021 dst.insert(dst.end(), it2, end2);
1025 template<
typename T,
typename C,
typename A>
1026 template<
typename FwdSk>
1027 void quantiles_sketch<T, C, A>::standard_merge(quantiles_sketch& tgt, FwdSk&& src) {
1028 if (src.get_k() != tgt.get_k()) {
1029 throw std::invalid_argument(
"src.get_k() != tgt.get_k()");
1031 if (src.is_empty()) {
1035 uint64_t new_n = src.get_n() + tgt.get_n();
1038 for (uint16_t i = 0; i < src.base_buffer_.size(); ++i) {
1039 tgt.update(conditional_forward<FwdSk>(src.base_buffer_[i]));
1043 uint8_t levels_needed = compute_levels_needed(tgt.get_k(), new_n);
1044 if (levels_needed > tgt.levels_.size()) {
1045 tgt.levels_.reserve(levels_needed);
1046 while (tgt.levels_.size() < levels_needed) {
1047 Level empty_level(tgt.allocator_);
1048 empty_level.reserve(tgt.get_k());
1049 tgt.levels_.push_back(std::move(empty_level));
1053 Level scratch_buf(tgt.allocator_);
1054 scratch_buf.reserve(2 * tgt.get_k());
1056 uint64_t src_pattern = src.bit_pattern_;
1057 for (uint8_t src_lvl = 0; src_pattern != 0; ++src_lvl, src_pattern >>= 1) {
1058 if ((src_pattern & 1) > 0) {
1059 scratch_buf.clear();
1062 in_place_propagate_carry(src_lvl,
1063 src.levels_[src_lvl], scratch_buf,
1069 if ((tgt.get_n() / (2 * tgt.get_k())) != tgt.bit_pattern_) {
1070 throw std::logic_error(
"Failed internal consistency check after standard_merge()");
1076 if (!tgt.min_item_) {
1077 tgt.min_item_.emplace(conditional_forward<FwdSk>(*src.min_item_));
1079 if (tgt.comparator_(*src.min_item_, *tgt.min_item_))
1080 *tgt.min_item_ = conditional_forward<FwdSk>(*src.min_item_);
1082 if (!tgt.max_item_) {
1083 tgt.max_item_.emplace(conditional_forward<FwdSk>(*src.max_item_));
1085 if (tgt.comparator_(*tgt.max_item_, *src.max_item_))
1086 *tgt.max_item_ = conditional_forward<FwdSk>(*src.max_item_);
1090 template<
typename T,
typename C,
typename A>
1091 template<
typename FwdSk>
1092 void quantiles_sketch<T, C, A>::downsampling_merge(quantiles_sketch& tgt, FwdSk&& src) {
1093 if (src.get_k() % tgt.get_k() != 0) {
1094 throw std::invalid_argument(
"src.get_k() is not a multiple of tgt.get_k()");
1096 if (src.is_empty()) {
1100 const uint16_t downsample_factor = src.get_k() / tgt.get_k();
1101 const uint8_t lg_sample_factor = count_trailing_zeros_in_u32(downsample_factor);
1103 const uint64_t new_n = src.get_n() + tgt.get_n();
1106 for (uint16_t i = 0; i < src.base_buffer_.size(); ++i) {
1107 tgt.update(conditional_forward<FwdSk>(src.base_buffer_[i]));
1111 const uint8_t levels_needed = compute_levels_needed(tgt.get_k(), new_n);
1112 if (levels_needed > tgt.levels_.size()) {
1113 tgt.levels_.reserve(levels_needed);
1114 while (tgt.levels_.size() < levels_needed) {
1115 Level empty_level(tgt.allocator_);
1116 empty_level.reserve(tgt.get_k());
1117 tgt.levels_.push_back(std::move(empty_level));
1121 Level down_buf(tgt.allocator_);
1122 down_buf.reserve(tgt.get_k());
1124 Level scratch_buf(tgt.allocator_);
1125 scratch_buf.reserve(2 * tgt.get_k());
1127 uint64_t src_pattern = src.bit_pattern_;
1128 for (uint8_t src_lvl = 0; src_pattern != 0; ++src_lvl, src_pattern >>= 1) {
1129 if ((src_pattern & 1) > 0) {
1131 scratch_buf.clear();
1134 zip_buffer_with_stride(src.levels_[src_lvl], down_buf, downsample_factor);
1137 in_place_propagate_carry(src_lvl + lg_sample_factor,
1138 down_buf, scratch_buf,
1144 if ((tgt.get_n() / (2 * tgt.get_k())) != tgt.bit_pattern_) {
1145 throw std::logic_error(
"Failed internal consistency check after downsampling_merge()");
1151 if (!tgt.min_item_) {
1152 tgt.min_item_.emplace(conditional_forward<FwdSk>(*src.min_item_));
1154 if (tgt.comparator_(*src.min_item_, *tgt.min_item_))
1155 *tgt.min_item_ = conditional_forward<FwdSk>(*src.min_item_);
1157 if (!tgt.max_item_) {
1158 tgt.max_item_.emplace(conditional_forward<FwdSk>(*src.max_item_));
1160 if (tgt.comparator_(*tgt.max_item_, *src.max_item_))
1161 *tgt.max_item_ = conditional_forward<FwdSk>(*src.max_item_);
1165 template<
typename T,
typename C,
typename A>
1166 uint8_t quantiles_sketch<T, C, A>::lowest_zero_bit_starting_at(uint64_t bits, uint8_t starting_bit) {
1167 uint8_t pos = starting_bit & 0X3F;
1168 uint64_t my_bits = bits >> pos;
1170 while ((my_bits &
static_cast<uint64_t
>(1)) != 0) {
1177 template<
typename T,
typename C,
typename A>
1178 class quantiles_sketch<T, C, A>::items_deleter {
1180 items_deleter(
const A& allocator,
bool destroy,
size_t num): allocator_(allocator), destroy_(destroy), num_(num) {}
1181 void operator() (T* ptr) {
1182 if (ptr !=
nullptr) {
1184 for (
size_t i = 0; i < num_; ++i) {
1188 allocator_.deallocate(ptr, num_);
1191 void set_destroy(
bool destroy) { destroy_ = destroy; }
1198 template<
typename T,
typename C,
typename A>
1199 void quantiles_sketch<T, C, A>::setup_sorted_view()
const {
1200 if (sorted_view_ ==
nullptr) {
1201 using AllocSortedView =
typename std::allocator_traits<A>::template rebind_alloc<quantiles_sorted_view<T, C, A>>;
1202 sorted_view_ =
new (AllocSortedView(allocator_).allocate(1)) quantiles_sorted_view<T, C, A>(get_sorted_view());
1206 template<
typename T,
typename C,
typename A>
1207 void quantiles_sketch<T, C, A>::reset_sorted_view() {
1208 if (sorted_view_ !=
nullptr) {
1209 sorted_view_->~quantiles_sorted_view();
1210 using AllocSortedView =
typename std::allocator_traits<A>::template rebind_alloc<quantiles_sorted_view<T, C, A>>;
1211 AllocSortedView(allocator_).deallocate(sorted_view_, 1);
1212 sorted_view_ =
nullptr;
1218 template<
typename T,
typename C,
typename A>
1219 quantiles_sketch<T, C, A>::const_iterator::const_iterator(
const Level& base_buffer,
1220 const std::vector<Level, AllocLevel>& levels,
1224 base_buffer_(base_buffer),
1228 bb_count_(compute_base_buffer_items(k, n)),
1229 bit_pattern_(compute_bit_pattern(k, n)),
1236 if (bit_pattern_ == 0)
1237 index_ =
static_cast<uint32_t
>(n);
1239 level_ =
static_cast<int>(levels_.size());
1241 if (bb_count_ == 0 && bit_pattern_ > 0) {
1244 while ((bit_pattern_ & 0x01) == 0) {
1253 template<
typename T,
typename C,
typename A>
1254 typename quantiles_sketch<T, C, A>::const_iterator& quantiles_sketch<T, C, A>::const_iterator::operator++() {
1257 if ((level_ == -1 && index_ == base_buffer_.size() && levels_.size() > 0) || (level_ >= 0 && index_ == k_)) {
1261 if (level_ > 0) bit_pattern_ = bit_pattern_ >> 1;
1262 if (bit_pattern_ == 0)
return *
this;
1264 }
while ((bit_pattern_ &
static_cast<uint64_t
>(1)) == 0);
1269 template<
typename T,
typename C,
typename A>
1270 typename quantiles_sketch<T, C, A>::const_iterator& quantiles_sketch<T, C, A>::const_iterator::operator++(
int) {
1271 const_iterator tmp(*
this);
1276 template<
typename T,
typename C,
typename A>
1277 bool quantiles_sketch<T, C, A>::const_iterator::operator==(
const const_iterator& other)
const {
1278 return level_ == other.level_ && index_ == other.index_;
1281 template<
typename T,
typename C,
typename A>
1282 bool quantiles_sketch<T, C, A>::const_iterator::operator!=(
const const_iterator& other)
const {
1283 return !operator==(other);
1286 template<
typename T,
typename C,
typename A>
1287 auto quantiles_sketch<T, C, A>::const_iterator::operator*() const -> reference {
1288 return value_type(level_ == -1 ? base_buffer_[index_] : levels_[level_][index_], weight_);
1291 template<
typename T,
typename C,
typename A>
1292 auto quantiles_sketch<T, C, A>::const_iterator::operator->() const -> pointer {
This is a stochastic streaming sketch that enables near-real time analysis of the approximate distrib...
Definition: quantiles_sketch.hpp:153
Comparator get_comparator() const
Returns an instance of the comparator for this sketch.
Definition: quantiles_sketch_impl.hpp:681
quantiles_sorted_view< T, Comparator, Allocator > get_sorted_view() const
Gets the sorted view of this sketch.
Definition: quantiles_sketch_impl.hpp:723
quantiles_sketch & operator=(const quantiles_sketch &other)
Copy assignment.
Definition: quantiles_sketch_impl.hpp:89
vector_double get_CDF(const T *split_points, uint32_t size, bool inclusive=true) const
Returns an approximation to the Cumulative Distribution Function (CDF), which is the cumulative analo...
Definition: quantiles_sketch_impl.hpp:769
uint32_t get_num_retained() const
Returns the number of retained items (samples) in the sketch.
Definition: quantiles_sketch_impl.hpp:664
double get_normalized_rank_error(bool is_pmf) const
Gets the normalized rank error for this sketch.
Definition: quantiles_sketch_impl.hpp:711
vector_double get_PMF(const T *split_points, uint32_t size, bool inclusive=true) const
Returns an approximation to the Probability Mass Function (PMF) of the input stream given a set of sp...
Definition: quantiles_sketch_impl.hpp:762
void merge(FwdSk &&other)
Merges another sketch into this one.
Definition: quantiles_sketch_impl.hpp:235
void update(FwdT &&item)
Updates this sketch with the given data item.
Definition: quantiles_sketch_impl.hpp:212
void serialize(std::ostream &os, const SerDe &sd=SerDe()) const
This method serializes the sketch into a given stream in a binary form.
Definition: quantiles_sketch_impl.hpp:277
string< Allocator > to_string(bool print_levels=false, bool print_items=false) const
Prints a summary of the sketch.
Definition: quantiles_sketch_impl.hpp:595
uint16_t get_k() const
Returns configured parameter k.
Definition: quantiles_sketch_impl.hpp:644
bool is_empty() const
Returns true if this sketch is empty.
Definition: quantiles_sketch_impl.hpp:654
const T & get_max_item() const
Returns the max item of the stream.
Definition: quantiles_sketch_impl.hpp:675
static quantiles_sketch deserialize(std::istream &is, const SerDe &sd=SerDe(), const Comparator &comparator=Comparator(), const Allocator &allocator=Allocator())
This method deserializes a sketch from a given stream.
double get_rank(const T &item, bool inclusive=true) const
Returns an approximation to the normalized rank of the given item from 0 to 1, inclusive.
Definition: quantiles_sketch_impl.hpp:755
allocator_type get_allocator() const
Returns the allocator for this sketch.
Definition: quantiles_sketch_impl.hpp:686
quantile_return_type get_quantile(double rank, bool inclusive=true) const
Returns an approximation to the data item associated with the given rank of a hypothetical sorted ver...
Definition: quantiles_sketch_impl.hpp:744
const_iterator begin() const
Iterator pointing to the first item in the sketch.
Definition: quantiles_sketch_impl.hpp:866
size_t get_serialized_size_bytes(const SerDe &sd=SerDe()) const
Computes size needed to serialize the current state of the sketch.
Definition: quantiles_sketch_impl.hpp:693
bool is_estimation_mode() const
Returns true if this sketch is in estimation mode.
Definition: quantiles_sketch_impl.hpp:659
const T & get_min_item() const
Returns the min item of the stream.
Definition: quantiles_sketch_impl.hpp:669
const_iterator end() const
Iterator pointing to the past-the-end item in the sketch.
Definition: quantiles_sketch_impl.hpp:871
uint64_t get_n() const
Returns the length of the input stream.
Definition: quantiles_sketch_impl.hpp:649
const uint16_t MAX_K
maximum value of parameter K
Definition: quantiles_sketch.hpp:41
const uint16_t MIN_K
minimum value of parameter K
Definition: quantiles_sketch.hpp:39
DataSketches namespace.
Definition: binomial_bounds.hpp:38
Interface for serializing and deserializing items.
Definition: serde.hpp:34
void serialize(std::ostream &os, const T *items, unsigned num) const
Stream serialization.