forked from SuLab/ab_cluster
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcluster.cpp
1931 lines (1703 loc) · 55.9 KB
/
cluster.cpp
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
#include <map>
#include <unordered_map>
#include <vector>
#include <string>
#include <cstring>
#include <cmath>
#include <fstream>
#include <iostream>
#include <sys/time.h>
#include <algorithm>
#include <cassert>
#include <cmath>
#include <cstring>
#include <string>
#include <iostream>
#include <fstream>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netdb.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/sysinfo.h>
#include <cstdlib>
#include <cfloat>
#include <cstddef>
#include <stdexcept>
#include <cstdio>
#include <map>
#include <sstream>
#include <cctype>
#include <iomanip>
#include <sstream>
#include <vector>
#include <limits>
#define fc_isnan(X) ((X)!=(X))
#ifndef NO_INCLUDE_FENV
#include <fenv.h>
#endif
#ifndef DBL_MANT_DIG
#error The constant DBL_MANT_DIG could not be defined.
#endif
#define T_FLOAT_MANT_DIG DBL_MANT_DIG
#ifndef LONG_MAX
#include <climits>
#endif
#ifndef LONG_MAX
#error The constant LONG_MAX could not be defined.
#endif
#ifndef INT_MAX
#error The constant INT_MAX could not be defined.
#endif
#ifndef INT32_MAX
#define __STDC_LIMIT_MACROS
#include <stdint.h>
#endif
#ifndef HAVE_DIAGNOSTIC
#if __GNUC__ > 4 || (__GNUC__ == 4 && (__GNUC_MINOR__ >= 6))
#define HAVE_DIAGNOSTIC 1
#endif
#endif
#ifndef HAVE_VISIBILITY
#if __GNUC__ >= 4
#define HAVE_VISIBILITY 1
#endif
#endif
/* Since the public interface is given by the Python respectively R interface,
* we do not want other symbols than the interface initalization routines to be
* visible in the shared object file. The "visibility" switch is a GCC concept.
* Hiding symbols keeps the relocation table small and decreases startup time.
* See http://gcc.gnu.org/wiki/Visibility
*/
#if HAVE_VISIBILITY
#pragma GCC visibility push(hidden)
#endif
typedef int_fast32_t t_index;
#ifndef INT32_MAX
#define MAX_INDEX 0x7fffffffL
#else
#define MAX_INDEX INT32_MAX
#endif
#if (LONG_MAX < MAX_INDEX)
#error The integer format "t_index" must not have a greater range than "long int".
#endif
#if (INT_MAX > MAX_INDEX)
#error The integer format "int" must not have a greater range than "t_index".
#endif
typedef double t_float;
// self-destructing array pointer
template <typename type>
class auto_array_ptr{
private:
type * ptr;
auto_array_ptr(auto_array_ptr const &); // non construction-copyable
auto_array_ptr& operator=(auto_array_ptr const &); // non copyable
public:
auto_array_ptr()
: ptr(NULL)
{ }
template <typename index>
auto_array_ptr(index const size)
: ptr(new type[size])
{ }
template <typename index, typename value>
auto_array_ptr(index const size, value const val)
: ptr(new type[size])
{
std::fill_n(ptr, size, val);
}
~auto_array_ptr() {
delete [] ptr; }
void free() {
delete [] ptr;
ptr = NULL;
}
template <typename index>
void init(index const size) {
ptr = new type [size];
}
template <typename index, typename value>
void init(index const size, value const val) {
init(size);
std::fill_n(ptr, size, val);
}
inline operator type *() const { return ptr; }
};
struct node {
t_index node1, node2;
t_float dist;
/*
inline bool operator< (const node a) const {
return this->dist < a.dist;
}
*/
inline friend bool operator< (const node a, const node b) {
return (a.dist < b.dist);
}
};
class cluster_result {
private:
auto_array_ptr<node> Z;
t_index pos;
public:
cluster_result(const t_index size)
: Z(size)
, pos(0)
{}
void append(const t_index node1, const t_index node2, const t_float dist) {
Z[pos].node1 = node1;
Z[pos].node2 = node2;
Z[pos].dist = dist;
++pos;
}
node * operator[] (const t_index idx) const { return Z + idx; }
/* Define several methods to postprocess the distances. All these functions
are monotone, so they do not change the sorted order of distances. */
void sqrt() const {
for (node * ZZ=Z; ZZ!=Z+pos; ++ZZ) {
ZZ->dist = ::sqrt(ZZ->dist);
}
}
void sqrt(const t_float) const { // ignore the argument
sqrt();
}
void sqrtdouble(const t_float) const { // ignore the argument
for (node * ZZ=Z; ZZ!=Z+pos; ++ZZ) {
ZZ->dist = ::sqrt(2*ZZ->dist);
}
}
#ifdef R_pow
#define my_pow R_pow
#else
#define my_pow pow
#endif
void power(const t_float p) const {
t_float const q = 1/p;
for (node * ZZ=Z; ZZ!=Z+pos; ++ZZ) {
ZZ->dist = my_pow(ZZ->dist,q);
}
}
void plusone(const t_float) const { // ignore the argument
for (node * ZZ=Z; ZZ!=Z+pos; ++ZZ) {
ZZ->dist += 1;
}
}
void divide(const t_float denom) const {
for (node * ZZ=Z; ZZ!=Z+pos; ++ZZ) {
ZZ->dist /= denom;
}
}
};
class doubly_linked_list {
/*
Class for a doubly linked list. Initially, the list is the integer range
[0, size]. We provide a forward iterator and a method to delete an index
from the list.
Typical use: for (i=L.start; L<size; i=L.succ[I])
or
for (i=somevalue; L<size; i=L.succ[I])
*/
public:
t_index start;
auto_array_ptr<t_index> succ;
private:
auto_array_ptr<t_index> pred;
// Not necessarily private, we just do not need it in this instance.
public:
doubly_linked_list(const t_index size)
// Initialize to the given size.
: start(0)
, succ(size+1)
, pred(size+1)
{
for (t_index i=0; i<size; ++i) {
pred[i+1] = i;
succ[i] = i+1;
}
// pred[0] is never accessed!
//succ[size] is never accessed!
}
~doubly_linked_list() {}
void remove(const t_index idx) {
// Remove an index from the list.
if (idx==start) {
start = succ[idx];
}
else {
succ[pred[idx]] = succ[idx];
pred[succ[idx]] = pred[idx];
}
succ[idx] = 0; // Mark as inactive
}
bool is_inactive(t_index idx) const {
return (succ[idx]==0);
}
};
// Indexing functions
// D is the upper triangular part of a symmetric (NxN)-matrix
// We require r_ < c_ !
#define D_(r_,c_) ( D[(static_cast<std::ptrdiff_t>(2*N-3-(r_))*(r_)>>1)+(c_)-1] )
// Z is an ((N-1)x4)-array
#define Z_(_r, _c) (Z[(_r)*4 + (_c)])
/*
Lookup function for a union-find data structure.
The function finds the root of idx by going iteratively through all
parent elements until a root is found. An element i is a root if
nodes[i] is zero. To make subsequent searches faster, the entry for
idx and all its parents is updated with the root element.
*/
class union_find {
private:
auto_array_ptr<t_index> parent;
t_index nextparent;
public:
union_find(const t_index size)
: parent(size>0 ? 2*size-1 : 0, 0)
, nextparent(size)
{ }
t_index Find (t_index idx) const {
if (parent[idx] != 0 ) { // a → b
t_index p = idx;
idx = parent[idx];
if (parent[idx] != 0 ) { // a → b → c
do {
idx = parent[idx];
} while (parent[idx] != 0);
do {
t_index tmp = parent[p];
parent[p] = idx;
p = tmp;
} while (parent[p] != idx);
}
}
return idx;
}
void Union (const t_index node1, const t_index node2) {
parent[node1] = parent[node2] = nextparent++;
}
};
class nan_error{};
#ifdef FE_INVALID
class fenv_error{};
#endif
/* Functions for the update of the dissimilarity array */
inline static void f_average( t_float * const b, const t_float a, const t_float s, const t_float t) {
*b = s*a + t*(*b);
#ifndef FE_INVALID
#if HAVE_DIAGNOSTIC
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wfloat-equal"
#endif
if (fc_isnan(*b)) {
throw(nan_error());
}
#if HAVE_DIAGNOSTIC
#pragma GCC diagnostic pop
#endif
#endif
}
template <typename t_members>
static void NN_chain_core(const t_index N, t_float * const D, t_members * const members, cluster_result & Z2) {
/*
N: integer
D: condensed distance matrix N*(N-1)/2
Z2: output data structure
This is the NN-chain algorithm, described on page 86 in the following book:
Fionn Murtagh, Multidimensional Clustering Algorithms,
Vienna, Würzburg: Physica-Verlag, 1985.
*/
t_index i;
auto_array_ptr<t_index> NN_chain(N);
t_index NN_chain_tip = 0;
t_index idx1, idx2;
t_float size1, size2;
doubly_linked_list active_nodes(N);
t_float min;
#ifdef FE_INVALID
if (feclearexcept(FE_INVALID)) throw fenv_error();
#endif
for (t_index j=0; j<N-1; ++j) {
if (NN_chain_tip <= 3) {
NN_chain[0] = idx1 = active_nodes.start;
NN_chain_tip = 1;
idx2 = active_nodes.succ[idx1];
min = D_(idx1,idx2);
for (i=active_nodes.succ[idx2]; i<N; i=active_nodes.succ[i]) {
if (D_(idx1,i) < min) {
min = D_(idx1,i);
idx2 = i;
}
}
} // a: idx1 b: idx2
else {
NN_chain_tip -= 3;
idx1 = NN_chain[NN_chain_tip-1];
idx2 = NN_chain[NN_chain_tip];
min = idx1<idx2 ? D_(idx1,idx2) : D_(idx2,idx1);
} // a: idx1 b: idx2
do {
NN_chain[NN_chain_tip] = idx2;
for (i=active_nodes.start; i<idx2; i=active_nodes.succ[i]) {
if (D_(i,idx2) < min) {
min = D_(i,idx2);
idx1 = i;
}
}
for (i=active_nodes.succ[idx2]; i<N; i=active_nodes.succ[i]) {
if (D_(idx2,i) < min) {
min = D_(idx2,i);
idx1 = i;
}
}
idx2 = idx1;
idx1 = NN_chain[NN_chain_tip++];
} while (idx2 != NN_chain[NN_chain_tip-2]);
Z2.append(idx1, idx2, min);
if (idx1>idx2) {
t_index tmp = idx1;
idx1 = idx2;
idx2 = tmp;
}
size1 = static_cast<t_float>(members[idx1]);
size2 = static_cast<t_float>(members[idx2]);
members[idx2] += members[idx1];
// Remove the smaller index from the valid indices (active_nodes).
active_nodes.remove(idx1);
t_float s = size1/(size1+size2);
t_float t = size2/(size1+size2);
for (i=active_nodes.start; i<idx1; i=active_nodes.succ[i])
f_average(&D_(i, idx2), D_(i, idx1), s, t );
// Update the distance matrix in the range (idx1, idx2).
for (; i<idx2; i=active_nodes.succ[i])
f_average(&D_(i, idx2), D_(idx1, i), s, t );
// Update the distance matrix in the range (idx2, N).
for (i=active_nodes.succ[idx2]; i<N; i=active_nodes.succ[i])
f_average(&D_(idx2, i), D_(idx1, i), s, t );
}
#ifdef FE_INVALID
if (fetestexcept(FE_INVALID)) throw fenv_error();
#endif
}
#if HAVE_VISIBILITY
#pragma GCC visibility pop
#endif
#define size_(r_) ( ((r_<N) ? 1 : Z_(r_-N,3)) )
class linkage_output {
private:
t_float * Z;
public:
linkage_output(t_float * const Z_)
: Z(Z_)
{}
void append(const t_index node1, const t_index node2, const t_float dist,
const t_float size) {
if (node1<node2) {
*(Z++) = static_cast<t_float>(node1);
*(Z++) = static_cast<t_float>(node2);
}
else {
*(Z++) = static_cast<t_float>(node2);
*(Z++) = static_cast<t_float>(node1);
}
*(Z++) = dist;
*(Z++) = size;
}
};
template <const bool sorted>
static void generate_SciPy_dendrogram(t_float * const Z, cluster_result & Z2, const t_index N) {
// The array "nodes" is a union-find data structure for the cluster
// identities (only needed for unsorted cluster_result input).
union_find nodes(sorted ? 0 : N);
if (!sorted) {
std::stable_sort(Z2[0], Z2[N-1]);
}
linkage_output output(Z);
t_index node1, node2;
for (node const * NN=Z2[0]; NN!=Z2[N-1]; ++NN) {
// Get two data points whose clusters are merged in step i.
if (sorted) {
node1 = NN->node1;
node2 = NN->node2;
}
else {
// Find the cluster identifiers for these points.
node1 = nodes.Find(NN->node1);
node2 = nodes.Find(NN->node2);
// Merge the nodes in the union-find data structure by making them
// children of a new node.
nodes.Union(node1, node2);
}
output.append(node1, node2, NN->dist, size_(node1)+size_(node2));
}
}
void linkage(const size_t N, double* matrix, t_index* members, double* Z) {
cluster_result Z2(N - 1);
NN_chain_core<t_index>(N, matrix, members, Z2);
generate_SciPy_dendrogram<false>(Z, Z2, N);
}
#define CPY_MAX(_x, _y) ((_x > _y) ? (_x) : (_y))
#define CPY_MIN(_x, _y) ((_x < _y) ? (_x) : (_y))
#define NCHOOSE2(_n) ((_n)*(_n-1)/2)
#define CPY_BITS_PER_CHAR (sizeof(unsigned char) * 8)
#define CPY_FLAG_ARRAY_SIZE_BYTES(num_bits) (CPY_CEIL_DIV((num_bits), \
CPY_BITS_PER_CHAR))
#define CPY_GET_BIT(_xx, i) (((_xx)[(i) / CPY_BITS_PER_CHAR] >> \
((CPY_BITS_PER_CHAR-1) - \
((i) % CPY_BITS_PER_CHAR))) & 0x1)
#define CPY_SET_BIT(_xx, i) ((_xx)[(i) / CPY_BITS_PER_CHAR] |= \
((0x1) << ((CPY_BITS_PER_CHAR-1) \
-((i) % CPY_BITS_PER_CHAR))))
#define CPY_CLEAR_BIT(_xx, i) ((_xx)[(i) / CPY_BITS_PER_CHAR] &= \
~((0x1) << ((CPY_BITS_PER_CHAR-1) \
-((i) % CPY_BITS_PER_CHAR))))
#ifndef CPY_CEIL_DIV
#define CPY_CEIL_DIV(x, y) ((((double)x)/(double)y) == \
((double)((x)/(y))) ? ((x)/(y)) : ((x)/(y) + 1))
#endif
#ifdef CPY_DEBUG
#define CPY_DEBUG_MSG(...) fprintf(stderr, __VA_ARGS__)
#else
#define CPY_DEBUG_MSG(...)
#endif
#define ISCLUSTER(_nd) ((_nd)->id >= n)
#define GETCLUSTER(_id) ((lists + _id - n))
/** The number of link stats (for the inconsistency computation) for each
cluster. */
#define CPY_NIS 4
/** The column offsets for the different link stats for the inconsistency
computation. */
#define CPY_INS_MEAN 0
#define CPY_INS_STD 1
#define CPY_INS_N 2
#define CPY_INS_INS 3
/** The number of linkage stats for each cluster. */
#define CPY_LIS 4
/** The column offsets for the different link stats for the linkage matrix. */
#define CPY_LIN_LEFT 0
#define CPY_LIN_RIGHT 1
#define CPY_LIN_DIST 2
#define CPY_LIN_CNT 3
void get_max_dist_for_each_cluster(const double *Z, double *max_dists, int n) {
int *curNode;
int ndid, lid, rid, k;
unsigned char *lvisited, *rvisited;
const double *Zrow;
double max_dist;
const int bff = CPY_FLAG_ARRAY_SIZE_BYTES(n);
k = 0;
curNode = (int*)malloc(n * sizeof(int));
lvisited = (unsigned char*)malloc(bff);
rvisited = (unsigned char*)malloc(bff);
curNode[k] = (n * 2) - 2;
memset(lvisited, 0, bff);
memset(rvisited, 0, bff);
while (k >= 0) {
ndid = curNode[k];
Zrow = Z + ((ndid-n) * CPY_LIS);
lid = (int)Zrow[CPY_LIN_LEFT];
rid = (int)Zrow[CPY_LIN_RIGHT];
if (lid >= n && !CPY_GET_BIT(lvisited, ndid-n)) {
CPY_SET_BIT(lvisited, ndid-n);
curNode[k+1] = lid;
k++;
continue;
}
if (rid >= n && !CPY_GET_BIT(rvisited, ndid-n)) {
CPY_SET_BIT(rvisited, ndid-n);
curNode[k+1] = rid;
k++;
continue;
}
max_dist = Zrow[CPY_LIN_DIST];
if (lid >= n) {
max_dist = CPY_MAX(max_dist, max_dists[lid-n]);
}
if (rid >= n) {
max_dist = CPY_MAX(max_dist, max_dists[rid-n]);
}
max_dists[ndid-n] = max_dist;
CPY_DEBUG_MSG("i=%d maxdist[i]=%5.5f verif=%5.5f\n",
ndid-n, max_dist, max_dists[ndid-n]);
k--;
}
free(curNode);
free(lvisited);
free(rvisited);
}
void form_flat_clusters_from_monotonic_criterion(const double *Z,
const double *mono_crit,
int *T, double cutoff, int n) {
int *curNode;
int ndid, lid, rid, k, ms, nc;
unsigned char *lvisited, *rvisited;
double max_crit;
const double *Zrow;
const int bff = CPY_FLAG_ARRAY_SIZE_BYTES(n);
curNode = (int*)malloc(n * sizeof(int));
lvisited = (unsigned char*)malloc(bff);
rvisited = (unsigned char*)malloc(bff);
/** number of clusters formed so far. */
nc = 0;
/** are we in part of a tree below the cutoff? .*/
ms = -1;
k = 0;
curNode[k] = (n * 2) - 2;
memset(lvisited, 0, bff);
memset(rvisited, 0, bff);
ms = -1;
while (k >= 0) {
ndid = curNode[k];
Zrow = Z + ((ndid-n) * CPY_LIS);
lid = (int)Zrow[CPY_LIN_LEFT];
rid = (int)Zrow[CPY_LIN_RIGHT];
max_crit = mono_crit[ndid-n];
CPY_DEBUG_MSG("cutoff: %5.5f maxc: %5.5f nc: %d\n", cutoff, max_crit, nc);
if (ms == -1 && max_crit <= cutoff) {
CPY_DEBUG_MSG("leader: i=%d\n", ndid);
ms = k;
nc++;
}
if (lid >= n && !CPY_GET_BIT(lvisited, ndid-n)) {
CPY_SET_BIT(lvisited, ndid-n);
curNode[k+1] = lid;
k++;
continue;
}
if (rid >= n && !CPY_GET_BIT(rvisited, ndid-n)) {
CPY_SET_BIT(rvisited, ndid-n);
curNode[k+1] = rid;
k++;
continue;
}
if (ndid >= n) {
if (lid < n) {
if (ms == -1) {
nc++;
T[lid] = nc;
}
else {
T[lid] = nc;
}
}
if (rid < n) {
if (ms == -1) {
nc++;
T[rid] = nc;
}
else {
T[rid] = nc;
}
}
if (ms == k) {
ms = -1;
}
}
k--;
}
free(curNode);
free(lvisited);
free(rvisited);
}
void form_flat_clusters_from_dist(const double *Z, int *T,
double cutoff, int n) {
double *max_dists = (double*)malloc(sizeof(double) * n);
get_max_dist_for_each_cluster(Z, max_dists, n);
//CPY_DEBUG_MSG("cupid: n=%d cutoff=%5.5f MD[0]=%5.5f MD[n-1]=%5.5f\n", n, cutoff, max_dists[0], max_dists[n-2]);
form_flat_clusters_from_monotonic_criterion(Z, max_dists, T, cutoff, n);
free(max_dists);
}
void linkage(const size_t N, double* matrix, double* Z);
void form_flat_clusters_from_dist(const double *Z, int *T,
double cutoff, int n) ;
void form_flat_clusters_maxclust_monocrit(const double *Z,
const double *mono_crit,
int *T, int n, int mc);
void get_max_dist_for_each_cluster(const double *Z, double *max_dists, int n);
using namespace std;
/*
* Compilation options.
*/
#define SIMD // use optimized SSE implementation (SSE4 required)
#define NO_TIMING // remove ALL calls to timing functions
//#define PROFILING // enable profiling
//#define SLOW_MODE // disable megaclustering (much slower but could be more accurate)
/*
* Problem definition.
*/
namespace cluster_param {
const double cutoff = 0.32;
const double mut_value = 0.35;
const double epsilon = 0.001;
const int len_penalty = 2;
}
/*
* Input data limits. They must NEVER be exceeded.
*/
const int MAX_SEQUENCES = 2500000;
const int MAX_AVERAGE_MUTATIONS_PER_SEQUENCE = 32;
const int MAX_PARTITIONS = 7 + 1;
const int MAX_SEQUENCES_PER_PARTITION = MAX_SEQUENCES/2;
const int MAX_ESSENCES_PER_PARTITION = MAX_SEQUENCES_PER_PARTITION/5;
const int MAX_CLUSTERS_PER_PARTITION = 256 + MAX_SEQUENCES_PER_PARTITION/50;
const int MAX_AA_LENGTH = 64;
const int MAX_MUTATION_LOC = 4096;
/*
* Tweakable parameters.
*/
#ifndef SLOW_MODE
const int MIN_CENTER_SIZE_10K = 3; // minimum number of sequences for a center (10K dataset)
const int MIN_CENTER_SIZE_100K = 9; // minimum number of sequences for a center (100K dataset)
#else
const int MIN_CENTER_SIZE_10K = INT_MAX;
const int MIN_CENTER_SIZE_100K = INT_MAX;
#endif
const double MIN_MEGACLUSTER_DISSIMILARITY = 0.40; // should probably be a bit above cluster_param::cutoff
const int CANONICAL_SAMPLES = 17; // number of samples to compute canonical_mutlist
const int MUTLIST_BLOCKS = 3; // keep track of 3*128 mutation locations: this is enough for the dataset (384 > 316)
/*
* Constants.
*/
const int MUTTYPE_BITS = 4; // there are 16 = 1<<4 distinct types of mutations
const int SIMD_BITS_PER_BLOCK = 128; // size of SIMD register
const int SIMD_BYTES = SIMD_BITS_PER_BLOCK / 8;
#ifdef SIMD
#pragma GCC target ("sse4")
#endif
#ifdef SIMD
#define SIMD_LEV // SIMD-optimized Levenshtein distance
#define SIMD_MUT // SIMD-optimized mutation intersection
union ByteSimd {
__m128i simd;
uint8_t byte[SIMD_BYTES];
};
#endif
#define NOINLINE __attribute__((noinline))
#define FOR(i,a,b) for(int i=(a); i<(b); i++)
#define REP(i,n) FOR(i,0,n)
#define BLACK_BOX(x) asm("" :: "r" (x))
static inline void assert_invariant(bool condition) {
if (!condition)
throw std::logic_error("assert_invariant failed");
}
static inline void _range_check(bool condition, const char *message) {
if (!condition)
throw std::out_of_range((string)"range_check("+message+") failed");
}
#define range_check(condition) _range_check(condition, #condition)
map<string, double> globalStats;
class Stopwatch {
struct timeval tv_startup;
public:
Stopwatch() {
reset();
}
void reset() {
#ifndef NO_TIMING
gettimeofday(&tv_startup, NULL);
#endif
}
double time() const {
#ifndef NO_TIMING
struct timeval tv;
gettimeofday(&tv, NULL);
return (tv.tv_sec - tv_startup.tv_sec) + (tv.tv_usec - tv_startup.tv_usec) * 1e-6;
#else
return 0;
#endif
}
#ifndef NO_TIMING
void print(string prefix) const {
cerr << prefix << ": " << (time()*1000) << " ms" << endl;
}
#else
void print(const char *) const {}
#endif
#ifdef PROFILING
void store(string prefix) const {
double t = time();
globalStats["time for " + prefix + " (ms)"] += t * 1000;
}
#else
void store(const char *) const {}
#endif
} globalStopwatch;
template<class T>
struct Slice {
typedef T value_type;
const T* _head;
int _size;
Slice<T>(const T* _head, int _size): _head(_head), _size(_size) {}
const T& operator[](int i) const {
return _head[i];
}
int size() const { return _size; }
const T* begin() const {
return _head;
}
const T* end() const {
return _head + size();
}
};
struct StringSlice : Slice<char> {
StringSlice(const Slice<char>& slice): Slice<char>(slice._head, slice._size) {}
StringSlice(const char* _head, int _size): Slice<char>(_head, _size) {}
bool operator<(const StringSlice& o) const {
return lexicographical_compare(begin(), end(), o.begin(), o.end());
}
bool operator==(const StringSlice& o) const {
return size() == o.size() && !memcmp(begin(), o.begin(), size());
}
bool operator==(const string& o) const {
return (size_t)size() == o.size() && !memcmp(begin(), o.c_str(), size());
}
string to_string() const {
return string(_head, _size);
}
};
template<class T, class S>
S& operator<<(S& stream, Slice<T> slice) {
stream << "[";
REP(i, slice.size())
stream << (i ? ", " : "") << slice[i];
return stream << "]";
}
template<class T, class S>
S& operator<<(S& stream, StringSlice slice) {
return stream << slice.to_string();
}
template<class T, class S>
S& operator<<(S& stream, const vector<T>& vec) {
stream << "[";
REP(i, vec.size())
stream << (i ? ", " : "") << vec[i];
return stream << "]";
}
template<class T, class U, class S>
S& operator<<(S& stream, const pair<T,U>& xy) {
return stream << "(" << xy.first << ", " << xy.second << ")";
}
StringSlice make_persistent(StringSlice slice) {
static vector<string> archive;
archive.push_back(slice.to_string());
const string& s = archive.back();
return StringSlice(s.c_str(), s.size());
}
template<class K, class V>
class Interning {
unordered_map<K,V> mapping;
vector<K> values;
V next;
public:
Interning(): next(V()) {}
V intern(const K& key) {
auto it = mapping.find(key);
if (it != mapping.end())
return it->second;
V value = next++;
K persistent_key = make_persistent(key);
mapping[persistent_key] = value;
values.push_back(persistent_key);
return value;
}
const K& lookup(V id) const {
return values[id];
}
};
typedef uint16_t Mutation;
#ifdef SIMD_MUT
int popcnt128(__m128i x) {
int lo = _popcnt64(_mm_cvtsi128_si64(x));
int hi = _popcnt64(_mm_cvtsi128_si64(_mm_unpackhi_epi64(x, x)));
return lo + hi;
}
vector<int16_t> mutloc_map(MAX_MUTATION_LOC, -1);
int16_t mutloc_count = 0;
string str(__m128i x) {
union {
__m128i simd;
uint8_t byte[16];
} v;
v.simd = x;
ostringstream oss;
oss << "0x";
REP(i, 16) {
char buf[3];
sprintf(buf, "%02x", v.byte[15 - i]);
oss << buf;
}
return oss.str();
}
struct FastMutList {
ByteSimd bitmap[MUTLIST_BLOCKS][MUTTYPE_BITS + 1];
FastMutList() {
REP(i, MUTLIST_BLOCKS)
REP(k, MUTTYPE_BITS + 1)
bitmap[i][k].simd = _mm_set1_epi8(0);
}
FastMutList(const FastMutList& o) {
*this = o;
}
FastMutList& operator=(const FastMutList& o) {
REP(i, MUTLIST_BLOCKS)
REP(k, MUTTYPE_BITS + 1)
bitmap[i][k].simd = o.bitmap[i][k].simd;
return *this;
}
void set_mutations(Slice<Mutation> mutlist) {
for (Mutation m : mutlist) {
unsigned int bit = mutloc_map[m >> MUTTYPE_BITS];
unsigned int i = bit / SIMD_BITS_PER_BLOCK;
unsigned int j = bit % SIMD_BITS_PER_BLOCK;
unsigned int data = m | 1 << MUTTYPE_BITS;
REP(k, MUTTYPE_BITS + 1) {
//bitmap[i][k].byte[j/8] &= ~(1 << (j%8));
bitmap[i][k].byte[j/8] |= ((data>>k) & 1) << (j%8);
}
}
}
int count_intersection(const FastMutList& o) const {
range_check(MUTTYPE_BITS == 4);