-
Notifications
You must be signed in to change notification settings - Fork 13
/
tdigest.c
3420 lines (2734 loc) · 86.4 KB
/
tdigest.c
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
/*
* tdigest.c - implementation of t-digest for PostgreSQL, useful for estimation
* of quantiles, percentiles, trimmed means, and various similar metrics.
*
* Copyright (C) Tomas Vondra, 2019
*/
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <sys/time.h>
#include <unistd.h>
#include <limits.h>
#include "postgres.h"
#include "libpq/pqformat.h"
#include "utils/array.h"
#include "utils/builtins.h"
#include "utils/lsyscache.h"
#include "catalog/pg_type.h"
PG_MODULE_MAGIC;
/*
* A centroid, used both for in-memory and on-disk storage.
*/
typedef struct centroid_t {
double mean;
int64 count;
} centroid_t;
/*
* On-disk representation of the t-digest.
*/
typedef struct tdigest_t {
int32 vl_len_; /* varlena header (do not touch directly!) */
int32 flags; /* reserved for future use (versioning, ...) */
int64 count; /* number of items added to the t-digest */
int compression; /* compression used to build the digest */
int ncentroids; /* number of cetroids in the array */
centroid_t centroids[FLEXIBLE_ARRAY_MEMBER];
} tdigest_t;
/*
* Centroids used to store (sum,count), but we want to store (mean,count)
* because that allows us to prevent rounding errors e.g. when merging
* centroids with the same mean, or adding the same value to the centroid.
*
* To handle existing tdigest data in backwards-compatible way, we have
* a flag marking the new ones with mean, and we convert the old values.
*/
#define TDIGEST_STORES_MEAN 0x0001
/*
* An aggregate state, representing the t-digest and some additional info
* (requested percentiles, ...).
*
* When adding new values to the t-digest, we add them as centroids into a
* separate "uncompacted" part of the array. While centroids need more space
* than plain points (24B vs. 8B), making the aggregate state quite a bit
* larger, it does simplify the code quite a bit as it only needs to deal
* with single struct type instead of two (centroids + points). But maybe
* we should separate those two things in the future.
*
* XXX We only ever use one of values/percentiles, never both at the same
* time. In the future the values may use a different data types than double
* (e.g. numeric), so we keep both fields.
*/
typedef struct tdigest_aggstate_t {
/* basic t-digest fields (centroids at the end) */
int64 count; /* number of samples in the digest */
int ncompactions; /* number of merges/compactions */
int compression; /* compression algorithm */
int ncentroids; /* number of centroids */
int ncompacted; /* compacted part */
/* array of requested percentiles and values */
int npercentiles; /* number of percentiles */
int nvalues; /* number of values */
double trim_low; /* low threshold (for trimmed aggs) */
double trim_high; /* high threshold (for trimmed aggs) */
double *percentiles; /* array of percentiles (if any) */
double *values; /* array of values (if any) */
centroid_t *centroids; /* centroids for the digest */
} tdigest_aggstate_t;
static int centroid_cmp(const void *a, const void *b);
#define PG_GETARG_TDIGEST(x) (tdigest_t *) PG_DETOAST_DATUM(PG_GETARG_DATUM(x))
/*
* Size of buffer for incoming data, as a multiple of the compression value.
* Quoting from the t-digest paper:
*
* The constant of proportionality should be determined by experiment, but
* micro-benchmarks indicate that C2/C1 is in the range from 5 to 20 for
* a single core of an Intel i7 processor. In these micro-benchmarks,
* increasing the buffer size to (10 * delta) dramatically improves the
* average speed but further buffer size increases have much less effect.
*
* XXX Maybe make the coefficient user-defined, with some reasonable limits
* (say 2 - 20), so that users can pick the right trade-off between speed
* and memory usage.
*/
#define BUFFER_SIZE(compression) (10 * (compression))
#define AssertBounds(index, length) Assert((index) >= 0 && (index) < (length))
#define MIN_COMPRESSION 10
#define MAX_COMPRESSION 10000
/* prototypes */
PG_FUNCTION_INFO_V1(tdigest_add_double_array);
PG_FUNCTION_INFO_V1(tdigest_add_double_array_count);
PG_FUNCTION_INFO_V1(tdigest_add_double_array_values);
PG_FUNCTION_INFO_V1(tdigest_add_double_array_values_count);
PG_FUNCTION_INFO_V1(tdigest_add_double);
PG_FUNCTION_INFO_V1(tdigest_add_double_count);
PG_FUNCTION_INFO_V1(tdigest_add_double_values);
PG_FUNCTION_INFO_V1(tdigest_add_double_values_count);
PG_FUNCTION_INFO_V1(tdigest_add_digest_array);
PG_FUNCTION_INFO_V1(tdigest_add_digest_array_values);
PG_FUNCTION_INFO_V1(tdigest_add_digest);
PG_FUNCTION_INFO_V1(tdigest_add_digest_values);
PG_FUNCTION_INFO_V1(tdigest_array_percentiles);
PG_FUNCTION_INFO_V1(tdigest_array_percentiles_of);
PG_FUNCTION_INFO_V1(tdigest_percentiles);
PG_FUNCTION_INFO_V1(tdigest_percentiles_of);
PG_FUNCTION_INFO_V1(tdigest_digest);
PG_FUNCTION_INFO_V1(tdigest_serial);
PG_FUNCTION_INFO_V1(tdigest_deserial);
PG_FUNCTION_INFO_V1(tdigest_combine);
PG_FUNCTION_INFO_V1(tdigest_in);
PG_FUNCTION_INFO_V1(tdigest_out);
PG_FUNCTION_INFO_V1(tdigest_send);
PG_FUNCTION_INFO_V1(tdigest_recv);
PG_FUNCTION_INFO_V1(tdigest_count);
PG_FUNCTION_INFO_V1(tdigest_to_json);
PG_FUNCTION_INFO_V1(tdigest_to_array);
PG_FUNCTION_INFO_V1(tdigest_add_double_increment);
PG_FUNCTION_INFO_V1(tdigest_add_double_array_increment);
PG_FUNCTION_INFO_V1(tdigest_union_double_increment);
PG_FUNCTION_INFO_V1(tdigest_add_double_trimmed);
PG_FUNCTION_INFO_V1(tdigest_add_double_count_trimmed);
PG_FUNCTION_INFO_V1(tdigest_add_digest_trimmed);
PG_FUNCTION_INFO_V1(tdigest_add_digest_count_trimmed);
PG_FUNCTION_INFO_V1(tdigest_trimmed_avg);
PG_FUNCTION_INFO_V1(tdigest_trimmed_sum);
PG_FUNCTION_INFO_V1(tdigest_digest_sum);
PG_FUNCTION_INFO_V1(tdigest_digest_avg);
Datum tdigest_add_double_array(PG_FUNCTION_ARGS);
Datum tdigest_add_double_array_count(PG_FUNCTION_ARGS);
Datum tdigest_add_double_array_values(PG_FUNCTION_ARGS);
Datum tdigest_add_double_array_values_count(PG_FUNCTION_ARGS);
Datum tdigest_add_double(PG_FUNCTION_ARGS);
Datum tdigest_add_double_count(PG_FUNCTION_ARGS);
Datum tdigest_add_double_values(PG_FUNCTION_ARGS);
Datum tdigest_add_double_values_count(PG_FUNCTION_ARGS);
Datum tdigest_add_digest_array(PG_FUNCTION_ARGS);
Datum tdigest_add_digest_array_values(PG_FUNCTION_ARGS);
Datum tdigest_add_digest(PG_FUNCTION_ARGS);
Datum tdigest_add_digest_values(PG_FUNCTION_ARGS);
Datum tdigest_array_percentiles(PG_FUNCTION_ARGS);
Datum tdigest_array_percentiles_of(PG_FUNCTION_ARGS);
Datum tdigest_percentiles(PG_FUNCTION_ARGS);
Datum tdigest_percentiles_of(PG_FUNCTION_ARGS);
Datum tdigest_digest(PG_FUNCTION_ARGS);
Datum tdigest_serial(PG_FUNCTION_ARGS);
Datum tdigest_deserial(PG_FUNCTION_ARGS);
Datum tdigest_combine(PG_FUNCTION_ARGS);
Datum tdigest_in(PG_FUNCTION_ARGS);
Datum tdigest_out(PG_FUNCTION_ARGS);
Datum tdigest_send(PG_FUNCTION_ARGS);
Datum tdigest_recv(PG_FUNCTION_ARGS);
Datum tdigest_count(PG_FUNCTION_ARGS);
Datum tdigest_add_double_increment(PG_FUNCTION_ARGS);
Datum tdigest_add_double_array_increment(PG_FUNCTION_ARGS);
Datum tdigest_union_double_increment(PG_FUNCTION_ARGS);
Datum tdigest_to_json(PG_FUNCTION_ARGS);
Datum tdigest_to_array(PG_FUNCTION_ARGS);
Datum tdigest_add_double_trimmed(PG_FUNCTION_ARGS);
Datum tdigest_add_double_count_trimmed(PG_FUNCTION_ARGS);
Datum tdigest_add_digest_trimmed(PG_FUNCTION_ARGS);
Datum tdigest_add_digest_count_trimmed(PG_FUNCTION_ARGS);
Datum tdigest_trimmed_avg(PG_FUNCTION_ARGS);
Datum tdigest_trimmed_sum(PG_FUNCTION_ARGS);
Datum tdigest_digest_sum(PG_FUNCTION_ARGS);
Datum tdigest_digest_avg(PG_FUNCTION_ARGS);
static Datum double_to_array(FunctionCallInfo fcinfo, double * d, int len);
static double *array_to_double(FunctionCallInfo fcinfo, ArrayType *v, int * len);
/* basic checks on the t-digest (proper sum of counts, ...) */
static void
AssertCheckTDigest(tdigest_t *digest)
{
#ifdef USE_ASSERT_CHECKING
int i;
int64 cnt;
Assert(digest->flags == 0 || digest->flags == TDIGEST_STORES_MEAN);
Assert((digest->compression >= MIN_COMPRESSION) &&
(digest->compression <= MAX_COMPRESSION));
Assert(digest->ncentroids >= 0);
Assert(digest->ncentroids <= BUFFER_SIZE(digest->compression));
cnt = 0;
for (i = 0; i < digest->ncentroids; i++)
{
Assert(digest->centroids[i].count > 0);
cnt += digest->centroids[i].count;
/* FIXME also check this does work with the scale function */
}
Assert(VARSIZE_ANY(digest) == offsetof(tdigest_t, centroids) +
digest->ncentroids * sizeof(centroid_t));
Assert(digest->count == cnt);
#endif
}
static void
AssertCheckTDigestAggState(tdigest_aggstate_t *state)
{
#ifdef USE_ASSERT_CHECKING
int i;
int64 cnt;
Assert(state->npercentiles >= 0);
Assert(((state->npercentiles == 0) && (state->percentiles == NULL)) ||
((state->npercentiles > 0) && (state->percentiles != NULL)));
for (i = 0; i < state->npercentiles; i++)
Assert((state->percentiles[i] >= 0.0) &&
(state->percentiles[i] <= 1.0));
Assert((state->compression >= MIN_COMPRESSION) &&
(state->compression <= MAX_COMPRESSION));
Assert(state->ncentroids >= 0);
Assert(state->ncentroids <= BUFFER_SIZE(state->compression));
cnt = 0;
for (i = 0; i < state->ncentroids; i++)
{
Assert(state->centroids[i].count > 0);
cnt += state->centroids[i].count;
/* XXX maybe check this does work with the scale function */
}
Assert(state->count == cnt);
#endif
}
static void
reverse_centroids(centroid_t *centroids, int ncentroids)
{
int start = 0,
end = (ncentroids - 1);
while (start < end)
{
centroid_t tmp = centroids[start];
centroids[start] = centroids[end];
centroids[end] = tmp;
start++;
end--;
}
}
static void
rebalance_centroids(centroid_t *centroids, int ncentroids,
int64 weight_before, int64 weight_after)
{
double ratio = weight_before / (double) weight_after;
int64 count_before = 0;
int64 count_after = 0;
int start = 0;
int end = (ncentroids - 1);
int i;
centroid_t *scratch = palloc(sizeof(centroid_t) * ncentroids);
i = 0;
while (i < ncentroids)
{
while (i < ncentroids)
{
scratch[start] = centroids[i];
count_before += centroids[i].count;
i++;
start++;
if (count_before > count_after * ratio)
break;
}
while (i < ncentroids)
{
scratch[end] = centroids[i];
count_after += centroids[i].count;
i++;
end--;
if (count_before < count_after * ratio)
break;
}
}
memcpy(centroids, scratch, sizeof(centroid_t) * ncentroids);
pfree(scratch);
}
/*
* Sort centroids in the digest.
*
* We have to sort the whole array, because we don't just simply sort the
* centroids - we do the rebalancing of items with the same mean too.
*/
static void
tdigest_sort(tdigest_aggstate_t *state)
{
int i;
int64 count_so_far;
int64 next_group;
int64 median_count;
/* do qsort on the non-sorted part */
pg_qsort(state->centroids,
state->ncentroids,
sizeof(centroid_t), centroid_cmp);
/*
* The centroids are sorted by (mean,count). That's fine for centroids up
* to median, but above median this ordering is incorrect for centroids
* with the same mean (or for groups crossing the median boundary). To fix
* this we 'rebalance' those groups. Those entirely above median can be
* simply sorted in the opposite order, while those crossing the median
* need to be rebalanced depending on what part is below/above median.
*/
count_so_far = 0;
next_group = 0; /* includes count_so_far */
median_count = (state->count / 2);
/*
* Split the centroids into groups with the same mean, process each group
* depending on whether it falls before/after median.
*/
i = 0;
while (i < state->ncentroids)
{
int j = i;
int group_size = 0;
/* determine the end of the group */
while ((j < state->ncentroids) &&
(state->centroids[i].mean == state->centroids[j].mean))
{
next_group += state->centroids[j].count;
group_size++;
j++;
}
/*
* We can ignore groups of size 1 (number of centroids, not counts), as
* those are trivially sorted.
*/
if (group_size > 1)
{
if (count_so_far >= median_count)
{
/* group fully above median - reverse the order */
reverse_centroids(&state->centroids[i], group_size);
}
else if (next_group >= median_count) /* group split by median */
{
rebalance_centroids(&state->centroids[i], group_size,
median_count - count_so_far,
next_group - median_count);
}
}
i = j;
count_so_far = next_group;
}
}
/*
* Perform compaction of the t-digest, i.e. merge the centroids as required
* by the compression parameter.
*
* We always keep the data sorted in ascending order. This way we can reuse
* the sort between compactions, and also when computing the quantiles.
*
* XXX Switch the direction regularly, to eliminate possible bias and improve
* accuracy, as mentioned in the paper.
*
* XXX This initially used the k1 scale function, but the implementation was
* not limiting the number of centroids for some reason (it might have been
* a bug in the implementation, of course). The current code is a modified
* copy from ajwerner [1], and AFAIK it's the k2 function, it's much simpler
* and generally works quite nicely.
*
* [1] https://github.com/ajwerner/tdigestc/blob/master/go/tdigest.c
*/
static void
tdigest_compact(tdigest_aggstate_t *state)
{
int i;
int cur; /* current centroid */
int64 count_so_far;
int64 total_count;
double denom;
double normalizer;
int start;
int step;
int n;
AssertCheckTDigestAggState(state);
/* if the digest is fully compacted, it's been already compacted */
if (state->ncompacted == state->ncentroids)
return;
tdigest_sort(state);
state->ncompactions++;
if (state->ncompactions % 2 == 0)
{
start = 0;
step = 1;
}
else
{
start = state->ncentroids - 1;
step = -1;
}
total_count = state->count;
denom = 2 * M_PI * total_count * log(total_count);
normalizer = state->compression / denom;
cur = start;
count_so_far = 0;
n = 1;
for (i = start + step; (i >= 0) && (i < state->ncentroids); i += step)
{
int64 proposed_count;
double q0;
double q2;
double z;
bool should_add;
proposed_count = state->centroids[cur].count + state->centroids[i].count;
z = proposed_count * normalizer;
q0 = count_so_far / (double) total_count;
q2 = (count_so_far + proposed_count) / (double) total_count;
should_add = (z <= (q0 * (1 - q0))) && (z <= (q2 * (1 - q2)));
if (should_add)
{
/*
* If both centroids have the same mean, don't calculate it again.
* The recaulculation may cause rounding errors, so that the means
* would drift apart over time. We want to keep them equal for as
* long as possible.
*/
if (state->centroids[cur].mean != state->centroids[i].mean)
{
double sum;
int64 count;
sum = state->centroids[i].count * state->centroids[i].mean;
sum += state->centroids[cur].count * state->centroids[cur].mean;
count = state->centroids[i].count;
count += state->centroids[cur].count;
state->centroids[cur].mean = (sum / count);
}
/* XXX Do this after possibly recalculating the mean. */
state->centroids[cur].count += state->centroids[i].count;
}
else
{
count_so_far += state->centroids[cur].count;
cur += step;
n++;
state->centroids[cur] = state->centroids[i];
}
if (cur != i)
{
state->centroids[i].count = 0;
state->centroids[i].mean = 0;
}
}
state->ncentroids = n;
state->ncompacted = state->ncentroids;
if (step < 0)
memmove(state->centroids, &state->centroids[cur], n * sizeof(centroid_t));
AssertCheckTDigestAggState(state);
Assert(state->ncentroids < BUFFER_SIZE(state->compression));
}
/*
* Estimate requested quantiles from the t-digest agg state.
*/
static void
tdigest_compute_quantiles(tdigest_aggstate_t *state, double *result)
{
int i, j;
AssertCheckTDigestAggState(state);
/*
* Trigger a compaction, which also sorts the data.
*
* XXX maybe just do a sort here, which should give us a bit more accurate
* results, probably.
*/
tdigest_compact(state);
for (i = 0; i < state->npercentiles; i++)
{
double count;
double delta;
double goal = (state->percentiles[i] * state->count);
bool on_the_right;
centroid_t *prev, *next;
centroid_t *c = NULL;
double slope;
/* first centroid for percentile 1.0 */
if (state->percentiles[i] == 0.0)
{
c = &state->centroids[0];
result[i] = c->mean;
continue;
}
/* last centroid for percentile 1.0 */
if (state->percentiles[i] == 1.0)
{
c = &state->centroids[state->ncentroids - 1];
result[i] = c->mean;
continue;
}
/* walk throught the centroids and count number of items */
count = 0;
for (j = 0; j < state->ncentroids; j++)
{
c = &state->centroids[j];
/* have we exceeded the expected count? */
if (count + c->count > goal)
break;
/* account for the centroid */
count += c->count;
}
delta = goal - count - (c->count / 2.0);
/*
* double arithmetics, so don't compare to 0.0 direcly, it's enough
* to be "close enough"
*/
if (fabs(delta) < 0.000000001)
{
result[i] = c->mean;
continue;
}
on_the_right = (delta > 0.0);
/*
* for extreme percentiles we might end on the right of the last node or on the
* left of the first node, instead of interpolating we return the mean of the node
*/
if ((on_the_right && (j+1) >= state->ncentroids) ||
(!on_the_right && (j-1) < 0))
{
result[i] = c->mean;
continue;
}
if (on_the_right)
{
prev = &state->centroids[j];
AssertBounds(j+1, state->ncentroids);
next = &state->centroids[j+1];
count += (prev->count / 2.0);
}
else
{
AssertBounds(j-1, state->ncentroids);
prev = &state->centroids[j-1];
next = &state->centroids[j];
count -= (prev->count / 2.0);
}
slope = (next->mean - prev->mean) / (next->count / 2.0 + prev->count / 2.0);
result[i] = prev->mean + slope * (goal - count);
}
}
/*
* Estimate inverse of quantile given a value from the t-digest agg state.
*
* Essentially an inverse to tdigest_compute_quantiles.
*/
static void
tdigest_compute_quantiles_of(tdigest_aggstate_t *state, double *result)
{
int i;
AssertCheckTDigestAggState(state);
/*
* Trigger a compaction, which also sorts the data.
*
* XXX maybe just do a sort here, which should give us a bit more accurate
* results, probably.
*/
tdigest_compact(state);
for (i = 0; i < state->nvalues; i++)
{
int j;
double count;
centroid_t *c = NULL;
centroid_t *prev;
double value = state->values[i];
double m, x;
count = 0;
for (j = 0; j < state->ncentroids; j++)
{
c = &state->centroids[j];
if (c->mean >= value)
break;
count += c->count;
}
/* the value exactly matches the mean */
if (value == c->mean)
{
int64 count_at_value = 0;
/*
* There may be multiple centroids with this mean (i.e. containing
* this value), so find all of them and sum their weights.
*/
while (state->centroids[j].mean == value && j < state->ncentroids)
{
count_at_value += state->centroids[j].count;
j++;
}
result[i] = (count + (count_at_value / 2.0)) / state->count;
continue;
}
else if (value > c->mean) /* past the largest */
{
result[i] = 1;
continue;
}
else if (j == 0) /* past the smallest */
{
result[i] = 0;
continue;
}
/*
* The value lies somewhere between two centroids. We want to figure out
* where along the line from the prev node to this node the value is.
*
* FIXME What if there are multiple centroids with the same mean as the
* prev/curr centroid? This probably needs to lookup all of them and sum
* their counts, just like we did in case of the exact match, no?
*/
prev = c - 1;
count -= (prev->count / 2);
/*
* We assume for both prev/curr centroid, half the count is on left/righ,
* so between them we have (prev->count/2 + curr->count/2). At zero we
* are in prev->mean and at (prev->count/2 + curr->count/2) we're at
* curr->mean.
*/
m = (c->mean - prev->mean) / (c->count / 2.0 + prev->count / 2.0);
x = (value - prev->mean) / m;
result[i] = (double) (count + x) / state->count;
}
}
/* add a value to the t-digest, trigger a compaction if full */
static void
tdigest_add(tdigest_aggstate_t *state, double v)
{
int compression = state->compression;
int ncentroids = state->ncentroids;
AssertCheckTDigestAggState(state);
/* make sure we have space for the value */
Assert(state->ncentroids < BUFFER_SIZE(compression));
/* for a single point, the value is both sum and mean */
state->centroids[ncentroids].count = 1;
state->centroids[ncentroids].mean = v;
state->ncentroids++;
state->count++;
Assert(state->ncentroids <= BUFFER_SIZE(compression));
/* if the buffer got full, trigger compaction here so that next
* insert has free space */
if (state->ncentroids == BUFFER_SIZE(compression))
tdigest_compact(state);
}
/*
* Add a centroid (possibly with count not equal to 1) to the t-digest,
* triggers a compaction when buffer full.
*/
static void
tdigest_add_centroid(tdigest_aggstate_t *state, double mean, int64 count)
{
int compression = state->compression;
int ncentroids = state->ncentroids;
AssertCheckTDigestAggState(state);
/* make sure we have space for the value */
Assert(state->ncentroids < BUFFER_SIZE(compression));
/* for a single point, the value is both sum and mean */
state->centroids[ncentroids].count = count;
state->centroids[ncentroids].mean = mean;
state->ncentroids++;
state->count += count;
Assert(state->ncentroids <= BUFFER_SIZE(compression));
/* if the buffer got full, trigger compaction here so that next
* insert has free space */
if (state->ncentroids == BUFFER_SIZE(compression))
tdigest_compact(state);
}
/* allocate t-digest with enough space for a requested number of centroids */
static tdigest_t *
tdigest_allocate(int ncentroids)
{
Size len;
tdigest_t *digest;
char *ptr;
len = offsetof(tdigest_t, centroids) + ncentroids * sizeof(centroid_t);
/* we pre-allocate the array for all centroids and also the buffer for incoming data */
ptr = palloc(len);
SET_VARSIZE(ptr, len);
digest = (tdigest_t *) ptr;
digest->flags = 0;
digest->ncentroids = 0;
digest->count = 0;
digest->compression = 0;
/* new tdigest are automatically storing mean */
digest->flags |= TDIGEST_STORES_MEAN;
return digest;
}
/*
* tdigest_update_format
* Update t-digest format to represent centroids as (mean,count).
*
* Switches the centroids from (sum,count) to (mean,count), so that all
* the places processing centroids can use just the new format.
*
* If the digest already uses the new format, this is a no-op. Otherwise
* a modified copy of the digest is returned.
*
* XXX This does not affect on-disk representation of existing digests,
* we create just an in-memory version of the digest. Only when the
* digest gets modified a new format will be written back.
*/
static tdigest_t *
tdigest_update_format(tdigest_t *digest)
{
int i;
int s;
char *ptr;
/* if already new format, we're done */
if (digest->flags & TDIGEST_STORES_MEAN)
return digest;
/*
* We'll convert the digest so that centroids use means, but we must
* not modify the input digest - it might be just a pointer to data
* buffer, or something like that. So we have to create a copy first.
*/
s = VARSIZE_ANY(digest);
ptr = palloc(s);
memcpy(ptr, digest, s);
digest = (tdigest_t *) ptr;
/* And now tweak the contents of the copy. */
for (i = 0; i < digest->ncentroids; i++)
{
digest->centroids[i].mean
= digest->centroids[i].mean / digest->centroids[i].count;
}
digest->flags |= TDIGEST_STORES_MEAN;
return digest;
}
/*
* allocate a tdigest aggregate state, along with space for percentile(s)
* and value(s) requested when calling the aggregate function
*/
static tdigest_aggstate_t *
tdigest_aggstate_allocate(int npercentiles, int nvalues, int compression)
{
Size len;
tdigest_aggstate_t *state;
char *ptr;
/* at least one of those values is 0 */
Assert(nvalues == 0 || npercentiles == 0);
/*
* We allocate a single chunk for the struct including percentiles and
* centroids (including extra buffer for new data).
*/
len = MAXALIGN(sizeof(tdigest_aggstate_t)) +
MAXALIGN(sizeof(double) * npercentiles) +
MAXALIGN(sizeof(double) * nvalues) +
(BUFFER_SIZE(compression) * sizeof(centroid_t));
ptr = palloc0(len);
state = (tdigest_aggstate_t *) ptr;
ptr += MAXALIGN(sizeof(tdigest_aggstate_t));
state->nvalues = nvalues;
state->npercentiles = npercentiles;
state->compression = compression;
if (npercentiles > 0)
{
state->percentiles = (double *) ptr;
ptr += MAXALIGN(sizeof(double) * npercentiles);
}
if (nvalues > 0)
{
state->values = (double *) ptr;
ptr += MAXALIGN(sizeof(double) * nvalues);
}
state->centroids = (centroid_t *) ptr;
ptr += (BUFFER_SIZE(compression) * sizeof(centroid_t));
Assert(ptr == (char *) state + len);
return state;
}
static tdigest_t *
tdigest_aggstate_to_digest(tdigest_aggstate_t *state, bool compact)
{
int i;
tdigest_t *digest;
if (compact)
tdigest_compact(state);
digest = tdigest_allocate(state->ncentroids);
digest->count = state->count;
digest->ncentroids = state->ncentroids;
digest->compression = state->compression;
for (i = 0; i < state->ncentroids; i++)
{
digest->centroids[i].mean = state->centroids[i].mean;
digest->centroids[i].count = state->centroids[i].count;
}
return digest;
}
/* check that the requested percentiles are valid */
static void
check_percentiles(double *percentiles, int npercentiles)
{
int i;
for (i = 0; i < npercentiles; i++)
{
if ((percentiles[i] < 0.0) || (percentiles[i] > 1.0))
elog(ERROR, "invalid percentile value %f, should be in [0.0, 1.0]",
percentiles[i]);
}
}
static void
check_compression(int compression)
{
if (compression < MIN_COMPRESSION || compression > MAX_COMPRESSION)
elog(ERROR, "invalid compression value %d", compression);
}
static void
check_trim_values(double low, double high)
{
if (low < 0.0)
elog(ERROR, "invalid low percentile value %f, should be in [0.0, 1.0]",
low);
if (high > 1.0)
elog(ERROR, "invalid high percentile value %f, should be in [0.0, 1.0]",
high);
if (low >= high)
elog(ERROR, "invalid low/high percentile values %f/%f, should be low < high",
low, high);
}
/*
* Add a value to the tdigest (create one if needed). Transition function
* for tdigest aggregate with a single percentile.
*/
Datum
tdigest_add_double(PG_FUNCTION_ARGS)
{
tdigest_aggstate_t *state;
MemoryContext aggcontext;
/* cannot be called directly because of internal-type argument */
if (!AggCheckCallContext(fcinfo, &aggcontext))
elog(ERROR, "tdigest_add_double called in non-aggregate context");
/*
* We want to skip NULL values altogether - we return either the existing
* t-digest (if it already exists) or NULL.
*/
if (PG_ARGISNULL(1))
{