]> git.donarmstrong.com Git - samtools.git/blob - misc/sam2vcf.pl
Print an error for pileups in simple format
[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         "   -t, --column-title <string>      The column title.\n",
29         "   -h, -?, --help                   This help message.\n",
30         "\n";
31 }
32
33
34 sub parse_params
35 {
36     my %opts = ();
37
38     $opts{fh_in}  = *STDIN;
39     $opts{fh_out} = *STDOUT;
40
41     while (my $arg=shift(@ARGV))
42     {
43         if ( $arg eq '-r' || $arg eq '--refseq' ) { $opts{refseq}=shift(@ARGV); next; }
44         if ( $arg eq '-t' || $arg eq '--column-title' ) { $opts{title}=shift(@ARGV); next; }
45         if ( $arg eq '-s' || $arg eq '--snps-only' ) { $opts{snps_only}=1; next; }
46         if ( $arg eq '-?' || $arg eq '-h' || $arg eq '--help' ) { error(); }
47
48         error("Unknown parameter \"$arg\". Run -h for help.\n");
49     }
50     return \%opts;
51 }
52
53 sub iupac_to_gtype
54 {
55     my ($ref,$base) = @_;
56     my %iupac = (
57             'K' => ['G','T'],
58             'M' => ['A','C'],
59             'S' => ['C','G'],
60             'R' => ['A','G'],
61             'W' => ['A','T'],
62             'Y' => ['C','T'],
63             );
64     if ( !exists($iupac{$base}) ) 
65     { 
66         if ( $base ne 'A' && $base ne 'C' && $base ne 'G' && $base ne 'T' ) { error("FIXME: what is this [$base]?\n"); }
67         if ( $ref eq $base ) { return ('.','0/0'); }
68         return ($base,'1/1');
69     }
70     my $gt = $iupac{$base};
71     if ( $$gt[0] eq $ref  ) { return ($$gt[1],'0/1'); }
72     elsif ( $$gt[1] eq $ref ) { return ($$gt[0],'0/1'); }
73     return ("$$gt[0],$$gt[1]",'1/2');
74 }
75
76
77 sub parse_indel
78 {
79     my ($cons) = @_;
80     if ( $cons=~/^-/ ) 
81     { 
82         my $len = length($');
83         return "D$len"; 
84     }
85     elsif ( $cons=~/^\+/ ) { return "I$'"; }
86     elsif ( $cons eq '*' ) { return undef; }
87     error("FIXME: could not parse [$cons]\n");
88 }
89
90
91 # An example of the pileup format:
92 #   1       3000011 C       C       32      0       98      1       ^~,     A
93 #   1       3002155 *       +T/+T   53      119     52      5       +T      *       4       1       0
94 #   1       3003094 *       -TT/-TT 31      164     60      11      -TT     *       5       6       0
95 #   1       3073986 *       */-AAAAAAAAAAAAAA       3       3       45      9       *       -AAAAAAAAAAAAAA 7       2       0
96 #
97 sub do_pileup_to_vcf
98 {
99     my ($opts) = @_;
100
101     my $fh_in  = $$opts{fh_in};
102     my $fh_out = $$opts{fh_out};
103     my ($prev_chr,$prev_pos,$prev_ref);
104     my $refseq;
105     my $ignore_indels = $$opts{snps_only} ? 1 : 0;
106     my $title = exists($$opts{title}) ? $$opts{title} : 'data';
107
108     print $fh_out 
109         qq[##fileformat=VCFv3.3\n],
110         qq[##INFO=DP,1,Integer,"Total Depth"\n],
111         qq[##FORMAT=GT,1,String,"Genotype"\n],
112         qq[##FORMAT=GQ,1,Integer,"Genotype Quality"\n],
113         qq[##FORMAT=DP,1,Integer,"Read Depth"\n],
114         qq[#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT\t$title\n]
115         ;
116
117     while (my $line=<$fh_in>)
118     {
119         chomp($line);
120         my (@items) = split(/\t/,$line);
121         if ( scalar @items<8 ) 
122         { 
123             error("\nToo few columns, does not look like output of 'samtools pileup -c': $line\n"); 
124         }
125         my ($chr,$pos,$ref,$cons,$cons_qual,$snp_qual,$rms_qual,$depth) = @items;
126
127         my ($alt,$gt);
128         if ( $ref eq '*' )
129         {
130             # An indel is involved.
131             if ( $ignore_indels ) { next; }
132
133             if ($chr ne $prev_chr || $pos ne $prev_pos) 
134             {
135                 if ( !$$opts{refseq} ) { error("Cannot do indels without the reference.\n"); }
136                 if ( !$refseq ) { $refseq = Fasta->new(file=>$$opts{refseq}); }
137                 $ref = $refseq->get_base($chr,$pos);
138             }
139             else { $ref = $prev_ref; }
140
141             # One of the alleles can be a reference and it can come in arbitrary order
142             my ($al1,$al2) = split(m{/},$cons);
143             my $alt1 = parse_indel($al1);
144             my $alt2 = parse_indel($al2);
145             if ( !$alt1 && !$alt2 ) { error("FIXME: could not parse indel:\n", $line); }
146             if ( $alt1 && $alt2 && $alt1 eq $alt2 ) { $alt2=''; }
147             if ( !$alt1 ) 
148             { 
149                 $alt=$alt2; 
150                 $gt='0/1'; 
151             }
152             elsif ( !$alt2 ) 
153             { 
154                 $alt=$alt1; 
155                 $gt='0/1'; 
156             }
157             else 
158             { 
159                 $alt="$alt1,$alt2"; 
160                 $gt='1/2'; 
161             }
162         }
163         else
164         {
165             # SNP
166             ($alt,$gt) = iupac_to_gtype($ref,$cons);
167         }
168
169         print $fh_out "$chr\t$pos\t.\t$ref\t$alt\t$snp_qual\t0\tDP=$depth\tGT:GQ:DP\t$gt:$cons_qual:$depth\n";
170
171         $prev_ref = $ref;
172         $prev_pos = $pos;
173         $prev_chr = $chr;
174     }
175 }
176
177
178 #------------- Fasta --------------------
179 #
180 # Uses samtools to get a requested base from a fasta file. For efficiency, preloads
181 #   a chunk to memory. The size of the cached sequence can be controlled by the 'size'
182 #   parameter.
183 #
184 package Fasta;
185
186 use strict;
187 use warnings;
188 use Carp;
189
190 sub Fasta::new
191 {
192     my ($class,@args) = @_;
193     my $self = {@args};
194     bless $self, ref($class) || $class;
195     if ( !$$self{file} ) { $self->throw(qq[Missing the parameter "file"\n]); }
196     $$self{chr}  = undef;
197     $$self{from} = undef;
198     $$self{to}   = undef;
199     if ( !$$self{size} ) { $$self{size}=10_000_000; }
200     bless $self, ref($class) || $class;
201     return $self;
202 }
203
204 sub read_chunk
205 {
206     my ($self,$chr,$pos) = @_;
207     my $to = $pos + $$self{size};
208     my $cmd = "samtools faidx $$self{file} $chr:$pos-$to";
209     my @out = `$cmd`;
210     if ( $? ) { $self->throw("$cmd: $!"); }
211     my $line = shift(@out);
212     if ( !($line=~/^>$chr:(\d+)-(\d+)/) ) { $self->throw("Could not parse: $line"); }
213     $$self{chr}  = $chr;
214     $$self{from} = $1;
215     $$self{to}   = $2;
216     my $chunk = '';
217     while ($line=shift(@out))
218     {
219         chomp($line);
220         $chunk .= $line;
221     }
222     $$self{chunk} = $chunk;
223     return;
224 }
225
226 sub get_base
227 {
228     my ($self,$chr,$pos) = @_;
229     if ( !$$self{chr} || $chr ne $$self{chr} || $pos<$$self{from} || $pos>$$self{to} )
230     {
231         $self->read_chunk($chr,$pos);
232     }
233     my $idx = $pos - $$self{from};
234     return substr($$self{chunk},$idx,1);
235 }
236
237 sub throw
238 {
239     my ($self,@msg) = @_;
240     croak(@msg);
241 }