datasketches-cpp
Loading...
Searching...
No Matches
quantiles_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 _QUANTILES_SKETCH_IMPL_HPP_
21#define _QUANTILES_SKETCH_IMPL_HPP_
22
23#include <cmath>
24#include <algorithm>
25#include <stdexcept>
26#include <iomanip>
27#include <sstream>
28#include <type_traits>
29
30#include "count_zeros.hpp"
31#include "conditional_forward.hpp"
32
33namespace datasketches {
34
35template<typename T, typename C, typename A>
36quantiles_sketch<T, C, A>::quantiles_sketch(uint16_t k, const C& comparator, const A& allocator):
37comparator_(comparator),
38allocator_(allocator),
39is_base_buffer_sorted_(true),
40k_(k),
41n_(0),
42bit_pattern_(0),
43base_buffer_(allocator_),
44levels_(allocator_),
45min_item_(),
46max_item_(),
47sorted_view_(nullptr)
48{
49 check_k(k_);
50 base_buffer_.reserve(2 * std::min(quantiles_constants::MIN_K, k));
51}
52
53template<typename T, typename C, typename A>
54quantiles_sketch<T, C, A>::quantiles_sketch(const quantiles_sketch& other):
55comparator_(other.comparator_),
56allocator_(other.allocator_),
57is_base_buffer_sorted_(other.is_base_buffer_sorted_),
58k_(other.k_),
59n_(other.n_),
60bit_pattern_(other.bit_pattern_),
61base_buffer_(other.base_buffer_),
62levels_(other.levels_),
63min_item_(other.min_item_),
64max_item_(other.max_item_),
65sorted_view_(nullptr)
66{
67 for (size_t i = 0; i < levels_.size(); ++i) {
68 if (levels_[i].capacity() != other.levels_[i].capacity()) {
69 levels_[i].reserve(other.levels_[i].capacity());
70 }
71 }
72}
73
74template<typename T, typename C, typename A>
75quantiles_sketch<T, C, A>::quantiles_sketch(quantiles_sketch&& other) noexcept:
76comparator_(other.comparator_),
77allocator_(other.allocator_),
78is_base_buffer_sorted_(other.is_base_buffer_sorted_),
79k_(other.k_),
80n_(other.n_),
81bit_pattern_(other.bit_pattern_),
82base_buffer_(std::move(other.base_buffer_)),
83levels_(std::move(other.levels_)),
84min_item_(std::move(other.min_item_)),
85max_item_(std::move(other.max_item_)),
86sorted_view_(nullptr)
87{}
88
89template<typename T, typename C, typename A>
90quantiles_sketch<T, C, A>& quantiles_sketch<T, C, A>::operator=(const quantiles_sketch& other) {
91 quantiles_sketch<T, C, A> copy(other);
92 std::swap(comparator_, copy.comparator_);
93 std::swap(allocator_, copy.allocator_);
94 std::swap(is_base_buffer_sorted_, copy.is_base_buffer_sorted_);
95 std::swap(k_, copy.k_);
96 std::swap(n_, copy.n_);
97 std::swap(bit_pattern_, copy.bit_pattern_);
98 std::swap(base_buffer_, copy.base_buffer_);
99 std::swap(levels_, copy.levels_);
100 std::swap(min_item_, copy.min_item_);
101 std::swap(max_item_, copy.max_item_);
102 reset_sorted_view();
103 return *this;
104}
105
106template<typename T, typename C, typename A>
107quantiles_sketch<T, C, A>& quantiles_sketch<T, C, A>::operator=(quantiles_sketch&& other) noexcept {
108 std::swap(comparator_, other.comparator_);
109 std::swap(allocator_, other.allocator_);
110 std::swap(is_base_buffer_sorted_, other.is_base_buffer_sorted_);
111 std::swap(k_, other.k_);
112 std::swap(n_, other.n_);
113 std::swap(bit_pattern_, other.bit_pattern_);
114 std::swap(base_buffer_, other.base_buffer_);
115 std::swap(levels_, other.levels_);
116 std::swap(min_item_, other.min_item_);
117 std::swap(max_item_, other.max_item_);
118 reset_sorted_view();
119 return *this;
120}
121
122template<typename T, typename C, typename A>
123quantiles_sketch<T, C, A>::quantiles_sketch(uint16_t k, uint64_t n, uint64_t bit_pattern,
124 Level&& base_buffer, VectorLevels&& levels,
125 optional<T>&& min_item, optional<T>&& max_item,
126 bool is_sorted, const C& comparator, const A& allocator):
127comparator_(comparator),
128allocator_(allocator),
129is_base_buffer_sorted_(is_sorted),
130k_(k),
131n_(n),
132bit_pattern_(bit_pattern),
133base_buffer_(std::move(base_buffer)),
134levels_(std::move(levels)),
135min_item_(std::move(min_item)),
136max_item_(std::move(max_item)),
137sorted_view_(nullptr)
138{
139 uint32_t item_count = static_cast<uint32_t>(base_buffer_.size());
140 for (Level& lvl : levels_) {
141 item_count += static_cast<uint32_t>(lvl.size());
142 }
143 if (item_count != compute_retained_items(k_, n_))
144 throw std::logic_error("Item count does not match value computed from k, n");
145}
146
147template<typename T, typename C, typename A>
148template<typename From, typename FC, typename FA>
149quantiles_sketch<T, C, A>::quantiles_sketch(const quantiles_sketch<From, FC, FA>& other,
150 const C& comparator, const A& allocator):
151comparator_(comparator),
152allocator_(allocator),
153is_base_buffer_sorted_(false),
154k_(other.get_k()),
155n_(other.get_n()),
156bit_pattern_(compute_bit_pattern(other.get_k(), other.get_n())),
157base_buffer_(allocator),
158levels_(allocator),
159min_item_(other.min_item_),
160max_item_(other.max_item_),
161sorted_view_(nullptr)
162{
163 static_assert(std::is_constructible<T, From>::value,
164 "Type converting constructor requires new type to be constructible from existing type");
165
166 base_buffer_.reserve(2 * std::min(quantiles_constants::MIN_K, k_));
167
168 if (!other.is_empty()) {
169 // reserve space in levels
170 const uint8_t num_levels = compute_levels_needed(k_, n_);
171 levels_.reserve(num_levels);
172 for (int i = 0; i < num_levels; ++i) {
173 Level level(allocator);
174 level.reserve(k_);
175 levels_.push_back(std::move(level));
176 }
177
178 // iterate through points, assigning to the correct level as needed
179 for (auto pair : other) {
180 const uint64_t wt = pair.second;
181 if (wt == 1) {
182 base_buffer_.push_back(T(pair.first));
183 // resize where needed as if adding points via update()
184 if (base_buffer_.size() + 1 > base_buffer_.capacity()) {
185 const size_t new_size = std::max(std::min(static_cast<size_t>(2 * k_), 2 * base_buffer_.size()), static_cast<size_t>(1));
186 base_buffer_.reserve(new_size);
187 }
188 }
189 else {
190 const uint8_t idx = count_trailing_zeros_in_u64(pair.second) - 1;
191 levels_[idx].push_back(T(pair.first));
192 }
193 }
194
195 // validate that ordering within each level is preserved
196 // base_buffer_ can be considered unsorted for this purpose
197 for (int i = 0; i < num_levels; ++i) {
198 if (!std::is_sorted(levels_[i].begin(), levels_[i].end(), comparator_)) {
199 throw std::logic_error("Copy construction across types produces invalid sorting");
200 }
201 }
202 }
203}
204
205
206template<typename T, typename C, typename A>
207quantiles_sketch<T, C, A>::~quantiles_sketch() {
208 reset_sorted_view();
209}
210
211template<typename T, typename C, typename A>
212template<typename FwdT>
214 if (!check_update_item(item)) { return; }
215 // compare and copy first, but change nothing until the item has been fully processed,
216 // so that an exception leaves the sketch as it was
217 const bool is_new_min = is_empty() || comparator_(item, *min_item_);
218 const bool is_new_max = is_empty() || comparator_(*max_item_, item);
219 optional<T> new_min;
220 optional<T> new_max;
221 if (is_new_min) new_min.emplace(item);
222 if (is_new_max) new_max.emplace(item);
223 reset_sorted_view();
224 try {
225 insert_base(std::forward<FwdT>(item));
226 } catch (...) {
227 trim_levels();
228 throw;
229 }
230 if (is_new_min) min_item_ = std::move(new_min);
231 if (is_new_max) max_item_ = std::move(new_max);
232}
233
234template<typename T, typename C, typename A>
235template<typename FwdT>
236void quantiles_sketch<T, C, A>::insert_base(FwdT&& item) {
237 // allocate first
238 // if exceed capacity, grow until size 2k -- assumes eager processing
239 if (base_buffer_.size() + 1 > base_buffer_.capacity()) grow_base_buffer();
240 const bool fills_base_buffer = base_buffer_.size() + 1 == 2 * k_;
241 if (fills_base_buffer) grow_levels_if_needed(n_ + 1); // make sure there will be enough levels for the propagation
242
243 base_buffer_.push_back(std::forward<FwdT>(item)); // a failed copy leaves the base buffer as it was
244 if (fills_base_buffer) {
245 process_full_base_buffer(n_ + 1);
246 } else if (base_buffer_.size() > 1) {
247 is_base_buffer_sorted_ = false;
248 }
249 ++n_;
250}
251
252template<typename T, typename C, typename A>
253template<typename FwdSk>
255 if (other.is_empty()) {
256 return; // nothing to do
257 }
258 reset_sorted_view();
259 try {
260 merge_unchecked(std::forward<FwdSk>(other));
261 } catch (...) {
262 trim_levels(); // a failed merge can leave levels added for the items it did not merge
263 throw;
264 }
265}
266
267template<typename T, typename C, typename A>
268template<typename FwdSk>
269void quantiles_sketch<T, C, A>::merge_unchecked(FwdSk&& other) {
270 if (!other.is_estimation_mode()) {
271 // other is exact, stream in regardless of k
272 reserve_for_merge(*this, n_ + other.n_, other.n_); // allocate first, so that a failure changes nothing
273 for (auto& item : other.base_buffer_) {
274 update(conditional_forward<FwdSk>(item));
275 }
276 return;
277 }
278
279 // other has data and is in estimation mode
280 if (is_estimation_mode()) {
281 if (k_ == other.get_k()) {
282 standard_merge(*this, std::forward<FwdSk>(other));
283 } else if (k_ > other.get_k()) {
284 quantiles_sketch sk_copy(std::forward<FwdSk>(other));
285 downsampling_merge(sk_copy, std::move(*this));
286 *this = std::move(sk_copy);
287 } else { // k_ < other.get_k()
288 downsampling_merge(*this, std::forward<FwdSk>(other));
289 }
290 } else {
291 // exact or empty
292 quantiles_sketch sk_copy(std::forward<FwdSk>(other));
293 if (k_ <= sk_copy.get_k()) {
294 if (!is_empty()) {
295 // allocate first, so that no item is moved out of this sketch unless the merge succeeds
296 reserve_for_merge(sk_copy, sk_copy.get_n() + n_, base_buffer_.size());
297 merge_min_max(sk_copy, std::move(*this));
298 for (auto& item : base_buffer_) sk_copy.insert_base(std::move(item));
299 }
300 } else { // k_ > other.get_k()
301 downsampling_merge(sk_copy, std::move(*this));
302 }
303 *this = std::move(sk_copy);
304 }
305}
306
307template<typename T, typename C, typename A>
308template<typename SerDe>
309void quantiles_sketch<T, C, A>::serialize(std::ostream& os, const SerDe& serde) const {
310 const uint8_t preamble_longs = is_empty() ? PREAMBLE_LONGS_SHORT : PREAMBLE_LONGS_FULL;
311 write(os, preamble_longs);
312 const uint8_t ser_ver = SERIAL_VERSION;
313 write(os, ser_ver);
314 const uint8_t family = FAMILY;
315 write(os, family);
316
317 // side-effect: sort base buffer since always compact
318 std::sort(const_cast<Level&>(base_buffer_).begin(), const_cast<Level&>(base_buffer_).end(), comparator_);
319 const_cast<quantiles_sketch*>(this)->is_base_buffer_sorted_ = true;
320
321 // empty, ordered, compact are valid flags
322 const uint8_t flags_byte(
323 (is_empty() ? 1 << flags::IS_EMPTY : 0)
324 | (1 << flags::IS_SORTED) // always sorted as side effect noted above
325 | (1 << flags::IS_COMPACT) // always compact -- could be optional for numeric types?
326 );
327 write(os, flags_byte);
328 write(os, k_);
329 const uint16_t unused = 0;
330 write(os, unused);
331
332 if (!is_empty()) {
333 write(os, n_);
334
335 // min and max
336 serde.serialize(os, &*min_item_, 1);
337 serde.serialize(os, &*max_item_, 1);
338
339 // base buffer items
340 serde.serialize(os, base_buffer_.data(), static_cast<unsigned>(base_buffer_.size()));
341
342 // levels, only when data is present
343 for (Level lvl : levels_) {
344 if (lvl.size() > 0)
345 serde.serialize(os, lvl.data(), static_cast<unsigned>(lvl.size()));
346 }
347 }
348}
349
350template<typename T, typename C, typename A>
351template<typename SerDe>
352auto quantiles_sketch<T, C, A>::serialize(unsigned header_size_bytes, const SerDe& serde) const -> vector_bytes {
353 const size_t size = get_serialized_size_bytes(serde) + header_size_bytes;
354 vector_bytes bytes(size, 0, allocator_);
355 uint8_t* ptr = bytes.data() + header_size_bytes;
356 const uint8_t* end_ptr = bytes.data() + size;
357
358 const uint8_t preamble_longs = is_empty() ? PREAMBLE_LONGS_SHORT : PREAMBLE_LONGS_FULL;
359 ptr += copy_to_mem(preamble_longs, ptr);
360 const uint8_t ser_ver = SERIAL_VERSION;
361 ptr += copy_to_mem(ser_ver, ptr);
362 const uint8_t family = FAMILY;
363 ptr += copy_to_mem(family, ptr);
364
365 // side-effect: sort base buffer since always compact
366 std::sort(const_cast<Level&>(base_buffer_).begin(), const_cast<Level&>(base_buffer_).end(), comparator_);
367 const_cast<quantiles_sketch*>(this)->is_base_buffer_sorted_ = true;
368
369 // empty, ordered, compact are valid flags
370 const uint8_t flags_byte(
371 (is_empty() ? 1 << flags::IS_EMPTY : 0)
372 | (1 << flags::IS_SORTED) // always sorted as side effect noted above
373 | (1 << flags::IS_COMPACT) // always compact
374 );
375 ptr += copy_to_mem(flags_byte, ptr);
376 ptr += copy_to_mem(k_, ptr);
377 ptr += sizeof(uint16_t); // 2 unused bytes
378
379 if (!is_empty()) {
380
381 ptr += copy_to_mem(n_, ptr);
382
383 // min and max
384 ptr += serde.serialize(ptr, end_ptr - ptr, &*min_item_, 1);
385 ptr += serde.serialize(ptr, end_ptr - ptr, &*max_item_, 1);
386
387 // base buffer items
388 if (base_buffer_.size() > 0)
389 ptr += serde.serialize(ptr, end_ptr - ptr, base_buffer_.data(), static_cast<unsigned>(base_buffer_.size()));
390
391 // levels, only when data is present
392 for (Level lvl : levels_) {
393 if (lvl.size() > 0)
394 ptr += serde.serialize(ptr, end_ptr - ptr, lvl.data(), static_cast<unsigned>(lvl.size()));
395 }
396 }
397
398 return bytes;
399}
400
401template<typename T, typename C, typename A>
402template<typename SerDe>
403auto quantiles_sketch<T, C, A>::deserialize(std::istream &is, const SerDe& serde,
404 const C& comparator, const A &allocator) -> quantiles_sketch {
405 const auto preamble_longs = read<uint8_t>(is);
406 const auto serial_version = read<uint8_t>(is);
407 const auto family_id = read<uint8_t>(is);
408 const auto flags_byte = read<uint8_t>(is);
409 const auto k = read<uint16_t>(is);
410 read<uint16_t>(is); // unused
411
412 check_k(k);
413 check_serial_version(serial_version); // a little redundant with the header check
414 check_family_id(family_id);
415 check_header_validity(preamble_longs, flags_byte, serial_version);
416
417 if (!is.good()) throw std::runtime_error("error reading from std::istream");
418 const bool is_empty = (flags_byte & (1 << flags::IS_EMPTY)) > 0;
419 if (is_empty) {
420 return quantiles_sketch(k, comparator, allocator);
421 }
422
423 const auto items_seen = read<uint64_t>(is);
424
425 const bool is_compact = (serial_version == 2) | ((flags_byte & (1 << flags::IS_COMPACT)) > 0);
426 const bool is_sorted = (flags_byte & (1 << flags::IS_SORTED)) > 0;
427
428 optional<T> min_item;
429 optional<T> max_item;
430
431 // Space to deserialize min and max.
432 // serde::deserialize expects allocated but not initialized storage.
433 typename std::aligned_storage<sizeof(T), alignof(T)>::type tmp_storage;
434 T* tmp = reinterpret_cast<T*>(&tmp_storage);
435
436 serde.deserialize(is, tmp, 1);
437 // serde call did not throw, repackage and cleanup
438 min_item.emplace(std::move(*tmp));
439 tmp->~T();
440 serde.deserialize(is, tmp, 1);
441 // serde call did not throw, repackage and cleanup
442 max_item.emplace(std::move(*tmp));
443 tmp->~T();
444
445 if (serial_version == 1) {
446 read<uint64_t>(is); // no longer used
447 }
448
449 // allocate buffers as needed
450 const uint8_t levels_needed = compute_levels_needed(k, items_seen);
451 const uint64_t bit_pattern = compute_bit_pattern(k, items_seen);
452
453 // Java provides a compact storage layout for a sketch of primitive doubles. The C++ version
454 // does not currently operate sketches in compact mode, but will only serialize as compact
455 // to avoid complications around serialization of empty values for generic type T. We also need
456 // to be able to ingest either serialized format from Java.
457
458 // load base buffer
459 const uint32_t bb_items = compute_base_buffer_items(k, items_seen);
460 uint32_t items_to_read = (levels_needed == 0 || is_compact) ? bb_items : 2 * k;
461 Level base_buffer = deserialize_array(is, bb_items, 2 * k, serde, allocator);
462 if (items_to_read > bb_items) { // either equal or greater, never read fewer items
463 // read remaining items, but don't store them
464 deserialize_array(is, items_to_read - bb_items, items_to_read - bb_items, serde, allocator);
465 }
466
467 // populate vector of Levels directly
468 VectorLevels levels(allocator);
469 levels.reserve(levels_needed);
470 if (levels_needed > 0) {
471 uint64_t working_pattern = bit_pattern;
472 for (size_t i = 0; i < levels_needed; ++i, working_pattern >>= 1) {
473 if ((working_pattern & 0x01) == 1) {
474 Level level = deserialize_array(is, k, k, serde, allocator);
475 levels.push_back(std::move(level));
476 } else {
477 Level level(allocator);
478 level.reserve(k);
479 levels.push_back(std::move(level));
480 }
481 }
482 }
483
484 return quantiles_sketch(k, items_seen, bit_pattern,
485 std::move(base_buffer), std::move(levels), std::move(min_item), std::move(max_item), is_sorted,
486 comparator, allocator);
487}
488
489template<typename T, typename C, typename A>
490template<typename SerDe>
491auto quantiles_sketch<T, C, A>::deserialize_array(std::istream& is, uint32_t num_items, uint32_t capacity, const SerDe& serde, const A& allocator) -> Level {
492 A alloc(allocator);
493 std::unique_ptr<T, items_deleter> items(alloc.allocate(num_items), items_deleter(allocator, false, num_items));
494 serde.deserialize(is, items.get(), num_items);
495 // serde did not throw, enable destructors
496 items.get_deleter().set_destroy(true);
497 if (!is.good()) throw std::runtime_error("error reading from std::istream");
498
499 // successfully read, now put into a Level
500 Level level(allocator);
501 level.reserve(capacity);
502 level.insert(level.begin(),
503 std::make_move_iterator(items.get()),
504 std::make_move_iterator(items.get() + num_items));
505 return level;
506}
507
508template<typename T, typename C, typename A>
509template<typename SerDe>
510auto quantiles_sketch<T, C, A>::deserialize(const void* bytes, size_t size, const SerDe& serde,
511 const C& comparator, const A &allocator) -> quantiles_sketch {
512 ensure_minimum_memory(size, 8);
513 const char* ptr = static_cast<const char*>(bytes);
514 const char* end_ptr = static_cast<const char*>(bytes) + size;
515
516 uint8_t preamble_longs;
517 ptr += copy_from_mem(ptr, preamble_longs);
518 uint8_t serial_version;
519 ptr += copy_from_mem(ptr, serial_version);
520 uint8_t family_id;
521 ptr += copy_from_mem(ptr, family_id);
522 uint8_t flags_byte;
523 ptr += copy_from_mem(ptr, flags_byte);
524 uint16_t k;
525 ptr += copy_from_mem(ptr, k);
526 uint16_t unused;
527 ptr += copy_from_mem(ptr, unused);
528
529 check_k(k);
530 check_serial_version(serial_version); // a little redundant with the header check
531 check_family_id(family_id);
532 check_header_validity(preamble_longs, flags_byte, serial_version);
533
534 const bool is_empty = (flags_byte & (1 << flags::IS_EMPTY)) > 0;
535 if (is_empty) {
536 return quantiles_sketch(k, comparator, allocator);
537 }
538
539 ensure_minimum_memory(size, 16);
540 uint64_t items_seen;
541 ptr += copy_from_mem(ptr, items_seen);
542
543 const bool is_compact = (serial_version == 2) | ((flags_byte & (1 << flags::IS_COMPACT)) > 0);
544 const bool is_sorted = (flags_byte & (1 << flags::IS_SORTED)) > 0;
545
546 optional<T> min_item;
547 optional<T> max_item;
548
549 // Space to deserialize min and max.
550 // serde::deserialize expects allocated but not initialized storage.
551 typename std::aligned_storage<sizeof(T), alignof(T)>::type tmp_storage;
552 T* tmp = reinterpret_cast<T*>(&tmp_storage);
553
554 ptr += serde.deserialize(ptr, end_ptr - ptr, tmp, 1);
555 // serde call did not throw, repackage and cleanup
556 min_item.emplace(std::move(*tmp));
557 tmp->~T();
558 ptr += serde.deserialize(ptr, end_ptr - ptr, tmp, 1);
559 // serde call did not throw, repackage and cleanup
560 max_item.emplace(std::move(*tmp));
561 tmp->~T();
562
563 if (serial_version == 1) {
564 uint64_t unused_long;
565 ensure_minimum_memory(end_ptr - ptr, sizeof(unused_long));
566 ptr += copy_from_mem(ptr, unused_long); // no longer used
567 }
568
569 // allocate buffers as needed
570 const uint8_t levels_needed = compute_levels_needed(k, items_seen);
571 const uint64_t bit_pattern = compute_bit_pattern(k, items_seen);
572
573 // Java provides a compact storage layout for a sketch of primitive doubles. The C++ version
574 // does not currently operate sketches in compact mode, but will only serialize as compact
575 // to avoid complications around serialization of empty values for generic type T. We also need
576 // to be able to ingest either serialized format from Java.
577
578 // load base buffer
579 const uint32_t bb_items = compute_base_buffer_items(k, items_seen);
580 uint32_t items_to_read = (levels_needed == 0 || is_compact) ? bb_items : 2 * k;
581 auto base_buffer_pair = deserialize_array(ptr, end_ptr - ptr, bb_items, 2 * k, serde, allocator);
582 ptr += base_buffer_pair.second;
583 if (items_to_read > bb_items) { // either equal or greater, never read fewer items
584 // read remaining items, only use to advance the pointer
585 auto extras = deserialize_array(ptr, end_ptr - ptr, items_to_read - bb_items, items_to_read - bb_items, serde, allocator);
586 ptr += extras.second;
587 }
588
589 // populate vector of Levels directly
590 VectorLevels levels(allocator);
591 levels.reserve(levels_needed);
592 if (levels_needed > 0) {
593 uint64_t working_pattern = bit_pattern;
594 for (size_t i = 0; i < levels_needed; ++i, working_pattern >>= 1) {
595
596 if ((working_pattern & 0x01) == 1) {
597 auto pair = deserialize_array(ptr, end_ptr - ptr, k, k, serde, allocator);
598 ptr += pair.second;
599 levels.push_back(std::move(pair.first));
600 } else {
601 Level level(allocator);
602 level.reserve(k);
603 levels.push_back(std::move(level));
604 }
605 }
606 }
607
608 return quantiles_sketch(k, items_seen, bit_pattern,
609 std::move(base_buffer_pair.first), std::move(levels), std::move(min_item), std::move(max_item), is_sorted,
610 comparator, allocator);
611}
612
613template<typename T, typename C, typename A>
614template<typename SerDe>
615auto 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)
616 -> std::pair<Level, size_t> {
617 const char* ptr = static_cast<const char*>(bytes);
618 const char* end_ptr = static_cast<const char*>(bytes) + size;
619 A alloc(allocator);
620 std::unique_ptr<T, items_deleter> items(alloc.allocate(num_items), items_deleter(allocator, false, num_items));
621 ptr += serde.deserialize(ptr, end_ptr - ptr, items.get(), num_items);
622 // serde did not throw, enable destructors
623 items.get_deleter().set_destroy(true);
624
625 // successfully read, now put into a Level
626 Level level(allocator);
627 level.reserve(capacity);
628 level.insert(level.begin(),
629 std::make_move_iterator(items.get()),
630 std::make_move_iterator(items.get() + num_items));
631
632 return std::pair<Level, size_t>(std::move(level), ptr - static_cast<const char*>(bytes));
633}
634
635template<typename T, typename C, typename A>
636string<A> quantiles_sketch<T, C, A>::to_string(bool print_levels, bool print_items) const {
637 // Using a temporary stream for implementation here does not comply with AllocatorAwareContainer requirements.
638 // The stream does not support passing an allocator instance, and alternatives are complicated.
639 std::ostringstream os;
640 os << "### Quantiles Sketch summary:" << std::endl;
641 os << " K : " << k_ << std::endl;
642 os << " N : " << n_ << std::endl;
643 os << " Epsilon : " << std::setprecision(3) << get_normalized_rank_error(false) * 100 << "%" << std::endl;
644 os << " Epsilon PMF : " << get_normalized_rank_error(true) * 100 << "%" << std::endl;
645 os << " Empty : " << (is_empty() ? "true" : "false") << std::endl;
646 os << " Estimation mode: " << (is_estimation_mode() ? "true" : "false") << std::endl;
647 os << " Levels (w/o BB): " << levels_.size() << std::endl;
648 os << " Used Levels : " << count_valid_levels(bit_pattern_) << std::endl;
649 os << " Retained items : " << get_num_retained() << std::endl;
650 if (!is_empty()) {
651 os << " Min item : " << *min_item_ << std::endl;
652 os << " Max item : " << *max_item_ << std::endl;
653 }
654 os << "### End sketch summary" << std::endl;
655
656 if (print_levels) {
657 os << "### Quantiles Sketch levels:" << std::endl;
658 os << " index: items in use" << std::endl;
659 os << " BB: " << base_buffer_.size() << std::endl;
660 for (uint8_t i = 0; i < levels_.size(); i++) {
661 os << " " << static_cast<unsigned int>(i) << ": " << levels_[i].size() << std::endl;
662 }
663 os << "### End sketch levels" << std::endl;
664 }
665
666 if (print_items) {
667 os << "### Quantiles Sketch data:" << std::endl;
668 uint8_t level = 0;
669 os << " BB:" << std::endl;
670 for (const T& item : base_buffer_) {
671 os << " " << item << std::endl;
672 }
673 for (uint8_t i = 0; i < levels_.size(); ++i) {
674 os << " level " << static_cast<unsigned int>(level) << ":" << std::endl;
675 for (const T& item : levels_[i]) {
676 os << " " << item << std::endl;
677 }
678 }
679 os << "### End sketch data" << std::endl;
680 }
681 return string<A>(os.str().c_str(), allocator_);
682}
683
684template<typename T, typename C, typename A>
686 return k_;
687}
688
689template<typename T, typename C, typename A>
691 return n_;
692}
693
694template<typename T, typename C, typename A>
696 return n_ == 0;
697}
698
699template<typename T, typename C, typename A>
701 return bit_pattern_ != 0;
702}
703
704template<typename T, typename C, typename A>
706 return compute_retained_items(k_, n_);
707}
708
709template<typename T, typename C, typename A>
711 if (is_empty()) throw std::runtime_error("operation is undefined for an empty sketch");
712 return *min_item_;
713}
714
715template<typename T, typename C, typename A>
717 if (is_empty()) throw std::runtime_error("operation is undefined for an empty sketch");
718 return *max_item_;
719}
720
721template<typename T, typename C, typename A>
723 return comparator_;
724}
725
726template<typename T, typename C, typename A>
728 return allocator_;
729}
730
731// implementation for fixed-size arithmetic types (integral and floating point)
732template<typename T, typename C, typename A>
733template<typename SerDe, typename TT, typename std::enable_if<std::is_arithmetic<TT>::value, int>::type>
735 if (is_empty()) { return EMPTY_SIZE_BYTES; }
736 return DATA_START + ((get_num_retained() + 2) * sizeof(TT));
737}
738
739// implementation for all other types
740template<typename T, typename C, typename A>
741template<typename SerDe, typename TT, typename std::enable_if<!std::is_arithmetic<TT>::value, int>::type>
743 if (is_empty()) { return EMPTY_SIZE_BYTES; }
744 size_t size = DATA_START;
745 size += serde.size_of_item(*min_item_);
746 size += serde.size_of_item(*max_item_);
747 for (auto it: *this) size += serde.size_of_item(it.first);
748 return size;
749}
750
751template<typename T, typename C, typename A>
753 return get_normalized_rank_error(k_, is_pmf);
754}
755
756template<typename T, typename C, typename A>
758 return is_pmf
759 ? 1.854 / std::pow(k, 0.9657)
760 : 1.576 / std::pow(k, 0.9726);
761}
762
763template<typename T, typename C, typename A>
765 // allow side-effect of sorting the base buffer
766 if (!is_base_buffer_sorted_) {
767 std::sort(const_cast<Level&>(base_buffer_).begin(), const_cast<Level&>(base_buffer_).end(), comparator_);
768 const_cast<quantiles_sketch*>(this)->is_base_buffer_sorted_ = true;
769 }
770 quantiles_sorted_view<T, C, A> view(get_num_retained(), comparator_, allocator_);
771
772 uint64_t weight = 1;
773 view.add(base_buffer_.begin(), base_buffer_.end(), weight);
774 for (const auto& level: levels_) {
775 weight <<= 1;
776 if (level.empty()) { continue; }
777 view.add(level.begin(), level.end(), weight);
778 }
779
780 view.convert_to_cummulative();
781 return view;
782}
783
784template<typename T, typename C, typename A>
785auto quantiles_sketch<T, C, A>::get_quantile(double rank, bool inclusive) const -> quantile_return_type {
786 if (is_empty()) throw std::runtime_error("operation is undefined for an empty sketch");
787 if ((rank < 0.0) || (rank > 1.0)) {
788 throw std::invalid_argument("Normalized rank cannot be less than 0 or greater than 1");
789 }
790 // possible side-effect: sorting base buffer
791 setup_sorted_view();
792 return sorted_view_->get_quantile(rank, inclusive);
793}
794
795template<typename T, typename C, typename A>
796double quantiles_sketch<T, C, A>::get_rank(const T& item, bool inclusive) const {
797 if (is_empty()) throw std::runtime_error("operation is undefined for an empty sketch");
798 setup_sorted_view();
799 return sorted_view_->get_rank(item, inclusive);
800}
801
802template<typename T, typename C, typename A>
803auto quantiles_sketch<T, C, A>::get_PMF(const T* split_points, uint32_t size, bool inclusive) const -> vector_double {
804 if (is_empty()) throw std::runtime_error("operation is undefined for an empty sketch");
805 setup_sorted_view();
806 return sorted_view_->get_PMF(split_points, size, inclusive);
807}
808
809template<typename T, typename C, typename A>
810auto quantiles_sketch<T, C, A>::get_CDF(const T* split_points, uint32_t size, bool inclusive) const -> vector_double {
811 if (is_empty()) throw std::runtime_error("operation is undefined for an empty sketch");
812 setup_sorted_view();
813 return sorted_view_->get_CDF(split_points, size, inclusive);
814}
815
816template<typename T, typename C, typename A>
817uint32_t quantiles_sketch<T, C, A>::compute_retained_items(uint16_t k, uint64_t n) {
818 const uint32_t bb_count = compute_base_buffer_items(k, n);
819 const uint64_t bit_pattern = compute_bit_pattern(k, n);
820 const uint32_t valid_levels = count_valid_levels(bit_pattern);
821 return bb_count + (k * valid_levels);
822}
823
824template<typename T, typename C, typename A>
825uint32_t quantiles_sketch<T, C, A>::compute_base_buffer_items(uint16_t k, uint64_t n) {
826 return n % (static_cast<uint64_t>(2) * k);
827}
828
829template<typename T, typename C, typename A>
830uint64_t quantiles_sketch<T, C, A>::compute_bit_pattern(uint16_t k, uint64_t n) {
831 return n / (static_cast<uint64_t>(2) * k);
832}
833
834template<typename T, typename C, typename A>
835uint32_t quantiles_sketch<T, C, A>::count_valid_levels(uint64_t bit_pattern) {
836 uint32_t count = 0;
837 for (; bit_pattern > 0; ++count) bit_pattern &= bit_pattern - 1;
838 return count;
839}
840
841template<typename T, typename C, typename A>
842uint8_t quantiles_sketch<T, C, A>::compute_levels_needed(uint16_t k, uint64_t n) {
843 return static_cast<uint8_t>(64U) - count_leading_zeros_in_u64(n / (2 * k));
844}
845
846template<typename T, typename C, typename A>
847void quantiles_sketch<T, C, A>::check_k(uint16_t k) {
848 if (k < quantiles_constants::MIN_K || k > quantiles_constants::MAX_K || (k & (k - 1)) != 0) {
849 throw std::invalid_argument("k must be a power of 2 that is >= "
850 + std::to_string(quantiles_constants::MIN_K) + " and <= "
851 + std::to_string(quantiles_constants::MAX_K) + ". Found: " + std::to_string(k));
852 }
853}
854
855template<typename T, typename C, typename A>
856void quantiles_sketch<T, C, A>::check_serial_version(uint8_t serial_version) {
857 if (serial_version == SERIAL_VERSION || serial_version == SERIAL_VERSION_1 || serial_version == SERIAL_VERSION_2)
858 return;
859 else
860 throw std::invalid_argument("Possible corruption. Unrecognized serialization version: " + std::to_string(serial_version));
861}
862
863template<typename T, typename C, typename A>
864void quantiles_sketch<T, C, A>::check_family_id(uint8_t family_id) {
865 if (family_id == FAMILY)
866 return;
867 else
868 throw std::invalid_argument("Possible corruption. Family id does not indicate quantiles sketch: " + std::to_string(family_id));
869}
870
871template<typename T, typename C, typename A>
872void quantiles_sketch<T, C, A>::check_header_validity(uint8_t preamble_longs, uint8_t flags_byte, uint8_t serial_version) {
873 const bool empty = (flags_byte & (1 << flags::IS_EMPTY)) > 0;
874 const bool compact = (flags_byte & (1 << flags::IS_COMPACT)) > 0;
875
876 const uint8_t sw = (compact ? 1 : 0) + (2 * (empty ? 1 : 0))
877 + (4 * (serial_version & 0xF)) + (32 * (preamble_longs & 0x3F));
878 bool valid = true;
879
880 switch (sw) { // exhaustive list and description of all valid cases
881 case 38 : break;
882 case 164 : break;
883 case 42 : break;
884 case 72 : break;
885 case 47 : break; // compact, empty, serVer = 3, preLongs = 1;
886 case 46 : break;
887 case 79 : break; // compact, empty, serVer = 3, preLongs = 2;
888 case 78 : break;
889 case 77 : break; // compact, !empty, serVer = 3, preLongs = 2;
890 case 76 : break;
891 default : //all other case values are invalid
892 valid = false;
893 }
894
895 if (!valid) {
896 std::ostringstream os;
897 os << "Possible sketch corruption. Inconsistent state: "
898 << "preamble_longs = " << preamble_longs
899 << ", empty = " << (empty ? "true" : "false")
900 << ", serialization_version = " << serial_version
901 << ", compact = " << (compact ? "true" : "false");
902 throw std::invalid_argument(os.str());
903 }
904}
905
906template <typename T, typename C, typename A>
907typename quantiles_sketch<T, C, A>::const_iterator quantiles_sketch<T, C, A>::begin() const {
908 return quantiles_sketch<T, C, A>::const_iterator(base_buffer_, levels_, k_, n_, false);
909}
910
911template <typename T, typename C, typename A>
912typename quantiles_sketch<T, C, A>::const_iterator quantiles_sketch<T, C, A>::end() const {
913 return quantiles_sketch<T, C, A>::const_iterator(base_buffer_, levels_, k_, n_, true);
914}
915
916template<typename T, typename C, typename A>
917void quantiles_sketch<T, C, A>::grow_base_buffer() {
918 const size_t new_size = std::max(std::min(static_cast<size_t>(2 * k_), 2 * base_buffer_.size()), static_cast<size_t>(1));
919 base_buffer_.reserve(new_size);
920}
921
922template<typename T, typename C, typename A>
923void quantiles_sketch<T, C, A>::process_full_base_buffer(uint64_t new_n) {
924 // the levels were grown by the caller: from here on, only moves and comparisons
925 std::sort(base_buffer_.begin(), base_buffer_.end(), comparator_);
926 in_place_propagate_carry(0,
927 levels_[0], // unused here, but 0 is guaranteed to exist
928 base_buffer_,
929 true, *this);
930 base_buffer_.clear();
931 is_base_buffer_sorted_ = true;
932 if (new_n / (2 * k_) != bit_pattern_) {
933 throw std::logic_error("Internal error: n / 2k (" + std::to_string(new_n / (2 * k_))
934 + " != bit_pattern " + std::to_string(bit_pattern_));
935 }
936}
937
938template<typename T, typename C, typename A>
939bool quantiles_sketch<T, C, A>::grow_levels_if_needed(uint64_t n) {
940 const uint8_t levels_needed = compute_levels_needed(k_, n);
941 const bool grow = levels_needed > levels_.size(); // levels_needed == 0 is possible during merges
942 if (grow) {
943 levels_.reserve(levels_needed);
944 while (levels_.size() < levels_needed) {
945 Level empty_level(allocator_);
946 empty_level.reserve(k_);
947 levels_.push_back(std::move(empty_level));
948 }
949 }
950 // Growing levels_ copies the levels instead of moving them if moving a level can throw,
951 // as it can with some allocators, and a copy of an empty level has no capacity.
952 // Every level needs capacity k, since zip_buffer() fills a level without allocating.
953 // This also completes a previous call that failed here.
954 for (auto& level : levels_) {
955 if (level.capacity() < k_) level.reserve(k_);
956 }
957 return grow;
958}
959
960template<typename T, typename C, typename A>
961void quantiles_sketch<T, C, A>::trim_levels() {
962 const uint8_t levels_needed = compute_levels_needed(k_, n_);
963 while (levels_.size() > levels_needed) levels_.pop_back();
964}
965
966template<typename T, typename C, typename A>
967void quantiles_sketch<T, C, A>::reserve_for_merge(quantiles_sketch& tgt, uint64_t new_n, uint64_t num_base_items) {
968 // the base buffer grows only as far as the merge needs; a full base buffer has capacity 2k
969 const uint64_t base_capacity = std::min<uint64_t>(2 * tgt.k_, tgt.base_buffer_.size() + num_base_items);
970 if (tgt.base_buffer_.capacity() < base_capacity) tgt.base_buffer_.reserve(static_cast<size_t>(base_capacity));
971 tgt.grow_levels_if_needed(new_n);
972}
973
974template<typename T, typename C, typename A>
975template<typename FwdSk>
976void quantiles_sketch<T, C, A>::merge_min_max(quantiles_sketch& tgt, FwdSk&& src) {
977 // can't just check is_empty() since min and max might not have been set if
978 // there were no base buffer items added via update()
979 const bool is_new_min = !tgt.min_item_ || tgt.comparator_(*src.min_item_, *tgt.min_item_);
980 const bool is_new_max = !tgt.max_item_ || tgt.comparator_(*tgt.max_item_, *src.max_item_);
981 // copy first, so that a failed copy leaves tgt as it was
982 optional<T> new_min;
983 optional<T> new_max;
984 if (is_new_min) new_min.emplace(conditional_forward<FwdSk>(*src.min_item_));
985 if (is_new_max) new_max.emplace(conditional_forward<FwdSk>(*src.max_item_));
986 if (is_new_min) tgt.min_item_ = std::move(new_min);
987 if (is_new_max) tgt.max_item_ = std::move(new_max);
988}
989
990template<typename T, typename C, typename A>
991template<typename FwdV>
992void quantiles_sketch<T, C, A>::in_place_propagate_carry(uint8_t starting_level,
993 FwdV&& buf_size_k, Level& buf_size_2k,
994 bool apply_as_update,
995 quantiles_sketch& sketch) {
996 const uint64_t bit_pattern = sketch.bit_pattern_;
997 const int k = sketch.k_;
998
999 uint8_t ending_level = lowest_zero_bit_starting_at(bit_pattern, starting_level);
1000
1001 if (apply_as_update) {
1002 // update version of computation
1003 // its is okay for buf_size_k to be null in this case
1004 zip_buffer(buf_size_2k, sketch.levels_[ending_level]);
1005 } else {
1006 // merge_into version of computation
1007 // the ending level is empty, so a failed copy can be undone by clearing it
1008 try {
1009 for (uint16_t i = 0; i < k; ++i) {
1010 sketch.levels_[ending_level].push_back(conditional_forward<FwdV>(buf_size_k[i]));
1011 }
1012 } catch (...) {
1013 sketch.levels_[ending_level].clear();
1014 throw;
1015 }
1016 }
1017
1018 for (uint64_t lvl = starting_level; lvl < ending_level; lvl++) {
1019 if ((bit_pattern & (static_cast<uint64_t>(1) << lvl)) == 0) {
1020 throw std::logic_error("unexpected empty level in bit_pattern");
1021 }
1022 merge_two_size_k_buffers(
1023 sketch.levels_[lvl],
1024 sketch.levels_[ending_level],
1025 buf_size_2k, sketch.get_comparator());
1026 sketch.levels_[lvl].clear();
1027 sketch.levels_[ending_level].clear();
1028 zip_buffer(buf_size_2k, sketch.levels_[ending_level]);
1029 } // end of loop over lower levels
1030
1031 // update bit pattern with binary-arithmetic ripple carry
1032 sketch.bit_pattern_ = bit_pattern + (static_cast<uint64_t>(1) << starting_level);
1033}
1034
1035template<typename T, typename C, typename A>
1036void quantiles_sketch<T, C, A>::zip_buffer(Level& buf_in, Level& buf_out) {
1037#ifdef QUANTILES_VALIDATION
1038 static uint32_t next_offset = 0;
1039 uint32_t rand_offset = next_offset;
1040 next_offset = 1 - next_offset;
1041#else
1042 uint32_t rand_offset = random_utils::random_bit();
1043#endif
1044 if ((buf_in.size() != 2 * buf_out.capacity())
1045 || (buf_out.size() > 0)) {
1046 throw std::logic_error("zip_buffer requires buf_in.size() == "
1047 "2*buf_out.capacity() and empty buf_out");
1048 }
1049
1050 size_t k = buf_out.capacity();
1051 for (uint32_t i = rand_offset, o = 0; o < k; i += 2, ++o) {
1052 buf_out.push_back(std::move(buf_in[i]));
1053 }
1054 buf_in.clear();
1055}
1056
1057template<typename T, typename C, typename A>
1058template<typename FwdV>
1059void quantiles_sketch<T, C, A>::zip_buffer_with_stride(FwdV&& buf_in, Level& buf_out, uint16_t stride) {
1060 // Random offset in range [0, stride)
1061 std::uniform_int_distribution<uint16_t> dist(0, stride - 1);
1062 const uint16_t rand_offset = dist(random_utils::rand);
1063
1064 if ((buf_in.size() != stride * buf_out.capacity())
1065 || (buf_out.size() > 0)) {
1066 throw std::logic_error("zip_buffer_with_stride requires buf_in.size() == "
1067 "stride*buf_out.capacity() and empty buf_out");
1068 }
1069
1070 const size_t k = buf_out.capacity();
1071 for (uint16_t i = rand_offset, o = 0; o < k; i += stride, ++o) {
1072 buf_out.push_back(conditional_forward<FwdV>(buf_in[i]));
1073 }
1074 // do not clear input buffer
1075}
1076
1077template<typename T, typename C, typename A>
1078void quantiles_sketch<T, C, A>::merge_two_size_k_buffers(Level& src_1, Level& src_2,
1079 Level& dst, const C& comparator) {
1080 if (src_1.size() != src_2.size()
1081 || src_1.size() * 2 != dst.capacity()
1082 || dst.size() != 0) {
1083 throw std::logic_error("Input invariants violated in merge_two_size_k_buffers()");
1084 }
1085
1086 auto end1 = src_1.end(), end2 = src_2.end();
1087 auto it1 = src_1.begin(), it2 = src_2.begin();
1088
1089 while (it1 != end1 && it2 != end2) {
1090 if (comparator(*it1, *it2)) {
1091 dst.push_back(std::move(*it1++));
1092 } else {
1093 dst.push_back(std::move(*it2++));
1094 }
1095 }
1096
1097 if (it1 != end1) {
1098 dst.insert(dst.end(), std::make_move_iterator(it1), std::make_move_iterator(end1));
1099 } else {
1100 if (it2 == end2) { throw std::logic_error("it2 unexpectedly already at end of range"); }
1101 dst.insert(dst.end(), std::make_move_iterator(it2), std::make_move_iterator(end2));
1102 }
1103}
1104
1105// Both merges allocate everything first, so that an allocation failure leaves tgt unchanged.
1106// After that, a copy of an item from a const src is the only thing that can throw,
1107// and n is advanced with each step, so that tgt stays valid if one does.
1108template<typename T, typename C, typename A>
1109template<typename FwdSk>
1110void quantiles_sketch<T, C, A>::standard_merge(quantiles_sketch& tgt, FwdSk&& src) {
1111 if (src.get_k() != tgt.get_k()) {
1112 throw std::invalid_argument("src.get_k() != tgt.get_k()");
1113 }
1114 if (src.is_empty()) {
1115 return;
1116 }
1117
1118 const uint64_t new_n = src.get_n() + tgt.get_n();
1119 reserve_for_merge(tgt, new_n, src.base_buffer_.size());
1120 Level scratch_buf(tgt.allocator_);
1121 scratch_buf.reserve(2 * tgt.get_k());
1122
1123 merge_min_max(tgt, std::forward<FwdSk>(src));
1124
1125 // move items from src's base buffer
1126 for (auto& item : src.base_buffer_) {
1127 tgt.insert_base(conditional_forward<FwdSk>(item));
1128 }
1129
1130 uint64_t src_pattern = src.bit_pattern_;
1131 for (uint8_t src_lvl = 0; src_pattern != 0; ++src_lvl, src_pattern >>= 1) {
1132 if ((src_pattern & 1) > 0) {
1133 scratch_buf.clear();
1134
1135 // propagate-carry
1136 in_place_propagate_carry(src_lvl,
1137 conditional_forward<FwdSk>(src.levels_[src_lvl]), scratch_buf,
1138 false, tgt);
1139 tgt.n_ += static_cast<uint64_t>(2 * tgt.get_k()) << src_lvl;
1140 }
1141 }
1142 if (tgt.n_ != new_n || (tgt.get_n() / (2 * tgt.get_k())) != tgt.bit_pattern_) {
1143 throw std::logic_error("Failed internal consistency check after standard_merge()");
1144 }
1145}
1146
1147template<typename T, typename C, typename A>
1148template<typename FwdSk>
1149void quantiles_sketch<T, C, A>::downsampling_merge(quantiles_sketch& tgt, FwdSk&& src) {
1150 if (src.get_k() % tgt.get_k() != 0) {
1151 throw std::invalid_argument("src.get_k() is not a multiple of tgt.get_k()");
1152 }
1153 if (src.is_empty()) {
1154 return;
1155 }
1156
1157 const uint16_t downsample_factor = src.get_k() / tgt.get_k();
1158 const uint8_t lg_sample_factor = count_trailing_zeros_in_u32(downsample_factor);
1159
1160 const uint64_t new_n = src.get_n() + tgt.get_n();
1161 reserve_for_merge(tgt, new_n, src.base_buffer_.size());
1162 Level down_buf(tgt.allocator_);
1163 down_buf.reserve(tgt.get_k());
1164 Level scratch_buf(tgt.allocator_);
1165 scratch_buf.reserve(2 * tgt.get_k());
1166
1167 merge_min_max(tgt, std::forward<FwdSk>(src));
1168
1169 // move items from src's base buffer
1170 for (auto& item : src.base_buffer_) {
1171 tgt.insert_base(conditional_forward<FwdSk>(item));
1172 }
1173
1174 uint64_t src_pattern = src.bit_pattern_;
1175 for (uint8_t src_lvl = 0; src_pattern != 0; ++src_lvl, src_pattern >>= 1) {
1176 if ((src_pattern & 1) > 0) {
1177 down_buf.clear();
1178 scratch_buf.clear();
1179
1180 // zip with stride; a failed copy changes only down_buf
1181 zip_buffer_with_stride(conditional_forward<FwdSk>(src.levels_[src_lvl]), down_buf, downsample_factor);
1182
1183 // propagate-carry
1184 in_place_propagate_carry(src_lvl + lg_sample_factor,
1185 std::move(down_buf), scratch_buf,
1186 false, tgt);
1187 tgt.n_ += static_cast<uint64_t>(2 * tgt.get_k()) << (src_lvl + lg_sample_factor);
1188 }
1189 }
1190 if (tgt.n_ != new_n || (tgt.get_n() / (2 * tgt.get_k())) != tgt.bit_pattern_) {
1191 throw std::logic_error("Failed internal consistency check after downsampling_merge()");
1192 }
1193}
1194
1195template<typename T, typename C, typename A>
1196uint8_t quantiles_sketch<T, C, A>::lowest_zero_bit_starting_at(uint64_t bits, uint8_t starting_bit) {
1197 uint8_t pos = starting_bit & 0X3F;
1198 uint64_t my_bits = bits >> pos;
1199
1200 while ((my_bits & static_cast<uint64_t>(1)) != 0) {
1201 my_bits >>= 1;
1202 pos++;
1203 }
1204 return pos;
1205}
1206
1207template<typename T, typename C, typename A>
1208class quantiles_sketch<T, C, A>::items_deleter {
1209 public:
1210 items_deleter(const A& allocator, bool destroy, size_t num): allocator_(allocator), destroy_(destroy), num_(num) {}
1211 void operator() (T* ptr) {
1212 if (ptr != nullptr) {
1213 if (destroy_) {
1214 for (size_t i = 0; i < num_; ++i) {
1215 ptr[i].~T();
1216 }
1217 }
1218 allocator_.deallocate(ptr, num_);
1219 }
1220 }
1221 void set_destroy(bool destroy) { destroy_ = destroy; }
1222 private:
1223 A allocator_;
1224 bool destroy_;
1225 size_t num_;
1226};
1227
1228template<typename T, typename C, typename A>
1229void quantiles_sketch<T, C, A>::setup_sorted_view() const {
1230 if (sorted_view_ == nullptr) {
1231 using AllocSortedView = typename std::allocator_traits<A>::template rebind_alloc<quantiles_sorted_view<T, C, A>>;
1232 sorted_view_ = new (AllocSortedView(allocator_).allocate(1)) quantiles_sorted_view<T, C, A>(get_sorted_view());
1233 }
1234}
1235
1236template<typename T, typename C, typename A>
1237void quantiles_sketch<T, C, A>::reset_sorted_view() {
1238 if (sorted_view_ != nullptr) {
1239 sorted_view_->~quantiles_sorted_view();
1240 using AllocSortedView = typename std::allocator_traits<A>::template rebind_alloc<quantiles_sorted_view<T, C, A>>;
1241 AllocSortedView(allocator_).deallocate(sorted_view_, 1);
1242 sorted_view_ = nullptr;
1243 }
1244}
1245
1246// quantiles_sketch::const_iterator implementation
1247
1248template<typename T, typename C, typename A>
1249quantiles_sketch<T, C, A>::const_iterator::const_iterator(const Level& base_buffer,
1250 const std::vector<Level, AllocLevel>& levels,
1251 uint16_t k,
1252 uint64_t n,
1253 bool is_end):
1254base_buffer_(base_buffer),
1255levels_(levels),
1256level_(-1),
1257index_(0),
1258bb_count_(compute_base_buffer_items(k, n)),
1259bit_pattern_(compute_bit_pattern(k, n)),
1260weight_(1),
1261k_(k)
1262{
1263 if (is_end) {
1264 // if exact mode: index_ = n is end
1265 // if sampling, level_ = max_level + 1 and index_ = 0 is end
1266 if (bit_pattern_ == 0) // only a valid check for exact mode in constructor
1267 index_ = static_cast<uint32_t>(n);
1268 else
1269 level_ = static_cast<int>(levels_.size());
1270 } else { // find first non-empty item
1271 if (bb_count_ == 0 && bit_pattern_ > 0) {
1272 level_ = 0;
1273 weight_ = 2;
1274 while ((bit_pattern_ & 0x01) == 0) {
1275 weight_ *= 2;
1276 ++level_;
1277 bit_pattern_ >>= 1;
1278 }
1279 }
1280 }
1281}
1282
1283template<typename T, typename C, typename A>
1284typename quantiles_sketch<T, C, A>::const_iterator& quantiles_sketch<T, C, A>::const_iterator::operator++() {
1285 ++index_;
1286
1287 if ((level_ == -1 && index_ == base_buffer_.size() && levels_.size() > 0) || (level_ >= 0 && index_ == k_)) { // go to the next non-empty level
1288 index_ = 0;
1289 do {
1290 ++level_;
1291 if (level_ > 0) bit_pattern_ = bit_pattern_ >> 1;
1292 if (bit_pattern_ == 0) return *this;
1293 weight_ *= 2;
1294 } while ((bit_pattern_ & static_cast<uint64_t>(1)) == 0);
1295 }
1296 return *this;
1297}
1298
1299template<typename T, typename C, typename A>
1300typename quantiles_sketch<T, C, A>::const_iterator& quantiles_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 quantiles_sketch<T, C, A>::const_iterator::operator==(const const_iterator& other) const {
1308 return level_ == other.level_ && index_ == other.index_;
1309}
1310
1311template<typename T, typename C, typename A>
1312bool quantiles_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 quantiles_sketch<T, C, A>::const_iterator::operator*() const -> reference {
1318 return value_type(level_ == -1 ? base_buffer_[index_] : levels_[level_][index_], weight_);
1319}
1320
1321template<typename T, typename C, typename A>
1322auto quantiles_sketch<T, C, A>::const_iterator::operator->() const -> pointer {
1323 return **this;
1324}
1325
1326} /* namespace datasketches */
1327
1328#endif // _QUANTILES_SKETCH_IMPL_HPP_
This is a stochastic streaming sketch that enables near-real time analysis of the approximate distrib...
Definition quantiles_sketch.hpp:158
Comparator get_comparator() const
Returns an instance of the comparator for this sketch.
Definition quantiles_sketch_impl.hpp:722
quantiles_sorted_view< T, Comparator, Allocator > get_sorted_view() const
Gets the sorted view of this sketch.
Definition quantiles_sketch_impl.hpp:764
quantiles_sketch & operator=(const quantiles_sketch &other)
Copy assignment.
Definition quantiles_sketch_impl.hpp:90
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:810
uint32_t get_num_retained() const
Returns the number of retained items (samples) in the sketch.
Definition quantiles_sketch_impl.hpp:705
double get_normalized_rank_error(bool is_pmf) const
Gets the normalized rank error for this sketch.
Definition quantiles_sketch_impl.hpp:752
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:803
void merge(FwdSk &&other)
Merges another sketch into this one.
Definition quantiles_sketch_impl.hpp:254
void update(FwdT &&item)
Updates this sketch with the given data item.
Definition quantiles_sketch_impl.hpp:213
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:309
string< Allocator > to_string(bool print_levels=false, bool print_items=false) const
Prints a summary of the sketch.
Definition quantiles_sketch_impl.hpp:636
uint16_t get_k() const
Returns configured parameter k.
Definition quantiles_sketch_impl.hpp:685
bool is_empty() const
Returns true if this sketch is empty.
Definition quantiles_sketch_impl.hpp:695
const T & get_max_item() const
Returns the max item of the stream.
Definition quantiles_sketch_impl.hpp:716
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:796
allocator_type get_allocator() const
Returns the allocator for this sketch.
Definition quantiles_sketch_impl.hpp:727
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:785
const_iterator begin() const
Iterator pointing to the first item in the sketch.
Definition quantiles_sketch_impl.hpp:907
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:734
bool is_estimation_mode() const
Returns true if this sketch is in estimation mode.
Definition quantiles_sketch_impl.hpp:700
const T & get_min_item() const
Returns the min item of the stream.
Definition quantiles_sketch_impl.hpp:710
const_iterator end() const
Iterator pointing to the past-the-end item in the sketch.
Definition quantiles_sketch_impl.hpp:912
uint64_t get_n() const
Returns the length of the input stream.
Definition quantiles_sketch_impl.hpp:690
Sorted view for quantiles sketches (REQ, KLL and Quantiles).
Definition quantiles_sorted_view.hpp:40
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:35
void serialize(std::ostream &os, const T *items, unsigned num) const
Stream serialization.