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