/
var_opt_sketch_impl.hpp
1755 lines (1508 loc) · 58.6 KB
/
var_opt_sketch_impl.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#ifndef _VAR_OPT_SKETCH_IMPL_HPP_
#define _VAR_OPT_SKETCH_IMPL_HPP_
#include <memory>
#include <sstream>
#include <cmath>
#include <random>
#include <algorithm>
#include "var_opt_sketch.hpp"
#include "serde.hpp"
#include "bounds_binomial_proportions.hpp"
#include "count_zeros.hpp"
#include "memory_operations.hpp"
#include "ceiling_power_of_2.hpp"
namespace datasketches {
/**
* Implementation code for the VarOpt sketch.
*
* author Kevin Lang
* author Jon Malkin
*/
template<typename T, typename S, typename A>
var_opt_sketch<T,S,A>::var_opt_sketch(uint32_t k, resize_factor rf, const A& allocator) :
var_opt_sketch<T,S,A>(k, rf, false, allocator) {}
template<typename T, typename S, typename A>
var_opt_sketch<T,S,A>::var_opt_sketch(const var_opt_sketch& other) :
k_(other.k_),
h_(other.h_),
m_(other.m_),
r_(other.r_),
n_(other.n_),
total_wt_r_(other.total_wt_r_),
rf_(other.rf_),
curr_items_alloc_(other.curr_items_alloc_),
filled_data_(other.filled_data_),
allocator_(other.allocator_),
data_(nullptr),
weights_(nullptr),
num_marks_in_h_(other.num_marks_in_h_),
marks_(nullptr)
{
data_ = allocator_.allocate(curr_items_alloc_);
// skip gap or anything unused at the end
for (size_t i = 0; i < h_; ++i)
new (&data_[i]) T(other.data_[i]);
for (size_t i = h_ + 1; i < h_ + r_ + 1; ++i)
new (&data_[i]) T(other.data_[i]);
// we skipped the gap
filled_data_ = false;
weights_ = AllocDouble(allocator_).allocate(curr_items_alloc_);
// doubles so can successfully copy regardless of the internal state
std::copy(other.weights_, other.weights_ + curr_items_alloc_, weights_);
if (other.marks_ != nullptr) {
marks_ = AllocBool(allocator_).allocate(curr_items_alloc_);
std::copy(other.marks_, other.marks_ + curr_items_alloc_, marks_);
}
}
template<typename T, typename S, typename A>
var_opt_sketch<T,S,A>::var_opt_sketch(const var_opt_sketch& other, bool as_sketch, uint64_t adjusted_n) :
k_(other.k_),
h_(other.h_),
m_(other.m_),
r_(other.r_),
n_(adjusted_n),
total_wt_r_(other.total_wt_r_),
rf_(other.rf_),
curr_items_alloc_(other.curr_items_alloc_),
filled_data_(other.filled_data_),
allocator_(other.allocator_),
data_(nullptr),
weights_(nullptr),
num_marks_in_h_(other.num_marks_in_h_),
marks_(nullptr)
{
data_ = allocator_.allocate(curr_items_alloc_);
// skip gap or anything unused at the end
for (size_t i = 0; i < h_; ++i)
new (&data_[i]) T(other.data_[i]);
for (size_t i = h_ + 1; i < h_ + r_ + 1; ++i)
new (&data_[i]) T(other.data_[i]);
// we skipped the gap
filled_data_ = false;
weights_ = AllocDouble(allocator_).allocate(curr_items_alloc_);
// doubles so can successfully copy regardless of the internal state
std::copy(other.weights_, other.weights_ + curr_items_alloc_, weights_);
if (!as_sketch && other.marks_ != nullptr) {
marks_ = AllocBool(allocator_).allocate(curr_items_alloc_);
std::copy(other.marks_, other.marks_ + curr_items_alloc_, marks_);
}
}
template<typename T, typename S, typename A>
var_opt_sketch<T,S,A>::var_opt_sketch(T* data, double* weights, size_t len,
uint32_t k, uint64_t n, uint32_t h_count, uint32_t r_count, double total_wt_r, const A& allocator) :
k_(k),
h_(h_count),
m_(0),
r_(r_count),
n_(n),
total_wt_r_(total_wt_r),
rf_(var_opt_constants::DEFAULT_RESIZE_FACTOR),
curr_items_alloc_(len),
filled_data_(n > k),
allocator_(allocator),
data_(data),
weights_(weights),
num_marks_in_h_(0),
marks_(nullptr)
{}
template<typename T, typename S, typename A>
var_opt_sketch<T,S,A>::var_opt_sketch(var_opt_sketch&& other) noexcept :
k_(other.k_),
h_(other.h_),
m_(other.m_),
r_(other.r_),
n_(other.n_),
total_wt_r_(other.total_wt_r_),
rf_(other.rf_),
curr_items_alloc_(other.curr_items_alloc_),
filled_data_(other.filled_data_),
allocator_(other.allocator_),
data_(other.data_),
weights_(other.weights_),
num_marks_in_h_(other.num_marks_in_h_),
marks_(other.marks_)
{
other.data_ = nullptr;
other.weights_ = nullptr;
other.marks_ = nullptr;
}
template<typename T, typename S, typename A>
var_opt_sketch<T,S,A>::var_opt_sketch(uint32_t k, resize_factor rf, bool is_gadget, const A& allocator) :
k_(k), h_(0), m_(0), r_(0), n_(0), total_wt_r_(0.0), rf_(rf), allocator_(allocator) {
if (k == 0 || k_ > MAX_K) {
throw std::invalid_argument("k must be at least 1 and less than 2^31 - 1");
}
uint32_t ceiling_lg_k = to_log_2(ceiling_power_of_2(k_));
uint32_t initial_lg_size = starting_sub_multiple(ceiling_lg_k, rf_, MIN_LG_ARR_ITEMS);
curr_items_alloc_ = get_adjusted_size(k_, 1 << initial_lg_size);
if (curr_items_alloc_ == k_) { // if full size, need to leave 1 for the gap
++curr_items_alloc_;
}
allocate_data_arrays(curr_items_alloc_, is_gadget);
num_marks_in_h_ = 0;
}
template<typename T, typename S, typename A>
var_opt_sketch<T,S,A>::var_opt_sketch(uint32_t k, uint32_t h, uint32_t m, uint32_t r, uint64_t n, double total_wt_r, resize_factor rf,
uint32_t curr_items_alloc, bool filled_data, std::unique_ptr<T, items_deleter> items,
std::unique_ptr<double, weights_deleter> weights, uint32_t num_marks_in_h,
std::unique_ptr<bool, marks_deleter> marks, const A& allocator) :
k_(k),
h_(h),
m_(m),
r_(r),
n_(n),
total_wt_r_(total_wt_r),
rf_(rf),
curr_items_alloc_(curr_items_alloc),
filled_data_(filled_data),
allocator_(allocator),
data_(items.release()),
weights_(weights.release()),
num_marks_in_h_(num_marks_in_h),
marks_(marks.release())
{}
template<typename T, typename S, typename A>
var_opt_sketch<T,S,A>::~var_opt_sketch() {
if (data_ != nullptr) {
if (filled_data_) {
// destroy everything
const size_t num_to_destroy = std::min(k_ + 1, curr_items_alloc_);
for (size_t i = 0; i < num_to_destroy; ++i) {
allocator_.destroy(data_ + i);
}
} else {
// skip gap or anything unused at the end
for (size_t i = 0; i < h_; ++i) {
allocator_.destroy(data_+ i);
}
for (size_t i = h_ + 1; i < h_ + r_ + 1; ++i) {
allocator_.destroy(data_ + i);
}
}
allocator_.deallocate(data_, curr_items_alloc_);
}
if (weights_ != nullptr) {
AllocDouble(allocator_).deallocate(weights_, curr_items_alloc_);
}
if (marks_ != nullptr) {
AllocBool(allocator_).deallocate(marks_, curr_items_alloc_);
}
}
template<typename T, typename S, typename A>
var_opt_sketch<T,S,A>& var_opt_sketch<T,S,A>::operator=(const var_opt_sketch& other) {
var_opt_sketch<T,S,A> sk_copy(other);
std::swap(k_, sk_copy.k_);
std::swap(h_, sk_copy.h_);
std::swap(m_, sk_copy.m_);
std::swap(r_, sk_copy.r_);
std::swap(n_, sk_copy.n_);
std::swap(total_wt_r_, sk_copy.total_wt_r_);
std::swap(rf_, sk_copy.rf_);
std::swap(curr_items_alloc_, sk_copy.curr_items_alloc_);
std::swap(filled_data_, sk_copy.filled_data_);
std::swap(allocator_, sk_copy.allocator_);
std::swap(data_, sk_copy.data_);
std::swap(weights_, sk_copy.weights_);
std::swap(num_marks_in_h_, sk_copy.num_marks_in_h_);
std::swap(marks_, sk_copy.marks_);
return *this;
}
template<typename T, typename S, typename A>
var_opt_sketch<T,S,A>& var_opt_sketch<T,S,A>::operator=(var_opt_sketch&& other) {
std::swap(k_, other.k_);
std::swap(h_, other.h_);
std::swap(m_, other.m_);
std::swap(r_, other.r_);
std::swap(n_, other.n_);
std::swap(total_wt_r_, other.total_wt_r_);
std::swap(rf_, other.rf_);
std::swap(curr_items_alloc_, other.curr_items_alloc_);
std::swap(filled_data_, other.filled_data_);
std::swap(allocator_, other.allocator_);
std::swap(data_, other.data_);
std::swap(weights_, other.weights_);
std::swap(num_marks_in_h_, other.num_marks_in_h_);
std::swap(marks_, other.marks_);
return *this;
}
/*
* An empty sketch requires 8 bytes.
*
* <pre>
* Long || Start Byte Adr:
* Adr:
* || 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
* 0 || Preamble_Longs | SerVer | FamID | Flags |---------Max Res. Size (K)---------|
* </pre>
*
* A non-empty sketch requires 24 bytes of preamble for an under-full sample; once there are
* at least k items the sketch uses 32 bytes of preamble.
*
* The count of items seen is limited to 48 bits (~256 trillion) even though there are adjacent
* unused preamble bits. The acceptance probability for an item is a double in the range [0,1),
* limiting us to 53 bits of randomness due to details of the IEEE floating point format. To
* ensure meaningful probabilities as the items seen count approaches capacity, we intentionally
* use slightly fewer bits.
*
* Following the header are weights for the heavy items, then marks in the event this is a gadget.
* The serialized items come last.
*
* <pre>
* Long || Start Byte Adr:
* Adr:
* || 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
* 0 || Preamble_Longs | SerVer | FamID | Flags |---------Max Res. Size (K)---------|
*
* || 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 |
* 1 ||---------------------------Items Seen Count (N)--------------------------------|
*
* || 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 |
* 2 ||-------------Item Count in H---------------|-------Item Count in R-------------|
*
* || 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 |
* 3 ||-------------------------------Total Weight in R-------------------------------|
* </pre>
*/
// implementation for fixed-size arithmetic types (integral and floating point)
template<typename T, typename S, typename A>
template<typename TT, typename std::enable_if<std::is_arithmetic<TT>::value, int>::type>
size_t var_opt_sketch<T,S,A>::get_serialized_size_bytes() const {
if (is_empty()) { return PREAMBLE_LONGS_EMPTY << 3; }
size_t num_bytes = (r_ == 0 ? PREAMBLE_LONGS_WARMUP : PREAMBLE_LONGS_FULL) << 3;
num_bytes += h_ * sizeof(double); // weights
if (marks_ != nullptr) { // marks
num_bytes += (h_ / 8) + (h_ % 8 > 0);
}
num_bytes += (h_ + r_) * sizeof(TT); // the actual items
return num_bytes;
}
// implementation for all other types
template<typename T, typename S, typename A>
template<typename TT, typename std::enable_if<!std::is_arithmetic<TT>::value, int>::type>
size_t var_opt_sketch<T,S,A>::get_serialized_size_bytes() const {
if (is_empty()) { return PREAMBLE_LONGS_EMPTY << 3; }
size_t num_bytes = (r_ == 0 ? PREAMBLE_LONGS_WARMUP : PREAMBLE_LONGS_FULL) << 3;
num_bytes += h_ * sizeof(double); // weights
if (marks_ != nullptr) { // marks
num_bytes += (h_ / 8) + (h_ % 8 > 0);
}
// must iterate over the items
for (auto it: *this)
num_bytes += S().size_of_item(it.first);
return num_bytes;
}
template<typename T, typename S, typename A>
std::vector<uint8_t, AllocU8<A>> var_opt_sketch<T,S,A>::serialize(unsigned header_size_bytes) const {
const size_t size = header_size_bytes + get_serialized_size_bytes();
std::vector<uint8_t, AllocU8<A>> bytes(size, 0, allocator_);
uint8_t* ptr = bytes.data() + header_size_bytes;
uint8_t* end_ptr = ptr + size;
bool empty = is_empty();
uint8_t preLongs = (empty ? PREAMBLE_LONGS_EMPTY
: (r_ == 0 ? PREAMBLE_LONGS_WARMUP : PREAMBLE_LONGS_FULL));
uint8_t first_byte = (preLongs & 0x3F) | ((static_cast<uint8_t>(rf_)) << 6);
uint8_t flags = (marks_ != nullptr ? GADGET_FLAG_MASK : 0);
if (empty) {
flags |= EMPTY_FLAG_MASK;
}
// first prelong
uint8_t ser_ver(SER_VER);
uint8_t family(FAMILY_ID);
ptr += copy_to_mem(first_byte, ptr);
ptr += copy_to_mem(ser_ver, ptr);
ptr += copy_to_mem(family, ptr);
ptr += copy_to_mem(flags, ptr);
ptr += copy_to_mem(k_, ptr);
if (!empty) {
// second and third prelongs
ptr += copy_to_mem(n_, ptr);
ptr += copy_to_mem(h_, ptr);
ptr += copy_to_mem(r_, ptr);
// fourth prelong, if needed
if (r_ > 0) {
ptr += copy_to_mem(total_wt_r_, ptr);
}
// first h_ weights
ptr += copy_to_mem(weights_, ptr, h_ * sizeof(double));
// first h_ marks as packed bytes iff we have a gadget
if (marks_ != nullptr) {
uint8_t val = 0;
for (uint32_t i = 0; i < h_; ++i) {
if (marks_[i]) {
val |= 0x1 << (i & 0x7);
}
if ((i & 0x7) == 0x7) {
ptr += copy_to_mem(val, ptr);
val = 0;
}
}
// write out any remaining values
if ((h_ & 0x7) > 0) {
ptr += copy_to_mem(val, ptr);
}
}
// write the sample items, skipping the gap. Either h_ or r_ may be 0
ptr += S().serialize(ptr, end_ptr - ptr, data_, h_);
ptr += S().serialize(ptr, end_ptr - ptr, &data_[h_ + 1], r_);
}
size_t bytes_written = ptr - bytes.data();
if (bytes_written != size) {
throw std::logic_error("serialized size mismatch: " + std::to_string(bytes_written) + " != " + std::to_string(size));
}
return bytes;
}
template<typename T, typename S, typename A>
void var_opt_sketch<T,S,A>::serialize(std::ostream& os) const {
const bool empty = (h_ == 0) && (r_ == 0);
const uint8_t preLongs = (empty ? PREAMBLE_LONGS_EMPTY
: (r_ == 0 ? PREAMBLE_LONGS_WARMUP : PREAMBLE_LONGS_FULL));
const uint8_t first_byte = (preLongs & 0x3F) | ((static_cast<uint8_t>(rf_)) << 6);
uint8_t flags = (marks_ != nullptr ? GADGET_FLAG_MASK : 0);
if (empty) {
flags |= EMPTY_FLAG_MASK;
}
// first prelong
const uint8_t ser_ver(SER_VER);
const uint8_t family(FAMILY_ID);
write(os, first_byte);
write(os, ser_ver);
write(os, family);
write(os, flags);
write(os, k_);
if (!empty) {
// second and third prelongs
write(os, n_);
write(os, h_);
write(os, r_);
// fourth prelong, if needed
if (r_ > 0) {
write(os, total_wt_r_);
}
// write the first h_ weights
write(os, weights_, h_ * sizeof(double));
// write the first h_ marks as packed bytes iff we have a gadget
if (marks_ != nullptr) {
uint8_t val = 0;
for (uint32_t i = 0; i < h_; ++i) {
if (marks_[i]) {
val |= 0x1 << (i & 0x7);
}
if ((i & 0x7) == 0x7) {
write(os, val);
val = 0;
}
}
// write out any remaining values
if ((h_ & 0x7) > 0) {
write(os, val);
}
}
// write the sample items, skipping the gap. Either h_ or r_ may be 0
S().serialize(os, data_, h_);
S().serialize(os, &data_[h_ + 1], r_);
}
}
template<typename T, typename S, typename A>
var_opt_sketch<T,S,A> var_opt_sketch<T,S,A>::deserialize(const void* bytes, size_t size, const A& allocator) {
ensure_minimum_memory(size, 8);
const char* ptr = static_cast<const char*>(bytes);
const char* base = ptr;
const char* end_ptr = ptr + size;
uint8_t first_byte;
ptr += copy_from_mem(ptr, first_byte);
uint8_t preamble_longs = first_byte & 0x3f;
resize_factor rf = static_cast<resize_factor>((first_byte >> 6) & 0x03);
uint8_t serial_version;
ptr += copy_from_mem(ptr, serial_version);
uint8_t family_id;
ptr += copy_from_mem(ptr, family_id);
uint8_t flags;
ptr += copy_from_mem(ptr, flags);
uint32_t k;
ptr += copy_from_mem(ptr, k);
check_preamble_longs(preamble_longs, flags);
check_family_and_serialization_version(family_id, serial_version);
ensure_minimum_memory(size, preamble_longs << 3);
const bool is_empty = flags & EMPTY_FLAG_MASK;
const bool is_gadget = flags & GADGET_FLAG_MASK;
if (is_empty) {
return var_opt_sketch<T,S,A>(k, rf, is_gadget, allocator);
}
// second and third prelongs
uint64_t n;
uint32_t h, r;
ptr += copy_from_mem(ptr, n);
ptr += copy_from_mem(ptr, h);
ptr += copy_from_mem(ptr, r);
const uint32_t array_size = validate_and_get_target_size(preamble_longs, k, n, h, r, rf);
// current_items_alloc_ is set but validate R region weight (4th prelong), if needed, before allocating
double total_wt_r = 0.0;
if (preamble_longs == PREAMBLE_LONGS_FULL) {
ptr += copy_from_mem(ptr, total_wt_r);
if (std::isnan(total_wt_r) || r == 0 || total_wt_r <= 0.0) {
throw std::invalid_argument("Possible corruption: deserializing in full mode but r = 0 or invalid R weight. "
"Found r = " + std::to_string(r) + ", R region weight = " + std::to_string(total_wt_r));
}
} else {
total_wt_r = 0.0;
}
// read the first h_ weights, fill in rest of array with -1.0
check_memory_size(ptr - base + (h * sizeof(double)), size);
std::unique_ptr<double, weights_deleter> weights(AllocDouble(allocator).allocate(array_size),
weights_deleter(array_size, allocator));
double* wts = weights.get(); // to avoid lots of .get() calls -- do not delete
ptr += copy_from_mem(ptr, wts, h * sizeof(double));
for (size_t i = 0; i < h; ++i) {
if (!(wts[i] > 0.0)) {
throw std::invalid_argument("Possible corruption: Non-positive weight when deserializing: " + std::to_string(wts[i]));
}
}
std::fill(wts + h, wts + array_size, -1.0);
// read the first h_ marks as packed bytes iff we have a gadget
uint32_t num_marks_in_h = 0;
std::unique_ptr<bool, marks_deleter> marks(nullptr, marks_deleter(array_size, allocator));
if (is_gadget) {
uint8_t val = 0;
marks = std::unique_ptr<bool, marks_deleter>(AllocBool(allocator).allocate(array_size), marks_deleter(array_size, allocator));
const size_t size_marks = (h / 8) + (h % 8 > 0 ? 1 : 0);
check_memory_size(ptr - base + size_marks, size);
for (uint32_t i = 0; i < h; ++i) {
if ((i & 0x7) == 0x0) { // should trigger on first iteration
ptr += copy_from_mem(ptr, val);
}
marks.get()[i] = ((val >> (i & 0x7)) & 0x1) == 1;
num_marks_in_h += (marks.get()[i] ? 1 : 0);
}
}
// read the sample items, skipping the gap. Either h_ or r_ may be 0
items_deleter deleter(array_size, allocator);
std::unique_ptr<T, items_deleter> items(A(allocator).allocate(array_size), deleter);
ptr += S().deserialize(ptr, end_ptr - ptr, items.get(), h);
items.get_deleter().set_h(h); // serde didn't throw, so the items are now valid
ptr += S().deserialize(ptr, end_ptr - ptr, &(items.get()[h + 1]), r);
items.get_deleter().set_r(r); // serde didn't throw, so the items are now valid
return var_opt_sketch(k, h, (r > 0 ? 1 : 0), r, n, total_wt_r, rf, array_size, false,
std::move(items), std::move(weights), num_marks_in_h, std::move(marks), allocator);
}
template<typename T, typename S, typename A>
var_opt_sketch<T,S,A> var_opt_sketch<T,S,A>::deserialize(std::istream& is, const A& allocator) {
const auto first_byte = read<uint8_t>(is);
uint8_t preamble_longs = first_byte & 0x3f;
const resize_factor rf = static_cast<resize_factor>((first_byte >> 6) & 0x03);
const auto serial_version = read<uint8_t>(is);
const auto family_id = read<uint8_t>(is);
const auto flags = read<uint8_t>(is);
const auto k = read<uint32_t>(is);
check_preamble_longs(preamble_longs, flags);
check_family_and_serialization_version(family_id, serial_version);
const bool is_empty = flags & EMPTY_FLAG_MASK;
const bool is_gadget = flags & GADGET_FLAG_MASK;
if (is_empty) {
if (!is.good())
throw std::runtime_error("error reading from std::istream");
else
return var_opt_sketch<T,S,A>(k, rf, is_gadget, allocator);
}
// second and third prelongs
const auto n = read<uint64_t>(is);
const auto h = read<uint32_t>(is);
const auto r = read<uint32_t>(is);
const uint32_t array_size = validate_and_get_target_size(preamble_longs, k, n, h, r, rf);
// current_items_alloc_ is set but validate R region weight (4th prelong), if needed, before allocating
double total_wt_r = 0.0;
if (preamble_longs == PREAMBLE_LONGS_FULL) {
total_wt_r = read<double>(is);
if (std::isnan(total_wt_r) || r == 0 || total_wt_r <= 0.0) {
throw std::invalid_argument("Possible corruption: deserializing in full mode but r = 0 or invalid R weight. "
"Found r = " + std::to_string(r) + ", R region weight = " + std::to_string(total_wt_r));
}
}
// read the first h weights, fill remainder with -1.0
std::unique_ptr<double, weights_deleter> weights(AllocDouble(allocator).allocate(array_size),
weights_deleter(array_size, allocator));
double* wts = weights.get(); // to avoid lots of .get() calls -- do not delete
read(is, wts, h * sizeof(double));
for (size_t i = 0; i < h; ++i) {
if (!(wts[i] > 0.0)) {
throw std::invalid_argument("Possible corruption: Non-positive weight when deserializing: " + std::to_string(wts[i]));
}
}
std::fill(wts + h, wts + array_size, -1.0);
// read the first h_ marks as packed bytes iff we have a gadget
uint32_t num_marks_in_h = 0;
std::unique_ptr<bool, marks_deleter> marks(nullptr, marks_deleter(array_size, allocator));
if (is_gadget) {
marks = std::unique_ptr<bool, marks_deleter>(AllocBool(allocator).allocate(array_size), marks_deleter(array_size, allocator));
uint8_t val = 0;
for (uint32_t i = 0; i < h; ++i) {
if ((i & 0x7) == 0x0) { // should trigger on first iteration
val = read<uint8_t>(is);
}
marks.get()[i] = ((val >> (i & 0x7)) & 0x1) == 1;
num_marks_in_h += (marks.get()[i] ? 1 : 0);
}
}
// read the sample items, skipping the gap. Either h or r may be 0
items_deleter deleter(array_size, allocator);
std::unique_ptr<T, items_deleter> items(A(allocator).allocate(array_size), deleter);
S().deserialize(is, items.get(), h); // aka &data_[0]
items.get_deleter().set_h(h); // serde didn't throw, so the items are now valid
S().deserialize(is, &(items.get()[h + 1]), r);
items.get_deleter().set_r(r); // serde didn't throw, so the items are now valid
if (!is.good())
throw std::runtime_error("error reading from std::istream");
return var_opt_sketch(k, h, (r > 0 ? 1 : 0), r, n, total_wt_r, rf, array_size, false,
std::move(items), std::move(weights), num_marks_in_h, std::move(marks), allocator);
}
template<typename T, typename S, typename A>
bool var_opt_sketch<T,S,A>::is_empty() const {
return (h_ == 0 && r_ == 0);
}
template<typename T, typename S, typename A>
void var_opt_sketch<T,S,A>::reset() {
const uint32_t prev_alloc = curr_items_alloc_;
const uint32_t ceiling_lg_k = to_log_2(ceiling_power_of_2(k_));
const uint32_t initial_lg_size = starting_sub_multiple(ceiling_lg_k, rf_, MIN_LG_ARR_ITEMS);
curr_items_alloc_ = get_adjusted_size(k_, 1 << initial_lg_size);
if (curr_items_alloc_ == k_) { // if full size, need to leave 1 for the gap
++curr_items_alloc_;
}
if (filled_data_) {
// destroy everything
const size_t num_to_destroy = std::min(k_ + 1, prev_alloc);
for (size_t i = 0; i < num_to_destroy; ++i)
allocator_.destroy(data_ + i);
} else {
// skip gap or anything unused at the end
for (size_t i = 0; i < h_; ++i)
allocator_.destroy(data_+ i);
for (size_t i = h_ + 1; i < h_ + r_ + 1; ++i)
allocator_.destroy(data_ + i);
}
if (curr_items_alloc_ < prev_alloc) {
const bool is_gadget = (marks_ != nullptr);
allocator_.deallocate(data_, prev_alloc);
AllocDouble(allocator_).deallocate(weights_, prev_alloc);
if (marks_ != nullptr)
AllocBool(allocator_).deallocate(marks_, prev_alloc);
allocate_data_arrays(curr_items_alloc_, is_gadget);
}
n_ = 0;
h_ = 0;
m_ = 0;
r_ = 0;
num_marks_in_h_ = 0;
total_wt_r_ = 0.0;
filled_data_ = false;
}
template<typename T, typename S, typename A>
uint64_t var_opt_sketch<T,S,A>::get_n() const {
return n_;
}
template<typename T, typename S, typename A>
uint32_t var_opt_sketch<T,S,A>::get_k() const {
return k_;
}
template<typename T, typename S, typename A>
uint32_t var_opt_sketch<T,S,A>::get_num_samples() const {
const uint32_t num_in_sketch = h_ + r_;
return (num_in_sketch < k_ ? num_in_sketch : k_);
}
template<typename T, typename S, typename A>
void var_opt_sketch<T,S,A>::update(const T& item, double weight) {
update(item, weight, false);
}
template<typename T, typename S, typename A>
void var_opt_sketch<T,S,A>::update(T&& item, double weight) {
update(std::move(item), weight, false);
}
template<typename T, typename S, typename A>
string<A> var_opt_sketch<T,S,A>::to_string() const {
std::basic_ostringstream<char, std::char_traits<char>, AllocChar<A>> os;
os << "### VarOpt SUMMARY: " << std::endl;
os << " k : " << k_ << std::endl;
os << " h : " << h_ << std::endl;
os << " r : " << r_ << std::endl;
os << " weight_r : " << total_wt_r_ << std::endl;
os << " Current size : " << curr_items_alloc_ << std::endl;
os << " Resize factor: " << (1 << rf_) << std::endl;
os << "### END SKETCH SUMMARY" << std::endl;
return os.str();
}
template<typename T, typename S, typename A>
string<A> var_opt_sketch<T,S,A>::items_to_string() const {
std::basic_ostringstream<char, std::char_traits<char>, AllocChar<A>> os;
os << "### Sketch Items" << std::endl;
int idx = 0;
for (auto record : *this) {
os << idx << ": " << record.first << "\twt = " << record.second << std::endl;
++idx;
}
return os.str();
}
template<typename T, typename S, typename A>
string<A> var_opt_sketch<T,S,A>::items_to_string(bool print_gap) const {
std::basic_ostringstream<char, std::char_traits<char>, AllocChar<A>> os;
os << "### Sketch Items" << std::endl;
const uint32_t array_length = (n_ < k_ ? n_ : k_ + 1);
for (uint32_t i = 0, display_idx = 0; i < array_length; ++i) {
if (i == h_ && print_gap) {
os << i << ": GAP" << std::endl;
++display_idx;
} else {
os << i << ": " << data_[i] << "\twt = ";
if (weights_[i] == -1.0) {
os << get_tau() << "\t(-1.0)" << std::endl;
} else {
os << weights_[i] << std::endl;
}
++display_idx;
}
}
return os.str();
}
template<typename T, typename S, typename A>
template<typename O>
void var_opt_sketch<T,S,A>::update(O&& item, double weight, bool mark) {
if (weight < 0.0 || std::isnan(weight) || std::isinf(weight)) {
throw std::invalid_argument("Item weights must be nonnegative and finite. Found: "
+ std::to_string(weight));
} else if (weight == 0.0) {
return;
}
++n_;
if (r_ == 0) {
// exact mode
update_warmup_phase(std::forward<O>(item), weight, mark);
} else {
// sketch is in estimation mode so we can make the following check,
// although very conservative to check every time
if ((h_ != 0) && (peek_min() < get_tau()))
throw std::logic_error("sketch not in valid estimation mode");
// what tau would be if deletion candidates turn out to be R plus the new item
// note: (r_ + 1) - 1 is intentional
const double hypothetical_tau = (weight + total_wt_r_) / ((r_ + 1) - 1);
// is new item's turn to be considered for reservoir?
const double condition1 = (h_ == 0) || (weight <= peek_min());
// is new item light enough for reservoir?
const double condition2 = weight < hypothetical_tau;
if (condition1 && condition2) {
update_light(std::forward<O>(item), weight, mark);
} else if (r_ == 1) {
update_heavy_r_eq1(std::forward<O>(item), weight, mark);
} else {
update_heavy_general(std::forward<O>(item), weight, mark);
}
}
}
template<typename T, typename S, typename A>
template<typename O>
void var_opt_sketch<T,S,A>::update_warmup_phase(O&& item, double weight, bool mark) {
// seems overly cautious
if (r_ > 0 || m_ != 0 || h_ > k_) throw std::logic_error("invalid sketch state during warmup");
if (h_ >= curr_items_alloc_) {
grow_data_arrays();
}
// store items as they come in until full
new (&data_[h_]) T(std::forward<O>(item));
weights_[h_] = weight;
if (marks_ != nullptr) {
marks_[h_] = mark;
}
++h_;
num_marks_in_h_ += mark ? 1 : 0;
// check if need to heapify
if (h_ > k_) {
filled_data_ = true;
transition_from_warmup();
}
}
/* In the "light" case the new item has weight <= old_tau, so
would appear to the right of the R items in a hypothetical reverse-sorted
list. It is easy to prove that it is light enough to be part of this
round's downsampling */
template<typename T, typename S, typename A>
template<typename O>
void var_opt_sketch<T,S,A>::update_light(O&& item, double weight, bool mark) {
if (r_ == 0 || (r_ + h_) != k_) throw std::logic_error("invalid sketch state during light warmup");
const uint32_t m_slot = h_; // index of the gap, which becomes the M region
if (filled_data_) {
data_[m_slot] = std::forward<O>(item);
} else {
new (&data_[m_slot]) T(std::forward<O>(item));
filled_data_ = true;
}
weights_[m_slot] = weight;
if (marks_ != nullptr) { marks_[m_slot] = mark; }
++m_;
grow_candidate_set(total_wt_r_ + weight, r_ + 1);
}
/* In the "heavy" case the new item has weight > old_tau, so would
appear to the left of items in R in a hypothetical reverse-sorted list and
might or might not be light enough be part of this round's downsampling.
[After first splitting off the R=1 case] we greatly simplify the code by
putting the new item into the H heap whether it needs to be there or not.
In other words, it might go into the heap and then come right back out,
but that should be okay because pseudo_heavy items cannot predominate
in long streams unless (max wt) / (min wt) > o(exp(N)) */
template<typename T, typename S, typename A>
template<typename O>
void var_opt_sketch<T,S,A>::update_heavy_general(O&& item, double weight, bool mark) {
if (r_ < 2 || m_ != 0 || (r_ + h_) != k_) throw std::logic_error("invalid sketch state during heavy general update");
// put into H, although may come back out momentarily
push(std::forward<O>(item), weight, mark);
grow_candidate_set(total_wt_r_, r_);
}
/* The analysis of this case is similar to that of the general heavy case.
The one small technical difference is that since R < 2, we must grab an M item
to have a valid starting point for continue_by_growing_candidate_set () */
template<typename T, typename S, typename A>
template<typename O>
void var_opt_sketch<T,S,A>::update_heavy_r_eq1(O&& item, double weight, bool mark) {
if (r_ != 1 || m_ != 0 || (r_ + h_) != k_) throw std::logic_error("invalid sketch state during heavy r=1 update");
push(std::forward<O>(item), weight, mark); // new item into H
pop_min_to_m_region(); // pop lightest back into M
// Any set of two items is downsample-able to one item,
// so the two lightest items are a valid starting point for the following
const uint32_t m_slot = k_ - 1; // array is k+1, 1 in R, so slot before is M
grow_candidate_set(weights_[m_slot] + total_wt_r_, 2);
}
/**
* Decreases sketch's value of k by 1, updating stored values as needed.
*
* <p>Subject to certain pre-conditions, decreasing k causes tau to increase. This fact is used by
* the unioning algorithm to force "marked" items out of H and into the reservoir region.</p>
*/
template<typename T, typename S, typename A>
void var_opt_sketch<T,S,A>::decrease_k_by_1() {
if (k_ <= 1) {
throw std::logic_error("Cannot decrease k below 1 in union");
}
if ((h_ == 0) && (r_ == 0)) {
// exact mode, but no data yet; this reduction is somewhat gratuitous
--k_;
} else if ((h_ > 0) && (r_ == 0)) {
// exact mode, but we have some data
--k_;
if (h_ > k_) {
transition_from_warmup();
}
} else if ((h_ > 0) && (r_ > 0)) {
// reservoir mode, but we have some exact samples.
// Our strategy will be to pull an item out of H (which we are allowed to do since it's
// still just data), reduce k, and then re-insert the item
// first, slide the R zone to the left by 1, temporarily filling the gap
const uint32_t old_gap_idx = h_;
const uint32_t old_final_r_idx = (h_ + 1 + r_) - 1;
//if (old_final_r_idx != k_) throw std::logic_error("gadget in invalid state");
swap_values(old_final_r_idx, old_gap_idx);
// now we pull an item out of H; any item is ok, but if we grab the rightmost and then
// reduce h_, the heap invariant will be preserved (and the gap will be restored), plus
// the push() of the item that will probably happen later will be cheap.
const uint32_t pulled_idx = h_ - 1;
double pulled_weight = weights_[pulled_idx];
bool pulled_mark = marks_[pulled_idx];
// will move the pulled item below; don't do antying to it here
if (pulled_mark) { --num_marks_in_h_; }
weights_[pulled_idx] = -1.0; // to make bugs easier to spot
--h_;
--k_;
--n_; // will be re-incremented with the update
update(std::move(data_[pulled_idx]), pulled_weight, pulled_mark);
} else if ((h_ == 0) && (r_ > 0)) {
// pure reservoir mode, so can simply eject a randomly chosen sample from the reservoir
if (r_ < 2) throw std::logic_error("r_ too small for pure reservoir mode");
const uint32_t r_idx_to_delete = 1 + next_int(r_); // 1 for the gap
const uint32_t rightmost_r_idx = (1 + r_) - 1;
swap_values(r_idx_to_delete, rightmost_r_idx);
weights_[rightmost_r_idx] = -1.0;
--k_;
--r_;
}
}
template<typename T, typename S, typename A>
void var_opt_sketch<T,S,A>::allocate_data_arrays(uint32_t tgt_size, bool use_marks) {
filled_data_ = false;
data_ = allocator_.allocate(tgt_size);
weights_ = AllocDouble(allocator_).allocate(tgt_size);
if (use_marks) {
marks_ = AllocBool(allocator_).allocate(tgt_size);
} else {
marks_ = nullptr;
}
}
template<typename T, typename S, typename A>
void var_opt_sketch<T,S,A>::grow_data_arrays() {
const uint32_t prev_size = curr_items_alloc_;
curr_items_alloc_ = get_adjusted_size(k_, curr_items_alloc_ << rf_);
if (curr_items_alloc_ == k_) {
++curr_items_alloc_;
}
if (prev_size < curr_items_alloc_) {
filled_data_ = false;
T* tmp_data = allocator_.allocate(curr_items_alloc_);
double* tmp_weights = AllocDouble(allocator_).allocate(curr_items_alloc_);
for (uint32_t i = 0; i < prev_size; ++i) {
new (&tmp_data[i]) T(std::move(data_[i]));
allocator_.destroy(data_ + i);
tmp_weights[i] = weights_[i];