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;
42}
43
166template <
167 typename T,
168 typename C = std::less<T>, // strict weak ordering function (see C++ named requirements: Compare)
169 typename A = std::allocator<T>
170>
172 public:
173 using value_type = T;
174 using comparator = C;
175 using allocator_type = A;
176 using vector_u32 = std::vector<uint32_t, typename std::allocator_traits<A>::template rebind_alloc<uint32_t>>;
177 using vector_double = typename quantiles_sorted_view<T, C, A>::vector_double;
178
184
191 explicit kll_sketch(uint16_t k = kll_constants::DEFAULT_K, const C& comparator = C(), const A& allocator = A());
192
197 kll_sketch(const kll_sketch& other);
198
203 kll_sketch(kll_sketch&& other) noexcept;
204
205
206 ~kll_sketch();
207
213 kll_sketch& operator=(const kll_sketch& other);
214
221
222 /*
223 * Type converting constructor.
224 * @param other sketch of a different type
225 * @param comparator instance of a Comparator
226 * @param allocator instance of an Allocator
227 */
228 template<typename TT, typename CC, typename AA>
229 explicit kll_sketch(const kll_sketch<TT, CC, AA>& other, const C& comparator = C(), const A& allocator = A());
230
237 template<typename FwdT>
238 void update(FwdT&& item);
239
246 template<typename FwdSk>
247 void merge(FwdSk&& other);
248
253 bool is_empty() const;
254
259 uint16_t get_k() const;
260
265 uint64_t get_n() const;
266
271 uint32_t get_num_retained() const;
272
277 bool is_estimation_mode() const;
278
284 T get_min_item() const;
285
291 T get_max_item() const;
292
297 C get_comparator() const;
298
303 A get_allocator() const;
304
316 quantile_return_type get_quantile(double rank, bool inclusive = true) const;
317
333 double get_rank(const T& item, bool inclusive = true) const;
334
357 vector_double get_PMF(const T* split_points, uint32_t size, bool inclusive = true) const;
358
384 vector_double get_CDF(const T* split_points, uint32_t size, bool inclusive = true) const;
385
393 double get_normalized_rank_error(bool pmf) const;
394
401 template<typename TT = T, typename SerDe = serde<T>, typename std::enable_if<std::is_arithmetic<TT>::value, int>::type = 0>
402 size_t get_serialized_size_bytes(const SerDe& sd = SerDe()) const;
403
410 template<typename TT = T, typename SerDe = serde<T>, typename std::enable_if<!std::is_arithmetic<TT>::value, int>::type = 0>
411 size_t get_serialized_size_bytes(const SerDe& sd = SerDe()) const;
412
423 template<typename TT = T, typename std::enable_if<std::is_arithmetic<TT>::value, int>::type = 0>
424 static size_t get_max_serialized_size_bytes(uint16_t k, uint64_t n);
425
437 template<typename TT = T, typename std::enable_if<!std::is_arithmetic<TT>::value, int>::type = 0>
438 static size_t get_max_serialized_size_bytes(uint16_t k, uint64_t n, size_t max_item_size_bytes);
439
445 template<typename SerDe = serde<T>>
446 void serialize(std::ostream& os, const SerDe& sd = SerDe()) const;
447
448 // This is a convenience alias for users
449 // The type returned by the following serialize method
450 using vector_bytes = std::vector<uint8_t, typename std::allocator_traits<A>::template rebind_alloc<uint8_t>>;
451
461 template<typename SerDe = serde<T>>
462 vector_bytes serialize(unsigned header_size_bytes = 0, const SerDe& sd = SerDe()) const;
463
472 template<typename SerDe = serde<T>>
473 static kll_sketch deserialize(std::istream& is, const SerDe& sd = SerDe(),
474 const C& comparator = C(), const A& allocator = A());
475
485 template<typename SerDe = serde<T>>
486 static kll_sketch deserialize(const void* bytes, size_t size, const SerDe& sd = SerDe(),
487 const C& comparator = C(), const A& allocator = A());
488
489 /*
490 * Gets the normalized rank error given k and pmf.
491 * k - the configuration parameter
492 * pmf - if true, returns the "double-sided" normalized rank error for the get_PMF() function.
493 * Otherwise, it is the "single-sided" normalized rank error for all the other queries.
494 * Constants were derived as the best fit to 99 percentile empirically measured max error in thousands of trials
495 */
496 static double get_normalized_rank_error(uint16_t k, bool pmf);
497
503 string<A> to_string(bool print_levels = false, bool print_items = false) const;
504
505 class const_iterator;
506
512 const_iterator begin() const;
513
520 const_iterator end() const;
521
527
528 private:
529 /* Serialized sketch layout:
530 * Addr:
531 * || 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 |
532 * 0 || unused | M |--------K--------| Flags | FamID | SerVer | PreambleInts |
533 * || 15 | 14 | 13 | 12 | 11 | 10 | 9 | 8 |
534 * 1 ||-----------------------------------N------------------------------------------|
535 * || 23 | 22 | 21 | 20 | 19 | 18 | 17 | 16 |
536 * 2 ||---------------data----------------|-unused-|numLevels|-------min K-----------|
537 */
538
539 static const size_t EMPTY_SIZE_BYTES = 8;
540 static const size_t DATA_START_SINGLE_ITEM = 8;
541 static const size_t DATA_START = 20;
542
543 static const uint8_t SERIAL_VERSION_1 = 1;
544 static const uint8_t SERIAL_VERSION_2 = 2;
545 static const uint8_t FAMILY = 15;
546
547 enum flags { IS_EMPTY, IS_LEVEL_ZERO_SORTED, IS_SINGLE_ITEM };
548
549 static const uint8_t PREAMBLE_INTS_SHORT = 2; // for empty and single item
550 static const uint8_t PREAMBLE_INTS_FULL = 5;
551
552 C comparator_;
553 A allocator_;
554 uint16_t k_;
555 uint8_t m_; // minimum buffer "width"
556 uint16_t min_k_; // for error estimation after merging with different k
557 uint8_t num_levels_;
558 bool is_level_zero_sorted_;
559 uint64_t n_;
560 vector_u32 levels_;
561 T* items_;
562 uint32_t items_size_;
563 optional<T> min_item_;
564 optional<T> max_item_;
565 mutable quantiles_sorted_view<T, C, A>* sorted_view_;
566
567 // for deserialization
568 class items_deleter;
569 kll_sketch(uint16_t k, uint16_t min_k, uint64_t n, uint8_t num_levels, vector_u32&& levels,
570 std::unique_ptr<T, items_deleter> items, uint32_t items_size, optional<T>&& min_item,
571 optional<T>&& max_item, bool is_level_zero_sorted, const C& comparator);
572
573 // common update code
574 inline void update_min_max(const T& item);
575 inline uint32_t internal_update();
576
577 // The following code is only valid in the special case of exactly reaching capacity while updating.
578 // It cannot be used while merging, while reducing k, or anything else.
579 void compress_while_updating(void);
580
581 uint8_t find_level_to_compact() const;
582 void add_empty_top_level_to_completely_full_sketch();
583 void sort_level_zero();
584
585 template<typename O> void merge_higher_levels(O&& other, uint64_t final_n);
586
587 template<typename FwdSk>
588 void populate_work_arrays(FwdSk&& other, T* workbuf, uint32_t* worklevels, uint8_t provisional_num_levels);
589
590 void assert_correct_total_weight() const;
591 uint32_t safe_level_size(uint8_t level) const;
592 uint32_t get_num_retained_above_level_zero() const;
593
594 static void check_m(uint8_t m);
595 static void check_preamble_ints(uint8_t preamble_ints, uint8_t flags_byte);
596 static void check_serial_version(uint8_t serial_version);
597 static void check_family_id(uint8_t family_id);
598
599 void check_sorting() const;
600
601 template<typename TT = T, typename std::enable_if<std::is_floating_point<TT>::value, int>::type = 0>
602 static inline bool check_update_item(TT item) {
603 return !std::isnan(item);
604 }
605
606 template<typename TT = T, typename std::enable_if<!std::is_floating_point<TT>::value, int>::type = 0>
607 static inline bool check_update_item(TT) {
608 return true;
609 }
610
611 // for type converting constructor
612 template<typename TT, typename CC, typename AA> friend class kll_sketch;
613
614 void setup_sorted_view() const; // modifies mutable state
615 void reset_sorted_view();
616};
617
618template<typename T, typename C, typename A>
619class kll_sketch<T, C, A>::const_iterator {
620public:
621 using iterator_category = std::input_iterator_tag;
622 using value_type = std::pair<const T&, const uint64_t>;
623 using difference_type = void;
624 using pointer = const return_value_holder<value_type>;
625 using reference = const value_type;
626
627 friend class kll_sketch<T, C, A>;
628 const_iterator& operator++();
629 const_iterator& operator++(int);
630 bool operator==(const const_iterator& other) const;
631 bool operator!=(const const_iterator& other) const;
632 reference operator*() const;
633 pointer operator->() const;
634private:
635 const T* items;
636 const uint32_t* levels;
637 const uint8_t num_levels;
638 uint32_t index;
639 uint8_t level;
640 uint64_t weight;
641 const_iterator(const T* items, const uint32_t* levels, const uint8_t num_levels);
642};
643
644} /* namespace datasketches */
645
646#include "kll_sketch_impl.hpp"
647
648#endif
Implementation of a very compact quantiles sketch with lazy compaction scheme and nearly optimal accu...
Definition kll_sketch.hpp:171
C get_comparator() const
Returns an instance of the comparator for this sketch.
Definition kll_sketch_impl.hpp:272
quantiles_sorted_view< T, C, A > get_sorted_view() const
Gets the sorted view of this sketch.
Definition kll_sketch_impl.hpp:769
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:296
const_iterator begin() const
Iterator pointing to the first item in the sketch.
Definition kll_sketch_impl.hpp:965
uint32_t get_num_retained() const
Returns the number of retained items (samples) in the sketch.
Definition kll_sketch_impl.hpp:250
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:289
void merge(FwdSk &&other)
Merges another sketch into this one.
Definition kll_sketch_impl.hpp:210
T get_max_item() const
Returns the max item of the stream.
Definition kll_sketch_impl.hpp:266
const_iterator end() const
Iterator pointing to the past-the-end item in the sketch.
Definition kll_sketch_impl.hpp:970
void update(FwdT &&item)
Updates this sketch with the given data item.
Definition kll_sketch_impl.hpp:181
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:368
string< A > to_string(bool print_levels=false, bool print_items=false) const
Prints a summary of the sketch.
Definition kll_sketch_impl.hpp:913
uint16_t get_k() const
Returns configured parameter k.
Definition kll_sketch_impl.hpp:240
bool is_empty() const
Returns true if this sketch is empty.
Definition kll_sketch_impl.hpp:235
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:282
A get_allocator() const
Returns an instance of the allocator for this sketch.
Definition kll_sketch_impl.hpp:277
T get_min_item() const
Returns the min item of the stream.
Definition kll_sketch_impl.hpp:260
typename quantiles_sorted_view< T, C, A >::quantile_return_type quantile_return_type
Quantile return type.
Definition kll_sketch.hpp:183
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:303
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:321
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:349
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:314
bool is_estimation_mode() const
Returns true if this sketch is in estimation mode.
Definition kll_sketch_impl.hpp:255
uint64_t get_n() const
Returns the length of the input stream.
Definition kll_sketch_impl.hpp:245
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:38
typename std::conditional< std::is_arithmetic< T >::value, T, const T & >::type quantile_return_type
Quantile return type.
Definition quantiles_sorted_view.hpp:93
const uint16_t MAX_K
max value of parameter K
Definition kll_sketch.hpp:41
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