Calculate coverage depth for a set of windows (perl)
Appearance
calDepth /group/jrigrp/bigd/B73.24.merged.bam chr10:85100000-85150000 | awk '{sum+=$3} END { print sum }'
This code gives the sum total depth for a region on Chromosome 10 from B73 sequence. To get the average, divide by the length of the region.
perl getcov.pl pi_windows
This perl script gets average coverage across all lines we have for a set of regions in the file pi_windows. See notes on FGS_finder for window file format.
#!/usr/bin/perl
use strict;
die "needs file you dork\n\n" unless $ARGV[0];
my $file=$ARGV[0];
open FILE, "<$file" or die "Cannot open file $file dorkwad\n\n";
#open bam directory and get file names
my $dir="/group/jrigrp/bigd_bam/";
opendir(my $dh, $dir) or die "Cannot open directory $dir dumbface\n\n";
#we only want bam files not bai files
my @files = grep { /bam$/ && -f "$dir/$_" } readdir($dh);
#add directory onto front for calDepth
foreach (@files){ $_=$dir.$_; }
while(<FILE>){
#get data from line
chomp;
next unless $_=~m/^\d+/; # skip header
$_=~m/(\d+)\s+(\d+)\s+(\d+)/;
my $chr=$1; my $win_start=$2; my $win_end=$3;
$chr="chr".$chr;
#loop through files
#is it more efficient to open files one at a time and loop through windows?
my $avg=0;
my $counter=0;
my $winsize=($win_end-$win_start);
foreach my $bam (@files){
$counter++;
#get depth, use awk to get sum
my $depth=`calDepth $bam $chr:$win_start-$win_end | awk '{sum+=\$3} END { print sum }'`;
chomp $depth;
#calculate average across region
#calDepth returns nothing if no reads, turn nothing into 0 for average
$depth = $depth > 0 ? $depth : 0;
$avg+=$depth/$winsize;
}
#calculate average across lines
$avg=$avg/$counter;
print "$chr\t$win_start\t$win_end\t$avg\n";
}
close FILE;