datasketches-cpp
Loading...
Searching...
No Matches
req_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 REQ_SKETCH_IMPL_HPP_
21#define REQ_SKETCH_IMPL_HPP_
22
23#include <limits>
24#include <sstream>
25#include <stdexcept>
26#include <type_traits>
27
28namespace datasketches {
29
30template<typename T, typename C, typename A>
31req_sketch<T, C, A>::req_sketch(uint16_t k, bool hra, const C& comparator, const A& allocator):
32comparator_(comparator),
33allocator_(allocator),
34k_(std::max<uint16_t>(static_cast<int>(k) & -2, static_cast<int>(req_constants::MIN_K))), //rounds down one if odd
35hra_(hra),
36max_nom_size_(0),
37num_retained_(0),
38n_(0),
39compactors_(allocator),
40min_item_(),
41max_item_(),
42sorted_view_(nullptr)
43{
44 if (k > req_constants::MAX_K) {
45 throw std::invalid_argument("K must be <= " + std::to_string(req_constants::MAX_K) + ": " + std::to_string(k));
46 }
47 grow();
48}
49
50template<typename T, typename C, typename A>
51req_sketch<T, C, A>::~req_sketch() {
52 reset_sorted_view();
53}
54
55template<typename T, typename C, typename A>
56req_sketch<T, C, A>::req_sketch(const req_sketch& other):
57comparator_(other.comparator_),
58allocator_(other.allocator_),
59k_(other.k_),
60hra_(other.hra_),
61max_nom_size_(other.max_nom_size_),
62num_retained_(other.num_retained_),
63n_(other.n_),
64compactors_(other.compactors_),
65min_item_(other.min_item_),
66max_item_(other.max_item_),
67sorted_view_(nullptr)
68{}
69
70template<typename T, typename C, typename A>
71req_sketch<T, C, A>::req_sketch(req_sketch&& other) noexcept :
72comparator_(std::move(other.comparator_)),
73allocator_(std::move(other.allocator_)),
74k_(other.k_),
75hra_(other.hra_),
76max_nom_size_(other.max_nom_size_),
77num_retained_(other.num_retained_),
78n_(other.n_),
79compactors_(std::move(other.compactors_)),
80min_item_(std::move(other.min_item_)),
81max_item_(std::move(other.max_item_)),
82sorted_view_(nullptr)
83{}
84
85template<typename T, typename C, typename A>
86req_sketch<T, C, A>& req_sketch<T, C, A>::operator=(const req_sketch& other) {
87 req_sketch copy(other);
88 std::swap(comparator_, copy.comparator_);
89 std::swap(allocator_, copy.allocator_);
90 std::swap(k_, copy.k_);
91 std::swap(hra_, copy.hra_);
92 std::swap(max_nom_size_, copy.max_nom_size_);
93 std::swap(num_retained_, copy.num_retained_);
94 std::swap(n_, copy.n_);
95 std::swap(compactors_, copy.compactors_);
96 std::swap(min_item_, copy.min_item_);
97 std::swap(max_item_, copy.max_item_);
98 reset_sorted_view();
99 return *this;
100}
101
102template<typename T, typename C, typename A>
103req_sketch<T, C, A>& req_sketch<T, C, A>::operator=(req_sketch&& other) {
104 std::swap(comparator_, other.comparator_);
105 std::swap(allocator_, other.allocator_);
106 std::swap(k_, other.k_);
107 std::swap(hra_, other.hra_);
108 std::swap(max_nom_size_, other.max_nom_size_);
109 std::swap(num_retained_, other.num_retained_);
110 std::swap(n_, other.n_);
111 std::swap(compactors_, other.compactors_);
112 std::swap(min_item_, other.min_item_);
113 std::swap(max_item_, other.max_item_);
114 reset_sorted_view();
115 return *this;
116}
117
118template<typename T, typename C, typename A>
119template<typename TT, typename CC, typename AA>
120req_sketch<T, C, A>::req_sketch(const req_sketch<TT, CC, AA>& other, const C& comparator, const A& allocator):
121comparator_(comparator),
122allocator_(allocator),
123k_(other.k_),
124hra_(other.hra_),
125max_nom_size_(other.max_nom_size_),
126num_retained_(other.num_retained_),
127n_(other.n_),
128compactors_(allocator),
129min_item_(other.min_item_),
130max_item_(other.max_item_),
131sorted_view_(nullptr)
132{
133 static_assert(
134 std::is_constructible<T, TT>::value,
135 "Type converting constructor requires new type to be constructible from existing type"
136 );
137 compactors_.reserve(other.compactors_.size());
138 for (const auto& compactor: other.compactors_) {
139 compactors_.push_back(req_compactor<T, C, A>(compactor, comparator_, allocator_));
140 }
141}
142
143template<typename T, typename C, typename A>
145 return k_;
146}
147
148template<typename T, typename C, typename A>
150 return hra_;
151}
152
153template<typename T, typename C, typename A>
155 return n_ == 0;
156}
157
158template<typename T, typename C, typename A>
160 return n_;
161}
162
163template<typename T, typename C, typename A>
165 return num_retained_;
166}
167
168template<typename T, typename C, typename A>
170 return compactors_.size() > 1;
171}
172
173template<typename T, typename C, typename A>
174template<typename FwdT>
176 if (!check_update_item(item)) { return; }
177 compactors_[0].reserve(); // first, so that a failure leaves the sketch unchanged
178 if (is_empty()) {
179 min_item_.emplace(item);
180 max_item_.emplace(item);
181 } else {
182 if (comparator_(item, *min_item_)) *min_item_ = item;
183 if (comparator_(*max_item_, item)) *max_item_ = item;
184 }
185 compactors_[0].append(std::forward<FwdT>(item));
186 ++num_retained_;
187 ++n_;
188 reset_sorted_view();
189 if (num_retained_ >= max_nom_size_) compress();
190}
191
192template<typename T, typename C, typename A>
193template<typename FwdSk>
194void req_sketch<T, C, A>::merge(FwdSk&& other) {
195 if (is_HRA() != other.is_HRA()) throw std::invalid_argument("merging HRA and LRA is not valid");
196 if (other.is_empty()) return;
197 reset_sorted_view();
198 const size_t num_levels = compactors_.size();
199 try {
200 // grow until this has at least as many compactors as other
201 while (get_num_levels() < other.get_num_levels()) grow();
202 if (is_empty()) {
203 min_item_.emplace(conditional_forward<FwdSk>(*other.min_item_));
204 max_item_.emplace(conditional_forward<FwdSk>(*other.max_item_));
205 } else {
206 if (comparator_(*other.min_item_, *min_item_)) *min_item_ = conditional_forward<FwdSk>(*other.min_item_);
207 if (comparator_(*max_item_, *other.max_item_)) *max_item_ = conditional_forward<FwdSk>(*other.max_item_);
208 }
209 // merge the items in all height compactors
210 for (size_t i = 0; i < other.get_num_levels(); ++i) {
211 compactors_[i].merge(conditional_forward<FwdSk>(other.compactors_[i]));
212 }
213 } catch (...) {
214 remove_empty_levels_above(num_levels);
215 restore_counts(); // some levels may be merged already
216 throw;
217 }
218 n_ += other.n_;
219 update_max_nom_size();
220 update_num_retained();
221 if (num_retained_ >= max_nom_size_) compress();
222}
223
224template<typename T, typename C, typename A>
226 compactors_[0].reserve();
227}
228
229template<typename T, typename C, typename A>
231 if (is_empty()) throw std::runtime_error("operation is undefined for an empty sketch");
232 return *min_item_;
233}
234
235template<typename T, typename C, typename A>
237 if (is_empty()) throw std::runtime_error("operation is undefined for an empty sketch");
238 return *max_item_;
239}
240
241template<typename T, typename C, typename A>
243 return comparator_;
244}
245
246template<typename T, typename C, typename A>
248 return allocator_;
249}
250
251template<typename T, typename C, typename A>
252double req_sketch<T, C, A>::get_rank(const T& item, bool inclusive) const {
253 if (is_empty()) throw std::runtime_error("operation is undefined for an empty sketch");
254 uint64_t weight = 0;
255 for (const auto& compactor: compactors_) {
256 weight += compactor.compute_weight(item, inclusive);
257 }
258 return static_cast<double>(weight) / n_;
259}
260
261template<typename T, typename C, typename A>
262auto req_sketch<T, C, A>::get_PMF(const T* split_points, uint32_t size, bool inclusive) const -> vector_double {
263 if (is_empty()) throw std::runtime_error("operation is undefined for an empty sketch");
264 setup_sorted_view();
265 return sorted_view_->get_PMF(split_points, size, inclusive);
266}
267
268template<typename T, typename C, typename A>
269auto req_sketch<T, C, A>::get_CDF(const T* split_points, uint32_t size, bool inclusive) const -> vector_double {
270 if (is_empty()) throw std::runtime_error("operation is undefined for an empty sketch");
271 setup_sorted_view();
272 return sorted_view_->get_CDF(split_points, size, inclusive);
273}
274
275template<typename T, typename C, typename A>
276auto req_sketch<T, C, A>::get_quantile(double rank, bool inclusive) const -> quantile_return_type {
277 if (is_empty()) throw std::runtime_error("operation is undefined for an empty sketch");
278 if ((rank < 0.0) || (rank > 1.0)) {
279 throw std::invalid_argument("Normalized rank cannot be less than 0 or greater than 1");
280 }
281 // possible side-effect of sorting level zero
282 setup_sorted_view();
283 return sorted_view_->get_quantile(rank, inclusive);
284}
285
286template<typename T, typename C, typename A>
288 if (!compactors_[0].is_sorted()) {
289 const_cast<Compactor&>(compactors_[0]).sort(); // allow this side effect
290 }
291 quantiles_sorted_view<T, C, A> view(get_num_retained(), comparator_, allocator_);
292
293 for (auto& compactor: compactors_) {
294 view.add(compactor.begin(), compactor.end(), 1ULL << compactor.get_lg_weight());
295 }
296
297 view.convert_to_cummulative();
298 return view;
299}
300
301template<typename T, typename C, typename A>
302double req_sketch<T, C, A>::get_rank_lower_bound(double rank, uint8_t num_std_dev) const {
303 return get_rank_lb(get_k(), get_num_levels(), rank, num_std_dev, get_n(), hra_);
304}
305
306template<typename T, typename C, typename A>
307double req_sketch<T, C, A>::get_rank_upper_bound(double rank, uint8_t num_std_dev) const {
308 return get_rank_ub(get_k(), get_num_levels(), rank, num_std_dev, get_n(), hra_);
309}
310
311template<typename T, typename C, typename A>
312double req_sketch<T, C, A>::get_RSE(uint16_t k, double rank, bool hra, uint64_t n) {
313 return get_rank_ub(k, 2, rank, 1, n, hra) - rank;
314}
315
316template<typename T, typename C, typename A>
317double req_sketch<T, C, A>::get_rank_lb(uint16_t k, uint8_t num_levels, double rank, uint8_t num_std_dev, uint64_t n, bool hra) {
318 if (is_exact_rank(k, num_levels, rank, n, hra)) return rank;
319 const double relative = relative_rse_factor() / k * (hra ? 1.0 - rank : rank);
320 const double fixed = FIXED_RSE_FACTOR / k;
321 const double lb_rel = rank - num_std_dev * relative;
322 const double lb_fix = rank - num_std_dev * fixed;
323 return std::max(lb_rel, lb_fix);
324}
325
326template<typename T, typename C, typename A>
327double req_sketch<T, C, A>::get_rank_ub(uint16_t k, uint8_t num_levels, double rank, uint8_t num_std_dev, uint64_t n, bool hra) {
328 if (is_exact_rank(k, num_levels, rank, n, hra)) return rank;
329 const double relative = relative_rse_factor() / k * (hra ? 1.0 - rank : rank);
330 const double fixed = FIXED_RSE_FACTOR / k;
331 const double ub_rel = rank + num_std_dev * relative;
332 const double ub_fix = rank + num_std_dev * fixed;
333 return std::min(ub_rel, ub_fix);
334}
335
336template<typename T, typename C, typename A>
337bool req_sketch<T, C, A>::is_exact_rank(uint16_t k, uint8_t num_levels, double rank, uint64_t n, bool hra) {
338 const unsigned base_cap = k * req_constants::INIT_NUM_SECTIONS;
339 if (num_levels == 1 || n <= base_cap) return true;
340 const double exact_rank_thresh = static_cast<double>(base_cap) / n;
341 return (hra && rank >= 1.0 - exact_rank_thresh) || (!hra && rank <= exact_rank_thresh);
342}
343
344template<typename T, typename C, typename A>
345double req_sketch<T, C, A>::relative_rse_factor() {
346 return sqrt(0.0512 / req_constants::INIT_NUM_SECTIONS);
347}
348
349// implementation for fixed-size arithmetic types (integral and floating point)
350template<typename T, typename C, typename A>
351template<typename TT, typename SerDe, typename std::enable_if<std::is_arithmetic<TT>::value, int>::type>
353 size_t size = PREAMBLE_SIZE_BYTES;
354 if (is_empty()) return size;
355 if (is_estimation_mode()) {
356 size += sizeof(n_) + sizeof(TT) * 2; // min and max
357 }
358 if (n_ <= req_constants::MIN_K) { // raw items, without a compactor header
359 size += sizeof(TT) * static_cast<size_t>(n_);
360 } else {
361 for (const auto& compactor: compactors_) size += compactor.get_serialized_size_bytes(sd);
362 }
363 return size;
364}
365
366// implementation for all other types
367template<typename T, typename C, typename A>
368template<typename TT, typename SerDe, typename std::enable_if<!std::is_arithmetic<TT>::value, int>::type>
369size_t req_sketch<T, C, A>::get_serialized_size_bytes(const SerDe& sd) const {
370 size_t size = PREAMBLE_SIZE_BYTES;
371 if (is_empty()) return size;
372 if (is_estimation_mode()) {
373 size += sizeof(n_);
374 size += sd.size_of_item(*min_item_);
375 size += sd.size_of_item(*max_item_);
376 }
377 if (n_ <= req_constants::MIN_K) { // raw items, without a compactor header
378 for (auto it = compactors_[0].begin(); it != compactors_[0].end(); ++it) size += sd.size_of_item(*it);
379 } else {
380 for (const auto& compactor: compactors_) size += compactor.get_serialized_size_bytes(sd);
381 }
382 return size;
383}
384
385template<typename T, typename C, typename A>
386template<typename SerDe>
387void req_sketch<T, C, A>::serialize(std::ostream& os, const SerDe& sd) const {
388 const uint8_t preamble_ints = is_estimation_mode() ? 4 : 2;
389 write(os, preamble_ints);
390 const uint8_t serial_version = SERIAL_VERSION;
391 write(os, serial_version);
392 const uint8_t family = FAMILY;
393 write(os, family);
394 const bool raw_items = n_ <= req_constants::MIN_K;
395 const uint8_t flags_byte(
396 (is_empty() ? 1 << flags::IS_EMPTY : 0)
397 | (hra_ ? 1 << flags::IS_HIGH_RANK : 0)
398 | (raw_items ? 1 << flags::RAW_ITEMS : 0)
399 | (compactors_[0].is_sorted() ? 1 << flags::IS_LEVEL_ZERO_SORTED : 0)
400 );
401 write(os, flags_byte);
402 write(os, k_);
403 const uint8_t num_levels = is_empty() ? 0 : get_num_levels();
404 write(os, num_levels);
405 const uint8_t num_raw_items = raw_items ? static_cast<uint8_t>(n_) : 0;
406 write(os, num_raw_items);
407 if (is_empty()) return;
408 if (is_estimation_mode()) {
409 write(os, n_);
410 sd.serialize(os, &*min_item_, 1);
411 sd.serialize(os, &*max_item_, 1);
412 }
413 if (raw_items) {
414 sd.serialize(os, compactors_[0].begin(), num_raw_items);
415 } else {
416 for (const auto& compactor: compactors_) compactor.serialize(os, sd);
417 }
418}
419
420template<typename T, typename C, typename A>
421template<typename SerDe>
422auto req_sketch<T, C, A>::serialize(unsigned header_size_bytes, const SerDe& sd) const -> vector_bytes {
423 const size_t size = header_size_bytes + get_serialized_size_bytes(sd);
424 vector_bytes bytes(size, 0, allocator_);
425 uint8_t* ptr = bytes.data() + header_size_bytes;
426 const uint8_t* end_ptr = bytes.data() + size;
427
428 const uint8_t preamble_ints = is_estimation_mode() ? 4 : 2;
429 ptr += copy_to_mem(preamble_ints, ptr);
430 const uint8_t serial_version = SERIAL_VERSION;
431 ptr += copy_to_mem(serial_version, ptr);
432 const uint8_t family = FAMILY;
433 ptr += copy_to_mem(family, ptr);
434 const bool raw_items = n_ <= req_constants::MIN_K;
435 const uint8_t flags_byte(
436 (is_empty() ? 1 << flags::IS_EMPTY : 0)
437 | (hra_ ? 1 << flags::IS_HIGH_RANK : 0)
438 | (raw_items ? 1 << flags::RAW_ITEMS : 0)
439 | (compactors_[0].is_sorted() ? 1 << flags::IS_LEVEL_ZERO_SORTED : 0)
440 );
441 ptr += copy_to_mem(flags_byte, ptr);
442 ptr += copy_to_mem(k_, ptr);
443 const uint8_t num_levels = is_empty() ? 0 : get_num_levels();
444 ptr += copy_to_mem(num_levels, ptr);
445 const uint8_t num_raw_items = raw_items ? static_cast<uint8_t>(n_) : 0;
446 ptr += copy_to_mem(num_raw_items, ptr);
447 if (!is_empty()) {
448 if (is_estimation_mode()) {
449 ptr += copy_to_mem(n_, ptr);
450 ptr += sd.serialize(ptr, end_ptr - ptr, &*min_item_, 1);
451 ptr += sd.serialize(ptr, end_ptr - ptr, &*max_item_, 1);
452 }
453 if (raw_items) {
454 ptr += sd.serialize(ptr, end_ptr - ptr, compactors_[0].begin(), num_raw_items);
455 } else {
456 for (const auto& compactor: compactors_) ptr += compactor.serialize(ptr, end_ptr - ptr, sd);
457 }
458 }
459 return bytes;
460}
461
462template<typename T, typename C, typename A>
463template<typename SerDe>
464req_sketch<T, C, A> req_sketch<T, C, A>::deserialize(std::istream& is, const SerDe& sd, const C& comparator, const A& allocator) {
465 const auto preamble_ints = read<uint8_t>(is);
466 const auto serial_version = read<uint8_t>(is);
467 const auto family_id = read<uint8_t>(is);
468 const auto flags_byte = read<uint8_t>(is);
469 const auto k = read<uint16_t>(is);
470 const auto num_levels = read<uint8_t>(is);
471 const auto num_raw_items = read<uint8_t>(is);
472
473 check_k(k);
474 check_preamble_ints(preamble_ints, num_levels);
475 check_serial_version(serial_version);
476 check_family_id(family_id);
477
478 if (!is.good()) throw std::runtime_error("error reading from std::istream");
479 const bool is_empty = flags_byte & (1 << flags::IS_EMPTY);
480 const bool hra = flags_byte & (1 << flags::IS_HIGH_RANK);
481 if (is_empty) return req_sketch(k, hra, comparator, allocator);
482
483 optional<T> min_item;
484 optional<T> max_item;
485
486 const bool raw_items = flags_byte & (1 << flags::RAW_ITEMS);
487 check_num_levels(num_levels, raw_items);
488 const bool is_level_0_sorted = flags_byte & (1 << flags::IS_LEVEL_ZERO_SORTED);
489 std::vector<Compactor, AllocCompactor> compactors(allocator);
490
491 uint64_t n = 1;
492 if (num_levels > 1) {
493 n = read<uint64_t>(is);
494 // Space to deserialize min and max.
495 // serde::deserialize expects allocated but not initialized storage.
496 typename std::aligned_storage<sizeof(T), alignof(T)>::type tmp_storage;
497 T* tmp = reinterpret_cast<T*>(&tmp_storage);
498
499 sd.deserialize(is, tmp, 1);
500 // serde call did not throw, repackage and cleanup
501 min_item.emplace(std::move(*tmp));
502 tmp->~T();
503 sd.deserialize(is, tmp, 1);
504 // serde call did not throw, repackage and cleanup
505 max_item.emplace(std::move(*tmp));
506 tmp->~T();
507 }
508
509 if (raw_items) {
510 compactors.push_back(Compactor::deserialize(is, sd, comparator, allocator, is_level_0_sorted, k, num_raw_items, hra));
511 } else {
512 for (size_t i = 0; i < num_levels; ++i) {
513 compactors.push_back(Compactor::deserialize(is, sd, comparator, allocator, i == 0 ? is_level_0_sorted : true, hra,
514 k, static_cast<uint8_t>(i)));
515 }
516 }
517 if (num_levels > 1) check_n(n, compactors);
518 if (num_levels == 1) {
519 if (compactors[0].get_num_items() == 0) throw std::invalid_argument("Possible corruption: non-empty sketch with no items");
520 const auto begin = compactors[0].begin();
521 const auto end = compactors[0].end();
522 n = compactors[0].get_num_items();
523 auto min_it = begin;
524 auto max_it = begin;
525 for (auto it = begin; it != end; ++it) {
526 if (comparator(*it, *min_it)) min_it = it;
527 if (comparator(*max_it, *it)) max_it = it;
528 }
529 min_item.emplace(*min_it);
530 max_item.emplace(*max_it);
531 }
532
533 if (!is.good()) throw std::runtime_error("error reading from std::istream");
534 return req_sketch(k, hra, n, std::move(min_item), std::move(max_item), std::move(compactors), comparator);
535}
536
537template<typename T, typename C, typename A>
538template<typename SerDe>
539req_sketch<T, C, A> req_sketch<T, C, A>::deserialize(const void* bytes, size_t size, const SerDe& sd, const C& comparator, const A& allocator) {
540 ensure_minimum_memory(size, 8);
541 const char* ptr = static_cast<const char*>(bytes);
542 const char* end_ptr = static_cast<const char*>(bytes) + size;
543
544 uint8_t preamble_ints;
545 ptr += copy_from_mem(ptr, preamble_ints);
546 uint8_t serial_version;
547 ptr += copy_from_mem(ptr, serial_version);
548 uint8_t family_id;
549 ptr += copy_from_mem(ptr, family_id);
550 uint8_t flags_byte;
551 ptr += copy_from_mem(ptr, flags_byte);
552 uint16_t k;
553 ptr += copy_from_mem(ptr, k);
554 uint8_t num_levels;
555 ptr += copy_from_mem(ptr, num_levels);
556 uint8_t num_raw_items;
557 ptr += copy_from_mem(ptr, num_raw_items);
558
559 check_k(k);
560 check_preamble_ints(preamble_ints, num_levels);
561 check_serial_version(serial_version);
562 check_family_id(family_id);
563
564 const bool is_empty = flags_byte & (1 << flags::IS_EMPTY);
565 const bool hra = flags_byte & (1 << flags::IS_HIGH_RANK);
566 if (is_empty) return req_sketch(k, hra, comparator, allocator);
567
568 optional<T> min_item;
569 optional<T> max_item;
570
571 const bool raw_items = flags_byte & (1 << flags::RAW_ITEMS);
572 check_num_levels(num_levels, raw_items);
573 const bool is_level_0_sorted = flags_byte & (1 << flags::IS_LEVEL_ZERO_SORTED);
574 std::vector<Compactor, AllocCompactor> compactors(allocator);
575
576 uint64_t n = 1;
577 if (num_levels > 1) {
578 ensure_minimum_memory(end_ptr - ptr, sizeof(n));
579 ptr += copy_from_mem(ptr, n);
580 // Space to deserialize min and max.
581 // serde::deserialize expects allocated but not initialized storage.
582 typename std::aligned_storage<sizeof(T), alignof(T)>::type tmp_storage;
583 T* tmp = reinterpret_cast<T*>(&tmp_storage);
584
585 ptr += sd.deserialize(ptr, end_ptr - ptr, tmp, 1);
586 // serde call did not throw, repackage and cleanup
587 min_item.emplace(std::move(*tmp));
588 tmp->~T();
589 ptr += sd.deserialize(ptr, end_ptr - ptr, tmp, 1);
590 // serde call did not throw, repackage and cleanup
591 max_item.emplace(std::move(*tmp));
592 tmp->~T();
593 }
594
595 if (raw_items) {
596 auto pair = Compactor::deserialize(ptr, end_ptr - ptr, sd, comparator, allocator, is_level_0_sorted, k, num_raw_items, hra);
597 compactors.push_back(std::move(pair.first));
598 ptr += pair.second;
599 } else {
600 for (size_t i = 0; i < num_levels; ++i) {
601 auto pair = Compactor::deserialize(ptr, end_ptr - ptr, sd, comparator, allocator, i == 0 ? is_level_0_sorted : true, hra,
602 k, static_cast<uint8_t>(i));
603 compactors.push_back(std::move(pair.first));
604 ptr += pair.second;
605 }
606 }
607 if (num_levels > 1) check_n(n, compactors);
608 if (num_levels == 1) {
609 if (compactors[0].get_num_items() == 0) throw std::invalid_argument("Possible corruption: non-empty sketch with no items");
610 const auto begin = compactors[0].begin();
611 const auto end = compactors[0].end();
612 n = compactors[0].get_num_items();
613 auto min_it = begin;
614 auto max_it = begin;
615 for (auto it = begin; it != end; ++it) {
616 if (comparator(*it, *min_it)) min_it = it;
617 if (comparator(*max_it, *it)) max_it = it;
618 }
619 min_item.emplace(*min_it);
620 max_item.emplace(*max_it);
621 }
622
623 return req_sketch(k, hra, n, std::move(min_item), std::move(max_item), std::move(compactors), comparator);
624}
625
626template<typename T, typename C, typename A>
627void req_sketch<T, C, A>::check_n(uint64_t n, const std::vector<Compactor, AllocCompactor>& compactors) {
628 // compaction keeps the total weight, so it is always n
629 uint64_t total_weight = 0;
630 for (const auto& compactor: compactors) {
631 const uint64_t num_items = compactor.get_num_items();
632 // an empty compactor adds no weight, and its lg_weight can be 64 or more, too large to shift by
633 if (num_items == 0) continue;
634 const uint8_t lg_weight = compactor.get_lg_weight();
635 if (lg_weight >= 64 || num_items > ((std::numeric_limits<uint64_t>::max() - total_weight) >> lg_weight)) {
636 throw std::invalid_argument("Possible corruption: the total weight of the retained items overflows");
637 }
638 total_weight += num_items << lg_weight;
639 }
640 if (n != total_weight) {
641 throw std::invalid_argument("Possible corruption: n " + std::to_string(n)
642 + " is not the total weight of the retained items " + std::to_string(total_weight));
643 }
644}
645
646template<typename T, typename C, typename A>
647void req_sketch<T, C, A>::grow() {
648 const uint8_t lg_weight = get_num_levels();
649 compactors_.push_back(Compactor(hra_, lg_weight, k_, comparator_, allocator_));
650 update_max_nom_size();
651}
652
653template<typename T, typename C, typename A>
654uint8_t req_sketch<T, C, A>::get_num_levels() const {
655 return static_cast<uint8_t>(compactors_.size());
656}
657
658template<typename T, typename C, typename A>
659void req_sketch<T, C, A>::update_max_nom_size() {
660 max_nom_size_ = 0;
661 for (const auto& compactor: compactors_) max_nom_size_ += compactor.get_nom_capacity();
662}
663
664template<typename T, typename C, typename A>
665void req_sketch<T, C, A>::update_num_retained() {
666 num_retained_ = 0;
667 for (const auto& compactor: compactors_) num_retained_ += compactor.get_num_items();
668}
669
670template<typename T, typename C, typename A>
671void req_sketch<T, C, A>::restore_counts() {
672 // the total weight of the retained items is always n
673 n_ = 0;
674 for (const auto& compactor: compactors_) n_ += static_cast<uint64_t>(compactor.get_num_items()) << compactor.get_lg_weight();
675 update_num_retained();
676 update_max_nom_size();
677}
678
679template<typename T, typename C, typename A>
680void req_sketch<T, C, A>::compress() {
681 const size_t num_levels = compactors_.size();
682 try {
683 compress_levels();
684 } catch (...) {
685 remove_empty_levels_above(num_levels); // a level can be added, and then the compaction into it fail
686 restore_counts(); // a compactor can fail to grow after a compaction moved its items
687 throw;
688 }
689}
690
691template<typename T, typename C, typename A>
692void req_sketch<T, C, A>::remove_empty_levels_above(size_t num_levels) {
693 while (compactors_.size() > num_levels && compactors_.back().get_num_items() == 0) compactors_.pop_back();
694}
695
696template<typename T, typename C, typename A>
697void req_sketch<T, C, A>::compress_levels() {
698 for (size_t h = 0; h < compactors_.size(); ++h) {
699 if (compactors_[h].get_num_items() >= compactors_[h].get_nom_capacity()) {
700 if (h == 0) compactors_[0].sort();
701 if (h + 1 >= get_num_levels()) { // at the top?
702 grow(); // add a level, increases max_nom_size
703 }
704 auto pair = compactors_[h].compact(compactors_[h + 1]);
705 num_retained_ -= pair.first;
706 max_nom_size_ += pair.second;
707 if (LAZY_COMPRESSION && num_retained_ < max_nom_size_) break;
708 }
709 }
710}
711
712template<typename T, typename C, typename A>
713string<A> req_sketch<T, C, A>::to_string(bool print_levels, bool print_items) const {
714 // Using a temporary stream for implementation here does not comply with AllocatorAwareContainer requirements.
715 // The stream does not support passing an allocator instance, and alternatives are complicated.
716 std::ostringstream os;
717 os << "### REQ sketch summary:" << std::endl;
718 os << " K : " << k_ << std::endl;
719 os << " High Rank Acc : " << (hra_ ? "true" : "false") << std::endl;
720 os << " Empty : " << (is_empty() ? "true" : "false") << std::endl;
721 os << " Estimation mode: " << (is_estimation_mode() ? "true" : "false") << std::endl;
722 os << " Sorted : " << (compactors_[0].is_sorted() ? "true" : "false") << std::endl;
723 os << " N : " << n_ << std::endl;
724 os << " Levels : " << compactors_.size() << std::endl;
725 os << " Retained items : " << num_retained_ << std::endl;
726 os << " Capacity items : " << max_nom_size_ << std::endl;
727 if (!is_empty()) {
728 os << " Min item : " << *min_item_ << std::endl;
729 os << " Max item : " << *max_item_ << std::endl;
730 }
731 os << "### End sketch summary" << std::endl;
732
733 if (print_levels) {
734 os << "### REQ sketch levels:" << std::endl;
735 os << " index: nominal capacity, actual size" << std::endl;
736 for (uint8_t i = 0; i < compactors_.size(); i++) {
737 os << " " << (unsigned int) i << ": "
738 << compactors_[i].get_nom_capacity() << ", "
739 << compactors_[i].get_num_items() << std::endl;
740 }
741 os << "### End sketch levels" << std::endl;
742 }
743
744 if (print_items) {
745 os << "### REQ sketch data:" << std::endl;
746 unsigned level = 0;
747 for (const auto& compactor: compactors_) {
748 os << " level " << level << ": " << std::endl;
749 for (auto it = compactor.begin(); it != compactor.end(); ++it) {
750 os << " " << *it << std::endl;
751 }
752 ++level;
753 }
754 os << "### End sketch data" << std::endl;
755 }
756 return string<A>(os.str().c_str(), allocator_);
757}
758
759template<typename T, typename C, typename A>
760req_sketch<T, C, A>::req_sketch(uint16_t k, bool hra, uint64_t n,
761 optional<T>&& min_item, optional<T>&& max_item,
762 std::vector<Compactor, AllocCompactor>&& compactors, const C& comparator):
763comparator_(comparator),
764allocator_(compactors.get_allocator()),
765k_(k),
766hra_(hra),
767max_nom_size_(0),
768num_retained_(0),
769n_(n),
770compactors_(std::move(compactors)),
771min_item_(std::move(min_item)),
772max_item_(std::move(max_item)),
773sorted_view_(nullptr)
774{
775 update_max_nom_size();
776 update_num_retained();
777}
778
779template<typename T, typename C, typename A>
780void req_sketch<T, C, A>::check_k(uint16_t k) {
781 if (k < req_constants::MIN_K || k > req_constants::MAX_K || (k & 1) != 0) {
782 throw std::invalid_argument("Possible corruption: k must be even and in the range ["
783 + std::to_string(req_constants::MIN_K) + ", " + std::to_string(req_constants::MAX_K) + "]: " + std::to_string(k));
784 }
785}
786
787template<typename T, typename C, typename A>
788void req_sketch<T, C, A>::check_num_levels(uint8_t num_levels, bool raw_items) {
789 // a non-empty sketch has at least one compactor, and raw items fit in one
790 if (num_levels == 0 || num_levels > 64 || (raw_items && num_levels != 1)) {
791 throw std::invalid_argument("Possible corruption: number of levels " + std::to_string(num_levels)
792 + (raw_items ? " with raw items" : ""));
793 }
794}
795
796template<typename T, typename C, typename A>
797void req_sketch<T, C, A>::check_preamble_ints(uint8_t preamble_ints, uint8_t num_levels) {
798 const uint8_t expected_preamble_ints = num_levels > 1 ? 4 : 2;
799 if (preamble_ints != expected_preamble_ints) {
800 throw std::invalid_argument("Possible corruption: preamble ints must be "
801 + std::to_string(expected_preamble_ints) + ", got " + std::to_string(preamble_ints));
802 }
803}
804
805template<typename T, typename C, typename A>
806void req_sketch<T, C, A>::check_serial_version(uint8_t serial_version) {
807 if (serial_version != SERIAL_VERSION) {
808 throw std::invalid_argument("Possible corruption: serial version mismatch: expected "
809 + std::to_string(SERIAL_VERSION)
810 + ", got " + std::to_string(serial_version));
811 }
812}
813
814template<typename T, typename C, typename A>
815void req_sketch<T, C, A>::check_family_id(uint8_t family_id) {
816 if (family_id != FAMILY) {
817 throw std::invalid_argument("Possible corruption: family mismatch: expected "
818 + std::to_string(FAMILY) + ", got " + std::to_string(family_id));
819 }
820}
821
822template<typename T, typename C, typename A>
823auto req_sketch<T, C, A>::begin() const -> const_iterator {
824 return const_iterator(compactors_.begin(), compactors_.end());
825}
826
827template<typename T, typename C, typename A>
828auto req_sketch<T, C, A>::end() const -> const_iterator {
829 return const_iterator(compactors_.end(), compactors_.end());
830}
831
832template<typename T, typename C, typename A>
833void req_sketch<T, C, A>::setup_sorted_view() const {
834 if (sorted_view_ == nullptr) {
835 using AllocSortedView = typename std::allocator_traits<A>::template rebind_alloc<quantiles_sorted_view<T, C, A>>;
836 sorted_view_ = new (AllocSortedView(allocator_).allocate(1)) quantiles_sorted_view<T, C, A>(get_sorted_view());
837 }
838}
839
840template<typename T, typename C, typename A>
841void req_sketch<T, C, A>::reset_sorted_view() {
842 if (sorted_view_ != nullptr) {
843 sorted_view_->~quantiles_sorted_view();
844 using AllocSortedView = typename std::allocator_traits<A>::template rebind_alloc<quantiles_sorted_view<T, C, A>>;
845 AllocSortedView(allocator_).deallocate(sorted_view_, 1);
846 sorted_view_ = nullptr;
847 }
848}
849
850// iterator
851
852template<typename T, typename C, typename A>
853req_sketch<T, C, A>::const_iterator::const_iterator(LevelsIterator begin, LevelsIterator end):
854 levels_it_(begin),
855 levels_end_(end),
856 compactor_it_(nullptr)
857{
858 skip_empty_levels();
859}
860
861template<typename T, typename C, typename A>
862void req_sketch<T, C, A>::const_iterator::skip_empty_levels() {
863 while (levels_it_ != levels_end_ && (*levels_it_).get_num_items() == 0) ++levels_it_;
864 if (levels_it_ != levels_end_) compactor_it_ = (*levels_it_).begin();
865}
866
867template<typename T, typename C, typename A>
868auto req_sketch<T, C, A>::const_iterator::operator++() -> const_iterator& {
869 ++compactor_it_;
870 if (compactor_it_ == (*levels_it_).end()) {
871 ++levels_it_;
872 skip_empty_levels();
873 }
874 return *this;
875}
876
877template<typename T, typename C, typename A>
878auto req_sketch<T, C, A>::const_iterator::operator++(int) -> const_iterator& {
879 const_iterator tmp(*this);
880 operator++();
881 return tmp;
882}
883
884template<typename T, typename C, typename A>
885bool req_sketch<T, C, A>::const_iterator::operator==(const const_iterator& other) const {
886 if (levels_it_ != other.levels_it_) return false;
887 if (levels_it_ == levels_end_) return true;
888 return compactor_it_ == other.compactor_it_;
889}
890
891template<typename T, typename C, typename A>
892bool req_sketch<T, C, A>::const_iterator::operator!=(const const_iterator& other) const {
893 return !operator==(other);
894}
895
896template<typename T, typename C, typename A>
897auto req_sketch<T, C, A>::const_iterator::operator*() const -> reference {
898 return value_type(*compactor_it_, 1ULL << (*levels_it_).get_lg_weight());
899}
900
901template<typename T, typename C, typename A>
902auto req_sketch<T, C, A>::const_iterator::operator->() const -> pointer {
903 return **this;
904}
905
906} /* namespace datasketches */
907
908#endif
Sorted view for quantiles sketches (REQ, KLL and Quantiles).
Definition quantiles_sorted_view.hpp:40
Relative Error Quantiles Sketch.
Definition req_sketch.hpp:91
void reserve()
Allocates storage for items now, rather than on the first update or merge.
Definition req_sketch_impl.hpp:225
Comparator get_comparator() const
Returns an instance of the comparator for this sketch.
Definition req_sketch_impl.hpp:242
quantiles_sorted_view< T, Comparator, Allocator > get_sorted_view() const
Gets the sorted view of this sketch.
Definition req_sketch_impl.hpp:287
static req_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.
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 req_sketch_impl.hpp:269
uint32_t get_num_retained() const
Returns the number of retained items in the sketch.
Definition req_sketch_impl.hpp:164
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 req_sketch_impl.hpp:262
void merge(FwdSk &&other)
Merges another sketch into this one.
Definition req_sketch_impl.hpp:194
typename quantiles_sorted_view< T, Comparator, Allocator >::quantile_return_type quantile_return_type
Quantile return type.
Definition req_sketch.hpp:104
void update(FwdT &&item)
Updates this sketch with the given data item.
Definition req_sketch_impl.hpp:175
void serialize(std::ostream &os, const SerDe &sd=SerDe()) const
This method serializes the sketch into a given stream in a binary form.
Definition req_sketch_impl.hpp:387
string< Allocator > to_string(bool print_levels=false, bool print_items=false) const
Prints a summary of the sketch.
Definition req_sketch_impl.hpp:713
uint16_t get_k() const
Returns configured parameter K.
Definition req_sketch_impl.hpp:144
bool is_empty() const
Returns true if this sketch is empty.
Definition req_sketch_impl.hpp:154
const T & get_max_item() const
Returns the max item of the stream.
Definition req_sketch_impl.hpp:236
double get_rank_upper_bound(double rank, uint8_t num_std_dev) const
Returns an approximate upper bound of the given normalized rank.
Definition req_sketch_impl.hpp:307
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 req_sketch_impl.hpp:252
static double get_RSE(uint16_t k, double rank, bool hra, uint64_t n)
Returns an a priori estimate of relative standard error (RSE, expressed as a number in [0,...
Definition req_sketch_impl.hpp:312
double get_rank_lower_bound(double rank, uint8_t num_std_dev) const
Returns an approximate lower bound of the given normalized rank.
Definition req_sketch_impl.hpp:302
Allocator get_allocator() const
Returns an instance of the allocator for this sketch.
Definition req_sketch_impl.hpp:247
req_sketch & operator=(const req_sketch &other)
Copy assignment.
Definition req_sketch_impl.hpp:86
quantile_return_type get_quantile(double rank, bool inclusive=true) const
Returns an approximate quantile of the given normalized rank.
Definition req_sketch_impl.hpp:276
const_iterator begin() const
Iterator pointing to the first item in the sketch.
Definition req_sketch_impl.hpp:823
size_t get_serialized_size_bytes(const SerDe &sd=SerDe()) const
Computes size needed to serialize the current state of the sketch.
Definition req_sketch_impl.hpp:352
const_iterator end() const
Iterator pointing to the past-the-end item in the sketch.
Definition req_sketch_impl.hpp:828
bool is_estimation_mode() const
Returns true if this sketch is in estimation mode.
Definition req_sketch_impl.hpp:169
const T & get_min_item() const
Returns the min item of the stream.
Definition req_sketch_impl.hpp:230
bool is_HRA() const
Returns configured parameter High Rank Accuracy.
Definition req_sketch_impl.hpp:149
uint64_t get_n() const
Returns the length of the input stream.
Definition req_sketch_impl.hpp:159
const uint16_t MIN_K
min value of parameter K
Definition kll_sketch.hpp:39
REQ sketch constants.
Definition req_common.hpp:31
const uint8_t INIT_NUM_SECTIONS
initial number of sections
Definition req_common.hpp:37
const uint16_t MAX_K
maximum value of parameter K
Definition req_common.hpp:35
const uint16_t MIN_K
minimum value of parameter K
Definition req_common.hpp:33
DataSketches namespace.
Definition binomial_bounds.hpp:38