forked from grenaud/schmutzi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
contDeam.cpp
2085 lines (1522 loc) · 67.8 KB
/
contDeam.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
/*
* mitonchondrialDeam
* Date: Mar-26-2014
* Author : Gabriel Renaud gabriel.reno [at sign here ] gmail.com
*
*/
#if defined(__CYGWIN__)
#define atanl(X) atan(X)
#define logl(X) log(X)
#define sqrtl(X) sqrt(X)
#endif
//TODO
// #define DEBUG1
// #define DEBUG2
// #define DEBUG3
// #define DEBUGPRIORENDO
// CODE ORGANIZATION
//
// main()
// call initScores() to initialize probability scores
// read arguments
// read error and deamnination profiles
// read fasta reference
// call iterateOverReads() to populate infoPPos using reads from the BAM file
// call printLogAndGenome() to print the log and genome using infoPPos
// if a length or deamination prior is used:
// call computePriorOnReads() to compute the prior on being endogenous or contaminant for each read using deamination/length using the endogenous base in iterateOverReads
// re-call iterateOverReads() to incorporate the prior on being endogenous
// re-call printLogAndGenome() to print the final genome.
//
// computePriorOnReads(): Used to compute probability that a given read is endogenous
// if deamination is used
// compute likelihood for illumina error
// compute likelihood for deamination
// if length is used
// compute pdf for endogenous distribution
// compute pdf for contaminant distribution
// compute prob(endogenous) using the two tests + contamination prior and store read2endoProb
//
// iterateOverReads(): Use to call MyPileupVisitor::visit() and populated infoPPos
// clear and initialize infoPPos
// open BAM file and iterate over reads using an MyPileupVisitor object. The Visit() subroutine will be called for each position
//
// MyPileupVisitor::Visit() : called for a single position in the sorted BAM file
// compute average mapping quality
// Compute likelihood of variants:
//
// For insertion in the reads/deletion in the reference:
// Iterate over each read to get all possible inserts
// Initialize log likelihood for all inserts (including the no insert empty string) to zero
// if we assume a single contaminant
// store likelihood for all pairs (endo,cont) of inserts in insertion2loglikeEndoCont
// if we do not assume a single contaminant
// store likelihood in insertion2loglike
//
// For deletion in the sample (or insertion in the reference)
// Iterate over each read
// if we assume a single contaminant
// Compute llikDeletionBoth : likelihood that both endo. and cont. have an deletion
// Compute llikDeletionCont : likelihood that only the cont. (not endo.) has an deletion
// Compute llikDeletionEndo : likelihood that only the endo. (not cont.) has an deletion
// Compute llikDeletionNone : likelihood that neither the endo. nor the cont. have an deletion
// if we do not assume a single contaminant
// Compute llikDeletion for the likelihood of having a deletion
// Compute llikNoDeletion for the likelihood of not having a deletion
//
// For single nucleotides
// Iterate over each read
// Compute the probability of deamination for that given base given the distance to the 5p and 3p end
// if we assume a single contaminant
// Compute the likelihood for every pair of nucleotide (endo.,cont.) and store it in likeBaseNoindelCont[endo. nuc][cont. nuc]
// if we do not assume a single contaminant
// Compute the likelihood for every endogenous nucleotide and store it likeBaseNoindel[endo nuc]
//
// printLogAndGenome(): Subroutine that uses infoPPos to generate the genome and the log file
// For each position on the mitonchondria
// Call deletionInSample() to detect deletions in the endogenous/contaminant/insertions in the reference
// Call noCoverage to skip positions with no coverage
// Call callSingleNucleotide to call the endogenous (or contaminant)
// Call insertionInSample to call insertions after the base
//
//
#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 <math.h>
#include "utils.h"
#include "miscfunc.h"
#include "ReconsReferenceBAM.h"
using namespace BamTools;
using namespace std;
#define MAXCOV 5000
#define INDELERRORPROB 1.0e-5 // http://genomebiology.com/2011/12/11/R112
#define LOGRATIOFORINDEL 50 //beyond that difference in log, a indel will be called
#define MAXMAPPINGQUAL 257 // maximal mapping quality, should be sufficient as mapping qualities are encoded using 8 bits
#define MIN(a,b) (((a)<(b))?(a):(b))
const long double PI = atanl(1.0L)*4;
//! Computes log of probability density function
/*!
Computes the log base 10 of pdf(x)
\param mu The mean (location)
\param sigma The variance (scale)
\param x The value for which we want the pdf
\return The values of log base 10 of (pdf(x))
*/
long double logcomppdf(long double mu,long double sigma,long double x){
if(x==0){
x=1.0;
}
long double two = 2.0;
long double exponent = log(x) - mu;
exponent *= -exponent;
exponent /= two * sigma * sigma;
long double result = exponent/logl(10);
result -= logl(sigma * sqrtl(two * PI) * x)/logl(10);
return result;
}
// typedef struct {
// double likeBaseNoindel[4];
// int covPerBase[4];
// double mapqAvg;
// int numDel;
// vector<string> insertionRight;
// int cov;
// } positionInformation;
char offsetQual=33;
double likeMatch[MAXMAPPINGQUAL];
double likeMismatch[MAXMAPPINGQUAL];
double likeMatchMQ[MAXMAPPINGQUAL][MAXMAPPINGQUAL];
double likeMismatchMQ[MAXMAPPINGQUAL][MAXMAPPINGQUAL];
double likeMatchProb[MAXMAPPINGQUAL];
double likeMismatchProb[MAXMAPPINGQUAL];
double likeMatchProbMQ[MAXMAPPINGQUAL][MAXMAPPINGQUAL];
double likeMismatchProbMQ[MAXMAPPINGQUAL][MAXMAPPINGQUAL];
double probMapping[MAXMAPPINGQUAL];
double probMismapping[MAXMAPPINGQUAL];
double probLengthEndo[1000];
probSubstition illuminaErrorsProb;
vector<probSubstition> sub5p;
vector<probSubstition> sub3p;
probSubstition defaultSubMatch;
string dnaAlphabet="ACGT";
map<int, PHREDgeno> pos2phredgeno;
map<string, long double > read2endoProb; //map seq id to probability that the read is endogenous using a deamination model
long double read2endoProbInit=false;
template <typename T>
inline string arrayToStringInt(const T toPrint[] ,const int size,const string separator=","){
if(size == 0){
return "";
}
string toReturn="";
for(int i=0;i<(size-1);i++){
toReturn+=(stringify(int(toPrint[i]))+separator);
}
toReturn+=(stringify(int(toPrint[ size -1 ])));
return toReturn;
}
inline void transformRef(char * refeBase,char * readBase){
if( (*refeBase) == 'M'){
(*refeBase)=(*readBase);
}
}
inline bool hasIinfirstOrLastTwoBases(const string & reconstructedReference){
if(reconstructedReference.length() <= 4){
cerr<<"ERROR read has length less than 4 bp"<<endl;
exit(1);
}
for(unsigned int j=0;j<2;j++){
if(reconstructedReference[j] == 'I')
return true;
}
for(unsigned int j=(reconstructedReference.length()-2);
j<(reconstructedReference.length());
j++){
if(reconstructedReference[j] == 'I')
return true;
}
return false;
}
inline bool deletionsNextToTwo(const BamAlignment * al){
vector<int> lengthOfNonDels;
vector<CigarOp> cigarData=al->CigarData;
bool foundDel=false;
for(unsigned int i=0;i<cigarData.size();i++){
if(cigarData[i].Type == 'D'){
foundDel=true;
}else{
lengthOfNonDels.push_back(cigarData[i].Length);
}
}
if(foundDel){
if(lengthOfNonDels[0]<=2)
return true;
if(lengthOfNonDels[ lengthOfNonDels.size() -1 ]<=2)
return true;
}
return false;
}
//checks for an 'R' or 'S' for soft clip
inline bool hasBadCharacter(const string & reconstructedReference){
for(unsigned int j=0;j<(reconstructedReference.length());j++){
if(reconstructedReference[j] == 'R' ||
reconstructedReference[j] == 'S' ){
return true;
}
}
return false;
}
// if we skip the alignment and cannot get a deamination for this read
inline bool skipAlign(const string & reconstructedReference,const BamAlignment * al,unsigned int * skipped){
if(hasBadCharacter(reconstructedReference)){
(*skipped)++;
return true;
}
if(hasIinfirstOrLastTwoBases(reconstructedReference)){
(*skipped)++;
return true;
}
if(deletionsNextToTwo(al)){
(*skipped)++;
return true;
}
return false;
}
// typedef struct {
// char ref;
// char alt;
// unsigned int pos;
// double contFreq;
// unsigned char cov;
// unsigned char refCov;
// unsigned char altCov;
// // unsigned int ;
// bool refOrAlt[MAXCOV]; //ref = false, alt=true
// unsigned char mapq[MAXCOV];
// unsigned char quals[MAXCOV];;
// unsigned char dist5p[MAXCOV];;
// unsigned char dist3p[MAXCOV];;
// } positionInfo;
//unsigned int posFound;
//vector<positionInfo> * positionsInfoFound;
// map<string, map<unsigned int,contaminationInfo> > contFreq;
//! Object to iterate over read at a single position
/*!
This object is called by iterateOverReads() and the Visit() method is used for each position
*/
class MyPileupVisitor : public PileupVisitor {
public:
MyPileupVisitor(const RefVector& references,
Fasta * fastaReference,
vector<singlePosInfo> * infoPPos,
const int sizeGenome,
const bool ignoreMQ,
const long double contaminationPrior,
const bool singleCont,
const bool specifiedReference)
: PileupVisitor()
, m_references(references)
, m_infoPPos(infoPPos)
, sizeGenome(sizeGenome)
, ignoreMQ(ignoreMQ)
, contaminationPrior(contaminationPrior)
, singleCont(singleCont)
, specifiedReference(specifiedReference)
{
if(specifiedReference)
m_fastaReference=fastaReference;
}
~MyPileupVisitor(void) { }
// PileupVisitor interface implementation
public:
// prints coverage results ( tab-delimited )
//! Method to visit each read for each position in the BAM alignment
/*!
This methods iterates over each read and considers 3 cases:
1) There is a insertion in the sample (or deletion in the reference)
Store all possible inserts in allInserts
When we assume that there is a single contaminant:
Compute the likelihood in insertion2loglikeEndoCont for each 4 possibilities:
1: Both the endogenous and contaminant have the insertion
2: The endogenous has the insertion but not the contaminant
3: The contaminant has the insertion but not the endogenous
4: None have it
When we cannot assume that there is a single contaminant:
Compute the likelihood of an insert versus not having it and store it in insertion2loglike
2) There is a deletion in the sample (or insertion in the reference)
When we assume that there is a single contaminant:
Compute the likelihood for each four possibilities:
1: llikDeletionBoth When both the endogenous and the contaminant have the deletion
2: llikDeletionEndo When only the endogenous has the deletion
3: llikDeletionCont When only the contaminant has the deletion
4: llikDeletionNone When none have the deletion
When we cannot assume that there is a single contaminant:
Compute the likelihood that there is a deletion versus not having a deletion, store it in llikDeletion and llikNoDeletion.
3) There is potentially a variation of a single nucleotide
When we assume that there is a single contaminant:
Compute the likelihood for each 16 (4x4) possible nucleotide pairs and store in likeBaseNoindelCont as [nuc endogenous][nuc contaminant]
When we cannot assume that there is a single contaminant:
Compute the likelihood for each 4 possibilties and store it in likeBaseNoindel.
*/
void Visit(const PileupPosition& pileupData) {
//cout<<"visit"<<endl;
char referenceBase = 'N';
unsigned int posAlign = pileupData.Position+1;
int posVector=int(pileupData.Position)%sizeGenome;
// if( (posAlign%100) == 0){
// cerr<<"pos = "<<posAlign<<endl;
// }
//cout<<endl<<"pos = "<<posAlign<<"\t"<<posVector;
//for some reason, we have to do -1 on the .Position
if(specifiedReference){
if ( !m_fastaReference->GetBase(pileupData.RefId, posAlign-1, referenceBase ) ) {
cerr << "bamtools convert ERROR: pileup conversion - could not read reference base from FASTA file at chr "<<pileupData.RefId<<" position "<<(posAlign-1) << endl;
exit(1);
}
}
//cout<<"\t"<<referenceBase<<"\t"<<endl;
for(unsigned int i=0;i<pileupData.PileupAlignments.size();i++){
m_infoPPos->at(posVector).cov++;
//Add mapq
m_infoPPos->at(posVector).mapqAvg += pow(10.0, (long double)(pileupData.PileupAlignments[i].Alignment.MapQuality)/-10.0);
// cout<<pileupData.PileupAlignments[i].Alignment.Name<<"\t"<<
// pileupData.PileupAlignments[i].IsCurrentDeletion<<"\t"<<
// pileupData.PileupAlignments[i].IsNextDeletion<<"\t"<<
// pileupData.PileupAlignments[i].IsNextInsertion<<"\t"<<
// pileupData.PileupAlignments[i].DeletionLength<<"\t"<<
// pileupData.PileupAlignments[i].InsertionLength<<"\t"<<
// pileupData.PileupAlignments[i].IsSegmentBegin<<"\t"<<
// pileupData.PileupAlignments[i].IsSegmentEnd<<"\t"<<
// endl;
}
m_infoPPos->at(posVector).mapqAvg = m_infoPPos->at(posVector).mapqAvg/(long double)(m_infoPPos->at(posVector).cov);
m_infoPPos->at(posVector).mapqAvg = -10.0*( log( m_infoPPos->at(posVector).mapqAvg )/log(10.0) );
//There are 3 possibilities:
//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
///////////////////////////////////////////////////
//detecting to find all possible insertions
// set<string> allInsert;
for(unsigned int i=0;i<pileupData.PileupAlignments.size();i++){
if( !pileupData.PileupAlignments[i].IsCurrentDeletion &&
pileupData.PileupAlignments[i].IsNextInsertion &&
(pileupData.PileupAlignments[i].InsertionLength>0)){ //has insertion
string insert="";
for(int del=1;del<=pileupData.PileupAlignments[i].InsertionLength;del++){
insert+= pileupData.PileupAlignments[i].Alignment.QueryBases[ pileupData.PileupAlignments[i].PositionInAlignment+del ];
}
m_infoPPos->at(posVector).allInserts.insert(insert);
m_infoPPos->at(posVector).insertionRight.push_back(insert);
m_infoPPos->at(posVector).insertion2count[insert]++;
} //else{
// string insert="";
// m_infoPPos->at(posVector).allInserts.insert(insert);
//}
}
//entering an "null" model of not having an insertion
m_infoPPos->at(posVector).allInserts.insert("");
//init likelihood for all possible pairs of inserts
for(set<string>::const_iterator it1 = m_infoPPos->at(posVector).allInserts.begin();
it1 != m_infoPPos->at(posVector).allInserts.end();
++it1) {
m_infoPPos->at(posVector).insertion2loglike[*it1] = 0.0;
for(set<string>::const_iterator it2 = m_infoPPos->at(posVector).allInserts.begin();
it2 != m_infoPPos->at(posVector).allInserts.end();
++it2) {
pair<string,string> keytouse (*it1,*it2);
m_infoPPos->at(posVector).insertion2loglikeEndoCont[ keytouse ] = 0.0;
}
}
//re-iterate over each read
for(unsigned int i=0;i<pileupData.PileupAlignments.size();i++){
int m = int(pileupData.PileupAlignments[i].Alignment.MapQuality);
long double probEndogenous=1.0-contaminationPrior;
if(read2endoProbInit){ //include probability of endogenous
map<string,long double>::iterator itRead2endoProb = read2endoProb.find( pileupData.PileupAlignments[i].Alignment.Name+
"#"+
stringify(pileupData.PileupAlignments[i].Alignment.AlignmentFlag) );
if( itRead2endoProb == read2endoProb.end() ){ // skipped due to deletions near the end or something
probEndogenous = 1.0-contaminationPrior; // assume that a read is equally to belong to either the endo or the contaminant
}else{
probEndogenous = itRead2endoProb->second;
}
}
if( !pileupData.PileupAlignments[i].IsCurrentDeletion &&
pileupData.PileupAlignments[i].IsNextInsertion &&
(pileupData.PileupAlignments[i].InsertionLength>0)){ //has insertion
string insert="";
for(int del=1;del<=pileupData.PileupAlignments[i].InsertionLength;del++){
insert+= pileupData.PileupAlignments[i].Alignment.QueryBases[ pileupData.PileupAlignments[i].PositionInAlignment+del ];
}
//cout<<"ins "<<insert<<endl;
if(singleCont){
// m_infoPPos->at(posVector).insertion2loglike[insert] += log( ( probEndogenous)*probMapping[m]*( INDELERRORPROB))/log(10);
// m_infoPPos->at(posVector).insertion2loglikeCont[insert] += log( (1.0-probEndogenous)*probMapping[m]*( INDELERRORPROB))/log(10);
//both endo and cont have the insert, both right
if(1){
pair<string,string> keytouse (insert,insert);
m_infoPPos->at(posVector).insertion2loglikeEndoCont [ keytouse ] +=
log( ( probEndogenous)*probMapping[m]*(1.0-INDELERRORPROB) + (1.0-probEndogenous)*probMapping[m]*(1.0-INDELERRORPROB) )/log(10);
}
//only endo has the insert, endo has it right, cont has is wrong
for(set<string>::const_iterator it = m_infoPPos->at(posVector).allInserts.begin();
it != m_infoPPos->at(posVector).allInserts.end();
++it) {
if( *it != insert){
pair<string,string> keytouse (insert,*it);
m_infoPPos->at(posVector).insertion2loglikeEndoCont [ keytouse ] +=
log( ( probEndogenous)*probMapping[m]*(1.0-INDELERRORPROB) + (1.0-probEndogenous)*probMapping[m]*( INDELERRORPROB) )/log(10);
}
}
//only cont has the insert, endo has it wrong, cont has is cont
for(set<string>::const_iterator it = m_infoPPos->at(posVector).allInserts.begin();
it != m_infoPPos->at(posVector).allInserts.end();
++it) {
if( *it != insert){
pair<string,string> keytouse (*it ,insert);
m_infoPPos->at(posVector).insertion2loglikeEndoCont [ keytouse ] +=
log( ( probEndogenous)*probMapping[m]*( INDELERRORPROB) + (1.0-probEndogenous)*probMapping[m]*(1.0-INDELERRORPROB) )/log(10);
}
}
//none have the insert, both have it wrong
for(set<string>::const_iterator it1 = m_infoPPos->at(posVector).allInserts.begin();
it1 != m_infoPPos->at(posVector).allInserts.end();
++it1) {
if( *it1 != insert){
for(set<string>::const_iterator it2 = m_infoPPos->at(posVector).allInserts.begin();
it2 != m_infoPPos->at(posVector).allInserts.end();
++it2) {
if( *it2 != insert){
pair<string,string> keytouse (*it1 ,*it2);
m_infoPPos->at(posVector).insertion2loglikeEndoCont [ keytouse ] +=
log((probEndogenous)*probMapping[m]*(INDELERRORPROB) + (1.0-probEndogenous)*probMapping[m]*( INDELERRORPROB) )/log(10);
}
}
}
}
}else{ //not single cont
//got it right for the insert
m_infoPPos->at(posVector).insertion2loglike[insert] += log( ( probEndogenous)*probMapping[m]*(1.0-INDELERRORPROB))/log(10);
//The remaining insertions have it wrong
for(set<string>::const_iterator it = m_infoPPos->at(posVector).allInserts.begin();
it != m_infoPPos->at(posVector).allInserts.end();
++it) {
if( *it != insert)
m_infoPPos->at(posVector).insertion2loglike[*it] += log( ( probEndogenous)*probMapping[m]*( INDELERRORPROB))/log(10);
}
}
}else{ //does not have insert but bases
string insert="";
//push none
if(singleCont){
// m_infoPPos->at(posVector).insertion2loglike[""] += log( ( probEndogenous)*probMapping[m]*( INDELERRORPROB))/log(10);
// m_infoPPos->at(posVector).insertion2loglikeCont[""] += log( (1.0-probEndogenous)*probMapping[m]*( INDELERRORPROB))/log(10);
//both endo and cont have the insert, both right
if(1){
pair<string,string> keytouse (insert,insert);
m_infoPPos->at(posVector).insertion2loglikeEndoCont [ keytouse ] +=
log( ( probEndogenous)*probMapping[m]*(1.0-INDELERRORPROB) + (1.0-probEndogenous)*probMapping[m]*(1.0-INDELERRORPROB) )/log(10);
}
//only endo has the insert, endo has it right, cont has is wrong
for(set<string>::const_iterator it = m_infoPPos->at(posVector).allInserts.begin();
it != m_infoPPos->at(posVector).allInserts.end();
++it) {
if( *it != insert){
pair<string,string> keytouse (insert,*it);
m_infoPPos->at(posVector).insertion2loglikeEndoCont [ keytouse ] +=
log( ( probEndogenous)*probMapping[m]*(1.0-INDELERRORPROB) + (1.0-probEndogenous)*probMapping[m]*( INDELERRORPROB) )/log(10);
}
}
//only cont has the insert, endo has it wrong, cont has is cont
for(set<string>::const_iterator it = m_infoPPos->at(posVector).allInserts.begin();
it != m_infoPPos->at(posVector).allInserts.end();
++it) {
if( *it != insert){
pair<string,string> keytouse (*it ,insert);
m_infoPPos->at(posVector).insertion2loglikeEndoCont [ keytouse ] +=
log( ( probEndogenous)*probMapping[m]*( INDELERRORPROB) + (1.0-probEndogenous)*probMapping[m]*(1.0-INDELERRORPROB) )/log(10);
}
}
//none have the insert, both have it wrong
for(set<string>::const_iterator it1 = m_infoPPos->at(posVector).allInserts.begin();
it1 != m_infoPPos->at(posVector).allInserts.end();
++it1) {
if( *it1 != insert){
for(set<string>::const_iterator it2 = m_infoPPos->at(posVector).allInserts.begin();
it2 != m_infoPPos->at(posVector).allInserts.end();
++it2) {
if( *it2 != insert){
pair<string,string> keytouse (*it1 ,*it2);
m_infoPPos->at(posVector).insertion2loglikeEndoCont [ keytouse ] +=
log((probEndogenous)*probMapping[m]*(INDELERRORPROB) + (1.0-probEndogenous)*probMapping[m]*( INDELERRORPROB) )/log(10);
}
}
}
}
}else{ //not single cont
//got it right for the insert
m_infoPPos->at(posVector).insertion2loglike[insert] += log( ( probEndogenous)*probMapping[m]*(1.0-INDELERRORPROB))/log(10);
//The remaining insertions have it wrong
for(set<string>::const_iterator it = m_infoPPos->at(posVector).allInserts.begin();
it != m_infoPPos->at(posVector).allInserts.end();
++it) {
if( *it != insert)
m_infoPPos->at(posVector).insertion2loglike[*it] += log( ( probEndogenous)*probMapping[m]*( INDELERRORPROB))/log(10);
}
}
}//end, no insert
}//end for each read
// for(map<int,int>::iterator it = test2test.begin();
// it != test2test.end();
// ++it) {
// m_infoPPos->at(posVector).llikNoDeletion += log( ( probEndogenous)*probMapping[m]*(1.0-INDELERRORPROB))/log(10); //got it right
/////////////////////////////////////////////////////
//deletion in the reads/insertion in the reference
/////////////////////////////////////////////////////
for(unsigned int i=0;i<pileupData.PileupAlignments.size();i++){
int m = int(pileupData.PileupAlignments[i].Alignment.MapQuality);
long double probEndogenous=1.0-contaminationPrior;
string rg;
pileupData.PileupAlignments[i].Alignment.GetTag("RG",rg);//REMOVE ME
if(read2endoProbInit){ //include probability of endogenous
map<string,long double>::iterator itRead2endoProb = read2endoProb.find( pileupData.PileupAlignments[i].Alignment.Name+
"#"+
stringify(pileupData.PileupAlignments[i].Alignment.AlignmentFlag) );
if( itRead2endoProb == read2endoProb.end() ){ // skipped due to deletions near the end or something
probEndogenous = 1.0-contaminationPrior; // assume that a read is equally to belong to either the endo or the contaminant
}else{
probEndogenous = itRead2endoProb->second;
}
}
// if(posVector>=513 && posVector<=516){
// cout<<"pos ="<<posVector<<"\t"<<rg<<endl;
// }
if( pileupData.PileupAlignments[i].IsCurrentDeletion &&
pileupData.PileupAlignments[i].IsNextInsertion &&
(pileupData.PileupAlignments[i].InsertionLength == 0)){ //has deletion
//continue;
//cout<<"del"<<endl;
// if(posVector>=513 && posVector<=516){
// cout<<"pos ="<<posVector<<"\tdel\t"<<rg<<endl;
// }
m_infoPPos->at(posVector).numDel++;
if(singleCont){
// m_infoPPos->at(posVector).llikDeletion += log( ( probEndogenous)*probMapping[m]*(1.0-INDELERRORPROB))/log(10); //got it right
// m_infoPPos->at(posVector).llikNoDeletion += log( ( probEndogenous)*probMapping[m]*( INDELERRORPROB))/log(10); //got it wrong
// m_infoPPos->at(posVector).llikDeletionCont += log( (1.0-probEndogenous)*probMapping[m]*(1.0-INDELERRORPROB))/log(10); //got it right
// m_infoPPos->at(posVector).llikNoDeletionCont += log( (1.0-probEndogenous)*probMapping[m]*( INDELERRORPROB))/log(10); //got it wrong
//there is a deletion in both, got it right 2x
m_infoPPos->at(posVector).llikDeletionBoth += log( probEndogenous*probMapping[m]*(1.0-INDELERRORPROB) + (1.0-probEndogenous)*probMapping[m]*(1.0-INDELERRORPROB) )/log(10);
//only in endo, right if endo, wrong if cont
m_infoPPos->at(posVector).llikDeletionEndo += log( probEndogenous*probMapping[m]*(1.0-INDELERRORPROB) + (1.0-probEndogenous)*probMapping[m]*( INDELERRORPROB) )/log(10);
//only in cont, wrong if endo, right if cont
m_infoPPos->at(posVector).llikDeletionCont += log( probEndogenous*probMapping[m]*( INDELERRORPROB) + (1.0-probEndogenous)*probMapping[m]*(1.0-INDELERRORPROB) )/log(10);
//none have it, wrong in both
m_infoPPos->at(posVector).llikDeletionNone += log( probEndogenous*probMapping[m]*( INDELERRORPROB) + (1.0-probEndogenous)*probMapping[m]*( INDELERRORPROB) )/log(10);
}else{
m_infoPPos->at(posVector).llikDeletion += log( ( probEndogenous)*probMapping[m]*(1.0-INDELERRORPROB))/log(10); //got it right
m_infoPPos->at(posVector).llikNoDeletion += log( ( probEndogenous)*probMapping[m]*( INDELERRORPROB))/log(10); //got it wrong
}
}else{ //does not have deletion
// if(posVector>=513 && posVector<=516){
// cout<<"pos ="<<posVector<<"\tnodel\t"<<rg<<endl;
// }
if(singleCont){
//there is a deletion in both, got it wrong 2x
m_infoPPos->at(posVector).llikDeletionBoth += log( probEndogenous*probMapping[m]*( INDELERRORPROB) + (1.0-probEndogenous)*probMapping[m]*( INDELERRORPROB) )/log(10);
//only in endo, wrong in endo, right in cont
m_infoPPos->at(posVector).llikDeletionEndo += log( probEndogenous*probMapping[m]*( INDELERRORPROB) + (1.0-probEndogenous)*probMapping[m]*(1.0-INDELERRORPROB) )/log(10);
//only in cont, right in endo, wrong in cont
m_infoPPos->at(posVector).llikDeletionCont += log( probEndogenous*probMapping[m]*(1.0-INDELERRORPROB) + (1.0-probEndogenous)*probMapping[m]*( INDELERRORPROB) )/log(10);
//none have it, right in both
m_infoPPos->at(posVector).llikDeletionNone += log( probEndogenous*probMapping[m]*(1.0-INDELERRORPROB) + (1.0-probEndogenous)*probMapping[m]*(1.0-INDELERRORPROB) )/log(10);
// m_infoPPos->at(posVector).llikDeletion += log( ( probEndogenous)*probMapping[m]*( INDELERRORPROB))/log(10); //got it wrong
// m_infoPPos->at(posVector).llikNoDeletion += log( ( probEndogenous)*probMapping[m]*(1.0-INDELERRORPROB))/log(10); //got it right
// m_infoPPos->at(posVector).llikDeletionCont += log( (1.0-probEndogenous)*probMapping[m]*( INDELERRORPROB))/log(10); //got it wrong
// m_infoPPos->at(posVector).llikNoDeletionCont += log( (1.0-probEndogenous)*probMapping[m]*(1.0-INDELERRORPROB))/log(10); //got it right
}else{
m_infoPPos->at(posVector).llikDeletion += log( ( probEndogenous)*probMapping[m]*( INDELERRORPROB))/log(10); //got it wrong
m_infoPPos->at(posVector).llikNoDeletion += log( ( probEndogenous)*probMapping[m]*(1.0-INDELERRORPROB))/log(10); //got it right
}
}
}
/////////////////////////////////////////////////////
// Variations of a single nucleotide //
/////////////////////////////////////////////////////
for(unsigned int i=0;i<pileupData.PileupAlignments.size();i++){ //for each alignment
unsigned int numReads=0;
numReads++;
if(numReads >= MAXCOV){
break;
}
//skip deletion in the reads/insertion in the reference
if( pileupData.PileupAlignments[i].IsCurrentDeletion &&
pileupData.PileupAlignments[i].IsNextInsertion ){
continue;
}
//base that was read
char b = pileupData.PileupAlignments[i].Alignment.QueryBases[pileupData.PileupAlignments[i].PositionInAlignment];
//quality score
char q = pileupData.PileupAlignments[i].Alignment.Qualities[pileupData.PileupAlignments[i].PositionInAlignment]-offsetQual;
int m = int(pileupData.PileupAlignments[i].Alignment.MapQuality);
//skip unresolved
if(b == 'N')
continue;
// if(posVector== 145){
// cout<<b<<endl;
// }
// BEGIN DEAMINATION COMPUTATION
//zero base distance to the 5p/3p end
int dist5p=-1;
int dist3p=-1;
if( pileupData.PileupAlignments[i].Alignment.IsReverseStrand() ){
dist5p = pileupData.PileupAlignments[i].Alignment.QueryBases.size() - pileupData.PileupAlignments[i].PositionInAlignment-1;
dist3p = pileupData.PileupAlignments[i].PositionInAlignment;
}else{
dist5p = pileupData.PileupAlignments[i].PositionInAlignment;
dist3p = pileupData.PileupAlignments[i].Alignment.QueryBases.size() - pileupData.PileupAlignments[i].PositionInAlignment-1;
}
probSubstition * probSubMatchToUseEndo = &defaultSubMatch ;
probSubstition * probSubMatchToUseCont = &defaultSubMatch ;
// for(int jas=0;jas<16;jas++){
// cout<<jas<<"\t"<<probSubMatchToUse->s[jas]<<endl;
// }
// cout<<"sub\t"<<dist5p<<"\t"<<dist3p<<"\t"<<int(sub5p.size())<< "\t"<<int(sub3p.size()) <<endl;
if(dist5p <= (int(sub5p.size()) -1)){
probSubMatchToUseEndo = &sub5p[ dist5p ];
// cout<<"5p sub"<<endl;
}
if(dist3p <= (int(sub3p.size()) -1)){
probSubMatchToUseEndo = &sub3p[ dist3p ];
// cout<<"3p sub"<<endl;
}
//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 ];
// cout<<"5p sub"<<endl;
}else{
probSubMatchToUseEndo = &sub3p[ dist3p ];
// cout<<"3p sub"<<endl;
}
}
// END DEAMINATION COMPUTATION
long double probEndogenous=1.0-contaminationPrior;
if(read2endoProbInit){ //include probability of endogenous
map<string,long double>::iterator itRead2endoProb = read2endoProb.find( pileupData.PileupAlignments[i].Alignment.Name+
"#"+
stringify(pileupData.PileupAlignments[i].Alignment.AlignmentFlag) );
if( itRead2endoProb == read2endoProb.end() ){ // skipped due to deletions near the end or something
probEndogenous = 1.0-contaminationPrior; // assume that a read is equally to belong to either the endo or the contaminant
}else{
probEndogenous = itRead2endoProb->second;
}
}
if(singleCont){ // we consider a single contaminant
for(unsigned int nuce=0;nuce<4;nuce++){ //iterate over each possible endogenous base
char currentNuc=dnaAlphabet[nuce];
if(currentNuc == b){//match
m_infoPPos->at(posVector).covPerBase[nuce]++;
}else{//mismatch
}
// b is the observed
// nuce is the model for the endogenous base
int dinucIndexe;//The index depends on the strand
if( pileupData.PileupAlignments[i].Alignment.IsReverseStrand() ){
dinucIndexe= (3-nuce)*4+baseResolved2int(complement(b));
}else{
dinucIndexe= nuce *4+baseResolved2int(b);
}
// probability of generating the base for the endogenous
// (1-e) * p(sub|1-e) + ( e ) * p(sub|1-e)
long double probBasee = likeMatchProb[int(q)] * (probSubMatchToUseEndo->s[dinucIndexe] ) + (1.0 - likeMatchProb[int(q)])*(illuminaErrorsProb.s[dinucIndexe]);
for(unsigned int nucc=0;nucc<4;nucc++){ //iterate over each possible contaminant base
// b is the observed
// nucc is the model for the endogenous base
int dinucIndexc;//The index depends on the strand
if( pileupData.PileupAlignments[i].Alignment.IsReverseStrand() ){
dinucIndexc= (3-nucc)*4+baseResolved2int(complement(b));
}else{
dinucIndexc= nucc *4+baseResolved2int(b);
}
// probability of generating the base for the contaminant
// The substitution probability is probSubMatchToUseCont
// which is simply the Illumina sub probability
// (1-e) * p(sub|1-e) + ( e ) * p(sub|1-e)
long double probBasec = likeMatchProb[int(q)] * (probSubMatchToUseCont->s[dinucIndexc] ) + (1.0 - likeMatchProb[int(q)])*(illuminaErrorsProb.s[dinucIndexc]);
long double probBase = ( probEndogenous )*(probBasee) + ( 1.0-probEndogenous )*(probBasec) ;
long double probFinal;
if(ignoreMQ){ //ignore MQ
probFinal = ( probBase );
}else{
probFinal = (probMapping[m]*probBase + probMismapping[m]*0.25);
}
m_infoPPos->at(posVector).likeBaseNoindelCont[nuce][nucc] += log(probFinal)/log(10);
#ifdef DEBUG3
if(posVector== 146){
cout<<posAlign<<"\t"<<"b_obs="<<b<<" e_b="<< dnaAlphabet[nuce]<<" c_b="<< dnaAlphabet[nucc]<<" q="<<int(q)<<" m="<<m<<" p(endo) "<<probEndogenous<<" p(cont) "<<( 1.0-probEndogenous )
<<"\t"<<"final="<<(probFinal)<<"\t"<<log(probFinal)/log(10)<<"\t"
<<"\tllik\t"<<(m_infoPPos->at(posVector).likeBaseNoindelCont[nuce][nucc])<<"\t"
<<"p(match)= "<<likeMatchProb[int(q)] <<"\t"
<<"p(sub|matche)= "<< (probSubMatchToUseEndo->s[dinucIndexe] ) <<"\t"
<<"p(sub|matchc)= "<< (probSubMatchToUseCont->s[dinucIndexc] ) <<"\t"
<<"p(match)*p(sub|matche) "<< (likeMatchProb[int(q)] * (probSubMatchToUseEndo->s[dinucIndexe] )) <<"\t"
<<"p(match)*p(sub|matchc) "<< (likeMatchProb[int(q)] * (probSubMatchToUseCont->s[dinucIndexc] )) <<"\t"
<<"p(mismatch)= "<<(1.0 - likeMatchProb[int(q)]) <<"\t"
<<"p(sub|mismatche)= "<<(illuminaErrorsProb.s[dinucIndexe])<<"\t"
<<"p(sub|mismatchc)= "<<(illuminaErrorsProb.s[dinucIndexc])<<"\t"
<<"p(mismatch)*p(sub|mismatche) "<<( (1.0 - likeMatchProb[int(q)]) *(illuminaErrorsProb.s[dinucIndexe]) )<<"\t"
<<"p(mismatch)*p(sub|mismatchc) "<<( (1.0 - likeMatchProb[int(q)]) *(illuminaErrorsProb.s[dinucIndexc]) )<<endl;
//cout<<"-----------------"<<endl;
}
#endif
}//end for each contaminant
}//end for each endo
#ifdef DEBUG3
if(posVector== 146){
cout<<"-----------------"<<endl;
}
#endif
}else{ //if we cannot assume that there is a single contaminant
for(unsigned int nuc=0;nuc<4;nuc++){ //iterate over each possible endogenous base
char currentNuc=dnaAlphabet[nuc];
if(currentNuc == b){//match
m_infoPPos->at(posVector).covPerBase[nuc]++;
}else{//mismatch
}
// b is the observed
// nuc is the model
int dinucIndex;//The index depends on the strand
if( pileupData.PileupAlignments[i].Alignment.IsReverseStrand() ){
dinucIndex= (3-nuc)*4+baseResolved2int(complement(b));
}else{
dinucIndex= nuc *4+baseResolved2int(b);
}
// = nuc*4+baseResolved2int(b);
// (1-e) * p(sub|1-e) + ( e ) * p(sub|1-e)
long double probBase = likeMatchProb[int(q)] * (probSubMatchToUseEndo->s[dinucIndex] ) + (1.0 - likeMatchProb[int(q)])*(illuminaErrorsProb.s[dinucIndex]);
//m_infoPPos->at(posVector).likeBaseNoindel[nuc] +=
long double probFinal;
if(read2endoProbInit){ //include probability of endogenous
probBase = ( probEndogenous )*(probBase) + ( 1.0-probEndogenous )*(0.25) ;
}
if(ignoreMQ){ //ignore MQ
probFinal = ( probBase );
}else{
probFinal = (probMapping[m]*probBase + probMismapping[m]*0.25);
}
m_infoPPos->at(posVector).likeBaseNoindel[nuc] += log(probFinal)/log(10);
#ifdef DEBUG2
cout<<"b_obs="<<b<<" n_model="<<currentNuc<<"\tindex="<<dinucIndex<<" q="<<int(q)<<" m="<<m<<endl;
cout<<"p(match)="<<likeMatchProb[int(q)] <<"\t"
<<"p(sub|match)="<< (probSubMatchToUse->s[dinucIndex] ) <<"\t"
<<"p(match)*p(sub|match)"<< (likeMatchProb[int(q)] * (probSubMatchToUse->s[dinucIndex] )) <<"\t"
<<"p(mismatch)="<<(1.0 - likeMatchProb[int(q)]) <<"\t"
<<"p(sub|mismatch)="<<(illuminaErrorsProb.s[dinucIndex])<<"\t"
<<"p(mismatch)*p(sub|mismatch)"<<( (1.0 - likeMatchProb[int(q)]) *(illuminaErrorsProb.s[dinucIndex]) )
<<"\t"<<"final="<<(probFinal)<<"\t"<<log(probFinal)/log(10)<<endl;
#endif
#ifdef DEBUG2