forked from insilico/plink
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcluster.cpp
More file actions
1777 lines (1323 loc) · 42.1 KB
/
Copy pathcluster.cpp
File metadata and controls
1777 lines (1323 loc) · 42.1 KB
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
//////////////////////////////////////////////////////////////////
// //
// PLINK (c) 2005-2009 Shaun Purcell //
// //
// This file is distributed under the GNU General Public //
// License, Version 2. Please see the file COPYING for more //
// details //
// //
//////////////////////////////////////////////////////////////////
#include <iostream>
#include <iomanip>
#include <fstream>
#include <sstream>
#include <set>
#include <algorithm>
#include <cmath>
#include "plink.h"
#include "helper.h"
#include "options.h"
#include "perm.h"
#include "stats.h"
using namespace std;
extern ofstream LOG;
// Helper function: find the maximum distance between two clusters
double cldist(vector<vector<double> > &, vector<int> &, vector<int> &);
// Helper function: group average link
double groupAvgLink(vector<vector<double> > &, vector<int> &, vector<int> &);
// Helper function: are two clusters phenotypically homogeneous?
bool homogeneous_clusters(Plink &, vector<int> &, vector<int> &);
// Do two clusters conform to any --mcc Ncase Ncontrol specification?
bool spec_clusters(Plink &, vector<int> &, vector<int> &);
// Any members of the clusters that can't be matched?
bool pairable_cluster(vector<vector<bool> > & , vector<int>&, vector<int>&);
// Have we already picked somebody from this category?
bool selcon_inds(Plink&, vector<int>&, vector<int>&, set<int>&);
class Neighbour
{
public:
double dist;
Individual * neighbour;
bool operator< (const Neighbour & s2) const
{ return (dist < s2.dist); }
};
// Complete-linkage clustering based on average IBS distance
// Extra constraints:
// --pmerge P do not merge clusters containing two individuals who differ at this level
// --mc N do not let clusters contain more than N individuals
// --cc do not merge phenotypically identical clusters
// --mcc N1 N2 do not let cluster contain more than N1 cases and N2 controls
// --match external categorical matching criteria
// --match-type positive or negative matches
// --qmatch external quantitative threshold based
// --qt define thresholds for QT matching
// --pick1 only select one individual from each covariate group
// --ibm X identity-by-missingness threshold
void Plink::buildCluster()
{
///////////////////////////////////////
// This is an individual-mode analysis
if (par::SNP_major)
SNP2Ind();
//////////////////////////////////////
// Force an initial cluster solution?
// Initially, # of clusters = # of people, unless
// we are forcing a starting solution
int ni = n;
vector<vector<int> > cl;
if ( par::force_initial_cluster )
{
if (!readClusterFile())
error("Problem reading --within {file}");
printLOG("Forcing an initial starting solution from [ " + par::include_cluster_filename + " ]\n");
set<int> added;
for (int k=0;k<nk;k++)
{
vector<int> t;
for (int i=0;i<ni;i++)
{
if ( sample[i]->sol == k )
{
t.push_back(i);
added.insert(i);
}
}
cl.push_back(t);
}
// And now add any remain individuals, in their own clusters,
// starting from cluster nk onwards
for (int i=0;i<ni;i++)
{
if ( added.find(i) == added.end() )
{
vector<int> t(1);
t[0] = i;
cl.push_back(t);
}
}
}
else
{
for (int i=0;i<ni;i++)
{
vector<int> t(1);
t[0] = i;
cl.push_back(t);
}
}
// T/F matrix (lower diagonal) for whether
// two people can be matched, based on p-value
// constraint and any external criteria
// pairable[i][j] (default = T)
vector<vector<bool> > pairable(n);
for (int i=0; i<n; i++)
{
vector<bool> tmp(n,true);
pairable[i] = tmp;
}
///////////////////////////////
// External matching criteria
// Determine, in advance, potential pairwise matching
if (par::bmatch)
{
printLOG("Applying categorical matching criteria...\n");
// Read in each covariate one at a time,
// and determine matching
// we can use the covariate file, as the cluster
// routine exits after clustering (i.e. so covariates
// never used)
// Has the user specified a match-type file? If not,
// assume all are positive matches.
vector<bool> btype(0);
if (par::bmatch_usertype)
{
checkFileExists(par::bmatch_direction_filename);
ifstream BT(par::bmatch_direction_filename.c_str(), ios::in);
while (!BT.eof())
{
string tmp;
BT >> tmp;
if(BT.eof()) break;
if (tmp=="+" || tmp=="1")
btype.push_back(true);
else
btype.push_back(false);
}
BT.close();
printLOG(int2str(btype.size())+" match-type definitions read from [ "+
par::bmatch_direction_filename+" ]\n");
}
int c=0;
// Swap b-match filename as cluster/within filename
par::include_cluster_filename = par::bmatch_filename;
while (1)
{
par::mult_clst = ++c;
if (!readClusterFile()) break;
if (!par::bmatch_usertype)
btype.push_back(true);
for (int i=0; i<n-1; i++)
for (int j=i+1; j<n; j++)
{
// ->missing means missing on covariate in this context
// Simple matching (no usertypes or +-match)
if ( btype[c-1] )
{
// +/match
if (sample[i]->sol != sample[j]->sol &&
(!sample[i]->missing ) &&
(!sample[j]->missing ) )
pairable[i][j] = pairable[j][i] = false;
}
else
{
// -/match
if (sample[i]->sol == sample[j]->sol &&
(!sample[i]->missing ) &&
(!sample[j]->missing ) )
pairable[i][j] = pairable[j][i] = false;
}
}
}
printLOG("Matched on "+int2str(c-1)+
" variables from [ "+par::bmatch_filename+" ]\n");
}
if (par::qmatch)
{
printLOG("Applying quantitative matching criteria...\n");
vector<double> qt; // number of thresholds specified
checkFileExists(par::qmatch_threshold_filename);
ifstream QT(par::qmatch_threshold_filename.c_str(), ios::in);
while (!QT.eof())
{
double tmp;
QT >> tmp;
if(QT.eof()) break;
qt.push_back(tmp);
}
QT.close();
printLOG(int2str(qt.size())+" q-match thresholds read from [ "+
par::qmatch_threshold_filename+" ]\n");
// Swap q-match filename as covariate file
par::covar_filename = par::qmatch_filename;
int c=0; // counter for number of fields in qmatch file
for (int z=1; z<=qt.size(); z++)
{
par::mult_covar = z;
if (!readCovariateFile()) break;
c++;
for (int i=0; i<n-1; i++)
for (int j=i+1; j<n; j++)
{
if ( abs( sample[i]->covar - sample[j]->covar ) > qt[c-1] &&
(!sample[i]->missing) &&
(!sample[j]->missing) )
pairable[i][j] = pairable[j][i] = false;
}
}
printLOG("Matched on "+
int2str(c)+" quantitative covariates from [ "
+par::qmatch_filename +" ]\n");
}
if (par::cluster_missing)
{
printLOG("Clustering individuals based on genome-wide IBM\n");
}
else
{
printLOG("Clustering individuals based on genome-wide IBS\n");
stringstream s2;
s2 << "Merge distance p-value constraint = " << par::merge_p << "\n";
printLOG(s2.str());
}
if (par::outlier_detection)
printLOG("Outlier detection based on neighbours "+int2str(par::min_neighbour)+
" to "+int2str(par::max_neighbour)+"\n");
/////////////////////////////////////////////////////////
// Also, if --pick1 is in effect, we need to read a list from which
// we can pick only 1 individual
if (par::cluster_selcon)
{
// Swap pick1 filename as covariate file
par::include_cluster_filename = par::cluster_selcon_file;
par::mult_clst = 1;
if (!readClusterFile())
error("Problem reading for --pick1 option");
}
// Keep track of what has been selected already
set<int> selcon;
/////////////////////////////
// Set up distance matrices
// Lower diagonal structure, requires that i > j
mdist.resize(n);
for (int j=0;j<n;j++)
mdist[j].resize(j);
//////////////////////////////////////////
// Genome-wide IBS for each pair
// Either calculate, or re-read from file
vector<double> prop_sig_diff(n);
// Calculate...
if (!par::ibd_read)
{
int c=0;
int c2=0;
for (int i1=0; i1<n-1; i1++)
for (int i2=i1+1; i2<n; i2++)
{
// Only update message every 100 iterations
if (c==c2 || c==np)
{
if (par::cluster_missing)
{
cout << "IBM calculation: "
<< c++ << " of " << np
<< " \r";
cout.flush();
}
else
{
cout << "IBS(g) calculation: "
<< c++ << " of " << np
<< " \r";
cout.flush();
}
c2+=100;
}
else
++c;
Z IBSg;
if (par::cluster_missing)
calcGenomeIBM(sample[i1],sample[i2]);
else
{
// Also calculate IBM as a constraint?
if (par::cluster_ibm_constraint)
{
calcGenomeIBM(sample[i1],sample[i2]);
if ( dst < par::cluster_ibm_constraint_value )
pairable[i1][i2] = pairable[i2][i1] = false;
}
// IBS distance (stored in dst)
IBSg = calcGenomeIBS(sample[i1],sample[i2]);
}
mdist[i2][i1]=dst;
//////////////////////////
// Is this pair pairable?
if (pv < par::merge_p && realnum(pv))
{
// record pair as unpairable
pairable[i1][i2] = pairable[i2][i1] = false;
// record for both individuals a IBS-based mismatch
prop_sig_diff[i1]++;
prop_sig_diff[i2]++;
}
}
}
else // ... read IBS information from .genome file
{
checkFileExists(par::ibd_file);
if ( par::ibd_read_minimal )
printLOG("Reading IBS estimates (minimal format) from [ "
+par::ibd_file+" ] \n");
else
printLOG("Reading genome-wide IBS estimates from [ "
+par::ibd_file+" ] \n");
if ( compressed( par::ibd_file ) )
par::compress_genome = true;
ZInput ZINC( par::ibd_file , par::compress_genome );
map<string,int> mperson;
for (int i=0; i<n; i++)
mperson.insert(make_pair( sample[i]->fid+"_"+sample[i]->iid , i ));
map<Individual*,int> mcode;
for (int i=0; i<n; i++)
mcode.insert(make_pair( sample[i] , i ));
vector<Individual*> peeps;
if ( par::ibd_read_minimal )
{
// read in list of people here
while ( 1 )
{
vector<string> ids = ZINC.tokenizeLine();
if ( ids.size() != 2 )
{
string emsg = "Problem with line in [ " + par::ibd_file + " ]\n";
for (int i=0;i<ids.size();i++)
emsg += ids[i] + " ";
error(emsg);
}
string fid = ids[0];
string iid = ids[1];
if ( fid == "__END" )
break;
// Find this person
string pcode = fid+"_"+iid;
map<string,int>::iterator p = mperson.find(pcode);
// Add NULL if this person actually not in
// the current file -- in this case, they
// will be ignored -- but remember we have
// to check for NULLs below and skip those
// numbers in that case...
if ( p == mperson.end() )
peeps.push_back( NULL );
else
peeps.push_back( sample[p->second] );
// Just in case we have a malformed file
if ( ZINC.endOfFile() )
error("Problem with premature stop in file [ " + par::ibd_file + " ]\n");
}
//////////////////////////////////////////////////////
// Now read the actual IBS/PPC values for these peeps
if ( peeps.size() != sample.size() )
printLOG("Warning -- a different number of people in .genome.min that dataset\n");
int size = peeps.size();
int p1 = 0, p2 = 1;
while ( 1 )
{
double mydst, pv, ibd;
vector<string> val = ZINC.tokenizeLine();
if ( ZINC.endOfFile() )
{
// Check that p1,p2 counts are as should be...
break;
}
if ( val.size() != 3 )
{
string emsg = "Problem with line in [ " + par::ibd_file + " ]\n";
for (int i=0;i<val.size();i++)
emsg += val[i] + " ";
error(emsg);
}
if ( !from_string<double>( mydst, val[0], std::dec ) )
mydst = 0;
if ( !from_string<double>( pv, val[1], std::dec ) )
pv = 0;
if ( !from_string<double>( ibd, val[2], std::dec ) )
ibd = 0;
Individual * person1 = peeps[p1];
Individual * person2 = peeps[p2];
int pn1 = mcode.find( person1 )->second;
int pn2 = mcode.find( person2 )->second;
if ( person1 == NULL || person2 == NULL || person1 == person2 )
{
// Advance to next pair
++p2;
if ( p2 == n )
{
++p1;
p2=p1+1;
}
if ( p1==n )
break;
continue;
}
// cout << "found " << pn1 << " and " << pn2 << " is "
// << person1->fid << " " << person1->iid << " x "
// << person2->fid << " " << person2->iid << "\t"
// << " with "
// << mydst << " " << pv << "\n";
// Record IBS distance
if ( pn1 > pn2 )
mdist[pn1][pn2] = mydst;
else
mdist[pn2][pn1] = mydst;
//////////////////////////
// Is this pair pairable?
if (pv < par::merge_p && realnum(pv))
{
// record pair as unpairable
pairable[pn1][pn2] = false;
pairable[pn2][pn1] = false;
// record for both individuals a IBS-based mismatch
prop_sig_diff[pn1]++;
prop_sig_diff[pn2]++;
}
// Also calculate IBM as a constraint?
if (par::cluster_ibm_constraint)
{
calcGenomeIBM(person1,person2);
if ( dst < par::cluster_ibm_constraint_value )
{
pairable[pn1][pn2] = false;
pairable[pn2][pn1] = false;
}
}
// Advance to next peep-pair
++p2;
if ( p2 == n )
{
++p1;
p2=p1+1;
}
// Finished?
if ( p1==n )
break;
}
}
else
{
// Read in .genome file in verbose mode
// We only want FID1,IID1,FID2,IID2 (always first four)
// DST and PPC
// Get field codes from header
int ppc_code = -1;
int dst_code = -1;
int col_length = 0;
double mydst;
vector<string> tokens = ZINC.tokenizeLine();
col_length = tokens.size();
if ( tokens.size() < 4 ||
tokens[0] != "FID1" ||
tokens[1] != "IID1" ||
tokens[2] != "FID2" ||
tokens[3] != "IID2" )
error("Problem with header row of .genome file");
for ( int i = 4; i<tokens.size(); i++)
{
if ( tokens[i] == "PPC" )
ppc_code = i;
if ( tokens[i] == "P" )
ppc_code = i;
if ( tokens[i] == "DST" )
dst_code = i;
}
if ( ppc_code == -1 || dst_code == -1 )
error("Could not find PPC or DST fields in .genome file");
// Read each pair at a time
while ( ! ZINC.endOfFile() )
{
vector<string> tokens = ZINC.tokenizeLine();
if ( tokens.size() == 0 )
continue;
if ( col_length != tokens.size() )
{
string strmsg = "";
for (int i=0;i<tokens.size();i++)
strmsg += tokens[i] + " ";
error("Problem reading line in .genome file:\n"+strmsg+"\n");
}
string fid1 = tokens[0];
string iid1 = tokens[1];
string fid2 = tokens[2];
string iid2 = tokens[3];
string ipv = tokens[ppc_code];
string idst = tokens[dst_code];
// Skip any blank rows, or additional header rows
if (fid1=="") continue;
if (fid1=="FID1") continue;
// if ( ! ( from_string<double>( ibs0 , i0 , std::dec) &&
// from_string<double>( ibs1 , i1 , std::dec) &&
// from_string<double>( ibs2 , i2 , std::dec) ) )
// {
// error("Problem with line in .genome file, IBS estimates: \n"
// +i0+" "+i1+" "+i2+" "+ipv+"\n");
// }
if ( ! from_string<double>( mydst , idst , std::dec) )
mydst = 0;
if ( ! from_string<double>( pv , ipv , std::dec) )
pv = 1;
// Calculate proportion IBS matching
// if (par::cluster_euclidean)
// mydst = (ibs2*2+ibs1*0.5)/(ibs2*2+ibs1+ibs0);
// else
// mydst = (ibs2+ibs1*0.5)/(ibs2+ibs1+ibs0);
map<string,int>::iterator person1 = mperson.find(fid1+"_"+iid1);
map<string,int>::iterator person2 = mperson.find(fid2+"_"+iid2);
if ( person1 == mperson.end() || person2 == mperson.end() || person1 == person2 )
continue;
// Record IBS distance
if ( person1->second > person2->second )
mdist[person1->second][person2->second] = mydst;
else
mdist[person2->second][person1->second] = mydst;
//////////////////////////
// Is this pair pairable?
if (pv < par::merge_p && pv==pv)
{
// record pair as unpairable
pairable[person1->second][person2->second] = false;
pairable[person2->second][person1->second] = false;
// record for both individuals a IBS-based mismatch
prop_sig_diff[person1->second]++;
prop_sig_diff[person2->second]++;
}
// Also calculate IBM as a constraint?
if (par::cluster_ibm_constraint)
{
calcGenomeIBM(sample[person1->second],sample[person2->second]);
if ( dst < par::cluster_ibm_constraint_value )
{
pairable[person1->second][person2->second] = false;
pairable[person2->second][person1->second] = false;
}
}
} // Read next line in .genome
}
ZINC.close();
/////////////////////////////////////////////
// Check that every pair in the dataset has
// actually been assigned a value -- i.e. check
// for 0 IBS codes, etc.
}
///////////////////////////////////
// IBS permutation test
if ( par::ibs_test )
{
// If we were called by permutationIBSTest(),
// now it is time to return
return;
}
///////////////////////////////////
// Display matrix of IBS distances
if (par::matrix)
{
string f;
if (par::cluster_missing)
f = par::output_file_name+ ".mdist.missing";
else if (par::distance_matrix)
f = par::output_file_name+ ".mdist";
else
f = par::output_file_name+ ".mibs";
if (!par::cluster_missing)
{
if (par::distance_matrix)
printLOG("Writing IBS distance matrix to [ "+f + " ]\n");
else
printLOG("Writing IBS similarity matrix to [ "+f + " ]\n");
}
else
printLOG("Writing IBM distance matrix to [ "+f + " ]\n");
ofstream MAT(f.c_str(),ios::out);
MAT.clear();
for (int i=0;i<mdist.size();i++)
{
for (int j=0;j<mdist.size();j++)
{
if ( par::distance_matrix )
{
// Distances
if (i>j)
MAT << 1 - mdist[i][j] << " ";
else if (i==j)
MAT << 0 << " ";
else
MAT << 1 - mdist[j][i] << " ";
}
else
{
// Similarities
if (i>j)
MAT << mdist[i][j] << " ";
else if (i==j)
MAT << 1 << " ";
else
MAT << mdist[j][i] << " ";
}
}
MAT << "\n";
}
MAT.close();
}
////////////////////////////////////
// Determine how many pairable pairs
// we have now
if (!par::cluster_missing)
{
int paircount = 0;
for (int i=0; i<n-1; i++)
for (int j=i+1; j<n; j++)
if (pairable[i][j]) paircount++;
printLOG("Of these, "+int2str(paircount)+" are pairable based on constraints\n");
}
//////////////////////////
// Outlier detection
if (par::outlier_detection)
{
printLOG("Writing individual neighbour/outlier statatistics to [ " +
par::output_file_name + ".nearest ]\n");
vector<vector<double> > min_dst(n);
vector<vector<double> > zmin_dst(n);
vector<vector<Individual*> > min_ind(n);
if (par::max_neighbour > n-1)
error("Nearest neighbour range specified as [ "+int2str(par::max_neighbour)
+" ] but only [ "+int2str(n)+" ] individuals in sample.");
for (int k=par::min_neighbour;k<=par::max_neighbour;k++)
{
// Consider each person
for (int i=0;i<n;i++)
{
vector<Neighbour> ibs(n-1);
int c=0;
for (int j=0;j<n;j++)
if (i!=j)
{
if ( i>j )
ibs[c].dist = mdist[i][j];
else
ibs[c].dist = mdist[j][i];
ibs[c].neighbour = sample[j];
c++;
}
sort(ibs.begin(),ibs.end());
min_dst[i].push_back(ibs[ibs.size() - k].dist);
min_ind[i].push_back(ibs[ibs.size() - k].neighbour);
}
// Calculate mean and variance of min_dst to
// give Z-scores
double mean = 0;
double var = 0;
for (int i=0; i<n; i++)
mean += min_dst[i][min_dst[i].size()-1];
mean /= (double)n;
for (int i=0; i<n; i++)
var += (min_dst[i][min_dst[i].size()-1]-mean)*(min_dst[i][min_dst[i].size()-1]-mean);
var /= (double)(n-1);
for (int i=0; i<n; i++)
zmin_dst[i].push_back( ( min_dst[i][min_dst[i].size()-1] - mean ) / sqrt(var) ) ;
}
// Second measure: based on significance test
// Proportion of rest of sample with whom significant difference at 'pmerge' threshold
// pv might be NaN, but only if very small # of markers is used -- ignore, as
// all values will be meaningless in any case
if (!par::cluster_missing)
for (int i=0;i<n;i++)
prop_sig_diff[i] /= (double)(n-1);
// And output to a file
ofstream MD((par::output_file_name+".nearest").c_str(),ios::out);
MD.clear();
MD.precision(4);
MD << setw(12) << "FID" << " "
<< setw(12) << "IID" << " "
<< setw(6) << "NN" << " "
<< setw(12) << "MIN_DST" << " "
<< setw(12) << "Z" << " "
<< setw(12) << "FID2" << " "
<< setw(12) << "IID2" << " ";
if (!par::cluster_missing)
MD << setw(12) << "PROP_DIFF" << " ";
MD << "\n";
for (int i=0; i<n; i++)
for (int k=0;k<min_dst[0].size();k++)
{
MD << setw(12) << sample[i]->fid << " "
<< setw(12) << sample[i]->iid << " "
<< setw(6) << par::min_neighbour+k << " "
<< setw(12) << min_dst[i][k] << " "
<< setw(12) << zmin_dst[i][k] << " "
<< setw(12) << min_ind[i][k]->fid << " "
<< setw(12) << min_ind[i][k]->iid << " ";
if (!par::cluster_missing)
MD << setw(12) << prop_sig_diff[i] << " ";
MD << "\n";
}
MD.close();
}
//////////////////////////
// Cluster analysis
if ( par::cluster )
{
int c=1;
bool done=false;
// Matrix of solutions
vector< vector<int> > sol(ni);
for (int i=0;i<ni;i++) sol[i].resize(ni);
vector<double> hist(1);
// Build solution
for (int i=0; i<cl.size(); i++)
for (int j=0; j<cl[i].size(); j++)
sol[cl[i][j]][0] = i;
printLOG("Writing cluster progress to [ "+par::output_file_name + ".cluster0 ]\n");
ofstream CLST((par::output_file_name+".cluster0").c_str(),ios::out);
CLST.clear();
while(!done)
{
double dmin = -999;
int imin=-1;
int jmin=-1;
// 1. Find min/max distance between pairable clusters
for (int i=0; i<cl.size()-1; i++)
for (int j=i+1; j<cl.size(); j++)
{
// Cluster on IBS: group average link or complete linkage?
double d = par::cluster_group_avg ? groupAvgLink(mdist,cl[i],cl[j]) : cldist(mdist,cl[i],cl[j]);
// Are these individuals/clusters more similar AND pairable?
if ( d>dmin && pairable_cluster(pairable,cl[i],cl[j]) )
{
// And will the max cluster size requirement be fulfilled?
if (par::max_cluster_size==0 ||
(( cl[i].size()+cl[j].size()) <= par::max_cluster_size) )
{
// And will the basic phenotypic matching requirement be fulfilled?
if ( (!par::cluster_on_phenotype)
|| (!homogeneous_clusters((*this),cl[i],cl[j])))
{
// What about the --mcc clustering
if ( (!par::cluster_on_mcc) || spec_clusters( (*this),cl[i],cl[j]) )