forked from ANGSD/angsd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathabcFreq.cpp
1581 lines (1296 loc) · 44 KB
/
abcFreq.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
/*
part of angsd.
gnu license, mit, bsd whatever free license
BUGS:
phat doesn't put data into freq->freq. Maybe this should be fixed, in either case, nobody is using the phat estimator
*/
#include <cassert>
#include <cmath>
#include <htslib/kstring.h>
#include <htslib/bgzf.h>
#include "abcFreq.h"
#include "abcSaf.h"
#include "abcFilter.h"
#include "analysisFunction.h"
int abcFreq::emIter = EM_NITER;
double abcFreq::EM_start = EM_START;
double *abcFreq::indF = NULL;
//simple phat estimator from the 200danes article, one site function
double phatFun(suint *counts,int nFiles,double eps,char major,char minor) {
double pis[nFiles];
double wis[nFiles];
if(major==minor)
return 0.0;
//if the site is variable
for(int i=0;i<nFiles;i++){
int ni = counts[i*4+minor];
int nt= counts[i*4+minor] + counts[i*4+major];
if(nt==0){//if we dont have any reads for individual 'i'
pis[i] = 0;
wis[i] = 0;
continue;
}
pis[i] = (ni-eps*nt)/(nt*(1-2*eps));
wis[i] = 2.0*nt/(nt+1.0);
}
double tmp=0;
for(int i=0;i<nFiles;i++)
tmp+= (pis[i]*wis[i]);
double phatV = std::max(0.0,tmp/angsd::sum<double>(wis,nFiles));
return phatV;
}
//simple phat estimator will loop over all sites in the pars
void phatLoop(funkyPars *pars,double eps,double nInd,freqStruct *freqs){
freqs->phat = new double[pars->numSites];
freqs->freq = new double[pars->numSites];
for(int s=0;s<pars->numSites;s++)
if(pars->keepSites[s]){
freqs->phat[s] = phatFun(pars->counts[s],nInd,eps,pars->major[s],pars->minor[s]);
freqs->freq[s] = freqs->phat[s];
}
}
void abcFreq::printArg(FILE *argFile){
fprintf(argFile,"------------------------\n%s:\n",__FILE__);
fprintf(argFile,"-doMaf\t%d (Calculate persite frequencies \'.mafs.gz\')\n",doMaf);
fprintf(argFile,"\t1: Frequency (fixed major and minor)\n");
fprintf(argFile,"\t2: Frequency (fixed major unknown minor)\n");
fprintf(argFile,"\t4: Frequency from genotype probabilities\n");
fprintf(argFile,"\t8: AlleleCounts based method (known major minor)\n");
fprintf(argFile,"\tNB. Filedumping is supressed if value is negative\n");
fprintf(argFile,"-doPost\t%d\t(Calculate posterior prob 3xgprob)\n",doPost);
fprintf(argFile,"\t1: Using frequency as prior\n");
fprintf(argFile,"\t2: Using uniform prior\n");
fprintf(argFile,"\t3: Using SFS as prior (still in development)\n");
fprintf(argFile,"\t4: Using reference panel as prior (still in development), requires a site file with chr pos major minor af ac an\n");
fprintf(argFile,"Filters:\n");
fprintf(argFile,"\t-minMaf \t%f\t(Remove sites with MAF below)\n",minMaf);
fprintf(argFile,"\t-SNP_pval\t%f\t(Remove sites with a pvalue larger)\n",SNP_pval);
fprintf(argFile,"\t-rmTriallelic\t%f\t(Remove sites with a pvalue lower)\n",rmTriallelic);
fprintf(argFile,"Extras:\n");
fprintf(argFile,"\t-ref\t%s\t(Filename for fasta reference)\n",refName);
fprintf(argFile,"\t-anc\t%s\t(Filename for fasta ancestral)\n",ancName);
fprintf(argFile,"\t-eps\t%f [Only used for -doMaf &8]\n",eps);
fprintf(argFile,"\t-beagleProb\t%d (Dump beagle style postprobs)\n",beagleProb);
fprintf(argFile,"\t-indFname\t%s (file containing individual inbreedcoeficients)\n",indFname);
fprintf(argFile,"\t-underFlowProtect\t%d (file containing individual inbreedcoeficients)\n",underflowprotect);
fprintf(argFile,"NB These frequency estimators requires major/minor -doMajorMinor\n");
}
//fancy little function
int isPowerOfTwo (unsigned int x)
{
return ((x != 0) && ((x & (~x + 1)) == x));
}
void abcFreq::getOptions(argStruct *arguments){
int inputtype = arguments->inputtype;
doMaf=angsd::getArg("-doMaf",doMaf,arguments);
doPost=angsd::getArg("-doPost",doPost,arguments);
if(doMaf==0 && doPost ==0)
return;
rmTriallelic=angsd::getArg("-rmTriallelic",rmTriallelic,arguments);
GL=angsd::getArg("-GL",GL,arguments);
if(inputtype!=INPUT_VCF_GL && inputtype!=INPUT_GLF && inputtype!=INPUT_GLF3 && doPost && GL==0){
fprintf(stderr,"\t-> Potential problem: You are required to choose a genotype likelihood model (-GL) for estimating genotypes posteriors.\n");
exit(0);
}
doMajorMinor=angsd::getArg("-doMajorMinor",doMajorMinor,arguments);
// fprintf(stderr,"%d %d\n",inputtype,INPUT_VCF_GL);
if((doPost||doMaf) &&doMajorMinor==0 &&inputtype!=INPUT_VCF_GL){
if(doMaf!=4){
fprintf(stderr,"\t-> Potential problem: You are required to choose a major/minor estimator (-doMajorMinor)\n");
exit(0);
}
}
if(doPost==1 &&doMaf==0){
fprintf(stderr,"\t-> Potential problem: You are required to choose a maf estimator (-doMaf) with -doPost 1\n");
exit(0);
}
indFname = angsd::getArg("-indF",indFname,arguments);
if(indFname !=NULL)
indF = angsd::readDouble(indFname,arguments->nInd);
if(doMaf==0 )//&& doPost==0?
return;
underflowprotect=angsd::getArg("-underFlowProtect",underflowprotect,arguments);
chisq1 = new Chisqdist(1);
chisq2 = new Chisqdist(2);
chisq3 = new Chisqdist(3);
minMaf=angsd::getArg("-minMaf",minMaf,arguments);
// assert(minMaf<=1&&minMaf>=0);
double tmp=-1;
tmp=angsd::getArg("-SNP_pval",tmp,arguments);
if(tmp!=-1){
SNP_pval = tmp;
double pre = SNP_pval;
// fprintf(stderr,"ind:%f :%p: \t",SNP_pval,chisq3);
if(SNP_pval <=1){
if(abs(doMaf) ==2)
SNP_pval = chisq1->invcdf(1-SNP_pval);
if(abs(doMaf) ==1)
SNP_pval = chisq1->invcdf(1-SNP_pval);
}
doSNP =1 ;
fprintf(stderr,"\t-> SNP-filter using a pvalue: %e correspond to %f likelihood units\n",pre,SNP_pval);
}
if(rmTriallelic)
SNP_pval_tri = chisq2->invcdf(1-rmTriallelic);
refName = angsd::getArg("-ref",refName,arguments);
ancName = angsd::getArg("-anc",ancName,arguments);
if(abs(doMaf)&& !isPowerOfTwo((unsigned int) abs(doMaf))){
fprintf(stderr,"\n[%s] You have selected filters for maf/lrt\n",__FILE__);
fprintf(stderr,"If you have selected more than one MAF estimator we will choose in following order\n");
fprintf(stderr,"\t1. knownminor EM\n");
fprintf(stderr,"\t2. unknownminor EM\n");
fprintf(stderr,"\t3. Posterior maf\n");
}
if(doSNP && abs(doMaf)&8){
fprintf(stderr,"\t-> LRT based snp calling is not defined for count based maf estimates\n");
exit(0);
}
if(doSNP&&abs(doMaf)==0){
fprintf(stderr,"You've selected SNP-calling but no maf estimator please select -doMaf INT\n");
exit(0);
}
if(doSNP==1 && abs(doMaf)==0){
fprintf(stderr,"You've selected SNP_pval threshold please also select -doMaf \n");
exit(0);
}
if(minMaf>0.0 &&(abs(doMaf)==0)){
fprintf(stderr,"\nYou've selected minMaf but no MAF estimator, choose -doMaf\n\n");
exit(0);
}
if(rmTriallelic>0.0 &&(abs(doMaf)!=1)){
fprintf(stderr,"\n rmTriallelic only works with -doMaf 1 \n\n");
exit(0);
}
int doCounts =0;
doCounts=angsd::getArg("-doCounts",doCounts,arguments);
beagleProb=angsd::getArg("-beagleProb",beagleProb,arguments);
minInd=angsd::getArg("-minInd",minInd,arguments);
if(abs(doMaf)==0 &&doPost==0)
return;
if(inputtype!=INPUT_VCF_GP&&inputtype!=INPUT_BEAGLE&&inputtype!=0&&doMajorMinor==0&&inputtype!=INPUT_VCF_GL){
fprintf(stderr,"You must specify \'-doMajorMinor\' to infer major/minor \n");
exit(0);
}
if(inputtype==INPUT_BEAGLE&&abs(doMaf)!=4){
fprintf(stderr,"Only \'-doMaf 4\' can not be performed on posterior input\n");
exit(0);
}
if(inputtype!=INPUT_BEAGLE&&inputtype!=INPUT_VCF_GP&&abs(doMaf)==4){
fprintf(stderr,"\t \'-doMaf 4\' can only be performed on genotype probabilities provided by the user (-beagle).\n");
exit(0);
}
if((inputtype==INPUT_BAM || inputtype==INPUT_PILEUP )&& GL==0 &&doMaf!=8){
fprintf(stderr,"Error: For sequence data (BAM,pileups) likehoods (-GL) must be specified for frequency estimation\n");
exit(0);
}
if(doSNP&&abs(doMaf) &4){
fprintf(stderr,"Error: -doMaf 4 cannot be used for a likelihood ratio test (doSNP) \n");
exit(0);
}
if(inputtype==INPUT_BEAGLE&&doPost){
fprintf(stderr,"Error: Cannot estimate post (doPost) based on posterior probabilites\n");
exit(0);
}
if(abs(doMaf)&8&&doCounts==0){
fprintf(stderr,"Must supply -doCounts for MAF estimator based on counts\n");
exit(0);
}
if(beagleProb && doPost==0 &&inputtype!=INPUT_VCF_GP){
fprintf(stderr,"Must supply -doPost 1 to write beaglestyle postprobs\n");
exit(0);
}
if(doPost!=0 && doMajorMinor==0 &&INPUT_VCF_GL!=inputtype){
fprintf(stderr,"Do post requires major and minor: supply -doMajorMinor \n");
exit(0);
}
}
//constructor
abcFreq::abcFreq(const char *outfiles,argStruct *arguments,int inputtype){
underflowprotect =0;
minInd = 0;
chisq1=chisq2=chisq3=NULL;
inputIsBeagle =0;
beagleProb = 0; //<-output for beagleprobs
minMaf =-1.0;
SNP_pval = 1;
nInd = arguments->nInd;
eps = 0.001;
outfileZ2 = NULL;
outfileZ = NULL;
indFname = NULL;
doMaf=0;
rmTriallelic=0;
GL=0;
doSNP=0;
doPost=0;
bufstr.s=NULL;bufstr.l=bufstr.m=0;
//emIter=EM_NITER; //these are static see top of this file
//EM_start = EM_START; //these are static see top of this file
doMajorMinor=0;
refName = NULL;
ancName = NULL;
if(arguments->argc==2){
if(!strcasecmp(arguments->argv[1],"-doMaf")||!strcasecmp(arguments->argv[1],"-doPost")){
printArg(stdout);
exit(0);
}else
return;
}
getOptions(arguments);
if(doMaf==0 && doPost==0){
shouldRun[index]=0;
return;
}
printArg(arguments->argumentFile);
if(doMaf>0){
//make output files
const char* postfix;
postfix=".mafs.gz";
outfileZ = aio::openFileBG(outfiles,postfix);
if(beagleProb){
postfix=".beagle.gprobs.gz";
outfileZ2 = aio::openFileBG(outfiles,postfix);
}
}else
doMaf=abs(doMaf);
//print header
kputs("chromo\tposition\tmajor\tminor\t",&bufstr);
if(refName!=NULL||arguments->inputtype==INPUT_PILEUP)
kputs("ref\t",&bufstr);
if(ancName)
kputs("anc\t",&bufstr);
if(doMaf &1)
kputs("knownEM\t",&bufstr);
if(doMaf &2)
kputs("unknownEM\t",&bufstr);
if(doMaf &4)
kputs("PPmaf\t",&bufstr);
if(doMaf &8)
kputs("phat\t",&bufstr);
if(doSNP){
if(doMaf &1)
kputs("pK-EM\t",&bufstr);
if(doMaf &2)
kputs("pu-EM\t",&bufstr);
}
kputs("nInd\n",&bufstr);
aio::bgzf_write(outfileZ,bufstr.s,bufstr.l);
bufstr.l=0;
if(beagleProb){
kputs("marker\tallele1\tallele2",&bufstr);
for(int i=0;i<arguments->nInd;i++){
kputs("\tInd",&bufstr);
kputw(i,&bufstr);
kputs("\tInd",&bufstr);
kputw(i,&bufstr);
kputs("\tInd",&bufstr);
kputw(i,&bufstr);
}
kputc('\n',&bufstr);
aio::bgzf_write(outfileZ2,bufstr.s,bufstr.l);
bufstr.l=0;
}
}
abcFreq::~abcFreq(){
if(outfileZ!=NULL){
bgzf_close(outfileZ);
}
if(outfileZ2!=NULL){
bgzf_close(outfileZ2);
}
free(refName);
free(ancName);
delete [] indF;
delete chisq1;
delete chisq2;
delete chisq3;
free(bufstr.s);
}
void abcFreq::print(funkyPars *pars) {
if(outfileZ==NULL&&outfileZ2==NULL)
return;
freqStruct *freq =(freqStruct *) pars->extras[index];
for(int s=0;s<pars->numSites;s++) {
if(pars->keepSites[s]==0)
continue;
//plugin chr,pos,major,minor
kputs(header->target_name[pars->refId],&bufstr);kputc('\t',&bufstr);
kputw(pars->posi[s]+1,&bufstr);kputc('\t',&bufstr);
kputc(intToRef[pars->major[s]],&bufstr);kputc('\t',&bufstr);
kputc(intToRef[pars->minor[s]],&bufstr);kputc('\t',&bufstr);
//plugin ref, anc if exists
if(pars->ref!=NULL)
{kputc(intToRef[pars->ref[s]],&bufstr);kputc('\t',&bufstr);}
if(pars->anc!=NULL)
{kputc(intToRef[pars->anc[s]],&bufstr);kputc('\t',&bufstr);}
if(doMaf &1)
ksprintf(&bufstr,"%f\t",freq->freq_EM[s]);
if(doMaf &2)
ksprintf(&bufstr,"%f\t",freq->freq_EM_unknown[s]);
if(doMaf &4)
ksprintf(&bufstr,"%f\t",freq->freq[s]);
if(doMaf &8)
ksprintf(&bufstr,"%f\t",freq->phat[s]);
if(doSNP){
if(doMaf &1)
ksprintf(&bufstr,"%e\t",angsd::to_pval(chisq1,freq->lrt_EM[s]));
if(doMaf &2)
ksprintf(&bufstr,"%e\t",angsd::to_pval(chisq1,freq->lrt_EM_unknown[s]));
}
kputw(pars->keepSites[s],&bufstr);kputc('\n',&bufstr);
}
aio::bgzf_write(outfileZ,bufstr.s,bufstr.l);
bufstr.l=0;
if(beagleProb){
//beagle format
for(int s=0;s<pars->numSites;s++) {
if(pars->keepSites[s]==0)
continue;
// fprintf(stderr,"keepsites=%d\n",pars->keepSites[s]);
kputs(header->target_name[pars->refId],&bufstr);
kputc('_',&bufstr);
kputw(pars->posi[s]+1,&bufstr);
kputc('\t',&bufstr);
kputw(pars->major[s],&bufstr);
kputc('\t',&bufstr);
kputw(pars->minor[s],&bufstr);
int major = pars->major[s];
int minor = pars->minor[s];
assert(major!=4&&minor!=4);
for(int i=0;i<3*pars->nInd;i++) {
ksprintf(&bufstr, "\t%f",pars->post[s][i]);
}
kputc('\n',&bufstr);
}
//valgrind on osx complains here check if prob on unix
int ret=aio::bgzf_write(outfileZ2,bufstr.s,bufstr.l);
bufstr.l=0;
//fprintf(stderr,"ret.l:%d bufstr.l:%zu\n",ret,bufstr.l);
}
}
void abcFreq::clean(funkyPars *pars) {
if(doMaf==0&&doPost==0)
return;
freqStruct *freq =(freqStruct *) pars->extras[index];
//cleaning
delete [] freq->freq;
delete [] freq->lrt;//maybe in doSNP
delete [] freq->freq_EM;
delete [] freq->freq_EM_unknown;
delete [] freq->lrt_tri;
delete [] freq->lrt_EM;
delete [] freq->lrt_EM_unknown;
delete [] freq->phat;
delete freq;
if(pars->post!=NULL){
for(int i=0;i<pars->numSites;i++)
delete [] pars->post[i];
delete [] pars->post;
pars->post =NULL;
}
}
freqStruct *allocFreqStruct(){
freqStruct *freq = new freqStruct;
freq->freq_EM=NULL;
freq->freq_EM_unknown= NULL;
freq->lrt_tri=NULL;
freq->lrt_EM=NULL;
freq->lrt_EM_unknown=NULL;
freq->freq = NULL;
freq->lrt = NULL;
freq->phat = NULL;
return freq;
}
//filipes
void make_post_F(double *like,double *post,double freqEst,int nInd){
//fprintf(stderr,"[%s]\n",__FUNCTION__);
double *indF = abcFreq::indF;
for(int i=0;i<nInd;i++){
post[i*3+2]=like[i*3+2] + log(pow(freqEst,2) + (1-freqEst)*freqEst*indF[i]);
post[i*3+1]=like[i*3+1] + log(2*(1-freqEst)*freqEst - 2*(1-freqEst)*freqEst*indF[i]);
post[i*3+0]=like[i*3+0] + log(pow(1-freqEst,2) + (1-freqEst)*freqEst*indF[i]);
double norm = angsd::addProtect3(post[i*3+0],post[i*3+1],post[i*3+2]);
post[i*3+0]=exp(post[i*3+0]-norm);
post[i*3+1]=exp(post[i*3+1]-norm);
post[i*3+2]=exp(post[i*3+2]-norm);
}
//
}
void make_post(double *like,double *post,double freqEst,int nInd){
if(abcFreq::indF!=NULL){
make_post_F(like,post,freqEst,nInd);
return;
}
for(int i=0;i<nInd;i++){
// fprintf(stderr,"[%d]\nlik= %f %f %f\n",i,like[0][i*3+0],like[0][i*3+1],like[0][i*3+2]);
post[i*3+2]=like[i*3+2]+2*log(freqEst);
post[i*3+1]=like[i*3+1]+log(2)+log(1-freqEst)+log(freqEst);
post[i*3+0]=like[i*3+0]+2*log(1-freqEst);
// fprintf(stderr,"likmod= %f %f %f\n",post[0][i*3+0],post[0][i*3+1],post[0][i*3+2]);
double norm = angsd::addProtect3(post[i*3+0],post[i*3+1],post[i*3+2]);
post[i*3+0]=exp(post[i*3+0]-norm);
post[i*3+1]=exp(post[i*3+1]-norm);
post[i*3+2]=exp(post[i*3+2]-norm);
// fprintf(stderr,"%f %f %f\n",post[0][i*3+0],post[0][i*3+1],post[0][i*3+2]);
}
}
void abcFreq::run(funkyPars *pars) {
if(doMaf==0&&doPost==0)
return;
freqStruct *freq = allocFreqStruct();
pars->extras[index] = freq;
extern abc **allMethods;
// abcFilter *abcf=(abcFilter *) allMethods[0];
filt *fl = ((abcFilter *) allMethods[0])->fl;
if(doMaf!=0) {
if(doMaf&8)
phatLoop(pars,eps,nInd,freq);
if(doMaf&4)
postFreq(pars,freq);
if(doMaf % 4){ // doMaf =1 or doMaf 2
likeFreq(pars,freq);
}
assert(freq->freq!=NULL);
for(int s=0;s<pars->numSites;s++){
if(pars->keepSites[s]==0)
continue;
if(freq->freq[s] < minMaf)
pars->keepSites[s]=0;
else if(freq->freq[s] > 1 - minMaf)
pars->keepSites[s]=0;
if(doSNP && (freq->lrt[s] < SNP_pval))
pars->keepSites[s]=0;
if(rmTriallelic && (freq->lrt_tri[s] > SNP_pval_tri))
pars->keepSites[s]=0;
if(minInd>0&&pars->keepSites[s]<minInd)
pars->keepSites[s] = 0;
}
}
if(doPost) {
assert(pars->likes!=NULL);
double **post = new double*[pars->numSites];
double **like=angsd::get3likes(pars);
for(int s=0;s<pars->numSites;s++){
post[s] = new double [3*pars->nInd];
if(pars->keepSites[s]==0){
delete [] like[s];
continue;
}
if(doPost==1) //maf prior
make_post(like[s],post[s],freq->freq[s],pars->nInd);
else if(doPost==2) {//uniform prior
for(int i=0;i<pars->nInd;i++){
double norm = angsd::addProtect3(like[s][i*3+0],like[s][i*3+1],like[s][i*3+2]);
for(int g=0;g<3;g++)
post[s][i*3+g]=exp(like[s][i*3+g]-norm);
}
}
else if(doPost==3){//uniform prior
if(algoGeno(pars->likes[s],refToInt[pars->major[s]],refToInt[pars->minor[s]],pars->nInd,underflowprotect,abcSaf::prior,post[s]))
fprintf(stderr,"\t-> Problem calling genotypes at: (%s,%d)\n",header->target_name[pars->refId],pars->posi[s]+1);
}
else if(doPost==4){
assert(fl!=NULL);
//af for this pos: fl->af[pars->posi[s]]
//an for this pos: fl->an[pars->posi[s]]
//ac for this pos: fl->ac[pars->posi[s]]
// fprintf(stderr,"chr: %s pos: %d freq:%f\n",header->target_name[pars->refId],pars->posi[s]+1,fl->af[pars->posi[s]]);
if(fl->keeps[pars->posi[s]]==0)
make_post(like[s],post[s],freq->freq[s],pars->nInd);
else{
double exp_obs_allels_in_ngs= freq->freq[s]*pars->keepSites[s];
// fprintf(stderr,"pars->keepSite:%d\n",pars->k)
double aac = fl->ac[pars->posi[s]];
double aan = fl->an[pars->posi[s]];
double af = (aac+exp_obs_allels_in_ngs)/(1.0*(aan+pars->keepSites[s]));
fprintf(stderr,"aac:%f aan:%f nal_in_ngs:%f af:%f\n",aac,aan,exp_obs_allels_in_ngs,af);
make_post(like[s],post[s],af,pars->nInd);
}
}
else{
fprintf(stderr,"[%s] doPost must be 1 or 2 \n",__FUNCTION__);
exit(0);
}
delete [] like[s];
}
pars->post = post;
delete[] like;
}
}
/*
Estimate the allele frequency from the posterior probabilities
*/
void abcFreq::postFreq(funkyPars *pars,freqStruct *freq){
if(freq->freq==NULL)
freq->freq = new double[pars->numSites];
for(int s=0;s<pars->numSites;s++){
freq->freq[s]=0;
for(int i=0;i<pars->nInd;i++){
freq->freq[s] += pars->post[s][i*3+1]+2*pars->post[s][i*3+2];
}
freq->freq[s] = freq->freq[s]/(pars->nInd*2);
}
}
void abcFreq::likeFreq(funkyPars *pars,freqStruct *freq){//method=1: bfgs_known ;method=2 em;method=4 bfgs_unknown
//here only the likelihoods for the three genotypes are used.
double **loglike = NULL;
if(inputIsBeagle==1)
loglike= pars->likes;
else
loglike=angsd::get3likesRescale(pars);
assert(loglike!=NULL);
if(freq->freq == NULL)
freq->freq = new double[pars->numSites];
if(doSNP)
freq->lrt = new double[pars->numSites];
if(rmTriallelic)
freq->lrt_tri = new double[pars->numSites];
if(doMaf &1){
freq->freq_EM = new double[pars->numSites];
if(doSNP)
freq->lrt_EM = new double[pars->numSites];
}
if(doMaf &2){
freq->freq_EM_unknown =new double[pars->numSites];
if(doSNP)
freq->lrt_EM_unknown =new double[pars->numSites];
}
// number of individuals with data
int *keepInd = pars->keepSites;
int keepList[pars->nInd];
//loop though all sites and check if we have data.
for(int s=0;s<pars->numSites;s++) {
if(keepInd[s]==0)//if we dont have any information
continue;
keepInd[s]=0;//
for(int i=0 ; i<pars->nInd ;i++) {//DRAGON CHECK THIS
keepList[i]=1;
//also discard if all gls are the same
if(loglike[s][i*3+0]+loglike[s][i*3+1]+loglike[s][i*3+2]>-0.0001||((loglike[s][i*3]==loglike[s][i*3+1] )&& (loglike[s][i*3]==loglike[s][i*3+2]))){
keepList[i]=0;
}
else{
keepInd[s]++;
}
}
if(keepInd[s]==0)//if we dont have any information
continue;
if(doMaf &1) {
double mstart = EM_start;
if(freq->phat!=NULL)
mstart = freq->phat[s];
freq->freq_EM[s]=emFrequency(loglike[s],pars->nInd,emIter,mstart,keepList,keepInd[s]);
if(doSNP){
freq->lrt_EM[s]= 2*likeFixedMinor(0.0,loglike[s],pars->nInd)-2*likeFixedMinor(freq->freq_EM[s],loglike[s],pars->nInd);
if(freq->lrt_EM[s]<0)
freq->lrt_EM[s]=0;
}
}
if( doMaf &2) {
double mstart = EM_start;
if(freq->phat!=NULL)
mstart = freq->phat[s];
freq->freq_EM_unknown[s]=emFrequencyNoFixed(pars->likes[s],pars->nInd,emIter,mstart,keepList,keepInd[s],pars->major[s],pars->posi[s]);
if(doSNP){
freq->lrt_EM_unknown[s] = 2*likeNoFixedMinor(0.0,pars->likes[s],pars->nInd,pars->major[s])-2*likeNoFixedMinor(freq->freq_EM_unknown[s],pars->likes[s],pars->nInd,pars->major[s]);
if(freq->lrt_EM_unknown[s]<0)
freq->lrt_EM_unknown[s]=0;
}
}
if(rmTriallelic!=0){
double lrtTri=0;
if(freq->freq_EM[s]>0.0001)
lrtTri=isMultiAllelic(pars->likes[s],pars->nInd,emIter,freq->freq_EM[s],keepList,keepInd[s],pars->major[s],pars->minor[s]);
freq->lrt_tri[s] = lrtTri;
}
}
if(inputIsBeagle!=1){
for(int i=0;i<pars->numSites;i++)
delete [] loglike[i];
delete [] loglike;
}
for(int s=0;s<pars->numSites;s++){
if(doMaf &2 )
freq->freq[s]=freq->freq_EM_unknown[s];
else if(doMaf &1 )
freq->freq[s]=freq->freq_EM[s];
}
//thorfinn april 16 2012
for(int s=0;s<pars->numSites;s++){
if((doMaf &2) && doSNP )
freq->lrt[s]=freq->lrt_EM_unknown[s];
else if((doMaf &1) && doSNP)
freq->lrt[s]=freq->lrt_EM[s];
}
}
double abcFreq::emFrequencyNoFixed_ext(double *loglike,int numInds,int *keep,int keepInd,int major,int posi){
return emFrequencyNoFixed(loglike,numInds, emIter,EM_start, keep,keepInd,major,posi);
}
double abcFreq::emFrequencyNoFixed_F(double *loglike,int numInds, int iter,double start,int *keep,int keepInd,int major,int posi){
int iMinor[3];
int n=0;
for(int i=0;i<4;i++){
if(i!=major){
iMinor[n]=i;
n++;
}
}
double **loglikeGeno;
loglikeGeno =new double*[3];
for(int j=0;j<3;j++){
loglikeGeno[j] = new double[numInds*3];
for(int i=0;i<numInds;i++){
loglikeGeno[j][i*3+0]=loglike[i*10+angsd::majorminor[major][major]];
loglikeGeno[j][i*3+1]=loglike[i*10+angsd::majorminor[major][iMinor[j]]];
loglikeGeno[j][i*3+2]=loglike[i*10+angsd::majorminor[iMinor[j]][iMinor[j]]];
}
}
float W0[3];
float W1[3];
float W2[3];
start=0.4;
float p=(float)start;
float temp_p=(float)start;
double accu=0.00001;
double accu2=0;
float sum;
int it=0;
float weight[3];
float normWeight[3];
float norm;
int correctInd;
for(it=0;it<iter;it++){
for(int j=0;j<3;j++)
weight[j]=-likeFixedMinor(p,loglikeGeno[j],keepInd);
norm=angsd::addProtect3(weight[0],weight[1],weight[2]);
for(int j=0;j<3;j++)
normWeight[j]=exp(weight[j]-norm);
sum=0;
correctInd=keepInd;
for(int i=0;i<numInds;i++){
if(keep[i]==0)
continue;
for(int j=0;j<3;j++){
W0[j]=exp(loglike[i*10+angsd::majorminor[major][major]]) * (pow(1-p,2) + (1-p)*p*indF[i]);
W1[j]=exp(loglike[i*10+angsd::majorminor[major][iMinor[j]]]) * (2*(1-p)*p - 2*(1-p)*p*indF[i]);
W2[j]=exp(loglike[i*10+angsd::majorminor[iMinor[j]][iMinor[j]]]) * (pow(p,2) + (1-p)*p*indF[i]);
if(W0[j]+W1[j]+W2[j]<0.0000001)
continue;
}
}
p=sum/correctInd;
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 at position: %d\n",__FUNCTION__,posi);
for(int j=0;j<3;j++)
fprintf(stderr,"w%d %f ",j,weight[j]);
fflush(stderr);
for(int i=0;i<numInds;i++){
for(int j=0;j<10;j++){
if(keep[i]==0)
continue;
fprintf(stderr,"%f\t",loglike[i*10+j]);
}
fprintf(stderr,"\n");
}
fprintf(stderr,"%f | %f %f %f |%f | %d | \n",p, normWeight[0], normWeight[1], normWeight[2],angsd::addProtect3(weight[0],weight[1],weight[2]),major);
}
}
for(int j=0;j<3;j++)
delete[] loglikeGeno[j];
delete[] loglikeGeno;
return(p);
}
double abcFreq::emFrequencyNoFixed(double *loglike,int numInds, int iter,double start,int *keep,int keepInd,int major,int posi){
if(indF!=NULL)
return emFrequencyNoFixed_F(loglike,numInds,iter,start,keep,keepInd,major,posi);
int iMinor[3];
int n=0;
for(int i=0;i<4;i++){
if(i!=major){
iMinor[n]=i;
n++;
}
}
double **loglikeGeno;
loglikeGeno =new double*[3];
for(int j=0;j<3;j++){
loglikeGeno[j] = new double[numInds*3];
for(int i=0;i<numInds;i++){
loglikeGeno[j][i*3+0]=loglike[i*10+angsd::majorminor[major][major]];
loglikeGeno[j][i*3+1]=loglike[i*10+angsd::majorminor[major][iMinor[j]]];
loglikeGeno[j][i*3+2]=loglike[i*10+angsd::majorminor[iMinor[j]][iMinor[j]]];
}
}
float W0[3];
float W1[3];
float W2[3];
start=0.4;
float p=(float)start;
float temp_p=(float)start;
double accu=0.00001;
double accu2=0;
float sum;
int it=0;
float weight[3];
float normWeight[3];
float norm;
int correctInd;
for(it=0;it<iter;it++){
for(int j=0;j<3;j++)
weight[j]=-likeFixedMinor(p,loglikeGeno[j],keepInd);
norm=angsd::addProtect3(weight[0],weight[1],weight[2]);
for(int j=0;j<3;j++)
normWeight[j]=exp(weight[j]-norm);
sum=0;
correctInd=keepInd;
for(int i=0;i<numInds;i++){
if(keep!=NULL && keep[i]==0)
continue;
for(int j=0;j<3;j++){
W0[j]=exp(loglike[i*10+angsd::majorminor[major][major]])*pow(1-p,2);
W1[j]=exp(loglike[i*10+angsd::majorminor[major][iMinor[j]]])*2*p*(1-p);
W2[j]=exp(loglike[i*10+angsd::majorminor[iMinor[j]][iMinor[j]]])*(pow(p,2));
if(W0[j]+W1[j]+W2[j]<0.0000001)
continue;
sum+=(W1[j]+2*W2[j])/(2*(W0[j]+W1[j]+W2[j]))*normWeight[j];
}
}
p=sum/correctInd;
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 at position: %d will exit\n",__FUNCTION__,posi+1);
for(int j=0;j<3;j++)
fprintf(stderr,"w%d %f ",j,weight[j]);
fflush(stderr);
for(int i=0;i<numInds;i++){
for(int j=0;j<10;j++){
if(keep[i]==0)
continue;
fprintf(stderr,"%f\t",loglike[i*10+j]);
}
fprintf(stderr,"\n");
}
fprintf(stderr,"%f | %f %f %f |%f | %d | \n",p, normWeight[0], normWeight[1], normWeight[2],angsd::addProtect3(weight[0],weight[1],weight[2]),major);
}
}
for(int j=0;j<3;j++)
delete[] loglikeGeno[j];
delete[] loglikeGeno;
return(p);
}
///////////////////////////////////////////////
double abcFreq::isMultiAllelic(double *loglike,int numInds, int iter,double freqStandard,int *keep,int keepInd,int major,int minor){
double freq[4];
double temp_freq[4];
double W[10];
float sum[4];
for(int j=0;j<4;j++)
freq[j] = 0.25;
double accu=0.00001;
int it=0;
float norm;
/* for(int i=0;i<numInds;i++){
if(keep!=NULL && keep[i]==0)
continue;
for(int j=0;j<10;j++)
fprintf(stderr,"%f ", loglike[i*10+j]);
fprintf(stderr,"\n");
}
*/
for(it=0;it<iter;it++){
for(int j=0;j<4;j++){
temp_freq[j] = freq[j] ;
sum[j]=0;
}
for(int i=0;i<numInds;i++){
if(keep!=NULL && keep[i]==0)
continue;
W[0] = exp(loglike[i*10+0]) * pow(freq[0],2); //AA 0
W[1] = exp(loglike[i*10+1]) * 2*freq[0]*freq[1]; //AC 1
W[2] = exp(loglike[i*10+2]) * 2*freq[0]*freq[2]; //AG 2
W[3] = exp(loglike[i*10+3]) * 2*freq[0]*freq[3]; //AT 3
W[4] = exp(loglike[i*10+4]) * pow(freq[1],2); //CC 4
W[5] = exp(loglike[i*10+5]) * 2*freq[1]*freq[2]; //CG 5
W[6] = exp(loglike[i*10+6]) * 2*freq[1]*freq[3]; //CT 6
W[7] = exp(loglike[i*10+7]) * pow(freq[2],2); //GG 7
W[8] = exp(loglike[i*10+8]) * 2*freq[2]*freq[3]; //GT 8
W[9] = exp(loglike[i*10+9]) * pow(freq[3],2); //TT 9
norm=0;
for(int s=0;s<10;s++){
norm+=W[s];