| 1 | package Bio::ToolBox::db_helper::bam; | ||
| 2 | |||
| 3 | use warnings; | ||
| 4 | use strict; | ||
| 5 | use Carp; | ||
| 6 | use File::Copy; | ||
| 7 | use English qw( -no_match_vars ); | ||
| 8 | use Bio::ToolBox::db_helper::constants; | ||
| 9 | use Bio::ToolBox::db_helper::alignment_callbacks; | ||
| 10 | use Bio::DB::Sam; | ||
| 11 | require Exporter; | ||
| 12 | |||
| 13 | my $parallel; | ||
| 14 | eval { | ||
| 15 | # check for parallel support, when counting bam alignments | ||
| 16 | require Parallel::ForkManager; | ||
| 17 | $parallel = 1; | ||
| 18 | }; | ||
| 19 | |||
| 20 | our $VERSION = '2.03'; | ||
| 21 | |||
| 22 | # Exported names | ||
| 23 | our @ISA = qw(Exporter); | ||
| 24 | ## no critic | ||
| 25 | ## this is never intended to be used directly by end users | ||
| 26 | ## and exporting everything is required | ||
| 27 | our @EXPORT = qw( | ||
| 28 | open_bam_db | ||
| 29 | open_indexed_fasta | ||
| 30 | check_bam_index | ||
| 31 | write_new_bam_file | ||
| 32 | collect_bam_scores | ||
| 33 | sum_total_bam_alignments | ||
| 34 | ); | ||
| 35 | ## use critic | ||
| 36 | |||
| 37 | # Hash of Bam chromosomes | ||
| 38 | my %BAM_CHROMOS; | ||
| 39 | |||
| 40 | # sometimes user may request a chromosome that's not in the bigfile | ||
| 41 | # that could lead to an exception | ||
| 42 | # we will record the chromosomes list in this hash | ||
| 43 | # $BAM_CHROMOS{bamfile}{chromos} | ||
| 44 | # we also record the chromosome name variant with or without chr prefix | ||
| 45 | # to accommodate different naming conventions | ||
| 46 | |||
| 47 | # Opened Bam db objects | ||
| 48 | my %OPENED_BAM; | ||
| 49 | |||
| 50 | # a cache for opened Bam files | ||
| 51 | # caching here is only for local purposes of collecting scores | ||
| 52 | # db_helper also provides caching of db objects but with option to force open in | ||
| 53 | # the case of forking processes - we don't have that here | ||
| 54 | |||
| 55 | ### Open a bam database connection | ||
| 56 | sub open_bam_db { | ||
| 57 | my $bamfile = shift; | ||
| 58 | |||
| 59 | # check the path | ||
| 60 | my $path = $bamfile; | ||
| 61 | $path =~ s/^file://; # strip the file prefix if present | ||
| 62 | |||
| 63 | # check for bam index | ||
| 64 | check_bam_index($path); | ||
| 65 | |||
| 66 | # open the bam database object | ||
| 67 | # we specifically do not cache the bam object or chromosome names here | ||
| 68 | my $sam; | ||
| 69 | eval { $sam = Bio::DB::Sam->new( -bam => $path ); }; | ||
| 70 | if ($sam) { | ||
| 71 | return $sam; | ||
| 72 | } | ||
| 73 | elsif ( $EVAL_ERROR or $OS_ERROR ) { | ||
| 74 | carp "ERROR: Unable to open Bam file: $EVAL_ERROR $OS_ERROR"; | ||
| 75 | return; | ||
| 76 | } | ||
| 77 | else { | ||
| 78 | return; | ||
| 79 | } | ||
| 80 | } | ||
| 81 | |||
| 82 | ### Open an indexed fasta file | ||
| 83 | sub open_indexed_fasta { | ||
| 84 | my $fasta = shift; | ||
| 85 | if ( $fasta =~ /\.gz$/ ) { | ||
| 86 | carp | ||
| 87 | "ERROR: Bio::DB::Sam::Fai doesn't support compressed fasta files! Please decompress"; | ||
| 88 | return; | ||
| 89 | } | ||
| 90 | my $fai; | ||
| 91 | eval { $fai = Bio::DB::Sam::Fai->load($fasta) }; | ||
| 92 | |||
| 93 | # this should automatically build the fai index if possible | ||
| 94 | if ($fai) { | ||
| 95 | return $fai; | ||
| 96 | } | ||
| 97 | else { | ||
| 98 | carp "ERROR: unable to open Fasta file!"; | ||
| 99 | return; | ||
| 100 | } | ||
| 101 | } | ||
| 102 | |||
| 103 | ### Check for a bam index | ||
| 104 | sub check_bam_index { | ||
| 105 | |||
| 106 | # the old samtools always expects a .bam.bai index file | ||
| 107 | # I find that relying on -autoindex yields a flaky Bio::DB::Sam object that | ||
| 108 | # doesn't always work as expected. Best to create the index BEFORE opening | ||
| 109 | |||
| 110 | my $bamfile = shift; | ||
| 111 | return if ( $bamfile =~ /^(?:http | ftp)/xi ); # I can't do much with remote files | ||
| 112 | |||
| 113 | # we will check the modification time to make sure index is newer | ||
| 114 | my $bam_mtime = ( stat($bamfile) )[9]; | ||
| 115 | |||
| 116 | # optional index names | ||
| 117 | my $bam_index = "$bamfile.bai"; # .bam.bai | ||
| 118 | my $alt_index = $bamfile; | ||
| 119 | $alt_index =~ s/bam$/bai/i; # picard uses .bai instead of .bam.bai as samtools does | ||
| 120 | |||
| 121 | # check for existing index | ||
| 122 | if ( -e $bam_index ) { | ||
| 123 | if ( ( stat($bam_index) )[9] < $bam_mtime ) { | ||
| 124 | |||
| 125 | # index is older than bam file | ||
| 126 | print " index $bam_index is old. Attempting to update time stamp.\n"; | ||
| 127 | my $now = time; | ||
| 128 | utime( $now, $now, $bam_index ) || Bio::DB::Bam->reindex($bamfile); | ||
| 129 | } | ||
| 130 | } | ||
| 131 | elsif ( -e $alt_index ) { | ||
| 132 | if ( ( stat($alt_index) )[9] < $bam_mtime ) { | ||
| 133 | |||
| 134 | # index is older than bam file | ||
| 135 | print " index $alt_index is old.\n"; | ||
| 136 | } | ||
| 137 | |||
| 138 | # reuse this index | ||
| 139 | copy( $alt_index, $bam_index ); | ||
| 140 | } | ||
| 141 | else { | ||
| 142 | # make a new index | ||
| 143 | Bio::DB::Bam->reindex($bamfile); | ||
| 144 | } | ||
| 145 | } | ||
| 146 | |||
| 147 | ### Write a new bam file | ||
| 148 | sub write_new_bam_file { | ||
| 149 | my $file = shift; | ||
| 150 | $file .= '.bam' unless $file =~ /\.bam$/i; | ||
| 151 | my $bam = Bio::DB::Bam->open( $file, 'w' ); | ||
| 152 | if ($bam) { | ||
| 153 | return $bam; | ||
| 154 | } | ||
| 155 | else { | ||
| 156 | carp "ERROR: unable to open bam file $file! $OS_ERROR"; | ||
| 157 | return; | ||
| 158 | } | ||
| 159 | } | ||
| 160 | |||
| 161 | ### Collect Bam scores | ||
| 162 | sub collect_bam_scores { | ||
| 163 | |||
| 164 | # passed parameters as array ref | ||
| 165 | # chromosome, start, stop, strand, strandedness, method, db, dataset | ||
| 166 | my $param = shift; | ||
| 167 | |||
| 168 | # initialize score structures | ||
| 169 | # which one is used depends on the return type variable | ||
| 170 | my %pos2data; # either position => count or position => [scores] | ||
| 171 | my $scores = []; # just scores | ||
| 172 | |||
| 173 | # look at each bamfile | ||
| 174 | # usually there is only one, but there may be more than one | ||
| 175 | for ( my $b = DATA; $b < scalar @{$param}; $b++ ) { | ||
| 176 | |||
| 177 | ## Open the Bam File | ||
| 178 | my $bamfile = $param->[$b]; | ||
| 179 | my $bam = $OPENED_BAM{$bamfile} || undef; | ||
| 180 | unless ($bam) { | ||
| 181 | |||
| 182 | # open and cache the bam file | ||
| 183 | $bam = open_bam_db($bamfile) | ||
| 184 | or croak "FATAL: Unable to open bam file '$bamfile'!"; | ||
| 185 | $OPENED_BAM{$bamfile} = $bam; | ||
| 186 | |||
| 187 | # record the chromosomes and possible variants | ||
| 188 | $BAM_CHROMOS{$bamfile} = {}; | ||
| 189 | foreach my $s ( $bam->seq_ids ) { | ||
| 190 | $BAM_CHROMOS{$bamfile}{$s} = $s; | ||
| 191 | if ( $s =~ /^chr(.+)$/ ) { | ||
| 192 | $BAM_CHROMOS{$bamfile}{$1} = $s; | ||
| 193 | } | ||
| 194 | else { | ||
| 195 | $BAM_CHROMOS{$bamfile}{"chr$s"} = $s; | ||
| 196 | } | ||
| 197 | } | ||
| 198 | } | ||
| 199 | |||
| 200 | # first check that the chromosome is present | ||
| 201 | my $chromo = $BAM_CHROMOS{$bamfile}{ $param->[CHR] } or next; | ||
| 202 | |||
| 203 | # convert coordinates into low level coordinates | ||
| 204 | # consumed by the low level Bam API | ||
| 205 | my ( $tid, $zstart, $end ) = $bam->header->parse_region( | ||
| 206 | sprintf( "%s:%d-%d", $chromo, $param->[STRT], $param->[STOP] ) ); | ||
| 207 | |||
| 208 | ## Collect the data according to the requested value type | ||
| 209 | # we will either use simple coverage or alignments (count) | ||
| 210 | if ( $param->[METH] =~ /count/ ) { | ||
| 211 | |||
| 212 | # Need to collect and count alignments | ||
| 213 | |||
| 214 | ## Set the callback and a callback data structure | ||
| 215 | my $callback = assign_callback($param); | ||
| 216 | my %data = ( | ||
| 217 | 'scores' => $scores, | ||
| 218 | 'index' => \%pos2data, | ||
| 219 | 'start' => $param->[STRT], | ||
| 220 | 'stop' => $param->[STOP], | ||
| 221 | ); | ||
| 222 | |||
| 223 | # get the alignments | ||
| 224 | # we are using the low level API to eke out performance | ||
| 225 | $bam->bam_index->fetch( $bam->bam, $tid, $zstart, $end, $callback, \%data ); | ||
| 226 | } | ||
| 227 | else { | ||
| 228 | ## Coverage | ||
| 229 | # I am assuming everything else is working with read coverage | ||
| 230 | |||
| 231 | # generate the coverage, this will ignore strand | ||
| 232 | my $coverage = $bam->bam_index->coverage( | ||
| 233 | $bam->bam, | ||
| 234 | $tid, | ||
| 235 | $zstart, # 0-based coordinates | ||
| 236 | $end, | ||
| 237 | ); | ||
| 238 | |||
| 239 | # convert the coverage data | ||
| 240 | # by default, this should return the coverage at 1 bp resolution | ||
| 241 | if ( scalar @{$coverage} ) { | ||
| 242 | |||
| 243 | # check whether we need to index the scores | ||
| 244 | if ( $param->[RETT] == 2 ) { | ||
| 245 | for ( my $i = $param->[STRT]; $i <= $param->[STOP]; $i++ ) { | ||
| 246 | |||
| 247 | # move the scores into the position score hash | ||
| 248 | $pos2data{$i} += $coverage->[ $i - $param->[STRT] ]; | ||
| 249 | } | ||
| 250 | } | ||
| 251 | else { | ||
| 252 | $scores = $coverage; | ||
| 253 | } | ||
| 254 | } | ||
| 255 | } | ||
| 256 | } | ||
| 257 | |||
| 258 | ## Return collected data | ||
| 259 | if ( $param->[RETT] == 2 ) { | ||
| 260 | return wantarray ? %pos2data : \%pos2data; | ||
| 261 | } | ||
| 262 | else { | ||
| 263 | return wantarray ? @{$scores} : $scores; | ||
| 264 | } | ||
| 265 | } | ||
| 266 | |||
| 267 | ### Determine total number of alignments in a bam file | ||
| 268 | sub sum_total_bam_alignments { | ||
| 269 | |||
| 270 | # Passed arguments; | ||
| 271 | my $sam_file = shift; | ||
| 272 | my $cpu = shift || 2; # number of forks to execute in parallel | ||
| 273 | $cpu = 1 unless ($parallel); | ||
| 274 | unless ($sam_file) { | ||
| 275 | carp "ERROR: no Bam file or bam db object passed!"; | ||
| 276 | return; | ||
| 277 | } | ||
| 278 | |||
| 279 | # Open Bam file if necessary | ||
| 280 | my $sam; | ||
| 281 | my $sam_ref = ref $sam_file; | ||
| 282 | if ( $sam_ref =~ /Bio::DB::Sam/x ) { | ||
| 283 | |||
| 284 | # we have an opened sam db object | ||
| 285 | $sam = $sam_file; | ||
| 286 | } | ||
| 287 | else { | ||
| 288 | # we have a name of a sam file | ||
| 289 | $sam = open_bam_db($sam_file); | ||
| 290 | return unless ($sam); | ||
| 291 | } | ||
| 292 | |||
| 293 | # prepare the alignment iterator callback | ||
| 294 | my $callback = sub { | ||
| 295 | my ( $a, $n ) = @_; | ||
| 296 | |||
| 297 | # check alignment flags | ||
| 298 | my $flag = $a->flag; | ||
| 299 | return if $flag & 0xf04; # UNMAP,SECONDARY,QCFAIL,DUP,SUPPLEMENTARY | ||
| 300 | |||
| 301 | # check mapping quality based on global variable | ||
| 302 | return if $a->qual < $MAPQ; | ||
| 303 | |||
| 304 | # count properly paired alignments only once by skipping reverse alignment | ||
| 305 | if ( $flag & 0x01 and $flag & 0x2 ) { | ||
| 306 | return if ( $flag & 0x10 ); | ||
| 307 | } | ||
| 308 | |||
| 309 | # count this fragment | ||
| 310 | ${$n}++; | ||
| 311 | }; | ||
| 312 | |||
| 313 | # prepare the counting subroutine | ||
| 314 | my $counter = sub { | ||
| 315 | my $tid = shift; | ||
| 316 | my $number = 0; | ||
| 317 | $sam->bam_index->fetch( $sam->bam, $tid, 0, $sam->target_len($tid), | ||
| 318 | $callback, \$number ); | ||
| 319 | return $number; | ||
| 320 | }; | ||
| 321 | |||
| 322 | # Count the alignments on each chromosome | ||
| 323 | my $total_read_number = 0; | ||
| 324 | if ( $cpu > 1 ) { | ||
| 325 | |||
| 326 | # count each chromosome in multiple parallel threads to speed things up | ||
| 327 | |||
| 328 | # generate relatively equal lists of chromosome for each process based on length | ||
| 329 | my @chromosomes = map { $_->[0] } | ||
| 330 | sort { $b->[1] <=> $a->[1] } | ||
| 331 | map { [ $_, $sam->target_len($_) ] } ( 0 .. $sam->n_targets - 1 ); | ||
| 332 | my @list; # array of arrays, [process][chromosome id] | ||
| 333 | my $i = 1; | ||
| 334 | while (@chromosomes) { | ||
| 335 | push @{ $list[$i] }, shift @chromosomes; | ||
| 336 | $i++; | ||
| 337 | $i = 1 if $i > $cpu; | ||
| 338 | } | ||
| 339 | |||
| 340 | # we will use Parallel ForkManager for convenience | ||
| 341 | my $pm = Parallel::ForkManager->new($cpu); | ||
| 342 | $pm->run_on_finish( | ||
| 343 | sub { | ||
| 344 | my ( $pid, $exit_code, $ident, $exit_signal, $core_dump, $count ) = | ||
| 345 | @_; | ||
| 346 | $total_read_number += ${$count}; | ||
| 347 | } | ||
| 348 | ); | ||
| 349 | |||
| 350 | # Count the chromosomes in parallel processess | ||
| 351 | foreach my $n ( 1 .. $cpu ) { | ||
| 352 | $pm->start and next; | ||
| 353 | |||
| 354 | ### In child | ||
| 355 | $sam->clone; # to make it fork safe | ||
| 356 | my $count = 0; | ||
| 357 | foreach ( @{ $list[$n] } ) { | ||
| 358 | |||
| 359 | # count each chromosome in this process list | ||
| 360 | $count += &{$counter}($_); | ||
| 361 | } | ||
| 362 | $pm->finish( 0, \$count ); | ||
| 363 | } | ||
| 364 | $pm->wait_all_children; | ||
| 365 | } | ||
| 366 | |||
| 367 | else { | ||
| 368 | # loop through all the chromosomes in one execution thread | ||
| 369 | for my $tid ( 0 .. $sam->n_targets - 1 ) { | ||
| 370 | |||
| 371 | # each chromosome is internally represented in the bam file as | ||
| 372 | # a numeric target identifier | ||
| 373 | $total_read_number += &{$counter}($tid); | ||
| 374 | } | ||
| 375 | } | ||
| 376 | |||
| 377 | # done | ||
| 378 | return $total_read_number; | ||
| 379 | } | ||
| 380 | |||
| 381 | 1; | ||
| 382 | |||
| 383 | __END__ |