a5eedcb951bfafc819701a740bcad64e68f162ac
[ccan] / ccan / tally / tally.c
1 /* Licensed under LGPLv3+ - see LICENSE file for details */
2 #include <ccan/tally/tally.h>
3 #include <ccan/build_assert/build_assert.h>
4 #include <ccan/likely/likely.h>
5 #include <stdint.h>
6 #include <limits.h>
7 #include <string.h>
8 #include <stdio.h>
9 #include <assert.h>
10 #include <stdlib.h>
11
12 #define SIZET_BITS (sizeof(size_t)*CHAR_BIT)
13
14 /* We use power of 2 steps.  I tried being tricky, but it got buggy. */
15 struct tally {
16         ssize_t min, max;
17         size_t total[2];
18         /* This allows limited frequency analysis. */
19         unsigned buckets, step_bits;
20         size_t counts[1 /* Actually: [buckets] */ ];
21 };
22
23 struct tally *tally_new(unsigned buckets)
24 {
25         struct tally *tally;
26
27         /* There is always 1 bucket. */
28         if (buckets == 0)
29                 buckets = 1;
30
31         /* Overly cautious check for overflow. */
32         if (sizeof(*tally) * buckets / sizeof(*tally) != buckets)
33                 return NULL;
34         tally = (struct tally *)malloc(
35                 sizeof(*tally) + sizeof(tally->counts[0])*(buckets-1));
36         if (tally == NULL) {
37                 return NULL;
38         }
39
40         tally->max = ((size_t)1 << (SIZET_BITS - 1));
41         tally->min = ~tally->max;
42         tally->total[0] = tally->total[1] = 0;
43         tally->buckets = buckets;
44         tally->step_bits = 0;
45         memset(tally->counts, 0, sizeof(tally->counts[0])*buckets);
46         return tally;
47 }
48
49 static unsigned bucket_of(ssize_t min, unsigned step_bits, ssize_t val)
50 {
51         /* Don't over-shift. */
52         if (step_bits == SIZET_BITS)
53                 return 0;
54         assert(step_bits < SIZET_BITS);
55         return (size_t)(val - min) >> step_bits;
56 }
57
58 /* Return the min value in bucket b. */
59 static ssize_t bucket_min(ssize_t min, unsigned step_bits, unsigned b)
60 {
61         /* Don't over-shift. */
62         if (step_bits == SIZET_BITS)
63                 return min;
64         assert(step_bits < SIZET_BITS);
65         return min + ((ssize_t)b << step_bits);
66 }
67
68 /* Does shifting by this many bits truncate the number? */
69 static bool shift_overflows(size_t num, unsigned bits)
70 {
71         if (bits == 0)
72                 return false;
73
74         return ((num << bits) >> 1) != (num << (bits - 1));
75 }
76
77 /* When min or max change, we may need to shuffle the frequency counts. */
78 static void renormalize(struct tally *tally,
79                         ssize_t new_min, ssize_t new_max)
80 {
81         size_t range, spill;
82         unsigned int i, old_min;
83
84         /* Uninitialized?  Don't do anything... */
85         if (tally->max < tally->min)
86                 goto update;
87
88         /* If we don't have sufficient range, increase step bits until
89          * buckets cover entire range of ssize_t anyway. */
90         range = (new_max - new_min) + 1;
91         while (!shift_overflows(tally->buckets, tally->step_bits)
92                && range > ((size_t)tally->buckets << tally->step_bits)) {
93                 /* Collapse down. */
94                 for (i = 1; i < tally->buckets; i++) {
95                         tally->counts[i/2] += tally->counts[i];
96                         tally->counts[i] = 0;
97                 }
98                 tally->step_bits++;
99         }
100
101         /* Now if minimum has dropped, move buckets up. */
102         old_min = bucket_of(new_min, tally->step_bits, tally->min);
103         memmove(tally->counts + old_min,
104                 tally->counts,
105                 sizeof(tally->counts[0]) * (tally->buckets - old_min));
106         memset(tally->counts, 0, sizeof(tally->counts[0]) * old_min);
107
108         /* If we moved boundaries, adjust buckets to that ratio. */
109         spill = (tally->min - new_min) % (1 << tally->step_bits);
110         for (i = 0; i < tally->buckets-1; i++) {
111                 size_t adjust = (tally->counts[i] >> tally->step_bits) * spill;
112                 tally->counts[i] -= adjust;
113                 tally->counts[i+1] += adjust;
114         }
115
116 update:
117         tally->min = new_min;
118         tally->max = new_max;
119 }
120
121 void tally_add(struct tally *tally, ssize_t val)
122 {
123         ssize_t new_min = tally->min, new_max = tally->max;
124         bool need_renormalize = false;
125
126         if (val < tally->min) {
127                 new_min = val;
128                 need_renormalize = true;
129         }
130         if (val > tally->max) {
131                 new_max = val;
132                 need_renormalize = true;
133         }
134         if (need_renormalize)
135                 renormalize(tally, new_min, new_max);
136
137         /* 128-bit arithmetic!  If we didn't want exact mean, we could just
138          * pull it out of counts. */
139         if (val > 0 && tally->total[0] + val < tally->total[0])
140                 tally->total[1]++;
141         else if (val < 0 && tally->total[0] + val > tally->total[0])
142                 tally->total[1]--;
143         tally->total[0] += val;
144         tally->counts[bucket_of(tally->min, tally->step_bits, val)]++;
145 }
146
147 size_t tally_num(const struct tally *tally)
148 {
149         size_t i, num = 0;
150         for (i = 0; i < tally->buckets; i++)
151                 num += tally->counts[i];
152         return num;
153 }
154
155 ssize_t tally_min(const struct tally *tally)
156 {
157         return tally->min;
158 }
159
160 ssize_t tally_max(const struct tally *tally)
161 {
162         return tally->max;
163 }
164
165 /* FIXME: Own ccan module please! */
166 static unsigned fls64(uint64_t val)
167 {
168 #if HAVE_BUILTIN_CLZL
169         if (val <= ULONG_MAX) {
170                 /* This is significantly faster! */
171                 return val ? sizeof(long) * CHAR_BIT - __builtin_clzl(val) : 0;
172         } else {
173 #endif
174         uint64_t r = 64;
175
176         if (!val)
177                 return 0;
178         if (!(val & 0xffffffff00000000ull)) {
179                 val <<= 32;
180                 r -= 32;
181         }
182         if (!(val & 0xffff000000000000ull)) {
183                 val <<= 16;
184                 r -= 16;
185         }
186         if (!(val & 0xff00000000000000ull)) {
187                 val <<= 8;
188                 r -= 8;
189         }
190         if (!(val & 0xf000000000000000ull)) {
191                 val <<= 4;
192                 r -= 4;
193         }
194         if (!(val & 0xc000000000000000ull)) {
195                 val <<= 2;
196                 r -= 2;
197         }
198         if (!(val & 0x8000000000000000ull)) {
199                 val <<= 1;
200                 r -= 1;
201         }
202         return r;
203 #if HAVE_BUILTIN_CLZL
204         }
205 #endif
206 }
207
208 /* This is stolen straight from Hacker's Delight. */
209 static uint64_t divlu64(uint64_t u1, uint64_t u0, uint64_t v)
210 {
211         const uint64_t b = 4294967296ULL; // Number base (32 bits).
212         uint32_t un[4],           // Dividend and divisor
213                 vn[2];            // normalized and broken
214                                   // up into halfwords.
215         uint32_t q[2];            // Quotient as halfwords.
216         uint64_t un1, un0,        // Dividend and divisor
217                 vn0;              // as fullwords.
218         uint64_t qhat;            // Estimated quotient digit.
219         uint64_t rhat;            // A remainder.
220         uint64_t p;               // Product of two digits.
221         int64_t s, i, j, t, k;
222
223         if (u1 >= v)              // If overflow, return the largest
224                 return (uint64_t)-1; // possible quotient.
225
226         s = 64 - fls64(v);                // 0 <= s <= 63.
227         vn0 = v << s;             // Normalize divisor.
228         vn[1] = vn0 >> 32;        // Break divisor up into
229         vn[0] = vn0 & 0xFFFFFFFF; // two 32-bit halves.
230
231         // Shift dividend left.
232         un1 = ((u1 << s) | (u0 >> (64 - s))) & (-s >> 63);
233         un0 = u0 << s;
234         un[3] = un1 >> 32;        // Break dividend up into
235         un[2] = un1;              // four 32-bit halfwords
236         un[1] = un0 >> 32;        // Note: storing into
237         un[0] = un0;              // halfwords truncates.
238
239         for (j = 1; j >= 0; j--) {
240                 // Compute estimate qhat of q[j].
241                 qhat = (un[j+2]*b + un[j+1])/vn[1];
242                 rhat = (un[j+2]*b + un[j+1]) - qhat*vn[1];
243         again:
244                 if (qhat >= b || qhat*vn[0] > b*rhat + un[j]) {
245                         qhat = qhat - 1;
246                         rhat = rhat + vn[1];
247                         if (rhat < b) goto again;
248                 }
249
250                 // Multiply and subtract.
251                 k = 0;
252                 for (i = 0; i < 2; i++) {
253                         p = qhat*vn[i];
254                         t = un[i+j] - k - (p & 0xFFFFFFFF);
255                         un[i+j] = t;
256                         k = (p >> 32) - (t >> 32);
257                 }
258                 t = un[j+2] - k;
259                 un[j+2] = t;
260
261                 q[j] = qhat;              // Store quotient digit.
262                 if (t < 0) {              // If we subtracted too
263                         q[j] = q[j] - 1;  // much, add back.
264                         k = 0;
265                         for (i = 0; i < 2; i++) {
266                                 t = un[i+j] + vn[i] + k;
267                                 un[i+j] = t;
268                                 k = t >> 32;
269                         }
270                         un[j+2] = un[j+2] + k;
271                 }
272         } // End j.
273
274         return q[1]*b + q[0];
275 }
276
277 static int64_t divls64(int64_t u1, uint64_t u0, int64_t v)
278 {
279         int64_t q, uneg, vneg, diff, borrow;
280
281         uneg = u1 >> 63;          // -1 if u < 0.
282         if (uneg) {               // Compute the absolute
283                 u0 = -u0;         // value of the dividend u.
284                 borrow = (u0 != 0);
285                 u1 = -u1 - borrow;
286         }
287
288         vneg = v >> 63;           // -1 if v < 0.
289         v = (v ^ vneg) - vneg;    // Absolute value of v.
290
291         if ((uint64_t)u1 >= (uint64_t)v)
292                 goto overflow;
293
294         q = divlu64(u1, u0, v);
295
296         diff = uneg ^ vneg;       // Negate q if signs of
297         q = (q ^ diff) - diff;    // u and v differed.
298
299         if ((diff ^ q) < 0 && q != 0) {    // If overflow, return the largest
300         overflow:                          // possible neg. quotient.
301                 q = 0x8000000000000000ULL;
302         }
303         return q;
304 }
305
306 ssize_t tally_mean(const struct tally *tally)
307 {
308         size_t count = tally_num(tally);
309         if (!count)
310                 return 0;
311
312         if (sizeof(tally->total[0]) == sizeof(uint32_t)) {
313                 /* Use standard 64-bit arithmetic. */
314                 int64_t total = tally->total[0]
315                         | (((uint64_t)tally->total[1]) << 32);
316                 return total / count;
317         }
318         return divls64(tally->total[1], tally->total[0], count);
319 }
320
321 ssize_t tally_total(const struct tally *tally, ssize_t *overflow)
322 {
323         if (overflow) {
324                 *overflow = tally->total[1];
325                 return tally->total[0];
326         }
327
328         /* If result is negative, make sure we can represent it. */
329         if (tally->total[1] & ((size_t)1 << (SIZET_BITS-1))) {
330                 /* Must have only underflowed once, and must be able to
331                  * represent result at ssize_t. */
332                 if ((~tally->total[1])+1 != 0
333                     || (ssize_t)tally->total[0] >= 0) {
334                         /* Underflow, return minimum. */
335                         return (ssize_t)((size_t)1 << (SIZET_BITS - 1));
336                 }
337         } else {
338                 /* Result is positive, must not have overflowed, and must be
339                  * able to represent as ssize_t. */
340                 if (tally->total[1] || (ssize_t)tally->total[0] < 0) {
341                         /* Overflow.  Return maximum. */
342                         return (ssize_t)~((size_t)1 << (SIZET_BITS - 1));
343                 }
344         }
345         return tally->total[0];
346 }
347
348 static ssize_t bucket_range(const struct tally *tally, unsigned b, size_t *err)
349 {
350         ssize_t min, max;
351
352         min = bucket_min(tally->min, tally->step_bits, b);
353         if (b == tally->buckets - 1)
354                 max = tally->max;
355         else
356                 max = bucket_min(tally->min, tally->step_bits, b+1) - 1;
357
358         /* FIXME: Think harder about cumulative error; is this enough?. */
359         *err = (max - min + 1) / 2;
360         /* Avoid overflow. */
361         return min + (max - min) / 2;
362 }
363
364 ssize_t tally_approx_median(const struct tally *tally, size_t *err)
365 {
366         size_t count = tally_num(tally), total = 0;
367         unsigned int i;
368
369         for (i = 0; i < tally->buckets; i++) {
370                 total += tally->counts[i];
371                 if (total * 2 >= count)
372                         break;
373         }
374         return bucket_range(tally, i, err);
375 }
376
377 ssize_t tally_approx_mode(const struct tally *tally, size_t *err)
378 {
379         unsigned int i, min_best = 0, max_best = 0;
380
381         for (i = 0; i < tally->buckets; i++) {
382                 if (tally->counts[i] > tally->counts[min_best]) {
383                         min_best = max_best = i;
384                 } else if (tally->counts[i] == tally->counts[min_best]) {
385                         max_best = i;
386                 }
387         }
388
389         /* We can have more than one best, making our error huge. */
390         if (min_best != max_best) {
391                 ssize_t min, max;
392                 min = bucket_range(tally, min_best, err);
393                 max = bucket_range(tally, max_best, err);
394                 max += *err;
395                 *err += (size_t)(max - min);
396                 return min + (max - min) / 2;
397         }
398
399         return bucket_range(tally, min_best, err);
400 }
401
402 static unsigned get_max_bucket(const struct tally *tally)
403 {
404         unsigned int i;
405
406         for (i = tally->buckets; i > 0; i--)
407                 if (tally->counts[i-1])
408                         break;
409         return i;
410 }
411
412 char *tally_histogram(const struct tally *tally,
413                       unsigned width, unsigned height)
414 {
415         unsigned int i, count, max_bucket, largest_bucket;
416         struct tally *tmp;
417         char *graph, *p;
418
419         assert(width >= TALLY_MIN_HISTO_WIDTH);
420         assert(height >= TALLY_MIN_HISTO_HEIGHT);
421
422         /* Ignore unused buckets. */
423         max_bucket = get_max_bucket(tally);
424
425         /* FIXME: It'd be nice to smooth here... */
426         if (height >= max_bucket) {
427                 height = max_bucket;
428                 tmp = NULL;
429         } else {
430                 /* We create a temporary then renormalize so < height. */
431                 /* FIXME: Antialias properly! */
432                 tmp = tally_new(tally->buckets);
433                 if (!tmp)
434                         return NULL;
435                 tmp->min = tally->min;
436                 tmp->max = tally->max;
437                 tmp->step_bits = tally->step_bits;
438                 memcpy(tmp->counts, tally->counts,
439                        sizeof(tally->counts[0]) * tmp->buckets);
440                 while ((max_bucket = get_max_bucket(tmp)) >= height)
441                         renormalize(tmp, tmp->min, tmp->max * 2);
442                 /* Restore max */
443                 tmp->max = tally->max;
444                 tally = tmp;
445                 height = max_bucket;
446         }
447
448         /* Figure out longest line, for scale. */
449         largest_bucket = 0;
450         for (i = 0; i < tally->buckets; i++) {
451                 if (tally->counts[i] > largest_bucket)
452                         largest_bucket = tally->counts[i];
453         }
454
455         p = graph = (char *)malloc(height * (width + 1) + 1);
456         if (!graph) {
457                 free(tmp);
458                 return NULL;
459         }
460
461         for (i = 0; i < height; i++) {
462                 unsigned covered = 1, row;
463
464                 /* People expect minimum at the bottom. */
465                 row = height - i - 1;
466                 count = (double)tally->counts[row] / largest_bucket * (width-1)+1;
467
468                 if (row == 0)
469                         covered = snprintf(p, width, "%zi", tally->min);
470                 else if (row == height - 1)
471                         covered = snprintf(p, width, "%zi", tally->max);
472                 else if (row == bucket_of(tally->min, tally->step_bits, 0))
473                         *p = '+';
474                 else
475                         *p = '|';
476
477                 if (covered > width)
478                         covered = width;
479                 p += covered;
480
481                 if (count > covered)
482                         count -= covered;
483                 else
484                         count = 0;
485
486                 memset(p, '*', count);
487                 p += count;
488                 *p = '\n';
489                 p++;
490         }
491         *p = '\0';
492         free(tmp);
493         return graph;
494 }