Coverage Report

Created: 2026-10-08 13:10

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
be/src/util/tdigest.h
Line
Count
Source
1
// Licensed to the Apache Software Foundation (ASF) under one
2
// or more contributor license agreements.  See the NOTICE file
3
// distributed with this work for additional information
4
// regarding copyright ownership.  The ASF licenses this file
5
// to you under the Apache License, Version 2.0 (the
6
// "License"); you may not use this file except in compliance
7
// with the License.  You may obtain a copy of the License at
8
//
9
//   http://www.apache.org/licenses/LICENSE-2.0
10
//
11
// Unless required by applicable law or agreed to in writing,
12
// software distributed under the License is distributed on an
13
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
// KIND, either express or implied.  See the License for the
15
// specific language governing permissions and limitations
16
// under the License.
17
18
/*
19
 * Licensed to Derrick R. Burns under one or more
20
 * contributor license agreements.  See the NOTICES file distributed with
21
 * this work for additional information regarding copyright ownership.
22
 * The ASF licenses this file to You under the Apache License, Version 2.0
23
 * (the "License"); you may not use this file except in compliance with
24
 * the License.  You may obtain a copy of the License at
25
 *
26
 *     http://www.apache.org/licenses/LICENSE-2.0
27
 *
28
 * Unless required by applicable law or agreed to in writing, software
29
 * distributed under the License is distributed on an "AS IS" BASIS,
30
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
31
 * See the License for the specific language governing permissions and
32
 * limitations under the License.
33
 */
