Coverage Report

Created: 2026-08-04 03:41

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