Merge commit 'upstream/0.1.17'
[samtools.git] / misc / psl2sam.pl
1 #!/usr/bin/perl -w
2
3 # Author: lh3
4
5 # This script calculates a score using the BLAST scoring
6 # system. However, I am not sure how to count gap opens and gap
7 # extensions. It seems to me that column 5-8 are not what I am
8 # after. This script counts gaps from the last three columns. It does
9 # not generate reference skip (N) in the CIGAR as it is not easy to
10 # directly tell which gaps correspond to introns.
11
12 use strict;
13 use warnings;
14 use Getopt::Std;
15
16 my %opts = (a=>1, b=>3, q=>5, r=>2);
17 getopts('a:b:q:r:', \%opts);
18 die("Usage: psl2sam.pl [-a $opts{a}] [-b $opts{b}] [-q $opts{q}] [-r $opts{r}] <in.psl>\n") if (@ARGV == 0 && -t STDIN);
19
20 my @stack;
21 my $last = '';
22 my ($a, $b, $q, $r) = ($opts{a}, $opts{b}, $opts{q}, $opts{r});
23 while (<>) {
24   next unless (/^\d/);
25   my @t = split;
26   my @s;
27   my $cigar = '';
28   if ($t[8] eq '-') {
29         my $tmp = $t[11];
30         $t[11] = $t[10] - $t[12];
31         $t[12] = $t[10] - $tmp;
32   }
33   @s[0..4] = ($t[9], (($t[8] eq '+')? 0 : 16), $t[13], $t[15]+1, 0);
34   @s[6..10] = ('*', 0, 0, '*', '*');
35   $cigar .= $t[11].'H' if ($t[11]); # 5'-end clipping
36   my @x = split(',', $t[18]);
37   my @y = split(',', $t[19]);
38   my @z = split(',', $t[20]);
39   my ($y0, $z0) = ($y[0], $z[0]);
40   my ($gap_open, $gap_ext) = (0, 0, 0);
41   for (1 .. $t[17]-1) {
42         my $ly = $y[$_] - $y[$_-1] - $x[$_-1];
43         my $lz = $z[$_] - $z[$_-1] - $x[$_-1];
44         if ($ly < $lz) { # del: the reference gap is longer
45           ++$gap_open;
46           $gap_ext += $lz - $ly;
47           $cigar .= ($y[$_] - $y0) . 'M';
48           $cigar .= ($lz - $ly) . 'D';
49           ($y0, $z0) = ($y[$_], $z[$_]);
50         } elsif ($lz < $ly) { # ins: the query gap is longer
51           ++$gap_open;
52           $gap_ext += $ly - $lz;
53           $cigar .= ($z[$_] - $z0) . 'M';
54           $cigar .= ($ly - $lz) . 'I';
55           ($y0, $z0) = ($y[$_], $z[$_]);
56         }
57   }
58   $cigar .= ($t[12] - $y0) . 'M';
59   $cigar .= ($t[10] - $t[12]).'H' if ($t[10] != $t[12]); # 3'-end clipping
60   $s[5] = $cigar;
61   my $score = $a * $t[0] - $b * $t[1] - $q * $gap_open - $r * $gap_ext;
62   $score = 0 if ($score < 0);
63   $s[11] = "AS:i:$score";
64   print join("\t", @s), "\n";
65 }