-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathngsRelate.cpp
More file actions
1655 lines (1417 loc) · 49.7 KB
/
ngsRelate.cpp
File metadata and controls
1655 lines (1417 loc) · 49.7 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
/*
NgsRelateV2
http://www.popgen.dk/software/
https://github.com/ANGSD/NgsRelate/
*/
#include <vector>
#include <cstring>
#include <zlib.h>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cassert>
#include <map>
#include <libgen.h> // basename
#include <pthread.h> // threading
#include <time.h> // time
#include <limits>
#include <string>
#include <algorithm> //shuffle
#include <unistd.h>
#include "filereaders.h"
#ifdef __WITH_BCF__
#include "vcf.h"
#endif
double total_sites;
int FINISHED=0;
std::vector<FILE *> spillfiles;
std::vector<char *> spillfilesnames;
typedef struct{
int a;
int b;//<-if inbreding a=b
char *res;//<-results as char*
}mypair;
std::vector<mypair> mp;
bool myfunction (mypair i,mypair j) { return i.a==j.a?i.b<j.b:i.a<j.a;}
//this is as close to the bound we will allow
double TINY=1e-8;
double p10[2]={1-TINY,TINY};
double p01[2]={TINY,1-TINY};
int num_threads = 4;
char *freqname=NULL;
char *gname=NULL;
char *beaglefile=NULL;
int maxIter =10000;
double tole =1e-8;
int n=-1;
int nBootstrap = 0;//counter for howmany bootstraps
int seed=std::numeric_limits<int>::max();
int ntimes =1;
int model =1;
int gc =0;
double errate = 0.005;
int pair1 =-1;
int pair2 =-1;
int nind =-1;
int nsites_nofreqfile = 0;
size_t overall_number_of_sites = 0;
int do_2dsfs_only = 0;
int do_inbred=0;
int do_simple=0;
int switchMaf = 0;
double minMaf =0.05;
int hasDef = 0;
double ttol=1e-6;
char *vcf_format_field = strdup("PL"); // can take PL or GT
char *vcf_allele_field = strdup("AFngsrelate"); // can take any tag value e.g. AF AF1 etc
std::vector<char *> ids;
float emTole=1e-12;
// https://en.cppreference.com/w/c/numeric/math/isnan
bool is_nan(double x) { return x != x; }
double emFrequency_from_data(double *like,int numInds, int iter,double start){
float W0;
float W1;
float W2;
// fprintf(stderr,"start=%f\n",start);
float p=(float)start;
float temp_p=(float)start;
double accu=0.00001;
double accu2=0;
float sum;
int it=0;
for(it=0;it<iter;it++){
sum=0;
for(int i=0;i<numInds;i++){
W0=like[i*3+0]*pow(1-p,2);
W1=like[i*3+1]*2*p*(1-p);
W2=like[i*3+2]*(pow(p,2));
sum+=(W1+2*W2)/(2*(W0+W1+W2));
if(std::isnan(sum))
fprintf(stderr,"PRE[%d]:gls:(%f,%f,%f) W(%f,%f,%f) sum=%f\n",i,like[i*3],like[i*3+1],like[i*3+2],W0,W1,W2,sum);
}
p=sum/numInds;
if((p-temp_p<accu&&temp_p-p<accu)||(p/temp_p<1+accu2&&p/temp_p>1-accu2))
break;
temp_p=p;
}
if(std::isnan(p)){
fprintf(stderr,"[%s] caught nan will not exit\n",__FUNCTION__);
fprintf(stderr,"Like (3*nInd). nInd=%d\n",numInds);
//print_array(stderr,like,3*numInds);
fprintf(stderr,"keepList (nInd)\n");
//print_array(stderr,keep,numInds);
fprintf(stderr,"used Like (3*length(keep))=%d\n",numInds);
for(int ii=0;1&&ii<numInds;ii++){
for(int gg=0;gg<3;gg++)
fprintf(stderr,"%f\t",like[ii*3+gg]);
fprintf(stderr,"\n");
}
sum=0;
for(int i=0;i<numInds;i++){
W0=like[i*3+0]*pow(1-p,2);
W1=like[i*3+1]*2*p*(1-p);
W2=like[i*3+2]*(pow(p,2));
sum+=(W1+2*W2)/(2*(W0+W1+W2));
fprintf(stderr,"[%s.%s():%d] p=%f W %f\t%f\t%f sum=%f like: %f\n",__FILE__,__FUNCTION__,__LINE__,p,W0,W1,W2,sum,like[i*3+2]*pow(1-p,2));
break;
}
p=-999;
assert(p!=999);
return p;
}
return(p);
}
double access_genotype(double **gls, const int & site, const int & indi, const int & geno){
return gls[site][indi * 3 + geno];
}
void normalize(double *tmp,int len){
double s=0;
for(int i=0;i<len;i++)
s += tmp[i];
for(int i=0;i<len;i++)
tmp[i] /=s;
}
void sample48(double *ary,int dim){
for(int i=0;i<dim;i++)
ary[i] =TINY+drand48()*(1-2*TINY);
normalize(ary,dim);
}
double loglike(double *p,double **emis,int len,int dim){
double ret =0;
for(int i=0;i<len;i++){
double tmp = 0;
for(int j=0;j<dim;j++)
tmp += p[j]*emis[i][j];
ret += log(tmp);
}
return ret;
}
void emStep(double *pre,double **emis,double *post,int len,int len2){
for(int i=0;i<len2;i++){
if(pre[i]<0||pre[i]>1||is_nan(pre[i])){
fprintf(stderr,"Problem with guess in emStep: ");
for(int j=0;j<len2;j++)
fprintf(stderr," %f ",pre[j]);
fprintf(stderr,"\n");
exit(0);
}
}
double inner[len2];
for(int x=0;x<len2;x++){
post[x] =0.0;
}
for(int i=0;i<len;i++){
for(int x=0;x<len2;x++){
inner[x] = pre[x]*emis[i][x];
}
normalize(inner,len2);
#ifdef DB_MP
for(int x=0;x<len2;x++){
if(is_nan(inner[x])){
fprintf(stderr, "pre: %d ", i);
for(int x=0;x<len2;x++){
fprintf(stderr, "%f ", pre[x]);
}
fprintf(stderr, "\n");
fprintf(stderr, "emis: %d ", i);
for(int x=0;x<len2;x++){
fprintf(stderr, "%f ", emis[i][x]);
}
fprintf(stderr, "\n");
fprintf(stderr, "site: %d ", i);
for(int x=0;x<len2;x++){
fprintf(stderr, "%f ", inner[x]);
}
fprintf(stderr, "\n");
exit(0);
}
}
#endif
for(int x=0;x<len2;x++){
post[x] += inner[x];
#ifdef DB_MP
if(is_nan(post[x])){
fprintf(stderr, "%d %f\n", i, inner[x]);
exit(0);
}
#endif
}
}
#ifdef DB_MP
fprintf(stderr, "post->sites: %d, params: %d ", len, len2);
for(int i=0; i<len2; i++){
fprintf(stderr, " %f", post[i]);
}
fprintf(stderr, "\n");
#endif
normalize(post,len2);
}
void minus(double * fst,double * sec,double * res,int dim){
for(int i=0;i<dim;i++)
res[i] = fst[i]-sec[i];
}
double sumSquare(double * mat,int dim){
double tmp=0;
for(size_t i=0;i<dim;i++){
tmp += mat[i]*mat[i];
}
return tmp;
}
int emAccel(double *F,double **emis,double *F_new,int len, int & niter,int dim){
// maybe these should be usersettable?
double stepMin =1;
double stepMax0 = 1;
static double stepMax=stepMax0;
double mstep=4;
// double objfnInc=1;
#ifdef DB_MP
fprintf(stderr, "iter: %d input: ", niter);
for(int i=0; i<dim; i++){
fprintf(stderr, " %f", F[i]);
}
fprintf(stderr, "\n");
#endif
double F_em1[dim];
double F_diff1[dim];
double F_em2[dim];
double F_diff2[dim];
double F_diff3[dim];
double F_tmp[dim];
niter++;
emStep(F, emis, F_em1, len,dim);
// stayin(F_em1);
#ifdef DB_MP
fprintf(stderr, "iter: %d emstep1: ", niter);
for(int i=0; i<dim; i++){
fprintf(stderr, " %f", F_em1[i]);
}
fprintf(stderr, "\n");
#endif
minus(F_em1, F, F_diff1,dim);
double sr2 = sumSquare(F_diff1,dim);
if(sqrt(sr2)<ttol){
#ifdef DB_MP
fprintf(stderr,"sr2 break1: %e\n", sqrt(sr2));
#endif
if (niter==2){
// This is required as breaking in first round will result in empty F_new
// copying F_em1 to F_new every time literally disables accelerated.
for(int i=0;i<dim;i++)
F_new[i] = F_em1[i];
}
for(int i=0;0&&i<dim;i++)
F_new[i] = F_em1[i];
return 1;
}
niter++;
emStep(F_em1, emis, F_em2, len,dim);
minus(F_em2, F_em1, F_diff2,dim);
#ifdef DB_MP
fprintf(stderr, "iter: %d emstep2: ", niter);
for(int i=0; i<dim; i++){
fprintf(stderr, " %f", F_em2[i]);
}
fprintf(stderr, "\n");
#endif
double sq2 = sumSquare(F_diff2,dim);
if(sqrt(sq2)<ttol){
#ifdef DB_MP
fprintf(stderr,"sr2 break2: %e\n", sqrt(sr2));
#endif
if (niter==3){
// This is required as breaking in first round will result in empty F_new
// copying F_em1 to F_new every time literally disables accelerated.
for(int i=0;i<dim;i++)
F_new[i] = F_em2[i];
}
for(int i=0;0&&i<dim;i++)
F_new[i] = F_em2[i];
return 1;
}
minus(F_diff2,F_diff1, F_diff3,dim);
double sv2 = sumSquare(F_diff3,dim);
double alpha = sqrt(sr2/sv2);
alpha = std::max(stepMin,std::min(stepMax,alpha));
for(size_t i=0;i<dim;i++){
// F_new[i] = std::min(1-ttol, std::max(ttol,F[i]+2*alpha*F_diff1[i]+alpha*alpha*F_diff3[i]));
F_new[i] = F[i]+2*alpha*F_diff1[i]+alpha*alpha*F_diff3[i];
}
int outofparspace =0;
for(int i=0;i<dim;i++){
if(F_new[i]<0||F_new[i]>1){
outofparspace++;
// break;
}
}
if(outofparspace){
#ifdef DB_MP
fprintf(stderr, "iter: %d outofspace: ", niter);
for(int i=0; i<dim; i++){
fprintf(stderr, " %f", F[i]);
}
fprintf(stderr, "\n");
#endif
for(int i=0;i<dim;i++)
F_new[i] = F_em2[i];
}
if (fabs(alpha - 1) > 0.01){
niter++;
emStep(F_new,emis,F_tmp,len,dim);
for(int i=0;i<dim;i++)
std::swap(F_new[i],F_tmp[i]);
}
if ((alpha - stepMax) > -0.001) {
stepMax = mstep*stepMax;
}
return 1;
}
//std em along with control logic for breaking
int em(double *sfs,double **emis, int len, int dim){
int niter = 0;
double oldLik,lik;
// sample48(sfs,dim);//<- moved to outside
oldLik = loglike(sfs,emis,len,dim);
double tmp[dim];
int it;
for(it=0;niter<maxIter;it++) {
niter++;
if(model==0)
emStep(sfs,emis,tmp,len,dim);
else
emAccel(sfs,emis,tmp,len, niter,dim);
for(int i=0;i<dim;i++)
sfs[i]= tmp[i];
lik = loglike(sfs,emis,len,dim);
if(fabs(lik-oldLik)<tole){
oldLik=lik;
break;
}
oldLik=lik;
}
return niter;
}
void emislike_2dsfs_gen(double **gls, double **emislike_2dsfs, int *keeplist, int & nkeep, int & ind1, int & ind2 ){
int i;
for(int x=0;x<nkeep;x++){
i = keeplist[x];
emislike_2dsfs[x][0] = access_genotype(gls, i, ind1, 0) * access_genotype(gls, i, ind2, 0);
emislike_2dsfs[x][1] = access_genotype(gls, i, ind1, 0) * access_genotype(gls, i, ind2, 1);
emislike_2dsfs[x][2] = access_genotype(gls, i, ind1, 0) * access_genotype(gls, i, ind2, 2);
emislike_2dsfs[x][3] = access_genotype(gls, i, ind1, 1) * access_genotype(gls, i, ind2, 0);
emislike_2dsfs[x][4] = access_genotype(gls, i, ind1, 1) * access_genotype(gls, i, ind2, 1);
emislike_2dsfs[x][5] = access_genotype(gls, i, ind1, 1) * access_genotype(gls, i, ind2, 2);
emislike_2dsfs[x][6] = access_genotype(gls, i, ind1, 2) * access_genotype(gls, i, ind2, 0);
emislike_2dsfs[x][7] = access_genotype(gls, i, ind1, 2) * access_genotype(gls, i, ind2, 1);
emislike_2dsfs[x][8] = access_genotype(gls, i, ind1, 2) * access_genotype(gls, i, ind2, 2);
#ifdef DB_EMIS
fprintf(stderr,"emis2dsfs[%d]:\t",x);
for(int j=0;j<9;j++)
fprintf(stderr,"%f ",emislike_2dsfs[x][j]);
fprintf(stderr,"\n");
#endif
}
}
void emission_ngsrelate9(std::vector<double> * freq, double **gls, double **emis, int *keeplist, int & nkeep, int & ind1, int & ind2 ){
// access_genotype(td->gls, i, td->a, 0);
int i;
for(int x=0;x<nkeep;x++){
i = keeplist[x];
double freqa=freq->at(i); // alternative allele frequency
double freqA=1-freqa;
// i == freqA == freq0
// j == freqa == freq1
// emis<- cbind(freq0,freq0^2,freq0^2, freq0^3,freq0^2,freq0^3, freq0^2,freq0^3,freq0^4)*gl1[1,]*gl2[1,]
// ##00&00
// G_real=(AA,AA)
double AAAA = access_genotype(gls, i, ind1, 0) * access_genotype(gls, i, ind2, 0);
emis[x][0] = pow(freqA, 4) * AAAA;
emis[x][1] = pow(freqA, 3) * AAAA;
emis[x][2] = pow(freqA, 2) * AAAA;
emis[x][3] = pow(freqA, 3) * AAAA;
emis[x][4] = pow(freqA, 2) * AAAA;
emis[x][5] = pow(freqA, 3) * AAAA;
emis[x][6] = pow(freqA, 2) * AAAA;
emis[x][7] = pow(freqA, 2) * AAAA;
emis[x][8] = freqA * AAAA;
// emis <- emis + cbind(freq1,freq1^2,freq1^2, freq1^3,freq1^2,freq1^3, freq1^2,freq1^3,freq1^4)*gl1[3,]*gl2[3,]
// ##11&11
// G_real=(aa,aa)
double aaaa = access_genotype(gls, i, ind1, 2) * access_genotype(gls, i, ind2, 2);
emis[x][0] += pow(freqa, 4) * aaaa;
emis[x][1] += pow(freqa, 3) * aaaa;
emis[x][2] += pow(freqa, 2) * aaaa;
emis[x][3] += pow(freqa, 3) * aaaa;
emis[x][4] += pow(freqa, 2) * aaaa;
emis[x][5] += pow(freqa, 3) * aaaa;
emis[x][6] += pow(freqa, 2) * aaaa;
emis[x][7] += pow(freqa, 2) * aaaa;
emis[x][8] += freqa * aaaa;
// emis <- emis + cbind(0,freq0*freq1,0, freq0*freq1^2,0,freq0^2*freq1 ,0,0,freq1^2*freq0^2)*gl1[1,]*gl2[3,]
// ##00&11
// G_real=(AA,aa)
double AAaa = access_genotype(gls, i, ind1, 0) * access_genotype(gls, i, ind2, 2);
emis[x][0] += pow(freqA, 2) * pow(freqa, 2) * AAaa;
emis[x][1] += 0;
emis[x][2] += 0;
emis[x][3] += pow(freqA, 2) * freqa * AAaa;
emis[x][4] += 0;
emis[x][5] += freqA * pow(freqa,2) * AAaa;
emis[x][6] += 0;
emis[x][7] += freqA * freqa * AAaa;
emis[x][8] += 0;
// emis <- emis + cbind(0,freq0*freq1,0, freq0^2*freq1,0,freq1^2*freq0, 0,0,freq1^2*freq0^2)*gl1[3,]*gl2[1,]
// ##11&00
// G_real=(aa,AA)
double aaAA = access_genotype(gls, i, ind1, 2) * access_genotype(gls, i, ind2, 0);
emis[x][0] += pow(freqA, 2) * pow(freqa, 2) * aaAA;
emis[x][1] += 0;
emis[x][2] += 0;
emis[x][3] += freqA * pow(freqa, 2) * aaAA;
emis[x][4] += 0;
emis[x][5] += pow(freqA, 2) * freqa * aaAA;
emis[x][6] += 0;
emis[x][7] += freqA * freqa * aaAA;
emis[x][8] += 0;
// emis <- emis + cbind(0,0,freq0*freq1, 2*freq0^2*freq1,0,0, 0,freq0^2*freq1,2*freq0^3*freq1)*gl1[1,]*gl2[2,]
// ##00&01
// G_real=(AA,Aa)
double AAAa = access_genotype(gls, i, ind1, 0) * access_genotype(gls, i, ind2, 1);
emis[x][0] += 2 * pow(freqA, 3) * freqa * AAAa;
emis[x][1] += pow(freqA, 2) * freqa * AAAa;
emis[x][2] += 0;
emis[x][3] += 0;
emis[x][4] += 0;
emis[x][5] += 2 * pow(freqA, 2) * freqa * AAAa;
emis[x][6] += freqA * freqa * AAAa;
emis[x][7] += 0;
emis[x][8] += 0;
// emis <- emis + cbind(0,0,freq0*freq1, 2*freq1^2*freq0,0,0, 0,freq1^2*freq0,2*freq1^3*freq0)*gl1[3,]*gl2[2,]
// ##11&01
// # G_real=(aa,Aa)
double aaAa = access_genotype(gls, i, ind1, 2) * access_genotype(gls, i, ind2, 1);
emis[x][0] += 2 * freqA * pow(freqa, 3) * aaAa;
emis[x][1] += freqA * pow(freqa, 2) * aaAa;
emis[x][2] += 0;
emis[x][3] += 0;
emis[x][4] += 0;
emis[x][5] += 2 * freqA * pow(freqa, 2) * aaAa;
emis[x][6] += freqA * freqa * aaAa;
emis[x][7] += 0;
emis[x][8] += 0;
// emis <- emis + cbind(0,0,0, 0,freq0*freq1,2*freq0^2*freq1, 0,freq0^2*freq1,2*freq0^3*freq1)*gl1[2,]*gl2[1,]
// ##01&00
// G_real=(Aa,AA)
double AaAA = access_genotype(gls, i, ind1, 1) * access_genotype(gls, i, ind2, 0);
emis[x][0] += 2 * pow(freqA, 3) * freqa * AaAA;
emis[x][1] += pow(freqA, 2) * freqa * AaAA;
emis[x][2] += 0;
emis[x][3] += 2 * pow(freqA, 2) * freqa * AaAA;
emis[x][4] += freqA * freqa * AaAA;
emis[x][5] += 0;
emis[x][6] += 0;
emis[x][7] += 0;
emis[x][8] += 0;
// emis <- emis + cbind(0,0,0, 0,freq0*freq1,2*freq1^2*freq0, 0,freq1^2*freq0,2*freq1^3*freq0)*gl1[2,]*gl2[3,]
// ##01&11
// G_real=(Aa,aa)
double Aaaa = access_genotype(gls, i, ind1, 1) * access_genotype(gls, i, ind2, 2);
emis[x][0] += 2 * freqA * pow(freqa, 3) * Aaaa;
emis[x][1] += freqA * pow(freqa, 2) * Aaaa;
emis[x][2] += 0;
emis[x][3] += 2 * freqA * pow(freqa, 2) * Aaaa;
emis[x][4] += freqA * freqa * Aaaa;
emis[x][5] += 0;
emis[x][6] += 0;
emis[x][7] += 0;
emis[x][8] += 0;
// emis <- emis + cbind(0,0,0, 0,0,0, 2*freq0*freq1,freq1*freq0,4*freq1^2*freq0^2)*gl1[2,]*gl2[2,]
// ##01&01 S7
// G_real=(Aa,Aa)
double AaAa = access_genotype(gls, i, ind1, 1) * access_genotype(gls, i, ind2, 1);
emis[x][0] += 4 * pow(freqA, 2) * pow(freqa, 2) * AaAa;
emis[x][1] += freqA * freqa * AaAa;
emis[x][2] += 2 * freqA * freqa * AaAa;
emis[x][3] += 0;
emis[x][4] += 0;
emis[x][5] += 0;
emis[x][6] += 0;
emis[x][7] += 0;
emis[x][8] += 0;
#ifdef myDEBUGemis9
double test =0;
for (int xx=0;xx<9;xx++){
test+=emis[x][xx];
}
if(test<1e-30){
fprintf(stderr, "%d %d g1:", i, x);
for (int geno=0; geno<3; geno++)
fprintf(stderr, " %f", access_genotype(gls, i, ind1, geno));
fprintf(stderr, " g2:");
for (int geno=0; geno<3; geno++)
fprintf(stderr, " %f", access_genotype(gls, i, ind2, geno));
fprintf(stderr,"\n");
}
#endif
}
}
void emission_ngs_inbred(std::vector<double> * freq, double **gls, double **emis, int *keeplist, int & nkeep, int & ind1){
int i;
double AA, Aa, aa, freqa, freqA;
for(int x=0;x<nkeep;x++){
i = keeplist[x];
freqa=freq->at(i); // alternative allele frequency
freqA=1-freqa;
AA = access_genotype(gls, i, ind1, 0);
Aa = access_genotype(gls, i, ind1, 1);
aa = access_genotype(gls, i, ind1, 2);
// G_real=(AA)
emis[x][0] = pow(freqA,2)*AA;
emis[x][1] = freqA*AA;
// G_real=(Aa)
emis[x][0] += 2*freqa*freqA*Aa;
emis[x][1] += 0;
// G_real=(aa)
emis[x][0] += pow(freqa,2)*aa;
emis[x][1] += freqa*aa;
}
}
void print_info(FILE *fp){
fprintf(fp, "\n");
fprintf(fp, "Usage main analyses: ./ngsrelate [options] \n");
fprintf(fp, "Options:\n");
fprintf(fp, " -f <filename> Name of file with frequencies\n");
fprintf(fp, " -O <filename> Output filename\n");
fprintf(fp, " -L <INT> Number of genomic sites. Must be provided if -f (allele frequency file) is NOT provided \n");
fprintf(fp, " -m <INTEGER> model 0=normalEM 1=acceleratedEM\n");
fprintf(fp, " -i <UINTEGER> Maximum number of EM iterations\n");
fprintf(fp, " -t <FLOAT> Tolerance for breaking EM\n");
fprintf(fp, " -r <FLOAT> Seed for rand\n");
fprintf(fp, " -R <chr:from-to> Region for analysis (only for bcf)\n");
fprintf(fp, " -g gfile Name of glf (compressed binary) file\n");
fprintf(fp, " -G gfile Name of beagle (compressed) file\n");
fprintf(fp, " -p <INT> threads (default 4)\n");
fprintf(fp, " -c <INT> Should call genotypes instead?\n");
fprintf(fp, " -s <INT> Should you swich the freq with 1-freq?\n");
fprintf(fp, " -F <INT> Estimate inbreeding instead of estimating the nine jacquard coefficients\n");
fprintf(fp, " -o <INT> estimating the 3 jacquard coefficient, assumming no inbreeding\n");
fprintf(fp, " -v <INT> Verbose. print like per iteration\n");
fprintf(fp, " -e <FLOAT> Errorrates when calling genotypes?\n");
fprintf(fp, " -a <INT> First individual used for analysis? (zero offset)\n");
fprintf(fp, " -b <INT> Second individual used for analysis? (zero offset)\n");
fprintf(fp, " -B <INT> Number of bootstrap replicates for (only for single pairs)\n");
fprintf(fp, " -N <INT> How many times to start each pair with random seed?\n");
fprintf(fp, " -n <INT> Number of samples in glf.gz\n");
fprintf(fp, " -l <FLOAT> minMaf or 1-Maf filter (default: 0.05)\n");
fprintf(fp, " -z <INT> Name of file with IDs (optional)\n");
fprintf(fp, " -T <STRING> For -h vcf use PL (default) or GT tag\n");
fprintf(fp, " -A <STRING> For -h vcf use allele frequency TAG e.g. AFngsrelate (default)\n");
fprintf(fp, " -P <filename> plink name of the binary plink file (excluding the .bed)\n");
fprintf(fp, "\n");
fprintf(fp,"Or\n ./ngsrelate extract_freq_bim pos.glf.gz plink.bim plink.freq\n");
fprintf(fp,"Or\n ./ngsrelate extract_freq .mafs.gz .pos.glf.gz [-rmTrans]\n");
#ifdef __WITH_BCF__
fprintf(fp,"Or\n ./ngsrelate -h my.bcf [DEVELOPMENT ONLY]\n");
#endif
exit(0);
}
int is_missing(double *ary){
if(fabs(ary[0] - ary[1])<1e-6 && fabs(ary[0] - ary[2])<1e-6 && fabs(ary[1] - ary[2])<1e-6)
return 1;
else if(is_nan(ary[0]) || is_nan(ary[1]) || is_nan(ary[2]))
return 1;
else
return 0;
}
int is_missing_old(double *ary){
if(ary[0]==ary[1]&&ary[0]==ary[2]&&ary[1]==ary[2])
return 1;
else
return 0;
}
void callgenotypesEps(double **gls,int nsites,int nind,double eps){
double g00 = (1-eps)*(1-eps);
double g01 = 2*(1-eps)*eps;
double g02 = eps*eps;
double g10 = (1-eps)*eps;
double g11 = (1-eps)*(1-eps)+eps*eps;
for(int off=0;off<nind;off++){
for(int s=0;s<nsites;s++){
if(!is_missing(&gls[s][off*3])){
int whmax=0;
for(int i=1;i<3;i++)
if(gls[s][off*3+i]>gls[s][off*3+whmax])
whmax=i;
if(whmax==0){
gls[s][off*3+0] = g00;
gls[s][off*3+1] = g01;
gls[s][off*3+2] = g02;
}else if(whmax==1){
gls[s][off*3+0]=gls[s][off*3+2]=g10;
gls[s][off*3+1]=g11;
}else if(whmax==2){
gls[s][off*3+0] = g02;
gls[s][off*3+1] = g01;
gls[s][off*3+2] = g00;
}else{
assert(0!=1);
}
}else
gls[s][off*3+0]=gls[s][off*3+1]=gls[s][off*3+2]=1;//how should we treat missing in the case of called genotypes?
}
}
}
void callgenotypesHwe(double **gls,int nsites,int nind,std::vector<double> freq){
for(int off=0;off<nind;off++){
for(int s=0;s<nsites;s++){
gls[s][3*off+0] *= freq[s]*freq[s];
gls[s][3*off+1] *= (1-freq[s])*freq[s];
gls[s][3*off+2] *= (1-freq[s])*(1-freq[s]);
int whmax=0;
for(int i=1;i<3;i++)
if(gls[s][3*off+i]>gls[s][3*off+whmax])
whmax=i;
for(int i=0;i<3;i++)
gls[s][3*off+i] = 0;
gls[s][3*off+whmax]=1;
}
}
}
struct worker_args_t {
int thread_id, nkeep, a,b, niter, best, niter_2dsfs;
double **gls;
std::vector<double> * freq;
size_t nsites;
double ll, bestll, ll_2dsfs;
double pars[9], pars_2dsfs[9];
int *keeplist;
double **emis;
int *bootindex;
worker_args_t(int & id_a, int & id_b, std::vector<double> * f, double ** gls_arg, size_t & s ){
a=id_a;
b=id_b;
nkeep=0;
best=0;
bestll=0.0;
freq = f;
gls=gls_arg;
nsites = s;
bootindex =NULL;
keeplist = new int[nsites];
emis = new double*[s];
if(nBootstrap>0)
bootindex = new int[nsites];
for(int i=0;i<s;i++)
emis[i] = new double[9];//<- will hold, 2dsfs,F and 9jacq emissions depending on context
}
~worker_args_t(){
for(int i=0;i<nsites;i++)
delete [] emis[i];
delete [] emis;
delete [] keeplist;
delete [] bootindex;
}
};
typedef struct worker_args_t worker_args;
// function will update pk_keeplist and return the number of sites that should be retained for analysis
int populate_keeplist(int pk_a,int pk_b,int pk_nsites,double **pk_gls,int pk_minmaf,std::vector<double> *pk_freq,int *pk_keeplist,int *tmp){//last is workspace to avoid allocation and deallocation;
int *keeplist = pk_keeplist;
int nkeep=0;
for (size_t i = 0; i < pk_nsites; i++) {
if(is_missing(&pk_gls[i][3*pk_a]))
continue;
if(is_missing(&pk_gls[i][3*pk_b]))
continue;
// removing minor allele frequencies
// if ( (!do_2dsfs_only) &&
// ((*pk_freq)[i] < minMaf || (1 - (*pk_freq)[i] < minMaf)))
// continue;
if ((*pk_freq)[i] < minMaf || (1 - (*pk_freq)[i] < minMaf))
continue;
#ifdef DB_GL
for (int x=0; x<3;x++)
fprintf(stderr, "%lu %f %f\n", i, pk_gls[i][3*pk_a+x], pk_gls[i][3*pk_b+x]);
#endif
keeplist[nkeep] = i;//dont forget
nkeep++;
}
if(tmp){//indicater for if we should bootstrap
for(int i=0;i<nkeep;i++){
tmp[i] = keeplist[lrand48() % nkeep];
// fprintf(stderr,"tmp:%d\n",tmp[i]);
}
std::sort(tmp,tmp+nkeep);
for(int i=0;i<nkeep;i++)
keeplist[i] = tmp[i];
}
return nkeep;
}
//this one does both inbreeding and the j9, the j3 is obtained by setting the j1-6 to zero
int analyse_jaq(double *pk_pars,std::vector<double> *pk_freq,double **pk_gls,int *pk_keeplist,double **pk_emis,int pk_nkeep,int pk_a,int pk_b,double &pk_ll,int &pk_best,double &pk_bestll,int &pk_niter, int ntimes){
double p100000000[9] = {1 - TINY, TINY / 8.0, TINY / 8.0,
TINY / 8.0, TINY / 8.0, TINY / 8.0,
TINY / 8.0, TINY / 8.0, TINY / 8.0};
double p010000000[9] = {TINY / 8.0, 1 - TINY, TINY / 8.0,
TINY / 8.0, TINY / 8.0, TINY / 8.0,
TINY / 8.0, TINY / 8.0, TINY / 8.0};
double p001000000[9] = {TINY / 8.0, TINY / 8.0, 1 - TINY,
TINY / 8.0, TINY / 8.0, TINY / 8.0,
TINY / 8.0, TINY / 8.0, TINY / 8.0};
double p000100000[9] = {TINY / 8.0, TINY / 8.0, TINY / 8.0,
1 - TINY, TINY / 8.0, TINY / 8.0,
TINY / 8.0, TINY / 8.0, TINY / 8.0};
double p000010000[9] = {TINY / 8.0, TINY / 8.0, TINY / 8.0,
TINY / 8.0, 1 - TINY, TINY / 8.0,
TINY / 8.0, TINY / 8.0, TINY / 8.0};
double p000001000[9] = {TINY / 8.0, TINY / 8.0, TINY / 8.0,
TINY / 8.0, TINY / 8.0, 1 - TINY,
TINY / 8.0, TINY / 8.0, TINY / 8.0};
double p000000100[9] = {TINY / 8.0, TINY / 8.0, TINY / 8.0,
TINY / 8.0, TINY / 8.0, TINY / 8.0,
1 - TINY, TINY / 8.0, TINY / 8.0};
double p000000010[9] = {TINY / 8.0, TINY / 8.0, TINY / 8.0,
TINY / 8.0, TINY / 8.0, TINY / 8.0,
TINY / 8.0, 1 - TINY, TINY / 8.0};
double p000000001[9] = {TINY / 8.0, TINY / 8.0, TINY / 8.0,
TINY / 8.0, TINY / 8.0, TINY / 8.0,
TINY / 8.0, TINY / 8.0, 1 - TINY};
if(do_inbred==0)
emission_ngsrelate9(pk_freq, pk_gls, pk_emis, pk_keeplist, pk_nkeep, pk_a, pk_b);
else
emission_ngs_inbred(pk_freq, pk_gls, pk_emis, pk_keeplist, pk_nkeep, pk_a);
#ifdef DB_EMIS
FILE * emis_fp = fopen("db_emis.txt", "w");
for(int i=0;i<pk_nkeep;i++){
fprintf(emis_fp, "%f", pk_emis[i][0]);
for(int x=1;x<9;x++){
fprintf(emis_fp, " %f", pk_emis[i][x]);
}
fprintf(emis_fp, "\n");
}
fclose(emis_fp);
#endif
//will not be used before values has been plugged in;
double tmp_pk_pars[9];
double tmp_pk_ll;
int tmp_pk_niter;
pk_ll=log(0);
#ifdef DB_MP
fprintf(stderr, "jacquard\n");
#endif
for(int n=0;n<ntimes;n++) {
sample48(tmp_pk_pars,do_inbred?2:9);
for(int i=3;do_simple&&do_inbred==0 && i<9;i++)//setting it to the old
tmp_pk_pars[i] = 0;
tmp_pk_niter = em(tmp_pk_pars, pk_emis, pk_nkeep,do_inbred?2:9);
tmp_pk_ll = loglike(tmp_pk_pars, pk_emis, pk_nkeep,do_inbred?2:9);
if(n==0||tmp_pk_ll>pk_ll){
if(0&&n>0)
fprintf(stderr,"n:%d better estimate: %f %f\n",n,tmp_pk_ll,pk_ll);
for(int i=0;i<(do_inbred?2:9);i++){
pk_pars[i] = tmp_pk_pars[i];
}
pk_ll=tmp_pk_ll;
pk_niter=tmp_pk_niter;
}
}
if(do_inbred==0){
double l100000000 = loglike(p100000000, pk_emis, pk_nkeep,9);//0
double l010000000 = loglike(p010000000, pk_emis, pk_nkeep,9);
double l001000000 = loglike(p001000000, pk_emis, pk_nkeep,9);
double l000100000 = loglike(p000100000, pk_emis, pk_nkeep,9);
double l000010000 = loglike(p000010000, pk_emis, pk_nkeep,9);
double l000001000 = loglike(p000001000, pk_emis, pk_nkeep,9);//5
double l000000100 = loglike(p000000100, pk_emis, pk_nkeep,9);//6
double l000000010 = loglike(p000000010, pk_emis, pk_nkeep,9);//7
double l000000001 = loglike(p000000001, pk_emis, pk_nkeep,9);//8
double likes[10] = {l100000000, l010000000, l001000000, l000100000,
l000010000, l000001000, l000000100, l000000010,
l000000001, pk_ll};
pk_best = 0;
pk_bestll = likes[0];
int stop= do_simple==0?10:3;
for (int i = 1; i < stop; i++) {
if (likes[i] > likes[pk_best]){
pk_best = i;
pk_bestll = likes[i];
}
}
if(stop==3&&likes[9]>likes[pk_best]){
pk_best=9;
pk_bestll = likes[pk_best];
}
}else{
double l01= loglike(p01,pk_emis,pk_nkeep,2);
double l10= loglike(p10,pk_emis,pk_nkeep,2);
double likes[3] ={l10,l01,pk_ll};
pk_best = 0;
pk_bestll = likes[0];
for(int i=1;i<3;i++){
if(likes[i]>likes[pk_best]){
pk_best=i;
pk_bestll = likes[i];
}
}
}
return 0;
}
void anal1(int a,int b,worker_args * td,double minMaf, bool & nosites){
assert(td->nsites>0);
td->nkeep = populate_keeplist(a,b,td->nsites,td->gls,minMaf,td->freq,td->keeplist,td->bootindex);
if (td->nkeep==0){
fprintf(stderr, "\t-> sample index %d and %d have no overlapping sites with data. Pair will not be analyzed\n", a, b);
nosites=true;
return ;
}
//if(!do_2dsfs_only)
analyse_jaq(td->pars,td->freq,td->gls,td->keeplist,td->emis,td->nkeep,a,b,td->ll,td->best,td->bestll,td->niter,ntimes);
if(do_inbred==0){
emislike_2dsfs_gen(td->gls, td->emis,td->keeplist, td->nkeep, a, b);
double tmp_pars_2dsfs[9];
int tmp_niter_2dsfs;
double tmp_ll_2dsfs;
#ifdef DB_MP
fprintf(stderr, "sfs\n");
#endif
td->ll_2dsfs=log(0);
for(int n=0;n<ntimes;n++){
sample48(tmp_pars_2dsfs,9);
tmp_niter_2dsfs = em(tmp_pars_2dsfs, td->emis, td->nkeep,9);
tmp_ll_2dsfs = loglike(tmp_pars_2dsfs, td->emis, td->nkeep,9);
if(n==0||tmp_ll_2dsfs>td->ll_2dsfs){
if(0&&n>0)
fprintf(stderr,"[sfs] n:%d better estimate: %f %f diff:%.3e\n",n,tmp_ll_2dsfs,td->ll_2dsfs,tmp_ll_2dsfs-td->ll_2dsfs);
for(int i=0;i<9;i++){
td->pars_2dsfs[i] = tmp_pars_2dsfs[i];
}
td->ll_2dsfs=tmp_ll_2dsfs;
td->niter_2dsfs = tmp_niter_2dsfs;
}
}
}
}
char *formatoutputnosites(int a, int b){
char retbuf[4096];
if (ids.size()) {
snprintf(retbuf,4096, "%d\t%d\t%s\t%s\t%d", a,
b, ids[a], ids[b], -1);
} else {