forked from depp/metric-tree-demo
-
Notifications
You must be signed in to change notification settings - Fork 5
/
tree.c
652 lines (576 loc) · 16.6 KB
/
tree.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
/* Metric tree sample implementation.
This generates a bunch of pseudorandom 32-bit integers, inserts
them into an index, and queries the index for points within a
certain distance of the given point.
That is,
Let S = { N pseudorandom 32-bit integers }
Let d(x,y) be the (base-2) Hamming distance between x and y
Let q(x,r) = { y in S : d(x,y) <= r }
There are three implementations in here which can be selected at runtime.
"bk" is a BK-Tree. Each internal node has a center point, and each
child node contains a set of all points a certain distance away
from the center.
"vp" is a VP-Tree. Each internal node has a center point and two
children. The "near" child contains all points contained in a
closed ball of a certain radius around the center, and the "far"
node contains all other points.
"linear" is a linear search.
The tree implementations use a linear search for leaf nodes. The
maximum number of points in a leaf node is configurable at runtime,
but 1000 is a good number. If the number is low, say 1, then the
memory usage of the tree implementations will skyrocket to
unreasonable levels: more than 24 bytes per element.
Note that VP trees are slightly faster than BK trees for this
problem, and neither tree implementation significantly outperforms
linear search (that is, by a factor of two or more) for r > 6. */
#include <stdint.h>
#include <stdlib.h>
#include <time.h>
#include <stdio.h>
#include <assert.h>
#include <string.h>
#ifndef DO_PRINT
#define DO_PRINT 0
#endif
#ifndef VERBOSE
#define VERBOSE 1
#endif
#ifndef HAVE_POPCNT
#define HAVE_POPCNT 0
#endif
static uint32_t rand_x0, rand_x1, rand_c;
#define RAND_A 4284966893U
void
seedrand(void)
{
time_t t;
time(&t);
rand_x0 = t;
fprintf(stderr, "seed: %u\n", rand_x0);
rand_x1 = 0x038acaf3U;
rand_c = 0xa2cc5886U;
}
uint32_t
irand(void)
{
uint64_t y = (uint64_t)rand_x0 * RAND_A + rand_c;
rand_x0 = rand_x1;
rand_x1 = y;
rand_c = y >> 32;
return y;
}
__attribute__((malloc))
static void *
xmalloc(size_t sz)
{
void *p;
if (!sz)
return NULL;
p = malloc(sz);
if (!p) {
printf("error: malloc\n");
exit(1);
}
return p;
}
unsigned long
xatoul(const char *p)
{
char *e;
unsigned long x;
x = strtoul(p, &e, 0);
if (*e) {
printf("error: must be a number: '%s'\n", p);
exit(1);
}
return x;
}
typedef uint32_t bkey_t;
enum { MAX_DISTANCE = 32 };
#if HAVE_POPCNT
static inline unsigned
distance(bkey_t x, bkey_t y)
{
return __builtin_popcount(x^y);
}
#else
static inline unsigned
distance(bkey_t x, bkey_t y)
{
uint32_t d = x^y;
d = (d & 0x55555555U) + ((d >> 1) & 0x55555555U);
d = (d & 0x33333333U) + ((d >> 2) & 0x33333333U);
d = (d + (d >> 4)) & 0x0f0f0f0fU;
d = d + (d >> 8);
d = d + (d >> 16);
return d & 63;
}
#endif
static char keybuf[33];
static const char *
keystr(bkey_t k)
{
unsigned i;
for (i = 0; i < 32; ++i) {
keybuf[31 - i] = '0' + (k & 1);
k >>= 1;
}
keybuf[32] = '\0';
return keybuf;
}
static const char *
keystr2(bkey_t k, bkey_t ref)
{
unsigned i;
bkey_t d = ref ^ k;
for (i = 0; i < 32; ++i) {
keybuf[31 - i] = (d & 1) ? ('0' + (k & 1)) : '.';
d >>= 1;
k >>= 1;
}
keybuf[32] = '\0';
return keybuf;
}
static unsigned num_nodes = 0;
static size_t tree_size = 0;
struct buf {
bkey_t *keys;
size_t n, a;
};
static void
addkey(struct buf *restrict b, bkey_t k)
{
size_t na;
bkey_t *np;
if (b->n >= b->a) {
na = b->a ? 2*b->a : 16;
np = xmalloc(sizeof(*np) * na);
memcpy(np, b->keys, sizeof(*np) * b->n);
free(b->keys);
b->keys = np;
b->a = na;
}
b->keys[b->n++] = k;
}
static bkey_t *
generate_keys(unsigned long nkeys) {
puts("Generating keys...");
bkey_t *keys;
unsigned long i;
// Empty bitset for all 2^32 possible keys to prevent duplicates.
size_t bn = 1 << (32 - 5);
uint32_t *bits = xmalloc(sizeof(uint32_t) * bn);
for (i = 0; i < bn; ++i)
bits[i] = 0;
// Create unique keys.
keys = malloc(sizeof(*keys) * nkeys);
for (i = 0; i < nkeys; ) {
bkey_t key = irand();
if (!((bits[key >> 5] >> (key & 31)) & 1)) {
keys[i++] = key;
bits[key >> 5] |= 1 << (key & 31);
}
}
// Don't need the bitset anymore.
free(bits);
return keys;
}
/* Linear search ==================== */
struct linear {
size_t count;
bkey_t *keys;
};
static struct linear *
mktree_linear(const bkey_t *restrict keys, size_t n, size_t max_linear)
{
struct linear* node;
(void)max_linear;
node = xmalloc(sizeof(*node));
node->count = n;
node->keys = xmalloc(sizeof(bkey_t) * n);
num_nodes += 1;
tree_size += sizeof(bkey_t) * n + sizeof(*node);
memcpy(node->keys, keys, sizeof(bkey_t) * n);
return node;
}
static size_t
query_linear(struct buf *restrict b, struct linear *restrict root,
bkey_t ref, unsigned maxd)
{
size_t i;
const bkey_t *restrict p = root->keys;
for (i = 0; i < root->count; ++i)
if (distance(ref, p[i]) <= maxd)
addkey(b, p[i]);
return root->count;
}
/* Bitset search ==================== */
struct bitset {
uint32_t *bits;
};
static struct bitset *
mktree_bitset(const bkey_t *restrict keys, size_t n, size_t max_bitset)
{
struct bitset* node;
(void)max_bitset;
node = xmalloc(sizeof(*node));
size_t bn = 1 << (32 - 5);
node->bits = xmalloc(sizeof(uint32_t) * bn);
num_nodes += 1;
tree_size += (1 << (32 - 3)) + sizeof(*node);
for (size_t i = 0; i < bn; i++)
node->bits[i] = 0;
for (size_t i = 0; i < n; i++) {
bkey_t key = keys[i];
node->bits[key >> 5] |= 1 << (key & 31);
}
return node;
}
static size_t
search_bitset(struct buf *restrict b, uint32_t *bits,
bkey_t ref, unsigned maxd, bkey_t bit)
{
size_t count = 1;
if ((bits[ref >> 5] >> (ref & 31)) & 1)
addkey(b, ref);
if (maxd == 0)
return 1;
while (bit) {
count += search_bitset(b, bits, ref ^ bit, maxd - 1, bit >> 1);
bit >>= 1;
}
return count;
}
static size_t
query_bitset(struct buf *restrict b, struct bitset *restrict root,
bkey_t ref, unsigned maxd)
{
return search_bitset(b, root->bits, ref, maxd, 1 << 31);
}
/* BK-tree ==================== */
struct bktree {
unsigned short distance;
unsigned short linear;
union {
struct {
bkey_t key;
struct bktree *child;
} tree;
struct {
unsigned count;
bkey_t *keys;
} linear;
} data;
struct bktree *sibling;
};
static struct bktree *
mktree_bk(const bkey_t *restrict keys, size_t n, size_t max_linear)
{
size_t dcnt[MAX_DISTANCE + 1], i, a, pos[MAX_DISTANCE + 1], off, len;
bkey_t rootkey = keys[0], *tmp;
struct bktree *root, *child, *prev;
assert(n > 0);
num_nodes += 1;
/* Build root */
root = xmalloc(sizeof(*root));
tree_size += sizeof(*root);
root->distance = 0;
root->sibling = NULL;
if (n <= max_linear || n <= 1) {
root->linear = 1;
tmp = xmalloc(sizeof(*tmp) * n);
tree_size += sizeof(*tmp) * n;
memcpy(tmp, keys, sizeof(*tmp) * n);
root->data.linear.count = n;
root->data.linear.keys = tmp;
return root;
}
root->linear = 0;
root->data.tree.key = rootkey;
root->data.tree.child = NULL;
n -= 1;
keys += 1;
if (!n)
return root;
/* Sort keys by distance to root */
tmp = xmalloc(sizeof(*tmp) * n);
for (i = 0; i <= MAX_DISTANCE; ++i)
dcnt[i] = 0;
for (i = 0; i < n; ++i)
dcnt[distance(rootkey, keys[i])]++;
for (i = 0, a = 0; i <= MAX_DISTANCE; ++i)
dcnt[i] = (a += dcnt[i]);
assert(a == n);
memcpy(pos, dcnt, sizeof(pos));
for (i = 0; i < n; ++i)
tmp[--pos[distance(rootkey, keys[i])]] = keys[i];
/* Add child nodes */
for (i = 1, prev = NULL; i <= MAX_DISTANCE; ++i) {
off = dcnt[i-1];
len = dcnt[i] - off;
if (!len)
continue;
child = mktree_bk(tmp + off, len, max_linear);
child->distance = i;
if (prev)
prev->sibling = child;
else
root->data.tree.child = child;
prev = child;
}
free(tmp);
return root;
}
static size_t
query_bk(struct buf *restrict b, struct bktree *restrict root,
bkey_t ref, unsigned maxd)
{
/* We are trying to find x that satisfy d(ref,x) <= maxd
By triangle inequality, we know: d(root,x) <= d(root,ref) + d(ref,x)
By algebra: d(root,x) - d(root,ref) <= d(ref,x)
By transitivity: d(root,x) - d(root,ref) <= maxd
By algebra: d(root,x) <= maxd + d(root,ref) */
if (root->linear) {
const bkey_t *restrict keys = root->data.linear.keys;
unsigned i, n = root->data.linear.count;
for (i = 0; i < n; ++i)
if (distance(ref, keys[i]) <= maxd)
addkey(b, keys[i]);
return n;
} else {
unsigned d = distance(root->data.tree.key, ref);
struct bktree *p = root->data.tree.child;
size_t nc = 1;
if (d <= maxd)
addkey(b, root->data.tree.key);
for (; p && p->distance + maxd < d; p = p->sibling);
for (; p && p->distance <= maxd + d; p = p->sibling)
nc += query_bk(b, p, ref, maxd);
return nc;
}
}
/* VP-tree ==================== */
struct vptree {
unsigned short linear;
union {
struct {
/* Closed ball (d = threshold is included) */
unsigned short threshold;
bkey_t vantage;
struct vptree *near;
struct vptree *far;
} tree;
struct {
unsigned count;
bkey_t *keys;
} linear;
} data;
};
static struct vptree *
mktree_vp(const bkey_t *restrict keys, size_t n, size_t max_linear)
{
size_t dcnt[MAX_DISTANCE + 1], i, a;
bkey_t rootkey = keys[0], *tmp;
struct vptree *root;
unsigned k;
size_t median, nnear, nfar, inear, ifar;
assert(n > 0);
num_nodes += 1;
/* Build root */
root = xmalloc(sizeof(*root));
tree_size += sizeof(root);
if (n <= max_linear || n <= 1) {
root->linear = 1;
tmp = xmalloc(sizeof(*tmp) * n);
tree_size += sizeof(*tmp) * n;
memcpy(tmp, keys, sizeof(*tmp) * n);
root->data.linear.count = n;
root->data.linear.keys = tmp;
return root;
}
root->linear = 0;
root->data.tree.threshold = 0;
root->data.tree.vantage = rootkey;
root->data.tree.near = NULL;
root->data.tree.far = NULL;
n -= 1;
keys += 1;
if (!n)
return root;
/* Count keys inside the given ball */
for (i = 0; i <= MAX_DISTANCE; ++i)
dcnt[i] = 0;
for (i = 0; i < n; ++i)
dcnt[distance(rootkey, keys[i])]++;
for (i = 0, a = 0; i <= MAX_DISTANCE; ++i)
dcnt[i] = (a += dcnt[i]);
assert(a == n);
median = dcnt[0] + (n - dcnt[0]) / 2;
for (k = 1; k <= MAX_DISTANCE; ++k)
if (dcnt[k] > median)
break;
if (k != 1 && median - dcnt[k-1] <= dcnt[k] - median)
k--;
nnear = dcnt[k] - dcnt[0];
nfar = n - dcnt[k];
// printf("keys: %zu; near: %zu; far: %zu; k=%u\n", n, nnear, nfar, k);
/* Sort keys into near and far sets */
tmp = xmalloc(sizeof(*tmp) * (nnear + nfar));
inear = 0;
ifar = nnear;
for (i = 0; i < n; ++i) {
if (keys[i] == rootkey)
continue;
if (distance(rootkey, keys[i]) <= k)
tmp[inear++] = keys[i];
else
tmp[ifar++] = keys[i];
}
assert(inear == nnear);
assert(ifar == nnear + nfar);
root->data.tree.threshold = k;
if (nnear)
root->data.tree.near = mktree_vp(tmp, nnear, max_linear);
if (nfar)
root->data.tree.far = mktree_vp(tmp + nnear, nfar, max_linear);
free(tmp);
return root;
}
static size_t
query_vp(struct buf *restrict b, struct vptree *restrict root,
bkey_t ref, unsigned maxd)
{
/* We are trying to find x that satisfy d(ref,x) <= maxd
By triangle inequality, we know: d(root,x) <= d(root,ref) + d(ref,x)
By algebra: d(root,x) - d(root,ref) <= d(ref,x)
By transitivity: d(root,x) - d(root,ref) <= maxd
By algebra: d(root,x) <= maxd + d(root,ref) */
if (root->linear) {
const bkey_t *restrict keys = root->data.linear.keys;
unsigned i, n = root->data.linear.count;
for (i = 0; i < n; ++i)
if (distance(ref, keys[i]) <= maxd)
addkey(b, keys[i]);
return n;
} else {
unsigned d = distance(root->data.tree.vantage, ref);
unsigned thr = root->data.tree.threshold;
size_t nc = 1;
if (d <= maxd + thr) {
if (root->data.tree.near)
nc += query_vp(b, root->data.tree.near, ref, maxd);
if (d <= maxd)
addkey(b, root->data.tree.vantage);
}
if (d + maxd > thr && root->data.tree.far)
nc += query_vp(b, root->data.tree.far, ref, maxd);
return nc;
}
}
/* Main ==================== */
typedef void *(*mktree_t)(bkey_t *, size_t, size_t);
typedef size_t (*query_t)(struct buf *, void *, bkey_t, unsigned);
int main(int argc, char *argv[])
{
double tm, qc;
clock_t ckref, t;
struct buf q = { 0, 0, 0 };
unsigned long nkeys, seconds, nquery, dist, i, j, k;
void *root;
bkey_t ref, *keys;
unsigned long long total, totalcmp, maxlin;
size_t nc;
char *type;
mktree_t mktree;
query_t query;
if (argc < 5) {
fputs("Usage: TYPE MAXLIN NKEYS SECONDS DIST...\n", stderr);
return 1;
}
type = argv[1];
if (!strcasecmp(type, "bk")) {
puts("Type: BK-tree");
mktree = (mktree_t) mktree_bk;
query = (query_t) query_bk;
} else if (!strcasecmp(type, "vp")) {
puts("Type: VP-tree");
mktree = (mktree_t) mktree_vp;
query = (query_t) query_vp;
} else if (!strcasecmp(type, "linear")) {
puts("Type: Linear search");
mktree = (mktree_t) mktree_linear;
query = (query_t) query_linear;
} else if (!strcasecmp(type, "bitset")) {
puts("Type: Bitset search");
mktree = (mktree_t) mktree_bitset;
query = (query_t) query_bitset;
} else {
puts("Unknown type");
return 1;
}
maxlin = xatoul(argv[2]);
nkeys = xatoul(argv[3]);
seconds = xatoul(argv[4]);
if (!nkeys) {
fputs("Need at least one key\n", stderr);
return 1;
}
seedrand();
printf("Keys: %lu\n", nkeys);
printf("Seconds (at least): %lu\n", seconds);
putchar('\n');
keys = generate_keys(nkeys);
puts("Building tree...");
ckref = clock();
root = mktree(keys, nkeys, maxlin);
free(keys);
t = clock();
printf("Time: %.3f sec\n",
(double)(t - ckref) / CLOCKS_PER_SEC);
printf("Nodes: %u\n", num_nodes);
printf("Tree size: %u\n", tree_size);
for (k = 5; k < (unsigned) argc; ++k) {
total = 0;
totalcmp = 0;
dist = xatoul(argv[k]);
if (dist >= MAX_DISTANCE || dist <= 0) {
fprintf(stderr, "Distance should be in the range 1..%d\n",
MAX_DISTANCE);
return 1;
}
if (VERBOSE) {
putchar('\n');
printf("Distance: %lu\n", dist);
}
nquery = 0;
ckref = clock();
while (nquery < 3 || (tm = clock() - ckref) / CLOCKS_PER_SEC < seconds) {
for (i = nquery + 1; i > 0; --i) {
ref = irand();
q.n = 0;
nc = query(&q, root, ref, dist);
totalcmp += nc;
total += q.n;
if (DO_PRINT) {
printf("Query: %s\n", keystr(ref));
for (j = 0; j < q.n; ++j)
printf(" %s\n", keystr2(q.keys[j], ref));
}
++nquery;
}
}
qc = (double) CLOCKS_PER_SEC * (double) nquery;
if (VERBOSE) {
printf("Rate: %f query/sec\n", qc / tm);
printf("Time: %f msec/query\n", 1000.0 * tm / qc);
printf("Queries: %lu\n", nquery);
printf("Hits: %f\n", total / (double)nquery);
printf("Coverage: %f%%\n",
100.0 * (double)totalcmp / ((double)nkeys * nquery));
printf("Cmp/result: %f\n", (double)totalcmp / (double)total);
} else {
printf("%2lu %10.2f %10lu\n", dist, qc / tm, nquery);
}
}
return 0;
}