forked from grenaud/schmutzi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathendoCaller.cpp
3689 lines (2674 loc) · 116 KB
/
endoCaller.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
/*
* endoCaller
* 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 DEBUGINS 5893
// #define DEBUG1
// #define DEBUG2
// #define DEBUG3
// #define DEBUG4
#define CONTPRIORBEFORE
// #define DEBUGPRIORENDO
//GLOBAL CONSTANTS
#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 IGNOREINDELBOUND 5 //ignore INDEL if there are within this amount of bp of the. 5 is good since it offsets the cost of a gap in a standard SW scoring scheme
#ifdef IGNOREINDELBOUND
#define IGNOREINDELLENGTH 35 //ignore reads of length less than this fpr INDEL calling, this cutoffs was decided because of presence of noise before 35bp
#endif
#define MIN(a,b) (((a)<(b))?(a):(b))
// 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 <limits>
#include "utils.h"
#include "miscfunc.h"
#include "ReconsReferenceBAM.h"
using namespace BamTools;
using namespace std;
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;
}
char offsetQual=33;
long double LOGRATIOFORINDEL=50;
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 probMappingCP[MAXMAPPINGQUAL];
double probMismappingCP[MAXMAPPINGQUAL];
double probLengthEndo[1000];
probSubstition illuminaErrorsProb;
vector<probSubstition> sub5p;
vector<probSubstition> sub3p;
vector<probSubstition> sub5pC;
vector<probSubstition> sub3pC;
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;
}
//! A method that calls the best nucleotide given the likelihood for the 4 nucleotides
/*!
This method is called by callSingleNucleotide and will use the information stored in likeBaseNoindel to find the most likely nucleotide and compute the error in this assignment. It can be used for both the contaminant and endogenous.
\param bestNuc : The best nucleotide will be stored here
\param sumLogLikeAll : Sum of the log-likelihood for every base will be stored here
\param sumLogLikeOnlyBest : Log-likelihood for the best nucleotide will be stored here
\param sumLogLikeAllButBest : Sum of the log-likelihood for every base excluding the best will be stored here
\param sumLogForNucs[] : The log-likelihood of the sum of the remaining bases (ex: For A, only consider C,G,T) for all 4 bases the will be stored here
\param likeBaseNoindel: The pre-computed likelihood for all bases
\param infoPPos: The vector of structure populated by the bam reader, needed to get the coverage to break ties in likelihood, unlikely to be used
\param i: The position in the genome
*/
inline void callBestNucleotideGivenLikelihood( int & bestNuc,
long double & sumLogLikeAll, // sum of all the logs
long double & sumLogLikeOnlyBest, // sum of the logs for the best
long double & sumLogLikeAllButBest, // sum of the logs for all but the best
long double sumLogForNucs[],
const long double likeBaseNoindel [],
const vector<singlePosInfo> & infoPPos,
const int i
){
//init
for(int nuc=0;nuc<4;nuc++){
sumLogForNucs[nuc] = 0.0;
}
sumLogLikeAll = 0.0; // sum of all the logs
sumLogLikeOnlyBest = 0.0; // sum of the logs for the best
sumLogLikeAllButBest = 0.0; // sum of the logs for all but the best
// bool sumLogLikeAllB = true;
// bool sumLogLikeOnlyBestB = true;
// bool sumLogLikeAllButBestB = true;
// bool sumLogForNucsB[4]; //sumLogForNucs has to be initialized
// for(int nuc=0;nuc<4;nuc++){
// sumLogForNucsB[nuc]=true;
// }
long double bestLike=-INFINITY;
//int bestNuc=-1;
//Determining most likely nucleotide
for(unsigned int nuc=0;nuc<4;nuc++){
// if(i==146){
// cout<<nuc<<"\t"<<likeBaseNoindel[nuc]<<endl;
// }
if(likeBaseNoindel[nuc] > bestLike){
bestLike=likeBaseNoindel[nuc];
bestNuc=nuc;
}
}
//If there are more than one with equal likelihood (this is highly unlikely)
//take the one with the greatest coverage
vector<int> bestNucs;
for(unsigned int nuc=0;nuc<4;nuc++){
if(likeBaseNoindel[nuc] == bestLike){
bestNucs.push_back(nuc);
}
}
if(bestNucs.size() > 1){ // multiple equally likely nuc, use coverage to call best one
// cerr<<"size "<<bestNucs.size()<<endl;
// return 1;
int bestCov=-1;
int bestCovN=bestNucs[0];
for(unsigned int bc=0;bc<bestNucs.size();bc++){
if(infoPPos[i].covPerBase[ bestNucs[bc] ] > bestCov){
bestCov =infoPPos[i].covPerBase[ bestNucs[bc] ];
bestCovN = bestNucs[bc];
}
}
bestNuc = bestCovN;
}
//end
//computing the probability of error
for(int nuc=0;nuc<4;nuc++){
// cout<<(i+1)<<"\tnuc\t"<<dnaAlphabet[nuc]<<"\t"<<dnaAlphabet[bestNuc]<<"\t"<<infoPPos[i].likeBaseNoindel[nuc]<<"\t"<<likeBaseNoindel[nuc]<<"\t"<<pow(10.0,infoPPos[i].likeBaseNoindel[nuc])<<endl;
for(int nuc2=0;nuc2<4;nuc2++){
if(nuc!=nuc2){
//sumLogForNucs[nuc] += pow(10.0,likeBaseNoindel[nuc2]);
sumLogForNucs[nuc] = oplusInit(sumLogForNucs[nuc] , likeBaseNoindel[nuc2]);
}
}
//sumLogLikeAll += pow(10.0,likeBaseNoindel[nuc]);
sumLogLikeAll = oplusInit(sumLogLikeAll,likeBaseNoindel[nuc]);
if(nuc==bestNuc){
//sumLogLikeOnlyBest += pow(10.0,likeBaseNoindel[nuc]);
sumLogLikeOnlyBest = oplusInit(sumLogLikeOnlyBest,likeBaseNoindel[nuc]);
}else{
//sumLogLikeAllButBest += pow(10.0,likeBaseNoindel[nuc]);
sumLogLikeAllButBest = oplusInit( sumLogLikeAllButBest,likeBaseNoindel[nuc]);
}
}//end for nuc
}
//! A method that calls potential insertion in the sample/deletions in the reference
/*!
This method is called by printLogAndGenome().
When we assume we have a single contaminant :
We use insertion2loglikeEndoCont to call both insertions in the contaminant and endogenous. We marginalize over each possible insertion (and no insertion) for the other and determine the most likely insert (or lack thereof)
When we cannot assume we have a single contaminant:
Just use insertion2loglike to find the most likely insert (or lack thereof)
\param i : Position on the mitonchondria
\param genomeRef : The reference genome
\param infoPPos: The vector of structure populated by the bam reader
\param singleCont: Boolean as to we assume that we have a single contaminant or not
\param minQual: PHRED quality threshold, beyong this we print N instead of the base
\param genomeToPrint: String on which the endogenous genome will be printed
\param genomeToPrintC: String on which the contaminant genome will be printed
\param logToPrint: Pointer to the string stream for the endogenous log
\param logToPrintC: Pointer to the string stream for the contaminant log
\param setFlags: Boolean to say whether we skip printing to the genome/log or not
\param endoIndel: Boolean to know if the endogenous has a deletion
\param contIndel: Boolean to know if the contaminanthas a deletion
*/
void insertionInSample(const int i,
const string & genomeRef,
const vector<singlePosInfo> & infoPPos,
const bool singleCont,
const int minQual,
string & genomeToPrint,
string & genomeToPrintC,
stringstream * logToPrint,
stringstream * logToPrintC,
const bool setFlags,
bool & endoIndel,
bool & contIndel){
if(infoPPos[i].allInserts.size() != 0){ // there are potential insertions
if(singleCont){
//calling the endogenous
string bestInsertEndo = "";
long double bestInsertLogLikeEndo = -1.0*numeric_limits<long double>::infinity();
bool initializeBEndo = false;
long double sumLogLikeEndo = 0.0;
//iterate for each endogenous insert
for(set<string>::const_iterator it1 = infoPPos[i].allInserts.begin();
it1 != infoPPos[i].allInserts.end();
++it1) {
long double sumLogLikeForThisIns=0.0;
//marginalize over each possible contaminant
for(set<string>::const_iterator it2 = infoPPos[i].allInserts.begin();
it2 != infoPPos[i].allInserts.end();
++it2) {
pair<string,string> keytouse (*it1,*it2);
// infoPPos[i].insertion2loglikeEndoCont[ keytouse ] = 0.0;
#ifdef DEBUGINS
if(i==DEBUGINS){
//cout<<"i\t"<<i<<"\t"<<"inse="<<keytouse.first<<"#"<<"\tinsc="<<keytouse.second<<"#"<<"\t" << infoPPos[i].insertion2loglikeEndoCont.at( keytouse ) <<endl;
cout<<"i\t"<<i<<"\t"<<"inse=#"<<keytouse.first<<"#"<<infoPPos[i].insertion2count.at(keytouse.first)<<"\tinsc=#"<<keytouse.second<<"#"<<infoPPos[i].insertion2count.at(keytouse.second)<<"\t" << infoPPos[i].insertion2loglikeEndoCont.at( keytouse ) <<endl;
}
#endif
sumLogLikeForThisIns = oplusInit(sumLogLikeForThisIns,
infoPPos[i].insertion2loglikeEndoCont.at( keytouse ));
}
if(!initializeBEndo){
bestInsertEndo = *it1;
bestInsertLogLikeEndo = sumLogLikeForThisIns;
initializeBEndo = true;
}else{
if(bestInsertLogLikeEndo < sumLogLikeForThisIns){
bestInsertEndo = *it1;
bestInsertLogLikeEndo = sumLogLikeForThisIns;
}
}
//cout<<i<<"\tins=#"<<*it1<<"#\t"<<sumLogLikeForThisIns<<"\t"<<setFlags<<"\t"<<sumLogLikeEndo<<"\tbest=\t"<<bestInsertEndo<<"#\t"<<bestInsertLogLikeEndo<<endl;
sumLogLikeEndo = oplusInit(sumLogLikeEndo,sumLogLikeForThisIns);
//cout<<i<<"\tins=#"<<*it1<<"#\t"<<sumLogLikeForThisIns<<"\t"<<setFlags<<"\t"<<sumLogLikeEndo<<"\tbest=\t"<<bestInsertEndo<<"#\t"<<bestInsertLogLikeEndo<<endl;
}//end for each endogenous insert
string bestInsertCont = "";
long double bestInsertLogLikeCont = -1.0*numeric_limits<long double>::infinity();;
bool initializeBCont = false;
long double sumLogLikeCont = 0.0;
//iterate for each contaminant insert
for(set<string>::const_iterator it2 = infoPPos[i].allInserts.begin();
it2 != infoPPos[i].allInserts.end();
++it2) {
long double sumLogLikeForThisIns=0.0;
//marginalize over each possible endegenous
for(set<string>::const_iterator it1 = infoPPos[i].allInserts.begin();
it1 != infoPPos[i].allInserts.end();
++it1) {
pair<string,string> keytouse (*it1,*it2);
// infoPPos[i].insertion2loglikeEndoCont[ keytouse ] = 0.0;
sumLogLikeForThisIns = oplusInit(sumLogLikeForThisIns,
infoPPos[i].insertion2loglikeEndoCont.at( keytouse ));
}
if(!initializeBCont){
bestInsertCont = *it2;
bestInsertLogLikeCont = sumLogLikeForThisIns;
initializeBCont = true;
}else{
if(bestInsertLogLikeCont < sumLogLikeForThisIns){
bestInsertCont = *it2;
bestInsertLogLikeCont = sumLogLikeForThisIns;
}
}
sumLogLikeCont = oplusInit(sumLogLikeCont,sumLogLikeForThisIns);
}//end for each endogenous insert
endoIndel=(bestInsertEndo != "");
contIndel=(bestInsertCont != "");
if(setFlags){
return ;
}
if(bestInsertEndo != ""){ //more likely there is an insert in the endogenous
long double sumLogLikeButTheBestEndo=log( pow(10.0,sumLogLikeEndo) - pow(10.0,bestInsertLogLikeEndo) )/log(10);
//cout<<i<<"\t"<<setFlags<<"\t"<<sumLogLikeEndo<<"\tbest=\t"<<bestInsertEndo<<"#\t"<<bestInsertLogLikeEndo<<"\t"<<sumLogLikeButTheBestEndo<<"\t"<<(sumLogLikeEndo==bestInsertLogLikeEndo)<<"\t"<<(sumLogLikeEndo==bestInsertLogLikeEndo)<<endl;
long double qualInsToPrint ;
if(sumLogLikeEndo==bestInsertLogLikeEndo)
qualInsToPrint = 1.0/INDELERRORPROB; //There is no likely alternative
else
qualInsToPrint = -10.0*( sumLogLikeButTheBestEndo - sumLogLikeEndo);
for(unsigned int k=0;k<(bestInsertEndo.size());k++){
(*logToPrint)<<(i+1)<<"i\t"<<"-"<<"\t"<<bestInsertEndo[k]<<"\t"<<qualInsToPrint<<"\t"<<infoPPos[i].mapqAvg<<"\t"<<infoPPos[i].cov<<"\t"<<infoPPos[i].insertion2count.at(bestInsertEndo)<<"\t0.0\t0.0\t0.0\t0.0"<<endl;
}
//cout<<"inse "<<i<<"\t"<<qualInsToPrint<<"\t"<<minQual<<"\t"<<bestInsertEndo<<endl;
if(qualInsToPrint >= minQual){
//cout<<"inse "<<i<<"\t"<<qualInsToPrint<<"\t"<<minQual<<"\t"<<bestInsertEndo<<endl<<genomeToPrint<<endl<<genomeToPrintC<<endl;
genomeToPrint+=bestInsertEndo;
//cout<<"inse "<<i<<"\t"<<qualInsToPrint<<"\t"<<minQual<<"\t"<<bestInsertEndo<<endl<<genomeToPrint<<endl<<genomeToPrintC<<endl;
}
}
if(bestInsertCont != ""){ //more likely there is an insert in the endogenous
long double sumLogLikeButTheBestCont=log( pow(10.0,sumLogLikeCont) - pow(10.0,bestInsertLogLikeCont) )/log(10);
long double qualInsToPrint ;
if(sumLogLikeCont==bestInsertLogLikeCont)
qualInsToPrint = 1.0/INDELERRORPROB; //There is no likely alternative
else
qualInsToPrint = -10.0*( sumLogLikeButTheBestCont - sumLogLikeCont);
for(unsigned int k=0;k<(bestInsertCont.size());k++){
(*logToPrintC)<<(i+1)<<"i\t"<<"-"<<"\t"<<bestInsertCont[k]<<"\t"<<qualInsToPrint<<"\t"<<infoPPos[i].mapqAvg<<"\t"<<infoPPos[i].cov<<"\t"<<infoPPos[i].insertion2count.at(bestInsertCont)<<"\t0.0\t0.0\t0.0\t0.0"<<endl;
}
//cout<<"insc "<<i<<"\t"<<qualInsToPrint<<"\t"<<minQual<<"\t"<<bestInsertEndo<<endl;
if(qualInsToPrint >= minQual)
genomeToPrintC+=bestInsertCont;
}
}else{ //cannot assume we have a single contaminant
//for each potential insert
string bestInsert = "";
long double bestInsertLogLike = -1.0*numeric_limits<long double>::infinity();
bool initializeB = false;
long double sumLogLike = 0.0;
for(set<string>::const_iterator it1 = infoPPos[i].allInserts.begin();
it1 != infoPPos[i].allInserts.end();
++it1) {
if(!initializeB){
bestInsertLogLike = infoPPos[i].insertion2loglike.at(*it1);
bestInsert = *it1;
initializeB = true;
}else{
if( bestInsertLogLike < infoPPos[i].insertion2loglike.at(*it1) ){
bestInsertLogLike = infoPPos[i].insertion2loglike.at(*it1);
bestInsert = *it1;
}
}
sumLogLike = oplusInit(sumLogLike,infoPPos[i].insertion2loglike.at(*it1));
}
endoIndel=(bestInsert != "");
if(setFlags){
return ;
}
if(bestInsert != ""){ //more likely there is an insert
long double sumLogLikeButTheBest=log( pow(10.0,sumLogLike) - pow(10.0,bestInsertLogLike) )/log(10);
long double qualInsToPrint ;
if(sumLogLike==bestInsertLogLike)
qualInsToPrint = 1.0/INDELERRORPROB; //There is no likely alternative
else
qualInsToPrint = -10.0*( sumLogLikeButTheBest - sumLogLike);
for(unsigned int k=0;k<(bestInsert.size());k++){
(*logToPrint)<<(i+1)<<"i\t"<<"-"<<"\t"<<bestInsert[k]<<"\t"<<qualInsToPrint<<"\t"<<infoPPos[i].mapqAvg<<"\t"<<infoPPos[i].cov<<"\t"<<infoPPos[i].insertion2count.at(bestInsert)<<"\t0.0\t0.0\t0.0\t0.0"<<endl;
}
//adding in fasta file if qual is higher than threshold
if(qualInsToPrint >= minQual)
genomeToPrint+=bestInsert;
}
}
}
}
//! A method that calls potential deletion in the sample/insertion in the reference
/*!
This method is called by printLogAndGenome().
When we assume we have a single contaminant :
We use llikDeletionBoth, llikDeletionEndo, llikDeletionEndo, llikDeletionCont, llikDeletionNone
from infoPPos to find the most likely state for both the endogenous and the contaminant.
When we cannot assume we have a single contaminant:
Use llikDeletion llikNoDeletion to find out wether a deletion is more likely than the
\param i : Position on the mitonchondria
\param genomeRef : The reference genome
\param infoPPos: The vector of structure populated by the bam reader
\param singleCont: Boolean as to we assume that we have a single contaminant or not
\param minQual: PHRED quality threshold, beyong this we print N instead of the base
\param logToPrint: Pointer to the string stream for the endogenous log
\param logToPrintC: Pointer to the string stream for the contaminant log
\param skipEndo: Boolean set by the method for the endogenous sample, set to 1 if the sample has a deletion hence no need to call a base
\param skipCont: Boolean set by the method for the contaminant, set to 1 if the contaminant has a deletion hence no need to call a base
\param setFlags: Boolean to say whether we skip printing to the genome/log or not
\param endoIndel: Boolean to know if the endogenous has a deletion
\param contIndel: Boolean to know if the contaminanthas a deletion
*/
void deletionInSample(const int i,
const string & genomeRef,
const vector<singlePosInfo> & infoPPos,
const bool singleCont,
const int minQual,
string & genomeToPrint,
string & genomeToPrintC,
stringstream * logToPrint,
stringstream * logToPrintC,
bool & skipEndo,
bool & skipCont,
const bool setFlags,
bool & endoIndel,
bool & contIndel){
if( infoPPos[i].numDel >= 0){
if(singleCont){
long double logLikeDel[] = { infoPPos[i].llikDeletionBoth,infoPPos[i].llikDeletionEndo,infoPPos[i].llikDeletionCont,infoPPos[i].llikDeletionNone };
pair<long double,long double> maxAndSecondMax = firstAndSecondHighestArray( logLikeDel,4 );
long double sumLogLikeAll=0.0;
for(int n=0;n<4;n++){
sumLogLikeAll = oplusInit(sumLogLikeAll,logLikeDel[n]);
}
// cout<<maxAndSecondMax.first<<"\t"<<maxAndSecondMax.second<<endl;
// if(i==513){
// cout<<"POSllik\t"<<infoPPos[i].llikDeletionBoth<<"\t"<<infoPPos[i].llikDeletionEndo<<"\t"<<infoPPos[i].llikDeletionCont<<"\t"<<infoPPos[i].llikDeletionNone<<endl;
// }
//both the contaminant and endegenous have a deletion wrt the reference, no need to call any base
if( (infoPPos[i].llikDeletionBoth == maxAndSecondMax.first) &&
((infoPPos[i].llikDeletionBoth - maxAndSecondMax.second) > LOGRATIOFORINDEL)){
endoIndel=true;
contIndel=true;
if(setFlags){
return ;
}
// cout<<"both"<<endl;
long double sumLogLikeCase=0.0;
for(int n=0;n<4;n++){
if(n!=0)
sumLogLikeCase = oplusInit(sumLogLikeCase,logLikeDel[n]);
}
long double qualDelToPrint = (-10.0*(sumLogLikeCase-sumLogLikeAll )/log(10.0));
(*logToPrint)<<(i+1)<<"\t"<<genomeRef[i]<<"\t"<<"D"<<"\t"<<(qualDelToPrint)<<"\t"<<infoPPos[i].mapqAvg<<"\t"<<infoPPos[i].cov<<"\t"<<infoPPos[i].numDel<<"\t0.0\t0.0\t0.0\t0.0"<<endl;
if(qualDelToPrint >= minQual){ //deletion is high quality, do nothing
}else{ //deletion is low quality, put an N
genomeToPrint+="N";
}
(*logToPrintC)<<(i+1)<<"\t"<<genomeRef[i]<<"\t"<<"D"<<"\t"<<(qualDelToPrint)<<"\t"<<infoPPos[i].mapqAvg<<"\t"<<infoPPos[i].cov<<"\t"<<infoPPos[i].numDel<<"\t0.0\t0.0\t0.0\t0.0"<<endl;
if(qualDelToPrint >= minQual){ //deletion is high quality, do nothing
}else{ //deletion is low quality, put an N
genomeToPrintC+="N";
}
PHREDgeno toadd;
toadd.ref = genomeRef[i];
toadd.consensus = 'D';
pos2phredgeno[ (i+1) ] = toadd;
//continue;
skipEndo=true;
skipCont=true;
}
//deletion only in the endogenous, need to call the base for the contaminant
if( (infoPPos[i].llikDeletionEndo == maxAndSecondMax.first) &&
((infoPPos[i].llikDeletionEndo - maxAndSecondMax.second) > LOGRATIOFORINDEL)){
endoIndel=true;
contIndel=false;
if(setFlags){
// cout<<"i="<<i<<"\t"<<endoIndel<<"\t"<<contIndel<<"\tendoDel"<<endl;
return ;
}
// cout<<"endo"<<endl;
long double sumLogLikeCase=0.0;
for(int n=0;n<4;n++){
if(n!=1)
sumLogLikeCase = oplusInit(sumLogLikeCase,logLikeDel[n]);
}
long double qualDelToPrint =(-10.0*(sumLogLikeCase-sumLogLikeAll )/log(10.0));
(*logToPrint)<<(i+1)<<"\t"<<genomeRef[i]<<"\t"<<"D"<<"\t"<< qualDelToPrint<<"\t"<<infoPPos[i].mapqAvg<<"\t"<<infoPPos[i].cov<<"\t"<<infoPPos[i].numDel<<"\t0.0\t0.0\t0.0\t0.0"<<endl;
//(*logToPrintD)<<(i+1)<<"\t"<<genomeRef[i]<<"\t"<<"D"<<"\t"<<(-10.0*(sumLogLikeCase-sumLogLikeAll )/log(10.0))<<"\t"<<infoPPos[i].mapqAvg<<"\t"<<infoPPos[i].cov<<"\t"<<infoPPos[i].numDel<<"\t0.0\t0.0\t0.0\t0.0"<<endl;
if(qualDelToPrint >= minQual){ //deletion is high quality, do nothing
}else{ //deletion is low quality, put an N
genomeToPrint+="N";
}
PHREDgeno toadd;
toadd.ref = genomeRef[i];
toadd.consensus = 'D';
pos2phredgeno[ (i+1) ] = toadd;
//continue;
skipEndo=true;
skipCont=false;
}
//deletion only in the contaminant, need to call the base for the endogenous
if( (infoPPos[i].llikDeletionCont == maxAndSecondMax.first) &&
((infoPPos[i].llikDeletionCont - maxAndSecondMax.second) > LOGRATIOFORINDEL)){
// cout<<"cont"<<endl;
endoIndel=false;
contIndel=true;
if(setFlags){
return ;
}
long double sumLogLikeCase=0.0;
for(int n=0;n<4;n++){
if(n!=2)
sumLogLikeCase = oplusInit(sumLogLikeCase,logLikeDel[n]);
}
//(*logToPrint)<<(i+1)<<"\t"<<genomeRef[i]<<"\t"<<"D"<<"\t"<<(-10.0*(sumLogLikeCase-sumLogLikeAll )/log(10.0))<<"\t"<<infoPPos[i].mapqAvg<<"\t"<<infoPPos[i].cov<<"\t"<<infoPPos[i].numDel<<"\t0.0\t0.0\t0.0\t0.0"<<endl;
long double qualDelToPrint = (-10.0*(sumLogLikeCase-sumLogLikeAll )/log(10.0)) ;
(*logToPrintC)<<(i+1)<<"\t"<<genomeRef[i]<<"\t"<<"D"<<"\t"<<qualDelToPrint <<"\t"<<infoPPos[i].mapqAvg<<"\t"<<infoPPos[i].cov<<"\t"<<infoPPos[i].numDel<<"\t0.0\t0.0\t0.0\t0.0"<<endl;
if(qualDelToPrint >= minQual){ //deletion is high quality, do nothing
}else{ //deletion is low quality, put an N
genomeToPrintC+="N";
}
// PHREDgeno toadd;
// toadd.ref = genomeRef[i];
// toadd.consensus = 'D';
// pos2phredgeno[ (i+1) ] = toadd;
//continue;
skipEndo=false;
skipCont=true;
}
}else{
// double llikDel =0;
// double llikNoDel=0;
if( infoPPos[i].llikDeletion - infoPPos[i].llikNoDeletion > LOGRATIOFORINDEL){
endoIndel=true;
if(setFlags){
return ;
}
long double qualDelToPrint = -10.0*( (infoPPos[i].llikNoDeletion - oplusInit(infoPPos[i].llikDeletion,infoPPos[i].llikNoDeletion))/log(10.0));
(*logToPrint)<<(i+1)<<"\t"<<genomeRef[i]<<"\t"<<"D"<<"\t"<<qualDelToPrint<<"\t"<<infoPPos[i].mapqAvg<<"\t"<<infoPPos[i].cov<<"\t"<<infoPPos[i].numDel<<"\t0.0\t0.0\t0.0\t0.0"<<endl;
if(qualDelToPrint >= minQual){ //deletion is high quality, do nothing
}else{ //deletion is low quality, put an N
genomeToPrint+="N";
}
PHREDgeno toadd;
toadd.ref = genomeRef[i];
toadd.consensus = 'D';
pos2phredgeno[ (i+1) ] = toadd;
//continue;
skipEndo=true;
skipCont=true;
}
}
//TODO add contamination detection
}
}
//! A method that prints the log for bases without any coverage
/*!
This method is called by printLogAndGenome() and just prints a simple line saying there was no coverage.
\param i : Position on the mitonchondria
\param genomeRef : The reference genome
\param infoPPos: The vector of structure populated by the bam reader
\param outLogCflag: Flag to say we print to the contaminant log as well.
\param genomeToPrint: String on which the endogenous genome will be printed
\param genomeToPrintC: String on which the contaminant genome will be printed
\param logToPrint: Pointer to the string stream for the endogenous log
\param logToPrintC: Pointer to the string stream for the contaminant log
\param skipEndo: Boolean if we skip the endogenous sample, set to 1 if the endogenous sample has no coverage
\param skipCont: Boolean set by the method for the contaminant, set to 1 if the contaminant has no coverage
*/
void noCoverage(const int i,
const string & genomeRef,
const vector<singlePosInfo> & infoPPos,
const bool outLogCflag,
string & genomeToPrint,
string & genomeToPrintC,
stringstream * logToPrint,
stringstream * logToPrintC,
bool & skipEndo,
bool & skipCont){
if(infoPPos[i].cov == 0){
genomeToPrint+="N";
(*logToPrint)<<(i+1)<<"\t"<<genomeRef[i]<<"\tN\t0\t0\t0\t0\t0.0\t0.0\t0.0\t0.0"<<endl;
if(outLogCflag){
genomeToPrintC+="N";
(*logToPrintC)<<(i+1)<<"\t"<<genomeRef[i]<<"\tN\t0\t0\t0\t0\t0.0\t0.0\t0.0\t0.0"<<endl;
}
skipEndo=true;
skipCont=true;
}
}
//! A method that computes the most likely single nucleotide
/*!
This method is called by printLogAndGenome() and either computes:
When we assume we have a single contaminant :
use likeBaseNoindelCont to compute the most likely endogenous base and contaminant
we marginalize over each contaminant base to call the endogenous base and vice-versa
When we cannot assume we have a single contaminant:
use likeBaseNoindel for all four endogenous nucleotides
It calls callBestNucleotideGivenLikelihood() for each possibility
\param i : Position on the mitonchondria
\param genomeRef : The reference genome
\param infoPPos: The vector of structure populated by the bam reader
\param singleCont: Boolean as to we assume that we have a single contaminant or not
\param minQual: PHRED quality threshold, beyong this we print N instead of the base
\param genomeToPrint: String on which the endogenous genome will be printed
\param genomeToPrintC: String on which the contaminant genome will be printed
\param logToPrint: Pointer to the string stream for the endogenous log
\param logToPrintC: Pointer to the string stream for the contaminant log
\param skipEndo: If there was a deletion, we do not print to the endogenous sample
\param skipCont: If there was a deletion, we do not print to the contaminant
*/
void callSingleNucleotide(const int i,
const string & genomeRef,
const vector<singlePosInfo> & infoPPos,
const bool singleCont,
const int minQual,
string & genomeToPrint,
string & genomeToPrintC,
stringstream * logToPrint,
stringstream * logToPrintC,
bool & skipEndo,
bool & skipCont,
const bool endoIndelCurrent,
const bool contIndelCurrent){
int bestNuc=-1;
int bestNucC=-1;
long double sumLogLikeAll = 0.0; // sum of all the logs
long double sumLogLikeOnlyBest = 0.0; // sum of the logs for the best
long double sumLogLikeAllButBest = 0.0; // sum of the logs for all but the best
long double sumLogLikeAllC = 0.0; // sum of all the logs
long double sumLogLikeOnlyBestC = 0.0; // sum of the logs for the best
long double sumLogLikeAllButBestC = 0.0; // sum of the logs for all but the best
// bool sumLogLikeAllB = true;
// bool sumLogLikeOnlyBestB = true;
// bool sumLogLikeAllButBestB = true;
// int nuc=0;
// sumLogLikeAll = infoPPos[i].likeBaseNoindel[nuc]; //oplus= log10( pow(10,x)+pow(10,y) )
// if(nuc==bestNuc)
// sumLogLikeOnlyBest = infoPPos[i].likeBaseNoindel[nuc];
// else
// sumLogLikeAllButBest = infoPPos[i].likeBaseNoindel[nuc];
long double sumLogForNucs[4]; //sum of the logs for all but the nucleotide itself
long double sumLogForNucsC[4]; //sum of the logs for all but the nucleotide itself