forked from zengzheng123/GetBaseCountsMultiSample
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGetBaseCountsMultiSample.cpp
2226 lines (2109 loc) · 98.6 KB
/
GetBaseCountsMultiSample.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
//
// GetBaseCountsMultiSample.cpp
// GetBaseCountsMultiSample
//
// Created by Zeng, Zheng/Sloan-Kettering Institute on 9/5/14.
// Copyright (c) 2014 Zeng, Zheng/Sloan-Kettering Institute. All rights reserved.
//
#include <iostream>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <sstream>
#include <fstream>
#include <getopt.h>
#include <vector>
#include <algorithm>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <math.h>
#include <limits.h>
#include <iomanip>
#include "api/BamReader.h"
#include "omp.h"
//#define _DEBUG
//#define _PARSING_DEBUG
//#define _FASTA_DEBUG
using namespace std;
using namespace BamTools;
const string VERSION = "GetBaseCountsMultiSample 1.2.5";
string input_fasta_file;
map<string, string> input_bam_files;
map<string, int> bam_index_map;
vector<string> output_sample_order;
vector<string> input_variant_files;
string output_file;
int mapping_quality_threshold = 20;
int base_quality_threshold = 0;
int quality_scale = 33;
int filter_duplicate = 1;
int filter_improper_pair = 0;
int filter_qc_failed = 0;
int filter_indel = 0;
int filter_non_primary = 0;
int output_positive_count = 1;
int output_negative_count = 0;
int output_fragment_count = 0;
int maximum_variant_block_size = 10000;
int maximum_variant_block_distance = 100000;
int num_thread = 1;
string count_method = "DMP";
bool input_variant_is_maf = false;
bool input_variant_is_vcf = false;
bool output_maf = false;
const size_t BIN_SIZE = 16*1024;
float FRAGMENT_REF_WEIGHT = 0;
float FRAGMENT_ALT_WEIGHT = 0;
enum Count_Type {DP, RD, AD, DPP, RDP, ADP, DPF, RDF, ADF, NUM_COUNT_TYPE}; // NUM_COUNT_TYPE will have the size of Count_Type
bool has_chr;
int max_warning_per_type = 3;
int warning_overlapping_multimapped = 0;
string maf_output_center = "msk";
string maf_output_genome_build = "hg19";
bool generic_counting = false;
bool isNumber(const string& s) //check if a string(chrom name) is number
{
string::const_iterator it = s.begin();
while (it != s.end() && isdigit(*it))
{
it++;
}
return !s.empty() && it == s.end();
}
void split(const string& line, char delim, vector<std::string>& parsed_item, bool ignore_empty_item = false) // split a string with specified delimiter
{
stringstream my_ss(line);
string item;
while (getline(my_ss, item, delim))
{
#ifdef _PARSING_DEBUG
cout << "[DEBUG] Parsed item: " << item << endl;
#endif
if (ignore_empty_item && item.empty())
continue; // use to skip empty item
parsed_item.push_back(item);
}
}
void addBamFile(string bam_string) // check and add a bam file to input list
{
vector<string> bam_items;
split(bam_string, ':', bam_items, true);
if(bam_items.size() != 2)
{
cerr << "[ERROR] Incorrect format of -bam parameter: " << bam_string << endl;
exit(1);
}
string sample_name = bam_items[0];
string bam_file_name = bam_items[1];
if(input_bam_files.find(sample_name) != input_bam_files.end())
{
cerr << "[ERROR] Multiple bam files specified for sample: " << sample_name << endl;
exit(1);
}
struct stat buffer;
if(stat(bam_file_name.c_str(), &buffer) != 0)
{
cerr << "[ERROR] Unable to access bam file:" << bam_file_name << endl;
exit(1);
}
input_bam_files.insert(make_pair(sample_name, bam_file_name));
output_sample_order.push_back(sample_name);
}
class BamFileofFile
{
public:
BamFileofFile(string input_bam_fof)
{
bam_fs.open(input_bam_fof.c_str());
if (!bam_fs)
{
cerr << "[ERROR] fail to open input bam file of file: " << input_bam_fof << endl;
exit(1);
}
}
~BamFileofFile() {}
bool get_next(string &line)
{
if (!getline(bam_fs, line))
return false;
return true;
}
void close()
{
if (bam_fs)
bam_fs.close();
}
bool eof()
{
return bam_fs.eof();
}
ifstream bam_fs;
};
void addBamFilefromFile(string bam_fof)
{
BamFileofFile my_bf(bam_fof);
string line;
while (my_bf.get_next(line))
{
if (line[0] == '#')
continue; // header
vector<string> bam_items;
split(line, '\t', bam_items, true);
if (bam_items.size() != 2)
{
cerr << "[ERROR] Incorrect format of entry in : " << line << " in " << bam_fof << ". Each row should be in the format \"SAMPLE_NAME\tBAM_FILE\"" << endl;
exit(1);
}
string sample_name = bam_items[0];
string bam_file_name = bam_items[1];
if (input_bam_files.find(sample_name) != input_bam_files.end())
{
cerr << "[ERROR] Multiple bam files specified for sample: " << sample_name << endl;
exit(1);
}
struct stat buffer;
if (stat(bam_file_name.c_str(), &buffer) != 0)
{
cerr << "[ERROR] Unable to access bam file:" << bam_file_name << endl;
exit(1);
}
input_bam_files.insert(make_pair(sample_name, bam_file_name));
output_sample_order.push_back(sample_name);
}
my_bf.close();
}
void addVariantFile(string variant_string) // add a variant file to input list
{
input_variant_files.push_back(variant_string);
}
void printUsage(string msg = "")
{
cout << endl;
cout << VERSION << endl;
cout << "Usage: " << endl;
cout << "[REQUIRED ARGUMENTS]" << endl;
cout << "\t--fasta <string> Input reference sequence file" << endl;
cout << "\t--bam <string> Input bam file, in the format of SAMPLE_NAME:BAM_FILE. This paramter need to be specified at least once" << endl;
cout << "\t e.g: --bam s_EV_crc_007:Proj_4495.eta_indelRealigned_recal_s_EV_crc_007_M3.bam." << endl;
cout << "\t--bam_fof <string> Input file of file with each row in the format of \"SAMPLE_NAME\tBAM_FILE\". This paramter is optional if --bam is specified at least once" << endl;
cout << "\t--maf <string> Input variant file in TCGA maf format. --maf or --vcf need to be specified at least once. But --maf and --vcf are mutually exclusive" << endl;
cout << "\t--vcf <string> Input variant file in vcf-like format(the first 5 columns are used). --maf or --vcf need to be specified at least once. But --maf and --vcf are mutually exclusive" << endl;
cout << "\t--output <string> Output file" << endl;
cout << endl;
cout << "[OPTIONAL ARGUMENTS]" << endl;
cout << "\t--omaf Output the result in maf format" << endl;
cout << "\t--thread <int> Number of thread. Default " << num_thread << endl;
cout << "\t--maq <int> Mapping quality threshold. Default 20" << endl;
cout << "\t--baq <int> Base quality threshold, Default 0" << endl;
cout << "\t--filter_duplicate [0, 1] Whether to filter reads that are marked as duplicate. 0=off, 1=on. Default 1" << endl;
cout << "\t--filter_improper_pair [0, 1] Whether to filter reads that are marked as improperly paired. 0=off, 1=on. Default 0" << endl;
cout << "\t--filter_qc_failed [0, 1] Whether to filter reads that are marked as failed quality control. 0=off, 1=on. Default 0" << endl;
cout << "\t--filter_indel [0, 1] Whether to filter reads that have indels. 0=off, 1=on. Default 0" << endl;
cout << "\t--filter_non_primary [0, 1] Whether to filter reads that are marked as non primary alignment. Default 0" << endl;
cout << "\t--positive_count [0, 1] Whether to output positive strand read counts DPP/RDP/ADP. 0=off, 1=on. Default 1" << endl;
cout << "\t--negative_count [0, 1] Whether to output negative strand read counts DPN/RDN/ADN. 0=off, 1=on. Default 0" << endl;
cout << "\t--fragment_count [0, 1] Whether to output fragment read counts DPF/RDF/ADF. 0=off, 1=on. Default 0" << endl;
cout << "\t--fragment_fractional_weight Whether to add a fractional depth (0.5) when there is disaggrement between strands on an ALT allele. Default 0" << endl;
cout << "\t--suppress_warning <int> Only print a limit number of warnings for each type. Default " << max_warning_per_type << endl;
cout << "\t--help Print command line usage" << endl;
cout << endl;
cout << "[ADVANCED ARGUMENTS, CHANGING THESE ARGUMENTS WILL SIGNIFICANTLY AFFECT MEMORY USAGE AND RUNNING TIME. USE WITH CAUTION]" << endl;
cout << "\t--max_block_size <int> The maximum size of variant chunks that can be processed at once per thread. Default 10,000" << endl;
cout << "\t--max_block_dist <int> The longest spanning region (bp) of variant chunks that can be processed at once per thread. Default 100,000" << endl;
cout << "\t--generic_counting Use the newly implemented generic counting algorithm. Works better for complex variants. You may get different allele count result from the default counting algorithm" << endl;
cout << endl;
if(!msg.empty())
cerr << msg << endl;
exit(1);
}
static struct option long_options[] =
{
{"fasta", required_argument, 0, 'f'},
{"bam", required_argument, 0, 'b'},
{"bam_fof", required_argument, 0, 'B'},
{"maf", required_argument, 0, 'v'},
{"vcf", required_argument, 0, 'V'},
{"output", required_argument, 0, 'o'},
{"thread", required_argument, 0, 't'},
{"omaf", no_argument, 0, 'O'},
{"maq", required_argument, 0, 'Q'},
{"baq", required_argument, 0, 'q'},
{"filter_duplicate", required_argument, 0, 'd'},
{"filter_improper_pair", required_argument, 0, 'p'},
{"filter_qc_failed", required_argument, 0, 'l'},
{"filter_indel", required_argument, 0, 'i'},
{"filter_non_primary", required_argument, 0, 'n'},
{"positive_count", required_argument, 0, 'P'},
{"negative_count", required_argument, 0, 'N'},
{"fragment_count", required_argument, 0, 'F'},
{"fragment_fractional_weight", no_argument, 0, 'W'},
{"suppress_warning", required_argument, 0, 'w'},
{"max_block_size", required_argument, 0, 'M'},
{"max_block_dist", required_argument, 0, 'm'},
{"generic_counting", no_argument, 0, 'g'},
{"help", no_argument, 0, 'h'},
{0, 0, 0, 0}
};
void parseOption(int argc, const char* argv[])
{
if(argc == 1)
printUsage();
int next_option;
int option_index = 0;
do
{
next_option = getopt_long(argc, const_cast<char**>(argv), "f:b:B:v:V:o:t:OQ:q:d:p:l:i:n:P:N:F:W:w:M:m:h", long_options, &option_index);
switch(next_option)
{
case 'f':
input_fasta_file = optarg;
break;
case 'b':
addBamFile(optarg);
break;
case 'B':
addBamFilefromFile(optarg);
break;
case 'v':
addVariantFile(optarg);
input_variant_is_maf = true;
break;
case 'V':
addVariantFile(optarg);
input_variant_is_vcf = true;
break;
case 'o':
output_file = optarg;
break;
case 't':
if(isNumber(optarg))
num_thread = atoi(optarg);
else
printUsage("[ERROR] Invalid value for --thread");
break;
case 'O':
output_maf = true;
break;
case 'Q':
if(isNumber(optarg))
mapping_quality_threshold = atoi(optarg);
else
printUsage("[ERROR] Invalid value for --maq");
break;
case 'q':
if(isNumber(optarg))
base_quality_threshold = atoi(optarg);
else
printUsage("[ERROR] Invalid value for --baq");
break;
case 'd':
if(isNumber(optarg))
filter_duplicate = atoi(optarg);
else
printUsage("[ERROR] Invalid value for --filter_duplicate");
break;
case 'p':
if(isNumber(optarg))
filter_improper_pair = atoi(optarg);
else
printUsage("[ERROR] Invalid value for --filter_improper_pair");
break;
case 'l':
if(isNumber(optarg))
filter_qc_failed = atoi(optarg);
else
printUsage("[ERROR] Invalid value for --filter_qc_failed");
break;
case 'i':
if(isNumber(optarg))
filter_indel = atoi(optarg);
else
printUsage("[ERROR] Invalid value for --filter_indel");
break;
case 'n':
if(isNumber(optarg))
filter_non_primary = atoi(optarg);
else
printUsage("[ERROR] Invalid value for --filter_non_primary");
break;
case 'P':
if(isNumber(optarg))
output_positive_count = atoi(optarg);
else
printUsage("[ERROR] Invalid value for --positive_count");
break;
case 'N':
if(isNumber(optarg))
output_negative_count = atoi(optarg);
else
printUsage("[ERROR] Invalid value for --negative_count");
break;
case 'F':
if(isNumber(optarg))
output_fragment_count = atoi(optarg);
else
printUsage("[ERROR] Invalid value for --fragment_count");
break;
case 'W':
FRAGMENT_REF_WEIGHT = FRAGMENT_ALT_WEIGHT = 0.5;
break;
case 'w':
if(isNumber(optarg))
max_warning_per_type = atoi(optarg);
else
printUsage("[ERROR] Invalid value for --suppress_warning");
break;
case 'M':
if(isNumber(optarg))
maximum_variant_block_size = atoi(optarg);
else
printUsage("[ERROR] Invalid value for --max_block_size");
break;
case 'm':
if(isNumber(optarg))
maximum_variant_block_distance = atoi(optarg);
else
printUsage("[ERROR] Invalid value for --max_block_dist");
break;
case 'g':
generic_counting = true;
break;
case 'h':
printUsage();
break;
case -1:
break; //parsed all options
default:
printUsage(string("[ERROR] Argument error: ") + argv[optind - 1]);
}
} while(next_option != -1);
if(input_fasta_file.empty())
printUsage("[ERROR] Please specify input fasta file");
if(input_bam_files.empty())
printUsage("[ERROR] Please specify at least one input bam file");
if(input_variant_files.empty())
printUsage("[ERROR] Please specify at least one input variant file with --maf or --vcf");
if(output_file.empty())
printUsage("[ERROR] Please specify output file");
if(num_thread <= 0)
printUsage("[ERROR] Invalid number of threads");
if(maximum_variant_block_size <= 0)
printUsage("[ERROR] Invalid max_block_size");
if(maximum_variant_block_distance <= 0)
printUsage("[ERROR] Invalid max_block_dist");
if(filter_duplicate != 0 && filter_duplicate != 1)
printUsage("[ERROR] --filter_duplicate should be 0 or 1");
if(filter_improper_pair != 0 && filter_improper_pair != 1)
printUsage("[ERROR] --filter_improper_pair should be 0 or 1");
if(filter_qc_failed != 0 && filter_qc_failed != 1)
printUsage("[ERROR] --filter_qc_failed should be 0 or 1");
if(filter_indel != 0 && filter_indel != 1)
printUsage("[ERROR] --filter_indel should be 0 or 1");
if(filter_non_primary != 0 && filter_non_primary != 1)
printUsage("[ERROR] --filter_non_primary should be 0 or 1");
if(output_positive_count != 0 && output_positive_count != 1)
printUsage("[ERROR] --positive_count should be 0 or 1");
if(output_negative_count != 0 && output_negative_count != 1)
printUsage("[ERROR] --negative_count should be 0 or 1");
if(output_fragment_count != 0 && output_fragment_count != 1)
printUsage("[ERROR] --fragment_count should be 0 or 1");
if(input_variant_is_maf && input_variant_is_vcf)
printUsage("[ERROR] --maf and --vcf are mutually exclusive");
if(input_variant_is_vcf && output_maf)
printUsage("[ERROR] --omaf can only be used with --maf input");
base_quality_threshold += quality_scale;
#ifdef _DEBUG
cout << "[DEBUG] Parsing options complete." << endl;
#endif
}
void outputReferenceSequence(string output_fastafile, map<string, string>& ref_seq, vector<string>& orignal_header)
{
size_t base_per_line = 80;
ofstream out_fs(output_fastafile.c_str());
for(size_t i = 0; i < orignal_header.size(); i++)
{
map<string, string>::iterator it = ref_seq.find(orignal_header[i]);
size_t chrom_len = it->second.length();
#ifdef _FASTA_DEBUG
cout << "[DEBUG] output reference sequence: " << it->first << ": " << chrom_len << endl;
#endif
size_t current_len = 0;
out_fs << ">" << it->first << endl;
while(current_len < chrom_len)
{
size_t output_len = min(base_per_line, chrom_len - current_len);
out_fs << it->second.substr(current_len, output_len) << endl;
current_len += output_len;
}
}
out_fs.close();
}
void loadReferenceSequenceSpeedup(string fasta_filename, map<string, string>& ref_seq) // load refseq fasta
{
cout << "[INFO] Loading reference sequence: " << fasta_filename << endl;
string fasta_index_filename = fasta_filename + ".fai";
ifstream index_fs(fasta_index_filename.c_str());
if(!index_fs)
{
cerr << "[ERROR] fail to open reference fasta index file: " << fasta_index_filename << endl;
exit(1);
}
#pragma omp parallel num_threads(num_thread)
{
int thread_num = omp_get_thread_num();
string line;
ifstream ref_fs(fasta_filename.c_str());
if(!ref_fs)
{
cerr << "[ERROR] fail to open reference fasta file: " << fasta_filename << endl;
exit(1);
}
while(!index_fs.eof())
{
#pragma omp critical(read_index)
{
getline(index_fs, line);
}
if(!index_fs.eof())
{
vector<string> index_items;
split(line, '\t', index_items);
string chrom_name = index_items[0];
int chrom_len = atoi(index_items[1].c_str());
long long int chrom_offset = atoll(index_items[2].c_str());
int base_per_line = atoi(index_items[3].c_str());
int byte_per_line = atoi(index_items[4].c_str());
int byte_len = chrom_len + (chrom_len / base_per_line) * (byte_per_line - base_per_line);
string new_seq;
#pragma omp critical(access_ref_seq_map)
{
ref_seq.insert(make_pair(chrom_name, new_seq));
ref_seq[chrom_name].resize(chrom_len);
}
ref_fs.seekg(chrom_offset);
char* seq_buff = new char[byte_len];
ref_fs.read(seq_buff, byte_len);
string::iterator it_target;
#pragma omp critical(access_ref_seq_map)
{
it_target = ref_seq[chrom_name].begin();
}
char* it_source = seq_buff;
for(int i = 0; i < byte_len; i++)
{
if(!isspace(*it_source))
{
*it_target = toupper(*it_source);
it_target ++;
}
it_source ++;
}
delete[] seq_buff;
}
}
ref_fs.close();
}
index_fs.close();
cout << "[INFO] Finished loading reference sequence" << endl;
}
class VariantFile
{
public:
VariantFile(string input_variant_file)
{
variant_fs.open(input_variant_file.c_str());
if(!variant_fs)
{
cerr << "[ERROR] fail to open input variant file: " << input_variant_file << endl;
exit(1);
}
}
~VariantFile() {}
bool get_next(string &line)
{
//if(cur_line.empty())
//{
if(!getline(variant_fs, line))
return false;
//}
//else
//{
// line = cur_line;
// cur_line.clear();
//}
return true;
}
//void roll_back(string &line)
//{
// cur_line = line;
//}
void close()
{
if(variant_fs)
variant_fs.close();
}
bool eof()
{
return variant_fs.eof();
}
ifstream variant_fs;
//string cur_line;
};
class VariantEntry
{
public:
VariantEntry()
{
pos = 0;
end_pos = 0;
snp = false;
dnp = false;
dnp_len = 0;
insertion = false;
deletion = false;
t_ref_count = 0;
t_alt_count = 0;
n_ref_count = 0;
n_alt_count = 0;
duplicate_variant_ptr = NULL;
base_count = new float*[input_bam_files.size()];
for (int i = 0; i < input_bam_files.size(); i++)
{
base_count[i] = new float[NUM_COUNT_TYPE](); // initialized to 0
}
}
VariantEntry(string _chrom, int _pos, int _end_pos, string _ref, string _alt, bool _snp, bool _dnp, int _dnp_len, bool _insertion, bool _deletion)
{
chrom = _chrom;
pos = _pos;
end_pos = _end_pos;
ref = _ref;
alt = _alt;
snp = _snp;
dnp = _dnp;
dnp_len = _dnp_len;
insertion = _insertion;
deletion = _deletion;
t_ref_count = 0;
t_alt_count = 0;
n_ref_count = 0;
n_alt_count = 0;
duplicate_variant_ptr = NULL;
base_count = new float*[input_bam_files.size()];
for (int i = 0; i < input_bam_files.size(); i++)
{
base_count[i] = new float[NUM_COUNT_TYPE](); // initialized to 0
}
}
VariantEntry(string _chrom, int _pos, int _end_pos, string _ref, string _alt, bool _snp, bool _dnp, int _dnp_len, bool _insertion, bool _deletion, string _tumor_sample, string _normal_sample)
{
chrom = _chrom;
pos = _pos;
end_pos = _end_pos;
ref = _ref;
alt = _alt;
snp = _snp;
dnp = _dnp;
dnp_len = _dnp_len;
insertion = _insertion;
deletion = _deletion;
tumor_sample = _tumor_sample;
normal_sample = _normal_sample;
t_ref_count = 0;
t_alt_count = 0;
n_ref_count = 0;
n_alt_count = 0;
duplicate_variant_ptr = NULL;
base_count = new float*[input_bam_files.size()];
for (int i = 0; i < input_bam_files.size(); i++)
{
base_count[i] = new float[NUM_COUNT_TYPE](); // initialized to 0
}
}
VariantEntry(string _chrom, int _pos, int _end_pos, string _ref, string _alt, bool _snp, bool _dnp, int _dnp_len, bool _insertion, bool _deletion, string _tumor_sample, string _normal_sample, string _gene, string _effect, int _t_ref_count, int _t_alt_count, int _n_ref_count, int _n_alt_count, int _maf_pos, int _maf_end_pos, string _maf_ref, string _maf_alt, string _caller)
{
chrom = _chrom;
pos = _pos;
end_pos = _end_pos;
ref = _ref;
alt = _alt;
snp = _snp;
dnp = _dnp;
dnp_len = _dnp_len;
insertion = _insertion;
deletion = _deletion;
tumor_sample = _tumor_sample;
normal_sample = _normal_sample;
gene = _gene;
effect = _effect;
t_ref_count = _t_ref_count;
t_alt_count = _t_alt_count;
n_ref_count = _n_ref_count;
n_alt_count = _n_alt_count;
maf_pos = _maf_pos;
maf_end_pos = _maf_end_pos;
maf_ref = _maf_ref;
maf_alt = _maf_alt;
caller = _caller;
duplicate_variant_ptr = NULL;
base_count = new float*[input_bam_files.size()];
for (int i = 0; i < input_bam_files.size(); i++)
{
base_count[i] = new float[NUM_COUNT_TYPE](); // initialized to 0
}
}
~VariantEntry()
{
for (int i = 0; i < input_bam_files.size(); i++)
{
if(base_count[i])
delete [] base_count[i];
}
if(base_count)
delete [] base_count;
}
VariantEntry(const VariantEntry& source); // prevent copying
VariantEntry& operator=(const VariantEntry& source); // prevent assigning
string chrom;
int pos;
int end_pos;
string ref;
string alt;
bool snp;
bool dnp;
int dnp_len;
bool insertion;
bool deletion;
string tumor_sample;
string normal_sample;
string gene; // gene name from input maf
string effect; // effect from input maf
int t_ref_count; // tumor ref count from input maf
int t_alt_count; // tumor alt count from input maf
int n_ref_count; // normal ref count from input maf
int n_alt_count; // normal alt count from input maf
float **base_count; //<sample_name, <count_type, count> >
VariantEntry* duplicate_variant_ptr; // pointer to the first identical variant, no need to do duplicate count for the same variant of different normal/tumor pair
string maf_ref;
string maf_alt;
int maf_pos;
int maf_end_pos;
string caller;
};
bool sortVariantByPos(const VariantEntry* lhs, const VariantEntry* rhs) // sort varaints by genomic position, 1-22, X, Y, etc
{
if(lhs->chrom != rhs->chrom)
{
string chrom1 = lhs->chrom;
string chrom2 = rhs->chrom;
if(has_chr)
{
chrom1 = chrom1.substr(3);
chrom2 = chrom2.substr(3);
}
bool chrom1_num = isNumber(chrom1);
bool chrom2_num = isNumber(chrom2);
if(chrom1_num && !chrom2_num)
return true;
if(!chrom1_num && chrom2_num)
return false;
if(chrom1_num && chrom2_num)
return atoi(chrom1.c_str()) < atoi(chrom2.c_str());
else //both string
return chrom1 < chrom2;
}
else
return lhs->pos < rhs->pos;
}
bool alignmentHasIndel(BamAlignment& my_bam_alignment) // check if an alignment has indel
{
vector<CigarOp>::const_iterator cigarIter;
for(cigarIter = my_bam_alignment.CigarData.begin() ; cigarIter != my_bam_alignment.CigarData.end(); cigarIter++)
{
if(cigarIter->Type == 'I' || cigarIter->Type == 'D')
return true;
}
return false;
}
/*void loadVariantFileDMPTXT(vector<string>& input_file_names, vector<VariantEntry>& variant_vec, vector<pair<size_t, size_t> >& variant_block_vec) // load variant from dmp-impact annotated_exonic_variants.txt
{
for(size_t i = 0; i < input_file_names.size(); i++)
{
int variant_count = 0;
VariantFile my_vf(input_file_names[i]);
string line;
my_vf.get_next(line); //header
while(my_vf.get_next(line))
{
vector<string> variant_items;
split(line, '\t', variant_items);
if(variant_items.size() < 6)
{
cerr << "[ERROR] Incorrectly formatted input variant entry:" << endl;
cerr << "[ERROR] " << line << endl;
exit(1);
}
string tumor_sample = variant_items[0];
string normal_sample = variant_items[1];
string chrom = variant_items[2];
int pos = atoi(variant_items[3].c_str()) - 1; //convert to 0-indexed, to be consistent with bam entry
string ref = variant_items[4];
string alt = variant_items[5];
bool insertion = (new_variant.alt.length() > new_variant.ref.length());
bool deletion = (new_variant.alt.length() < new_variant.ref.length());
//VariantEntry(string _chrom, int _pos, string _ref, string _alt, bool _insertion, bool _deletion, string _tumor_sample, string _normal_sample)
variant_vec.emplace_back(chrom, pos, ref, alt, insertion, deletion, tumor_sample, normal_sample);
variant_count ++;
}
my_vf.close();
cout << "[INFO] " << variant_count << " variants has been loaded from file: " << input_file_names[i] << endl;
}
}*/
void loadVariantFileVCF(vector<string>& input_file_names, vector<VariantEntry *>& variant_vec) // load variant from vcf-like format, only the first 5 columns are used
{
for(size_t i = 0; i < input_file_names.size(); i++)
{
cout << "[INFO] Loading variants file: " << input_file_names[i] << endl;
int variant_count = 0;
VariantFile my_vf(input_file_names[i]);
string line;
while(my_vf.get_next(line))
{
if(line[0] == '#')
continue; // header
vector<string> variant_items;
split(line, '\t', variant_items);
if(variant_items.size() < 5)
{
cerr << "[ERROR] Incorrectly formatted input variant entry:" << endl;
cerr << "[ERROR] " << line << endl;
exit(1);
}
string chrom = variant_items[0];
int pos = atoi(variant_items[1].c_str()) - 1; //convert to 0-indexed, to be consistent with bam entry
string ref = variant_items[3];
string alt = variant_items[4];
int end_pos = pos + (int)ref.length() - 1;
bool snp = (alt.length() == ref.length() && alt.length() == 1);
bool dnp = (alt.length() == ref.length() && alt.length() > 1);
int dnp_len = dnp ? ((int)ref.length()) : 0;
bool insertion = (alt.length() > ref.length());
bool deletion = (alt.length() < ref.length());
if(!snp && !dnp && !insertion && !deletion)
{
cerr << "[WARNING] Unrecognized variants type in input variant file, you won't get any counts for it" << endl;
cerr << "[WARNING] " << line << endl;
}
VariantEntry *new_variant_ptr = new VariantEntry(chrom, pos, end_pos, ref, alt, snp, dnp, dnp_len, insertion, deletion);
variant_vec.push_back(new_variant_ptr);
variant_count ++;
}
my_vf.close();
cout << "[INFO] " << variant_count << " variants has been loaded from file: " << input_file_names[i] << endl;
}
}
void loadVariantFileMAF(vector<string>& input_file_names, vector<VariantEntry *>& variant_vec, map<string, string>& reference_sequence) // load from exome-pipeline tcga maf format
{
for(size_t file_index = 0; file_index < input_file_names.size(); file_index++)
{
cout << "[INFO] Loading variants file: " << input_file_names[file_index] << endl;
int variant_count = 0;
map<string, size_t> header_index_hash;
VariantFile my_vf(input_file_names[file_index]);
string line;
while(my_vf.get_next(line))
{
if(line[0] != '#') // first non-comment line is the header line
break;
}
vector<string> header_items;
split(line, '\t', header_items);
for(size_t header_index = 0; header_index < header_items.size(); header_index++)
{
header_index_hash[header_items[header_index]] = header_index;
}
if(header_index_hash.find("Hugo_Symbol") == header_index_hash.end() || header_index_hash.find("Chromosome") == header_index_hash.end() ||
header_index_hash.find("Start_Position") == header_index_hash.end() || header_index_hash.find("End_Position") == header_index_hash.end() ||
header_index_hash.find("Reference_Allele") == header_index_hash.end() || header_index_hash.find("Tumor_Seq_Allele1") == header_index_hash.end() || header_index_hash.find("Tumor_Seq_Allele2") == header_index_hash.end() ||
header_index_hash.find("Tumor_Sample_Barcode") == header_index_hash.end() || header_index_hash.find("Matched_Norm_Sample_Barcode") == header_index_hash.end() ||
header_index_hash.find("t_ref_count") == header_index_hash.end() || header_index_hash.find("t_alt_count") == header_index_hash.end() ||
header_index_hash.find("n_ref_count") == header_index_hash.end() || header_index_hash.find("n_alt_count") == header_index_hash.end() ||
header_index_hash.find("Variant_Classification") == header_index_hash.end())
{
cerr << "[ERROR] Incorrect input MAF file header. Make sure the following column headers exist in the MAF file:" << endl;
cerr << "[ERROR] Hugo_Symbol, Chromosome, Start_Position, End_Position, Reference_Allele, Tumor_Seq_Allele1, Tumor_Seq_Allele2, Tumor_Sample_Barcode, Matched_Norm_Sample_Barcode, t_ref_count, t_alt_count, n_ref_count, n_alt_count, Variant_Classification" << endl;
exit(1);
}
bool load_caller_column = (header_index_hash.find("Caller") != header_index_hash.end());
while(my_vf.get_next(line))
{
vector<string> variant_items;
split(line, '\t', variant_items);
if(variant_count == 0)
{
if(header_index_hash.find("Center") != header_index_hash.end())
maf_output_center = variant_items[header_index_hash["Center"]];
if(header_index_hash.find("NCBI_Build") != header_index_hash.end())
maf_output_genome_build = variant_items[header_index_hash["NCBI_Build"]];
}
string gene = variant_items[header_index_hash["Hugo_Symbol"]];
string chrom = variant_items[header_index_hash["Chromosome"]];
int pos = atoi(variant_items[header_index_hash["Start_Position"]].c_str()) - 1; //convert to 0-indexed, to be consistent with bam entry
int end_pos = atoi(variant_items[header_index_hash["End_Position"]].c_str()) - 1;
string ref = variant_items[header_index_hash["Reference_Allele"]];
string alt = variant_items[header_index_hash["Tumor_Seq_Allele1"]];
int maf_pos = pos;
int maf_end_pos = end_pos;
string maf_ref = ref;
string maf_alt = alt;
if(alt.empty() || alt == ref)
alt = variant_items[header_index_hash["Tumor_Seq_Allele2"]];
maf_alt = alt;
if(alt.empty())
{
cerr << "Could not find alt allele for variant: " << chrom << "\t" << pos << endl;
exit(1);
}
if(ref == alt)
{
cerr << "The ref and alt alleles are the same for variant: " << chrom << "\t" << pos << endl;
exit(1);
}
string tumor_sample = variant_items[header_index_hash["Tumor_Sample_Barcode"]];
string normal_sample = variant_items[header_index_hash["Matched_Norm_Sample_Barcode"]];
int t_ref_count = atoi(variant_items[header_index_hash["t_ref_count"]].c_str());
int t_alt_count = atoi(variant_items[header_index_hash["t_alt_count"]].c_str());
int n_ref_count = atoi(variant_items[header_index_hash["n_ref_count"]].c_str());
int n_alt_count = atoi(variant_items[header_index_hash["n_alt_count"]].c_str());
string effect = variant_items[header_index_hash["Variant_Classification"]];
string caller = "";
if(load_caller_column)
{
caller = variant_items[header_index_hash["Caller"]];
}
if(effect.empty())
{
if(header_index_hash.find("ONCOTATOR_VARIANT_CLASSIFICATION") != header_index_hash.end() && !(variant_items[header_index_hash["ONCOTATOR_VARIANT_CLASSIFICATION"]].empty()) )
{
effect = variant_items[header_index_hash["ONCOTATOR_VARIANT_CLASSIFICATION"]];
}
else
{
cerr << "[ERROR] Could not find annotation information for variant:" << endl;
cerr << "[ERROR] " << line << endl;
exit(1);
}
}
if(ref == "-") // convert maf convention insertion to vcf convention - A => G GA
{
if(reference_sequence.find(chrom) == reference_sequence.end())
{
cerr << "[ERROR] Could not find variant chrom name in reference sequence: " << chrom << endl;
exit(1);
}
if(reference_sequence[chrom].length() <= pos)
{
cerr << "[ERROR] Variant position is out of the reference genome range: " << chrom << ":" << pos << endl;
exit(1);
}
char prev_ref = reference_sequence[chrom][pos]; // get allele before the current position
ref = prev_ref;
alt = prev_ref + alt;
end_pos --;
}
else if(alt == "-") // convert maf convention deletion to vcf convention G - => CG C
{
if(reference_sequence.find(chrom) == reference_sequence.end())
{
cerr << "[ERROR] Could not find variant chrom name in reference sequence: " << chrom << endl;
exit(1);
}
if(reference_sequence[chrom].length() <= pos)
{
cerr << "[ERROR] Variant position is out of the reference genome range: " << chrom << ":" << pos << endl;
exit(1);
}
pos --;
char prev_ref = reference_sequence[chrom][pos]; // get allele before the current position
ref = prev_ref + ref;
alt = prev_ref;
}
else if(alt.length() != ref.length()) // convert complex indel to vcf convention
{
if(reference_sequence.find(chrom) == reference_sequence.end())
{
cerr << "[ERROR] Could not find variant chrom name in reference sequence: " << chrom << endl;