]> git.donarmstrong.com Git - samtools.git/blob - misc/samtools.pl
* samtools-0.1.5-18 (r423)
[samtools.git] / misc / samtools.pl
1 #!/usr/bin/perl -w
2
3 # Author: lh3
4
5 use strict;
6 use warnings;
7 use Getopt::Std;
8
9 my $version = '0.3.2 (r321)';
10 &usage if (@ARGV < 1);
11
12 my $command = shift(@ARGV);
13 my %func = (showALEN=>\&showALEN, pileup2fq=>\&pileup2fq, varFilter=>\&varFilter, unique=>\&unique);
14
15 die("Unknown command \"$command\".\n") if (!defined($func{$command}));
16 &{$func{$command}};
17 exit(0);
18
19 #
20 # showALEN
21 #
22
23 sub showALEN {
24   die(qq/Usage: samtools.pl showALEN <in.sam>\n/) if (@ARGV == 0 && -t STDIN);
25   while (<>) {
26         my @t = split;
27         next if (/^\@/ || @t < 11);
28         my $l = 0;
29         $_ = $t[5];
30         s/(\d+)[SMI]/$l+=$1/eg;
31         print join("\t", @t[0..5]), "\t$l\t", join("\t", @t[6..$#t]), "\n";
32   }
33 }
34
35 #
36 # varFilter
37 #
38
39 sub varFilter {
40   my %opts = (d=>3, D=>100, l=>30, Q=>25, q=>10, G=>25, s=>100, w=>10, W=>10, N=>2, p=>undef);
41   getopts('pd:D:l:Q:w:W:N:G:', \%opts);
42   die(qq/
43 Usage:   samtools.pl varFilter [options] <in.cns-pileup>
44
45 Options: -Q INT    minimum RMS mapping quality for SNPs [$opts{Q}]
46          -q INT    minimum RMS mapping quality for gaps [$opts{q}]
47          -d INT    minimum read depth [$opts{d}]
48          -D INT    maximum read depth [$opts{D}]
49
50          -G INT    min indel score for nearby SNP filtering [$opts{G}]
51          -w INT    SNP within INT bp around a gap to be filtered [$opts{w}]
52
53          -W INT    window size for filtering dense SNPs [$opts{W}]
54          -N INT    max number of SNPs in a window [$opts{N}]
55
56          -l INT    window size for filtering adjacent gaps [$opts{l}]
57
58          -p        print filtered variants
59 \n/) if (@ARGV == 0 && -t STDIN);
60
61   # calculate the window size
62   my ($ol, $ow, $oW) = ($opts{l}, $opts{w}, $opts{W});
63   my $max_dist = $ol > $ow? $ol : $ow;
64   $max_dist = $oW if ($max_dist < $oW);
65   # the core loop
66   my @staging; # (indel_filtering_score, flt_tag)
67   while (<>) {
68         my @t = split;
69         next if ($t[2] eq $t[3] || $t[3] eq '*/*'); # skip non-var sites
70         # clear the out-of-range elements
71         while (@staging) {
72           last if ($staging[0][2] eq $t[0] && $staging[0][3] + $max_dist >= $t[1]);
73           varFilter_aux(shift(@staging), $opts{p}); # calling a function is a bit slower, not much
74         }
75         my ($flt, $score) = (0, -1);
76         # first a simple filter
77         if ($t[7] < $opts{d}) {
78           $flt = 2;
79         } elsif ($t[7] > $opts{D}) {
80           $flt = 3;
81         }
82         # site dependent filters
83         if ($flt == 0) {
84           if ($t[2] eq '*') { # an indel
85                 $flt = 1 if ($t[6] < $opts{q});
86                 # filtering SNPs
87                 if ($t[5] >= $opts{G}) {
88                   for my $x (@staging) {
89                         next if ($x->[0] >= 0 || $x->[3] + $ow < $t[1]);
90                         $x->[1] = 5 if ($x->[1] == 0);
91                   }
92                 }
93                 # calculate the filtering score (different from indel quality)
94                 $score = $t[5];
95                 $score += $opts{s} * $t[10] if ($t[8] ne '*');
96                 $score += $opts{s} * $t[11] if ($t[9] ne '*');
97                 # check the staging list for indel filtering
98                 for my $x (@staging) {
99                   next if ($x->[0] < 0 || $x->[3] + $ol < $t[1]);
100                   if ($x->[0] < $score) {
101                         $x->[1] = 6;
102                   } else {
103                         $flt = 6; last;
104                   }
105                 }
106           } else { # a SNP
107                 $flt = 1 if ($t[6] < $opts{Q});
108                 # check adjacent SNPs
109                 my $k = 1;
110                 for my $x (@staging) {
111                   ++$k if ($x->[0] < 0 && $x->[3] + $oW >= $t[1] && ($x->[1] == 0 || $x->[1] == 4 || $x->[1] == 5));
112                 }
113                 # filtering is necessary
114                 if ($k > $opts{N}) {
115                   $flt = 4;
116                   for my $x (@staging) {
117                          $x->[1] = 4 if ($x->[0] < 0 && $x->[3] + $oW >= $t[1] && $x->[1] == 0);
118                   }
119                 } else { # then check gap filter
120                   for my $x (@staging) {
121                         next if ($x->[0] < 0 || $x->[3] + $ow < $t[1]);
122                         if ($x->[0] >= $opts{G}) {
123                           $flt = 5; last;
124                         }
125                   }
126                 }
127           }
128         }
129         push(@staging, [$score, $flt, @t]);
130   }
131   # output the last few elements in the staging list
132   while (@staging) {
133         varFilter_aux(shift @staging, $opts{p});
134   }
135 }
136
137 sub varFilter_aux {
138   my ($first, $is_print) = @_;
139   if ($first->[1] == 0) {
140         print join("\t", @$first[2 .. @$first-1]), "\n";
141   } elsif ($is_print) {
142         print STDERR join("\t", substr("UQdDWGgX", $first->[1], 1), @$first[2 .. @$first-1]), "\n";
143   }
144 }
145
146 #
147 # pileup2fq
148 #
149
150 sub pileup2fq {
151   my %opts = (d=>3, D=>255, Q=>25, G=>25, l=>10);
152   getopts('d:D:Q:G:l:', \%opts);
153   die(qq/
154 Usage:   samtools.pl pileup2fq [options] <in.cns-pileup>
155
156 Options: -d INT    minimum depth        [$opts{d}]
157          -D INT    maximum depth        [$opts{D}]
158          -Q INT    min RMS mapQ         [$opts{Q}]
159          -G INT    minimum indel score  [$opts{G}]
160          -l INT    indel filter winsize [$opts{l}]\n
161 /) if (@ARGV == 0 && -t STDIN);
162
163   my ($last_chr, $seq, $qual, @gaps, $last_pos);
164   my $_Q = $opts{Q};
165   my $_d = $opts{d};
166   my $_D = $opts{D};
167
168   $last_chr = '';
169   while (<>) {
170         my @t = split;
171         if ($last_chr ne $t[0]) {
172           &p2q_post_process($last_chr, \$seq, \$qual, \@gaps, $opts{l}) if ($last_chr);
173           $last_chr = $t[0];
174           $last_pos = 0;
175           $seq = ''; $qual = '';
176           @gaps = ();
177         }
178         if ($t[1] - $last_pos != 1) {
179           $seq .= 'n' x ($t[1] - $last_pos - 1);
180           $qual .= '!' x ($t[1] - $last_pos - 1);
181         }
182         if ($t[2] eq '*') {
183           push(@gaps, $t[1]) if ($t[5] >= $opts{G});
184         } else {
185           $seq .= ($t[6] >= $_Q && $t[7] >= $_d && $t[7] <= $_D)? uc($t[3]) : lc($t[3]);
186           my $q = $t[4] + 33;
187           $q = 126 if ($q > 126);
188           $qual .= chr($q);
189         }
190         $last_pos = $t[1];
191   }
192   &p2q_post_process($last_chr, \$seq, \$qual, \@gaps, $opts{l});
193 }
194
195 sub p2q_post_process {
196   my ($chr, $seq, $qual, $gaps, $l) = @_;
197   &p2q_filter_gaps($seq, $gaps, $l);
198   print "\@$chr\n"; &p2q_print_str($seq);
199   print "+\n"; &p2q_print_str($qual);
200 }
201
202 sub p2q_filter_gaps {
203   my ($seq, $gaps, $l) = @_;
204   for my $g (@$gaps) {
205         my $x = $g > $l? $g - $l : 0;
206         substr($$seq, $x, $l + $l) = lc(substr($$seq, $x, $l + $l));
207   }
208 }
209
210 sub p2q_print_str {
211   my ($s) = @_;
212   my $l = length($$s);
213   for (my $i = 0; $i < $l; $i += 60) {
214         print substr($$s, $i, 60), "\n";
215   }
216 }
217
218 #
219 # unique
220 #
221
222 sub unique {
223   my %opts = (f=>5.0, q=>5, r=>2, a=>1, b=>3);
224   getopts('f:', \%opts);
225   die("Usage: samtools.pl unique [-f $opts{f}] <in.sam>\n") if (@ARGV == 0 && -t STDIN);
226   my $last = '';
227   my @a;
228   while (<>) {
229         my $score = -1;
230         print $_ if (/^\@/);
231         $score = $1 if (/AS:i:(\d+)/);
232         my @t = split("\t");
233         next if (@t < 11);
234         if ($score < 0) { # AS tag is unavailable
235           my $cigar = $t[5];
236           my ($mm, $go, $ge) = (0, 0, 0);
237           $cigar =~ s/(\d+)[ID]/++$go,$ge+=$1/eg;
238           $cigar = $t[5];
239           $cigar =~ s/(\d+)M/$mm+=$1/eg;
240           $score = $mm * $opts{a} - $go * $opts{q} - $ge * $opts{r}; # no mismatches...
241         }
242         $score = 0 if ($score < 0);
243         if ($t[0] ne $last) {
244           &unique_aux(\@a, $opts{f}) if (@a);
245           $last = $t[0];
246         }
247         push(@a, [$score, \@t]);
248   }
249   &unique_aux(\@a, $opts{f}) if (@a);
250 }
251
252 sub unique_aux {
253   my ($a, $fac) = @_;
254   my ($max, $max2, $max_i) = (-1, -1, -1);
255   for (my $i = 0; $i < @$a; ++$i) {
256         if ($a->[$i][0] > $max) {
257           $max2 = $max; $max = $a->[$i][0]; $max_i = $i;
258         } elsif ($a->[$i][0] > $max2) {
259           $max2 = $a->[$i][0];
260         }
261   }
262   my $q = int($fac * ($max - $max2) + .499);
263   $a->[$max_i][1][4] = $q < 250? $q : 250;
264   print join("\t", @{$a->[$max_i][1]});
265   @$a = ();
266 }
267
268 #
269 # Usage
270 #
271
272 sub usage {
273   die(qq/
274 Program: samtools.pl (helper script for SAMtools)
275 Version: $version
276 Contact: Heng Li <lh3\@sanger.ac.uk>\n
277 Usage:   samtools.pl <command> [<arguments>]\n
278 Command: varFilter     filtering SNPs and short indels
279          pileup2fq     generate fastq from `pileup -c'
280          showALEN      print alignment length (ALEN) following CIGAR
281 \n/);
282 }