This repository has been archived by the owner on Aug 9, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
isosplit5.cpp
1473 lines (1347 loc) · 50.5 KB
/
isosplit5.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 "isosplit5.h"
#include <stdlib.h>
#include <vector>
#include <stdio.h>
#include <math.h>
#include "isocut5.h"
typedef std::vector<std::vector<bigint> > intarray2d;
void alloc(intarray2d& X, bigint N1, bigint N2)
{
X.resize(N1);
for (bigint i = 0; i < N1; i++) {
X[i].resize(N2);
}
}
namespace ns_isosplit5 {
struct kmeans_opts {
bigint num_iterations = 0;
};
bigint compute_max(bigint N, int* labels);
bigint compute_max(bigint N, bigint* inds);
void kmeans_multistep(int* labels, bigint M, bigint N, float* X, bigint K1, bigint K2, bigint K3, kmeans_opts opts);
void kmeans_maxsize(int* labels, bigint M, bigint N, float* X, bigint maxsize, kmeans_opts opts);
void compare_clusters(double* dip_score, std::vector<bigint>* new_labels1, std::vector<bigint>* new_labels2, bigint M, bigint N1, bigint N2, float* X1, float* X2, float* centroid1, float* centroid2);
void compute_centroids(float* centroids, bigint M, bigint N, bigint Kmax, float* X, int* labels, std::vector<bigint>& clusters_to_compute_vec);
void compute_covmats(float* covmats, bigint M, bigint N, bigint Kmax, float* X, int* labels, float* centroids, std::vector<bigint>& clusters_to_compute_vec);
void get_pairs_to_compare(std::vector<bigint>* inds1, std::vector<bigint>* inds2, bigint M, bigint K, float* active_centroids, const intarray2d& active_comparisons_made);
void compare_pairs(std::vector<bigint>* clusters_changed, bigint* total_num_label_changes, bigint M, bigint N, float* X, int* labels, const std::vector<bigint>& inds1, const std::vector<bigint>& inds2, const isosplit5_opts& opts, float* centroids, float* covmats); //the labels are updated
}
namespace smi {
bool get_inverse_via_lu_decomposition(int M, float* out, float* in);
}
void isosplit5_mex(double* labels_out, int M, int N, double* X)
{
float* Xf = (float*)malloc(sizeof(float) * M * N);
int* labelsi = (int*)malloc(sizeof(int) * N);
for (bigint i = 0; i < M * N; i++)
Xf[i] = X[i];
isosplit5_opts opts;
//opts.refine_clusters=true;
isosplit5(labelsi, M, N, Xf, opts);
for (bigint i = 0; i < N; i++)
labels_out[i] = labelsi[i];
free(Xf);
free(labelsi);
}
struct parcelate2_opts {
bool final_reassign = false; //not yet implemented
};
struct p2_parcel {
std::vector<bigint> indices;
std::vector<float> centroid;
double radius;
};
void print_matrix(bigint M, bigint N, float* A)
{
for (bigint m = 0; m < M; m++) {
for (bigint n = 0; n < N; n++) {
float val = A[m + M * n];
printf("%g ", val);
}
printf("\n");
}
}
std::vector<float> p2_compute_centroid(bigint M, float* X, const std::vector<bigint>& indices)
{
std::vector<double> ret(M);
double count = 0;
for (bigint m = 0; m < M; m++) {
ret[m] = 0;
}
for (bigint i = 0; i < (bigint)indices.size(); i++) {
for (bigint m = 0; m < M; m++) {
ret[m] += X[m + M * indices[i]];
}
count++;
}
if (count) {
for (bigint m = 0; m < M; m++) {
ret[m] /= count;
}
}
std::vector<float> retf(M);
for (bigint m = 0; m < M; m++)
retf[m] = ret[m];
return retf;
}
double p2_compute_max_distance(const std::vector<float>& centroid, bigint M, float* X, const std::vector<bigint>& indices)
{
double max_dist = 0;
for (bigint i = 0; i < (bigint)indices.size(); i++) {
double dist = 0;
for (bigint m = 0; m < M; m++) {
double val = centroid[m] - X[m + M * indices[i]];
dist += val * val;
}
dist = sqrt(dist);
if (dist > max_dist)
max_dist = dist;
}
return max_dist;
}
std::vector<bigint> p2_randsample(bigint N, bigint K)
{
(void)N;
// Not we are not actually randomizing here. There's a reason, I believe.
std::vector<bigint> inds;
for (bigint a = 0; a < K; a++)
inds.push_back(a);
return inds;
/*
if (K>N) K=N;std::vector<bigint> inds;
std::vector<bigint> used(N);
for (bigint i=0; i<N; i++)
used[i]=0;
for (bigint k=0; k<K; k++)
used[k]=1;
for (bigint k=0; k<K; k++) {
bigint ii=rand()%N;
bigint tmp=used[k];
used[k]=used[ii];
used[ii]=tmp;
}
std::vector<bigint> inds;
for (bigint i=0; i<N; i++) {
if (used[i])
inds.push_back(i);
}
return inds;
*/
}
bool parcelate2(int* labels, bigint M, bigint N, float* X, bigint target_parcel_size, bigint target_num_parcels, const parcelate2_opts& p2opts)
{
std::vector<p2_parcel> parcels;
for (bigint i = 0; i < N; i++)
labels[i] = 1;
p2_parcel P;
P.indices.resize(N);
for (bigint i = 0; i < N; i++)
P.indices[i] = i;
P.centroid = p2_compute_centroid(M, X, P.indices);
P.radius = p2_compute_max_distance(P.centroid, M, X, P.indices);
parcels.push_back(P);
bigint split_factor = 3; // split factor around 2.71 is in a sense ideal
double target_radius;
while ((bigint)parcels.size() < target_num_parcels) {
bool candidate_found = false;
for (bigint i = 0; i < (bigint)parcels.size(); i++) {
std::vector<bigint>* indices = &parcels[i].indices;
if ((bigint)indices->size() > target_parcel_size) {
if (parcels[i].radius > 0)
candidate_found = true;
}
}
if (!candidate_found) {
// nothing else will ever be split
break;
}
target_radius = 0;
for (bigint i = 0; i < (bigint)parcels.size(); i++) {
if ((bigint)parcels[i].indices.size() > target_parcel_size) {
double tmp = parcels[i].radius * 0.95;
if (tmp > target_radius)
target_radius = tmp;
}
}
if (target_radius == 0) {
printf("Unexpected target radius of zero.\n");
break;
}
bigint p_index = 0;
while (p_index < (bigint)parcels.size()) {
std::vector<bigint> inds = parcels[p_index].indices;
double rad = parcels[p_index].radius;
bigint sz = parcels[p_index].indices.size();
if ((sz > target_parcel_size) && (rad >= target_radius)) {
std::vector<bigint> assignments(inds.size());
std::vector<bigint> iii = p2_randsample(sz, split_factor);
for (bigint i = 0; i < (bigint)inds.size(); i++) {
bigint best_pt = -1;
double best_dist = 0;
for (bigint j = 0; j < (bigint)iii.size(); j++) {
double dist = 0;
for (bigint m = 0; m < M; m++) {
double val = X[m + M * inds[iii[j]]] - X[m + M * inds[i]];
dist += val * val;
}
dist = sqrt(dist);
if ((best_pt < 0) || (dist < best_dist)) {
best_dist = dist;
best_pt = j;
}
}
assignments[i] = best_pt;
}
parcels[p_index].indices.clear();
for (bigint i = 0; i < (bigint)inds.size(); i++) {
if (assignments[i] == 0) {
parcels[p_index].indices.push_back(inds[i]);
labels[inds[i]] = p_index + 1;
}
}
parcels[p_index].centroid = p2_compute_centroid(M, X, parcels[p_index].indices);
parcels[p_index].radius = p2_compute_max_distance(parcels[p_index].centroid, M, X, parcels[p_index].indices);
for (bigint jj = 1; jj < (bigint)iii.size(); jj++) {
p2_parcel PP;
for (bigint i = 0; i < (bigint)inds.size(); i++) {
if (assignments[i] == jj) {
PP.indices.push_back(inds[i]);
labels[inds[i]] = parcels.size() + 1;
}
}
PP.centroid = p2_compute_centroid(M, X, PP.indices);
PP.radius = p2_compute_max_distance(PP.centroid, M, X, PP.indices);
if (PP.indices.size() > 0)
parcels.push_back(PP);
else {
printf("Unexpected problem. New parcel has no points -- perhaps dataset contains duplicate points? -- original size = %ld.\n", sz);
return false;
}
}
if ((bigint)parcels[p_index].indices.size() == sz) {
printf("Warning: Size did not change after splitting parcel.\n");
p_index++;
}
}
else {
p_index++;
}
}
}
//final reassign not yet implemented
if (p2opts.final_reassign) {
//centroids=get_parcel_centroids(parcels);
//labels=knnsearch(centroids',X','K',1)';
}
return true;
}
bool isosplit5(int* labels, bigint M, bigint N, float* X, isosplit5_opts opts)
{
// compute the initial clusters
bigint target_parcel_size = opts.min_cluster_size;
bigint target_num_parcels = opts.K_init;
// !! important not to do a final reassign because then the shapes will not be conducive to isosplit iterations -- hexagons are not good for isosplit!
parcelate2_opts p2opts;
p2opts.final_reassign = false;
if (!parcelate2(labels, M, N, X, target_parcel_size, target_num_parcels, p2opts))
return false;
int Kmax = ns_isosplit5::compute_max(N, labels);
float* centroids = (float*)malloc(sizeof(float) * M * Kmax);
float* covmats = (float*)malloc(sizeof(float) * M * M * Kmax);
std::vector<bigint> clusters_to_compute_vec;
for (bigint k = 0; k < Kmax; k++)
clusters_to_compute_vec.push_back(1);
ns_isosplit5::compute_centroids(centroids, M, N, Kmax, X, labels, clusters_to_compute_vec);
ns_isosplit5::compute_covmats(covmats, M, N, Kmax, X, labels, centroids, clusters_to_compute_vec);
// The active labels are those that are still being used -- for now, everything is active
int active_labels_vec[Kmax];
for (bigint i = 0; i < Kmax; i++)
active_labels_vec[i] = 1;
std::vector<int> active_labels;
for (bigint i = 0; i < Kmax; i++)
active_labels.push_back(i + 1);
// Repeat while something has been merged in the pass
bool final_pass = false; // plus we do one final pass at the end
intarray2d comparisons_made; // Keep a matrix of comparisons that have been made in this pass
alloc(comparisons_made, Kmax, Kmax);
for (bigint i1 = 0; i1 < Kmax; i1++)
for (bigint i2 = 0; i2 < Kmax; i2++)
comparisons_made[i1][i2] = 0;
while (true) { //passes
bool something_merged = false; //Keep track of whether something has merged in this pass. If not, do a final pass.
std::vector<bigint> clusters_changed_vec_in_pass(Kmax); //Keep track of the clusters that have changed in this pass so that we can update the comparisons_made matrix at the end
for (bigint i = 0; i < Kmax; i++)
clusters_changed_vec_in_pass[i] = 0;
bigint iteration_number = 0;
while (true) { //iterations
std::vector<bigint> clusters_changed_vec_in_iteration(Kmax); //Keep track of the clusters that have changed in this iteration so that we can update centroids and covmats
for (bigint i = 0; i < Kmax; i++)
clusters_changed_vec_in_iteration[i] = 0;
iteration_number++;
if (iteration_number > opts.max_iterations_per_pass) {
printf("Warning: max iterations per pass exceeded.\n");
break;
}
if (active_labels.size() > 0) {
// Create an array of active centroids and comparisons made, for determining the pairs to compare
float* active_centroids = (float*)malloc(sizeof(float) * M * active_labels.size());
for (bigint i = 0; i < (bigint)active_labels.size(); i++) {
for (bigint m = 0; m < M; m++) {
active_centroids[m + M * i] = centroids[m + M * (active_labels[i] - 1)];
}
}
intarray2d active_comparisons_made;
alloc(active_comparisons_made, active_labels.size(), active_labels.size());
for (bigint i1 = 0; i1 < (bigint)active_labels.size(); i1++) {
for (bigint i2 = 0; i2 < (bigint)active_labels.size(); i2++) {
active_comparisons_made[i1][i2] = comparisons_made[active_labels[i1] - 1][active_labels[i2] - 1];
}
}
// Find the pairs to compare on this iteration
// These will be closest pairs of active clusters that have not yet
// been compared in this pass
std::vector<bigint> inds1, inds2;
ns_isosplit5::get_pairs_to_compare(&inds1, &inds2, M, active_labels.size(), active_centroids, active_comparisons_made);
std::vector<bigint> inds1b, inds2b; //remap the clusters to the original labeling
for (bigint i = 0; i < (bigint)inds1.size(); i++) {
inds1b.push_back(active_labels[inds1[i] - 1]);
inds2b.push_back(active_labels[inds2[i] - 1]);
}
// If we didn't find any, break from this iteration
if (inds1b.size() == 0) {
break;
}
// Actually compare the pairs -- in principle this operation could be parallelized
std::vector<bigint> clusters_changed;
bigint total_num_label_changes = 0;
ns_isosplit5::compare_pairs(&clusters_changed, &total_num_label_changes, M, N, X, labels, inds1b, inds2b, opts, centroids, covmats); //the labels are updated
for (bigint i = 0; i < (bigint)clusters_changed.size(); i++) {
clusters_changed_vec_in_pass[clusters_changed[i] - 1] = 1;
clusters_changed_vec_in_iteration[clusters_changed[i] - 1] = 1;
}
// Update which comparisons have been made
for (bigint j = 0; j < (bigint)inds1b.size(); j++) {
comparisons_made[inds1b[j] - 1][inds2b[j] - 1] = 1;
comparisons_made[inds2b[j] - 1][inds1b[j] - 1] = 1;
}
// Recompute the centers for those that have changed in this iteration
ns_isosplit5::compute_centroids(centroids, M, N, Kmax, X, labels, clusters_changed_vec_in_iteration);
ns_isosplit5::compute_covmats(covmats, M, N, Kmax, X, labels, centroids, clusters_changed_vec_in_iteration);
// For diagnostics
//printf ("total num label changes = %d\n",total_num_label_changes);
// Determine whether something has merged and update the active labels
for (bigint i = 0; i < Kmax; i++)
active_labels_vec[i] = 0;
for (bigint i = 0; i < N; i++)
active_labels_vec[labels[i] - 1] = 1;
std::vector<int> new_active_labels;
for (bigint i = 0; i < Kmax; i++)
if (active_labels_vec[i])
new_active_labels.push_back(i + 1);
if (new_active_labels.size() < active_labels.size())
something_merged = true;
active_labels = new_active_labels;
free(active_centroids);
}
}
// zero out the comparisons made matrix only for those that have changed in this pass
for (bigint i = 0; i < Kmax; i++) {
if (clusters_changed_vec_in_pass[i]) {
for (bigint j = 0; j < Kmax; j++) {
comparisons_made[i][j] = 0;
comparisons_made[j][i] = 0;
}
}
}
if (something_merged)
final_pass = false;
if (final_pass)
break; // This was the final pass and nothing has merged
if (!something_merged)
final_pass = true; // If we are done, do one last pass for final redistributes
}
// We should remap the labels to occupy the first natural numbers
bigint labels_map[Kmax];
for (bigint i = 0; i < Kmax; i++)
labels_map[i] = 0;
for (bigint i = 0; i < (bigint)active_labels.size(); i++) {
labels_map[active_labels[i] - 1] = i + 1;
}
for (bigint i = 0; i < N; i++) {
labels[i] = labels_map[labels[i] - 1];
}
// If the user wants to refine the clusters, then we repeat isosplit on each
// of the new clusters, recursively. Unless we only found only one cluster.
bigint K = ns_isosplit5::compute_max(N, labels);
if ((opts.refine_clusters) && (K > 1)) {
int* labels_split = (int*)malloc(sizeof(int) * N);
isosplit5_opts opts2 = opts;
opts2.refine_clusters = true; // Maybe we should provide an option on whether to do recursive refinement
bigint k_offset = 0;
for (bigint k = 1; k <= K; k++) {
std::vector<bigint> inds_k;
for (bigint i = 0; i < N; i++)
if (labels[i] == k)
inds_k.push_back(i);
if (inds_k.size() > 0) {
float* X_k = (float*)malloc(sizeof(float) * M * inds_k.size()); //Warning: this may cause memory problems -- especially for recursive case
int* labels_k = (int*)malloc(sizeof(int) * inds_k.size());
for (bigint i = 0; i < (bigint)inds_k.size(); i++) {
for (bigint m = 0; m < M; m++) {
X_k[m + M * i] = X[m + M * inds_k[i]];
}
}
isosplit5(labels_k, M, inds_k.size(), X_k, opts2);
for (bigint i = 0; i < (bigint)inds_k.size(); i++) {
labels_split[inds_k[i]] = k_offset + labels_k[i];
}
k_offset += ns_isosplit5::compute_max(inds_k.size(), labels_k);
free(labels_k);
free(X_k);
}
}
for (bigint i = 0; i < N; i++)
labels[i] = labels_split[i];
free(labels_split);
}
free(centroids);
free(covmats);
return true;
}
/*
*/
/*
void isosplit5_old(bigint *labels_out,bigint M, bigint N,float *X,isosplit5_opts opts) {
for (bigint i=0; i<N; i++) {
labels_out[i]=1;
}
isosplit5_data DD(M,N,X);
DD.initialize_labels();
DD.compute_all_centroids();
bigint max_iterations=500;
bigint max_iterations_without_merges=5;
bigint iteration_number=1;
bigint num_iterations_without_merges=0;
while (true) {
iteration_number++;
if (iteration_number>max_iterations) {
printf ("isosplit5: Exceeded maximum number of iterations. Breaking.");
break;
}
printf ("Number of active labels: %d\n",DD.get_active_labels().size());
std::vector<bigint> k1s,k2s;
DD.get_pairs_to_compare(&k1s,&k2s);
printf ("compare %d pairs\n",k1s.size());
std::vector<bigint> old_active_labels=DD.get_active_labels();
bigint num_changes=DD.compare_pairs(k1s,k2s,opts.isocut_threshold);
std::vector<bigint> new_active_labels=DD.get_active_labels();
printf (" %d changes\n",num_changes);
if (new_active_labels.size()==old_active_labels.size())
num_iterations_without_merges++;
else
num_iterations_without_merges=0;
if (num_iterations_without_merges>=max_iterations_without_merges)
break;
}
for (bigint pass=1; pass<=2; pass++) {
std::vector<bigint> active_labels=DD.get_active_labels();
for (bigint i1=0; i1<(bigint)active_labels.size(); i1++) {
for (bigint i2=i1+1; i2<(bigint)active_labels.size(); i2++) {
bigint k1=active_labels[i1];
bigint k2=active_labels[i2];
if ((DD.active_labels_vec[k1-1])&&(DD.active_labels_vec[k2-1])) {
printf ("Number of active labels: %d\n",DD.get_active_labels().size());
printf ("compare %d/%d (pass %d)\n",k1,k2,pass);
std::vector<bigint> k1s,k2s;
k1s.push_back(k1);
k2s.push_back(k2);
bigint num_changes=DD.compare_pairs(k1s,k2s,opts.isocut_threshold);
printf (" %d changes\n",num_changes);
}
}
}
}
std::vector<bigint> active_labels=DD.get_active_labels();
std::vector<bigint> labels_map(ns_isosplit5::compute_max(N,DD.labels)+1);
for (bigint i=0; i<(bigint)active_labels.size(); i++) {
labels_map[active_labels[i]]=i+1;
}
for (bigint i=0; i<N; i++) {
labels_out[i]=labels_map[DD.labels[i]];
}
}
*/
namespace ns_isosplit5 {
bigint compute_max(bigint N, int* labels)
{
if (N == 0)
return 0;
bigint ret = labels[0];
for (bigint i = 0; i < N; i++) {
if (labels[i] > ret)
ret = labels[i];
}
return ret;
}
/*
bigint compute_max(bigint N, bigint* inds)
{
if (N == 0)
return 0;
bigint ret = inds[0];
for (bigint i = 0; i < N; i++) {
if (inds[i] > ret)
ret = inds[i];
}
return ret;
}
*/
void kmeans_initialize(double* centroids, bigint M, bigint N, bigint K, float* X)
{
std::vector<bigint> used(N);
for (bigint i = 0; i < N; i++)
used[i] = 0;
for (bigint k = 0; k < K; k++)
used[k] = 1;
for (bigint k = 0; k < K; k++) {
bigint ii = rand() % N;
bigint tmp = used[k];
used[k] = used[ii];
used[ii] = tmp;
}
std::vector<bigint> inds;
for (bigint i = 0; i < N; i++) {
if (used[i])
inds.push_back(i);
}
for (bigint k = 0; k < (bigint)inds.size(); k++) {
for (bigint m = 0; m < M; m++) {
centroids[m + M * k] = X[m + M * inds[k]];
}
}
}
double compute_dist(bigint M, float* X, double* Y)
{
double sumsqr = 0;
for (bigint m = 0; m < M; m++) {
double val = X[m] - Y[m];
sumsqr += val * val;
}
return sqrt(sumsqr);
}
bigint kmeans_assign2(bigint M, bigint K, float* X0, double* centroids)
{
bigint ret = 0;
double best_dist = 0;
for (bigint k = 1; k <= K; k++) {
double dist = compute_dist(M, X0, ¢roids[M * (k - 1)]);
if ((ret == 0) || (dist < best_dist)) {
best_dist = dist;
ret = k;
}
}
return ret;
}
void kmeans_assign(int* labels, bigint M, bigint N, bigint K, float* X, double* centroids)
{
for (bigint i = 0; i < N; i++) {
labels[i] = kmeans_assign2(M, K, &X[M * i], centroids);
}
}
void kmeans_centroids(double* centroids, bigint M, bigint N, bigint K, float* X, int* labels)
{
std::vector<bigint> counts(K);
for (bigint k = 1; k <= K; k++) {
counts[k - 1] = 0;
for (bigint m = 0; m < M; m++) {
centroids[m + (k - 1) * M] = 0;
}
}
for (bigint i = 0; i < N; i++) {
bigint k = labels[i];
for (bigint m = 0; m < M; m++) {
centroids[m + (k - 1) * M] += X[m + i * M];
}
counts[k - 1]++;
}
for (bigint k = 1; k <= K; k++) {
if (counts[k - 1]) {
for (bigint m = 0; m < M; m++) {
centroids[m + (k - 1) * M] /= counts[k - 1];
}
}
}
}
void kmeans(int* labels, bigint M, bigint N, float* X, bigint K, kmeans_opts opts)
{
if (K > N)
K = N;
double* centroids = (double*)malloc(sizeof(double) * M * K);
kmeans_initialize(centroids, M, N, K, X);
for (bigint it = 1; it <= opts.num_iterations; it++) {
kmeans_assign(labels, M, N, K, X, centroids);
kmeans_centroids(centroids, M, N, K, X, labels);
}
kmeans_assign(labels, M, N, K, X, centroids);
free(centroids);
}
void extract_subarray(float* X_sub, bigint M, float* X, const std::vector<bigint>& inds)
{
for (bigint i = 0; i < (bigint)inds.size(); i++) {
for (bigint m = 0; m < M; m++) {
X_sub[m + i * M] = X[m + inds[i] * M];
}
}
}
void kmeans_maxsize(int* labels, bigint M, bigint N, float* X, bigint maxsize, kmeans_opts opts)
{
if (N <= maxsize) {
for (bigint i = 0; i < N; i++)
labels[i] = 1;
return;
}
bigint K = ceil(N * 1.0 / maxsize);
int* labels1 = (int*)malloc(sizeof(int) * N);
kmeans(labels1, M, N, X, K, opts);
bigint L1 = compute_max(N, labels1);
bigint current_max_k = 0;
for (bigint k = 1; k <= L1; k++) {
std::vector<bigint> inds_k;
for (bigint i = 0; i < N; i++) {
if (labels1[i] == k)
inds_k.push_back(i);
}
if (inds_k.size() > 0) {
float* X2 = (float*)malloc(sizeof(float) * M * inds_k.size());
int* labels2 = (int*)malloc(sizeof(int) * inds_k.size());
extract_subarray(X2, M, X, inds_k);
kmeans_maxsize(labels2, M, inds_k.size(), X2, maxsize, opts);
for (bigint j = 0; j < (bigint)inds_k.size(); j++) {
labels[inds_k[j]] = current_max_k + labels2[j];
}
current_max_k += compute_max(inds_k.size(), labels2);
free(X2);
free(labels2);
}
}
free(labels1);
}
void kmeans_multistep(int* labels, bigint M, bigint N, float* X, bigint K1, bigint K2, bigint K3, kmeans_opts opts)
{
if (K2 > 1) {
int* labels1 = (int*)malloc(sizeof(int) * N);
for (bigint i = 0; i < N; i++)
labels1[i] = 0;
kmeans_multistep(labels1, M, N, X, K2, K3, 0, opts);
bigint L1 = compute_max(N, labels1);
bigint current_max_k = 0;
for (bigint k = 1; k <= L1; k++) {
std::vector<bigint> inds_k;
for (bigint i = 0; i < N; i++) {
if (labels1[i] == k)
inds_k.push_back(i);
}
if (inds_k.size() > 0) {
float* X2 = (float*)malloc(sizeof(float) * M * inds_k.size());
int* labels2 = (int*)malloc(sizeof(int) * inds_k.size());
extract_subarray(X2, M, X, inds_k);
kmeans_multistep(labels2, M, inds_k.size(), X2, K1, 0, 0, opts);
for (bigint j = 0; j < (bigint)inds_k.size(); j++) {
labels[inds_k[j]] = current_max_k + labels2[j];
}
current_max_k += compute_max(inds_k.size(), labels2);
free(X2);
free(labels2);
}
}
free(labels1);
}
else {
kmeans(labels, M, N, X, K1, opts);
}
}
double dot_product(bigint N, float* X, float* Y)
{
double ret = 0;
for (bigint i = 0; i < N; i++) {
ret += X[i] * Y[i];
}
return ret;
}
void normalize_vector(bigint N, float* V)
{
double norm = sqrt(dot_product(N, V, V));
if (!norm)
return;
for (bigint i = 0; i < N; i++)
V[i] /= norm;
}
void compare_clusters(double* dip_score, std::vector<bigint>* new_labels1, std::vector<bigint>* new_labels2, bigint M, bigint N1, bigint N2, float* X1, float* X2, double* centroid1, double* centroid2)
{
float* V = (float*)malloc(sizeof(float) * M);
float* projection = (float*)malloc(sizeof(float) * (N1 + N2));
for (bigint m = 0; m < M; m++) {
V[m] = centroid2[m] - centroid1[m];
}
normalize_vector(M, V);
for (bigint i = 0; i < N1; i++) {
projection[i] = dot_product(M, V, &X1[M * i]);
}
for (bigint i = 0; i < N2; i++) {
projection[N1 + i] = dot_product(M, V, &X2[M * i]);
}
isocut5_opts icopts;
icopts.already_sorted = false;
double cutpoint;
isocut5(dip_score, &cutpoint, N1 + N2, projection, icopts);
new_labels1->resize(N1);
new_labels2->resize(N2);
for (bigint i = 0; i < N1; i++) {
if (projection[i] < cutpoint)
(*new_labels1)[i] = 1;
else
(*new_labels1)[i] = 2;
}
for (bigint i = 0; i < N2; i++) {
if (projection[N1 + i] < cutpoint)
(*new_labels2)[i] = 1;
else
(*new_labels2)[i] = 2;
}
free(projection);
free(V);
}
void compute_centroids(float* centroids, bigint M, bigint N, bigint Kmax, float* X, int* labels, std::vector<bigint>& cluster_to_compute_vec)
{
std::vector<double> C(M * Kmax);
for (bigint jj = 0; jj < M * Kmax; jj++)
C[jj] = 0;
std::vector<double> counts(Kmax);
for (bigint k = 0; k < Kmax; k++)
counts[k] = 0;
for (bigint i = 0; i < N; i++) {
bigint k0 = labels[i];
bigint i0 = k0 - 1;
if (cluster_to_compute_vec[i0]) {
for (bigint m = 0; m < M; m++) {
C[m + M * i0] += X[m + M * i];
}
counts[i0]++;
}
}
for (bigint k = 0; k < Kmax; k++) {
if (cluster_to_compute_vec[k]) {
if (counts[k]) {
for (bigint m = 0; m < M; m++) {
C[m + M * k] /= counts[k];
}
}
}
}
for (bigint k = 0; k < Kmax; k++) {
if (cluster_to_compute_vec[k]) {
for (bigint m = 0; m < M; m++) {
centroids[m + k * M] = C[m + k * M];
}
}
}
}
void compute_covmats(float* covmats, bigint M, bigint N, bigint Kmax, float* X, int* labels, float* centroids, std::vector<bigint>& clusters_to_compute_vec)
{
std::vector<double> C(M * M * Kmax);
for (bigint jj = 0; jj < M * M * Kmax; jj++)
C[jj] = 0;
std::vector<double> counts(Kmax);
for (bigint k = 0; k < Kmax; k++)
counts[k] = 0;
for (bigint i = 0; i < N; i++) {
bigint i0 = labels[i] - 1;
if (clusters_to_compute_vec[i0]) {
for (bigint m1 = 0; m1 < M; m1++) {
for (bigint m2 = 0; m2 < M; m2++) {
C[m1 + M * m2 + M * M * i0] += (X[m1 + M * i] - centroids[m1 + i0 * M]) * (X[m2 + M * i] - centroids[m2 + i0 * M]);
}
}
counts[i0]++;
}
}
for (bigint k = 0; k < Kmax; k++) {
if (clusters_to_compute_vec[k]) {
if (counts[k]) {
for (bigint m1 = 0; m1 < M; m1++) {
for (bigint m2 = 0; m2 < M; m2++) {
C[m1 + m2 * M + M * M * k] /= counts[k];
}
}
}
}
}
for (bigint k = 0; k < Kmax; k++) {
if (clusters_to_compute_vec[k]) {
for (bigint mm = 0; mm < M * M; mm++) {
covmats[mm + k * M * M] = C[mm + k * M * M];
}
}
}
}
void get_pairs_to_compare(std::vector<bigint>* inds1, std::vector<bigint>* inds2, bigint M, bigint K, float* active_centroids, const intarray2d& active_comparisons_made)
{
inds1->clear();
inds2->clear();
double dists[K][K];
for (bigint k1 = 0; k1 < K; k1++) {
for (bigint k2 = 0; k2 < K; k2++) {
if ((active_comparisons_made[k1][k2]) || (k1 == k2))
dists[k1][k2] = -1;
else {
double dist = 0;
for (bigint m = 0; m < M; m++) {
double val = active_centroids[m + M * k1] - active_centroids[m + M * k2];
dist += val * val;
}
dist = sqrt(dist);
dists[k1][k2] = dist;
}
}
}
// important to only take the mutal closest pairs -- unlike how we originally did it
//bool something_changed = true;
//while (something_changed) {
//something_changed = false;
std::vector<bigint> best_inds(K);
for (bigint k = 0; k < K; k++) {
bigint best_ind = -1;
double best_distance = -1;
for (bigint k2 = 0; k2 < K; k2++) {
if (dists[k][k2] >= 0) {
if ((best_distance < 0) || (dists[k][k2] < best_distance)) {
best_distance = dists[k][k2];
best_ind = k2;
}
}
}
best_inds[k] = best_ind;
}
for (bigint j = 0; j < K; j++) {
if (best_inds[j] > j) {
if (best_inds[best_inds[j]] == j) { //mutual
if (dists[j][best_inds[j]] >= 0) {
inds1->push_back(j + 1);
inds2->push_back(best_inds[j] + 1);
for (bigint aa = 0; aa < K; aa++) {
dists[j][aa] = -1;
dists[aa][j] = -1;
dists[best_inds[j]][aa] = -1;
dists[aa][best_inds[j]] = -1;
}
//something_changed = true;
}
}
}
}
//}
}
std::vector<float> compute_centroid(bigint M, bigint N, float* X)
{
std::vector<double> ret(M);
double count = 0;
for (bigint m = 0; m < M; m++) {
ret[m] = 0;
}
for (bigint i = 0; i < N; i++) {
for (bigint m = 0; m < M; m++) {
ret[m] += X[m + M * i];
}
count++;
}
if (count) {
for (bigint m = 0; m < M; m++) {
ret[m] /= count;
}
}
std::vector<float> retf(M);
for (bigint m = 0; m < M; m++)
retf[m] = ret[m];
return retf;
}
bool matinv(bigint M, float* out, float* in)
{
return smi::get_inverse_via_lu_decomposition(M, out, in);
}
void matvec(bigint M, bigint N, float* out, float* mat, float* vec)
{
for (bigint m = 0; m < M; m++) {
float val = 0;
for (bigint n = 0; n < N; n++) {
val += mat[m + M * n] * vec[n];
}
out[m] = val;
}
}
double dbg_compute_mean(const std::vector<float>& X)
{
double ret = 0;
for (bigint i = 0; i < (bigint)X.size(); i++)
ret += X[i];
return ret / X.size();
}
double dbg_compute_var(const std::vector<float>& X)
{
double mu = dbg_compute_mean(X);
double ret = 0;
for (bigint i = 0; i < (bigint)X.size(); i++)
ret += (X[i] - mu) * (X[i] - mu);
return ret / X.size();
}
bool merge_test(std::vector<bigint>* L12, bigint M, bigint N1, bigint N2, float* X1, float* X2, const isosplit5_opts& opts, float* centroid1, float* centroid2, float* covmat1, float* covmat2)
{
L12->resize(N1 + N2);
for (bigint i = 0; i < N1 + N2; i++)
(*L12)[i] = 1;
if ((N1 == 0) || (N2 == 0)) {
printf("Error in merge test: N1 or N2 is zero.\n");
return true;
}
//std::vector<float> centroid1 = compute_centroid(M, N1, X1);
//std::vector<float> centroid2 = compute_centroid(M, N2, X2);
std::vector<float> V(M);
for (bigint m = 0; m < M; m++) {
V[m] = centroid2[m] - centroid1[m];
}
std::vector<float> avg_covmat;
avg_covmat.resize(M * M);
for (bigint rr = 0; rr < M * M; rr++) {
avg_covmat[rr] = (covmat1[rr] + covmat2[rr]) / 2;
}
std::vector<float> inv_avg_covmat;
inv_avg_covmat.resize(M * M);
if (!matinv(M, inv_avg_covmat.data(), avg_covmat.data())) {