-
Notifications
You must be signed in to change notification settings - Fork 260
/
AlleleParser.cpp
3996 lines (3497 loc) · 184 KB
/
AlleleParser.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
#include "AlleleParser.h"
#include "multichoose.h" // includes generic functions, so it must be included here
// otherwise we will get a linker error
// see: http://stackoverflow.com/questions/36039/templates-spread-across-multiple-files
// http://www.cplusplus.com/doc/tutorial/templates/ "Templates and Multi-file projects"
#include "multipermute.h"
// local helper debugging macros to improve code readability
#define DEBUG(msg) \
if (parameters.debug) { cerr << msg << endl; }
// lower-priority messages
#ifdef VERBOSE_DEBUG
#define DEBUG2(msg) \
if (parameters.debug2) { cerr << msg << endl; }
#else
#define DEBUG2(msg)
#endif
// must-see error messages
#define ERROR(msg) \
cerr << "ERROR(freebayes): " << msg << endl;
// must-see warning messages
#define WARNING(msg) \
cerr << "WARNING(freebayes): " << msg << endl;
using namespace std;
// open BAM input file
void AlleleParser::openBams(void) {
// report differently if we have one or many bam files
if (parameters.bams.size() == 1) {
DEBUG("Opening BAM fomat alignment input file: " << parameters.bams.front() << " ...");
} else if (parameters.bams.size() > 1) {
DEBUG("Opening " << parameters.bams.size() << " BAM fomat alignment input files");
for (vector<string>::const_iterator b = parameters.bams.begin();
b != parameters.bams.end(); ++b) {
DEBUG2(*b);
}
}
if (parameters.useStdin) {
if (!bamMultiReader.Open(parameters.bams)) {
ERROR("Could not read BAM data from stdin");
cerr << bamMultiReader.GetErrorString() << endl;
exit(1);
}
} else {
if (!bamMultiReader.Open(parameters.bams)) {
ERROR("Could not open input BAM files");
cerr << bamMultiReader.GetErrorString() << endl;
exit(1);
} else {
if (!bamMultiReader.LocateIndexes()) {
ERROR("Opened BAM reader without index file, jumping is disabled.");
cerr << bamMultiReader.GetErrorString() << endl;
if (!targets.empty()) {
ERROR("Targets specified but no BAM index file provided.");
ERROR("FreeBayes cannot jump through targets in BAM files without BAM index files, exiting.");
ERROR("Please generate a BAM index file eithe, e.g.:");
ERROR(" \% bamtools index -in <bam_file>");
ERROR(" \% samtools index <bam_file>");
exit(1);
}
}
}
if (!bamMultiReader.SetExplicitMergeOrder(bamMultiReader.MergeByCoordinate)) {
ERROR("could not set sort order to coordinate");
cerr << bamMultiReader.GetErrorString() << endl;
exit(1);
}
}
// retrieve header information
bamHeader = bamMultiReader.GetHeaderText();
bamHeaderLines = split(bamHeader, '\n');
DEBUG(" done");
}
void AlleleParser::openTraceFile(void) {
if (parameters.trace) {
traceFile.open(parameters.traceFile.c_str(), ios::out);
DEBUG("Opening trace file: " << parameters.traceFile << " ...");
if (!traceFile) {
ERROR(" unable to open trace file: " << parameters.traceFile );
exit(1);
}
}
}
void AlleleParser::openFailedFile(void) {
if (!parameters.failedFile.empty()) {
failedFile.open(parameters.failedFile.c_str(), ios::out);
DEBUG("Opening failed alleles file: " << parameters.failedFile << " ...");
if (!failedFile) {
ERROR(" unable to open failed alleles file: " << parameters.failedFile );
exit(1);
}
}
}
void AlleleParser::openOutputFile(void) {
if (parameters.outputFile != "") {
outputFile.open(parameters.outputFile.c_str(), ios::out);
DEBUG("Opening output file: " << parameters.outputFile << " ...");
if (!outputFile) {
ERROR(" unable to open output file: " << parameters.outputFile);
exit(1);
}
output = &outputFile;
} else {
output = &cout;
}
}
void AlleleParser::getSequencingTechnologies(void) {
map<string, bool> technologies;
for (vector<string>::const_iterator it = bamHeaderLines.begin(); it != bamHeaderLines.end(); ++it) {
// get next line from header, skip if empty
string headerLine = *it;
if ( headerLine.empty() ) { continue; }
// lines of the header look like:
// "@RG ID:- SM:NA11832 CN:BCM PL:454"
// ^^^^^^^\ is our sample name
if ( headerLine.find("@RG") == 0 ) {
vector<string> readGroupParts = split(headerLine, "\t ");
string tech;
string readGroupID;
for (vector<string>::const_iterator r = readGroupParts.begin(); r != readGroupParts.end(); ++r) {
size_t colpos = r->find(":");
if (colpos != string::npos) {
string fieldname = r->substr(0, colpos);
if (fieldname == "PL") {
tech = r->substr(colpos+1);
} else if (fieldname == "ID") {
readGroupID = r->substr(colpos+1);
}
}
}
if (tech.empty()) {
if (!sequencingTechnologies.empty()) {
cerr << "no sequencing technology specified in @RG tag (no PL: in @RG tag) " << endl << headerLine << endl;
}
} else {
readGroupToTechnology[readGroupID] = tech;
technologies[tech] = true;
}
if (readGroupID.empty()) {
cerr << "could not find ID: in @RG tag " << endl << headerLine << endl;
continue;
}
//string name = nameParts.back();
//mergedHeader.append(1, '\n');
//cerr << "found read group id " << readGroupID << " containing sample " << name << endl;
}
}
for (map<string, bool>::iterator st = technologies.begin(); st != technologies.end(); ++st) {
sequencingTechnologies.push_back(st->first);
}
}
void AlleleParser::getPopulations(void) {
map<string, string> allSamplePopulation;
if (!parameters.populationsFile.empty()) {
ifstream populationsFile(parameters.populationsFile.c_str(), ios::in);
if (!populationsFile) {
cerr << "unable to open population file: " << parameters.populationsFile << endl;
exit(1);
}
string line;
while (getline(populationsFile, line)) {
DEBUG2("found sample-population mapping: " << line);
vector<string> popsample = split(line, "\t ");
if (popsample.size() == 2) {
string& sample = popsample.front();
string& population = popsample.back();
DEBUG2("sample: " << sample << " population: " << population);
allSamplePopulation[sample] = population;
} else {
cerr << "malformed population/sample pair, " << line << endl;
exit(1);
}
}
}
// XXX
// TODO now, assign a default population to all the rest of the samples...
// XXX
for (vector<string>::iterator s = sampleList.begin(); s != sampleList.end(); ++s) {
if (!allSamplePopulation.count(*s)) {
samplePopulation[*s] = "DEFAULT";
} else {
samplePopulation[*s] = allSamplePopulation[*s];
}
}
// now, only keep the samples we are using for processing
for (map<string, string>::iterator s = samplePopulation.begin(); s != samplePopulation.end(); ++s) {
populationSamples[s->second].push_back(s->first);
}
}
// read sample list file or get sample names from bam file header
void AlleleParser::getSampleNames(void) {
// If a sample file is given, use it. But otherwise process the bam file
// header to get the sample names.
//
if (!parameters.samples.empty()) {
ifstream sampleFile(parameters.samples.c_str(), ios::in);
if (! sampleFile) {
cerr << "unable to open file: " << parameters.samples << endl;
exit(1);
}
string line;
while (getline(sampleFile, line)) {
DEBUG2("found sample " << line);
sampleList.push_back(line);
}
}
for (vector<string>::const_iterator it = bamHeaderLines.begin(); it != bamHeaderLines.end(); ++it) {
// get next line from header, skip if empty
string headerLine = *it;
if ( headerLine.empty() ) { continue; }
// lines of the header look like:
// "@RG ID:- SM:NA11832 CN:BCM PL:454"
// ^^^^^^^\ is our sample name
if ( headerLine.find("@RG") == 0 ) {
vector<string> readGroupParts = split(headerLine, "\t ");
string name = "";
string readGroupID = "";
for (vector<string>::const_iterator r = readGroupParts.begin(); r != readGroupParts.end(); ++r) {
size_t colpos = r->find(":");
if (colpos != string::npos) {
string fieldname = r->substr(0, colpos);
if (fieldname == "SM") {
name = r->substr(colpos+1);
} else if (fieldname == "ID") {
readGroupID = r->substr(colpos+1);
}
}
}
if (name == "") {
ERROR(" could not find SM: in @RG tag " << endl << headerLine);
exit(1);
}
if (readGroupID == "") {
ERROR(" could not find ID: in @RG tag " << endl << headerLine);
exit(1);
}
//string name = nameParts.back();
//mergedHeader.append(1, '\n');
DEBUG2("found read group id " << readGroupID << " containing sample " << name);
sampleListFromBam.push_back(name);
map<string, string>::iterator s = readGroupToSampleNames.find(readGroupID);
if (s != readGroupToSampleNames.end()) {
if (s->second != name) {
ERROR("ERROR: multiple samples (SM) map to the same read group (RG)" << endl
<< endl
<< "samples " << name << " and " << s->second << " map to " << readGroupID << endl
<< endl
<< "As freebayes operates on a virtually merged stream of its input files," << endl
<< "it will not be possible to determine what sample an alignment belongs to" << endl
<< "at runtime." << endl
<< endl
<< "To resolve the issue, ensure that RG ids are unique to one sample" << endl
<< "across all the input files to freebayes." << endl
<< endl
<< "See bamaddrg (https://github.com/ekg/bamaddrg) for a method which can" << endl
<< "add RG tags to alignments." << endl);
exit(1);
}
// if it's the same sample name and RG combo, no worries
}
readGroupToSampleNames[readGroupID] = name;
}
}
//cout << sampleListFromBam.size() << endl;
// no samples file given, read from BAM file header for sample names
if (sampleList.empty()) {
DEBUG("no sample list file given, reading sample names from bam file");
for (vector<string>::const_iterator s = sampleListFromBam.begin(); s != sampleListFromBam.end(); ++s) {
DEBUG2("found sample " << *s);
if (!stringInVector(*s, sampleList)) {
sampleList.push_back(*s);
}
}
DEBUG("found " << sampleList.size() << " samples in BAM file");
} else {
// verify that the samples in the sample list are present in the bam,
// and raise an error and exit if not
for (vector<string>::const_iterator s = sampleList.begin(); s != sampleList.end(); ++s) {
bool inBam = false;
bool inReadGroup = false;
//cout << "checking sample from sample file " << *s << endl;
for (vector<string>::const_iterator b = sampleListFromBam.begin(); b != sampleListFromBam.end(); ++b) {
//cout << *s << " against " << *b << endl;
if (*s == *b) { inBam = true; break; }
}
for (map<string, string>::const_iterator p = readGroupToSampleNames.begin(); p != readGroupToSampleNames.end(); ++p) {
if (*s == p->second) { inReadGroup = true; break; }
}
if (!inBam) {
ERROR("sample " << *s << " listed in sample file "
<< parameters.samples.c_str() << " is not listed in the header of BAM file(s) "
<< parameters.bam);
exit(1);
}
if (!inReadGroup) {
ERROR("sample " << *s << " listed in sample file "
<< parameters.samples.c_str() << " is not associated with any read group in the header of BAM file(s) "
<< parameters.bam);
exit(1);
}
}
}
if (sampleList.empty()) {
/*
ERROR(string(80, '-') << endl
//--------------------------------------------------------------------------------
<< "Warning: No sample file given, and no @RG tags found in BAM header." << endl
<< "All alignments from all input files will be assumed to come from the same" << endl
<< "individual. To group alignments by sample, you must add read groups and sample" << endl
<< "names to your alignments. You can do this using ./scripts/sam_add_rg.pl in the" << endl
<< "freebayes source tree, or by specifying read groups and sample names when you" << endl
<< "prepare your sequencing data for alignment." << endl
<< string(80, '-'));
*/
sampleList.push_back("unknown");
readGroupToSampleNames["unknown"] = "unknown";
oneSampleAnalysis = true;
}
}
string AlleleParser::vcfHeader() {
stringstream headerss;
headerss
<< "##fileformat=VCFv4.1" << endl
<< "##fileDate=" << dateStr() << endl
<< "##source=freeBayes " << VERSION_GIT << endl
<< "##reference=" << reference.filename << endl
<< "##phasing=none" << endl
<< "##commandline=\"" << parameters.commandline << "\"" << endl
<< "##INFO=<ID=NS,Number=1,Type=Integer,Description=\"Number of samples with data\">" << endl
<< "##INFO=<ID=DP,Number=1,Type=Integer,Description=\"Total read depth at the locus\">" << endl
<< "##INFO=<ID=DPB,Number=1,Type=Float,Description=\"Total read depth per bp at the locus; bases in reads overlapping / bases in haplotype\">" << endl
// allele frequency metrics
<< "##INFO=<ID=AC,Number=A,Type=Integer,Description=\"Total number of alternate alleles in called genotypes\">" << endl
<< "##INFO=<ID=AN,Number=1,Type=Integer,Description=\"Total number of alleles in called genotypes\">" << endl
<< "##INFO=<ID=AF,Number=A,Type=Float,Description=\"Estimated allele frequency in the range (0,1]\">" << endl
// observation counts
<< "##INFO=<ID=RO,Number=1,Type=Integer,Description=\"Reference allele observation count, with partial observations recorded fractionally\">" << endl
<< "##INFO=<ID=AO,Number=A,Type=Integer,Description=\"Alternate allele observations, with partial observations recorded fractionally\">" << endl
<< "##INFO=<ID=PRO,Number=1,Type=Float,Description=\"Reference allele observation count, with partial observations recorded fractionally\">" << endl
<< "##INFO=<ID=PAO,Number=A,Type=Float,Description=\"Alternate allele observations, with partial observations recorded fractionally\">" << endl
// qualities
<< "##INFO=<ID=QR,Number=1,Type=Integer,Description=\"Reference allele quality sum in phred\">" << endl
<< "##INFO=<ID=QA,Number=A,Type=Integer,Description=\"Alternate allele quality sum in phred\">" << endl
<< "##INFO=<ID=PQR,Number=1,Type=Float,Description=\"Reference allele quality sum in phred for partial observations\">" << endl
<< "##INFO=<ID=PQA,Number=A,Type=Float,Description=\"Alternate allele quality sum in phred for partial observations\">" << endl
// binomial balance metrics
<< "##INFO=<ID=SRF,Number=1,Type=Integer,Description=\"Number of reference observations on the forward strand\">" << endl
<< "##INFO=<ID=SRR,Number=1,Type=Integer,Description=\"Number of reference observations on the reverse strand\">" << endl
<< "##INFO=<ID=SAF,Number=A,Type=Integer,Description=\"Number of alternate observations on the forward strand\">" << endl
<< "##INFO=<ID=SAR,Number=A,Type=Integer,Description=\"Number of alternate observations on the reverse strand\">" << endl
//<< "##INFO=<ID=SRB,Number=1,Type=Float,Description=\"Strand bias for the reference allele: SRF / ( SRF + SRR )\">" << endl
//<< "##INFO=<ID=SAB,Number=1,Type=Float,Description=\"Strand bias for the alternate allele: SAF / ( SAF + SAR )\">" << endl
<< "##INFO=<ID=SRP,Number=1,Type=Float,Description=\"Strand balance probability for the reference allele: Phred-scaled upper-bounds estimate of the probability of observing the deviation between SRF and SRR given E(SRF/SRR) ~ 0.5, derived using Hoeffding's inequality\">" << endl
<< "##INFO=<ID=SAP,Number=A,Type=Float,Description=\"Strand balance probability for the alternate allele: Phred-scaled upper-bounds estimate of the probability of observing the deviation between SAF and SAR given E(SAF/SAR) ~ 0.5, derived using Hoeffding's inequality\">" << endl
//<< "##INFO=<ID=ABR,Number=1,Type=Integer,Description=\"Reference allele balance count: the number of sequence reads from apparent heterozygotes supporting the reference allele\">" << endl
//<< "##INFO=<ID=ABA,Number=1,Type=Integer,Description=\"Alternate allele balance count: the number of sequence reads from apparent heterozygotes supporting the alternate allele\">" << endl
<< "##INFO=<ID=AB,Number=A,Type=Float,Description=\"Allele balance at heterozygous sites: a number between 0 and 1 representing the ratio of reads showing the reference allele to all reads, considering only reads from individuals called as heterozygous\">" << endl
<< "##INFO=<ID=ABP,Number=A,Type=Float,Description=\"Allele balance probability at heterozygous sites: Phred-scaled upper-bounds estimate of the probability of observing the deviation between ABR and ABA given E(ABR/ABA) ~ 0.5, derived using Hoeffding's inequality\">" << endl
<< "##INFO=<ID=RUN,Number=A,Type=Integer,Description=\"Run length: the number of consecutive repeats of the alternate allele in the reference genome\">" << endl
//<< "##INFO=<ID=RL,Number=1,Type=Integer,Description=\"Reads Placed Left: number of reads supporting the alternate balanced to the left (5') of the alternate allele\">" << endl
//<< "##INFO=<ID=RR,Number=1,Type=Integer,Description=\"Reads Placed Right: number of reads supporting the alternate balanced to the right (3') of the alternate allele\">" << endl
<< "##INFO=<ID=RPP,Number=A,Type=Float,Description=\"Read Placement Probability: Phred-scaled upper-bounds estimate of the probability of observing the deviation between RPL and RPR given E(RPL/RPR) ~ 0.5, derived using Hoeffding's inequality\">" << endl
<< "##INFO=<ID=RPPR,Number=1,Type=Float,Description=\"Read Placement Probability for reference observations: Phred-scaled upper-bounds estimate of the probability of observing the deviation between RPL and RPR given E(RPL/RPR) ~ 0.5, derived using Hoeffding's inequality\">" << endl
<< "##INFO=<ID=RPL,Number=A,Type=Float,Description=\"Reads Placed Left: number of reads supporting the alternate balanced to the left (5') of the alternate allele\">" << endl
//<< "##INFO=<ID=RPLR,Number=A,Type=Float,Description=\"Reads Placed Left: number of reads supporting the alternate balanced to the left (5') of the alternate allele\">" << endl
<< "##INFO=<ID=RPR,Number=A,Type=Float,Description=\"Reads Placed Right: number of reads supporting the alternate balanced to the right (3') of the alternate allele\">" << endl
//<< "##INFO=<ID=RPRR,Number=A,Type=Float,Description=\"Reads Placed Right: number of reads supporting the alternate balanced to the right (3') of the alternate allele\">" << endl
//<< "##INFO=<ID=EL,Number=1,Type=Integer,Description=\"Allele End Left: number of observations of the alternate where the alternate occurs in the left end of the read\">" << endl
//<< "##INFO=<ID=ER,Number=1,Type=Integer,Description=\"Allele End Right: number of observations of the alternate where the alternate occurs in the right end of the read\">" << endl
<< "##INFO=<ID=EPP,Number=A,Type=Float,Description=\"End Placement Probability: Phred-scaled upper-bounds estimate of the probability of observing the deviation between EL and ER given E(EL/ER) ~ 0.5, derived using Hoeffding's inequality\">" << endl
<< "##INFO=<ID=EPPR,Number=1,Type=Float,Description=\"End Placement Probability for reference observations: Phred-scaled upper-bounds estimate of the probability of observing the deviation between EL and ER given E(EL/ER) ~ 0.5, derived using Hoeffding's inequality\">" << endl
//<< "##INFO=<ID=BL,Number=1,Type=Integer,Description=\"Base Pairs Left: number of base pairs in reads supporting the alternate to the left (5') of the alternate allele\">" << endl
//<< "##INFO=<ID=BR,Number=1,Type=Integer,Description=\"Base Pairs Right: number of base pairs in reads supporting the alternate to the right (3') of the alternate allele\">" << endl
//<< "##INFO=<ID=LRB,Number=1,Type=Float,Description=\"((max(BR, BL) / (BR + BL)) - 0.5) * 2 : The proportion of base pairs in reads on one side of the alternate allele relative to total bases, scaled from [0.5,1] to [0,1]\">" << endl
//<< "##INFO=<ID=LRBP,Number=1,Type=Float,Description=\"Left-Right Balance Probability: Phred-scaled upper-bounds estimate of the probability of observing the deviation between BL and BR given E(BR/BL) ~ 0.5, derived using Hoeffding's inequality\">" << endl
<< "##INFO=<ID=DPRA,Number=A,Type=Float,Description=\"Alternate allele depth ratio. Ratio between depth in samples with each called alternate allele and those without.\">" << endl
// error rates
/*
<< "##INFO=<ID=XRM,Number=1,Type=Float,Description=\"Reference allele read mismatch rate: The rate of SNPs + MNPs + INDELs in reads supporting the reference allele.\">" << endl
<< "##INFO=<ID=XRS,Number=1,Type=Float,Description=\"Reference allele read SNP rate: The rate of per-base mismatches (SNPs + MNPs) in reads supporting the reference allele.\">" << endl
<< "##INFO=<ID=XRI,Number=1,Type=Float,Description=\"Reference allele read INDEL rate: The rate of INDELs (gaps) in reads supporting the reference allele.\">" << endl
<< "##INFO=<ID=XAM,Number=A,Type=Float,Description=\"Alternate allele read mismatch rate: The rate of SNPs + MNPs + INDELs in reads supporting the alternate allele, excluding the called variant.\">" << endl
<< "##INFO=<ID=XAS,Number=A,Type=Float,Description=\"Alternate allele read SNP rate: The rate of per-base mismatches (SNPs + MNPs) in reads supporting the alternate allele, excluding the called variant.\">" << endl
<< "##INFO=<ID=XAI,Number=A,Type=Float,Description=\"Alternate allele read INDEL rate: The rate of INDELs (gaps) in reads supporting the alternate allele, excluding the called variant.\">" << endl
*/
// error rate ratios
//<< "##INFO=<ID=ARM,Number=A,Type=Float,Description=\"Alternate allele / reference allele read mismatch ratio: The rate of SNPs + MNPs + INDELs in reads supporting the alternate allele versus reads supporting the reference allele, excluding the called variant.\">" << endl
//<< "##INFO=<ID=ARS,Number=A,Type=Float,Description=\"Alternate allele / reference allele read SNP ratio: The rate of per-base mismatches (SNPs + MNPs) in reads supporting the alternate allele versus reads supporting the reference allele, excluding the called variant.\">" << endl
//<< "##INFO=<ID=ARI,Number=A,Type=Float,Description=\"Alternate allele / reference allele read INDEL ratio: The ratio in rate rate of INDELs (gaps) in reads supporting the alternate allele versus reads supporting the reference allele, excluding the called variant.\">" << endl
// supplementary information about the site
<< "##INFO=<ID=ODDS,Number=1,Type=Float,Description=\"The log odds ratio of the best genotype combination to the second-best.\">" << endl
<< "##INFO=<ID=GTI,Number=1,Type=Integer,Description=\"Number of genotyping iterations required to reach convergence or bailout.\">" << endl
//<< "##INFO=<ID=TS,Number=0,Type=Flag,Description=\"site has transition SNP\">" << endl
//<< "##INFO=<ID=TV,Number=0,Type=Flag,Description=\"site has transversion SNP\">" << endl
//<< "##INFO=<ID=CpG,Number=0,Type=Flag,Description=\"CpG site (either CpG, TpG or CpA)\">" << endl
<< "##INFO=<ID=TYPE,Number=A,Type=String,Description=\"The type of allele, either snp, mnp, ins, del, or complex.\">" << endl
<< "##INFO=<ID=CIGAR,Number=A,Type=String,Description=\"The extended CIGAR representation of each alternate allele, with the exception that '=' is replaced by 'M' to ease VCF parsing. Note that INDEL alleles do not have the first matched base (which is provided by default, per the spec) referred to by the CIGAR.\">" << endl
//<< "##INFO=<ID=SNP,Number=0,Type=Flag,Description=\"SNP allele at site\">" << endl
//<< "##INFO=<ID=MNP,Number=0,Type=Flag,Description=\"MNP allele at site\">" << endl
//<< "##INFO=<ID=INS,Number=0,Type=Flag,Description=\"insertion allele at site\">" << endl
//<< "##INFO=<ID=DEL,Number=0,Type=Flag,Description=\"deletion allele at site\">" << endl
//<< "##INFO=<ID=COMPLEX,Number=0,Type=Flag,Description=\"complex allele (insertion/deletion/substitution composite) at site\">" << endl
<< "##INFO=<ID=NUMALT,Number=1,Type=Integer,Description=\"Number of unique non-reference alleles in called genotypes at this position.\">" << endl
<< "##INFO=<ID=MEANALT,Number=A,Type=Float,Description=\"Mean number of unique non-reference allele observations per sample with the corresponding alternate alleles.\">" << endl
//<< "##INFO=<ID=HWE,Number=1,Type=Float,Description=\"Phred-scaled discrete HWE prior probability of the genotyping across all samples.\">" << endl
<< "##INFO=<ID=LEN,Number=A,Type=Integer,Description=\"allele length\">" << endl
<< "##INFO=<ID=MQM,Number=A,Type=Float,Description=\"Mean mapping quality of observed alternate alleles\">" << endl
<< "##INFO=<ID=MQMR,Number=1,Type=Float,Description=\"Mean mapping quality of observed reference alleles\">" << endl
<< "##INFO=<ID=PAIRED,Number=A,Type=Float,Description=\"Proportion of observed alternate alleles which are supported by properly paired read fragments\">" << endl
<< "##INFO=<ID=PAIREDR,Number=1,Type=Float,Description=\"Proportion of observed reference alleles which are supported by properly paired read fragments\">" << endl;
// sequencing technology tags, which vary according to input data
for (vector<string>::iterator st = sequencingTechnologies.begin(); st != sequencingTechnologies.end(); ++st) {
string& tech = *st;
headerss << "##INFO=<ID=technology." << tech << ",Number=A,Type=Float,Description=\"Fraction of observations supporting the alternate observed in reads from " << tech << "\">" << endl;
}
if (parameters.showReferenceRepeats) {
headerss << "##INFO=<ID=REPEAT,Number=1,Type=String,Description=\"Description of the local repeat structures flanking the current position\">" << endl;
}
// format fields for genotypes
headerss << "##FORMAT=<ID=GT,Number=1,Type=String,Description=\"Genotype\">" << endl
<< "##FORMAT=<ID=GQ,Number=1,Type=Float,Description=\"Genotype Quality, the Phred-scaled marginal (or unconditional) probability of the called genotype\">" << endl
// this can be regenerated with RA, AA, QR, QA
<< "##FORMAT=<ID=GL,Number=G,Type=Float,Description=\"Genotype Likelihood, log10-scaled likelihoods of the data given the called genotype for each possible genotype generated from the reference and alternate alleles given the sample ploidy\">" << endl
//<< "##FORMAT=<ID=GLE,Number=1,Type=String,Description=\"Genotype Likelihood Explicit, same as GL, but with tags to indicate the specific genotype. For instance, 0^-75.22|1^-223.42|0/0^-323.03|1/0^-99.29|1/1^-802.53 represents both haploid and diploid genotype likilehoods in a biallelic context\">" << endl
<< "##FORMAT=<ID=DP,Number=1,Type=Integer,Description=\"Read Depth\">" << endl
<< "##FORMAT=<ID=RO,Number=1,Type=Integer,Description=\"Reference allele observation count\">" << endl
<< "##FORMAT=<ID=QR,Number=1,Type=Integer,Description=\"Sum of quality of the reference observations\">" << endl
<< "##FORMAT=<ID=AO,Number=A,Type=Integer,Description=\"Alternate allele observation count\">" << endl
<< "##FORMAT=<ID=QA,Number=A,Type=Integer,Description=\"Sum of quality of the alternate observations\">" << endl
//<< "##FORMAT=<ID=SRF,Number=1,Type=Integer,Description=\"Number of reference observations on the forward strand\">" << endl
//<< "##FORMAT=<ID=SRR,Number=1,Type=Integer,Description=\"Number of reference observations on the reverse strand\">" << endl
//<< "##FORMAT=<ID=SAF,Number=1,Type=Integer,Description=\"Number of alternate observations on the forward strand\">" << endl
//<< "##FORMAT=<ID=SAR,Number=1,Type=Integer,Description=\"Number of alternate observations on the reverse strand\">" << endl
//<< "##FORMAT=<ID=LR,Number=1,Type=Integer,Description=\"Number of reference observations placed left of the loci\">" << endl
//<< "##FORMAT=<ID=LA,Number=1,Type=Integer,Description=\"Number of alternate observations placed left of the loci\">" << endl
//<< "##FORMAT=<ID=ER,Number=1,Type=Integer,Description=\"Number of reference observations overlapping the loci in their '3 end\">" << endl
//<< "##FORMAT=<ID=EA,Number=1,Type=Integer,Description=\"Number of alternate observations overlapping the loci in their '3 end\">" << endl
<< "#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT\t"
<< join(sampleList, "\t") << endl;
return headerss.str();
}
void AlleleParser::setupVCFOutput(void) {
string vcfheader = vcfHeader();
variantCallFile.openForOutput(vcfheader);
}
void AlleleParser::setupVCFInput(void) {
// variant input for analysis and targeting
if (!parameters.variantPriorsFile.empty()) {
variantCallInputFile.open(parameters.variantPriorsFile);
currentVariant = new vcf::Variant(variantCallInputFile);
usingVariantInputAlleles = true;
// get sample names from VCF input file
//
// NB, adding this stanza will change the way that the VCF output
// describes alternates, present observations, etc. so that the samples
// in the VCF input are also included. the result is confusing output,
// but it could be useful in some situations.
//
// TODO optionally include this (via command-line parameter)
//
//for (vector<string>::iterator s = variantCallInputFile.sampleNames.begin(); s != variantCallInputFile.sampleNames.end(); ++s) {
// sampleList.push_back(*s);
//}
}
// haplotype alleles for constructing haplotype alleles
if (!parameters.haplotypeVariantFile.empty()) {
haplotypeVariantInputFile.open(parameters.haplotypeVariantFile);
usingHaplotypeBasisAlleles = true;
}
}
void AlleleParser::loadBamReferenceSequenceNames(void) {
//--------------------------------------------------------------------------
// read reference sequences from input file
//--------------------------------------------------------------------------
// store the names of all the reference sequences in the BAM file
referenceSequences = bamMultiReader.GetReferenceData();
int i = 0;
for (RefVector::iterator r = referenceSequences.begin(); r != referenceSequences.end(); ++r) {
referenceIDToName[i] = r->RefName;
++i;
}
DEBUG("Number of ref seqs: " << bamMultiReader.GetReferenceCount());
}
void AlleleParser::loadFastaReference(void) {
DEBUG("loading fasta reference " << parameters.fasta);
// This call loads the reference and reads any index file it can find. If
// it can't find an index file for the reference, it will attempt to
// generate one alongside it. Note that this only loads the reference.
// Sequence data is obtained by progressive calls to
// reference.getSubSequence(..), thus keeping our memory requirements low.
reference.open(parameters.fasta);
}
bool AlleleParser::hasMoreInputVariants(void) {
pair<int, long> next = nextInputVariantPosition();
return next.first != -1;
}
bool AlleleParser::loadNextPositionWithAlignmentOrInputVariant(BamAlignment& alignment) {
pair<int, long> next = nextInputVariantPosition();
if (next.first != -1) {
int varRefID = next.first;
//cerr << varRefID << " " << alignment.RefID << " " << next.second << " " << alignment.Position << endl;
if (!hasMoreAlignments || varRefID < alignment.RefID || varRefID == alignment.RefID && next.second < alignment.Position) {
return loadNextPositionWithInputVariant();
} else {
loadReferenceSequence(alignment);
}
} else {
loadReferenceSequence(alignment);
}
return true;
}
bool AlleleParser::loadNextPositionWithInputVariant(void) {
pair<int, long> next = nextInputVariantPosition();
if (next.first != -1) {
//cerr << "Next is " << next.first << ":" << next.second << endl;
loadReferenceSequence(referenceIDToName[next.first]);
currentPosition = next.second;
rightmostHaplotypeBasisAllelePosition = currentPosition;
return true;
} else {
return false;
}
}
// alignment-based method for loading the first bit of our reference sequence
void AlleleParser::loadReferenceSequence(BamAlignment& alignment) {
loadReferenceSequence(referenceIDToName[alignment.RefID]);
currentPosition = alignment.Position;
}
void AlleleParser::loadReferenceSequence(string& seqname) {
if (currentSequenceName != seqname) {
currentSequenceName = seqname;
currentSequenceStart = 0;
currentRefID = bamMultiReader.GetReferenceID(currentSequenceName);
currentSequence = uppercase(reference.getSequence(currentSequenceName));
}
}
void AlleleParser::loadTargets(void) {
// if we have a targets file, use it...
// if target file specified use targets from file
if (!parameters.targets.empty()) {
DEBUG("Making BedReader object for target file: " << parameters.targets << " ...");
bedReader.openFile(parameters.targets);
if (!bedReader.is_open()) {
ERROR("Unable to open target file: " << parameters.targets << "... terminating.");
exit(1);
}
targets = bedReader.targets;
if (targets.empty()) {
ERROR("Could not load any targets from " << parameters.targets);
exit(1);
}
bedReader.close();
DEBUG("done");
}
// if we have a region specified, use it to generate a target
for (vector<string>::iterator r = parameters.regions.begin(); r != parameters.regions.end(); ++r) {
// drawn from bamtools_utilities.cpp, modified to suit 1-based context, no end sequence
string region = *r;
string startSeq;
int startPos;
int stopPos;
size_t foundFirstColon = region.find(":");
// we only have a single string, use the whole sequence as the target
if (foundFirstColon == string::npos) {
startSeq = region;
startPos = 0;
stopPos = -1;
} else {
startSeq = region.substr(0, foundFirstColon);
string sep = "..";
size_t foundRangeSep = region.find(sep, foundFirstColon);
if (foundRangeSep == string::npos) {
sep = "-";
foundRangeSep = region.find("-", foundFirstColon);
}
if (foundRangeSep == string::npos) {
startPos = atoi(region.substr(foundFirstColon + 1).c_str());
// differ from bamtools in this regard, in that we process only
// the specified position if a range isn't given
stopPos = startPos + 1;
} else {
startPos = atoi(region.substr(foundFirstColon + 1, foundRangeSep - foundFirstColon).c_str());
// if we have range sep specified, but no second number, read to the end of sequence
if (foundRangeSep + sep.size() != region.size()) {
stopPos = atoi(region.substr(foundRangeSep + sep.size()).c_str()); // end-exclusive, bed-format
} else {
stopPos = -1;
}
}
}
//DEBUG("startPos == " << startPos);
//DEBUG("stopPos == " << stopPos);
// REAL BED format is 0 based, half open (end base not included)
BedTarget bd(startSeq,
(startPos == 0) ? 0 : startPos,
((stopPos == -1) ? reference.sequenceLength(startSeq) : stopPos) - 1); // internally, we use 0-base inclusive end
DEBUG("will process reference sequence " << startSeq << ":" << bd.left << ".." << bd.right + 1);
targets.push_back(bd);
bedReader.targets.push_back(bd);
}
// check validity of targets wrt. reference
for (vector<BedTarget>::iterator e = targets.begin(); e != targets.end(); ++e) {
BedTarget& bd = *e;
// internally, we use 0-base inclusive end
if (bd.left < 0 || bd.right + 1 > reference.sequenceLength(bd.seq)) {
ERROR("Target region coordinates (" << bd.seq << " "
<< bd.left << " " << bd.right + 1
<< ") outside of reference sequence bounds ("
<< bd.seq << " " << reference.sequenceLength(bd.seq) << ") terminating.");
exit(1);
}
if (bd.right < bd.left) {
ERROR("Invalid target region coordinates (" << bd.seq << " " << bd.left << " " << bd.right + 1 << ")"
<< " right bound is lower than left bound!");
exit(1);
}
}
bedReader.buildIntervals(); // set up interval tree in the bedreader
DEBUG("Number of target regions: " << targets.size());
}
void AlleleParser::loadTargetsFromBams(void) {
// otherwise, if we weren't given a region string or targets file, analyze
// all reference sequences from BAM file
DEBUG2("no targets specified, using all targets from BAM files");
RefVector::iterator refIter = referenceSequences.begin();
RefVector::iterator refEnd = referenceSequences.end();
for( ; refIter != refEnd; ++refIter) {
RefData refData = *refIter;
string refName = refData.RefName;
BedTarget bd(refName, 0, refData.RefLength); // 0-based inclusive internally
DEBUG2("will process reference sequence " << refName << ":" << bd.left << ".." << bd.right + 1);
targets.push_back(bd);
}
}
void AlleleParser::loadSampleCNVMap(void) {
// set default ploidy
sampleCNV.setDefaultPloidy(parameters.ploidy);
// load CNV map if provided
if (!parameters.cnvFile.empty()) {
if (!sampleCNV.load(parameters.cnvFile)) {
ERROR("could not load sample map " << parameters.cnvFile << " ... exiting!");
exit(1);
}
}
// to assert that the reference is haploid, we can iterate through the BAM
// header to get the reference names and sizes, and then setPloidy on them
// in the sampleCNV map. note that the reference "sample" is named after
// the current reference sequence.
if (!parameters.diploidReference) {
for (RefVector::iterator r = referenceSequences.begin(); r != referenceSequences.end(); ++r) {
sampleCNV.setPloidy(referenceSampleName, r->RefName, 0, r->RefLength, 1);
}
}
}
int AlleleParser::currentSamplePloidy(string const& sample) {
return sampleCNV.ploidy(sample, currentSequenceName, currentPosition);
}
int AlleleParser::copiesOfLocus(Samples& samples) {
int copies = 0;
for (Samples::iterator s = samples.begin(); s != samples.end(); ++s) {
string const& name = s->first;
copies += currentSamplePloidy(name);
}
return copies;
}
vector<int> AlleleParser::currentPloidies(Samples& samples) {
map<int, bool> ploidiesMap;
vector<int> ploidies;
for (Samples::iterator s = samples.begin(); s != samples.end(); ++s) {
string const& name = s->first;
int samplePloidy = currentSamplePloidy(name);
ploidiesMap[samplePloidy] = true;
}
ploidiesMap[parameters.ploidy] = true;
for (map<int, bool>::iterator p = ploidiesMap.begin(); p != ploidiesMap.end(); ++p) {
ploidies.push_back(p->first);
}
return ploidies;
}
// meant to be used when we are reading from stdin, to check if we are within targets
bool AlleleParser::inTarget(void) {
if (targets.empty()) {
return true; // everything is in target if we don't have targets
} else {
// expects 0-based, fully-closed, and we're only checking a single
// base, so start == end.
if (bedReader.targetsOverlap(currentSequenceName, currentPosition, currentPosition)) {
return true;
} else {
return false;
}
}
}
// initialization function
// sets up environment so we can start registering alleles
AlleleParser::AlleleParser(int argc, char** argv) : parameters(Parameters(argc, argv))
{
oneSampleAnalysis = false;
currentRefID = 0; // will get set properly via toNextRefID
currentPosition = 0;
currentTarget = NULL; // to be initialized on first call to getNextAlleles
currentReferenceAllele = NULL; // same, NULL is brazenly used as an initialization flag
justSwitchedTargets = false; // flag to trigger cleanup of Allele*'s and objects after jumping targets
hasMoreAlignments = true; // flag to track when we run out of alignments in the current target or BAM files
currentSequenceStart = 0;
lastHaplotypeLength = 0;
usingHaplotypeBasisAlleles = false;
usingVariantInputAlleles = false;
rightmostHaplotypeBasisAllelePosition = 0;
rightmostInputAllelePosition = 0;
nullSample = new Sample();
referenceSampleName = "reference_sample";
// initialization
openTraceFile();
openFailedFile();
openOutputFile();
loadFastaReference();
// when we open the bam files we can use the number of targets to decide if
// we should load the indexes
openBams();
loadBamReferenceSequenceNames();
// check how many targets we have specified
loadTargets();
getSampleNames();
getPopulations();
getSequencingTechnologies();
// sample CNV
loadSampleCNVMap();
// output
setupVCFOutput();
// input
// (now that the VCF file is set up with the samples which are in the input alignments
// add the samples from the input VCF to the mix)
setupVCFInput();
}
AlleleParser::~AlleleParser(void) {
delete nullSample;
// close trace file? seems to get closed properly on object deletion...
if (currentReferenceAllele) delete currentReferenceAllele;
if (variantCallInputFile.is_open()) delete currentVariant;
}
// position of alignment relative to current sequence
int AlleleParser::currentSequencePosition(const BamAlignment& alignment) {
return alignment.Position - currentSequenceStart;
}
// relative current position within the cached currentSequence
int AlleleParser::currentSequencePosition() {
return currentPosition - currentSequenceStart;
}
char AlleleParser::currentReferenceBaseChar(void) {
return toupper(*currentReferenceBaseIterator());
}
string AlleleParser::currentReferenceBaseString(void) {
return currentSequence.substr(floor(currentPosition) - currentSequenceStart, 1);
}
string::iterator AlleleParser::currentReferenceBaseIterator(void) {
return currentSequence.begin() + (floor(currentPosition) - currentSequenceStart);
}
string AlleleParser::currentReferenceHaplotype(void) {
return currentSequence.substr(floor(currentPosition) - currentSequenceStart, lastHaplotypeLength);
}
string AlleleParser::referenceSubstr(long int pos, unsigned int len) {
return uppercase(reference.getSubSequence(currentSequenceName, floor(pos), len));
}
bool AlleleParser::isCpG(string& altbase) {
// bounds check
if (floor(currentPosition) - currentSequenceStart - 1 < 0
|| floor(currentPosition) - currentSequenceStart + 1 >= currentSequence.size()) {
return false;
}
string prevb = currentSequence.substr(floor(currentPosition) - currentSequenceStart - 1, 1);
string currb = currentSequence.substr(floor(currentPosition) - currentSequenceStart, 1);
string nextb = currentSequence.substr(floor(currentPosition) - currentSequenceStart + 1, 1);
// 5'-3' CpG <-> TpG is represented as CpG <-> CpA in on the opposite strand
if ((nextb == "G" && ((currb == "C" && altbase == "T") || (currb == "T" && altbase == "C")))
||
(prevb == "C" && ((currb == "G" && altbase == "A") || (currb == "A" && altbase == "G"))))
{
return true;
} else {
return false;
}
}
void capBaseQuality(BamAlignment& alignment, int baseQualityCap) {
string& rQual = alignment.Qualities;
char qualcap = qualityInt2Char(baseQualityCap);
for (string::iterator c = rQual.begin(); c != rQual.end(); ++c) {
if (qualityChar2ShortInt(*c) > baseQualityCap) {
*c = qualcap;
}
}
}
void RegisteredAlignment::addAllele(Allele newAllele, bool mergeComplex, int maxComplexGap, bool boundIndels) {
// allele combination rules. combine the last allele in the list of allele
// observations according to the following rules
// 0) reference + SNP, MNP
// 1) INDEL + (REF <= maxComplexGap) + MNP, INDEL + (REF <= maxComplexGap) + SNP -> complex
// 2) MNP + SNP, SNP + SNP -> MNP
// 2) reference + INDEL -> reference.substr(0, reference.size() - 1), reference.at(reference.size()) + INDEL
if (newAllele.alternateSequence.size() != newAllele.baseQualities.size()) {
cerr << "new allele qualities not == in length to sequence: " << newAllele << endl;
assert(false);
}
//cerr << "adding allele " << newAllele << " to " << alleles.size() << " alleles" << endl;
//if (!alleles.empty()) { cerr << "last allele " << alleles.back() << endl; }
alleleTypes |= newAllele.type;
if (alleles.empty()) {
// presently, it's unclear how to handle insertions and deletions
// reported at the beginning of the read. are these events actually
// indicative of longer alleles?
if (boundIndels && (newAllele.isInsertion() || newAllele.isDeletion() || !newAllele.isNull())) {
// ignore the allele
} else {
alleles.push_back(newAllele);
}
// the same goes for insertions and deletions at the end of reads,
// these must be dealt with elsewhere
} else {
Allele& lastAllele = alleles.back();
if (isEmptyAllele(newAllele) ||
newAllele.isReference() && newAllele.referenceLength == 0) {
// do nothing
} else if (newAllele.isReference() && isUnflankedIndel(lastAllele)) {
// add flanking base to indel, ensuring haplotype length of 2 for all indels
string seq; vector<pair<int, string> > cig; vector<short> quals;
//cerr << "subtracting from start " << newAllele << " giving to " << lastAllele << endl;
newAllele.subtractFromStart(1, seq, cig, quals);
lastAllele.addToEnd(seq, cig, quals);
//cerr << "done " << newAllele << " gave to " << lastAllele << " reflen " << lastAllele.referenceLength << endl;
// check that the new allele still has sequence
if (!isEmptyAllele(newAllele)) {
alleles.push_back(newAllele);
}
} else if (newAllele.isReference()
&& (newAllele.referenceLength > maxComplexGap
|| newAllele.basesRight == 0)) {
// if the last allele is reference too, we need to combine them!
if (lastAllele.isReference()) {
DEBUG2("addAllele: mergeAllele/1:"
<< " lastAllele " << lastAllele.typeStr() << "@" << lastAllele.position << ":" << lastAllele.cigar
<< " newAllele " << newAllele.typeStr() << "@" << newAllele.position << ":" << newAllele.cigar);
lastAllele.mergeAllele(newAllele, ALLELE_REFERENCE);
assert(lastAllele.alternateSequence.size() == lastAllele.baseQualities.size());
} else if (lastAllele.isComplex() || lastAllele.isMNP() || lastAllele.isSNP()) {
// split apart the last allele if it's 'complex' but followed by another reference allele
// that would cause the reference gap to be greater than the maxComplexGap
vector<pair<int, string> > cigar = splitCigar(lastAllele.cigar);
if (cigar.back().second == "M") {
int matchlen = cigar.back().first;
if (matchlen + newAllele.referenceLength > maxComplexGap) {
// break apart the complex allele
alleles.push_back(lastAllele);
Allele& pAllele = alleles.at(alleles.size() - 2);
string seq; vector<pair<int, string> > cig; vector<short> quals;
pAllele.subtractFromEnd(matchlen, seq, cig, quals);
alleles.back().subtractFromStart(pAllele.referenceLength, seq, cig, quals);
DEBUG2("addAllele: mergeAllele/2:"
<< " lastAllele " << lastAllele.typeStr() << "@" << lastAllele.position << ":" << lastAllele.cigar
<< " .back() " << alleles.back().typeStr() << "@" << alleles.back().position << ":" << alleles.back().cigar
<< " newAllele " << newAllele.typeStr() << "@" << newAllele.position << ":" << newAllele.cigar);
alleles.back().mergeAllele(newAllele, ALLELE_REFERENCE);
} else { // expand the complex allele