-
Notifications
You must be signed in to change notification settings - Fork 17
/
circllhist.c
1849 lines (1724 loc) · 54.5 KB
/
circllhist.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
/*
* Copyright (c) 2016-2021, Circonus, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#define _XOPEN_SOURCE
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <string.h>
#include <math.h>
#include <ctype.h>
#if !defined(WIN32)
#include <arpa/inet.h>
#include <sys/socket.h>
#endif
#include "circllhist.h"
#include "cdflib.h"
/* A search for inverse binmomial CDF values...
* Given a set of N retain each element with probability p resulting in M...
* tgt [0,1] is the placement on the CDF...
* It is reasonable to call this with drand48()
*/
static inline double cumbin_r(double s, double n, double pr, double ompr) {
double cum, ccum;
cumbin(&s, &n, &pr, &ompr, &cum, &ccum);
return cum;
}
static unsigned long binomial_reduce_random(unsigned long N, double pr, double tgt) {
if(pr == 1) return N;
if(pr == 0) return 0;
unsigned long left = 0, right = N;
unsigned long i = (double)N * pr; // we guess where we're likely to end up.
unsigned long bias = (double)N * 0.005; // then bias only the first bisection to reduce steps.
if(bias < 2) bias = 2;
// this are for calculating the CDF value
double ompr = 1.0 - pr;
double n = N;
double cum = 0;
double s = i;
while(right > left) {
s = i;
cum = cumbin_r(s, n, pr, ompr);
if(i == right) { // if i==left, we don't have the correct `cum` to compare to,
// we'll hit this case next iteration
if(right - left == 1) { // since we're not looking for an exact match, but just under
if(tgt <= cum) return i; // this
else return i-1; // or that
}
}
if(tgt <= cum) {
if(i == 0) return 0;
right = i;
}
else {
if(i == N) return N;
left = i;
}
// We don't necessarily bisect. B/c binomial distributions tend to be so tight,
// we can artificially limit our first bisection by about 50x. We'll rarely be wrong
// and we return to straight bisection on subsequent iterations, so it will only ever
// cost an extra step when we're unlucky.
unsigned long skip = (right - left) / bias;
if(bias != 2 && skip < 1) skip = (right - left) / 2;
if(skip < 1) skip = 1;
// because we may not simply bisect we have a conditional
if(tgt <= cum) {
i = right - skip;
}
else {
i = left + skip;
}
// simple bisection on subsequent iterations.
bias = 2;
}
return i;
}
static unsigned long binomial_reduce(unsigned long N, double pr) {
return binomial_reduce_random(N, pr, drand48());
}
const hist_allocator_t default_allocator = {
.malloc = malloc,
.calloc = calloc,
.free = free
};
static union {
uint64_t private_nan_internal_rep;
double private_nan_double_rep;
} private_nan_union = { .private_nan_internal_rep = 0x7fffffffffffffff };
static const hist_bucket_t hbnan = { (int8_t)0xff, 0 };
#define MAX_HIST_BINS (2 + 2 * 90 * 256)
#ifndef NDEBUG
#define unlikely(x) (x)
#define ASSERT_GOOD_HIST(h) do { \
if(h) { \
assert(h->allocd <= MAX_HIST_BINS); \
assert(h->used <= h->allocd); \
} \
} while(0)
#define ASSERT_GOOD_BUCKET(hb) assert(hist_bucket_is_valid(hb))
#else
#ifdef WIN32
#define unlikely(x) (x)
#else
#define unlikely(x) __builtin_expect(!!(x), 0)
#endif
#define ASSERT_GOOD_HIST(h)
#define ASSERT_GOOD_BUCKET(hb)
#endif
#define private_nan private_nan_union.private_nan_double_rep
#define HIST_POSITIVE_MIN_I 1e-128
#define HIST_NEGATIVE_MAX_I -1e-128
static double power_of_ten[256] = {
1, 10, 100, 1000, 10000, 100000, 1e+06, 1e+07, 1e+08, 1e+09, 1e+10,
1e+11, 1e+12, 1e+13, 1e+14, 1e+15, 1e+16, 1e+17, 1e+18, 1e+19, 1e+20,
1e+21, 1e+22, 1e+23, 1e+24, 1e+25, 1e+26, 1e+27, 1e+28, 1e+29, 1e+30,
1e+31, 1e+32, 1e+33, 1e+34, 1e+35, 1e+36, 1e+37, 1e+38, 1e+39, 1e+40,
1e+41, 1e+42, 1e+43, 1e+44, 1e+45, 1e+46, 1e+47, 1e+48, 1e+49, 1e+50,
1e+51, 1e+52, 1e+53, 1e+54, 1e+55, 1e+56, 1e+57, 1e+58, 1e+59, 1e+60,
1e+61, 1e+62, 1e+63, 1e+64, 1e+65, 1e+66, 1e+67, 1e+68, 1e+69, 1e+70,
1e+71, 1e+72, 1e+73, 1e+74, 1e+75, 1e+76, 1e+77, 1e+78, 1e+79, 1e+80,
1e+81, 1e+82, 1e+83, 1e+84, 1e+85, 1e+86, 1e+87, 1e+88, 1e+89, 1e+90,
1e+91, 1e+92, 1e+93, 1e+94, 1e+95, 1e+96, 1e+97, 1e+98, 1e+99, 1e+100,
1e+101, 1e+102, 1e+103, 1e+104, 1e+105, 1e+106, 1e+107, 1e+108, 1e+109,
1e+110, 1e+111, 1e+112, 1e+113, 1e+114, 1e+115, 1e+116, 1e+117, 1e+118,
1e+119, 1e+120, 1e+121, 1e+122, 1e+123, 1e+124, 1e+125, 1e+126, 1e+127,
1e-128, 1e-127, 1e-126, 1e-125, 1e-124, 1e-123, 1e-122, 1e-121, 1e-120,
1e-119, 1e-118, 1e-117, 1e-116, 1e-115, 1e-114, 1e-113, 1e-112, 1e-111,
1e-110, 1e-109, 1e-108, 1e-107, 1e-106, 1e-105, 1e-104, 1e-103, 1e-102,
1e-101, 1e-100, 1e-99, 1e-98, 1e-97, 1e-96,
1e-95, 1e-94, 1e-93, 1e-92, 1e-91, 1e-90, 1e-89, 1e-88, 1e-87, 1e-86,
1e-85, 1e-84, 1e-83, 1e-82, 1e-81, 1e-80, 1e-79, 1e-78, 1e-77, 1e-76,
1e-75, 1e-74, 1e-73, 1e-72, 1e-71, 1e-70, 1e-69, 1e-68, 1e-67, 1e-66,
1e-65, 1e-64, 1e-63, 1e-62, 1e-61, 1e-60, 1e-59, 1e-58, 1e-57, 1e-56,
1e-55, 1e-54, 1e-53, 1e-52, 1e-51, 1e-50, 1e-49, 1e-48, 1e-47, 1e-46,
1e-45, 1e-44, 1e-43, 1e-42, 1e-41, 1e-40, 1e-39, 1e-38, 1e-37, 1e-36,
1e-35, 1e-34, 1e-33, 1e-32, 1e-31, 1e-30, 1e-29, 1e-28, 1e-27, 1e-26,
1e-25, 1e-24, 1e-23, 1e-22, 1e-21, 1e-20, 1e-19, 1e-18, 1e-17, 1e-16,
1e-15, 1e-14, 1e-13, 1e-12, 1e-11, 1e-10, 1e-09, 1e-08, 1e-07, 1e-06,
1e-05, 0.0001, 0.001, 0.01, 0.1
};
static const char __b64[] = {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/', 0x00 };
struct hist_flevel {
uint8_t l2;
uint8_t l1;
};
//! A bucket-count pair
#if defined(WIN32)
#pragma pack(push, 1)
struct hist_bv_pair {
hist_bucket_t bucket;
uint64_t count;
};
#pragma pack(pop)
#else
struct hist_bv_pair {
hist_bucket_t bucket;
uint64_t count;
}__attribute__((packed));
#endif
//! The histogram structure
//! Internals are regarded private and might change with version.
//! Only use the public methods to operate on this structure.
struct histogram {
uint16_t allocd; //!< number of allocated bv pairs
uint16_t used; //!< number of used bv pairs
uint32_t fast: 1;
const hist_allocator_t *allocator;
struct hist_bv_pair *bvs; //!< pointer to bv-pairs
};
struct histogram_fast {
struct histogram internal;
uint16_t *faster[256];
};
uint64_t bvl_limits[7] = {
0x00000000000000ffULL, 0x0000000000000ffffULL,
0x0000000000ffffffULL, 0x00000000fffffffffULL,
0x000000ffffffffffULL, 0x0000fffffffffffffULL,
0x00ffffffffffffffULL
};
typedef enum {
BVL1 = 0,
BVL2 = 1,
BVL3 = 2,
BVL4 = 3,
BVL5 = 4,
BVL6 = 5,
BVL7 = 6,
BVL8 = 7
} bvdatum_t;
static inline int
hist_bucket_isnan(const hist_bucket_t hb) {
int aval = abs(hb.val);
if (99 < aval) return 1; // in [100... ]: nan
if ( 9 < aval) return 0; // in [10 - 99]: valid range
if ( 0 < aval) return 1; // in [1 - 9 ]: nan
if ( 0 == aval) return 0; // in [0]: zero bucket
assert(0);
return 0;
}
/* It's either not NaN, or exactly matches the one, true NaN */
static inline int
hist_bucket_is_valid(const hist_bucket_t hb) {
return !hist_bucket_isnan(hb) || (hb.val == hbnan.val && hb.exp == hbnan.exp);
}
static ssize_t
bv_size(const histogram_t *h, int idx) {
int i;
for(i=0; i<BVL8; i++)
if(h->bvs[idx].count <= bvl_limits[i]) return 3 + i + 1;
return 3+8;
}
static ssize_t
bv_write(const histogram_t *h, int idx, void *buff, ssize_t size) {
int i;
uint8_t *cp;
ssize_t needed;
bvdatum_t tgt_type = BVL8;
for(i=0; i<BVL8; i++)
if(h->bvs[idx].count <= bvl_limits[i]) {
tgt_type = i;
break;
}
needed = 3 + tgt_type + 1;
if(needed > size) return -1;
cp = buff;
cp[0] = h->bvs[idx].bucket.val;
cp[1] = h->bvs[idx].bucket.exp;
cp[2] = tgt_type;
for(i=tgt_type;i>=0;i--)
cp[i+3] = ((h->bvs[idx].count >> (i * 8)) & 0xff);
return needed;
}
static ssize_t
bv_read(histogram_t *h, int idx, const void *buff, ssize_t len) {
const uint8_t *cp;
uint64_t count = 0;
bvdatum_t tgt_type;
int i;
assert(idx == h->used);
if(len < 3) return -1;
cp = buff;
tgt_type = cp[2];
if(tgt_type > BVL8) return -1;
if(len < 3 + tgt_type + 1) return -1;
for(i=tgt_type;i>=0;i--)
count |= ((uint64_t)cp[i+3]) << (i * 8);
if(count != 0) {
h->bvs[idx].bucket.val = cp[0];
h->bvs[idx].bucket.exp = cp[1];
if(hist_bucket_is_valid(h->bvs[idx].bucket)) {
/* Protect against reading invalid/corrupt buckets */
h->bvs[idx].count = count;
h->used++;
}
}
return 3 + tgt_type + 1;
}
ssize_t
hist_serialize_estimate(const histogram_t *h) {
/* worst case if 2 for the length + 3+8 * used */
int i;
ssize_t len = 2;
if(h == NULL) return len;
for(i=0;i<h->used;i++) {
if(h->bvs[i].count != 0) {
len += bv_size(h, i);
}
}
return len;
}
#ifndef SKIP_LIBMTEV
ssize_t
hist_serialize_b64_estimate(const histogram_t *h) {
ssize_t len = hist_serialize_estimate(h);
// base 64 <=> 1 char == 6 bit <=> 4 chars = 3 Byte ==> n Bytpe = 4*ceil(len/3.) chars
return 4*(len/3+1);
}
#endif
#define ADVANCE(tracker, n) cp += (n), tracker += (n), len -= (n)
ssize_t
hist_serialize(const histogram_t *h, void *buff, ssize_t len) {
ssize_t written = 0;
uint8_t *cp = buff;
uint16_t nlen = 0;
int i;
if(len < 2) return -1;
ADVANCE(written, 2);
for(i=0;h && i<h->used;i++) {
ssize_t incr_written;
if(h->bvs[i].count) {
incr_written = bv_write(h, i, cp, len);
if(incr_written < 0) return -1;
nlen++;
ADVANCE(written, incr_written);
}
}
nlen = htons(nlen);
memcpy(buff, &nlen, sizeof(nlen));
return written;
}
static int
copy_of_mtev_b64_encode(const unsigned char *src, size_t src_len,
char *dest, size_t dest_len) {
const unsigned char *bptr = src;
char *eptr = dest;
int len = src_len;
int n = (((src_len + 2) / 3) * 4);
if(dest_len < n) return 0;
while(len > 2) {
*eptr++ = __b64[bptr[0] >> 2];
*eptr++ = __b64[((bptr[0] & 0x03) << 4) + (bptr[1] >> 4)];
*eptr++ = __b64[((bptr[1] & 0x0f) << 2) + (bptr[2] >> 6)];
*eptr++ = __b64[bptr[2] & 0x3f];
bptr += 3;
len -= 3;
}
if(len != 0) {
*eptr++ = __b64[bptr[0] >> 2];
if(len > 1) {
*eptr++ = __b64[((bptr[0] & 0x03) << 4) + (bptr[1] >> 4)];
*eptr++ = __b64[(bptr[1] & 0x0f) << 2];
*eptr = '=';
} else {
*eptr++ = __b64[(bptr[0] & 0x03) << 4];
*eptr++ = '=';
*eptr = '=';
}
}
return n;
}
ssize_t
hist_serialize_b64(const histogram_t *h, char *b64_serialized_histo_buff, ssize_t buff_len) {
ssize_t serialize_buff_length = hist_serialize_estimate(h);
uint8_t serialize_buff_static[8192];
void *serialize_buff = (void *)serialize_buff_static;
if(serialize_buff_length > sizeof(serialize_buff_static)) {
serialize_buff = malloc(serialize_buff_length);
if(!serialize_buff) return -1;
}
ssize_t serialized_length = hist_serialize(h, serialize_buff, serialize_buff_length);
if (serialized_length > 0) {
serialized_length = copy_of_mtev_b64_encode(serialize_buff, serialized_length, b64_serialized_histo_buff, buff_len);
}
if(serialize_buff != (void *)serialize_buff_static) free(serialize_buff);
return serialized_length;
}
ssize_t
hist_deserialize(histogram_t *h, const void *buff, ssize_t len) {
const uint8_t *cp = buff;
ssize_t bytes_read = 0;
uint16_t nlen, cnt;
if(len < 2) goto bad_read;
if(h->bvs) h->allocator->free(h->bvs);
h->bvs = NULL;
memcpy(&nlen, cp, sizeof(nlen));
ADVANCE(bytes_read, 2);
h->used = 0;
cnt = ntohs(nlen);
h->allocd = cnt;
if(h->allocd == 0) return bytes_read;
h->bvs = h->allocator->calloc(h->allocd, sizeof(*h->bvs));
if(!h->bvs) goto bad_read; /* yeah, yeah... bad label name */
while(len > 0 && cnt > 0) {
ssize_t incr_read = 0;
incr_read = bv_read(h, h->used, cp, len);
if(incr_read < 0) goto bad_read;
ADVANCE(bytes_read, incr_read);
cnt--;
}
return bytes_read;
bad_read:
if(h->bvs) h->allocator->free(h->bvs);
h->bvs = NULL;
h->used = h->allocd = 0;
return -1;
}
static int
copy_of_mtev_b64_decode(const char *src, size_t src_len,
unsigned char *dest, size_t dest_len) {
const unsigned char *cp = (unsigned char *)src;
unsigned char *dcp = dest;
unsigned char ch, in[4], out[3];
int ib = 0, ob = 3, needed = (((src_len / 4) * 3) - 2);
if(dest_len < needed) return 0;
while(cp <= ((unsigned char *)src+src_len)) {
if((*cp >= 'A') && (*cp <= 'Z')) ch = *cp - 'A';
else if((*cp >= 'a') && (*cp <= 'z')) ch = *cp - 'a' + 26;
else if((*cp >= '0') && (*cp <= '9')) ch = *cp - '0' + 52;
else if(*cp == '+') ch = 62;
else if(*cp == '/') ch = 63;
else if(*cp == '=') ch = 0xff;
else if(isspace((int)*cp)) { cp++; continue; }
else break;
cp++;
if(ch == 0xff) {
if(ib == 0) break;
if(ib == 1 || ib == 2) ob = 1;
else ob = 2;
while (ib < 3)
in[ib++] = '\0';
}
in[ib++] = ch;
if(ib == 4) {
out[0] = (in[0] << 2) | ((in[1] & 0x30) >> 4);
out[1] = ((in[1] & 0x0f) << 4) | ((in[2] & 0x3c) >> 2);
out[2] = ((in[2] & 0x03) << 6) | (in[3] & 0x3f);
for(ib = 0; ib < ob; ib++)
*dcp++ = out[ib];
ib = 0;
}
}
return dcp - (unsigned char *)dest;
}
ssize_t hist_deserialize_b64(histogram_t *h, const void *b64_string, ssize_t b64_string_len) {
int decoded_hist_len;
unsigned char decoded_hist_static[8192];
unsigned char* decoded_hist = decoded_hist_static;
if(b64_string_len > sizeof(decoded_hist_static)) {
decoded_hist = malloc(b64_string_len);
if(!decoded_hist) return -1;
}
decoded_hist_len = copy_of_mtev_b64_decode(b64_string, b64_string_len, decoded_hist, b64_string_len);
ssize_t bytes_read = -1;
if (decoded_hist_len >= 2) {
bytes_read = hist_deserialize(h, decoded_hist, decoded_hist_len);
if (bytes_read != decoded_hist_len) {
bytes_read = -1;
}
}
if(decoded_hist != decoded_hist_static) free(decoded_hist);
return bytes_read;
}
static inline
int hist_bucket_cmp(hist_bucket_t h1, hist_bucket_t h2) {
ASSERT_GOOD_BUCKET(h1);
ASSERT_GOOD_BUCKET(h2);
// checks if h1 < h2 on the real axis.
if(*(uint16_t *)&h1 == *(uint16_t *)&h2) return 0;
/* place NaNs at the beginning always */
if(hist_bucket_isnan(h1)) return 1;
if(hist_bucket_isnan(h2)) return -1;
/* zero values need special treatment */
if(h1.val == 0) return (h2.val > 0) ? 1 : -1;
if(h2.val == 0) return (h1.val < 0) ? 1 : -1;
/* opposite signs? */
if(h1.val < 0 && h2.val > 0) return 1;
if(h1.val > 0 && h2.val < 0) return -1;
/* here they are either both positive or both negative */
if(h1.exp == h2.exp) return (h1.val < h2.val) ? 1 : -1;
if(h1.exp > h2.exp) return (h1.val < 0) ? 1 : -1;
if(h1.exp < h2.exp) return (h1.val < 0) ? -1 : 1;
/* unreachable */
return 0;
}
double
hist_bucket_to_double(hist_bucket_t hb) {
uint8_t *pidx;
assert(private_nan != 0);
if(hist_bucket_isnan(hb)) return private_nan;
if(hb.val == 0) return 0.0;
pidx = (uint8_t *)&hb.exp;
return (((double)hb.val)/10.0) * power_of_ten[*pidx];
}
double
hist_bucket_to_double_bin_width(hist_bucket_t hb) {
if(hist_bucket_isnan(hb)) return private_nan;
if(hb.val == 0) return 0;
uint8_t *pidx;
pidx = (uint8_t *)&hb.exp;
return power_of_ten[*pidx]/10.0;
}
/*
* A midpoint in a bin should a minimum error midpoint, not a linear midpoint. Let
* us choose an M such that M * bin-width finds our our placement from the bottom
* of a bin
*
* Take the [B0,B1) bin, with a bin-width of B1-B0...
* as a sample S approaches B1, we see error ((B1-B0)(1-M))/B1
* and as S approaches B0, we see error ((B1-B0)M)/B0.
*
* M should be chosen such that:
*
* ((B1-B0)(1-M))/B1 = ((B1-B0)M)/B0
*
* (B0)(B1-B0)(1-M) = (B1)(B1-B0)(M)
*
* B0 - B0*M = B1*M
*
* B0 = (B0 + B1)(M)
*
* M = (B0)/(B0 + B1)
*/
double
hist_bucket_midpoint(hist_bucket_t in) {
double bottom, top, interval, ratio;
if(hist_bucket_isnan(in)) return private_nan;
if(in.val == 0) return 0;
bottom = hist_bucket_to_double(in);
interval = hist_bucket_to_double_bin_width(in);
if(bottom < 0) interval *= -1.0;
top = bottom + interval;
ratio = (bottom)/(bottom + top);
return bottom + interval * ratio;
}
/* This is used for quantile calculation,
* where we want the side of the bucket closest to -inf */
static double
hist_bucket_left(hist_bucket_t in) {
double out, interval;
if(hist_bucket_isnan(in)) return private_nan;
if(in.val == 0) return 0;
out = hist_bucket_to_double(in);
if(out > 0) return out;
/* out < 0 */
interval = hist_bucket_to_double_bin_width(in);
return out - interval;
}
double
hist_approx_mean(const histogram_t *hist) {
int i;
double divisor = 0.0;
double sum = 0.0;
if(!hist) return private_nan;
ASSERT_GOOD_HIST(hist);
for(i=0; i<hist->used; i++) {
if(hist_bucket_isnan(hist->bvs[i].bucket)) continue;
double midpoint = hist_bucket_midpoint(hist->bvs[i].bucket);
double cardinality = (double)hist->bvs[i].count;
divisor += cardinality;
sum += midpoint * cardinality;
}
if(divisor == 0.0) return private_nan;
return sum/divisor;
}
double
hist_approx_sum(const histogram_t *hist) {
int i;
double sum = 0.0;
if(!hist) return 0.0;
ASSERT_GOOD_HIST(hist);
for(i=0; i<hist->used; i++) {
if(hist_bucket_isnan(hist->bvs[i].bucket)) continue;
double value = hist_bucket_midpoint(hist->bvs[i].bucket);
double cardinality = (double)hist->bvs[i].count;
sum += value * cardinality;
}
return sum;
}
double
hist_approx_stddev(const histogram_t *hist) {
int i;
double total_count = 0.0;
double s1 = 0.0;
double s2 = 0.0;
if(!hist) return private_nan;
ASSERT_GOOD_HIST(hist);
for(i=0; i<hist->used; i++) {
if(hist_bucket_isnan(hist->bvs[i].bucket)) continue;
double midpoint = hist_bucket_midpoint(hist->bvs[i].bucket);
double count = hist->bvs[i].count;
total_count += count;
s1 += midpoint * count;
s2 += pow(midpoint, 2.0) * count;
}
if(total_count == 0.0) return private_nan;
return sqrt(s2 / total_count - pow(s1 / total_count, 2.0));
}
double
hist_approx_moment(const histogram_t *hist, double k) {
int i;
double total_count = 0.0;
double sk = 0.0;
if(!hist) return private_nan;
ASSERT_GOOD_HIST(hist);
for(i=0; i<hist->used; i++) {
if(hist_bucket_isnan(hist->bvs[i].bucket)) continue;
double midpoint = hist_bucket_midpoint(hist->bvs[i].bucket);
double count = hist->bvs[i].count;
total_count += count;
sk += pow(midpoint, k) * count;
}
if(total_count == 0.0) return private_nan;
return sk / pow(total_count, k);
}
void
hist_clamp(histogram_t *hist, double lower, double upper) {
int needs_cull = 0;
if(!hist) return;
ASSERT_GOOD_HIST(hist);
for(int i=0; i<hist->used; i++) {
if(hist_bucket_isnan(hist->bvs[i].bucket)) {
needs_cull = 1;
hist->bvs[i].count = 0;
continue;
}
double bucket_lower = hist_bucket_to_double(hist->bvs[i].bucket);
double bucket_upper;
if(bucket_lower < 0) {
bucket_upper = bucket_lower;
bucket_lower = bucket_upper - hist_bucket_to_double_bin_width(hist->bvs[i].bucket);
} else {
bucket_upper = bucket_lower + hist_bucket_to_double_bin_width(hist->bvs[i].bucket);
}
if(upper < bucket_lower || lower > bucket_upper) {
needs_cull = 1;
hist->bvs[i].count = 0;
}
}
if(needs_cull) hist_remove_zeroes(hist);
}
uint64_t __attribute__((alias("hist_approx_count_below_inclusive"))) hist_approx_count_below(const histogram_t *hist, double threshold);
uint64_t __attribute__((alias("hist_approx_count_above_inclusive"))) hist_approx_count_above(const histogram_t *hist, double threshold);
uint64_t
hist_approx_count_below_inclusive(const histogram_t *hist, double threshold) {
int i;
uint64_t running_count = 0;
if(!hist) return 0;
ASSERT_GOOD_HIST(hist);
hist_bucket_t tgt = double_to_hist_bucket(threshold);
for(i=0; i<hist->used; i++) {
if(hist_bucket_isnan(hist->bvs[i].bucket)) continue;
if(hist_bucket_cmp(tgt, hist->bvs[i].bucket) <= 0) {
running_count += hist->bvs[i].count;
}
else break;
}
return running_count;
}
uint64_t
hist_approx_count_below_exclusive(const histogram_t *hist, double threshold) {
int i;
uint64_t running_count = 0;
if(!hist) return 0;
ASSERT_GOOD_HIST(hist);
hist_bucket_t tgt = double_to_hist_bucket(threshold);
for(i=0; i<hist->used; i++) {
if(hist_bucket_isnan(hist->bvs[i].bucket)) continue;
if(hist_bucket_cmp(tgt, hist->bvs[i].bucket) < 0) {
running_count += hist->bvs[i].count;
}
else break;
}
return running_count;
}
uint64_t
hist_approx_count_above_exclusive(const histogram_t *hist, double threshold) {
int i;
if(!hist) return 0;
ASSERT_GOOD_HIST(hist);
hist_bucket_t tgt = double_to_hist_bucket(threshold);
uint64_t running_count = hist_sample_count(hist);
for(i=0; i<hist->used; i++) {
if(hist_bucket_isnan(hist->bvs[i].bucket)) continue;
if(hist_bucket_cmp(tgt, hist->bvs[i].bucket) <= 0) {
running_count -= hist->bvs[i].count;
}
else break;
}
return running_count;
}
uint64_t
hist_approx_count_above_inclusive(const histogram_t *hist, double threshold) {
int i;
if(!hist) return 0;
ASSERT_GOOD_HIST(hist);
hist_bucket_t tgt = double_to_hist_bucket(threshold);
uint64_t running_count = hist_sample_count(hist);
for(i=0; i<hist->used; i++) {
if(hist_bucket_isnan(hist->bvs[i].bucket)) continue;
if(hist_bucket_cmp(tgt, hist->bvs[i].bucket) < 0) {
running_count -= hist->bvs[i].count;
}
else break;
}
return running_count;
}
uint64_t
hist_approx_count_nearby(const histogram_t *hist, double value) {
int i;
if(!hist) return 0;
ASSERT_GOOD_HIST(hist);
for(i=0; i<hist->used; i++) {
if(hist_bucket_isnan(hist->bvs[i].bucket)) continue;
double bucket_bound = hist_bucket_to_double(hist->bvs[i].bucket);
double bucket_lower, bucket_upper;
if(bucket_bound < 0.0) {
bucket_lower = bucket_bound - hist_bucket_to_double_bin_width(hist->bvs[i].bucket);
bucket_upper = bucket_bound;
if(bucket_lower < value && value <= bucket_upper)
return hist->bvs[i].count;
}
else if(bucket_bound == 0.0) {
if(HIST_NEGATIVE_MAX_I < value && value < HIST_POSITIVE_MIN_I)
return hist->bvs[i].count;
}
else {
bucket_lower = bucket_bound;
bucket_upper = bucket_bound + hist_bucket_to_double_bin_width(hist->bvs[i].bucket);
if(bucket_lower <= value && value < bucket_upper)
return hist->bvs[i].count;
}
}
return 0;
}
typedef enum {
QTYPE1 = 1,
QTYPE7 = 7
} qtype_t;
/* 0 success,
* -1 (empty histogram),
* -2 (out of order quantile request)
* -3 (out of bound quantile)
*/
static inline int
hist_approx_quantile_dispatch(const histogram_t *hist, const double *q_in, int nq, double *q_out, qtype_t qtype) {
int i_q, i_b;
double total_cnt = 0.0, bucket_width = 0.0,
bucket_left = 0.0, lower_cnt = 0.0, upper_cnt = 0.0;
if(nq < 1) return 0; /* nothing requested, easy to satisfy successfully */
if(!hist) {
for(i_q=0;i_q<nq;i_q++) q_out[i_q] = private_nan;
return 0;
}
ASSERT_GOOD_HIST(hist);
/* Sum up all samples from all the bins */
for (i_b=0;i_b<hist->used;i_b++) {
/* ignore NaN */
if(hist_bucket_isnan(hist->bvs[i_b].bucket))
continue;
total_cnt += (double)hist->bvs[i_b].count;
}
/* Run through the quantiles and make sure they are in order */
for (i_q=1;i_q<nq;i_q++) if(q_in[i_q-1] > q_in[i_q]) return -2;
if(total_cnt == 0) {
for(i_q=0;i_q<nq;i_q++) q_out[i_q] = private_nan;
return 0;
}
/* We use q_out as temporary space to hold the count-normalized quantiles */
for (i_q=0;i_q<nq;i_q++) {
if(q_in[i_q] < 0.0 || q_in[i_q] > 1.0) return -3;
switch (qtype) {
case QTYPE1:
q_out[i_q] = total_cnt * q_in[i_q];
break;
case QTYPE7:
q_out[i_q] = floor( (total_cnt - 1) * q_in[i_q] + 1 );
break;
}
}
#define TRACK_VARS(idx) do { \
bucket_width = hist_bucket_to_double_bin_width(hist->bvs[idx].bucket); \
bucket_left = hist_bucket_left(hist->bvs[idx].bucket); \
lower_cnt = upper_cnt; \
upper_cnt = lower_cnt + hist->bvs[idx].count; \
} while(0)
/* Find the least bin (first) */
for(i_b=0;i_b<hist->used;i_b++) {
/* We don't include NaNs */
if(hist_bucket_isnan(hist->bvs[i_b].bucket))
continue;
if(hist->bvs[i_b].count == 0)
continue;
TRACK_VARS(i_b);
break;
}
/* Next walk the bins and the quantiles together */
for(i_q=0;i_q<nq;i_q++) {
/* And within that, advance the bins as needed */
while(i_b < (hist->used-1) && upper_cnt < q_out[i_q]) {
i_b++;
TRACK_VARS(i_b);
}
if(bucket_width == 0) {
// 0 bucket case
q_out[i_q] = bucket_left;
}
else {
/* Approximate quantile position within a non-zero bucket
*
* We use the following model:
* We represent the bucket by n independent random variables, that are
* uniformly distributed across the bucket. Let X_1 < X_2 < ... < X_n
* be a sorted version of these. X_k will be Beta(k,n+1-k) distributed.
* The expected location of X_k is:
*
* x_k = bucket_left + k/(n+1) * bucket_width
*
* [ Variant: The ML estimator for the bucket position is
* at (k-1)/(n-1) for n>1 and 1/2 if n=1 ]
*/
uint64_t n = hist->bvs[i_b].count;
double k;
switch (qtype) {
case QTYPE1:
/*
* For Type 1 Quantiles:
* A q-quantile for the bucket, will be represented by the sample number:
*
* (q = 0) k = 1
* (q > 0) k = ceil(q*n)
*
* so that q=0 => k=1 and q=1 => k=n. This corresponds to Type=1 quantiles
* in the Hyndman-Fan list (Statistical Computing, 1996).
*/
;
double qn = q_out[i_q];
assert(qn >= lower_cnt);
assert(qn <= upper_cnt);
k = ceil(qn - lower_cnt);
if (k == 0) { // case q == 0 above
q_out[i_q] = bucket_left + 1.0/(n+1) * bucket_width;
}
else { // case q > 0 above
q_out[i_q] = bucket_left + k/(n+1) * bucket_width;
}
break;
case QTYPE7:
/*
* For Type 7 Quantiles, we consider samples at indices:
*
* k = floor( q*(n-1) + 1 )
*
* This corresponds to discretized Type=7 quantiles in
* the Hyndman-Fan list (Statistical Computing,
* 1996).
*/
;
k = q_out[i_q] - lower_cnt;
q_out[i_q] = bucket_left + k/(n+1) * bucket_width;
break;
}
}
}
return 0;
}
int
hist_approx_quantile(const histogram_t *hist, const double *q_in, int nq, double *q_out) {
return hist_approx_quantile_dispatch(hist, q_in, nq, q_out, QTYPE1);
}
int
hist_approx_quantile7(const histogram_t *hist, const double *q_in, int nq, double *q_out) {
return hist_approx_quantile_dispatch(hist, q_in, nq, q_out, QTYPE7);
}
hist_bucket_t
int_scale_to_hist_bucket(int64_t value, int scale) {
hist_bucket_t hb = { 0, 0 };
int sign = 1;
if(unlikely(value == 0)) return hb;
scale++;
if(unlikely(value < 0)) {
if(unlikely(value == INT64_MIN)) value = INT64_MAX;
else value = 0 - value;
sign = -1;
}
if(unlikely(value < 10)) {
value *= 10;
scale -= 1;
}
while(unlikely(value >= 100)) {
value /= 10;
scale++;
}
if(unlikely(scale < -128)) return hb;
if(unlikely(scale > 127)) return hbnan;
hb.val = sign * value;
hb.exp = scale;
ASSERT_GOOD_BUCKET(hb);
return hb;
}
hist_bucket_t
double_to_hist_bucket(double d) {
hist_bucket_t hb = { (int8_t)0xff, 0 }; // NaN
assert(private_nan != 0);
if(unlikely(isnan(d))) return hb;
if(unlikely(isinf(d))) return hb;
else if(unlikely(d==0)) hb.val = 0;
else {
int big_exp;
uint8_t *pidx;
int sign = (d < 0) ? -1 : 1;
d = fabs(d);
big_exp = (int32_t)floor(log10(d));
hb.exp = (int8_t)big_exp;
if(unlikely(hb.exp != big_exp)) { /* we rolled */
if(unlikely(big_exp >= 0)) return hbnan;
hb.val = 0;
hb.exp = 0;
return hb;
}
pidx = (uint8_t *)&hb.exp;
d /= power_of_ten[*pidx];
d *= 10;
// avoid rounding problem at the bucket boundary
// e.g. d=0.11 results in hb.val = 10 (should be 11)
// by allowing an error margin (in the order or magnitude
// of the expected rounding errors of the above transformations)
hb.val = sign * (int)floor(d + 1e-13);
if(unlikely(hb.val == 100 || hb.val == -100)) {
if (hb.exp < 127) {
hb.val /= 10;
hb.exp++;
} else { // can't increase exponent. Return NaN
return hbnan;