datasketches-cpp
Loading...
Searching...
No Matches
quantiles_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 _QUANTILES_SKETCH_HPP_
21#define _QUANTILES_SKETCH_HPP_
22
23#include <functional>
24#include <memory>
25#include <vector>
26
27#include "quantiles_sorted_view.hpp"
28#include "common_defs.hpp"
29#include "serde.hpp"
30#include "optional.hpp"
31
32namespace datasketches {
33
37 const uint16_t DEFAULT_K = 128;
39 const uint16_t MIN_K = 2;
41 const uint16_t MAX_K = 1 << 15;
42}
43
155template <typename T,
156 typename Comparator = std::less<T>, // strict weak ordering function (see C++ named requirements: Compare)
157 typename Allocator = std::allocator<T>>
158class quantiles_sketch {
159public:
160 using value_type = T;
161 using allocator_type = Allocator;
162 using comparator = Comparator;
164 using vector_double = typename quantiles_sorted_view<T, Comparator, Allocator>::vector_double;
165
173 const Comparator& comparator = Comparator(), const Allocator& allocator = Allocator());
174
179 quantiles_sketch(const quantiles_sketch& other);
180
184 quantiles_sketch(quantiles_sketch&& other) noexcept;
185
186 ~quantiles_sketch();
187
193 quantiles_sketch& operator=(const quantiles_sketch& other);
194
200 quantiles_sketch& operator=(quantiles_sketch&& other) noexcept;
201
208 template<typename From, typename FC, typename FA>
209 explicit quantiles_sketch(const quantiles_sketch<From, FC, FA>& other,
210 const Comparator& comparator = Comparator(), const Allocator& allocator = Allocator());
211
222 template<typename FwdT>
223 void update(FwdT&& item);
224
234 template<typename FwdSk>
235 void merge(FwdSk&& other);
236
241 bool is_empty() const;
242
247 uint16_t get_k() const;
248
253 uint64_t get_n() const;
254
259 uint32_t get_num_retained() const;
260
265 bool is_estimation_mode() const;
266
272 const T& get_min_item() const;
273
279 const T& get_max_item() const;
280
285 Comparator get_comparator() const;
286
291 allocator_type get_allocator() const;
292
305 quantile_return_type get_quantile(double rank, bool inclusive = true) const;
306
321 double get_rank(const T& item, bool inclusive = true) const;
322
345 vector_double get_PMF(const T* split_points, uint32_t size, bool inclusive = true) const;
346
372 vector_double get_CDF(const T* split_points, uint32_t size, bool inclusive = true) const;
373
380 template<typename SerDe = serde<T>, typename TT = T, typename std::enable_if<std::is_arithmetic<TT>::value, int>::type = 0>
381 size_t get_serialized_size_bytes(const SerDe& sd = SerDe()) const;
382
389 template<typename SerDe = serde<T>, typename TT = T, typename std::enable_if<!std::is_arithmetic<TT>::value, int>::type = 0>
390 size_t get_serialized_size_bytes(const SerDe& sd = SerDe()) const;
391
397 template<typename SerDe = serde<T>>
398 void serialize(std::ostream& os, const SerDe& sd = SerDe()) const;
399
400 // This is a convenience alias for users
401 // The type returned by the following serialize method
402 using vector_bytes = std::vector<uint8_t, typename std::allocator_traits<Allocator>::template rebind_alloc<uint8_t>>;
403
413 template<typename SerDe = serde<T>>
414 vector_bytes serialize(unsigned header_size_bytes = 0, const SerDe& sd = SerDe()) const;
415
424 template<typename SerDe = serde<T>>
425 static quantiles_sketch deserialize(std::istream& is, const SerDe& sd = SerDe(),
426 const Comparator& comparator = Comparator(), const Allocator& allocator = Allocator());
427
437 template<typename SerDe = serde<T>>
438 static quantiles_sketch deserialize(const void* bytes, size_t size, const SerDe& sd = SerDe(),
439 const Comparator& comparator = Comparator(), const Allocator& allocator = Allocator());
440
448 double get_normalized_rank_error(bool is_pmf) const;
449
458 static double get_normalized_rank_error(uint16_t k, bool is_pmf);
459
465 string<Allocator> to_string(bool print_levels = false, bool print_items = false) const;
466
467 class const_iterator;
468
474 const_iterator begin() const;
475
482 const_iterator end() const;
483
489
490private:
491 using Level = std::vector<T, Allocator>;
492 using VectorLevels = std::vector<Level, typename std::allocator_traits<Allocator>::template rebind_alloc<Level>>;
493
494 /* Serialized sketch layout:
495 * Long || Start Byte Addr:
496 * Addr:
497 * || 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
498 * 0 || Preamble_Longs | SerVer | FamID | Flags |----- K ---------|---- unused -----|
499 *
500 * || 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 |
501 * 1 ||---------------------------Items Seen Count (N)--------------------------------|
502 *
503 * Long 3 is the start of data, beginning with serialized min and max item, followed by
504 * the sketch data buffers.
505 */
506
507 static const size_t EMPTY_SIZE_BYTES = 8;
508 static const uint8_t SERIAL_VERSION_1 = 1;
509 static const uint8_t SERIAL_VERSION_2 = 2;
510 static const uint8_t SERIAL_VERSION = 3;
511 static const uint8_t FAMILY = 8;
512
513 enum flags { RESERVED0, RESERVED1, IS_EMPTY, IS_COMPACT, IS_SORTED };
514
515 static const uint8_t PREAMBLE_LONGS_SHORT = 1; // for empty
516 static const uint8_t PREAMBLE_LONGS_FULL = 2;
517 static const size_t DATA_START = 16;
518
519 Comparator comparator_;
520 Allocator allocator_;
521 bool is_base_buffer_sorted_;
522 uint16_t k_;
523 uint64_t n_;
524 uint64_t bit_pattern_;
525 Level base_buffer_;
526 VectorLevels levels_;
527 optional<T> min_item_;
528 optional<T> max_item_;
530
531 void setup_sorted_view() const; // modifies mutable state
532 void reset_sorted_view();
533
534 // for deserialization
535 class items_deleter;
536 quantiles_sketch(uint16_t k, uint64_t n, uint64_t bit_pattern,
537 Level&& base_buffer, VectorLevels&& levels,
538 optional<T>&& min_item, optional<T>&& max_item,
539 bool is_sorted, const Comparator& comparator = Comparator(), const Allocator& allocator = Allocator());
540
541 void grow_base_buffer();
542 // adds an item to the base buffer and counts it; if this throws, the sketch is unchanged,
543 // unless the comparator throws
544 template<typename FwdT>
545 void insert_base(FwdT&& item);
546 // the base buffer is full with the new item, which brings n to new_n but is not counted yet
547 void process_full_base_buffer(uint64_t new_n);
548
549 // adds the levels needed for n items; returns true if size adjusted, else false
550 bool grow_levels_if_needed(uint64_t n);
551 // removes the empty levels above those that n needs, which a failed update or merge can leave
552 // (the iterator expects no levels above the highest level in use)
553 void trim_levels();
554
555 // allocates everything a merge into tgt that brings it to new_n items, num_base_items of them
556 // through the base buffer, needs, so that the rest of the merge allocates nothing in tgt
557 static void reserve_for_merge(quantiles_sketch& tgt, uint64_t new_n, uint64_t num_base_items);
558 // compares first, then sets the min and max items of tgt to cover src
559 template<typename FwdSk>
560 static void merge_min_max(quantiles_sketch& tgt, FwdSk&& src);
561 // merge() without the cleanup after a failure; other is not empty
562 template<typename FwdSk>
563 void merge_unchecked(FwdSk&& other);
564
565 // buffers should be pre-sized to target capacity as appropriate
566 template<typename FwdV>
567 static void in_place_propagate_carry(uint8_t starting_level, FwdV&& buf_size_k,
568 Level& buf_size_2k, bool apply_as_update,
569 quantiles_sketch& sketch);
570 static void zip_buffer(Level& buf_in, Level& buf_out);
571 static void merge_two_size_k_buffers(Level& arr_in_1, Level& arr_in_2, Level& arr_out, const Comparator& comparator);
572
573 template<typename SerDe>
574 static Level deserialize_array(std::istream& is, uint32_t num_items, uint32_t capacity, const SerDe& serde, const Allocator& allocator);
575
576 template<typename SerDe>
577 static std::pair<Level, size_t> deserialize_array(const void* bytes, size_t size, uint32_t num_items, uint32_t capacity, const SerDe& serde, const Allocator& allocator);
578
579 static void check_k(uint16_t k);
580 static void check_serial_version(uint8_t serial_version);
581 static void check_header_validity(uint8_t preamble_longs, uint8_t flags_byte, uint8_t serial_version);
582 static void check_family_id(uint8_t family_id);
583
584 static uint32_t compute_retained_items(uint16_t k, uint64_t n);
585 static uint32_t compute_base_buffer_items(uint16_t k, uint64_t n);
586 static uint64_t compute_bit_pattern(uint16_t k, uint64_t n);
587 static uint32_t count_valid_levels(uint64_t bit_pattern);
588 static uint8_t compute_levels_needed(uint16_t k, uint64_t n);
589
594 template<typename FwdSk>
595 static void standard_merge(quantiles_sketch& tgt, FwdSk&& src);
596
603 template<typename FwdSk>
604 static void downsampling_merge(quantiles_sketch& tgt, FwdSk&& src);
605
606 template<typename FwdV>
607 static void zip_buffer_with_stride(FwdV&& buf_in, Level& buf_out, uint16_t stride);
608
616 static uint8_t lowest_zero_bit_starting_at(uint64_t bits, uint8_t starting_bit);
617
618 template<typename TT = T, typename std::enable_if<std::is_floating_point<TT>::value, int>::type = 0>
619 static inline bool check_update_item(TT item) {
620 return !std::isnan(item);
621 }
622
623 template<typename TT = T, typename std::enable_if<!std::is_floating_point<TT>::value, int>::type = 0>
624 static inline bool check_update_item(TT) {
625 return true;
626 }
627
628 // for type converting constructor
629 template<typename From, typename FC, typename FA> friend class quantiles_sketch;
630};
631
632
633template<typename T, typename C, typename A>
634class quantiles_sketch<T, C, A>::const_iterator {
635public:
636 using iterator_category = std::input_iterator_tag;
637 using value_type = std::pair<const T&, const uint64_t>;
638 using difference_type = void;
639 using pointer = const return_value_holder<value_type>;
640 using reference = const value_type;
641
642 const_iterator& operator++();
643 const_iterator& operator++(int);
644 bool operator==(const const_iterator& other) const;
645 bool operator!=(const const_iterator& other) const;
646 reference operator*() const;
647 pointer operator->() const;
648private:
649 friend class quantiles_sketch<T, C, A>;
650 using Level = std::vector<T, A>;
651 using AllocLevel = typename std::allocator_traits<A>::template rebind_alloc<Level>;
652 Level base_buffer_;
653 std::vector<Level, AllocLevel> levels_;
654 int level_;
655 uint32_t index_;
656 uint32_t bb_count_;
657 uint64_t bit_pattern_;
658 uint64_t weight_;
659 uint16_t k_;
660 const_iterator(const Level& base_buffer, const std::vector<Level, AllocLevel>& levels, uint16_t k, uint64_t n, bool is_end);
661};
662
663} /* namespace datasketches */
664
665#include "quantiles_sketch_impl.hpp"
666
667#endif // _QUANTILES_SKETCH_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(uint16_t k=quantiles_constants::DEFAULT_K, const Comparator &comparator=Comparator(), const Allocator &allocator=Allocator())
Constructor.
quantiles_sketch & operator=(const quantiles_sketch &other)
Copy assignment.
Definition quantiles_sketch_impl.hpp:90
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 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
static quantiles_sketch deserialize(std::istream &is, const SerDe &sd=SerDe(), const Comparator &comparator=Comparator(), const Allocator &allocator=Allocator())
This method deserializes a sketch from a given stream.
double get_rank(const T &item, bool inclusive=true) const
Returns an approximation to the normalized rank of the given item from 0 to 1, inclusive.
Definition quantiles_sketch_impl.hpp:796
static quantiles_sketch deserialize(const void *bytes, size_t size, const SerDe &sd=SerDe(), const Comparator &comparator=Comparator(), const Allocator &allocator=Allocator())
This method deserializes a sketch from a given array of bytes.
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
quantiles_sketch(const quantiles_sketch< From, FC, FA > &other, const Comparator &comparator=Comparator(), const Allocator &allocator=Allocator())
Type converting constructor.
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
typename std::conditional< std::is_arithmetic< T >::value, T, const T & >::type quantile_return_type
Quantile return type.
Definition quantiles_sorted_view.hpp:101
Constants for Quantiles sketch.
Definition quantiles_sketch.hpp:35
const uint16_t MAX_K
maximum value of parameter K
Definition quantiles_sketch.hpp:41
const uint16_t MIN_K
minimum value of parameter K
Definition quantiles_sketch.hpp:39
const uint16_t DEFAULT_K
default value of parameter K
Definition quantiles_sketch.hpp:37
DataSketches namespace.
Definition binomial_bounds.hpp:38
Interface for serializing and deserializing items.
Definition serde.hpp:35