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