forked from grenaud/schmutzi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mtCont.cpp
1431 lines (995 loc) · 42.6 KB
/
mtCont.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
/*
* mtCont
* Date: Mar-26-2014
* Author : Gabriel Renaud gabriel.reno [at sign here ] gmail.com
*
*/
// #define DEBUG1
// #define DEBUG2
// #define DEBUGPOS 714 //position to debug
// #define DEBUGPOS 608 //position to debug
// #define DEBUGPOS 14250
// #define DEBUGPOSEACHREAD //to debug each read
//#define DEBUGCONTPOS //print pos that are potential contaminants
// #define DEBUGMTPOSSKIP
#define MAXCOV 5000 // beyond that coverage, we stop computing
#define MINPRIOR 0.1 // below that prior for contamination at a given base, we give up
#define MAXMAPPINGQUAL 257 // maximal mapping quality, should be sufficient as mapping qualities are encoded using 8 bits
#define MINDISTFROMINDEL 5 // ignore positions that are within X bp of an indel
//TODO
// mapping TODO
// probEndoVec seems to have been used twice
// CODE ORGANIZATION
//
// main()
// call initScores() to initialize probability scores
// read arguments, contaminant profiles are stored in queueFilesToprocess
// read error and deamination profiles
// read the endogenous consensus profile
// read the fasta reference
// read BAM file with MyPileupVisitor where MyPileupVisitor::Visit will be called on each position which populates infoPPos
// creates threads using pthread_create using mainContaminationThread()
// print to outlog and exit
//
// mainContaminationThread()
// gets a contamination profile to use via locking the mutex "mutexQueue"
// if no data is left to read, die
// otherwise, get an allele frequency file freqFileNameToUse from queueFilesToprocess
// call readMTAlleleFreq() on the freqFileNameToUse which will populate freqFromFile
// Begin pre-computations that are static for each contamination rate
// For every endogenous and contaminant pair
// Compute prior on the pair
// Compute the probability that the reads match them for the endogenous and contaminant probEndoVec
#include <api/BamConstants.h>
#include <api/BamMultiReader.h>
#include <utils/bamtools_fasta.h>
#include <utils/bamtools_options.h>
#include <utils/bamtools_pileup_engine.h>
#include <utils/bamtools_utilities.h>
#include <gzstream.h>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <limits>
#include <queue>
#include <algorithm>
#include "utils.h"
#include "miscfunc.h"
using namespace BamTools;
using namespace std;
//! Chunk of code to check if a certain thread call failed
/*!
This block is calls by the pthread
*/
#define checkResults(string, val) { \
if (val) { \
cerr<<"Failed with "<<val<<" at "<<string<<endl; \
exit(1); \
} \
}
typedef struct{
long double logLike;
string fname;
long double contEst;
long double contEstLow;
long double contEstHigh;
} contRecord;
bool compContRecord (contRecord i, contRecord j) { return (i.logLike<j.logLike); }
char offsetQual=33;
long double likeMatch[MAXMAPPINGQUAL];
long double likeMismatch[MAXMAPPINGQUAL];
long double likeMatchMQ[MAXMAPPINGQUAL][MAXMAPPINGQUAL];
long double likeMismatchMQ[MAXMAPPINGQUAL][MAXMAPPINGQUAL];
long double likeMatchProb[MAXMAPPINGQUAL];
long double likeMismatchProb[MAXMAPPINGQUAL];
long double likeMatchProbMQ[MAXMAPPINGQUAL][MAXMAPPINGQUAL];
long double likeMismatchProbMQ[MAXMAPPINGQUAL][MAXMAPPINGQUAL];
probSubstition illuminaErrorsProb;
vector<probSubstition> sub5p;
vector<probSubstition> sub3p;
probSubstition defaultSubMatch;
long double probMapping[MAXMAPPINGQUAL];
long double probMismapping[MAXMAPPINGQUAL];
string dnaAlphabet="ACGT";
long double stepContEst = 0.01;
long double topCont = 1.0;
#define MIN(a,b) (((a)<(b))?(a):(b))
queue<string> queueFilesToprocess;
vector< vector<contaminationEstimate> > outputToPrint;
pthread_mutex_t mutexQueue = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutexCounter = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutexRank = PTHREAD_MUTEX_INITIALIZER;
//GLOBALLY accessed
int sizeGenome =0;
vector<positionInformation> infoPPos;
map<int, PHREDgeno> pos2phredgeno;
vector<int> posOfIndels;
map<unsigned int, int> threadID2Rank;
vector<bool> * definedSite; //= new vector<bool>(sizeGenome+1,false); // if there is data
vector<bool> * skipPositions; //= new vector<bool>(sizeGenome+1,false); // if the site has such a low prior that it can be overlooked
//! Method to find positions to use where there is potential for contamination
/*!
*/
void findPosToSkip(bool printPosToskip){
queue<string> queueFilesToRead = queueFilesToprocess;
vector< map<int, alleleFrequency> > freqsFromFile;
cerr<<"Finding positions to skip"<<endl;
while(!queueFilesToRead.empty()){
string freqFileNameToread = queueFilesToRead.front();
queueFilesToRead.pop();
// cerr<<"file="<<freqFileNameToread<<"\t"<<queueFilesToproc.empty()<<endl;
map<int, alleleFrequency> freqToAdd;
readMTAlleleFreq(freqFileNameToread, freqToAdd);
// cerr<<"file2="<<freqFileNameToread<<endl;
freqsFromFile.push_back(freqToAdd);
// cerr<<"file3="<<freqFileNameToread<<"\t"<<queueFilesToprocess.empty()<<endl;
}
vector<bool> definedFreqPos = vector<bool>(sizeGenome+1,true);
//detect undefined positions
for(unsigned int fileFreq=0;fileFreq<freqsFromFile.size();fileFreq++){ // each frequency file found
for(int i=0;i<sizeGenome;i++){
double freqSum=0.0;
for(unsigned int nuc=0;nuc<4;nuc++){ // b = endogenous
freqSum+=freqsFromFile[fileFreq][ infoPPos[i].posAlign ].f[nuc];
}
if(freqSum<0.99){
definedFreqPos[i]=false;
}
}
}
#ifdef DEBUGMTPOSSKIP
for(int i=0;i<sizeGenome;i++){
if(!definedFreqPos[i])
cout<<"empty\t"<<i<<"\t"<<infoPPos[i].posAlign<<"\t"<<definedFreqPos[i]<<endl;
}
#endif
// cout<<sizeGenome<<endl;
for(int i=0;i<sizeGenome;i++){
//for(int i=261;i<=262;i++){
// cout<<"Thread #"<<rankThread <<" test2 "<<i<<endl;
//cout<<"pre i"<<i<<"\t"<<endl;
// cout<<infoPPos[i].cov<<endl;
// cout<<(pos2phredgeno.find( infoPPos[i].posAlign ) == pos2phredgeno.end())<<endl;
if( (infoPPos[i].cov == 0) || //no coverage
(pos2phredgeno.find( infoPPos[i].posAlign ) == pos2phredgeno.end()) || //not found in endogenous consensus, could be due to deletion
!definedFreqPos[i] ){ //frequency files disagree
definedSite->at(i) = false;
continue;
}
definedSite->at(i) = true;
//cout<<"Thread #"<<rankThread <<" test3 "<<i<<endl;
bool hasPriorAboveThreshold=false;
//computing prior
// p(nuc1) is the prob. of endogenous * p(contaminant)
for(unsigned int fileFreq=0;fileFreq<freqsFromFile.size();fileFreq++){ // each frequency file found
for(unsigned int nuc1=0;nuc1<4;nuc1++){ // b = endogenous
for(unsigned int nuc2=0;nuc2<4;nuc2++){// c = contaminant
long double priortemp = (1-pos2phredgeno[ infoPPos[i].posAlign ].perror[nuc1]) * freqsFromFile[fileFreq][ infoPPos[i].posAlign ].f[nuc2];
// priorDiNuc->p[nuc1][nuc2] = priortemp;
#ifdef DEBUGPOS
if(i==DEBUGPOS){
cout<<"MIN i"<<i<<"\te="<<dnaAlphabet[nuc1]<<"\tc="<<dnaAlphabet[nuc2]<<"\tprior="<<priortemp<<"\tposal="<<infoPPos[i].posAlign<<"\tproblog="<<(1-pos2phredgeno[ infoPPos[i].posAlign ].perror[nuc1])<<"\tfreq="<< freqsFromFile[fileFreq][ infoPPos[i].posAlign ].f[nuc2]<<endl;
}
#endif
if( (nuc1 != nuc2) && //){
(priortemp > MINPRIOR) ){ //this is to speed up computation and only look at sites that are likely to be contaminated
// #ifdef DEBUGPOS
// cout<<"MIN i"<<i<<"\t"<<nuc1<<"\t"<<nuc2<<"\t"<<priortemp<<"\t"<<infoPPos[i].posAlign<<"\t"<<(1-pos2phredgeno[ infoPPos[i].posAlign ].perror[nuc1])<<"\t"<< freqFromFile[ infoPPos[i].posAlign ].f[nuc2]<<endl;
// #endif
#ifdef DEBUGCONTPOS
cout<<"MIN i"<<i<<"\te="<<nuc1<<"\tc="<<nuc2<<"\tprior="<<priortemp<<"\tposal="<<infoPPos[i].posAlign<<"\tproblog="<<(1-pos2phredgeno[ infoPPos[i].posAlign ].perror[nuc1])<<"\tfreq="<< freqsFromFile[fileFreq][ infoPPos[i].posAlign ].f[nuc2]<<endl;
#endif
hasPriorAboveThreshold=true;
}
}
}
}
// cout<<"Thread #"<<rankThread <<" test4 "<<i<<endl;
#ifdef DEBUGCONTPOS
if(hasPriorAboveThreshold)
cout<<endl;
#endif
//priorDiNucVec[ i ] = priorDiNuc;
// if(i==3105){ exit(1); }
skipPositions->at(i) = (!hasPriorAboveThreshold);
if(printPosToskip && !skipPositions->at(i))
cerr<<"Skipping position "<<(i+1)<<endl;
//cout<<i<<"\t"<<skipPositions->at(i)<<endl;
// if(i%1000==0)
// skipPositions->at(i) = (false); //TO REMOVE
//cout<<i<<"\t"<<skipPositions->at(i)<<endl;
}//end for each pos in the genome
cerr<<"done"<<endl;
}
//! Method called for each thread to compute contamination likelihood
/*!
*/
void *mainContaminationThread(void * argc){
int rc;
// int stackIndex;
string freqFileNameToUse;
int rankThread=0;
rc = pthread_mutex_lock(&mutexRank);
checkResults("pthread_mutex_lock()\n", rc);
threadID2Rank[*(int *)pthread_self()] = threadID2Rank.size()+1;
rankThread = threadID2Rank[*(int *)pthread_self()];
rc = pthread_mutex_unlock(&mutexRank);
checkResults("pthread_mutex_unlock()\n", rc);
checkqueue:
// stackIndex=-1;
//check stack
rc = pthread_mutex_lock(&mutexQueue);
checkResults("pthread_mutex_lock()\n", rc);
bool foundData=false;
cerr<<"Thread #"<<rankThread <<" started and is requesting data"<<endl;
//cerr<<"Thread #"<<(unsigned int)pthread_self() <<" started "<<endl;
// cout<<"Thread "<<(unsigned int)pthread_self()<<" taking mutex queue "<<endl;
if(!queueFilesToprocess.empty()){
foundData=true;
freqFileNameToUse = queueFilesToprocess.front();
queueFilesToprocess.pop();
cerr<<"Thread #"<<rankThread<<" is reading "<<freqFileNameToUse<<endl;
}
if(!foundData){
//if(doneReading){
rc = pthread_mutex_unlock(&mutexQueue);
checkResults("pthread_mutex_unlock()\n", rc);
cerr<<"Thread #"<<rankThread<<" is done"<<endl;
return NULL;
// }else{
// sleep(1);
// goto checkqueue;
// }
}else{
//release stack
rc = pthread_mutex_unlock(&mutexQueue);
checkResults("pthread_mutex_unlock()\n", rc);
}
//////////////////////////////////////////////////////////////
// BEGIN COMPUTATION //
//////////////////////////////////////////////////////////////
vector<contaminationEstimate> toAddToLog;
long double contaminationRate=0.0;
map<int, alleleFrequency> freqFromFile;
readMTAlleleFreq(freqFileNameToUse, freqFromFile);
//////////////////////
//pre-computations ///
//////////////////////
cerr<<"Thread #"<<rankThread <<" started pre-computations"<<endl;
// map<int, diNucleotideProb> priorDiNucVec;
// map<int, vector<diNucleotideProb> > probConsVec;
// map<int, vector<diNucleotideProb> > probContVec;
vector< diNucleotideProb * > priorDiNucVec;
vector< vector< diNucleotideProb * > * > probEndoVec;
vector< vector< diNucleotideProb * > * > probContVec;
vector< vector< bool > * > strandVec;
priorDiNucVec.resize(sizeGenome+1);
probEndoVec.resize(sizeGenome+1);
probContVec.resize(sizeGenome+1);
strandVec.resize(sizeGenome+1);
// vector<bool> * definedSite = new vector<bool>(sizeGenome+1,false); // if there is data
// vector<bool> * skipPositions = new vector<bool>(sizeGenome+1,false); // if the site has such a low prior that it can be overlooked
for(int i=0;i<sizeGenome;i++){
//for(int i=261;i<=262;i++){
// cout<<"Thread #"<<rankThread <<" test2 "<<i<<endl;
if( !definedSite->at(i) ){
continue;
}
if( skipPositions->at(i) ){
continue;
}
diNucleotideProb * priorDiNuc = 0;
try{
priorDiNuc = new diNucleotideProb;
}catch( char * str ) {
cout << "Exception raised: " << str << endl;
}
//cout<<"Thread #"<<rankThread <<" test3 "<<i<<endl;
//bool hasPriorAboveThreshold=false;
//computing prior
// p(nuc1) is the prob. of endogenous * p(contaminant)
for(unsigned int nuc1=0;nuc1<4;nuc1++){ // b = endogenous
for(unsigned int nuc2=0;nuc2<4;nuc2++){// c = contaminant
long double priortemp = (1-pos2phredgeno[ infoPPos[i].posAlign ].perror[nuc1]) * freqFromFile[ infoPPos[i].posAlign ].f[nuc2];
priorDiNuc->p[nuc1][nuc2] = priortemp;
// if(i==3105){
//cout<<"i"<<i<<"\t"<<nuc1<<"\t"<<nuc2<<"\t"<<priortemp<<"\t"<<(1-pos2phredgeno[ infoPPos[i].posAlign ].perror[nuc1])<<"\t"<<freqFromFile[ infoPPos[i].posAlign ].f[nuc2]<<"\t"<<infoPPos[i].posAlign<<endl;
// }
#ifdef DEBUGPOS
if(i==DEBUGPOS){
cout<<"MIN i"<<i<<"\te="<<dnaAlphabet[nuc1]<<"\tc="<<dnaAlphabet[nuc2]<<"\tprior="<<priortemp<<"\tposal="<<infoPPos[i].posAlign<<"\tproblog="<<(1-pos2phredgeno[ infoPPos[i].posAlign ].perror[nuc1])<<"\tfreq="<< freqFromFile[ infoPPos[i].posAlign ].f[nuc2]<<endl;
}
#endif
}//end nuc2
}//end nuc1
// cout<<"Thread #"<<rankThread <<" test4 "<<i<<endl;
// #ifdef DEBUGCONTPOS
// if(hasPriorAboveThreshold)
// cout<<endl;
// #endif
priorDiNucVec[ i ] = priorDiNuc;
// if(i==3105){ exit(1); }
// skipPositions->at(i) = (!hasPriorAboveThreshold);
vector<diNucleotideProb *> * probEndoVecToAdd = new vector<diNucleotideProb *>();
vector<diNucleotideProb *> * probContVecToAdd = new vector<diNucleotideProb *>();
vector<bool > * strandVecToAdd = new vector<bool>();
// continue;
for(unsigned int k=0;k<infoPPos[i].readsVec.size();k++){ //for every read at that position
//cout<<"Thread #"<<rankThread <<" test5\t"<<i<<"\t"<<k<<endl;
diNucleotideProb * probEndoDinuc=0;
diNucleotideProb * probContDinuc=0;
try {
probEndoDinuc = new diNucleotideProb;
probContDinuc = new diNucleotideProb;
}catch( char * str ) {
cout << "Exception raised: " << str << endl;
}
//cout<<"Thread #"<<rankThread <<" test6\t"<<i<<"\t"<<k<<endl;
int baseIndex = baseResolved2int(infoPPos[i].readsVec[k].base);
int qual = infoPPos[i].readsVec[k].qual;
int dist5p = infoPPos[i].readsVec[k].dist5p;
int dist3p = infoPPos[i].readsVec[k].dist3p;
//int mapq = infoPPos[i].readsVec[k].mapq;
probSubstition * probSubMatchToUseEndo = &defaultSubMatch ;
probSubstition * probSubMatchToUseCont = &defaultSubMatch ; //leave it that way, we only allow deamination for the endogenous only
//consider deamination to be possible for the endogenous only
if(dist5p <= (int(sub5p.size()) -1)){
probSubMatchToUseEndo = &sub5p[ dist5p ];
}
if(dist3p <= (int(sub3p.size()) -1)){
probSubMatchToUseEndo = &sub3p[ dist3p ];
}
//we have substitution probabilities for both... take the closest
if(dist5p <= (int(sub5p.size()) -1) &&
dist3p <= (int(sub3p.size()) -1) ){
if(dist5p < dist3p){
probSubMatchToUseEndo = &sub5p[ dist5p ];
}else{
probSubMatchToUseEndo = &sub3p[ dist3p ];
}
}
#ifdef DEBUGPOS
if(i==DEBUGPOS){
for(int sub=0;sub<16;sub++){ // b = endogenous
cout<<sub<<"\t"<<probSubMatchToUseEndo->s[sub]<<endl;
}
}
#endif
//iterate over each possible endogenous and contaminant base
for(int nuc1=0;nuc1<4;nuc1++){ // b = endogenous
for(int nuc2=0;nuc2<4;nuc2++){// c = contaminant
//skip when contaminant is the endogenous
// if(nuc1 == nuc2)
// continue;
////////////////////
// Endogenous base /
////////////////////
// model*4 + obs
int dinucIndexEndo = nuc1*4+baseIndex;
if(infoPPos[i].readsVec[k].isReversed)
dinucIndexEndo = (3-nuc1)*4+(3-baseIndex);
#ifdef DEBUGPOS
if(i==DEBUGPOS){
if(infoPPos[i].readsVec[k].isReversed){
dinucIndexEndo = (3-nuc1)*4+(3-baseIndex);
cout<<dnaAlphabet[nuc1]<<"\t"<<dnaAlphabet[baseIndex]<<"\t"<<dinucIndexEndo<<"\t"<<probSubMatchToUseEndo->s[dinucIndexEndo]<<endl;
}else{
cout<<dnaAlphabet[nuc1]<<"\t"<<dnaAlphabet[baseIndex]<<"\t"<<dinucIndexEndo<<"\t"<<probSubMatchToUseEndo->s[dinucIndexEndo]<<endl;
}
}
// if(i==DEBUGPOS){
// cout<<dist5p<<"\t"<<dist3p<<endl;
// }
#endif
// (1-e) * p(sub|1-e) + (e) * p(sub|1-e)
long double probEndo=likeMatchProb[qual] * (probSubMatchToUseEndo->s[dinucIndexEndo] ) + (1.0 - likeMatchProb[qual])*(illuminaErrorsProb.s[dinucIndexEndo]);
///////////////////
//Contaminant base/
///////////////////
// model*4 + obs
int dinucIndexCont = nuc2*4+baseIndex;
if(infoPPos[i].readsVec[k].isReversed)
dinucIndexCont = (3-nuc2)*4+(3-baseIndex);
// (1-e) * p(sub|1-e) + (e) * p(sub|1-e)
long double probCont=likeMatchProb[qual] * (probSubMatchToUseCont->s[dinucIndexCont] ) + (1.0 - likeMatchProb[qual])*(illuminaErrorsProb.s[dinucIndexCont]);
probEndoDinuc->p[nuc1][nuc2] = probEndo;
probContDinuc->p[nuc1][nuc2] = probCont;
}
}//end for each di-nucleotide
probEndoVecToAdd->push_back(probEndoDinuc);
probContVecToAdd->push_back(probContDinuc);
strandVecToAdd->push_back(infoPPos[i].readsVec[k].isReversed);
} //end for each read at that position
// cout<<"Thread #"<<rankThread <<" test3\t"<<probEndoVec.size()<<"\t"<<probContVec.size()<<endl;
//cout<<"adding vector at pos "<<i<<endl;
probEndoVec[i] = probEndoVecToAdd;
probContVec[i] = probContVecToAdd;
strandVec[i] = strandVecToAdd;
// cout<<"Thread #"<<rankThread <<" test4"<<endl;
} //end for each position in the genome
cerr<<"Thread #"<<rankThread <<" is done with pre-computations"<<endl;
for(contaminationRate=0.0;contaminationRate<topCont;contaminationRate+=stepContEst){
long double logLike=0.0;
#ifdef DEBUGPOS
for(int i=DEBUGPOS;i<=DEBUGPOS;i++){
#else
for(int i=0;i<sizeGenome;i++){
#endif
if( !definedSite->at(i) ){//site is not defined
continue;
}
if( skipPositions->at(i) ){//position has a tiny prior on contamination and can be safely skipped
continue;
}
if((infoPPos[i].cov == 0) || //no coverage
(pos2phredgeno.find( infoPPos[i].posAlign ) == pos2phredgeno.end()) ){ //not found in endogenous, could be due to deletion
// skipPositions->at(i) ){ //position has a tiny prior on contamination and can be safely skipped
continue;
}
#ifdef DEBUGPOSEACHREAD
cout<<"after i"<<i<<"\t"<<infoPPos[i].posAlign<<endl;
#endif
// continue;
for(unsigned int k=0;k<infoPPos[i].readsVec.size();k++){ //for every read at that position
//for(unsigned int k=0;k<1;k++){ //for every read at that position
long double mappedProb =0.0; //initialized
long double misappedProb=0.25;
int mapq = infoPPos[i].readsVec[k].mapq;
//iterate over each possible endogenous and contaminant base
for(int nuc1=0;nuc1<4;nuc1++){ // b = endogenous
for(int nuc2=0;nuc2<4;nuc2++){// c = contaminant
//skip when contaminant is the endogenous
// if(nuc1 == nuc2)
// continue;
long double probForDinuc = priorDiNucVec[i]->p[nuc1][nuc2]*
( ( (1.0-contaminationRate) * probEndoVec[i]->at(k)->p[nuc1][nuc2]) +
( (contaminationRate) * probContVec[i]->at(k)->p[nuc1][nuc2] ) ) ;
// long double probForDinuc = priorDiNucVec[i]->p[nuc1][nuc2]*
// ( ( (1.0-contaminationRate) * probEndoVec[i]->at(k)->p[nuc1][nuc2]) +
// ( (contaminationRate) * probContVec[i]->at(k)->p[nuc1][nuc2] ) ) ;
mappedProb+=probForDinuc;
#ifdef DEBUGPOSEACHREAD
if(i==DEBUGPOS){
if(0){
cout<<endl<<"k="<< k <<"\ti="<<i<<"\te="<<dnaAlphabet[nuc1]<<"\tc="<<dnaAlphabet[nuc2]<<endl;
cout<<"c "<<contaminationRate<<endl;
cout<<"base read "<<infoPPos[i].readsVec[k].base<<endl;
cout<<"base qual "<<infoPPos[i].readsVec[k].qual<<endl;
cout<<"prior "<<priorDiNucVec[i]->p[nuc1][nuc2]<<endl;
cout<<"probCont "<<probContVec[i]->at(k)->p[nuc1][nuc2]<<endl;
cout<<"probEndo "<<probEndoVec[i]->at(k)->p[nuc1][nuc2]<<endl;
cout<<"probForDinuc "<<probForDinuc<<endl;
}else{
//if(priorDiNucVec[i].p[nuc1][nuc2]>0.9){
cout.precision(15);
cout<<"k="<< k <<"\ti="<<i<<"\te="<<dnaAlphabet[nuc1]<<"\tc="<<dnaAlphabet[nuc2]<<"\tbase="<<infoPPos[i].readsVec[k].base<<"\tqual=" <<infoPPos[i].readsVec[k].qual<<"\tprior="<<priorDiNucVec[i]->p[nuc1][nuc2]<<"\tp(e)="<<probEndoVec[i]->at(k)->p[nuc1][nuc2]<<"\tp(c)="<<probContVec[i]->at(k)->p[nuc1][nuc2]<<"\tp="<<probForDinuc<<"\tp(ma)="<<mappedProb<<"\t"<<mapq<<"\te="<<dnaAlphabet[nuc1]<<"\tc="<<dnaAlphabet[nuc2]<<"\t"<<strandVec[i]->at(k)<<endl;
//}
}
}
#endif
}
}//end for each di-nucleotide
// m = prob. of mismapping
// (1-m) * p(data|mapped) + m * p(data|mismapped)
long double pread = (probMapping[mapq]*(mappedProb) + probMismapping[mapq]*(misappedProb) );
// cout<<k<<"\t"<<pread<<endl;
//cout<<pread<<endl;
// cout<<probContVec[i][k].p[nuc1][nuc2]<<endl;
// cout<<probEndoVec[i][k].p[nuc1][nuc2]<<endl;
//exit(1);
logLike += log ( pread );
#ifdef DEBUGPOSEACHREAD
cout<<"pread\t"<<pread<<"\tloglike="<< logLike <<"\tcont="<<contaminationRate<<endl;
if(i==DEBUGPOS){
//cout<<"-------------"<<endl;
}
#endif
} //end for each read at that position
// cout<<"logLike "<<i<<"\t"<<logLike<<endl;
#ifdef DEBUGPOS
// if(i==DEBUGPOS){
// exit(1);
// }
#endif
} //end for each position in the genome
// exit(1);
//cout.precision(15);
//cout<<freqFileNameToUse<<"\t"<<contaminationRate<<"\t"<<logLike<<endl;
contaminationEstimate cse;
cse.filename = freqFileNameToUse ;
cse.contaminationRate = contaminationRate ;
cse.logLike = logLike ;
//toAddToLog+=(""+freqFileNameToUse+"\t"+stringify(contaminationRate)+"\t"+stringify(logLike)+"\n");
toAddToLog.push_back(cse);
}//end each contaminationRate
// }//end for each cont freq file
cerr<<"Thread #"<<rankThread <<" is done with computations"<<endl;
//////////////////////////////////////////////////////////////
// END COMPUTATION //
//////////////////////////////////////////////////////////////
// cout<<"done deleting"<<endl;
for(unsigned i=0;i<priorDiNucVec.size();i++){
//cout<<"i1 delete"<<i<<endl;
if(i<definedSite->size() &&
!definedSite->at(i) ){
continue;
}
if(i<skipPositions->size() &&
skipPositions->at(i) ){
continue;
}
///cout<<"i2 delete"<<i<<endl;
delete priorDiNucVec[i];
for(unsigned j=0;j<probEndoVec[i]->size();j++){
// cout<<"j "<<j<<endl;
delete probEndoVec[i]->at(j);
delete probContVec[i]->at(j);
}
delete probEndoVec[i];
delete probContVec[i];
}
//COUNTERS
rc = pthread_mutex_lock(&mutexCounter);
checkResults("pthread_mutex_lock()\n", rc);
outputToPrint.push_back(toAddToLog);
rc = pthread_mutex_unlock(&mutexCounter);
checkResults("pthread_mutex_unlock()\n", rc);
cerr<<"Thread #"<<rankThread <<" is re-starting"<<endl;
goto checkqueue;
cerr<<"Thread "<<rankThread<<" ended "<<endl;
return NULL;
}
//unsigned int posFound;
//vector<positionInfo> * positionsInfoFound;
// map<string, map<unsigned int,contaminationInfo> > contFreq;
class MyPileupVisitor : public PileupVisitor {
public:
MyPileupVisitor(const RefVector& references, Fasta * fastaReference,vector<positionInformation> * infoPPos,int sizeGenome,bool ignoreMQ)
: PileupVisitor()
, m_references(references)
, m_fastaReference(fastaReference)
, m_infoPPos(infoPPos)
, sizeGenome(sizeGenome)
, ignoreMQ(ignoreMQ)
{
}
~MyPileupVisitor(void) { }
// PileupVisitor interface implementation
public:
// prints coverage results ( tab-delimited )
void Visit(const PileupPosition& pileupData) {
char referenceBase = 'N';
unsigned int posAlign = pileupData.Position+1;
int posVector=int(pileupData.Position)%sizeGenome;
// cout<<posVector<<endl;
// cout<<endl<<"pos = "<<posAlign<<"\t"<<posVector;
if( (posAlign%100) == 0){
//cerr<<"pos = "<<posAlign<<endl;
}
//for some reason, we have to do -1 on the .Position
if ( !m_fastaReference->GetBase(pileupData.RefId, posAlign-1, referenceBase ) ) {
cerr << "bamtools convert ERROR: pileup conversion - could not read reference base from FASTA file" << endl;
exit(1);
}
//Like in the endogenous calling, there are 3 possibilities, except here we only use 3) :
//1) There is a insertion in the sample (or deletion in the reference)
//2) There is a deletion in the sample (or insertion in the reference)
//3) There is potentially a variation of a single nucleotide
//insertion in the reads/deletion in the reference, skipping
for(unsigned int i=0;i<pileupData.PileupAlignments.size();i++){
if( !pileupData.PileupAlignments[i].IsCurrentDeletion &&
pileupData.PileupAlignments[i].IsNextInsertion &&
(pileupData.PileupAlignments[i].InsertionLength>0)){
continue;
}
}
//deletion in the reads/insertion in the reference, skipping
unsigned int numReads=0;
for(unsigned int i=0;i<pileupData.PileupAlignments.size();i++){
if( pileupData.PileupAlignments[i].IsCurrentDeletion &&
pileupData.PileupAlignments[i].IsNextInsertion &&
(pileupData.PileupAlignments[i].InsertionLength == 0)){
continue;
//cout<<"del"<<endl;
//m_infoPPos->at(posVector).numDel++;
}
}
// typedef struct {
// vector<singleRead> readsVec;
// int cov;
// } positionInformation;
for(unsigned int i=0;i<pileupData.PileupAlignments.size();i++){
// cerr<<pileupData.PileupAlignments[i].Alignment.Name<<endl;
//skip deletion in the reads/insertion in the reference
if( pileupData.PileupAlignments[i].IsCurrentDeletion &&
pileupData.PileupAlignments[i].IsNextInsertion ){
continue;
}
char b = pileupData.PileupAlignments[i].Alignment.QueryBases[pileupData.PileupAlignments[i].PositionInAlignment];
char q = pileupData.PileupAlignments[i].Alignment.Qualities[pileupData.PileupAlignments[i].PositionInAlignment]-offsetQual;
int m = int(pileupData.PileupAlignments[i].Alignment.MapQuality);
if(b == 'N') //uninformative anyway...
continue;
singleRead sr;
sr.base=b;
sr.qual=int(q);
sr.mapq=int(m);
sr.dist5p=-1;
sr.dist3p=-1;
sr.isReversed= pileupData.PileupAlignments[i].Alignment.IsReverseStrand();
if( sr.isReversed ){
sr.dist5p = pileupData.PileupAlignments[i].Alignment.QueryBases.size() - pileupData.PileupAlignments[i].PositionInAlignment-1;
sr.dist3p = pileupData.PileupAlignments[i].PositionInAlignment;
}else{
sr.dist5p = pileupData.PileupAlignments[i].PositionInAlignment;
sr.dist3p = pileupData.PileupAlignments[i].Alignment.QueryBases.size() - pileupData.PileupAlignments[i].PositionInAlignment-1;
}
m_infoPPos->at(posVector).cov++;
//Add mapq
m_infoPPos->at(posVector).mapqAvg += pow(10.0, (long double)(pileupData.PileupAlignments[i].Alignment.MapQuality)/ (long double)(-10.0) );
m_infoPPos->at(posVector).readsVec.push_back(sr);
// numReads++;
if(numReads >= MAXCOV){
break;
}
}//end each read
// m_infoPPos->at(posVector).mapqAvg = m_infoPPos->at(posVector).mapqAvg/double(m_infoPPos->at(posVector).cov);
// m_infoPPos->at(posVector).mapqAvg = -10.0*( log( m_infoPPos->at(posVector).mapqAvg )/log(10.0) );
// m_infoPPos->at(posVector).refBase = referenceBase;
//cout<<"pv = "<<posVector<<"\tpa ="<<posAlign<<endl;
m_infoPPos->at(posVector).posAlign = int(pileupData.Position+1)%sizeGenome; //posVector;//posAlign;
// m_infoPPos->at(posVector).skipPosition = false;
}
private:
RefVector m_references;
Fasta * m_fastaReference;
vector<positionInformation> * m_infoPPos;
int sizeGenome;
bool ignoreMQ;
// ostream* m_out;
};
int main (int argc, char *argv[]) {
int numberOfThreads=1;
// string outSeq = "/dev/stdout";
string outLog = "/dev/stdout";
// string nameMT = "MT";
string fileFreq = "alleleFreqMT/1000g/freqHumans.dat";
// ofstream outSeqFP ;
ofstream outLogFP;
// int minQual=0;
bool ignoreMQ=false;
string line;
/////////////////////////////////////////
// INITIALIZE SCORES //
/////////////////////////////////////////
for(int i=0;i<2;i++){
likeMatch[i] = log1p( -pow(10.0,2.0/-10.0) ) /log(10);
likeMismatch[i] = log ( pow(10.0,2.0/-10.0)/3.0 )/log(10);
likeMatchProb[i] = 1.0-pow(10.0,2.0/-10.0) ;
likeMismatchProb[i] = pow(10.0,2.0/-10.0)/3.0 ;
}
//Computing for quality scores 2 and up
for(int i=2;i<MAXMAPPINGQUAL;i++){
likeMatch[i] = log1p( -pow(10.0,i/-10.0) ) /log(10);
likeMismatch[i] = log ( pow(10.0,i/-10.0)/3.0 )/log(10);
likeMatchProb[i] = 1.0-pow(10.0,i/-10.0);
likeMismatchProb[i] = pow(10.0,i/-10.0)/3.0;
}
//Adding mismapping probability
for(int m=0;m<MAXMAPPINGQUAL;m++){
//m = prob of mismapping
long double incorrectMappingProb = pow(10.0,m/-10.0); //m
long double correctMappingProb = 1.0-pow(10.0,m/-10.0); //1-m
probMapping[m] = correctMappingProb; //1-m
probMismapping[m] = incorrectMappingProb; //m
#ifdef DEBUG1
cerr<<"m\t"<<m<<"\t"<<incorrectMappingProb<<"\t"<<correctMappingProb<<endl;
#endif
for(int i=0;i<2;i++){
likeMatchMQ[m][i] = log( correctMappingProb*(1.0-pow(10.0,2.0/-10.0) ) + incorrectMappingProb/4.0 )/log(10);
likeMismatchMQ[m][i] = log( correctMappingProb*( pow(10.0,2.0/-10.0)/3.0) + incorrectMappingProb/4.0 )/log(10);
likeMatchProbMQ[m][i] = correctMappingProb*(1.0-pow(10.0,2.0/-10.0) ) + incorrectMappingProb/4.0;
likeMismatchProbMQ[m][i] = correctMappingProb*( pow(10.0,2.0/-10.0)/3.0) + incorrectMappingProb/4.0;
}
//Computing for quality scores 2 and up
for(int i=2;i<MAXMAPPINGQUAL;i++){
// (1-m)(1-e) + m/4 = 1-m-e+me +m/4 = 1+3m/4-e+me
likeMatchMQ[m][i] = log( correctMappingProb*(1.0-pow(10.0,i/-10.0) ) + incorrectMappingProb/4.0 )/log(10);
// (1-m)(e/3) + m/4 = e/3 -me/3 + m/4
likeMismatchMQ[m][i] = log( correctMappingProb*( pow(10.0,i/-10.0)/3.0) + incorrectMappingProb/4.0 )/log(10);
likeMatchProbMQ[m][i] = correctMappingProb*(1.0-pow(10.0,i/-10.0) ) + incorrectMappingProb/4.0;
likeMismatchProbMQ[m][i] = correctMappingProb*( pow(10.0,i/-10.0)/3.0) + incorrectMappingProb/4.0;
}
#ifdef DEBUG1
for(int i=0;i<MAXMAPPINGQUAL;i++){
cerr<<"m\t"<<m<<"\t"<<i<<"\t"<<likeMatchMQ[m][i]<<"\t"<<likeMismatchMQ[m][i]<<"\t"<<likeMatchProbMQ[m][i]<<"\t"<<likeMismatchProbMQ[m][i]<<endl;
}
#endif
}
/////////////////////////////////////////
// PARSING ARGUMENTS //
/////////////////////////////////////////
// return 1;
string errFile = getCWD(argv[0])+"illuminaProf/error.prof";
string deam5pfreq = getCWD(argv[0])+"deaminationProfile/none.prof";
string deam3pfreq = getCWD(argv[0])+"deaminationProfile/none.prof";
bool verbose = false;