datasketches-cpp
Loading...
Searching...
No Matches
kll_sketch.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_HPP_
21#define KLL_SKETCH_HPP_
22
23#include <memory>
24#include <vector>
25
26#include "common_defs.hpp"
27#include "serde.hpp"
28#include "quantiles_sorted_view.hpp"
29#include "optional.hpp"
30
31namespace datasketches {
32
34namespace kll_constants {
36 const uint16_t DEFAULT_K = 200;
37 const uint8_t DEFAULT_M = 8;
39 const uint16_t MIN_K = DEFAULT_M;
41 const uint16_t MAX_K = (1 << 16) - 1;
43 const uint64_t MAX_WEIGHT = (1ULL << 61) - 1;
45 const uint64_t MAX_N = (1ULL << 63) - 1;
46}
47
176
177template <
178 typename T,
179 typename C = std::less<T>, // strict weak ordering function (see C++ named requirements: Compare)
180 typename A = std::allocator<T>
181>
182class kll_sketch {
183 public:
184 using value_type = T;
185 using comparator = C;
186 using allocator_type = A;
187 using vector_u32 = std::vector<uint32_t, typename std::allocator_traits<A>::template rebind_alloc<uint32_t>>;
188 using vector_double = typename quantiles_sorted_view<T, C, A>::vector_double;
189
195
205 explicit kll_sketch(uint16_t k = kll_constants::DEFAULT_K, const C& comparator = C(), const A& allocator = A());
206
211 kll_sketch(const kll_sketch& other);
212
217 kll_sketch(kll_sketch&& other) noexcept;
218
219
220 ~kll_sketch();
221
227 kll_sketch& operator=(const kll_sketch& other);
228
234 kll_sketch& operator=(kll_sketch&& other);
235
236 /*
237 * Type converting constructor.
238 * @param other sketch of a different type
239 * @param comparator instance of a Comparator
240 * @param allocator instance of an Allocator
241 */
242 template<typename TT, typename CC, typename AA>
243 explicit kll_sketch(const kll_sketch<TT, CC, AA>& other, const C& comparator = C(), const A& allocator = A());
244
253 template<typename FwdT>
254 void update(FwdT&& item);
255
270 template<typename FwdT>
271 void update(FwdT&& item, uint64_t weight);
272
285 template<typename FwdSk>
286 void merge(FwdSk&& other);
287
296 void reserve();
297
302 bool is_empty() const;
303
308 uint16_t get_k() const;
309
314 uint64_t get_n() const;
315
320 uint32_t get_num_retained() const;
321
326 bool is_estimation_mode() const;
327
333 T get_min_item() const;
334
340 T get_max_item() const;
341
346 C get_comparator() const;
347
352 A get_allocator() const;
353
368 quantile_return_type get_quantile(double rank, bool inclusive = true) const;
369
385 double get_rank(const T& item, bool inclusive = true) const;
386
409 vector_double get_PMF(const T* split_points, uint32_t size, bool inclusive = true) const;
410
436 vector_double get_CDF(const T* split_points, uint32_t size, bool inclusive = true) const;
437
445 double get_normalized_rank_error(bool pmf) const;
446
453 template<typename TT = T, typename SerDe = serde<T>, typename std::enable_if<std::is_arithmetic<TT>::value, int>::type = 0>
454 size_t get_serialized_size_bytes(const SerDe& sd = SerDe()) const;
455
462 template<typename TT = T, typename SerDe = serde<T>, typename std::enable_if<!std::is_arithmetic<TT>::value, int>::type = 0>
463 size_t get_serialized_size_bytes(const SerDe& sd = SerDe()) const;
464
475 template<typename TT = T, typename std::enable_if<std::is_arithmetic<TT>::value, int>::type = 0>
476 static size_t get_max_serialized_size_bytes(uint16_t k, uint64_t n);
477
489 template<typename TT = T, typename std::enable_if<!std::is_arithmetic<TT>::value, int>::type = 0>
490 static size_t get_max_serialized_size_bytes(uint16_t k, uint64_t n, size_t max_item_size_bytes);
491
497 template<typename SerDe = serde<T>>
498 void serialize(std::ostream& os, const SerDe& sd = SerDe()) const;
499
500 // This is a convenience alias for users
501 // The type returned by the following serialize method
502 using vector_bytes = std::vector<uint8_t, typename std::allocator_traits<A>::template rebind_alloc<uint8_t>>;
503
513 template<typename SerDe = serde<T>>
514 vector_bytes serialize(unsigned header_size_bytes = 0, const SerDe& sd = SerDe()) const;
515
524 template<typename SerDe = serde<T>>
525 static kll_sketch deserialize(std::istream& is, const SerDe& sd = SerDe(),
526 const C& comparator = C(), const A& allocator = A());
527
537 template<typename SerDe = serde<T>>
538 static kll_sketch deserialize(const void* bytes, size_t size, const SerDe& sd = SerDe(),
539 const C& comparator = C(), const A& allocator = A());
540
541 /*
542 * Gets the normalized rank error given k and pmf.
543 * k - the configuration parameter
544 * pmf - if true, returns the "double-sided" normalized rank error for the get_PMF() function.
545 * Otherwise, it is the "single-sided" normalized rank error for all the other queries.
546 * Constants were derived as the best fit to 99 percentile empirically measured max error in thousands of trials
547 */
548 static double get_normalized_rank_error(uint16_t k, bool pmf);
549
555 string<A> to_string(bool print_levels = false, bool print_items = false) const;
556
557 class const_iterator;
558
564 const_iterator begin() const;
565
572 const_iterator end() const;
573
582
583 private:
584 /* Serialized sketch layout:
585 * Addr:
586 * || 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 |
587 * 0 || unused | M |--------K--------| Flags | FamID | SerVer | PreambleInts |
588 * || 15 | 14 | 13 | 12 | 11 | 10 | 9 | 8 |
589 * 1 ||-----------------------------------N------------------------------------------|
590 * || 23 | 22 | 21 | 20 | 19 | 18 | 17 | 16 |
591 * 2 ||---------------data----------------|-unused-|numLevels|-------min K-----------|
592 */
593
594 static const size_t EMPTY_SIZE_BYTES = 8;
595 static const size_t DATA_START_SINGLE_ITEM = 8;
596 static const size_t DATA_START = 20;
597
598 static const uint8_t SERIAL_VERSION_1 = 1;
599 static const uint8_t SERIAL_VERSION_2 = 2;
600 static const uint8_t FAMILY = 15;
601
602 enum flags { IS_EMPTY, IS_LEVEL_ZERO_SORTED, IS_SINGLE_ITEM };
603
604 static const uint8_t PREAMBLE_INTS_SHORT = 2; // for empty and single item
605 static const uint8_t PREAMBLE_INTS_FULL = 5;
606
607 // growth factor of the items buffer until it holds k items
608 static const resize_factor RESIZE_FACTOR = resize_factor::X8;
609 static_assert(RESIZE_FACTOR >= resize_factor::X1, "RESIZE_FACTOR must be at least X1");
610
611 C comparator_;
612 A allocator_;
613 uint16_t k_;
614 uint8_t m_; // minimum buffer "width"
615 uint16_t min_k_; // for error estimation after merging with different k
616 uint8_t num_levels_;
617 bool is_level_zero_sorted_;
618 uint64_t n_;
619 vector_u32 levels_;
620 T* items_; // nullptr until the sketch first receives items, see allocate_items()
621 uint32_t items_size_;
622 optional<T> min_item_;
623 optional<T> max_item_;
624 mutable quantiles_sorted_view<T, C, A>* sorted_view_;
625
626 // for deserialization
627 class items_deleter;
628 kll_sketch(uint16_t k, uint16_t min_k, uint64_t n, uint8_t num_levels, vector_u32&& levels,
629 std::unique_ptr<T, items_deleter> items, uint32_t items_size, optional<T>&& min_item,
630 optional<T>&& max_item, bool is_level_zero_sorted, const C& comparator);
631
632 // for weighted update
633 kll_sketch(uint16_t k, const T& item, uint64_t weight, const C& comparator, const A& allocator);
634
635 // common update code
636 inline void update_min_max(const T& item);
637 // items_ is allocated lazily, and these are the only places that deal with it being nullptr:
638 // allocates items_ (items_size_ items) unless it is allocated already
639 inline void allocate_items();
640 // copy-constructs the items of other, if other has any, into this newly constructed sketch
641 template<typename O> void copy_items(const O& other);
642 // &items_[index], or nullptr without item storage, which makes every item range empty
643 inline T* item_ptr(uint32_t index) const;
644 inline uint32_t internal_update();
645 // inserts an item into level zero; if constructing it throws, the sketch is unchanged
646 template<typename FwdT> void insert_level_zero(FwdT&& item);
647 // throws std::overflow_error if n_ + increase would exceed kll_constants::MAX_N
648 inline void check_n_increase(uint64_t increase) const;
649 // destroys the items and frees items_, for a constructor that throws
650 void destroy_items();
651
652 // The following code is only valid in the special case of exactly reaching capacity while updating.
653 // It cannot be used while merging, while reducing k, or anything else.
654 void compress_while_updating(void);
655
656 uint8_t find_level_to_compact() const;
657 void add_empty_top_level_to_completely_full_sketch();
658 void grow_items(uint32_t new_size); // only while there is one level
659 void sort_level_zero();
660
661 template<typename O> void merge_higher_levels(O&& other, uint64_t final_n);
662
663 template<typename FwdSk>
664 void populate_work_arrays(FwdSk&& other, T* workbuf, const uint32_t* worklevels, uint8_t provisional_num_levels);
665
666 void assert_correct_total_weight() const;
667 uint32_t safe_level_size(uint8_t level) const;
668 uint32_t get_num_retained_above_level_zero() const;
669 bool is_min_retained() const;
670
671 static void check_k(uint16_t k);
672 static void check_m(uint8_t m);
673 static void check_preamble_ints(uint8_t preamble_ints, uint8_t flags_byte);
674 static void check_serial_version(uint8_t serial_version);
675 static void check_family_id(uint8_t family_id);
676 static void check_num_levels(uint8_t num_levels);
677 static void check_n(uint64_t n, uint32_t num_retained);
678 static void check_levels(const vector_u32& levels);
679
680 void check_sorting() const;
681
682 template<typename TT = T, typename std::enable_if<std::is_floating_point<TT>::value, int>::type = 0>
683 static inline bool check_update_item(TT item) {
684 return !std::isnan(item);
685 }
686
687 template<typename TT = T, typename std::enable_if<!std::is_floating_point<TT>::value, int>::type = 0>
688 static inline bool check_update_item(TT) {
689 return true;
690 }
691
692 // for type converting constructor
693 template<typename TT, typename CC, typename AA> friend class kll_sketch;
694
695 void setup_sorted_view() const; // modifies mutable state
696 void reset_sorted_view();
697};
698
699template<typename T, typename C, typename A>
700class kll_sketch<T, C, A>::const_iterator {
701public:
702 using iterator_category = std::input_iterator_tag;
703 using value_type = std::pair<const T&, const uint64_t>;
704 using difference_type = void;
705 using pointer = const return_value_holder<value_type>;
706 using reference = const value_type;
707
708 friend class kll_sketch<T, C, A>;
709 const_iterator& operator++();
710 const_iterator& operator++(int);
711 bool operator==(const const_iterator& other) const;
712 bool operator!=(const const_iterator& other) const;
713 reference operator*() const;
714 pointer operator->() const;
715private:
716 const T* items;
717 const uint32_t* levels;
718 const uint8_t num_levels;
719 uint32_t index;
720 uint8_t level;
721 uint64_t weight;
722 const_iterator(const T* items, const uint32_t* levels, const uint8_t num_levels);
723};
724
725} /* namespace datasketches */
726
727#include "kll_sketch_impl.hpp"
728
729#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_bytes serialize(unsigned header_size_bytes=0, const SerDe &sd=SerDe()) const
This method serializes the sketch as a vector of bytes.
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
static kll_sketch deserialize(const void *bytes, size_t size, const SerDe &sd=SerDe(), const C &comparator=C(), const A &allocator=A())
This method deserializes a sketch from a given array of bytes.
Sorted view for quantiles sketches (REQ, KLL and Quantiles).
Definition quantiles_sorted_view.hpp:40
typename std::conditional< std::is_arithmetic< T >::value, T, const T & >::type quantile_return_type
Quantile return type.
Definition quantiles_sorted_view.hpp:101
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
const uint16_t DEFAULT_K
default value of parameter K
Definition kll_sketch.hpp:36
DataSketches namespace.
Definition binomial_bounds.hpp:38