Merge commit 'upstream/0.1.7.dfsg'
[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.3';
10 &usage if (@ARGV < 1);
11
12 my $command = shift(@ARGV);
13 my %func = (showALEN=>\&showALEN, pileup2fq=>\&pileup2fq, varFilter=>\&varFilter,
14                         unique=>\&unique, uniqcmp=>\&uniqcmp, sra2hdr=>\&sra2hdr);
15
16 die("Unknown command \"$command\".\n") if (!defined($func{$command}));
17 &{$func{$command}};
18 exit(0);
19
20 #
21 # showALEN
22 #
23
24 sub showALEN {
25   die(qq/Usage: samtools.pl showALEN <in.sam>\n/) if (@ARGV == 0 && -t STDIN);
26   while (<>) {
27         my @t = split;
28         next if (/^\@/ || @t < 11);
29         my $l = 0;
30         $_ = $t[5];
31         s/(\d+)[MI]/$l+=$1/eg;
32         print join("\t", @t[0..5]), "\t$l\t", join("\t", @t[6..$#t]), "\n";
33   }
34 }
35
36 #
37 # varFilter
38 #
39
40 #
41 # Filtration code:
42 #
43 # d low depth
44 # D high depth
45 # W too many SNPs in a window (SNP only)
46 # G close to a high-quality indel (SNP only)
47 # Q low RMS mapping quality (SNP only)
48 # g close to another indel with higher quality (indel only)
49
50 sub varFilter {
51   my %opts = (d=>3, D=>100, l=>30, Q=>25, q=>10, G=>25, s=>100, w=>10, W=>10, N=>2, p=>undef);
52   getopts('pq:d:D:l:Q:w:W:N:G:', \%opts);
53   die(qq/
54 Usage:   samtools.pl varFilter [options] <in.cns-pileup>
55
56 Options: -Q INT    minimum RMS mapping quality for SNPs [$opts{Q}]
57          -q INT    minimum RMS mapping quality for gaps [$opts{q}]
58          -d INT    minimum read depth [$opts{d}]
59          -D INT    maximum read depth [$opts{D}]
60
61          -G INT    min indel score for nearby SNP filtering [$opts{G}]
62          -w INT    SNP within INT bp around a gap to be filtered [$opts{w}]
63
64          -W INT    window size for filtering dense SNPs [$opts{W}]
65          -N INT    max number of SNPs in a window [$opts{N}]
66
67          -l INT    window size for filtering adjacent gaps [$opts{l}]
68
69          -p        print filtered variants
70 \n/) if (@ARGV == 0 && -t STDIN);
71
72   # calculate the window size
73   my ($ol, $ow, $oW) = ($opts{l}, $opts{w}, $opts{W});
74   my $max_dist = $ol > $ow? $ol : $ow;
75   $max_dist = $oW if ($max_dist < $oW);
76   # the core loop
77   my @staging; # (indel_filtering_score, flt_tag)
78   while (<>) {
79         my @t = split;
80         next if (uc($t[2]) eq uc($t[3]) || $t[3] eq '*/*'); # skip non-var sites
81         # clear the out-of-range elements
82         while (@staging) {
83           last if ($staging[0][2] eq $t[0] && $staging[0][3] + $max_dist >= $t[1]);
84           varFilter_aux(shift(@staging), $opts{p}); # calling a function is a bit slower, not much
85         }
86         my ($flt, $score) = (0, -1);
87         # first a simple filter
88         if ($t[7] < $opts{d}) {
89           $flt = 2;
90         } elsif ($t[7] > $opts{D}) {
91           $flt = 3;
92         }
93         # site dependent filters
94         if ($flt == 0) {
95           if ($t[2] eq '*') { # an indel
96                 $flt = 1 if ($t[6] < $opts{q});
97                 # filtering SNPs
98                 if ($t[5] >= $opts{G}) {
99                   for my $x (@staging) {
100                         next if ($x->[0] >= 0 || $x->[3] + $ow < $t[1]);
101                         $x->[1] = 5 if ($x->[1] == 0);
102                   }
103                 }
104                 # calculate the filtering score (different from indel quality)
105                 $score = $t[5];
106                 $score += $opts{s} * $t[10] if ($t[8] ne '*');
107                 $score += $opts{s} * $t[11] if ($t[9] ne '*');
108                 # check the staging list for indel filtering
109                 for my $x (@staging) {
110                   next if ($x->[0] < 0 || $x->[3] + $ol < $t[1]);
111                   if ($x->[0] < $score) {
112                         $x->[1] = 6;
113                   } else {
114                         $flt = 6; last;
115                   }
116                 }
117           } else { # a SNP
118                 $flt = 1 if ($t[6] < $opts{Q});
119                 # check adjacent SNPs
120                 my $k = 1;
121                 for my $x (@staging) {
122                   ++$k if ($x->[0] < 0 && $x->[3] + $oW >= $t[1] && ($x->[1] == 0 || $x->[1] == 4 || $x->[1] == 5));
123                 }
124                 # filtering is necessary
125                 if ($k > $opts{N}) {
126                   $flt = 4;
127                   for my $x (@staging) {
128                          $x->[1] = 4 if ($x->[0] < 0 && $x->[3] + $oW >= $t[1] && $x->[1] == 0);
129                   }
130                 } else { # then check gap filter
131                   for my $x (@staging) {
132                         next if ($x->[0] < 0 || $x->[3] + $ow < $t[1]);
133                         if ($x->[0] >= $opts{G}) {
134                           $flt = 5; last;
135                         }
136                   }
137                 }
138           }
139         }
140         push(@staging, [$score, $flt, @t]);
141   }
142   # output the last few elements in the staging list
143   while (@staging) {
144         varFilter_aux(shift @staging, $opts{p});
145   }
146 }
147
148 sub varFilter_aux {
149   my ($first, $is_print) = @_;
150   if ($first->[1] == 0) {
151         print join("\t", @$first[2 .. @$first-1]), "\n";
152   } elsif ($is_print) {
153         print STDERR join("\t", substr("UQdDWGgX", $first->[1], 1), @$first[2 .. @$first-1]), "\n";
154   }
155 }
156
157 #
158 # pileup2fq
159 #
160
161 sub pileup2fq {
162   my %opts = (d=>3, D=>255, Q=>25, G=>25, l=>10);
163   getopts('d:D:Q:G:l:', \%opts);
164   die(qq/
165 Usage:   samtools.pl pileup2fq [options] <in.cns-pileup>
166
167 Options: -d INT    minimum depth        [$opts{d}]
168          -D INT    maximum depth        [$opts{D}]
169          -Q INT    min RMS mapQ         [$opts{Q}]
170          -G INT    minimum indel score  [$opts{G}]
171          -l INT    indel filter winsize [$opts{l}]\n
172 /) if (@ARGV == 0 && -t STDIN);
173
174   my ($last_chr, $seq, $qual, @gaps, $last_pos);
175   my $_Q = $opts{Q};
176   my $_d = $opts{d};
177   my $_D = $opts{D};
178
179   $last_chr = '';
180   while (<>) {
181         my @t = split;
182         if ($last_chr ne $t[0]) {
183           &p2q_post_process($last_chr, \$seq, \$qual, \@gaps, $opts{l}) if ($last_chr);
184           $last_chr = $t[0];
185           $last_pos = 0;
186           $seq = ''; $qual = '';
187           @gaps = ();
188         }
189         if ($t[1] - $last_pos != 1) {
190           $seq .= 'n' x ($t[1] - $last_pos - 1);
191           $qual .= '!' x ($t[1] - $last_pos - 1);
192         }
193         if ($t[2] eq '*') {
194           push(@gaps, $t[1]) if ($t[5] >= $opts{G});
195         } else {
196           $seq .= ($t[6] >= $_Q && $t[7] >= $_d && $t[7] <= $_D)? uc($t[3]) : lc($t[3]);
197           my $q = $t[4] + 33;
198           $q = 126 if ($q > 126);
199           $qual .= chr($q);
200         }
201         $last_pos = $t[1];
202   }
203   &p2q_post_process($last_chr, \$seq, \$qual, \@gaps, $opts{l});
204 }
205
206 sub p2q_post_process {
207   my ($chr, $seq, $qual, $gaps, $l) = @_;
208   &p2q_filter_gaps($seq, $gaps, $l);
209   print "\@$chr\n"; &p2q_print_str($seq);
210   print "+\n"; &p2q_print_str($qual);
211 }
212
213 sub p2q_filter_gaps {
214   my ($seq, $gaps, $l) = @_;
215   for my $g (@$gaps) {
216         my $x = $g > $l? $g - $l : 0;
217         substr($$seq, $x, $l + $l) = lc(substr($$seq, $x, $l + $l));
218   }
219 }
220
221 sub p2q_print_str {
222   my ($s) = @_;
223   my $l = length($$s);
224   for (my $i = 0; $i < $l; $i += 60) {
225         print substr($$s, $i, 60), "\n";
226   }
227 }
228
229 #
230 # sra2hdr
231 #
232
233 # This subroutine does not use an XML parser. It requires that the SRA
234 # XML files are properly formated.
235 sub sra2hdr {
236   my %opts = ();
237   getopts('', \%opts);
238   die("Usage: samtools.pl sra2hdr <SRA.prefix>\n") if (@ARGV == 0);
239   my $pre = $ARGV[0];
240   my $fh;
241   # read sample
242   my $sample = 'UNKNOWN';
243   open($fh, "$pre.sample.xml") || die;
244   while (<$fh>) {
245         $sample = $1 if (/<SAMPLE.*alias="([^"]+)"/i);
246   }
247   close($fh);
248   # read experiment
249   my (%exp2lib, $exp);
250   open($fh, "$pre.experiment.xml") || die;
251   while (<$fh>) {
252         if (/<EXPERIMENT.*accession="([^\s"]+)"/i) {
253           $exp = $1;
254         } elsif (/<LIBRARY_NAME>\s*(\S+)\s*<\/LIBRARY_NAME>/i) {
255           $exp2lib{$exp} = $1;
256         }
257   }
258   close($fh);
259   # read run
260   my ($run, @fn);
261   open($fh, "$pre.run.xml") || die;
262   while (<$fh>) {
263         if (/<RUN.*accession="([^\s"]+)"/i) {
264           $run = $1; @fn = ();
265         } elsif (/<EXPERIMENT_REF.*accession="([^\s"]+)"/i) {
266           print "\@RG\tID:$run\tSM:$sample\tLB:$exp2lib{$1}\n";
267         } elsif (/<FILE.*filename="([^\s"]+)"/i) {
268           push(@fn, $1);
269         } elsif (/<\/RUN>/i) {
270           if (@fn == 1) {
271                 print STDERR "$fn[0]\t$run\n";
272           } else {
273                 for (0 .. $#fn) {
274                   print STDERR "$fn[$_]\t$run", "_", $_+1, "\n";
275                 }
276           }
277         }
278   }
279   close($fh);
280 }
281
282 #
283 # unique
284 #
285
286 sub unique {
287   my %opts = (f=>250.0, q=>5, r=>2, a=>1, b=>3);
288   getopts('Qf:q:r:a:b:', \%opts);
289   die("Usage: samtools.pl unique [-f $opts{f}] <in.sam>\n") if (@ARGV == 0 && -t STDIN);
290   my $last = '';
291   my $recal_Q = !defined($opts{Q});
292   my @a;
293   while (<>) {
294         my $score = -1;
295         print $_ if (/^\@/);
296         $score = $1 if (/AS:i:(\d+)/);
297         my @t = split("\t");
298         next if (@t < 11);
299         if ($score < 0) { # AS tag is unavailable
300           my $cigar = $t[5];
301           my ($mm, $go, $ge) = (0, 0, 0);
302           $cigar =~ s/(\d+)[ID]/++$go,$ge+=$1/eg;
303           $cigar = $t[5];
304           $cigar =~ s/(\d+)M/$mm+=$1/eg;
305           $score = $mm * $opts{a} - $go * $opts{q} - $ge * $opts{r}; # no mismatches...
306         }
307         $score = 1 if ($score < 1);
308         if ($t[0] ne $last) {
309           &unique_aux(\@a, $opts{f}, $recal_Q) if (@a);
310           $last = $t[0];
311         }
312         push(@a, [$score, \@t]);
313   }
314   &unique_aux(\@a, $opts{f}, $recal_Q) if (@a);
315 }
316
317 sub unique_aux {
318   my ($a, $fac, $is_recal) = @_;
319   my ($max, $max2, $max_i) = (0, 0, -1);
320   for (my $i = 0; $i < @$a; ++$i) {
321         if ($a->[$i][0] > $max) {
322           $max2 = $max; $max = $a->[$i][0]; $max_i = $i;
323         } elsif ($a->[$i][0] > $max2) {
324           $max2 = $a->[$i][0];
325         }
326   }
327   if ($is_recal) {
328         my $q = int($fac * ($max - $max2) / $max + .499);
329         $q = 250 if ($q > 250);
330         $a->[$max_i][1][4] = $q < 250? $q : 250;
331   }
332   print join("\t", @{$a->[$max_i][1]});
333   @$a = ();
334 }
335
336 #
337 # uniqcmp: compare two SAM files
338 #
339
340 sub uniqcmp {
341   my %opts = (q=>10, s=>100);
342   getopts('pq:s:', \%opts);
343   die("Usage: samtools.pl uniqcmp <in1.sam> <in2.sam>\n") if (@ARGV < 2);
344   my ($fh, %a);
345   warn("[uniqcmp] read the first file...\n");
346   &uniqcmp_aux($ARGV[0], \%a, 0);
347   warn("[uniqcmp] read the second file...\n");
348   &uniqcmp_aux($ARGV[1], \%a, 1);
349   warn("[uniqcmp] stats...\n");
350   my @cnt;
351   $cnt[$_] = 0 for (0..9);
352   for my $x (keys %a) {
353         my $p = $a{$x};
354         my $z;
355         if (defined($p->[0]) && defined($p->[1])) {
356           $z = ($p->[0][0] == $p->[1][0] && $p->[0][1] eq $p->[1][1] && abs($p->[0][2] - $p->[1][2]) < $opts{s})? 0 : 1;
357           if ($p->[0][3] >= $opts{q} && $p->[1][3] >= $opts{q}) {
358                 ++$cnt[$z*3+0];
359           } elsif ($p->[0][3] >= $opts{q}) {
360                 ++$cnt[$z*3+1];
361           } elsif ($p->[1][3] >= $opts{q}) {
362                 ++$cnt[$z*3+2];
363           }
364           print STDERR "$x\t$p->[0][1]:$p->[0][2]\t$p->[0][3]\t$p->[0][4]\t$p->[1][1]:$p->[1][2]\t$p->[1][3]\t$p->[1][4]\t",
365                 $p->[0][5]-$p->[1][5], "\n" if ($z && defined($opts{p}) && ($p->[0][3] >= $opts{q} || $p->[1][3] >= $opts{q}));
366         } elsif (defined($p->[0])) {
367           ++$cnt[$p->[0][3]>=$opts{q}? 6 : 7];
368           print STDERR "$x\t$p->[0][1]:$p->[0][2]\t$p->[0][3]\t$p->[0][4]\t*\t0\t*\t",
369                 $p->[0][5], "\n" if (defined($opts{p}) && $p->[0][3] >= $opts{q});
370         } else {
371           print STDERR "$x\t*\t0\t*\t$p->[1][1]:$p->[1][2]\t$p->[1][3]\t$p->[1][4]\t",
372                 -$p->[1][5], "\n" if (defined($opts{p}) && $p->[1][3] >= $opts{q});
373           ++$cnt[$p->[1][3]>=$opts{q}? 8 : 9];
374         }
375   }
376   print "Consistent (high, high):   $cnt[0]\n";
377   print "Consistent (high, low ):   $cnt[1]\n";
378   print "Consistent (low , high):   $cnt[2]\n";
379   print "Inconsistent (high, high): $cnt[3]\n";
380   print "Inconsistent (high, low ): $cnt[4]\n";
381   print "Inconsistent (low , high): $cnt[5]\n";
382   print "Second missing (high):     $cnt[6]\n";
383   print "Second missing (low ):     $cnt[7]\n";
384   print "First  missing (high):     $cnt[8]\n";
385   print "First  missing (low ):     $cnt[9]\n";
386 }
387
388 sub uniqcmp_aux {
389   my ($fn, $a, $which) = @_;
390   my $fh;
391   $fn = "samtools view $fn |" if ($fn =~ /\.bam/);
392   open($fh, $fn) || die;
393   while (<$fh>) {
394         my @t = split;
395         next if (@t < 11);
396 #       my $l = ($t[5] =~ /^(\d+)S/)? $1 : 0;
397         my $l = 0;
398         my ($x, $nm) = (0, 0);
399         $nm = $1 if (/NM:i:(\d+)/);
400         $_ = $t[5];
401         s/(\d+)[MI]/$x+=$1/eg;
402         @{$a->{$t[0]}[$which]} = (($t[1]&0x10)? 1 : 0, $t[2], $t[3]-$l, $t[4], "$x:$nm", $x - 4 * $nm);
403   }
404   close($fh);
405 }
406
407 #
408 # Usage
409 #
410
411 sub usage {
412   die(qq/
413 Program: samtools.pl (helper script for SAMtools)
414 Version: $version
415 Contact: Heng Li <lh3\@sanger.ac.uk>\n
416 Usage:   samtools.pl <command> [<arguments>]\n
417 Command: varFilter     filtering SNPs and short indels
418          pileup2fq     generate fastq from `pileup -c'
419          showALEN      print alignment length (ALEN) following CIGAR
420 \n/);
421 }