-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathfast_clustering.cpp
2490 lines (2187 loc) · 72.8 KB
/
fast_clustering.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
/*
fastcluster: Fast hierarchical clustering routines for R and Python
Copyright © 2011 Daniel Müllner
<http://math.stanford.edu/~muellner>
This library implements various fast algorithms for hierarchical, agglomerative
` clustering methods:
(1) Algorithms for the "stored matrix approach": the input is the array of
pairwise dissimilarities.
MST_linkage_core: single linkage clustering with the "minimum spanning tree
algorithm (Rohlfs)
NN_chain_core: nearest-neighbor-chain algorithm, suitable for single,
complete, average, weighted and Ward linkage (Murtagh)
generic_linkage: generic algorithm, suitable for all distance update formulas
(Müllner)
(2) Algorithms for the "stored data approach": the input are points in a vector
space.
MST_linkage_core_vector: single linkage clustering for vector data
generic_linkage_vector: generic algorithm for vector data, suitable for
the Ward, centroid and median methods.
generic_linkage_vector_alternative: alternative scheme for updating the
nearest neighbors. This method seems faster than "generic_linkage_vector"
for the centroid and median methods but slower for the Ward method.
*/
//#define __STDC_LIMIT_MACROS
//#include <stdint.h>
#include <limits> // for infinity()
#include <float.h>
#ifndef DBL_MANT_DIG
#error The constant DBL_MANT_DIG could not be defined.
#endif
//#include <cmath>
#include <algorithm>
#ifndef LONG_MAX
#include <limits.h>
#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
#include <cmath>
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;
#define T_FLOAT_MANT_DIG DBL_MANT_DIG
enum method_codes {
// non-Euclidean methods
METHOD_METR_SINGLE = 0,
METHOD_METR_COMPLETE = 1,
METHOD_METR_AVERAGE = 2,
METHOD_METR_WEIGHTED = 3,
METHOD_METR_WARD = 4,
METHOD_METR_CENTROID = 5,
METHOD_METR_MEDIAN = 6
};
enum {
// Euclidean methods
METHOD_VECTOR_SINGLE = 0,
METHOD_VECTOR_WARD = 1,
METHOD_VECTOR_CENTROID = 2,
METHOD_VECTOR_MEDIAN = 3
};
enum {
// Return values
RET_SUCCESS = 0,
RET_MEMORY_ERROR = 1,
RET_STL_ERROR = 2,
RET_UNKNOWN_ERROR = 3
};
// self-destructing array pointer
template <typename type>
class auto_array_ptr{
private:
type * ptr;
public:
auto_array_ptr() { ptr = NULL; }
template <typename index>
auto_array_ptr(index const size) { init(size); }
template <typename index, typename value>
auto_array_ptr(index const size, value const val) { init(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);
for (index i=0; i<size; i++) ptr[i] = 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) {
// Numbers are always smaller than NaNs.
return a.dist < b.dist || (a.dist==a.dist && b.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 (t_index i=0; i<pos; i++) {
Z[i].dist = ::sqrt(Z[i].dist);
}
}
void sqrt(const t_float) const { // ignore the argument
sqrt();
}
void sqrtdouble(const t_float) const { // ignore the argument
for (t_index i=0; i<pos; i++) {
Z[i].dist = ::sqrt(2*Z[i].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 (t_index i=0; i<pos; i++) {
Z[i].dist = my_pow(Z[i].dist,q);
}
}
void plusone(const t_float) const { // ignore the argument
for (t_index i=0; i<pos; i++) {
Z[i].dist += 1;
}
}
void divide(const t_float denom) const {
for (t_index i=0; i<pos; i++) {
Z[i].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.
: 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!
start = 0;
}
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:
void init(const t_index size) {
parent.init(2*size-1, 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++;
}
};
static void MST_linkage_core(const t_index N, const t_float * const D,
cluster_result & Z2) {
/*
N: integer, number of data points
D: condensed distance matrix N*(N-1)/2
Z2: output data structure
The basis of this algorithm is an algorithm by Rohlf:
F. James Rohlf, Hierarchical clustering using the minimum spanning tree,
The Computer Journal, vol. 16, 1973, p. 93–95.
This implementation should handle Inf values correctly (designed to
do so but not tested).
This implementation avoids NaN if possible. It treats NaN as if it was
greater than +Infinity, ie. whenever we find a non-NaN value, this is
preferred in all the minimum-distance searches.
*/
t_index i;
t_index idx2;
doubly_linked_list active_nodes(N);
auto_array_ptr<t_float> d(N);
t_index prev_node;
t_float min;
// first iteration
idx2 = 1;
min = d[1] = D[0];
for (i=2; min!=min && i<N; i++) { // eliminate NaNs if possible
min = d[i] = D[i-1];
idx2 = i;
}
for ( ; i<N; i++) {
d[i] = D[i-1];
if (d[i] < min) {
min = d[i];
idx2 = i;
}
}
Z2.append(0, idx2, min);
for (t_index j=1; j<N-1; j++) {
prev_node = idx2;
active_nodes.remove(prev_node);
idx2 = active_nodes.succ[0];
min = d[idx2];
for (i=idx2; min!=min && i<prev_node; i=active_nodes.succ[i]) {
min = d[i] = D_(i, prev_node);
idx2 = i;
}
for ( ; i<prev_node; i=active_nodes.succ[i]) {
if (d[i] > D_(i, prev_node))
d[i] = D_(i, prev_node);
if (d[i] < min) {
min = d[i];
idx2 = i;
}
}
for (; min!=min && i<N; i=active_nodes.succ[i]) {
min = d[i] = D_(prev_node, i);
idx2 = i;
}
for (; i<N; i=active_nodes.succ[i]) {
if (d[i] > D_(prev_node, i))
d[i] = D_(prev_node, i);
if (d[i] < min) {
min = d[i];
idx2 = i;
}
}
Z2.append(prev_node, idx2, min);
}
}
/* Functions for the update of the dissimilarity array */
inline static void f_single( t_float * const b, const t_float a ) {
if (*b > a) *b = a;
}
inline static void f_complete( t_float * const b, const t_float a ) {
if (*b < a) *b = a;
}
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);
}
inline static void f_weighted( t_float * const b, const t_float a) {
*b = (a+*b)/2;
}
inline static void f_ward( t_float * const b, const t_float a, const t_float c, const t_float s, const t_float t, const t_float v) {
*b = ( (v+s)*a - v*c + (v+t)*(*b) ) / (s+t+v);
//*b = a+(*b)-(t*a+s*(*b)+v*c)/(s+t+v);
}
inline static void f_centroid( t_float * const b, const t_float a, const t_float stc, const t_float s, const t_float t) {
*b = s*a + t*(*b) - stc;
}
inline static void f_median( t_float * const b, const t_float a, const t_float c_4) {
*b = (a+(*b))/2 - c_4;
}
template <const unsigned char method, 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.
This implementation does not give defined results when NaN or Inf values
are present in the array D.
*/
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;
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;
}
if (method==METHOD_METR_AVERAGE ||
method==METHOD_METR_WARD) {
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);
switch (method) {
case METHOD_METR_SINGLE:
/*
Single linkage.
Characteristic: new distances are never longer than the old distances.
*/
// Update the distance matrix in the range [start, idx1).
for (i=active_nodes.start; i<idx1; i=active_nodes.succ[i])
f_single(&D_(i, idx2), D_(i, idx1) );
// Update the distance matrix in the range (idx1, idx2).
for (; i<idx2; i=active_nodes.succ[i])
f_single(&D_(i, idx2), D_(idx1, i) );
// Update the distance matrix in the range (idx2, N).
for (i=active_nodes.succ[idx2]; i<N; i=active_nodes.succ[i])
f_single(&D_(idx2, i), D_(idx1, i) );
break;
case METHOD_METR_COMPLETE:
/*
Complete linkage.
Characteristic: new distances are never shorter than the old distances.
*/
// Update the distance matrix in the range [start, idx1).
for (i=active_nodes.start; i<idx1; i=active_nodes.succ[i])
f_complete(&D_(i, idx2), D_(i, idx1) );
// Update the distance matrix in the range (idx1, idx2).
for (; i<idx2; i=active_nodes.succ[i])
f_complete(&D_(i, idx2), D_(idx1, i) );
// Update the distance matrix in the range (idx2, N).
for (i=active_nodes.succ[idx2]; i<N; i=active_nodes.succ[i])
f_complete(&D_(idx2, i), D_(idx1, i) );
break;
case METHOD_METR_AVERAGE: {
/*
Average linkage.
Shorter and longer distances can occur.
*/
// Update the distance matrix in the range [start, 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 );
break;
}
case METHOD_METR_WEIGHTED:
/*
Weighted linkage.
Shorter and longer distances can occur.
*/
// Update the distance matrix in the range [start, idx1).
for (i=active_nodes.start; i<idx1; i=active_nodes.succ[i])
f_weighted(&D_(i, idx2), D_(i, idx1) );
// Update the distance matrix in the range (idx1, idx2).
for (; i<idx2; i=active_nodes.succ[i])
f_weighted(&D_(i, idx2), D_(idx1, i) );
// Update the distance matrix in the range (idx2, N).
for (i=active_nodes.succ[idx2]; i<N; i=active_nodes.succ[i])
f_weighted(&D_(idx2, i), D_(idx1, i) );
break;
case METHOD_METR_WARD:
/*
Ward linkage.
Shorter and longer distances can occur, not smaller than min(d1,d2)
but maybe bigger than max(d1,d2).
*/
// Update the distance matrix in the range [start, idx1).
//t_float v = static_cast<t_float>(members[i]);
for (i=active_nodes.start; i<idx1; i=active_nodes.succ[i])
f_ward(&D_(i, idx2), D_(i, idx1), min,
size1, size2, static_cast<t_float>(members[i]) );
// Update the distance matrix in the range (idx1, idx2).
for (; i<idx2; i=active_nodes.succ[i])
f_ward(&D_(i, idx2), D_(idx1, i), min,
size1, size2, static_cast<t_float>(members[i]) );
// Update the distance matrix in the range (idx2, N).
for (i=active_nodes.succ[idx2]; i<N; i=active_nodes.succ[i])
f_ward(&D_(idx2, i), D_(idx1, i), min,
size1, size2, static_cast<t_float>(members[i]) );
break;
}
}
}
class binary_min_heap {
/*
Class for a binary min-heap. The data resides in an array A. The elements of A
are not changed but two lists I and R of indices are generated which point to
elements of A and backwards.
The heap tree structure is
H[2*i+1] H[2*i+2]
\ /
\ /
≤ ≤
\ /
\ /
H[i]
where the children must be less or equal than their parent. Thus, H[0] contains
the minimum. The lists I and R are made such that H[i] = A[I[i]] and R[I[i]] = i.
This implementation avoids NaN if possible. It treats NaN as if it was
greater than +Infinity, ie. whenever we find a non-NaN value, this is
preferred in all comparisons.
*/
private:
t_float * A;
t_index size;
auto_array_ptr<t_index> I;
auto_array_ptr<t_index> R;
public:
binary_min_heap(const t_index size)
: I(size), R(size)
{ // Allocate memory and initialize the lists I and R to the identity. This does
// not make it a heap. Call heapify afterwards!
this->size = size;
for (t_index i=0; i<size; i++)
R[i] = I[i] = i;
}
binary_min_heap(const t_index size1, const t_index size2, const t_index start)
: I(size1), R(size2)
{ // Allocate memory and initialize the lists I and R to the identity. This does
// not make it a heap. Call heapify afterwards!
this->size = size1;
for (t_index i=0; i<size; i++) {
R[i+start] = i;
I[i] = i + start;
}
}
void heapify(t_float * const A) {
// Arrange the indices I and R so that H[i] := A[I[i]] satisfies the heap
// condition H[i] < H[2*i+1] and H[i] < H[2*i+2] for each i.
//
// Complexity: Θ(size)
// Reference: Cormen, Leiserson, Rivest, Stein, Introduction to Algorithms,
// 3rd ed., 2009, Section 6.3 “Building a heap”
t_index idx;
this->A = A;
for (idx=(size>>1); idx>0; ) {
idx--;
update_geq_(idx);
}
}
inline t_index argmin() const {
// Return the minimal element.
return I[0];
}
void heap_pop() {
// Remove the minimal element from the heap.
size--;
I[0] = I[size];
R[I[0]] = 0;
update_geq_(0);
}
void remove(t_index idx) {
// Remove an element from the heap.
size--;
R[I[size]] = R[idx];
I[R[idx]] = I[size];
if ( H(size)<=A[idx] || A[idx]!=A[idx] ) {
update_leq_(R[idx]);
}
else {
update_geq_(R[idx]);
}
}
void replace ( const t_index idxold, const t_index idxnew, const t_float val) {
R[idxnew] = R[idxold];
I[R[idxnew]] = idxnew;
if (val<=A[idxold] || A[idxold]!=A[idxold]) // avoid NaN! ????????????????????
update_leq(idxnew, val);
else
update_geq(idxnew, val);
}
void update ( const t_index idx, const t_float val ) const {
// Update the element A[i] with val and re-arrange the indices the preserve the
// heap condition.
if (val<=A[idx] || A[idx]!=A[idx]) // avoid NaN! ????????????????????
update_leq(idx, val);
else
update_geq(idx, val);
}
void update_leq ( const t_index idx, const t_float val ) const {
// Use this when the new value is not more than the old value.
A[idx] = val;
update_leq_(R[idx]);
}
void update_geq ( const t_index idx, const t_float val ) const {
// Use this when the new value is not less than the old value.
A[idx] = val;
update_geq_(R[idx]);
}
private:
void update_leq_ (t_index i) const {
t_index j;
for ( ; (i>0) && ( H(i)<H(j=(i-1)>>1) || H(j)!=H(j) ); i=j)
// avoid NaN!
heap_swap(i,j);
}
void update_geq_ (t_index i) const {
t_index j;
for ( ; (j=2*i+1)<size; i=j) {
if ( H(j)>=H(i) || H(j)!=H(j) ) { // avoid Nan!
j++;
if ( j>=size || H(j)>=H(i) || H(j)!=H(j) ) break; // avoid NaN!
}
else if ( j+1<size && H(j+1)<H(j) ) j++;
heap_swap(i, j);
}
}
void heap_swap(const t_index i, const t_index j) const {
// Swap two indices.
t_index tmp = I[i];
I[i] = I[j];
I[j] = tmp;
R[I[i]] = i;
R[I[j]] = j;
}
inline t_float H(const t_index i) const {
return A[I[i]];
}
};
template <const unsigned char method, typename t_members>
static void generic_linkage(const t_index N, t_float * const D, t_members * const members, cluster_result & Z2) {
/*
N: integer, number of data points
D: condensed distance matrix N*(N-1)/2
Z2: output data structure
This implementation does not give defined results when NaN or Inf values
are present in the array D.
*/
const t_index N_1 = N-1;
t_index i, j; // loop variables
t_index idx1, idx2; // row and column indices
auto_array_ptr<t_index> n_nghbr(N_1); // array of nearest neighbors
auto_array_ptr<t_float> mindist(N_1); // distances to the nearest neighbors
auto_array_ptr<t_index> row_repr(N); // row_repr[i]: node number that the i-th row
// represents
doubly_linked_list active_nodes(N);
binary_min_heap nn_distances(N_1); // minimum heap structure for the distance
// to the nearest neighbor of each point
t_index node1, node2; // node numbers in the output
t_float size1, size2; // and their cardinalities
t_float min; // minimum and row index for nearest-neighbor search
t_index idx;
for (i=0; i<N; i++)
// Build a list of row ↔ node label assignments.
// Initially i ↦ i
row_repr[i] = i;
// Initialize the minimal distances:
// Find the nearest neighbor of each point.
// n_nghbr[i] = argmin_{j>i} D(i,j) for i in range(N-1)
t_float * DD = D;
for (i=0; i<N_1; i++) {
min = *(DD++);
idx = j = i+1;
while (j<N_1) {
j++;
if (*DD<min) {
min = *DD;
idx = j;
}
DD++;
}
mindist[i] = min;
n_nghbr[i] = idx;
}
// Put the minimal distances into a heap structure to make the repeated global
// minimum searches fast.
nn_distances.heapify(mindist);
// Main loop: We have N-1 merging steps.
for (i=0; i<N_1; i++) {
/*
Here is a special feature that allows fast bookkeeping and updates of the
minimal distances.
mindist[i] stores a lower bound on the minimum distance of the point i to
all points of higher index:
mindist[i] ≥ min_{j>i} D(i,j)
Normally, we have equality. However, this minimum may become invalid due to
the updates in the distance matrix. The rules are:
1) If mindist[i] is equal to D(i, n_nghbr[i]), this is the correct minimum
and n_nghbr[i] is a nearest neighbor.
2) If mindist[i] is smaller than D(i, n_nghbr[i]), this might not be the
correct minimum. The minimum needs to be recomputed.
3) mindist[i] is never bigger than the true minimum. Hence, we never miss the
true minimum if we take the smallest mindist entry, re-compute the value if
necessary (thus maybe increasing it) and looking for the now smallest
mindist entry until a valid minimal entry is found. This step is done in the
lines below.
The update process for D below takes care that these rules are fulfilled. This
makes sure that the minima in the rows D(i,i+1:)of D are re-calculated when
necessary but re-calculation is avoided whenever possible.
The re-calculation of the minima makes the worst-case runtime of this algorithm
cubic in N. We avoid this whenever possible, and in most cases the runtime
appears to be quadratic.
*/
idx1 = nn_distances.argmin();
if (method != METHOD_METR_SINGLE) {
while ( D_(idx1, n_nghbr[idx1]) > mindist[idx1] ) {
// Recompute the minimum mindist[idx1] and n_nghbr[idx1].
n_nghbr[idx1] = j = active_nodes.succ[idx1]; // exists, maximally N-1
min = D_(idx1,j);
for (j=active_nodes.succ[j]; j<N; j=active_nodes.succ[j]) {
if (D_(idx1,j)<min) {
min = D_(idx1,j);
n_nghbr[idx1] = j;
}
}
/* Update the heap with the new true minimum and search for the (possibly
different) minimal entry. */
nn_distances.update_geq(idx1, min);
idx1 = nn_distances.argmin();
}
}
nn_distances.heap_pop(); // Remove the current minimum from the heap.
idx2 = n_nghbr[idx1];
// Write the newly found minimal pair of nodes to the output array.
node1 = row_repr[idx1];
node2 = row_repr[idx2];
if (method==METHOD_METR_AVERAGE ||
method==METHOD_METR_WARD ||
method==METHOD_METR_CENTROID) {
size1 = static_cast<t_float>(members[idx1]);
size2 = static_cast<t_float>(members[idx2]);
members[idx2] += members[idx1];
}
Z2.append(node1, node2, mindist[idx1]);
// Remove idx1 from the list of active indices (active_nodes).
active_nodes.remove(idx1);
// Index idx2 now represents the new (merged) node with label N+i.
row_repr[idx2] = N+i;
// Update the distance matrix
switch (method) {
case METHOD_METR_SINGLE:
/*
Single linkage.
Characteristic: new distances are never longer than the old distances.
*/
// Update the distance matrix in the range [start, idx1).
for (j=active_nodes.start; j<idx1; j=active_nodes.succ[j]) {
f_single(&D_(j, idx2), D_(j, idx1));
if (n_nghbr[j] == idx1)
n_nghbr[j] = idx2;
}
// Update the distance matrix in the range (idx1, idx2).
for (; j<idx2; j=active_nodes.succ[j]) {
f_single(&D_(j, idx2), D_(idx1, j));
// If the new value is below the old minimum in a row, update
// the mindist and n_nghbr arrays.
if (D_(j, idx2)<mindist[j]) {
nn_distances.update_leq(j, D_(j, idx2));
n_nghbr[j] = idx2;
}
}
// Update the distance matrix in the range (idx2, N).
// Recompute the minimum mindist[idx2] and n_nghbr[idx2].
if (idx2<N_1) {
min = mindist[idx2];
for (j=active_nodes.succ[idx2]; j<N; j=active_nodes.succ[j]) {
f_single(&D_(idx2, j), D_(idx1, j) );
if (D_(idx2, j) < min) {
n_nghbr[idx2] = j;
min = D_(idx2, j);
}
}
nn_distances.update_leq(idx2, min);
}
break;
case METHOD_METR_COMPLETE:
/*
Complete linkage.
Characteristic: new distances are never shorter than the old distances.
*/
// Update the distance matrix in the range [start, idx1).
for (j=active_nodes.start; j<idx1; j=active_nodes.succ[j]) {
f_complete(&D_(j, idx2), D_(j, idx1) );
if (n_nghbr[j] == idx1)
n_nghbr[j] = idx2;
}
// Update the distance matrix in the range (idx1, idx2).
for (; j<idx2; j=active_nodes.succ[j])
f_complete(&D_(j, idx2), D_(idx1, j) );
// Update the distance matrix in the range (idx2, N).
for (j=active_nodes.succ[idx2]; j<N; j=active_nodes.succ[j])
f_complete(&D_(idx2, j), D_(idx1, j) );
break;
case METHOD_METR_AVERAGE: {
/*
Average linkage.
Shorter and longer distances can occur.
*/
// Update the distance matrix in the range [start, idx1).
t_float s = size1/(size1+size2);
t_float t = size2/(size1+size2);
for (j=active_nodes.start; j<idx1; j=active_nodes.succ[j]) {
f_average(&D_(j, idx2), D_(j, idx1), s, t);
if (n_nghbr[j] == idx1)
n_nghbr[j] = idx2;
}
// Update the distance matrix in the range (idx1, idx2).
for (; j<idx2; j=active_nodes.succ[j]) {
f_average(&D_(j, idx2), D_(idx1, j), s, t);
if (D_(j, idx2)<mindist[j]) {
nn_distances.update_leq(j, D_(j, idx2));
n_nghbr[j] = idx2;
}
}
// Update the distance matrix in the range (idx2, N).
if (idx2<N_1) {
n_nghbr[idx2] = j = active_nodes.succ[idx2]; // exists, maximally N-1
f_average(&D_(idx2, j), D_(idx1, j), s, t);
min = D_(idx2,j);
for (j=active_nodes.succ[j]; j<N; j=active_nodes.succ[j]) {
f_average(&D_(idx2, j), D_(idx1, j), s, t);
if (D_(idx2,j)<min) {
min = D_(idx2,j);
n_nghbr[idx2] = j;
}
}
nn_distances.update(idx2, min);
}
break;
}
case METHOD_METR_WEIGHTED:
/*
Weighted linkage.
Shorter and longer distances can occur.
*/
// Update the distance matrix in the range [start, idx1).
for (j=active_nodes.start; j<idx1; j=active_nodes.succ[j]) {
f_weighted(&D_(j, idx2), D_(j, idx1) );
if (n_nghbr[j] == idx1)
n_nghbr[j] = idx2;
}
// Update the distance matrix in the range (idx1, idx2).
for (; j<idx2; j=active_nodes.succ[j]) {
f_weighted(&D_(j, idx2), D_(idx1, j) );