34
35
// T-Digest :  Percentile and Quantile Estimation of Big Data
36
// A new data structure for accurate on-line accumulation of rank-based statistics
37
// such as quantiles and trimmed means.
38
// See original paper: "Computing extremely accurate quantiles using t-digest"
39
// by Ted Dunning and Otmar Ertl for more details
40
// https://github.com/tdunning/t-digest/blob/07b8f2ca2be8d0a9f04df2feadad5ddc1bb73c88/docs/t-digest-paper/histo.pdf.
41
// https://github.com/derrickburns/tdigest
42
43
#pragma once
44
45
#include <pdqsort.h>
46
47
#include <algorithm>
48
#include <cfloat>
49
#include <cmath>
50
#include <iostream>
51
#include <memory>
52
#include <queue>
53
#include <utility>
54
#include <vector>
55
56
#include "common/factory_creator.h"
57
#include "common/logging.h"
58
59
namespace doris {
60
61
using Value = float;
62
using Weight = float;
63
using Index = size_t;
64
65
constexpr size_t K_HIGH_WATER = 40000;
66
67
class Centroid {
68
public:
69
246k
    Centroid() : Centroid(0.0, 0.0) {}
70
71
404k
    Centroid(Value mean, Weight weight) : _mean(mean), _weight(weight) {}
72
73
232M
    Value mean() const noexcept { return _mean; }
74
75
340M
    Weight weight() const noexcept { return _weight; }
76
77
15.9k
    Value& mean() noexcept { return _mean; }
78
79
14.3k
    Weight& weight() noexcept { return _weight; }
80
81
997k
    void add(const Centroid& c) {
82
997k
        DCHECK_GT(c._weight, 0);
83
1.00M
        if (_weight != 0.0) {
84
1.00M
            _weight += c._weight;
85
1.00M
            _mean += c._weight * (c._mean - _mean) / _weight;
86
18.4E
        } else {
87
18.4E
            _weight = c._weight;
88
18.4E
            _mean = c._mean;
89
18.4E
        }
90
997k
    }
91
92
private:
93
    Value _mean = 0;
94
    Weight _weight = 0;
95
};
96
97
struct CentroidList {
98
801
    CentroidList(const std::vector<Centroid>& s) : iter(s.cbegin()), end(s.cend()) {}
99
    std::vector<Centroid>::const_iterator iter;
100
    std::vector<Centroid>::const_iterator end;
101
102
1.89M
    bool advance() { return ++iter != end; }
103
};
104
105
class CentroidListComparator {
106
public:
107
    CentroidListComparator() = default;
108
109
1.76M
    bool operator()(const CentroidList& left, const CentroidList& right) const {
110
1.76M
        return left.iter->mean() > right.iter->mean();
111
1.76M
    }
112
};
113
114
using CentroidListQueue =
115
        std::priority_queue<CentroidList, std::vector<CentroidList>, CentroidListComparator>;
116
117
struct CentroidComparator {
118
114M
    bool operator()(const Centroid& a, const Centroid& b) const { return a.mean() < b.mean(); }
119
};
120
121
class TDigest {
122
    ENABLE_FACTORY_CREATOR(TDigest);
123
124
    class TDigestComparator {
125
    public:
126
        TDigestComparator() = default;
127
128
0
        bool operator()(const TDigest* left, const TDigest* right) const {
129
0
            return left->total_size() > right->total_size();
130
0
        }
131
    };
132
    using TDigestQueue =
133
            std::priority_queue<const TDigest*, std::vector<const TDigest*>, TDigestComparator>;
134
135
public:
136
0
    TDigest() : TDigest(10000) {}
137
138
1.74k
    explicit TDigest(Value compression) : TDigest(compression, 0) {}
139
140
1.74k
    TDigest(Value compression, Index buffer_size) : TDigest(compression, buffer_size, 0) {}
141
142
    TDigest(Value compression, Index unmerged_size, Index merged_size)
143
1.74k
            : _compression(compression),
144
1.74k
              _max_processed(processed_size(merged_size, compression)),
145
1.74k
              _max_unprocessed(unprocessed_size(unmerged_size, compression)) {
146
1.74k
        _processed.reserve(_max_processed);
147
1.74k
        _unprocessed.reserve(_max_unprocessed + 1);
148
1.74k
    }
149
150
    TDigest(std::vector<Centroid>&& processed, std::vector<Centroid>&& unprocessed,
151
            Value compression, Index unmerged_size, Index merged_size)
152
0
            : TDigest(compression, unmerged_size, merged_size) {
153
0
        _processed = std::move(processed);
154
0
        _unprocessed = std::move(unprocessed);
155
0
156
0
        _processed_weight = weight(_processed);
157
0
        _unprocessed_weight = weight(_unprocessed);
158
0
        if (_processed.size() > 0) {
159
0
            _min = std::min(_min, _processed[0].mean());
160
0
            _max = std::max(_max, (_processed.cend() - 1)->mean());
161
0
        }
162
0
        _update_cumulative();
163
0
    }
164
165
0
    static Weight weight(std::vector<Centroid>& centroids) noexcept {
166
0
        Weight w = 0.0;
167
0
        for (auto centroid : centroids) {
168
0
            w += centroid.weight();
169
0
        }
170
0
        return w;
171
0
    }
172
173
12.0k
    TDigest(const TDigest&) = default;
174
175
0
    TDigest& operator=(TDigest&& o) {
176
0
        _compression = o._compression;
177
0
        _max_processed = o._max_processed;
178
0
        _max_unprocessed = o._max_unprocessed;
179
0
        _processed_weight = o._processed_weight;
180
0
        _unprocessed_weight = o._unprocessed_weight;
181
0
        _processed = std::move(o._processed);
182
0
        _unprocessed = std::move(o._unprocessed);
183
0
        _cumulative = std::move(o._cumulative);
184
0
        _min = o._min;
185
0
        _max = o._max;
186
0
        return *this;
187
0
    }
188
189
    TDigest(TDigest&& o)
190
            : TDigest(std::move(o._processed), std::move(o._unprocessed), o._compression,
191
0
                      o._max_unprocessed, o._max_processed) {}
192
193
1.74k
    static inline Index processed_size(Index size, Value compression) noexcept {
194
1.74k
        return (size == 0) ? static_cast<Index>(2 * std::ceil(compression)) : size;
195
1.74k
    }
196
197
1.74k
    static inline Index unprocessed_size(Index size, Value compression) noexcept {
198
1.74k
        return (size == 0) ? static_cast<Index>(8 * std::ceil(compression)) : size;
199
1.74k
    }
200
201
    // merge in another t-digest
202
736
    void merge(const TDigest* other) {
203
736
        std::vector<const TDigest*> others {other};
204
736
        add(others.cbegin(), others.cend());
205
736
    }
206
207
6
    const std::vector<Centroid>& processed() const { return _processed; }
208
209
12.0k
    const std::vector<Centroid>& unprocessed() const { return _unprocessed; }
210
211
0
    Index max_unprocessed() const { return _max_unprocessed; }
212
213
0
    Index max_processed() const { return _max_processed; }
214
215
1
    void add(std::vector<const TDigest*> digests) { add(digests.cbegin(), digests.cend()); }
216
217
    // merge in a vector of tdigests in the most efficient manner possible
218
    // in constant space
219
    // works for any value of K_HIGH_WATER
220
    void add(std::vector<const TDigest*>::const_iterator iter,
221
737
             std::vector<const TDigest*>::const_iterator end) {
222
737
        if (iter != end) {
223
737
            auto size = std::distance(iter, end);
224
737
            TDigestQueue pq(TDigestComparator {});
225
1.47k
            for (; iter != end; iter++) {
226
736
                pq.push((*iter));
227
736
            }
228
737
            std::vector<const TDigest*> batch;
229
737
            batch.reserve(size);
230
231
737
            size_t total_size = 0;
232
1.47k
            while (!pq.empty()) {
233
737
                const auto* td = pq.top();
234
737
                batch.push_back(td);
235
737
                pq.pop();
236
737
                total_size += td->total_size();
237
737
                if (total_size >= K_HIGH_WATER || pq.empty()) {
238
737
                    _merge_processed(batch);
239
737
                    _merge_unprocessed(batch);
240
737
                    _process_if_necessary();
241
737
                    batch.clear();
242
737
                    total_size = 0;
243
737
                }
244
737
            }
245
737
            _update_cumulative();
246
737
        }
247
737
    }
248
249
0
    Weight processed_weight() const { return _processed_weight; }
250
251
0
    Weight unprocessed_weight() const { return _unprocessed_weight; }
252
253
26.0k
    bool have_unprocessed() const { return _unprocessed.size() > 0; }
254
255
2.14k
    size_t total_size() const { return _processed.size() + _unprocessed.size(); }
256
257
8
    long total_weight() const { return static_cast<long>(_processed_weight + _unprocessed_weight); }
258
259
    // return the cdf on the t-digest
260
11
    Value cdf(Value x) {
261
11
        if (have_unprocessed() || is_dirty()) {
262
0
            _process();
263
0
        }
264
11
        return cdf_processed(x);
265
11
    }
266
267
158k
    bool is_dirty() {
268
158k
        return _processed.size() > _max_processed || _unprocessed.size() > _max_unprocessed;
269
158k
    }
270
271
    // return the cdf on the processed values
272
11
    Value cdf_processed(Value x) const {
273
11
        VLOG_CRITICAL << "cdf value " << x;
274
11
        VLOG_CRITICAL << "processed size " << _processed.size();
275
11
        if (_processed.size() == 0) {
276
            // no data to examine
277
0
            VLOG_CRITICAL << "no processed values";
278
279
0
            return 0.0;
280
11
        } else if (_processed.size() == 1) {
281
0
            VLOG_CRITICAL << "one processed value "
282
0
                          << " _min " << _min << " _max " << _max;
283
            // exactly one centroid, should have _max==_min
284
0
            auto width = _max - _min;
285
0
            if (x < _min) {
286
0
                return 0.0;
287
0
            } else if (x > _max) {
288
0
                return 1.0;
289
0
            } else if (x - _min <= width) {
290
                // _min and _max are too close together to do any viable interpolation
291
0
                return 0.5;
292
0
            } else {
293
                // interpolate if somehow we have weight > 0 and _max != _min
294
0
                return (x - _min) / (_max - _min);
295
0
            }
296
11
        } else {
297
11
            auto n = _processed.size();
298
11
            if (x <= _min) {
299
3
                VLOG_CRITICAL << "below _min "
300
3
                              << " _min " << _min << " x " << x;
301
3
                return 0;
302
3
            }
303
304
8
            if (x >= _max) {
305
4
                VLOG_CRITICAL << "above _max "
306
4
                              << " _max " << _max << " x " << x;
307
4
                return 1;
308
4
            }
309
310
            // check for the left tail
311
4
            if (x <= _mean(0)) {
312
0
                VLOG_CRITICAL << "left tail "
313
0
                              << " _min " << _min << " mean(0) " << _mean(0) << " x " << x;
314
315
                // note that this is different than mean(0) > _min ... this guarantees interpolation works
316
0
                if (_mean(0) - _min > 0) {
317
0
                    return static_cast<Value>((x - _min) / (_mean(0) - _min) * _weight(0) /
318
0
                                              _processed_weight / 2.0);
319
0
                } else {
320
0
                    return 0;
321
0
                }
322
0
            }
323
324
            // and the right tail
325
4
            if (x >= _mean(n - 1)) {
326
0
                VLOG_CRITICAL << "right tail"
327
0
                              << " _max " << _max << " mean(n - 1) " << _mean(n - 1) << " x " << x;
328
329
0
                if (_max - _mean(n - 1) > 0) {
330
0
                    return static_cast<Value>(1.0 - (_max - x) / (_max - _mean(n - 1)) *
331
0
                                                            _weight(n - 1) / _processed_weight /
332
0
                                                            2.0);
333
0
                } else {
334
0
                    return 1;
335
0
                }
336
0
            }
337
338
4
            CentroidComparator cc;
339
4
            auto iter =
340
4
                    std::upper_bound(_processed.cbegin(), _processed.cend(), Centroid(x, 0), cc);
341
342
4
            auto i = std::distance(_processed.cbegin(), iter);
343
4
            auto z1 = x - (iter - 1)->mean();
344
4
            auto z2 = (iter)->mean() - x;
345
4
            DCHECK_LE(0.0, z1);
346
4
            DCHECK_LE(0.0, z2);
347
4
            VLOG_CRITICAL << "middle "
348
4
                          << " z1 " << z1 << " z2 " << z2 << " x " << x;
349
350
4
            return _weighted_average(_cumulative[i - 1], z2, _cumulative[i], z1) /
351
4
                   _processed_weight;
352
4
        }
353
11
    }
354
355
    // this returns a quantile on the t-digest
356
444
    Value quantile(Value q) {
357
444
        if (have_unprocessed() || is_dirty()) {
358
266
            _process();
359
266
        }
360
444
        return quantile_processed(q);
361
444
    }
362
363
    void quantiles(const double* quantile_levels, const size_t* permutation, size_t size,
364
370
                   double* result) {
365
370
        if (size == 0) {
366
0
            return;
367
0
        }
368
370
        if (have_unprocessed() || is_dirty()) {
369
332
            _process();
370
332
        }
371
372
370
        if (_processed.empty()) {
373
1
            std::fill(result, result + size, NAN);
374
1
            return;
375
1
        }
376
377
369
        if (_processed.size() == 1) {
378
317
            std::fill(result, result + size, static_cast<double>(_mean(0)));
379
317
            return;
380
317
        }
381
382
52
        const auto n = _processed.size();
383
52
        size_t cumulative_index = 0;
384
138
        for (size_t result_index = 0; result_index < size; ++result_index) {
385
86
            const size_t level_index = permutation[result_index];
386
86
            const auto q = static_cast<Value>(quantile_levels[level_index]);
387
86
            DCHECK_GE(q, 0);
388
86
            DCHECK_LE(q, 1);
389
390
86
            const auto index = q * _processed_weight;
391
86
            if (index <= _weight(0) / 2.0) {
392
35
                DCHECK_GT(_weight(0), 0);
393
35
                result[level_index] =
394
35
                        static_cast<Value>(_min + 2.0 * index / _weight(0) * (_mean(0) - _min));
395
35
                continue;
396
35
            }
397
398
1.21k
            while (cumulative_index < _cumulative.size() && _cumulative[cumulative_index] < index) {
399
1.16k
                ++cumulative_index;
400
1.16k
            }
401
402
51
            if (cumulative_index > 0 && cumulative_index + 1 < _cumulative.size()) {
403
45
                auto z1 = index - _cumulative[cumulative_index - 1];
404
45
                auto z2 = _cumulative[cumulative_index] - index;
405
45
                result[level_index] = static_cast<double>(_weighted_average(
406
45
                        _mean(cumulative_index - 1), z2, _mean(cumulative_index), z1));
407
45
                continue;
408
45
            }
409
410
51
            DCHECK_LE(index, _processed_weight);
411
6
            DCHECK_GE(index, _processed_weight - _weight(n - 1) / 2.0);
412
6
            auto z1 = static_cast<Value>(index - _processed_weight - _weight(n - 1) / 2.0);
413
6
            auto z2 = static_cast<Value>(_weight(n - 1) / 2 - z1);
414
6
            result[level_index] =
415
6
                    static_cast<double>(_weighted_average(_mean(n - 1), z1, _max, z2));
416
6
        }
417
52
    }
418
419
    // this returns a quantile on the currently processed values without changing the t-digest
420
    // the value will not represent the unprocessed values
421
1.30k
    Value quantile_processed(Value q) const {
422
1.30k
        if (q < 0 || q > 1) {
423
0
            VLOG_CRITICAL << "q should be in [0,1], got " << q;
424
0
            return NAN;
425
0
        }
426
427
1.30k
        if (_processed.size() == 0) {
428
            // no sorted means no data, no way to get a quantile
429
121
            return NAN;
430
1.18k
        } else if (_processed.size() == 1) {
431
            // with one data point, all quantiles lead to Rome
432
433
183
            return _mean(0);
434
183
        }
435
436
        // we know that there are at least two sorted now
437
1.00k
        auto n = _processed.size();
438
439
        // if values were stored in a sorted array, index would be the offset we are Weighterested in
440
1.00k
        const auto index = q * _processed_weight;
441
442
        // at the boundaries, we return _min or _max
443
1.00k
        if (index <= _weight(0) / 2.0) {
444
47
            DCHECK_GT(_weight(0), 0);
445
47
            return static_cast<Value>(_min + 2.0 * index / _weight(0) * (_mean(0) - _min));
446
47
        }
447
448
954
        auto iter = std::lower_bound(_cumulative.cbegin(), _cumulative.cend(), index);
449
450
954
        if (iter != _cumulative.cend() && iter != _cumulative.cbegin() &&
451
954
            iter + 1 != _cumulative.cend()) {
452
310
            auto i = std::distance(_cumulative.cbegin(), iter);
453
310
            auto z1 = index - *(iter - 1);
454
310
            auto z2 = *(iter)-index;
455
            // VLOG_CRITICAL << "z2 " << z2 << " index " << index << " z1 " << z1;
456
310
            return _weighted_average(_mean(i - 1), z2, _mean(i), z1);
457
310
        }
458
459
954
        DCHECK_LE(index, _processed_weight);
460
644
        DCHECK_GE(index, _processed_weight - _weight(n - 1) / 2.0);
461
462
644
        auto z1 = static_cast<Value>(index - _processed_weight - _weight(n - 1) / 2.0);
463
644
        auto z2 = static_cast<Value>(_weight(n - 1) / 2 - z1);
464
644
        return _weighted_average(_mean(n - 1), z1, _max, z2);
465
954
    }
466
467
0
    Value compression() const { return _compression; }
468
469
147k
    void add(Value x) { add(x, 1); }
470
471
12.1k
    void compress() { _process(); }
472
473
    // add a single centroid to the unprocessed vector, processing previously unprocessed sorted if our limit has
474
    // been reached.
475
157k
    bool add(Value x, Weight w) {
476
157k
        if (std::isnan(x)) {
477
381
            return false;
478
381
        }
479
157k
        _unprocessed.emplace_back(x, w);
480
157k
        _unprocessed_weight += w;
481
157k
        _process_if_necessary();
482
157k
        return true;
483
157k
    }
484
485
    void add(std::vector<Centroid>::const_iterator iter,
486
0
             std::vector<Centroid>::const_iterator end) {
487
0
        while (iter != end) {
488
0
            const size_t diff = std::distance(iter, end);
489
0
            const size_t room = _max_unprocessed - _unprocessed.size();
490
0
            auto mid = iter + std::min(diff, room);
491
0
            while (iter != mid) {
492
0
                _unprocessed.push_back(*(iter++));
493
0
            }
494
0
            if (_unprocessed.size() >= _max_unprocessed) {
495
0
                _process();
496
0
            }
497
0
        }
498
0
    }
499
500
635
    uint32_t serialized_size() {
501
635
        return static_cast<uint32_t>(sizeof(uint32_t) + sizeof(Value) * 5 + sizeof(Index) * 2 +
502
635
                                     sizeof(uint32_t) * 3 + _processed.size() * sizeof(Centroid) +
503
635
                                     _unprocessed.size() * sizeof(Centroid) +
504
635
                                     _cumulative.size() * sizeof(Weight));
505
635
    }
506
507
316
    size_t serialize(uint8_t* writer) {
508
316
        uint8_t* dst = writer;
509
316
        uint32_t total_size = serialized_size();
510
316
        memcpy(writer, &total_size, sizeof(uint32_t));
511
316
        writer += sizeof(uint32_t);
512
316
        memcpy(writer, &_compression, sizeof(Value));
513
316
        writer += sizeof(Value);
514
316
        memcpy(writer, &_min, sizeof(Value));
515
316
        writer += sizeof(Value);
516
316
        memcpy(writer, &_max, sizeof(Value));
517
316
        writer += sizeof(Value);
518
316
        memcpy(writer, &_max_processed, sizeof(Index));
519
316
        writer += sizeof(Index);
520
316
        memcpy(writer, &_max_unprocessed, sizeof(Index));
521
316
        writer += sizeof(Index);
522
316
        memcpy(writer, &_processed_weight, sizeof(Value));
523
316
        writer += sizeof(Value);
524
316
        memcpy(writer, &_unprocessed_weight, sizeof(Value));
525
316
        writer += sizeof(Value);
526
527
316
        auto size = static_cast<uint32_t>(_processed.size());
528
316
        memcpy(writer, &size, sizeof(uint32_t));
529
316
        writer += sizeof(uint32_t);
530
247k
        for (int i = 0; i < size; i++) {
531
247k
            memcpy(writer, &_processed[i], sizeof(Centroid));
532
247k
            writer += sizeof(Centroid);
533
247k
        }
534
535
316
        size = static_cast<uint32_t>(_unprocessed.size());
536
316
        memcpy(writer, &size, sizeof(uint32_t));
537
316
        writer += sizeof(uint32_t);
538
        //TODO(weixiang): may be once memcpy is enough!
539
4.59k
        for (int i = 0; i < size; i++) {
540
4.27k
            memcpy(writer, &_unprocessed[i], sizeof(Centroid));
541
4.27k
            writer += sizeof(Centroid);
542
4.27k
        }
543
544
316
        size = static_cast<uint32_t>(_cumulative.size());
545
316
        memcpy(writer, &size, sizeof(uint32_t));
546
316
        writer += sizeof(uint32_t);
547
247k
        for (int i = 0; i < size; i++) {
548
247k
            memcpy(writer, &_cumulative[i], sizeof(Weight));
549
247k
            writer += sizeof(Weight);
550
247k
        }
551
316
        return writer - dst;
552
316
    }
553
554
342
    void unserialize(const uint8_t* type_reader) {
555
342
        uint32_t total_length = 0;
556
342
        memcpy(&total_length, type_reader, sizeof(uint32_t));
557
342
        type_reader += sizeof(uint32_t);
558
342
        memcpy(&_compression, type_reader, sizeof(Value));
559
342
        type_reader += sizeof(Value);
560
342
        memcpy(&_min, type_reader, sizeof(Value));
561
342
        type_reader += sizeof(Value);
562
342
        memcpy(&_max, type_reader, sizeof(Value));
563
342
        type_reader += sizeof(Value);
564
565
342
        memcpy(&_max_processed, type_reader, sizeof(Index));
566
342
        type_reader += sizeof(Index);
567
342
        memcpy(&_max_unprocessed, type_reader, sizeof(Index));
568
342
        type_reader += sizeof(Index);
569
342
        memcpy(&_processed_weight, type_reader, sizeof(Value));
570
342
        type_reader += sizeof(Value);
571
342
        memcpy(&_unprocessed_weight, type_reader, sizeof(Value));
572
342
        type_reader += sizeof(Value);
573
574
342
        uint32_t size;
575
342
        memcpy(&size, type_reader, sizeof(uint32_t));
576
342
        type_reader += sizeof(uint32_t);
577
342
        _processed.resize(size);
578
242k
        for (int i = 0; i < size; i++) {
579
242k
            memcpy(&_processed[i], type_reader, sizeof(Centroid));
580
242k
            type_reader += sizeof(Centroid);
581
242k
        }
582
342
        memcpy(&size, type_reader, sizeof(uint32_t));
583
342
        type_reader += sizeof(uint32_t);
584
342
        _unprocessed.resize(size);
585
4.64k
        for (int i = 0; i < size; i++) {
586
4.30k
            memcpy(&_unprocessed[i], type_reader, sizeof(Centroid));
587
4.30k
            type_reader += sizeof(Centroid);
588
4.30k
        }
589
342
        memcpy(&size, type_reader, sizeof(uint32_t));
590
342
        type_reader += sizeof(uint32_t);
591
342
        _cumulative.resize(size);
592
242k
        for (int i = 0; i < size; i++) {
593
242k
            memcpy(&_cumulative[i], type_reader, sizeof(Weight));
594
242k
            type_reader += sizeof(Weight);
595
242k
        }
596
342
    }
597
598
private:
599
    Value _compression;
600
601
    Value _min = std::numeric_limits<Value>::max();
602
603
    // min() is the smallest positive value, so use lowest() for all-negative input,
604
    // e.g. {-3, -2, -1} must set _max to -1.
605
    Value _max = std::numeric_limits<Value>::lowest();
606
607
    Index _max_processed;
608
609
    Index _max_unprocessed;
610
611
    Value _processed_weight = 0.0;
612
613
    Value _unprocessed_weight = 0.0;
614
615
    std::vector<Centroid> _processed;
616
617
    std::vector<Centroid> _unprocessed;
618
619
    std::vector<Weight> _cumulative;
620
621
    // return mean of i-th centroid
622
1.94k
    Value _mean(int64_t i) const noexcept { return _processed[i].mean(); }
623
624
    // return weight of i-th centroid
625
114M
    Weight _weight(int64_t i) const noexcept { return _processed[i].weight(); }
626
627
    // append all unprocessed centroids into current unprocessed vector
628
736
    void _merge_unprocessed(const std::vector<const TDigest*>& tdigests) {
629
736
        if (tdigests.size() == 0) {
630
0
            return;
631
0
        }
632
633
736
        size_t total = _unprocessed.size();
634
737
        for (const auto& td : tdigests) {
635
737
            total += td->_unprocessed.size();
636
737
        }
637
638
736
        _unprocessed.reserve(total);
639
737
        for (const auto& td : tdigests) {
640
737
            _unprocessed.insert(_unprocessed.end(), td->_unprocessed.cbegin(),
641
737
                                td->_unprocessed.cend());
642
737
            _unprocessed_weight += td->_unprocessed_weight;
643
737
        }
644
736
    }
645
646
    // merge all processed centroids together into a single sorted vector
647
737
    void _merge_processed(const std::vector<const TDigest*>& tdigests) {
648
737
        if (tdigests.size() == 0) {
649
0
            return;
650
0
        }
651
652
737
        size_t total = 0;
653
737
        CentroidListQueue pq(CentroidListComparator {});
654
737
        for (const auto& td : tdigests) {
655
737
            const auto& sorted = td->_processed;
656
737
            auto size = sorted.size();
657
737
            if (size > 0) {
658
401
                pq.push(CentroidList(sorted));
659
401
                total += size;
660
401
                _processed_weight += td->_processed_weight;
661
401
            }
662
737
        }
663
737
        if (total == 0) {
664
336
            return;
665
336
        }
666
667
401
        if (_processed.size() > 0) {
668
400
            pq.push(CentroidList(_processed));
669
400
            total += _processed.size();
670
400
        }
671
672
401
        std::vector<Centroid> sorted;
673
401
        VLOG_CRITICAL << "total " << total;
674
401
        sorted.reserve(total);
675
676
1.93M
        while (!pq.empty()) {
677
1.93M
            auto best = pq.top();
678
1.93M
            pq.pop();
679
1.93M
            sorted.push_back(*(best.iter));
680
1.93M
            if (best.advance()) {
681
1.89M
                pq.push(best);
682
1.89M
            }
683
1.93M
        }
684
401
        _processed = std::move(sorted);
685
401
        if (_processed.size() > 0) {
686
401
            _min = std::min(_min, _processed[0].mean());
687
401
            _max = std::max(_max, (_processed.cend() - 1)->mean());
688
401
        }
689
401
    }
690
691
157k
    void _process_if_necessary() {
692
157k
        if (is_dirty()) {
693
402
            _process();
694
402
        }
695
157k
    }
696
697
13.8k
    void _update_cumulative() {
698
13.8k
        const auto n = _processed.size();
699
13.8k
        _cumulative.clear();
700
13.8k
        _cumulative.reserve(n + 1);
701
13.8k
        Weight previous = 0.0;
702
114M
        for (Index i = 0; i < n; i++) {
703
114M
            Weight current = _weight(i);
704
114M
            auto half_current = static_cast<Weight>(current / 2.0);
705
114M
            _cumulative.push_back(previous + half_current);
706
114M
            previous = previous + current;
707
114M
        }
708
13.8k
        _cumulative.push_back(previous);
709
13.8k
    }
710
711
    // merges _unprocessed centroids and _processed centroids together and processes them
712
    // when complete, _unprocessed will be empty and _processed will have at most _max_processed centroids
713
13.1k
    void _process() {
714
13.1k
        CentroidComparator cc;
715
        // select percentile_approx(lo_orderkey,0.5) from lineorder;
716
        // have test pdqsort and RadixSort, find here pdqsort performance is better when data is struct Centroid
717
        // But when sort plain type like int/float of std::vector<T>, find RadixSort is better
718
13.1k
        pdqsort(_unprocessed.begin(), _unprocessed.end(), cc);
719
13.1k
        auto count = _unprocessed.size();
720
13.1k
        _unprocessed.insert(_unprocessed.end(), _processed.cbegin(), _processed.cend());
721
13.1k
        std::inplace_merge(_unprocessed.begin(), _unprocessed.begin() + count, _unprocessed.end(),
722
13.1k
                           cc);
723
724
13.1k
        _processed_weight += _unprocessed_weight;
725
13.1k
        _unprocessed_weight = 0;
726
13.1k
        _processed.clear();
727
728
13.1k
        _processed.push_back(_unprocessed[0]);
729
13.1k
        Weight w_so_far = _unprocessed[0].weight();
730
13.1k
        Weight w_limit = _processed_weight * _integrated_q(1.0);
731
732
13.1k
        auto end = _unprocessed.end();
733
114M
        for (auto iter = _unprocessed.cbegin() + 1; iter < end; iter++) {
734
114M
            const auto& centroid = *iter;
735
114M
            Weight projected_w = w_so_far + centroid.weight();
736
114M
            if (projected_w <= w_limit) {
737
990k
                w_so_far = projected_w;
738
990k
                (_processed.end() - 1)->add(centroid);
739
113M
            } else {
740
113M
                auto k1 = _integrated_location(w_so_far / _processed_weight);
741
113M
                w_limit = _processed_weight * _integrated_q(static_cast<Value>(k1 + 1.0));
742
113M
                w_so_far += centroid.weight();
743
113M
                _processed.emplace_back(centroid);
744
113M
            }
745
114M
        }
746
13.1k
        _unprocessed.clear();
747
13.1k
        _min = std::min(_min, _processed[0].mean());
748
13.1k
        VLOG_CRITICAL << "new _min " << _min;
749
13.1k
        _max = std::max(_max, (_processed.cend() - 1)->mean());
750
13.1k
        VLOG_CRITICAL << "new _max " << _max;
751
13.1k
        _update_cumulative();
752
13.1k
    }
753
754
0
    size_t _check_weights(const std::vector<Centroid>& sorted, Value total) {
755
0
        size_t bad_weight = 0;
756
0
        auto k1 = 0.0;
757
0
        auto q = 0.0;
758
0
        for (auto iter = sorted.cbegin(); iter != sorted.cend(); iter++) {
759
0
            auto w = iter->weight();
760
0
            auto dq = w / total;
761
0
            auto k2 = _integrated_location(static_cast<Value>(q + dq));
762
0
            if (k2 - k1 > 1 && w != 1) {
763
0
                VLOG_CRITICAL << "Oversize centroid at " << std::distance(sorted.cbegin(), iter)
764
0
                              << " k1 " << k1 << " k2 " << k2 << " dk " << (k2 - k1) << " w " << w
765
0
                              << " q " << q;
766
0
                bad_weight++;
767
0
            }
768
0
            if (k2 - k1 > 1.5 && w != 1) {
769
0
                VLOG_CRITICAL << "Egregiously Oversize centroid at "
770
0
                              << std::distance(sorted.cbegin(), iter) << " k1 " << k1 << " k2 "
771
0
                              << k2 << " dk " << (k2 - k1) << " w " << w << " q " << q;
772
0
                bad_weight++;
773
0
            }
774
0
            q += dq;
775
0
            k1 = k2;
776
0
        }
777
0
778
0
        return bad_weight;
779
0
    }
780
781
    /**
782
    * Converts a quantile into a centroid scale value.  The centroid scale is nomin_ally
783
    * the number k of the centroid that a quantile point q should belong to.  Due to
784
    * round-offs, however, we can't align things perfectly without splitting points
785
    * and sorted.  We don't want to do that, so we have to allow for offsets.
786
    * In the end, the criterion is that any quantile range that spans a centroid
787
    * scale range more than one should be split across more than one centroid if
788
    * possible.  This won't be possible if the quantile range refers to a single point
789
    * or an already existing centroid.
790
    * <p/>
791
    * This mapping is steep near q=0 or q=1 so each centroid there will correspond to
792
    * less q range.  Near q=0.5, the mapping is flatter so that sorted there will
793
    * represent a larger chunk of quantiles.
794
    *
795
    * @param q The quantile scale value to be mapped.
796
    * @return The centroid scale value corresponding to q.
797
    */
798
113M
    Value _integrated_location(Value q) const {
799
113M
        return static_cast<Value>(_compression * (std::asin(2.0 * q - 1.0) + M_PI / 2) / M_PI);
800
113M
    }
801
802
113M
    Value _integrated_q(Value k) const {
803
113M
        return static_cast<Value>(
804
113M
                (std::sin(std::min(k, _compression) * M_PI / _compression - M_PI / 2) + 1) / 2);
805
113M
    }
806
807
    /**
808
     * Same as {@link #_weighted_average_sorted(Value, Value, Value, Value)} but flips
809
     * the order of the variables if <code>x2</code> is greater than
810
     * <code>x1</code>.
811
    */
812
1.00k
    static Value _weighted_average(Value x1, Value w1, Value x2, Value w2) {
813
1.00k
        return (x1 <= x2) ? _weighted_average_sorted(x1, w1, x2, w2)
814
1.00k
                          : _weighted_average_sorted(x2, w2, x1, w1);
815
1.00k
    }
816
817
    /**
818
    * Compute the weighted average between <code>x1</code> with a weight of
819
    * <code>w1</code> and <code>x2</code> with a weight of <code>w2</code>.
820
    * This expects <code>x1</code> to be less than or equal to <code>x2</code>
821
    * and is guaranteed to return a number between <code>x1</code> and
822
    * <code>x2</code>.
823
    */
824
1.00k
    static Value _weighted_average_sorted(Value x1, Value w1, Value x2, Value w2) {
825
1.00k
        DCHECK_LE(x1, x2);
826
1.00k
        const Value x = (x1 * w1 + x2 * w2) / (w1 + w2);
827
1.00k
        return std::max(x1, std::min(x, x2));
828
1.00k
    }
829
830
0
    static Value _interpolate(Value x, Value x0, Value x1) { return (x - x0) / (x1 - x0); }
831
832
    /**
833
    * Computes an interpolated value of a quantile that is between two sorted.
834
    *
835
    * Index is the quantile desired multiplied by the total number of samples - 1.
836
    *
837
    * @param index              Denormalized quantile desired
838
    * @param previous_index     The denormalized quantile corresponding to the center of the previous centroid.
839
    * @param next_index         The denormalized quantile corresponding to the center of the following centroid.
840
    * @param previous_mean      The mean of the previous centroid.
841
    * @param next_mean          The mean of the following centroid.
842
    * @return  The interpolated mean.
843
    */
844
    static Value _quantile(Value index, Value previous_index, Value next_index, Value previous_mean,
845
0
                           Value next_mean) {
846
0
        const auto delta = next_index - previous_index;
847
0
        const auto previous_weight = (next_index - index) / delta;
848
0
        const auto next_weight = (index - previous_index) / delta;
849
0
        return previous_mean * previous_weight + next_mean * next_weight;
850
0
    }
851
};
852
} // namespace doris