| 1 | package Genome::Model::Tools::Music::Bmr::CalcBmrscip-perl cpan Genome-Model-Tools-Music 0.04 Genome/Model/Tools/Music/Bmr/CalcBmr/; |
| 2 | |
| 3 | use warningsscip-perl cpan Genome-Model-Tools-Music 0.04 warnings/; |
| 4 | use strictscip-perl cpan Genome-Model-Tools-Music 0.04 strict/; |
| 5 | use Genomescip-perl cpan Genome-Model-Tools-Music 0.04 Genome/; |
| 6 | use IO::Filescip-perl cpan Genome-Model-Tools-Music 0.04 IO/File/; |
| 7 | use Bit::Vectorscip-perl cpan Genome-Model-Tools-Music 0.04 Bit/Vector/; |
| 8 | use List::Utilscip-perl cpan Genome-Model-Tools-Music 0.04 List/Util/ qw( min sum ); |
| 9 | |
| 10 | our $VERSIONscip-perl cpan Genome-Model-Tools-Music 0.04 Genome/Model/Tools/Music/Bmr/CalcBmr/$VERSION. = $Genome::Model::Tools::Music::VERSIONscip-perl cpan Genome-Model-Tools-Music 0.04 Genome/Model/Tools/Music/$VERSION.; |
| 11 | |
| 12 | # These constants let us use space-efficient arrays instead of hashes, while keeping the code fairly readable |
| 13 | use constantscip-perl cpan Genome-Model-Tools-Music 0.04 constant/ { AT_Transitionsscip-perl cpan Genome-Model-Tools-Music 0.04 Genome/Model/Tools/Music/Bmr/CalcBmr/AT_Transitions(). => 0, AT_Transversionsscip-perl cpan Genome-Model-Tools-Music 0.04 Genome/Model/Tools/Music/Bmr/CalcBmr/AT_Transversions(). => 1, CG_Transitionsscip-perl cpan Genome-Model-Tools-Music 0.04 Genome/Model/Tools/Music/Bmr/CalcBmr/CG_Transitions(). => 2, CG_Transversionsscip-perl cpan Genome-Model-Tools-Music 0.04 Genome/Model/Tools/Music/Bmr/CalcBmr/CG_Transversions(). => 3, |
| 14 | CpG_Transitionsscip-perl cpan Genome-Model-Tools-Music 0.04 Genome/Model/Tools/Music/Bmr/CalcBmr/CpG_Transitions(). => 4, CpG_Transversionsscip-perl cpan Genome-Model-Tools-Music 0.04 Genome/Model/Tools/Music/Bmr/CalcBmr/CpG_Transversions(). => 5, Indelsscip-perl cpan Genome-Model-Tools-Music 0.04 Genome/Model/Tools/Music/Bmr/CalcBmr/Indels(). => 6, Truncationsscip-perl cpan Genome-Model-Tools-Music 0.04 Genome/Model/Tools/Music/Bmr/CalcBmr/Truncations(). => 7, Overallscip-perl cpan Genome-Model-Tools-Music 0.04 Genome/Model/Tools/Music/Bmr/CalcBmr/Overall(). => 8, |
| 15 | covd_basesscip-perl cpan Genome-Model-Tools-Music 0.04 Genome/Model/Tools/Music/Bmr/CalcBmr/covd_bases(). => 0, mutationsscip-perl cpan Genome-Model-Tools-Music 0.04 Genome/Model/Tools/Music/Bmr/CalcBmr/mutations(). => 1, bmrscip-perl cpan Genome-Model-Tools-Music 0.04 Genome/Model/Tools/Music/Bmr/CalcBmr/bmr(). => 2 }; |
| 16 | |
| 17 | class Genome::Model::Tools::Music::Bmr::CalcBmrscip-perl cpan Genome-Model-Tools-Music 0.04 Genome/Model/Tools/Music/Bmr/CalcBmr/ { |
| 18 | is => 'Genome::Model::Tools::Music::Bmr::Base', |
| 19 | has_input => [ |
| 20 | roi_file => { is => 'Text', doc => "Tab delimited list of ROIs [chr start stop gene_name] (See DESCRIPTION)" }, |
| 21 | reference_sequence => { is => 'Text', doc => "Path to reference sequence in FASTA format" }, |
| 22 | bam_list => { is => 'Text', doc => "Tab delimited list of BAM files [sample_name normal_bam tumor_bam] (See DESCRIPTION)" }, |
| 23 | output_dir => { is => 'Text', doc => "Directory where output files will be written (Use the same one used with calc-covg)" }, |
| 24 | maf_file => { is => 'Text', doc => "List of mutations using TCGA MAF specification v2.3" }, |
| 25 | bmr_groups => { is => 'Integer', doc => "Number of clusters of samples with comparable BMRs (See DESCRIPTION)", is_optional => 1, default => 1 }, |
| 26 | show_skipped => { is => 'Boolean', doc => "Report each skipped mutation, not just how many", is_optional => 1, default => 0 }, |
| 27 | separate_truncations => { is => 'Boolean', doc => "Group truncational mutations as a separate category", is_optional => 1, default => 0 }, |
| 28 | merge_concurrent_muts => { is => 'Boolean', doc => "Multiple mutations of a gene in the same sample are treated as 1", is_optional => 1, default => 0 }, |
| 29 | genes_to_ignore => { is => 'Text', doc => "Comma-delimited list of genes to ignore for background mutation rates", is_optional => 1 }, |
| 30 | skip_non_coding => { is => 'Boolean', doc => "Skip non-coding mutations from the provided MAF file", is_optional => 1, default => 1 }, |
| 31 | skip_silent => { is => 'Boolean', doc => "Skip silent mutations from the provided MAF file", is_optional => 1, default => 1 }, |
| 32 | ], |
| 33 | has_output => [ |
| 34 | bmr_output => { is => 'Number', doc => "TODO" }, |
| 35 | gene_mr_file => { is => 'Text', doc => "TODO" }, |
| 36 | ], |
| 37 | doc => "Calculates mutation rates given per-gene coverage (from \"music bmr calc-covg\"), and a mutation list", |
| 38 | }; |
| 39 | |
| 40 | sub help_synopsisscip-perl cpan Genome-Model-Tools-Music 0.04 Genome/Model/Tools/Music/Bmr/CalcBmr/help_synopsis(). { |
| 41 | return <<HELP |
| 42 | ... music bmr calc-bmr \\ |
| 43 | --bam-list input_dir/bam_list \\ |
| 44 | --maf-file input_dir/myMAF.tsv \\ |
| 45 | --output-dir output_dir/ \\ |
| 46 | --reference-sequence input_dir/all_sequences.fa \\ |
| 47 | --roi-file input_dir/all_coding_exons.tsv |
| 48 | |
| 49 | ... music bmr calc-bmr \\ |
| 50 | --bam-list input_dir/bam_list \\ |
| 51 | --maf-file input_dir/myMAF.tsv \\ |
| 52 | --output-dir output_dir/ \\ |
| 53 | --reference-sequence input_dir/all_sequences.fa \\ |
| 54 | --roi-file input_dir/all_coding_exons.tsv \\ |
| 55 | --genes-to-ignore GENE1,GENE2 |
| 56 | HELP |
| 57 | } |
| 58 | |
| 59 | sub help_detailscip-perl cpan Genome-Model-Tools-Music 0.04 Genome/Model/Tools/Music/Bmr/CalcBmr/help_detail(). { |
| 60 | return <<HELP; |
| 61 | Given a mutation list (MAF), and per-gene coverage data calculated using \"music bmr calc-covg\"), |
| 62 | this script calculates overall Background Mutation Rate (BMR) and BMRs in the categories of |
| 63 | AT/CG/CpG Transitions, AT/CG/CpG Transversions, and Indels. An optional category for truncational |
| 64 | mutations can also be specified. The script generates a file with per-gene mutation rates that can |
| 65 | be used with the tool that tests for significantly mutated genes (music smg). |
| 66 | HELP |
| 67 | } |
| 68 | |
| 69 | sub _additional_help_sectionsscip-perl cpan Genome-Model-Tools-Music 0.04 Genome/Model/Tools/Music/Bmr/CalcBmr/_additional_help_sections(). { |
| 70 | return ( |
| 71 | "ARGUMENTS", |
| 72 | <<EOS |
| 73 | |
| 74 | =over 4 |
| 75 | |
| 76 | =item --roi-file |
| 77 | |
| 78 | =over 8 |
| 79 | |
| 80 | =item The regions of interest (ROIs) of each gene are typically regions targeted for sequencing or |
| 81 | are merged exon loci (from multiple transcripts) of genes with 2-bp flanks (splice junctions). |
| 82 | ROIs from the same chromosome must be listed adjacent to each other in this file. This allows |
| 83 | the underlying C-based code to run much more efficiently and avoid re-counting bases seen in |
| 84 | overlapping ROIs (for overall covered base counts). For per-gene base counts, an overlapping |
| 85 | base will be counted each time it appears in an ROI of the same gene. To avoid this, be sure to |
| 86 | merge together overlapping ROIs of the same gene. BEDtools' mergeBed can help if used per gene. |
| 87 | |
| 88 | =back |
| 89 | |
| 90 | =item --reference-sequence |
| 91 | |
| 92 | =over 8 |
| 93 | |
| 94 | =item The reference sequence in FASTA format. If a reference sequence index is not found next to |
| 95 | this file (a .fai file), it will be created. |
| 96 | |
| 97 | =back |
| 98 | |
| 99 | =item --bam-list |
| 100 | |
| 101 | =over 8 |
| 102 | |
| 103 | =item Provide a file containing sample names and normal/tumor BAM locations for each. Use the tab- |
| 104 | delimited format [sample_name normal_bam tumor_bam] per line. Additional columns like clinical |
| 105 | data are allowed, but ignored. The sample_name must be the same as the tumor sample names used |
| 106 | in the MAF file (16th column, with the header Tumor_Sample_Barcode). |
| 107 | |
| 108 | =back |
| 109 | |
| 110 | =item --bmr-groups |
| 111 | |
| 112 | =over 8 |
| 113 | |
| 114 | =item Ideally, we want to test the mutation rate (MR) of a gene in a sample against the background |
| 115 | mutation rate (BMR) across that sample. But if the BMRs of some samples are comparable, we can |
| 116 | instead test the MR of a gene across a group of samples with comparable BMR, against the overall |
| 117 | BMR of that group. This argument specifies how many such groups you want to cluster samples |
| 118 | into. By default, it is assumed that all samples have comparable BMRs (bmr-groups = 1). |
| 119 | |
| 120 | =back |
| 121 | |
| 122 | =item --output-dir |
| 123 | |
| 124 | =over 8 |
| 125 | |
| 126 | =item This should be the same output directory used when running "music bmr calc-covg". The |
| 127 | following outputs of this script will also be created/written: |
| 128 | overall_bmrs: File containing categorized overall background mutation rates. |
| 129 | gene_mrs: File containing categorized per-gene mutation rates. |
| 130 | |
| 131 | =back |
| 132 | |
| 133 | =item --genes-to-ignore |
| 134 | |
| 135 | =over 8 |
| 136 | |
| 137 | =item A comma-delimited list of genes to ignore for overall BMR calculations. List genes that are |
| 138 | known factors in this disease and whose mutations should not be classified as background. |
| 139 | |
| 140 | =back |
| 141 | |
| 142 | =back |
| 143 | |
| 144 | EOS |
| 145 | ); |
| 146 | } |
| 147 | |
| 148 | sub _doc_authors { |
| 149 | return " Cyriac Kandoth, Ph.D."; |
| 150 | } |
| 151 | |
| 152 | sub _doc_see_also { |
| 153 | return <<EOS |
| 154 | B<genome-music-bmr>(1), |
| 155 | B<genome-music>(1), |
| 156 | B<genome>(1) |
| 157 | EOS |
| 158 | } |
| 159 | |
| 160 | sub execute { |
| 161 | my $self = shift; |
| 162 | my $roi_file = $self->roi_file; |
| 163 | my $ref_seq = $self->reference_sequence; |
| 164 | my $bam_list = $self->bam_list; |
| 165 | my $output_dir = $self->output_dir; |
| 166 | my $maf_file = $self->maf_file; |
| 167 | my $show_skipped = $self->show_skipped; |
| 168 | my $bmr_groups = $self->bmr_groups; |
| 169 | my $separate_truncations = $self->separate_truncations; |
| 170 | my $merge_concurrent_muts = $self->merge_concurrent_muts; |
| 171 | my $genes_to_ignore = $self->genes_to_ignore; |
| 172 | my $skip_non_coding = $self->skip_non_coding; |
| 173 | my $skip_silent = $self->skip_silent; |
| 174 | |
| 175 | # Check on all the input data before starting work |
| 176 | print STDERR "ROI file not found or is empty: $roi_file\n" unless( -s $roi_file ); |
| 177 | print STDERR "Reference sequence file not found: $ref_seq\n" unless( -e $ref_seq ); |
| 178 | print STDERR "List of BAMs not found or is empty: $bam_list\n" unless( -s $bam_list ); |
| 179 | print STDERR "Output directory not found: $output_dir\n" unless( -e $output_dir ); |
| 180 | print STDERR "MAF file not found or is empty: $maf_file\n" unless( -s $maf_file ); |
| 181 | return undef unless( -s $roi_file && -e $ref_seq && -s $bam_list && -e $output_dir && -s $maf_file ); |
| 182 | |
| 183 | # Check on the files we expect to find within the provided output directory |
| 184 | $output_dir =~ s/(\/)+$//; # Remove trailing forward slashes if any |
| 185 | my $gene_covg_dir = "$output_dir/gene_covgs"; # Should contain per-gene coverage files per sample |
| 186 | my $total_covgs_file = "$output_dir/total_covgs"; # Should contain overall coverages per sample |
| 187 | print STDERR "Directory with per-gene coverages not found: $gene_covg_dir\n" unless( -e $gene_covg_dir ); |
| 188 | print STDERR "Total coverages file not found or is empty: $total_covgs_file\n" unless( -s $total_covgs_file ); |
| 189 | return undef unless( -e $gene_covg_dir && -s $total_covgs_file ); |
| 190 | |
| 191 | # Outputs of this script will be written to these locations in the output directory |
| 192 | my $overall_bmr_file = "$output_dir/overall_bmrs"; |
| 193 | my $gene_mr_file = "$output_dir/gene_mrs"; |
| 194 | $self->gene_mr_file( $gene_mr_file ); |
| 195 | |
| 196 | # Build a hash to quickly lookup the genes to be ignored for overall BMRs |
| 197 | my %ignored_genes = (); |
| 198 | if( defined $genes_to_ignore ) { |
| 199 | %ignored_genes = map { $_ => 1 } split( /,/, $genes_to_ignore ); |
| 200 | } |
| 201 | |
| 202 | # Parse out the names of the samples which should match the names of the coverage files needed |
| 203 | my ( @all_sample_names, %sample_idx ); |
| 204 | my $idx = 0; |
| 205 | my $sampleFh = IO::File->new( $bam_list ) or die "Couldn't open $bam_list. $!"; |
| 206 | while( my $line = $sampleFh->getline ) { |
| 207 | next if ( $line =~ m/^#/ ); |
| 208 | chomp( $line ); |
| 209 | my ( $sample ) = split( /\t/, $line ); |
| 210 | push( @all_sample_names, $sample ); |
| 211 | $sample_idx{$sample} = $idx++; |
| 212 | } |
| 213 | $sampleFh->close; |
| 214 | |
| 215 | # If the reference sequence FASTA file hasn't been indexed, do it |
| 216 | my $ref_seq_idx = "$ref_seq.fai"; |
| 217 | Genome::Sys->shellcmd( cmd => "samtools faidx $ref_seq" ) unless( -e $ref_seq_idx ); |
| 218 | |
| 219 | # Parse gene names and ROIs. Mutations outside these ROIs will be skipped |
| 220 | my ( @all_gene_names, %gene_idx ); |
| 221 | $idx = 0; |
| 222 | my $roi_bitmask = $self->create_empty_genome_bitmask( $ref_seq_idx ); |
| 223 | my $roiFh = IO::File->new( $roi_file ) or die "Couldn't open $roi_file. $!"; |
| 224 | while( my $line = $roiFh->getline ) { |
| 225 | next if( $line =~ m/^#/ ); |
| 226 | chomp $line; |
| 227 | my ( $chr, $start, $stop, $gene ) = split( /\t/, $line ); |
| 228 | if( !$roi_bitmask->{$chr} or $start > $roi_bitmask->{$chr}->Size ) { |
| 229 | print STDERR "Skipping invalid ROI bitmask $chr:$start-$stop\n"; |
| 230 | next; |
| 231 | } |
| 232 | $roi_bitmask->{$chr}->Interval_Fill( $start, $stop ); |
| 233 | unless( defined $gene_idx{$gene} ) { |
| 234 | push( @all_gene_names, $gene ); |
| 235 | $gene_idx{$gene} = $idx++; |
| 236 | } |
| 237 | } |
| 238 | $roiFh->close; |
| 239 | |
| 240 | # These are the various categories that each mutation will be classified into |
| 241 | my @mut_classes = ( AT_Transitions, AT_Transversions, CG_Transitions, CG_Transversions, CpG_Transitions, CpG_Transversions, Indels ); |
| 242 | push( @mut_classes, Truncations ) if( $separate_truncations ); |
| 243 | # Save the actual class names for reporting purposes, because the elements above are really just numerical constants |
| 244 | my @mut_class_names = qw( AT_Transitions AT_Transversions CG_Transitions CG_Transversions CpG_Transitions CpG_Transversions Indels ); |
| 245 | push( @mut_class_names, 'Truncations' ) if( $separate_truncations ); |
| 246 | |
| 247 | my @sample_mr; # Stores per sample covg and mutation information |
| 248 | foreach my $sample ( @all_sample_names ) { |
| 249 | $sample_mr[$sample_idx{$sample}][$_][mutations] = 0 foreach( @mut_classes ); |
| 250 | $sample_mr[$sample_idx{$sample}][$_][covd_bases] = 0 foreach( @mut_classes ); |
| 251 | } |
| 252 | |
| 253 | # Load the covered base-counts per sample from the output of "music bmr calc-covg" |
| 254 | print STDERR "Loading per-sample coverages stored in $total_covgs_file\n"; |
| 255 | my $sample_cnt_in_total_covgs_file = 0; |
| 256 | my $totCovgFh = IO::File->new( $total_covgs_file ) or die "Couldn't open $total_covgs_file. $!"; |
| 257 | while( my $line = $totCovgFh->getline ) { |
| 258 | next unless( $line =~ m/^\S+\t\d+\t\d+\t\d+\t\d+$/ and $line !~ m/^#/ ); |
| 259 | chomp( $line ); |
| 260 | ++$sample_cnt_in_total_covgs_file; |
| 261 | my ( $sample, $covd_bases, $covd_at_bases, $covd_cg_bases, $covd_cpg_bases ) = split( /\t/, $line ); |
| 262 | $sample_mr[$sample_idx{$sample}][AT_Transitions][covd_bases] = $covd_at_bases; |
| 263 | $sample_mr[$sample_idx{$sample}][AT_Transversions][covd_bases] = $covd_at_bases; |
| 264 | $sample_mr[$sample_idx{$sample}][CG_Transitions][covd_bases] = $covd_cg_bases; |
| 265 | $sample_mr[$sample_idx{$sample}][CG_Transversions][covd_bases] = $covd_cg_bases; |
| 266 | $sample_mr[$sample_idx{$sample}][CpG_Transitions][covd_bases] = $covd_cpg_bases; |
| 267 | $sample_mr[$sample_idx{$sample}][CpG_Transversions][covd_bases] = $covd_cpg_bases; |
| 268 | $sample_mr[$sample_idx{$sample}][Indels][covd_bases] = $covd_bases; |
| 269 | $sample_mr[$sample_idx{$sample}][Truncations][covd_bases] = $covd_bases if( $separate_truncations ); |
| 270 | } |
| 271 | $totCovgFh->close; |
| 272 | |
| 273 | unless( $sample_cnt_in_total_covgs_file == scalar( @all_sample_names )) { |
| 274 | print STDERR "Mismatching number of samples in $total_covgs_file and $bam_list\n"; |
| 275 | return undef; |
| 276 | } |
| 277 | |
| 278 | my @gene_mr; # Stores per gene covg and mutation information |
| 279 | foreach my $gene ( @all_gene_names ) { |
| 280 | foreach my $sample ( @all_sample_names ) { |
| 281 | $gene_mr[$sample_idx{$sample}][$gene_idx{$gene}][$_][mutations] = 0 foreach( @mut_classes ); |
| 282 | $gene_mr[$sample_idx{$sample}][$gene_idx{$gene}][$_][covd_bases] = 0 foreach( @mut_classes ); |
| 283 | } |
| 284 | } |
| 285 | |
| 286 | # Sum up the per-gene covered base-counts across samples from the output of "music bmr calc-covg" |
| 287 | print STDERR "Loading per-gene coverage files stored under $gene_covg_dir/\n"; |
| 288 | foreach my $sample ( @all_sample_names ) { |
| 289 | my $sample_covg_file = "$gene_covg_dir/$sample.covg"; |
| 290 | my $sampleCovgFh = IO::File->new( $sample_covg_file ) or die "Couldn't open $sample_covg_file. $!"; |
| 291 | while( my $line = $sampleCovgFh->getline ) { |
| 292 | next unless( $line =~ m/^\S+\t\d+\t\d+\t\d+\t\d+\t\d+$/ and $line !~ m/^#/ ); |
| 293 | chomp( $line ); |
| 294 | my ( $gene, undef, $covd_bases, $covd_at_bases, $covd_cg_bases, $covd_cpg_bases ) = split( /\t/, $line ); |
| 295 | $gene_mr[$sample_idx{$sample}][$gene_idx{$gene}][AT_Transitions][covd_bases] += $covd_at_bases; |
| 296 | $gene_mr[$sample_idx{$sample}][$gene_idx{$gene}][AT_Transversions][covd_bases] += $covd_at_bases; |
| 297 | $gene_mr[$sample_idx{$sample}][$gene_idx{$gene}][CG_Transitions][covd_bases] += $covd_cg_bases; |
| 298 | $gene_mr[$sample_idx{$sample}][$gene_idx{$gene}][CG_Transversions][covd_bases] += $covd_cg_bases; |
| 299 | $gene_mr[$sample_idx{$sample}][$gene_idx{$gene}][CpG_Transitions][covd_bases] += $covd_cpg_bases; |
| 300 | $gene_mr[$sample_idx{$sample}][$gene_idx{$gene}][CpG_Transversions][covd_bases] += $covd_cpg_bases; |
| 301 | $gene_mr[$sample_idx{$sample}][$gene_idx{$gene}][Indels][covd_bases] += $covd_bases; |
| 302 | $gene_mr[$sample_idx{$sample}][$gene_idx{$gene}][Truncations][covd_bases] += $covd_bases if( $separate_truncations ); |
| 303 | } |
| 304 | $sampleCovgFh->close; |
| 305 | } |
| 306 | |
| 307 | # Run "joinx ref-stats" to classify SNVs as being at AT, CG, or CpG sites in the reference |
| 308 | print STDERR "Running 'joinx ref-stats' to read reference FASTA and identify SNVs at AT, CG, CpG sites\n"; |
| 309 | my $maf_bed = Genome::Sys->create_temp_file_path(); |
| 310 | my $mafBedFh = IO::File->new( $maf_bed, ">" ) or die "Temporary file could not be created. $!"; |
| 311 | my $mafFh = IO::File->new( $maf_file ) or die "Couldn't open $maf_file. $!"; |
| 312 | while( my $line = $mafFh->getline ) { |
| 313 | next if( $line =~ m/^(#|Hugo_Symbol)/ ); |
| 314 | chomp $line; |
| 315 | my @cols = split( /\t/, $line ); |
| 316 | my ( $chr, $start, $stop, $mutation_type, $ref, $var1, $var2 ) = @cols[4..6,9..12]; |
| 317 | if( $mutation_type =~ m/^(SNP|DNP|ONP|TNP)$/ ) { |
| 318 | $mafBedFh->print( "$chr\t" . ( $start - 2 ) . "\t" . ( $start + 1 ) . "\n" ); |
| 319 | } |
| 320 | } |
| 321 | $mafFh->close; |
| 322 | $mafBedFh->close; |
| 323 | my $refstats_file = Genome::Sys->create_temp_file_path(); |
| 324 | Genome::Sys->shellcmd( cmd => "joinx ref-stats --ref-bases --bed $maf_bed --fasta $ref_seq --output $refstats_file" ); |
| 325 | |
| 326 | # Parse through the ref-stats output and load it into hashes for quick lookup later |
| 327 | my ( %ref_base, %cpg_site ); |
| 328 | my $refStatsFh = IO::File->new( $refstats_file ) or die "Couldn't open $refstats_file. $!"; |
| 329 | while( my $line = $refStatsFh->getline ) { |
| 330 | next if( $line =~ m/^#/ ); |
| 331 | chomp $line; |
| 332 | my ( $chr, undef, $pos, undef, undef, undef, $ref ) = split( /\t/, $line ); |
| 333 | my $locus = "$chr\t" . ( $pos - 1 ); |
| 334 | $ref_base{$locus} = substr( $ref, 1, 1 ); |
| 335 | $cpg_site{$locus} = 1 if( $ref =~ m/CG/ ); |
| 336 | } |
| 337 | $refStatsFh->close; |
| 338 | |
| 339 | # Create a hash to help classify SNVs |
| 340 | my %classify; |
| 341 | $classify{$_} = AT_Transitions foreach( qw( AG TC )); |
| 342 | $classify{$_} = AT_Transversions foreach( qw( AC AT TA TG )); |
| 343 | $classify{$_} = CG_Transitions foreach( qw( CT GA )); |
| 344 | $classify{$_} = CG_Transversions foreach( qw( CA CG GC GT )); |
| 345 | |
| 346 | # Parse through the MAF file and categorize each somatic mutation |
| 347 | print STDERR "Parsing MAF file to classify mutations\n"; |
| 348 | my %skip_cnts; |
| 349 | $mafFh = IO::File->new( $maf_file ) or die "Couldn't open $maf_file. $!"; |
| 350 | while( my $line = $mafFh->getline ) { |
| 351 | next if( $line =~ m/^(#|Hugo_Symbol)/ ); |
| 352 | chomp $line; |
| 353 | my @cols = split( /\t/, $line ); |
| 354 | my ( $gene, $chr, $start, $stop, $mutation_class, $mutation_type, $ref, $var1, $var2, $sample ) = @cols[0,4..6,8..12,15]; |
| 355 | |
| 356 | # Skip mutations in samples that are not in the provided bam list |
| 357 | unless( defined $sample_idx{$sample} ) { |
| 358 | $skip_cnts{"belong to unrecognized samples"}++; |
| 359 | print STDERR "Skipping unrecognized sample ($sample not in BAM list): $gene, $chr:$start-$stop\n" if( $show_skipped ); |
| 360 | next; |
| 361 | } |
| 362 | |
| 363 | # If the mutation classification is odd, quit with error |
| 364 | if( $mutation_class !~ m/^(Missense_Mutation|Nonsense_Mutation|Nonstop_Mutation|Splice_Site|Translation_Start_Site|Frame_Shift_Del|Frame_Shift_Ins|In_Frame_Del|In_Frame_Ins|Silent|Intron|RNA|3'Flank|3'UTR|5'Flank|5'UTR|IGR|Targeted_Region|De_novo_Start_InFrame|De_novo_Start_OutOfFrame)$/ ) { |
| 365 | print STDERR "Unrecognized Variant_Classification \"$mutation_class\" in MAF file: $gene, $chr:$start-$stop\n"; |
| 366 | print STDERR "Please use TCGA MAF Specification v2.3.\n"; |
| 367 | return undef; |
| 368 | } |
| 369 | |
| 370 | # If user wants, skip Silent mutations, or those in Introns, RNA, UTRs, Flanks, IGRs, or the ubiquitous Targeted_Region |
| 371 | if(( $skip_non_coding && $mutation_class =~ m/^(Intron|RNA|3'Flank|3'UTR|5'Flank|5'UTR|IGR|Targeted_Region)$/ ) || |
| 372 | ( $skip_silent && $mutation_class =~ m/^Silent$/ )) { |
| 373 | $skip_cnts{"are classified as $mutation_class"}++; |
| 374 | print STDERR "Skipping $mutation_class mutation: $gene, $chr:$start-$stop\n" if( $show_skipped ); |
| 375 | next; |
| 376 | } |
| 377 | |
| 378 | # If the mutation type is odd, quit with error |
| 379 | if( $mutation_type !~ m/^(SNP|DNP|TNP|ONP|INS|DEL|Consolidated)$/ ) { |
| 380 | print STDERR "Unrecognized Variant_Type \"$mutation_type\" in MAF file: $gene, $chr:$start-$stop\n"; |
| 381 | print STDERR "Please use TCGA MAF Specification v2.3.\n"; |
| 382 | return undef; |
| 383 | } |
| 384 | |
| 385 | # Skip mutations that were consolidated into others (E.g. SNP consolidated into a TNP) |
| 386 | if( $mutation_type =~ m/^Consolidated$/ ) { |
| 387 | $skip_cnts{"are consolidated into another"}++; |
| 388 | print STDERR "Skipping consolidated mutation: $gene, $chr:$start-$stop\n" if( $show_skipped ); |
| 389 | next; |
| 390 | } |
| 391 | |
| 392 | # Skip mutations that fall completely outside any of the provided regions of interest |
| 393 | if( $self->count_bits( $roi_bitmask->{$chr}, $start, $stop ) == 0 ) { |
| 394 | $skip_cnts{"are outside any ROIs"}++; |
| 395 | print STDERR "Skipping mutation that falls outside ROIs: $gene, $chr:$start-$stop\n" if( $show_skipped ); |
| 396 | next; |
| 397 | } |
| 398 | |
| 399 | # Skip mutations whose gene names don't match any of those in the ROI list |
| 400 | unless( defined $gene_idx{$gene} ) { |
| 401 | $skip_cnts{"have unrecognized gene names"}++; |
| 402 | print STDERR "Skipping unrecognized gene name (not in ROI file): $gene, $chr:$start-$stop\n" if( $show_skipped ); |
| 403 | next; |
| 404 | } |
| 405 | |
| 406 | my $class = ''; |
| 407 | # Check if the mutation is the truncating type, if the user wanted a separate category of those |
| 408 | if( $separate_truncations && $mutation_class =~ m/^(Nonsense_Mutation|Splice_Site|Frame_Shift_Del|Frame_Shift_Ins)/ ) { |
| 409 | $class = Truncations; |
| 410 | } |
| 411 | # Classify the mutation as AT/CG/CpG Transition, AT/CG/CpG Transversion |
| 412 | elsif( $mutation_type =~ m/^(SNP|DNP|ONP|TNP)$/ ) { |
| 413 | # ::TBD:: For DNPs and TNPs, we use only the first base for mutation classification |
| 414 | $ref = substr( $ref, 0, 1 ); |
| 415 | $var1 = substr( $var1, 0, 1 ); |
| 416 | $var2 = substr( $var2, 0, 1 ); |
| 417 | |
| 418 | # If the alleles are anything but A, C, G, or T then quit with error |
| 419 | if( $ref !~ m/[ACGT]/ || $var1 !~ m/[ACGT]/ || $var2 !~ m/[ACGT]/ ) { |
| 420 | print STDERR "Unrecognized allele in column Reference_Allele, Tumor_Seq_Allele1, or Tumor_Seq_Allele2: $gene, $chr:$start-$stop\n"; |
| 421 | print STDERR "Please use TCGA MAF Specification v2.3.\n"; |
| 422 | return undef; |
| 423 | } |
| 424 | |
| 425 | # Use the classify hash to find whether this SNV is an AT/CG Transition/Transversion |
| 426 | $class = $classify{ "$ref$var1" } if( defined $classify{ "$ref$var1" } ); |
| 427 | $class = $classify{ "$ref$var2" } if( defined $classify{ "$ref$var2" } ); |
| 428 | |
| 429 | # Check if the ref base in the MAF matched what we fetched from the ref-seq |
| 430 | my $locus = "$chr\t$start"; |
| 431 | if( defined $ref_base{$locus} && $ref_base{$locus} ne $ref ) { |
| 432 | print STDERR "Reference allele $ref for $gene variant at $chr:$start-$stop is " . $ref_base{$locus} . " in the FASTA. Using it anyway.\n"; |
| 433 | } |
| 434 | |
| 435 | # Check if a C or G reference allele belongs to a CpG pair in the refseq |
| 436 | if(( $ref eq 'C' || $ref eq 'G' ) && defined $cpg_site{$locus} ) { |
| 437 | $class = (( $class == CG_Transitions ) ? CpG_Transitions : CpG_Transversions ); |
| 438 | } |
| 439 | } |
| 440 | # Classify it as an indel (excludes splice-site and frame-shift if user wanted truncations separately) |
| 441 | elsif( $mutation_type =~ m/^(INS|DEL)$/ ) { |
| 442 | $class = Indels; |
| 443 | } |
| 444 | |
| 445 | # The user's gene exclusion list affects only the overall BMR calculations |
| 446 | $sample_mr[$sample_idx{$sample}][$class][mutations]++ unless( defined $ignored_genes{$gene} ); |
| 447 | $gene_mr[$sample_idx{$sample}][$gene_idx{$gene}][$class][mutations]++; |
| 448 | } |
| 449 | $mafFh->close; |
| 450 | |
| 451 | # Display statistics related to parsing the MAF |
| 452 | print STDERR "Finished Parsing the MAF file to classify mutations\n"; |
| 453 | foreach my $skip_type ( sort {$skip_cnts{$b} <=> $skip_cnts{$a}} keys %skip_cnts ) { |
| 454 | print STDERR "Skipped " . $skip_cnts{$skip_type} . " mutation(s) that $skip_type\n" if( defined $skip_cnts{$skip_type} ); |
| 455 | } |
| 456 | |
| 457 | # If the user wants, merge together concurrent mutations of a gene in the same sample |
| 458 | if( $merge_concurrent_muts ) { |
| 459 | foreach my $sample ( @all_sample_names ) { |
| 460 | foreach my $gene ( @all_gene_names ) { |
| 461 | next unless( defined $gene_mr[$sample_idx{$sample}][$gene_idx{$gene}] ); |
| 462 | my $num_muts = 0; |
| 463 | $num_muts += $gene_mr[$sample_idx{$sample}][$gene_idx{$gene}][$_][mutations] foreach( @mut_classes ); |
| 464 | if( $num_muts > 1 ) { |
| 465 | foreach my $class ( @mut_classes ) { |
| 466 | my $muts_in_class = $gene_mr[$sample_idx{$sample}][$gene_idx{$gene}][$class][mutations]; # Num of muts of gene in this class |
| 467 | $sample_mr[$sample_idx{$sample}][$class][mutations] -= $muts_in_class; # Take it out of the sample total |
| 468 | $muts_in_class /= $num_muts; # Turn it into a fraction of the total number of muts in this gene |
| 469 | $gene_mr[$sample_idx{$sample}][$gene_idx{$gene}][$class][mutations] = $muts_in_class; # Use the fraction as the num muts of gene in this class |
| 470 | $sample_mr[$sample_idx{$sample}][$class][mutations] += $muts_in_class; # Add the same fraction to the sample total |
| 471 | } |
| 472 | } |
| 473 | } |
| 474 | } |
| 475 | } |
| 476 | |
| 477 | # Calculate per-sample BMRs, and also subtract out covered bases in genes the user wants ignored |
| 478 | foreach my $sample ( @all_sample_names ) { |
| 479 | my $tot_muts = 0; |
| 480 | foreach my $class ( @mut_classes ) { |
| 481 | # Subtract the covered bases in this class that belong to the genes to be ignored |
| 482 | # ::TBD:: Some of these bases may also belong to another gene (on the other strand maybe?), and those should not be subtracted |
| 483 | foreach my $ignored_gene ( keys %ignored_genes ) { |
| 484 | $sample_mr[$sample_idx{$sample}][$class][covd_bases] -= $gene_mr[$sample_idx{$sample}][$gene_idx{$ignored_gene}][$class][covd_bases] if( defined $gene_mr[$sample_idx{$sample}][$gene_idx{$ignored_gene}] ); |
| 485 | } |
| 486 | $tot_muts += $sample_mr[$sample_idx{$sample}][$class][mutations]; |
| 487 | } |
| 488 | $sample_mr[$sample_idx{$sample}][Overall][bmr] = $tot_muts / $sample_mr[$sample_idx{$sample}][Indels][covd_bases]; |
| 489 | } |
| 490 | |
| 491 | # Cluster samples into bmr-groups using k-means clustering |
| 492 | my @sample_bmrs = map { $sample_mr[$sample_idx{$_}][Overall][bmr] } @all_sample_names; |
| 493 | my @bmr_clusters = k_means( $bmr_groups, \@sample_bmrs ); |
| 494 | |
| 495 | # Calculate overall BMRs for each cluster of samples, and print them to file |
| 496 | my %cluster_bmr; # Stores per cluster categorized BMR |
| 497 | my $totBmrFh = IO::File->new( $overall_bmr_file, ">" ) or die "Couldn't open $overall_bmr_file. $!"; |
| 498 | $totBmrFh->print( "#User-specified genes skipped in these calculations: $genes_to_ignore\n" ) if( defined $genes_to_ignore ); |
| 499 | my ( $covered_bases_sum, $mutations_sum ) = ( 0, 0 ); |
| 500 | for( my $i = 0; $i < scalar( @bmr_clusters ); ++$i ) { |
| 501 | my @samples_in_cluster = map { $all_sample_names[$_] } @{$bmr_clusters[$i]}; |
| 502 | unless( $bmr_groups == 1 ) { |
| 503 | $totBmrFh->print( "#BMR sub-group ", $i + 1, " (", scalar( @{$bmr_clusters[$i]} ), " samples)\n" ); |
| 504 | $totBmrFh->print( "#Samples: ", join( ",", @samples_in_cluster ), "\n" ); |
| 505 | } |
| 506 | $totBmrFh->print( "#Mutation_Class\tCovered_Bases\tMutations\tOverall_BMR\n" ); |
| 507 | |
| 508 | my ( $tot_covd_bases, $tot_muts ) = ( 0, 0 ); |
| 509 | foreach my $class ( @mut_classes ) { |
| 510 | my ( $covd_bases, $mutations ) = ( 0, 0 ); |
| 511 | foreach my $sample ( @samples_in_cluster ) { |
| 512 | $covd_bases += $sample_mr[$sample_idx{$sample}][$class][covd_bases]; |
| 513 | $mutations += $sample_mr[$sample_idx{$sample}][$class][mutations]; |
| 514 | } |
| 515 | $tot_covd_bases = $covd_bases if( $class == Indels ); # Save this to calculate overall BMR below |
| 516 | # Calculate overall BMR for this mutation class and print it to file |
| 517 | $cluster_bmr{$i}[$class][bmr] = ( $covd_bases == 0 ? 0 : ( $mutations / $covd_bases )); |
| 518 | $totBmrFh->print( join( "\t", $mut_class_names[$class], $covd_bases, $mutations, $cluster_bmr{$i}[$class][bmr] ), "\n" ); |
| 519 | $tot_muts += $mutations; |
| 520 | } |
| 521 | $totBmrFh->print( join( "\t", "Overall_BMR", $tot_covd_bases, $tot_muts, $tot_muts / $tot_covd_bases ), "\n\n" ); |
| 522 | $covered_bases_sum += $tot_covd_bases; |
| 523 | $mutations_sum += $tot_muts; |
| 524 | } |
| 525 | $totBmrFh->close; |
| 526 | $self->bmr_output( $mutations_sum / $covered_bases_sum ); |
| 527 | |
| 528 | # Print out a file containing per-gene mutation counts and covered bases for use by "music smg" |
| 529 | my $geneBmrFh = IO::File->new( $gene_mr_file, ">" ) or die "Couldn't open $gene_mr_file. $!"; |
| 530 | $geneBmrFh->print( "#Gene\tMutation_Class\tCovered_Bases\tMutations\tBMR\n" ); |
| 531 | foreach my $gene ( sort @all_gene_names ) { |
| 532 | my ( $tot_covd_bases, $tot_muts ) = ( 0, 0 ); |
| 533 | for( my $i = 0; $i < scalar( @bmr_clusters ); ++$i ) { |
| 534 | my @samples_in_cluster = map { $all_sample_names[$_] } @{$bmr_clusters[$i]}; |
| 535 | foreach my $class ( @mut_classes ) { |
| 536 | my ( $covd_bases, $mutations ) = ( 0, 0 ); |
| 537 | foreach my $sample( @samples_in_cluster ) { |
| 538 | if( defined $gene_mr[$sample_idx{$sample}][$gene_idx{$gene}] ) { |
| 539 | $covd_bases += $gene_mr[$sample_idx{$sample}][$gene_idx{$gene}][$class][covd_bases]; |
| 540 | $mutations += $gene_mr[$sample_idx{$sample}][$gene_idx{$gene}][$class][mutations]; |
| 541 | } |
| 542 | } |
| 543 | my $rename_class = $mut_class_names[$class]; |
| 544 | $rename_class = ( $rename_class . "_SubGroup" . ( $i + 1 )) if( $bmr_groups > 1 ); |
| 545 | $geneBmrFh->print( join( "\t", $gene, $rename_class, $covd_bases, $mutations, $cluster_bmr{$i}[$class][bmr] ), "\n" ); |
| 546 | $tot_muts += $mutations; |
| 547 | $tot_covd_bases += $covd_bases if( $class == Indels ); |
| 548 | } |
| 549 | } |
| 550 | $geneBmrFh->print( join( "\t", $gene, "Overall", $tot_covd_bases, $tot_muts, $self->bmr_output ), "\n" ); |
| 551 | } |
| 552 | $geneBmrFh->close; |
| 553 | |
| 554 | return 1; |
| 555 | } |
| 556 | |
| 557 | # Creates an empty whole genome bitmask based on the given reference sequence index |
| 558 | sub create_empty_genome_bitmask { |
| 559 | my ( $self, $ref_seq_idx_file ) = @_; |
| 560 | my %genome; |
| 561 | my $refFh = IO::File->new( $ref_seq_idx_file ) or die "Couldn't open $ref_seq_idx_file. $!"; |
| 562 | while( my $line = $refFh->getline ) { |
| 563 | my ( $chr, $length ) = split( /\t/, $line ); |
| 564 | $genome{$chr} = Bit::Vector->new( $length + 1 ); # Adding a base for 1-based coordinates |
| 565 | } |
| 566 | $refFh->close; |
| 567 | return \%genome; |
| 568 | } |
| 569 | |
| 570 | # Counts the number of bits that are set in the given region of a Bit:Vector |
| 571 | sub count_bits { |
| 572 | my ( $self, $vector, $start, $stop ) = @_; |
| 573 | my $count = 0; |
| 574 | for my $pos ( $start..$stop ) { |
| 575 | ++$count if( $vector->bit_test( $pos )); |
| 576 | } |
| 577 | return $count; |
| 578 | } |
| 579 | |
| 580 | # Given a list of numerical values, returns k clusters based on k-means clustering |
| 581 | sub k_means { |
| 582 | my ( $k, $list_ref ) = @_; |
| 583 | my @vals = @{$list_ref}; |
| 584 | my $num_vals = scalar( @vals ); |
| 585 | |
| 586 | # Start with the first k values as the centroids |
| 587 | my @centroids = @vals[0..($k-1)]; |
| 588 | my @prev_centroids = map { 0 } @centroids; |
| 589 | my @groups = (); |
| 590 | |
| 591 | my $diff_means = 1; # Arbitrary non-zero value |
| 592 | # Repeat until the difference between these centroids and the previous ones, converges to zero |
| 593 | while( $diff_means > 0 ) { |
| 594 | @groups = (); |
| 595 | # Group values into clusters based on closest centroid |
| 596 | for( my $i = 0; $i < $num_vals; ++$i ) { |
| 597 | my @distances = map { abs( $vals[$i] - $_ ) } @centroids; |
| 598 | my $closest = min( @distances ); |
| 599 | for( my $j = 0; $j < $k; ++$j ) { |
| 600 | if( $distances[$j] == $closest ) { push( @{$groups[$j]}, $i ); last; } |
| 601 | } |
| 602 | } |
| 603 | |
| 604 | # Calculate means to be the new centroids, and the sum of differences |
| 605 | $diff_means = 0; |
| 606 | for( my $i = 0; $i < $k; ++$i ) { |
| 607 | $centroids[$i] = sum( map {$vals[$_]} @{$groups[$i]} ); |
| 608 | $centroids[$i] /= scalar( @{$groups[$i]} ); |
| 609 | $diff_means += abs( $centroids[$i] - $prev_centroids[$i] ); |
| 610 | } |
| 611 | |
| 612 | # Save the current centroids for comparisons with those in the next iteration |
| 613 | @prev_centroids = @centroids; |
| 614 | } |
| 615 | return @groups; |
| 616 | } |
| 617 | |
| 618 | 1; |