datasketches-cpp
Loading...
Searching...
No Matches
kll_sketch_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 KLL_SKETCH_IMPL_HPP_
21#define KLL_SKETCH_IMPL_HPP_
22
23#include <iostream>
24#include <iomanip>
25#include <sstream>
26#include <stdexcept>
27#include <type_traits>
28
29#include "conditional_forward.hpp"
30#include "count_zeros.hpp"
31#include "memory_operations.hpp"
32#include "kll_helper.hpp"
33
34namespace datasketches {
35
36template<typename T, typename C, typename A>
37kll_sketch<T, C, A>::kll_sketch(uint16_t k, const C& comparator, const A& allocator):
38comparator_(comparator),
39allocator_(allocator),
40k_(k),
41m_(kll_constants::DEFAULT_M),
42min_k_(k),
43num_levels_(1),
44is_level_zero_sorted_(false),
45n_(0),
46levels_(2, 0, allocator),
47items_(nullptr),
48items_size_(RESIZE_FACTOR == resize_factor::X1 ? k_ : std::min(k_, kll_constants::DEFAULT_K)),
49min_item_(),
50max_item_(),
51sorted_view_(nullptr)
52{
53 if (k < kll_constants::MIN_K || k > kll_constants::MAX_K) {
54 throw std::invalid_argument("K must be >= " + std::to_string(kll_constants::MIN_K) + " and <= "
55 + std::to_string(kll_constants::MAX_K) + ": " + std::to_string(k));
56 }
57 levels_[0] = levels_[1] = items_size_;
58 // items_ is allocated by the first update or merge: many sketches (e.g. per-group aggregation states)
59 // stay empty or are only ever merged into
60}
61
62template<typename T, typename C, typename A>
63kll_sketch<T, C, A>::kll_sketch(const kll_sketch& other):
64comparator_(other.comparator_),
65allocator_(other.allocator_),
66k_(other.k_),
67m_(other.m_),
68min_k_(other.min_k_),
69num_levels_(other.num_levels_),
70is_level_zero_sorted_(other.is_level_zero_sorted_),
71n_(other.n_),
72levels_(other.levels_),
73items_(nullptr),
74items_size_(other.items_size_),
75min_item_(other.min_item_),
76max_item_(other.max_item_),
77sorted_view_(nullptr)
78{
79 copy_items(other);
80}
81
82template<typename T, typename C, typename A>
83kll_sketch<T, C, A>::kll_sketch(kll_sketch&& other) noexcept:
84comparator_(std::move(other.comparator_)),
85allocator_(std::move(other.allocator_)),
86k_(other.k_),
87m_(other.m_),
88min_k_(other.min_k_),
89num_levels_(other.num_levels_),
90is_level_zero_sorted_(other.is_level_zero_sorted_),
91n_(other.n_),
92levels_(std::move(other.levels_)),
93items_(other.items_),
94items_size_(other.items_size_),
95min_item_(std::move(other.min_item_)),
96max_item_(std::move(other.max_item_)),
97sorted_view_(nullptr)
98{
99 other.items_ = nullptr;
100}
101
102template<typename T, typename C, typename A>
103kll_sketch<T, C, A>& kll_sketch<T, C, A>::operator=(const kll_sketch& other) {
104 kll_sketch copy(other);
105 std::swap(comparator_, copy.comparator_);
106 std::swap(allocator_, copy.allocator_);
107 std::swap(k_, copy.k_);
108 std::swap(m_, copy.m_);
109 std::swap(min_k_, copy.min_k_);
110 std::swap(num_levels_, copy.num_levels_);
111 std::swap(is_level_zero_sorted_, copy.is_level_zero_sorted_);
112 std::swap(n_, copy.n_);
113 std::swap(levels_, copy.levels_);
114 std::swap(items_, copy.items_);
115 std::swap(items_size_, copy.items_size_);
116 std::swap(min_item_, copy.min_item_);
117 std::swap(max_item_, copy.max_item_);
118 reset_sorted_view();
119 return *this;
120}
121
122template<typename T, typename C, typename A>
123kll_sketch<T, C, A>& kll_sketch<T, C, A>::operator=(kll_sketch&& other) {
124 std::swap(comparator_, other.comparator_);
125 std::swap(allocator_, other.allocator_);
126 std::swap(k_, other.k_);
127 std::swap(m_, other.m_);
128 std::swap(min_k_, other.min_k_);
129 std::swap(num_levels_, other.num_levels_);
130 std::swap(is_level_zero_sorted_, other.is_level_zero_sorted_);
131 std::swap(n_, other.n_);
132 std::swap(levels_, other.levels_);
133 std::swap(items_, other.items_);
134 std::swap(items_size_, other.items_size_);
135 std::swap(min_item_, other.min_item_);
136 std::swap(max_item_, other.max_item_);
137 reset_sorted_view();
138 return *this;
139}
140
141template<typename T, typename C, typename A>
142kll_sketch<T, C, A>::~kll_sketch() {
143 destroy_items();
144 reset_sorted_view();
145}
146
147template<typename T, typename C, typename A>
148void kll_sketch<T, C, A>::destroy_items() {
149 if (items_ != nullptr) {
150 const uint32_t begin = levels_[0];
151 const uint32_t end = levels_[num_levels_];
152 for (uint32_t i = begin; i < end; i++) items_[i].~T();
153 allocator_.deallocate(items_, items_size_);
154 items_ = nullptr;
155 }
156}
157
158template<typename T, typename C, typename A>
159template<typename TT, typename CC, typename AA>
160kll_sketch<T, C, A>::kll_sketch(const kll_sketch<TT, CC, AA>& other, const C& comparator, const A& allocator):
161comparator_(comparator),
162allocator_(allocator),
163k_(other.k_),
164m_(other.m_),
165min_k_(other.min_k_),
166num_levels_(other.num_levels_),
167is_level_zero_sorted_(other.is_level_zero_sorted_),
168n_(other.n_),
169levels_(other.levels_, allocator_),
170items_(nullptr),
171items_size_(other.items_size_),
172min_item_(other.min_item_),
173max_item_(other.max_item_),
174sorted_view_(nullptr)
175{
176 static_assert(
177 std::is_constructible<T, TT>::value,
178 "Type converting constructor requires new type to be constructible from existing type"
179 );
180 copy_items(other);
181 try {
182 check_sorting();
183 } catch (...) {
184 destroy_items(); // the destructor doesn't run if a constructor throws
185 throw;
186 }
187}
188
189template<typename T, typename C, typename A>
190template<typename FwdT>
192 if (!check_update_item(item)) { return; }
193 check_n_increase(1);
194 allocate_items(); // first, so that a failure leaves the sketch unchanged
195 reset_sorted_view(); // before any change, so that a failed copy can't leave a stale view
196 update_min_max(static_cast<const T&>(item)); // min and max are always copies
197 insert_level_zero(std::forward<FwdT>(item));
198}
199
200template<typename T, typename C, typename A>
201template<typename FwdT>
202void kll_sketch<T, C, A>::insert_level_zero(FwdT&& item) {
203 if (levels_[0] == 0) {
204 // item can refer into items_, and internal_update() can destroy it
205 T copy(std::forward<FwdT>(item));
206 const uint32_t index = internal_update();
207 new (&items_[index]) T(std::move(copy));
208 } else {
209 // construct the item before counting it, so that a failed copy leaves the sketch unchanged
210 new (&items_[levels_[0] - 1]) T(std::forward<FwdT>(item));
211 internal_update();
212 }
213}
214
215template<typename T, typename C, typename A>
216void kll_sketch<T, C, A>::check_n_increase(uint64_t increase) const {
217 if (n_ > kll_constants::MAX_N || increase > kll_constants::MAX_N - n_) {
218 throw std::overflow_error("n would exceed 2^63 - 1");
219 }
220}
221
222template<typename T, typename C, typename A>
223template<typename FwdT>
224void kll_sketch<T, C, A>::update(FwdT&& item, uint64_t weight) {
225 if (!check_update_item(item)) { return; }
226 if (weight == 0) throw std::invalid_argument("weight must be at least 1");
227 if (weight > kll_constants::MAX_WEIGHT) {
228 throw std::invalid_argument("weight must be less than 2^61: " + std::to_string(weight));
229 }
230 check_n_increase(weight);
231 if (weight == 1) {
232 update(std::forward<FwdT>(item));
233 return;
234 }
235 allocate_items(); // first, so that a failure leaves the sketch unchanged
236 reset_sorted_view(); // before any change, so that a failed copy can't leave a stale view
237 if (weight < levels_[0]) { // fits into level zero without compaction
238 update_min_max(static_cast<const T&>(item));
239 // each copy is counted only once it is constructed, so a failed copy leaves a valid sketch
240 for (uint64_t i = 1; i < weight; ++i) insert_level_zero(static_cast<const T&>(item));
241 insert_level_zero(std::forward<FwdT>(item));
242 } else {
243 merge(kll_sketch(k_, static_cast<const T&>(item), weight, comparator_, allocator_));
244 }
245}
246
247// An item at level h carries weight 2^h, so one copy of the item at each level
248// whose bit is set in the weight is an exact sketch of that many copies.
249// The weight is less than 2^61, so this needs at most 61 levels.
250template<typename T, typename C, typename A>
251kll_sketch<T, C, A>::kll_sketch(uint16_t k, const T& item, uint64_t weight, const C& comparator, const A& allocator):
252comparator_(comparator),
253allocator_(allocator),
254k_(k),
255m_(kll_constants::DEFAULT_M),
256min_k_(k),
257num_levels_(static_cast<uint8_t>(64 - count_leading_zeros_in_u64(weight))),
258is_level_zero_sorted_(true),
259n_(weight),
260levels_(num_levels_ + 1, 0, allocator),
261items_(nullptr),
262items_size_(0),
263min_item_(item),
264max_item_(item),
265sorted_view_(nullptr)
266{
267 for (uint8_t level = 0; level < num_levels_; ++level) {
268 levels_[level + 1] = levels_[level] + static_cast<uint32_t>((weight >> level) & 1);
269 }
270 items_size_ = levels_[num_levels_];
271 items_ = allocator_.allocate(items_size_);
272 // the destructor doesn't run if a constructor throws, so release the items here
273 uint32_t num_constructed = 0;
274 try {
275 for (; num_constructed < items_size_; ++num_constructed) new (&items_[num_constructed]) T(item);
276 } catch (...) {
277 for (uint32_t i = 0; i < num_constructed; ++i) items_[i].~T();
278 allocator_.deallocate(items_, items_size_);
279 throw;
280 }
281}
282
283template<typename T, typename C, typename A>
284void kll_sketch<T, C, A>::update_min_max(const T& item) {
285 if (is_empty()) {
286 min_item_.emplace(item);
287 max_item_.emplace(item);
288 } else {
289 if (comparator_(item, *min_item_)) *min_item_ = item;
290 if (comparator_(*max_item_, item)) *max_item_ = item;
291 }
292}
293
294template<typename T, typename C, typename A>
296 if (items_ == nullptr) {
297 // nothing is stored yet, so the buffer can start at its full size
298 items_ = allocator_.allocate(k_);
299 items_size_ = k_;
300 levels_[0] = levels_[1] = k_;
301 } else if (num_levels_ == 1 && items_size_ < k_) {
302 grow_items(k_); // the buffer is still growing: grow it to its full size in one step
303 reset_sorted_view(); // the cached view points into the old buffer
304 }
305}
306
307template<typename T, typename C, typename A>
308void kll_sketch<T, C, A>::allocate_items() {
309 if (items_ == nullptr) items_ = allocator_.allocate(items_size_);
310}
311
312template<typename T, typename C, typename A>
313template<typename O>
314void kll_sketch<T, C, A>::copy_items(const O& other) {
315 if (other.items_ == nullptr) return;
316 allocate_items();
317 auto i = levels_[0];
318 try {
319 for (; i < levels_[num_levels_]; ++i) new (&items_[i]) T(other.items_[i]);
320 } catch (...) {
321 // the destructor doesn't run if a constructor throws, so release the items here
322 for (auto j = levels_[0]; j < i; ++j) items_[j].~T();
323 allocator_.deallocate(items_, items_size_);
324 items_ = nullptr;
325 throw;
326 }
327}
328
329template<typename T, typename C, typename A>
330T* kll_sketch<T, C, A>::item_ptr(uint32_t index) const {
331 return items_ == nullptr ? nullptr : items_ + index;
332}
333
334template<typename T, typename C, typename A>
335uint32_t kll_sketch<T, C, A>::internal_update() {
336 allocate_items();
337 if (levels_[0] == 0) {
338 if (items_size_ < k_) {
339 grow_items(std::min<uint32_t>(items_size_ << static_cast<uint8_t>(RESIZE_FACTOR), k_));
340 } else {
341 compress_while_updating();
342 }
343 }
344 n_++;
345 is_level_zero_sorted_ = false;
346 return --levels_[0];
347}
348
349template<typename T, typename C, typename A>
350template<typename FwdSk>
351void kll_sketch<T, C, A>::merge(FwdSk&& other) {
352 if (this == &other) { throw std::invalid_argument("A sketch cannot merge with itself."); }
353 if (other.is_empty()) { return; }
354 if (m_ != other.m_) {
355 throw std::invalid_argument("incompatible M: " + std::to_string(m_) + " and " + std::to_string(other.m_));
356 }
357 check_n_increase(other.n_);
358 allocate_items(); // the higher levels are merged into items_ even if other's level zero is empty
359 reset_sorted_view(); // before any change, so that a failed copy can't leave a stale view
360 if (is_empty()) {
361 min_item_.emplace(conditional_forward<FwdSk>(*other.min_item_));
362 max_item_.emplace(conditional_forward<FwdSk>(*other.max_item_));
363 } else {
364 if (comparator_(*other.min_item_, *min_item_)) *min_item_ = conditional_forward<FwdSk>(*other.min_item_);
365 if (comparator_(*max_item_, *other.max_item_)) *max_item_ = conditional_forward<FwdSk>(*other.max_item_);
366 }
367 const uint64_t final_n = n_ + other.n_;
368 for (uint32_t i = other.levels_[0]; i < other.levels_[1]; i++) {
369 insert_level_zero(conditional_forward<FwdSk>(other.items_[i]));
370 }
371 if (other.num_levels_ >= 2) { merge_higher_levels(std::forward<FwdSk>(other), final_n); }
372 n_ = final_n;
373 if (other.is_estimation_mode()) { min_k_ = std::min(min_k_, other.min_k_); }
374 assert_correct_total_weight();
375}
376
377template<typename T, typename C, typename A>
379 return n_ == 0;
380}
381
382template<typename T, typename C, typename A>
384 return k_;
385}
386
387template<typename T, typename C, typename A>
389 return n_;
390}
391
392template<typename T, typename C, typename A>
394 return levels_[num_levels_] - levels_[0];
395}
396
397template<typename T, typename C, typename A>
399 return num_levels_ > 1;
400}
401
402template<typename T, typename C, typename A>
404 if (is_empty()) { throw std::runtime_error("operation is undefined for an empty sketch"); }
405 return *min_item_;
406}
407
408template<typename T, typename C, typename A>
410 if (is_empty()) { throw std::runtime_error("operation is undefined for an empty sketch"); }
411 return *max_item_;
412}
413
414template<typename T, typename C, typename A>
416 return comparator_;
417}
418
419template<typename T, typename C, typename A>
421 return allocator_;
422}
423
424template<typename T, typename C, typename A>
425double kll_sketch<T, C, A>::get_rank(const T& item, bool inclusive) const {
426 if (is_empty()) { throw std::runtime_error("operation is undefined for an empty sketch"); }
427 setup_sorted_view();
428 return sorted_view_->get_rank(item, inclusive);
429}
430
431template<typename T, typename C, typename A>
432auto kll_sketch<T, C, A>::get_PMF(const T* split_points, uint32_t size, bool inclusive) const -> vector_double {
433 if (is_empty()) { throw std::runtime_error("operation is undefined for an empty sketch"); }
434 setup_sorted_view();
435 return sorted_view_->get_PMF(split_points, size, inclusive);
436}
437
438template<typename T, typename C, typename A>
439auto kll_sketch<T, C, A>::get_CDF(const T* split_points, uint32_t size, bool inclusive) const -> vector_double {
440 if (is_empty()) { throw std::runtime_error("operation is undefined for an empty sketch"); }
441 setup_sorted_view();
442 return sorted_view_->get_CDF(split_points, size, inclusive);
443}
444
445template<typename T, typename C, typename A>
446auto kll_sketch<T, C, A>::get_quantile(double rank, bool inclusive) const -> quantile_return_type {
447 if (is_empty()) { throw std::runtime_error("operation is undefined for an empty sketch"); }
448 if ((rank < 0.0) || (rank > 1.0)) {
449 throw std::invalid_argument("normalized rank cannot be less than zero or greater than 1.0");
450 }
451 // may have a side effect of sorting level zero if needed
452 setup_sorted_view();
453 return sorted_view_->get_quantile(rank, inclusive);
454}
455
456template<typename T, typename C, typename A>
458 return get_normalized_rank_error(min_k_, pmf);
459}
460
461// implementation for fixed-size arithmetic types (integral and floating point)
462template<typename T, typename C, typename A>
463template<typename TT, typename SerDe, typename std::enable_if<std::is_arithmetic<TT>::value, int>::type>
465 if (is_empty()) { return EMPTY_SIZE_BYTES; }
466 if (num_levels_ == 1 && get_num_retained() == 1) {
467 return DATA_START_SINGLE_ITEM + sizeof(TT);
468 }
469 // the last integer in the levels_ array is not serialized because it can be derived
470 return DATA_START + num_levels_ * sizeof(uint32_t) + (get_num_retained() + 2) * sizeof(TT);
471}
472
473// implementation for all other types
474template<typename T, typename C, typename A>
475template<typename TT, typename SerDe, typename std::enable_if<!std::is_arithmetic<TT>::value, int>::type>
476size_t kll_sketch<T, C, A>::get_serialized_size_bytes(const SerDe& sd) const {
477 if (is_empty()) { return EMPTY_SIZE_BYTES; }
478 if (num_levels_ == 1 && get_num_retained() == 1) {
479 return DATA_START_SINGLE_ITEM + sd.size_of_item(items_[levels_[0]]);
480 }
481 // the last integer in the levels_ array is not serialized because it can be derived
482 size_t size = DATA_START + num_levels_ * sizeof(uint32_t);
483 size += sd.size_of_item(*min_item_);
484 size += sd.size_of_item(*max_item_);
485 for (auto it: *this) size += sd.size_of_item(it.first);
486 return size;
487}
488
489// implementation for fixed-size arithmetic types (integral and floating point)
490template<typename T, typename C, typename A>
491template<typename TT, typename std::enable_if<std::is_arithmetic<TT>::value, int>::type>
493 const uint8_t num_levels = kll_helper::ub_on_num_levels(n);
494 const uint32_t max_num_retained = kll_helper::compute_total_capacity(k, kll_constants::DEFAULT_M, num_levels);
495 // the last integer in the levels_ array is not serialized because it can be derived
496 return DATA_START + num_levels * sizeof(uint32_t) + (max_num_retained + 2) * sizeof(TT);
497}
498
499// implementation for all other types
500template<typename T, typename C, typename A>
501template<typename TT, typename std::enable_if<!std::is_arithmetic<TT>::value, int>::type>
502size_t kll_sketch<T, C, A>::get_max_serialized_size_bytes(uint16_t k, uint64_t n, size_t max_item_size_bytes) {
503 const uint8_t num_levels = kll_helper::ub_on_num_levels(n);
504 const uint32_t max_num_retained = kll_helper::compute_total_capacity(k, kll_constants::DEFAULT_M, num_levels);
505 // the last integer in the levels_ array is not serialized because it can be derived
506 return DATA_START + num_levels * sizeof(uint32_t) + (max_num_retained + 2) * max_item_size_bytes;
507}
508
509template<typename T, typename C, typename A>
510template<typename SerDe>
511void kll_sketch<T, C, A>::serialize(std::ostream& os, const SerDe& sd) const {
512 const bool is_single_item = n_ == 1;
513 const uint8_t preamble_ints(is_empty() || is_single_item ? PREAMBLE_INTS_SHORT : PREAMBLE_INTS_FULL);
514 write(os, preamble_ints);
515 const uint8_t serial_version(is_single_item ? SERIAL_VERSION_2 : SERIAL_VERSION_1);
516 write(os, serial_version);
517 const uint8_t family(FAMILY);
518 write(os, family);
519 const uint8_t flags_byte(
520 (is_empty() ? 1 << flags::IS_EMPTY : 0)
521 | (is_level_zero_sorted_ ? 1 << flags::IS_LEVEL_ZERO_SORTED : 0)
522 | (is_single_item ? 1 << flags::IS_SINGLE_ITEM : 0)
523 );
524 write(os, flags_byte);
525 write(os, k_);
526 write(os, m_);
527 const uint8_t unused = 0;
528 write(os, unused);
529 if (is_empty()) return;
530 if (!is_single_item) {
531 write(os, n_);
532 write(os, min_k_);
533 write(os, num_levels_);
534 write(os, unused);
535 if (num_levels_ == 1 && items_size_ < k_) {
536 write(os, levels_[0] + (k_ - items_size_));
537 } else {
538 write(os, levels_.data(), sizeof(levels_[0]) * num_levels_);
539 }
540 sd.serialize(os, &*min_item_, 1);
541 sd.serialize(os, &*max_item_, 1);
542 }
543 sd.serialize(os, &items_[levels_[0]], get_num_retained());
544}
545
546template<typename T, typename C, typename A>
547template<typename SerDe>
548auto kll_sketch<T, C, A>::serialize(unsigned header_size_bytes, const SerDe& sd) const -> vector_bytes {
549 const bool is_single_item = n_ == 1;
550 const size_t size = header_size_bytes + get_serialized_size_bytes(sd);
551 vector_bytes bytes(size, 0, allocator_);
552 uint8_t* ptr = bytes.data() + header_size_bytes;
553 const uint8_t* end_ptr = bytes.data() + size;
554 const uint8_t preamble_ints(is_empty() || is_single_item ? PREAMBLE_INTS_SHORT : PREAMBLE_INTS_FULL);
555 ptr += copy_to_mem(preamble_ints, ptr);
556 const uint8_t serial_version(is_single_item ? SERIAL_VERSION_2 : SERIAL_VERSION_1);
557 ptr += copy_to_mem(serial_version, ptr);
558 const uint8_t family(FAMILY);
559 ptr += copy_to_mem(family, ptr);
560 const uint8_t flags_byte(
561 (is_empty() ? 1 << flags::IS_EMPTY : 0)
562 | (is_level_zero_sorted_ ? 1 << flags::IS_LEVEL_ZERO_SORTED : 0)
563 | (is_single_item ? 1 << flags::IS_SINGLE_ITEM : 0)
564 );
565 ptr += copy_to_mem(flags_byte, ptr);
566 ptr += copy_to_mem(k_, ptr);
567 ptr += copy_to_mem(m_, ptr);
568 ptr += sizeof(uint8_t); // unused
569 if (!is_empty()) {
570 if (!is_single_item) {
571 ptr += copy_to_mem(n_, ptr);
572 ptr += copy_to_mem(min_k_, ptr);
573 ptr += copy_to_mem(num_levels_, ptr);
574 ptr += sizeof(uint8_t); // unused
575 if (num_levels_ == 1 && items_size_ < k_) {
576 ptr += copy_to_mem(levels_[0] + (k_ - items_size_), ptr);
577 } else {
578 ptr += copy_to_mem(levels_.data(), ptr, sizeof(levels_[0]) * num_levels_);
579 }
580 ptr += sd.serialize(ptr, end_ptr - ptr, &*min_item_, 1);
581 ptr += sd.serialize(ptr, end_ptr - ptr, &*max_item_, 1);
582 }
583 const size_t bytes_remaining = end_ptr - ptr;
584 ptr += sd.serialize(ptr, bytes_remaining, &items_[levels_[0]], get_num_retained());
585 }
586 const size_t delta = ptr - bytes.data();
587 if (delta != size) throw std::logic_error("serialized size mismatch: " + std::to_string(delta)
588 + " != " + std::to_string(size));
589 return bytes;
590}
591
592template<typename T, typename C, typename A>
593template<typename SerDe>
594kll_sketch<T, C, A> kll_sketch<T, C, A>::deserialize(std::istream& is, const SerDe& sd,
595 const C& comparator, const A& allocator) {
596 const auto preamble_ints = read<uint8_t>(is);
597 const auto serial_version = read<uint8_t>(is);
598 const auto family_id = read<uint8_t>(is);
599 const auto flags_byte = read<uint8_t>(is);
600 const auto k = read<uint16_t>(is);
601 const auto m = read<uint8_t>(is);
602 read<uint8_t>(is); // skip unused byte
603
604 check_k(k);
605 check_m(m);
606 check_preamble_ints(preamble_ints, flags_byte);
607 check_serial_version(serial_version);
608 check_family_id(family_id);
609
610 if (!is.good()) throw std::runtime_error("error reading from std::istream");
611 const bool is_empty(flags_byte & (1 << flags::IS_EMPTY));
612 if (is_empty) return kll_sketch(k, comparator, allocator);
613
614 uint64_t n;
615 uint16_t min_k;
616 uint8_t num_levels;
617 const bool is_single_item(flags_byte & (1 << flags::IS_SINGLE_ITEM)); // used in serial version 2
618 if (is_single_item) {
619 n = 1;
620 min_k = k;
621 num_levels = 1;
622 } else {
623 n = read<uint64_t>(is);
624 min_k = read<uint16_t>(is);
625 num_levels = read<uint8_t>(is);
626 read<uint8_t>(is); // skip unused byte
627 check_num_levels(num_levels);
628 }
629 vector_u32 levels(num_levels + 1, 0, allocator);
630 const uint32_t capacity(kll_helper::compute_total_capacity(k, m, num_levels));
631 if (is_single_item) {
632 levels[0] = capacity - 1;
633 } else {
634 // the last integer in levels_ is not serialized because it can be derived
635 read(is, levels.data(), sizeof(levels[0]) * num_levels);
636 if (!is.good()) throw std::runtime_error("error reading from std::istream");
637 }
638 levels[num_levels] = capacity;
639 check_levels(levels);
640 check_n(n, levels[num_levels] - levels[0]);
641 optional<T> min_item;
642 optional<T> max_item;
643 if (!is_single_item) {
644 // Space to deserialize min and max.
645 // serde::deserialize expects allocated but not initialized storage.
646 typename std::aligned_storage<sizeof(T), alignof(T)>::type tmp_storage;
647 T* tmp = reinterpret_cast<T*>(&tmp_storage);
648
649 sd.deserialize(is, tmp, 1);
650 // serde call did not throw, repackage and cleanup
651 min_item.emplace(std::move(*tmp));
652 tmp->~T();
653 sd.deserialize(is, tmp, 1);
654 // serde call did not throw, repackage and cleanup
655 max_item.emplace(std::move(*tmp));
656 tmp->~T();
657 }
658 A alloc(allocator);
659 auto items_buffer_deleter = [capacity, &alloc](T* ptr) { alloc.deallocate(ptr, capacity); };
660 std::unique_ptr<T, decltype(items_buffer_deleter)> items_buffer(alloc.allocate(capacity), items_buffer_deleter);
661 const auto num_items = levels[num_levels] - levels[0];
662 sd.deserialize(is, &items_buffer.get()[levels[0]], num_items);
663 // serde call did not throw, repackage with destrtuctors
664 std::unique_ptr<T, items_deleter> items(items_buffer.release(), items_deleter(levels[0], capacity, allocator));
665 const bool is_level_zero_sorted = (flags_byte & (1 << flags::IS_LEVEL_ZERO_SORTED)) > 0;
666 if (is_single_item) {
667 min_item.emplace(items.get()[levels[0]]);
668 max_item.emplace(items.get()[levels[0]]);
669 }
670 if (!is.good())
671 throw std::runtime_error("error reading from std::istream");
672 return kll_sketch(k, min_k, n, num_levels, std::move(levels), std::move(items), capacity,
673 std::move(min_item), std::move(max_item), is_level_zero_sorted, comparator);
674}
675
676template<typename T, typename C, typename A>
677template<typename SerDe>
678kll_sketch<T, C, A> kll_sketch<T, C, A>::deserialize(const void* bytes, size_t size, const SerDe& sd,
679 const C& comparator, const A& allocator) {
680 ensure_minimum_memory(size, 8);
681 const char* ptr = static_cast<const char*>(bytes);
682 uint8_t preamble_ints;
683 ptr += copy_from_mem(ptr, preamble_ints);
684 uint8_t serial_version;
685 ptr += copy_from_mem(ptr, serial_version);
686 uint8_t family_id;
687 ptr += copy_from_mem(ptr, family_id);
688 uint8_t flags_byte;
689 ptr += copy_from_mem(ptr, flags_byte);
690 uint16_t k;
691 ptr += copy_from_mem(ptr, k);
692 uint8_t m;
693 ptr += copy_from_mem(ptr, m);
694 ptr += sizeof(uint8_t); // skip unused byte
695
696 check_k(k);
697 check_m(m);
698 check_preamble_ints(preamble_ints, flags_byte);
699 check_serial_version(serial_version);
700 check_family_id(family_id);
701 ensure_minimum_memory(size, preamble_ints * sizeof(uint32_t));
702
703 const bool is_empty(flags_byte & (1 << flags::IS_EMPTY));
704 if (is_empty) return kll_sketch(k, comparator, allocator);
705
706 uint64_t n;
707 uint16_t min_k;
708 uint8_t num_levels;
709 const bool is_single_item(flags_byte & (1 << flags::IS_SINGLE_ITEM)); // used in serial version 2
710 const char* end_ptr = static_cast<const char*>(bytes) + size;
711 if (is_single_item) {
712 n = 1;
713 min_k = k;
714 num_levels = 1;
715 } else {
716 ptr += copy_from_mem(ptr, n);
717 ptr += copy_from_mem(ptr, min_k);
718 ptr += copy_from_mem(ptr, num_levels);
719 ptr += sizeof(uint8_t); // skip unused byte
720 check_num_levels(num_levels);
721 }
722 vector_u32 levels(num_levels + 1, 0, allocator);
723 const uint32_t capacity(kll_helper::compute_total_capacity(k, m, num_levels));
724 if (is_single_item) {
725 levels[0] = capacity - 1;
726 } else {
727 // the last integer in levels_ is not serialized because it can be derived
728 ensure_minimum_memory(size, (ptr - static_cast<const char*>(bytes)) + sizeof(levels[0]) * num_levels);
729 ptr += copy_from_mem(ptr, levels.data(), sizeof(levels[0]) * num_levels);
730 }
731 levels[num_levels] = capacity;
732 check_levels(levels);
733 check_n(n, levels[num_levels] - levels[0]);
734 optional<T> min_item;
735 optional<T> max_item;
736 if (!is_single_item) {
737 // Space to deserialize min and max.
738 // serde::deserialize expects allocated but not initialized storage.
739 typename std::aligned_storage<sizeof(T), alignof(T)>::type tmp_storage;
740 T* tmp = reinterpret_cast<T*>(&tmp_storage);
741
742 ptr += sd.deserialize(ptr, end_ptr - ptr, tmp, 1);
743 // serde call did not throw, repackage and cleanup
744 min_item.emplace(std::move(*tmp));
745 tmp->~T();
746 ptr += sd.deserialize(ptr, end_ptr - ptr, tmp, 1);
747 // serde call did not throw, repackage and cleanup
748 max_item.emplace(std::move(*tmp));
749 tmp->~T();
750 }
751 A alloc(allocator);
752 auto items_buffer_deleter = [capacity, &alloc](T* ptr) { alloc.deallocate(ptr, capacity); };
753 std::unique_ptr<T, decltype(items_buffer_deleter)> items_buffer(alloc.allocate(capacity), items_buffer_deleter);
754 const auto num_items = levels[num_levels] - levels[0];
755 ptr += sd.deserialize(ptr, end_ptr - ptr, &items_buffer.get()[levels[0]], num_items);
756 // serde call did not throw, repackage with destrtuctors
757 std::unique_ptr<T, items_deleter> items(items_buffer.release(), items_deleter(levels[0], capacity, allocator));
758 const size_t delta = ptr - static_cast<const char*>(bytes);
759 if (delta != size) throw std::logic_error("deserialized size mismatch: " + std::to_string(delta) + " != " + std::to_string(size));
760 const bool is_level_zero_sorted = (flags_byte & (1 << flags::IS_LEVEL_ZERO_SORTED)) > 0;
761 if (is_single_item) {
762 min_item.emplace(items.get()[levels[0]]);
763 max_item.emplace(items.get()[levels[0]]);
764 }
765 return kll_sketch(k, min_k, n, num_levels, std::move(levels), std::move(items), capacity,
766 std::move(min_item), std::move(max_item), is_level_zero_sorted, comparator);
767}
768
769/*
770 * Gets the normalized rank error given k and pmf.
771 * k - the configuration parameter
772 * pmf - if true, returns the "double-sided" normalized rank error for the get_PMF() function.
773 * Otherwise, it is the "single-sided" normalized rank error for all the other queries.
774 * Constants were derived as the best fit to 99 percentile empirically measured max error in thousands of trials
775 */
776template<typename T, typename C, typename A>
777double kll_sketch<T, C, A>::get_normalized_rank_error(uint16_t k, bool pmf) {
778 return pmf
779 ? 2.446 / pow(k, 0.9433)
780 : 2.296 / pow(k, 0.9723);
781}
782
783// for deserialization
784template<typename T, typename C, typename A>
785kll_sketch<T, C, A>::kll_sketch(uint16_t k, uint16_t min_k, uint64_t n, uint8_t num_levels, vector_u32&& levels,
786 std::unique_ptr<T, items_deleter> items, uint32_t items_size, optional<T>&& min_item,
787 optional<T>&& max_item, bool is_level_zero_sorted, const C& comparator):
788comparator_(comparator),
789allocator_(levels.get_allocator()),
790k_(k),
791m_(kll_constants::DEFAULT_M),
792min_k_(min_k),
793num_levels_(num_levels),
794is_level_zero_sorted_(is_level_zero_sorted),
795n_(n),
796levels_(std::move(levels)),
797items_(items.release()),
798items_size_(items_size),
799min_item_(std::move(min_item)),
800max_item_(std::move(max_item)),
801sorted_view_(nullptr)
802{}
803
804// The following code is only valid in the special case of exactly reaching capacity while updating.
805// It cannot be used while merging, while reducing k, or anything else.
806template<typename T, typename C, typename A>
807void kll_sketch<T, C, A>::compress_while_updating(void) {
808 const uint8_t level = find_level_to_compact();
809
810 // It is important to add the new top level right here. Be aware that this operation
811 // grows the buffer and shifts the data and also the boundaries of the data and grows the
812 // levels array and increments num_levels_
813 if (level == (num_levels_ - 1)) {
814 add_empty_top_level_to_completely_full_sketch();
815 }
816
817 const uint32_t raw_beg = levels_[level];
818 const uint32_t raw_lim = levels_[level + 1];
819 // +2 is OK because we already added a new top level if necessary
820 const uint32_t pop_above = levels_[level + 2] - raw_lim;
821 const uint32_t raw_pop = raw_lim - raw_beg;
822 const bool odd_pop = kll_helper::is_odd(raw_pop);
823 const uint32_t adj_beg = odd_pop ? raw_beg + 1 : raw_beg;
824 const uint32_t adj_pop = odd_pop ? raw_pop - 1 : raw_pop;
825 const uint32_t half_adj_pop = adj_pop / 2;
826 const uint32_t destroy_beg = levels_[0];
827
828 // level zero might not be sorted, so we must sort it if we wish to compact it
829 // sort_level_zero() is not used here because of the adjustment for odd number of items
830 if ((level == 0) && !is_level_zero_sorted_) {
831 std::sort(items_ + adj_beg, items_ + adj_beg + adj_pop, comparator_);
832 }
833 if (pop_above == 0) {
834 kll_helper::randomly_halve_up(items_, adj_beg, adj_pop);
835 } else {
836 kll_helper::randomly_halve_down(items_, adj_beg, adj_pop);
837 kll_helper::merge_sorted_arrays<T, C>(items_, adj_beg, half_adj_pop, raw_lim, pop_above, adj_beg + half_adj_pop, comparator_);
838 }
839 levels_[level + 1] -= half_adj_pop; // adjust boundaries of the level above
840 if (odd_pop) {
841 levels_[level] = levels_[level + 1] - 1; // the current level now contains one item
842 if (levels_[level] != raw_beg) items_[levels_[level]] = std::move(items_[raw_beg]); // namely this leftover guy
843 } else {
844 levels_[level] = levels_[level + 1]; // the current level is now empty
845 }
846
847 // verify that we freed up half_adj_pop array slots just below the current level
848 if (levels_[level] != (raw_beg + half_adj_pop)) throw std::logic_error("compaction error");
849
850 // finally, we need to shift up the data in the levels below
851 // so that the freed-up space can be used by level zero
852 if (level > 0) {
853 const uint32_t amount = raw_beg - levels_[0];
854 std::move_backward(items_ + levels_[0], items_ + levels_[0] + amount, items_ + levels_[0] + half_adj_pop + amount);
855 for (uint8_t lvl = 0; lvl < level; lvl++) levels_[lvl] += half_adj_pop;
856 }
857 for (uint32_t i = 0; i < half_adj_pop; i++) items_[i + destroy_beg].~T();
858}
859
860template<typename T, typename C, typename A>
861uint8_t kll_sketch<T, C, A>::find_level_to_compact() const {
862 uint8_t level = 0;
863 while (true) {
864 if (level >= num_levels_) throw std::logic_error("capacity calculation error");
865 const uint32_t pop = levels_[level + 1] - levels_[level];
866 const uint32_t cap = kll_helper::level_capacity(k_, num_levels_, level, m_);
867 if (pop >= cap) {
868 return level;
869 }
870 level++;
871 }
872}
873
874template<typename T, typename C, typename A>
875void kll_sketch<T, C, A>::add_empty_top_level_to_completely_full_sketch() {
876 const uint32_t cur_total_cap = levels_[num_levels_];
877
878 // make sure that we are following a certain growth scheme
879 if (levels_[0] != 0) throw std::logic_error("full sketch expected");
880 if (items_size_ != cur_total_cap) throw std::logic_error("current capacity mismatch");
881
882 // note that merging MIGHT over-grow levels_, in which case we might not have to grow it here
883 const uint8_t new_levels_size = num_levels_ + 2;
884 if (levels_.size() < new_levels_size) {
885 levels_.resize(new_levels_size);
886 }
887
888 const uint32_t delta_cap = kll_helper::level_capacity(k_, num_levels_ + 1, 0, m_);
889 const uint32_t new_total_cap = cur_total_cap + delta_cap;
890
891 // move (and shift) the current data into the new buffer
892 T* new_buf = allocator_.allocate(new_total_cap);
893 kll_helper::move_construct<T>(items_, 0, cur_total_cap, new_buf, delta_cap, true);
894 allocator_.deallocate(items_, items_size_);
895 items_ = new_buf;
896 items_size_ = new_total_cap;
897
898 // this loop includes the old "extra" index at the top
899 for (uint8_t i = 0; i <= num_levels_; i++) {
900 levels_[i] += delta_cap;
901 }
902
903 if (levels_[num_levels_] != new_total_cap) throw std::logic_error("new capacity mismatch");
904
905 num_levels_++;
906 levels_[num_levels_] = new_total_cap; // initialize the new "extra" index at the top
907}
908
909// Grows the items buffer of a one-level sketch when it is full and smaller than k.
910// Compaction starts only when the buffer is full at k items, so growing does not change the result.
911template<typename T, typename C, typename A>
912void kll_sketch<T, C, A>::grow_items(uint32_t new_size) {
913 const uint32_t delta = new_size - items_size_;
914 T* new_items = allocator_.allocate(new_size);
915 kll_helper::move_construct<T>(items_, levels_[0], levels_[1], new_items, levels_[0] + delta, true);
916 allocator_.deallocate(items_, items_size_);
917 items_ = new_items;
918 items_size_ = new_size;
919 levels_[0] += delta;
920 levels_[1] += delta;
921}
922
923template<typename T, typename C, typename A>
924void kll_sketch<T, C, A>::sort_level_zero() {
925 if (!is_level_zero_sorted_) {
926 std::sort(item_ptr(levels_[0]), item_ptr(levels_[1]), comparator_);
927 is_level_zero_sorted_ = true;
928 }
929}
930
931template<typename T, typename C, typename A>
932void kll_sketch<T, C, A>::check_sorting() const {
933 // not checking level 0
934 for (uint8_t level = 1; level < num_levels_; ++level) {
935 const auto from = item_ptr(levels_[level]);
936 const auto to = item_ptr(levels_[level + 1]);
937 if (!std::is_sorted(from, to, comparator_)) {
938 throw std::logic_error("levels must be sorted");
939 }
940 }
941}
942
943template<typename T, typename C, typename A>
945 const_cast<kll_sketch*>(this)->sort_level_zero(); // allow this side effect
946 quantiles_sorted_view<T, C, A> view(get_num_retained(), comparator_, allocator_);
947 if (is_empty()) return view;
948 if (!is_min_retained()) view.add_min(*min_item_);
949 for (uint8_t level = 0; level < num_levels_; ++level) {
950 const auto from = item_ptr(levels_[level]);
951 const auto to = item_ptr(levels_[level + 1]); // exclusive
952 view.add(from, to, 1ULL << level);
953 }
954 view.convert_to_cummulative(*max_item_);
955 return view;
956}
957
958template<typename T, typename C, typename A>
959template<typename O>
960void kll_sketch<T, C, A>::merge_higher_levels(O&& other, uint64_t final_n) {
961 const uint32_t tmp_num_items = get_num_retained() + other.get_num_retained_above_level_zero();
962 A alloc(allocator_);
963 auto tmp_items_deleter = [tmp_num_items, &alloc](T* ptr) { alloc.deallocate(ptr, tmp_num_items); }; // no destructor needed
964 const std::unique_ptr<T, decltype(tmp_items_deleter)> workbuf(allocator_.allocate(tmp_num_items), tmp_items_deleter);
965 const uint8_t ub = kll_helper::ub_on_num_levels(final_n);
966 const size_t work_levels_size = ub + 2; // ub+1 does not work
967 vector_u32 worklevels(work_levels_size, 0, allocator_);
968 vector_u32 outlevels(work_levels_size, 0, allocator_);
969
970 const uint8_t provisional_num_levels = std::max(num_levels_, other.num_levels_);
971
972 // Allocate everything the merge needs before any item is moved out of this sketch,
973 // so that an allocation failure leaves this sketch valid.
974 // The level sizes after compression depend only on the level sizes before it.
975 worklevels[0] = 0;
976 worklevels[1] = safe_level_size(0); // the level zero items of other were already inserted into this
977 for (uint8_t lvl = 1; lvl < provisional_num_levels; lvl++) {
978 worklevels[lvl + 1] = worklevels[lvl] + safe_level_size(lvl) + other.safe_level_size(lvl);
979 }
980 const kll_helper::compress_result predicted = kll_helper::predict_compress(k_, m_, provisional_num_levels,
981 worklevels.data(), outlevels.data());
982 // ub can sometimes be much bigger
983 if (predicted.final_num_levels > ub) throw std::logic_error("merge error");
984 auto new_items_deleter = [&predicted, &alloc](T* ptr) { alloc.deallocate(ptr, predicted.final_capacity); }; // holds no items
985 std::unique_ptr<T, decltype(new_items_deleter)> new_items(
986 predicted.final_capacity != items_size_ ? allocator_.allocate(predicted.final_capacity) : nullptr, new_items_deleter);
987 const size_t new_levels_size = predicted.final_num_levels + 1;
988 levels_.reserve(new_levels_size);
989
990 populate_work_arrays(std::forward<O>(other), workbuf.get(), worklevels.data(), provisional_num_levels);
991
992 const kll_helper::compress_result result = kll_helper::general_compress<T, C>(k_, m_, provisional_num_levels, workbuf.get(),
993 worklevels.data(), outlevels.data(), is_level_zero_sorted_, comparator_);
994 if (result.final_num_levels != predicted.final_num_levels || result.final_capacity != predicted.final_capacity
995 || result.final_num_items != predicted.final_num_items) {
996 throw std::logic_error("merge error: compression does not match the prediction");
997 }
998
999 // now we need to transfer the results back into "this" sketch
1000 if (new_items) {
1001 allocator_.deallocate(items_, items_size_);
1002 items_size_ = result.final_capacity;
1003 items_ = new_items.release();
1004 }
1005 const uint32_t free_space_at_bottom = result.final_capacity - result.final_num_items;
1006 kll_helper::move_construct<T>(workbuf.get(), outlevels[0], outlevels[0] + result.final_num_items, items_, free_space_at_bottom, true);
1007
1008 if (levels_.size() < new_levels_size) {
1009 levels_.resize(new_levels_size); // within the reserved capacity
1010 }
1011 const uint32_t offset = free_space_at_bottom - outlevels[0];
1012 for (uint8_t lvl = 0; lvl < levels_.size(); lvl++) { // includes the "extra" index
1013 levels_[lvl] = outlevels[lvl] + offset;
1014 }
1015 num_levels_ = result.final_num_levels;
1016}
1017
1018// This leaves items_ uninitialized (all objects moved out and destroyed).
1019// worklevels must already hold the level boundaries in workbuf.
1020// The items of other are copied (or moved) first, the only step that can fail on a throwing copy:
1021// if one throws, the copies made are destroyed and this sketch is unchanged.
1022// After that, the items of this sketch are only moved.
1023template<typename T, typename C, typename A>
1024template<typename FwdSk>
1025void kll_sketch<T, C, A>::populate_work_arrays(FwdSk&& other, T* workbuf, const uint32_t* worklevels, uint8_t provisional_num_levels) {
1026 // the level zero items of other were already inserted into this
1027 // each level of other goes after the items of this sketch at that level
1028 uint8_t lvl = 1;
1029 uint32_t num_constructed = 0; // at level lvl
1030 try {
1031 for (; lvl < provisional_num_levels; ++lvl) {
1032 const uint32_t other_pop = other.safe_level_size(lvl);
1033 const uint32_t dst = worklevels[lvl] + safe_level_size(lvl);
1034 for (num_constructed = 0; num_constructed < other_pop; ++num_constructed) {
1035 new (&workbuf[dst + num_constructed]) T(conditional_forward<FwdSk>(other.items_[other.levels_[lvl] + num_constructed]));
1036 }
1037 }
1038 } catch (...) {
1039 for (uint8_t l = 1; l <= lvl && l < provisional_num_levels; ++l) {
1040 const uint32_t dst = worklevels[l] + safe_level_size(l);
1041 const uint32_t count = l < lvl ? other.safe_level_size(l) : num_constructed;
1042 for (uint32_t i = 0; i < count; ++i) workbuf[dst + i].~T();
1043 }
1044 throw;
1045 }
1046
1047 kll_helper::move_construct<T>(items_, levels_[0], levels_[1], workbuf, 0, true);
1048 for (lvl = 1; lvl < provisional_num_levels; ++lvl) {
1049 const uint32_t self_pop = safe_level_size(lvl);
1050 if (self_pop > 0) {
1051 kll_helper::merge_sorted_arrays_into_gap<T, C>(items_, levels_[lvl], self_pop, workbuf, worklevels[lvl],
1052 other.safe_level_size(lvl), comparator_);
1053 }
1054 }
1055}
1056
1057template<typename T, typename C, typename A>
1058void kll_sketch<T, C, A>::assert_correct_total_weight() const {
1059 const uint64_t total(kll_helper::sum_the_sample_weights(num_levels_, levels_.data()));
1060 if (total != n_) {
1061 throw std::logic_error("Total weight does not match N");
1062 }
1063}
1064
1065template<typename T, typename C, typename A>
1066uint32_t kll_sketch<T, C, A>::safe_level_size(uint8_t level) const {
1067 if (level >= num_levels_) return 0;
1068 return levels_[level + 1] - levels_[level];
1069}
1070
1071template<typename T, typename C, typename A>
1072uint32_t kll_sketch<T, C, A>::get_num_retained_above_level_zero() const {
1073 if (num_levels_ == 1) return 0;
1074 return levels_[num_levels_] - levels_[1];
1075}
1076
1077template<typename T, typename C, typename A>
1078bool kll_sketch<T, C, A>::is_min_retained() const {
1079 for (uint8_t level = 0; level < num_levels_; ++level) {
1080 const bool level_is_nonempty = levels_[level] < levels_[level + 1];
1081 if (level_is_nonempty) { // the if exists to skip a potentially expensive comparator run
1082 // min_item_ is the smallest item of the stream, so min_item_ <= item,
1083 // and !(min_item_ < item) means that item == min_item_
1084 if (!comparator_(*min_item_, items_[levels_[level]])) return true;
1085 }
1086 }
1087 return false;
1088}
1089
1090template<typename T, typename C, typename A>
1091void kll_sketch<T, C, A>::check_k(uint16_t k) {
1092 if (k < kll_constants::MIN_K) {
1093 throw std::invalid_argument("Possible corruption: K must be >= " + std::to_string(kll_constants::MIN_K)
1094 + ": " + std::to_string(k));
1095 }
1096}
1097
1098template<typename T, typename C, typename A>
1099void kll_sketch<T, C, A>::check_m(uint8_t m) {
1100 if (m != kll_constants::DEFAULT_M) {
1101 throw std::invalid_argument("Possible corruption: M must be " + std::to_string(kll_constants::DEFAULT_M)
1102 + ": " + std::to_string(m));
1103 }
1104}
1105
1106template<typename T, typename C, typename A>
1107void kll_sketch<T, C, A>::check_preamble_ints(uint8_t preamble_ints, uint8_t flags_byte) {
1108 const bool is_empty(flags_byte & (1 << flags::IS_EMPTY));
1109 const bool is_single_item(flags_byte & (1 << flags::IS_SINGLE_ITEM));
1110 if (is_empty || is_single_item) {
1111 if (preamble_ints != PREAMBLE_INTS_SHORT) {
1112 throw std::invalid_argument("Possible corruption: preamble ints must be "
1113 + std::to_string(PREAMBLE_INTS_SHORT) + " for an empty or single item sketch: " + std::to_string(preamble_ints));
1114 }
1115 } else {
1116 if (preamble_ints != PREAMBLE_INTS_FULL) {
1117 throw std::invalid_argument("Possible corruption: preamble ints must be "
1118 + std::to_string(PREAMBLE_INTS_FULL) + " for a sketch with more than one item: " + std::to_string(preamble_ints));
1119 }
1120 }
1121}
1122
1123template<typename T, typename C, typename A>
1124void kll_sketch<T, C, A>::check_serial_version(uint8_t serial_version) {
1125 if (serial_version != SERIAL_VERSION_1 && serial_version != SERIAL_VERSION_2) {
1126 throw std::invalid_argument("Possible corruption: serial version mismatch: expected "
1127 + std::to_string(SERIAL_VERSION_1) + " or " + std::to_string(SERIAL_VERSION_2)
1128 + ", got " + std::to_string(serial_version));
1129 }
1130}
1131
1132template<typename T, typename C, typename A>
1133void kll_sketch<T, C, A>::check_family_id(uint8_t family_id) {
1134 if (family_id != FAMILY) {
1135 throw std::invalid_argument("Possible corruption: family mismatch: expected "
1136 + std::to_string(FAMILY) + ", got " + std::to_string(family_id));
1137 }
1138}
1139
1140// a sketch that is not empty retains at least one item, has n from 1 to kll_constants::MAX_N,
1141// the cap that update() and merge() keep, and has n at least as large as the number of retained items,
1142// each of which has a weight of at least 1
1143template<typename T, typename C, typename A>
1144void kll_sketch<T, C, A>::check_n(uint64_t n, uint32_t num_retained) {
1145 if (num_retained == 0) {
1146 throw std::invalid_argument("Possible corruption: a sketch that is not empty retains no items");
1147 }
1148 if (n == 0 || n > kll_constants::MAX_N) {
1149 throw std::invalid_argument("Possible corruption: n must be from 1 to 2^63 - 1: " + std::to_string(n));
1150 }
1151 if (n < num_retained) {
1152 throw std::invalid_argument("Possible corruption: n " + std::to_string(n)
1153 + " is less than the number of retained items " + std::to_string(num_retained));
1154 }
1155}
1156
1157template<typename T, typename C, typename A>
1158void kll_sketch<T, C, A>::check_num_levels(uint8_t num_levels) {
1159 if (num_levels == 0) {
1160 throw std::invalid_argument("Possible corruption: number of levels must be > 0");
1161 }
1162}
1163
1164// The last entry is the capacity. Each level must start at or after the previous one,
1165// so every level lies within the items buffer.
1166template<typename T, typename C, typename A>
1167void kll_sketch<T, C, A>::check_levels(const vector_u32& levels) {
1168 for (size_t i = 1; i < levels.size(); ++i) {
1169 if (levels[i - 1] > levels[i]) {
1170 throw std::invalid_argument("Possible corruption: levels[" + std::to_string(i - 1) + "] = "
1171 + std::to_string(levels[i - 1]) + " > levels[" + std::to_string(i) + "] = " + std::to_string(levels[i]));
1172 }
1173 }
1174}
1175
1176template <typename T, typename C, typename A>
1177string<A> kll_sketch<T, C, A>::to_string(bool print_levels, bool print_items) const {
1178 // Using a temporary stream for implementation here does not comply with AllocatorAwareContainer requirements.
1179 // The stream does not support passing an allocator instance, and alternatives are complicated.
1180 std::ostringstream os;
1181 os << "### KLL sketch summary:" << std::endl;
1182 os << " K : " << k_ << std::endl;
1183 os << " min K : " << min_k_ << std::endl;
1184 os << " M : " << (unsigned int) m_ << std::endl;
1185 os << " N : " << n_ << std::endl;
1186 os << " Epsilon : " << std::setprecision(3) << get_normalized_rank_error(false) * 100 << "%" << std::endl;
1187 os << " Epsilon PMF : " << get_normalized_rank_error(true) * 100 << "%" << std::endl;
1188 os << " Empty : " << (is_empty() ? "true" : "false") << std::endl;
1189 os << " Estimation mode: " << (is_estimation_mode() ? "true" : "false") << std::endl;
1190 os << " Levels : " << (unsigned int) num_levels_ << std::endl;
1191 os << " Sorted : " << (is_level_zero_sorted_ ? "true" : "false") << std::endl;
1192 // a buffer still growing to k items shows the capacity of a full one
1193 os << " Capacity items : " << std::max<uint32_t>(items_size_, k_) << std::endl;
1194 os << " Retained items : " << get_num_retained() << std::endl;
1195 if (!is_empty()) {
1196 os << " Min item : " << *min_item_ << std::endl;
1197 os << " Max item : " << *max_item_ << std::endl;
1198 }
1199 os << "### End sketch summary" << std::endl;
1200
1201 if (print_levels) {
1202 os << "### KLL sketch levels:" << std::endl;
1203 os << " index: nominal capacity, actual size" << std::endl;
1204 for (uint8_t i = 0; i < num_levels_; i++) {
1205 os << " " << (unsigned int) i << ": " << kll_helper::level_capacity(k_, num_levels_, i, m_) << ", " << safe_level_size(i) << std::endl;
1206 }
1207 os << "### End sketch levels" << std::endl;
1208 }
1209
1210 if (print_items) {
1211 os << "### KLL sketch data:" << std::endl;
1212 uint8_t level = 0;
1213 while (level < num_levels_) {
1214 const uint32_t from_index = levels_[level];
1215 const uint32_t to_index = levels_[level + 1]; // exclusive
1216 if (from_index < to_index) {
1217 os << " level " << (unsigned int) level << ":" << std::endl;
1218 }
1219 for (uint32_t i = from_index; i < to_index; i++) {
1220 os << " " << items_[i] << std::endl;
1221 }
1222 level++;
1223 }
1224 os << "### End sketch data" << std::endl;
1225 }
1226 return string<A>(os.str().c_str(), allocator_);
1227}
1228
1229template <typename T, typename C, typename A>
1230typename kll_sketch<T, C, A>::const_iterator kll_sketch<T, C, A>::begin() const {
1231 return kll_sketch<T, C, A>::const_iterator(items_, levels_.data(), num_levels_);
1232}
1233
1234template <typename T, typename C, typename A>
1235typename kll_sketch<T, C, A>::const_iterator kll_sketch<T, C, A>::end() const {
1236 return kll_sketch<T, C, A>::const_iterator(nullptr, levels_.data(), num_levels_);
1237}
1238
1239template<typename T, typename C, typename A>
1240class kll_sketch<T, C, A>::items_deleter {
1241 public:
1242 items_deleter(uint32_t start, uint32_t num, const A& allocator):
1243 allocator_(allocator), start_(start), num_(num) {}
1244 void operator() (T* ptr) {
1245 if (ptr != nullptr) {
1246 for (uint32_t i = start_; i < num_; ++i) ptr[i].~T();
1247 allocator_.deallocate(ptr, num_);
1248 }
1249 }
1250 private:
1251 A allocator_;
1252 uint32_t start_;
1253 uint32_t num_;
1254};
1255
1256template<typename T, typename C, typename A>
1257void kll_sketch<T, C, A>::setup_sorted_view() const {
1258 if (sorted_view_ == nullptr) {
1259 using AllocSortedView = typename std::allocator_traits<A>::template rebind_alloc<quantiles_sorted_view<T, C, A>>;
1260 sorted_view_ = new (AllocSortedView(allocator_).allocate(1)) quantiles_sorted_view<T, C, A>(get_sorted_view());
1261 }
1262}
1263
1264template<typename T, typename C, typename A>
1265void kll_sketch<T, C, A>::reset_sorted_view() {
1266 if (sorted_view_ != nullptr) {
1267 sorted_view_->~quantiles_sorted_view();
1268 using AllocSortedView = typename std::allocator_traits<A>::template rebind_alloc<quantiles_sorted_view<T, C, A>>;
1269 AllocSortedView(allocator_).deallocate(sorted_view_, 1);
1270 sorted_view_ = nullptr;
1271 }
1272}
1273
1274// kll_sketch::const_iterator implementation
1275
1276template<typename T, typename C, typename A>
1277kll_sketch<T, C, A>::const_iterator::const_iterator(const T* items, const uint32_t* levels, const uint8_t num_levels):
1278items(items), levels(levels), num_levels(num_levels), index(items == nullptr ? levels[num_levels] : levels[0]), level(items == nullptr ? num_levels : 0), weight(1)
1279{
1280 // start at the first non-empty level: level zero can be empty after a merge
1281 while (level < num_levels && levels[level] == levels[level + 1]) {
1282 ++level;
1283 weight *= 2;
1284 }
1285}
1286
1287template<typename T, typename C, typename A>
1288typename kll_sketch<T, C, A>::const_iterator& kll_sketch<T, C, A>::const_iterator::operator++() {
1289 ++index;
1290 if (index == levels[level + 1]) { // go to the next non-empty level
1291 do {
1292 ++level;
1293 weight *= 2;
1294 } while (level < num_levels && levels[level] == levels[level + 1]);
1295 }
1296 return *this;
1297}
1298
1299template<typename T, typename C, typename A>
1300typename kll_sketch<T, C, A>::const_iterator& kll_sketch<T, C, A>::const_iterator::operator++(int) {
1301 const_iterator tmp(*this);
1302 operator++();
1303 return tmp;
1304}
1305
1306template<typename T, typename C, typename A>
1307bool kll_sketch<T, C, A>::const_iterator::operator==(const const_iterator& other) const {
1308 return index == other.index;
1309}
1310
1311template<typename T, typename C, typename A>
1312bool kll_sketch<T, C, A>::const_iterator::operator!=(const const_iterator& other) const {
1313 return !operator==(other);
1314}
1315
1316template<typename T, typename C, typename A>
1317auto kll_sketch<T, C, A>::const_iterator::operator*() const -> reference {
1318 return value_type(items[index], weight);
1319}
1320
1321template<typename T, typename C, typename A>
1322auto kll_sketch<T, C, A>::const_iterator::operator->() const -> pointer {
1323 return **this;
1324}
1325
1326} /* namespace datasketches */
1327
1328#endif
Implementation of a very compact quantiles sketch with lazy compaction scheme and nearly optimal accu...
Definition kll_sketch.hpp:182
void reserve()
Allocates storage for k items now, rather than on the first update or merge, or as the buffer grows.
Definition kll_sketch_impl.hpp:295
C get_comparator() const
Returns an instance of the comparator for this sketch.
Definition kll_sketch_impl.hpp:415
quantiles_sorted_view< T, C, A > get_sorted_view() const
Gets the sorted view of this sketch.
Definition kll_sketch_impl.hpp:944
kll_sketch & operator=(const kll_sketch &other)
Copy assignment.
Definition kll_sketch_impl.hpp:103
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 kll_sketch_impl.hpp:439
const_iterator begin() const
Iterator pointing to the first item in the sketch.
Definition kll_sketch_impl.hpp:1230
uint32_t get_num_retained() const
Returns the number of retained items (samples) in the sketch.
Definition kll_sketch_impl.hpp:393
static kll_sketch deserialize(std::istream &is, const SerDe &sd=SerDe(), const C &comparator=C(), const A &allocator=A())
This method deserializes a sketch from a given stream.
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 kll_sketch_impl.hpp:432
void merge(FwdSk &&other)
Merges another sketch into this one.
Definition kll_sketch_impl.hpp:351
T get_max_item() const
Returns the max item of the stream.
Definition kll_sketch_impl.hpp:409
const_iterator end() const
Iterator pointing to the past-the-end item in the sketch.
Definition kll_sketch_impl.hpp:1235
void update(FwdT &&item)
Updates this sketch with the given data item.
Definition kll_sketch_impl.hpp:191
void serialize(std::ostream &os, const SerDe &sd=SerDe()) const
This method serializes the sketch into a given stream in a binary form.
Definition kll_sketch_impl.hpp:511
string< A > to_string(bool print_levels=false, bool print_items=false) const
Prints a summary of the sketch.
Definition kll_sketch_impl.hpp:1177
uint16_t get_k() const
Returns configured parameter k.
Definition kll_sketch_impl.hpp:383
bool is_empty() const
Returns true if this sketch is empty.
Definition kll_sketch_impl.hpp:378
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 kll_sketch_impl.hpp:425
A get_allocator() const
Returns an instance of the allocator for this sketch.
Definition kll_sketch_impl.hpp:420
T get_min_item() const
Returns the min item of the stream.
Definition kll_sketch_impl.hpp:403
typename quantiles_sorted_view< T, C, A >::quantile_return_type quantile_return_type
Quantile return type.
Definition kll_sketch.hpp:194
quantile_return_type get_quantile(double rank, bool inclusive=true) const
Returns an item from the sketch that is the best approximation to an item from the original stream wi...
Definition kll_sketch_impl.hpp:446
size_t get_serialized_size_bytes(const SerDe &sd=SerDe()) const
Computes size needed to serialize the current state of the sketch.
Definition kll_sketch_impl.hpp:464
static size_t get_max_serialized_size_bytes(uint16_t k, uint64_t n)
Returns upper bound on the serialized size of a sketch given a parameter k and stream length.
Definition kll_sketch_impl.hpp:492
double get_normalized_rank_error(bool pmf) const
Gets the approximate rank error of this sketch normalized as a fraction between zero and one.
Definition kll_sketch_impl.hpp:457
bool is_estimation_mode() const
Returns true if this sketch is in estimation mode.
Definition kll_sketch_impl.hpp:398
uint64_t get_n() const
Returns the length of the input stream.
Definition kll_sketch_impl.hpp:388
Sorted view for quantiles sketches (REQ, KLL and Quantiles).
Definition quantiles_sorted_view.hpp:40
KLL sketch constants.
Definition kll_sketch.hpp:34
const uint16_t MAX_K
max value of parameter K
Definition kll_sketch.hpp:41
const uint64_t MAX_N
maximum stream length n, the largest signed 64-bit integer, as in datasketches-java
Definition kll_sketch.hpp:45
const uint64_t MAX_WEIGHT
maximum weight of a weighted update, the same as in datasketches-java
Definition kll_sketch.hpp:43
const uint16_t MIN_K
min value of parameter K
Definition kll_sketch.hpp:39
DataSketches namespace.
Definition binomial_bounds.hpp:38