]> git.donarmstrong.com Git - samtools.git/blob - misc/sam2vcf.pl
Small fix in VCF format: dot for the empty INFO field
[samtools.git] / misc / sam2vcf.pl
1 #!/usr/bin/perl -w
2
3 # VCF specs: http://www.1000genomes.org/wiki/doku.php?id=1000_genomes:analysis:vcf3.3
4
5 # Contact: pd3@sanger
6 # Version: 2009-12-08
7
8 use strict;
9 use warnings;
10 use Carp;
11
12 my $opts = parse_params();
13 do_pileup_to_vcf($opts);
14
15 exit;
16
17 #---------------
18
19 sub error
20 {
21     my (@msg) = @_;
22     if ( scalar @msg ) { croak(@msg); }
23     die
24         "Usage: sam2vcf.pl [OPTIONS] < in.pileup > out.vcf\n",
25         "Options:\n",
26         "   -r, --refseq <file.fa>           The reference sequence, required when indels are present.\n",
27         "   -s, --snps-only                  Ignore indels.\n",
28         "   -h, -?, --help                   This help message.\n",
29         "\n";
30 }
31
32
33 sub parse_params
34 {
35     my %opts = ();
36
37     $opts{fh_in}  = *STDIN;
38     $opts{fh_out} = *STDOUT;
39
40     while (my $arg=shift(@ARGV))
41     {
42         if ( $arg eq '-r' || $arg eq '--refseq' ) { $opts{refseq}=shift(@ARGV); next; }
43         if ( $arg eq '-s' || $arg eq '--snps-only' ) { $opts{snps_only}=1; next; }
44         if ( $arg eq '-?' || $arg eq '-h' || $arg eq '--help' ) { error(); }
45
46         error("Unknown parameter \"$arg\". Run -h for help.\n");
47     }
48     return \%opts;
49 }
50
51 sub iupac_to_gtype
52 {
53     my ($ref,$base) = @_;
54     my %iupac = (
55             'K' => ['G','T'],
56             'M' => ['A','C'],
57             'S' => ['C','G'],
58             'R' => ['A','G'],
59             'W' => ['A','T'],
60             'Y' => ['C','T'],
61             );
62     if ( !exists($iupac{$base}) ) 
63     { 
64         if ( $ref eq $base ) { return ('.','0|0'); }
65         return ($base,'1|1');
66     }
67     my $gt = $iupac{$base};
68     if ( $$gt[0] eq $ref  ) { return ($$gt[1],'0|1'); }
69     elsif ( $$gt[1] eq $ref ) { return ($$gt[0],'0|1'); }
70     return ("$$gt[0],$$gt[1]",'1|2');
71 }
72
73
74 sub parse_indel
75 {
76     my ($cons) = @_;
77     if ( $cons=~/^-/ ) 
78     { 
79         my $len = length($');
80         return "D$len"; 
81     }
82     elsif ( $cons=~/^\+/ ) { return "I$'"; }
83     elsif ( $cons eq '*' ) { return undef; }
84     error("FIXME: could not parse [$cons]\n");
85 }
86
87
88 # An example of the pileup format:
89 #   1       3000011 C       C       32      0       98      1       ^~,     A
90 #   1       3002155 *       +T/+T   53      119     52      5       +T      *       4       1       0
91 #   1       3003094 *       -TT/-TT 31      164     60      11      -TT     *       5       6       0
92 #   1       3073986 *       */-AAAAAAAAAAAAAA       3       3       45      9       *       -AAAAAAAAAAAAAA 7       2       0
93 #
94 sub do_pileup_to_vcf
95 {
96     my ($opts) = @_;
97
98     my $fh_in  = $$opts{fh_in};
99     my $fh_out = $$opts{fh_out};
100     my ($prev_chr,$prev_pos,$prev_ref);
101     my $refseq;
102     my $ignore_indels = $$opts{snps_only} ? 1 : 0;
103
104     while (my $line=<$fh_in>)
105     {
106         chomp($line);
107         my ($chr,$pos,$ref,$cons,$cons_qual,$snp_qual,$rms_qual,$depth,@items) = split(/\t/,$line);
108
109         my ($alt,$gt);
110         if ( $ref eq '*' )
111         {
112             # An indel is involved.
113             if ( $ignore_indels ) { next; }
114
115             if ($chr ne $prev_chr || $pos ne $prev_pos) 
116             {
117                 if ( !$$opts{refseq} ) { error("Cannot do indels without the reference.\n"); }
118                 if ( !$refseq ) { $refseq = Fasta->new(file=>$$opts{refseq}); }
119                 $ref = $refseq->get_base($chr,$pos);
120             }
121             else { $ref = $prev_ref; }
122
123             # One of the alleles can be a reference and it can come in arbitrary order
124             my ($al1,$al2) = split(m{/},$cons);
125             my $alt1 = parse_indel($al1);
126             my $alt2 = parse_indel($al2);
127             if ( !$alt1 && !$alt2 ) { error("FIXME: could not parse indel:\n", $line); }
128             if ( $alt1 && $alt2 && $alt1 eq $alt2 ) { $alt2=''; }
129             if ( !$alt1 ) 
130             { 
131                 $alt=$alt2; 
132                 $gt='0|1'; 
133             }
134             elsif ( !$alt2 ) 
135             { 
136                 $alt=$alt1; 
137                 $gt='0|1'; 
138             }
139             else 
140             { 
141                 $alt="$alt1,$alt2"; 
142                 $gt='1|2'; 
143             }
144         }
145         else
146         {
147             # SNP
148             ($alt,$gt) = iupac_to_gtype($ref,$cons);
149         }
150
151         print $fh_out "$chr\t$pos\t.\t$ref\t$alt\t$snp_qual\t0\t.\tGT:GQ:DP\t$gt:$cons_qual:$depth\n";
152
153         $prev_ref = $ref;
154         $prev_pos = $pos;
155         $prev_chr = $chr;
156     }
157 }
158
159
160 #------------- Fasta --------------------
161 #
162 # Uses samtools to get a requested base from a fasta file. For efficiency, preloads
163 #   a chunk to memory. The size of the cached sequence can be controlled by the 'size'
164 #   parameter.
165 #
166 package Fasta;
167
168 use strict;
169 use warnings;
170 use Carp;
171
172 sub Fasta::new
173 {
174     my ($class,@args) = @_;
175     my $self = {@args};
176     bless $self, ref($class) || $class;
177     if ( !$$self{file} ) { $self->throw(qq[Missing the parameter "file"\n]); }
178     $$self{chr}  = undef;
179     $$self{from} = undef;
180     $$self{to}   = undef;
181     if ( !$$self{size} ) { $$self{size}=10_000_000; }
182     bless $self, ref($class) || $class;
183     return $self;
184 }
185
186 sub read_chunk
187 {
188     my ($self,$chr,$pos) = @_;
189     my $to = $pos + $$self{size};
190     my $cmd = "samtools faidx $$self{file} $chr:$pos-$to";
191     my @out = `$cmd`;
192     if ( $? ) { $self->throw("$cmd: $!"); }
193     my $line = shift(@out);
194     if ( !($line=~/^>$chr:(\d+)-(\d+)/) ) { $self->throw("Could not parse: $line"); }
195     $$self{chr}  = $chr;
196     $$self{from} = $1;
197     $$self{to}   = $2;
198     my $chunk = '';
199     while ($line=shift(@out))
200     {
201         chomp($line);
202         $chunk .= $line;
203     }
204     $$self{chunk} = $chunk;
205     return;
206 }
207
208 sub get_base
209 {
210     my ($self,$chr,$pos) = @_;
211     if ( !$$self{chr} || $chr ne $$self{chr} || $pos<$$self{from} || $pos>$$self{to} )
212     {
213         $self->read_chunk($chr,$pos);
214     }
215     my $idx = $pos - $$self{from};
216     return substr($$self{chunk},$idx,1);
217 }
218
219 sub throw
220 {
221     my ($self,@msg) = @_;
222     croak(@msg);
223 }