-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsam2bed.pl
executable file
·392 lines (322 loc) · 8.16 KB
/
sam2bed.pl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
#!/usr/bin/env perl
use strict;
use warnings;
use Data::Dumper;
use Carp;
use File::Basename;
use Getopt::Long;
my $prog = basename ($0);
my $separateBed = 0;
my $printUniqOnly = 0;
my $printPrimaryOnly = 0;
my $verbose = 0;
my $reverseStrand = 0;
my $useRNAStrand = 0; # use the strand of the RNA instead of the read
GetOptions (
"p|primary"=>\$printPrimaryOnly,
"u|uniq"=>\$printUniqOnly,
"r|use-RNA-strand"=>\$useRNAStrand,
"reverse-strand:i"=>\$reverseStrand,
# "s|separate-bed"=>\$separateBed,
"v|verbose"=>\$verbose);
if (@ARGV != 2 && @ARGV != 3)
{
print STDERR "Convert OLego SAM format to BED format (for both paired-end and single-end data)\n";
print STDERR "Usage: $prog [options] <in.sam> <out1.bed> [out2.bed]\n";
print STDERR " <in.sam> : compressed input file with .gz/.bz2 extension is allowed\n";
print STDERR " <out1.bed> [out2.bed]: specify both out1.bed and out2.bed to output results of PE data to separate BED files.\n";
print STDERR " You can also use - to specify STDIN for input or STDOUT for output\n\n";
print STDERR "options:\n";
print STDERR "-p,--primary : print primary alignment only\n";
print STDERR "-u,--uniq : print uniquely mapped reads only\n";
print STDERR "--reverse-strand [int] : reverse strand (1=read1, 2=read2, 0=no reverse(default))\n";
print STDERR "-r,--use-RNA-strand : force to use the strand of the RNA based on the XS tag (for junction reads)\n";
print STDERR "-v,--verbose : verbose\n";
exit (1);
}
my ($inSAMFile, $outBedFile) = @ARGV;
my $outBedFile2 = "";
if (@ARGV == 3)
{
$outBedFile2 = $ARGV[2];
die "Please specify different names for the seperate bed files.\n" if ($outBedFile eq $outBedFile2);
$separateBed = 1;
}
my ($fin, $fout, $fout2);
if ( $inSAMFile eq "-")
{
$fin = *STDIN;
}
else
{
if ($inSAMFile =~/\.gz$/)
{
open ($fin, "gunzip -c $inSAMFile | ") || Carp::croak "cannot open file $inSAMFile to read\n";
}
elsif ($inSAMFile =~/\.bz2$/)
{
open ($fin, "bunzip2 -c $inSAMFile | ") || Carp::croak "cannot open file $inSAMFile to read\n";
}
else
{
open ($fin, "<$inSAMFile") || Carp::croak "cannot open file $inSAMFile to read\n";
}
}
if ( $outBedFile eq "-")
{
$fout = *STDOUT;
}
else
{
open ($fout, ">$outBedFile") || Carp::croak "cannot open file $outBedFile to write\n";
}
if ($separateBed)
{
if ($outBedFile2 eq "-")
{
$fout2 = *STDOUT;
}
else
{
open ($fout2, ">$outBedFile2") || Carp::croak "cannot open file $outBedFile2 to write\n";
}
}
my $i = 0;
my $found = 0;
while (my $line = <$fin>)
{
chomp $line;
next if $line=~/^\s*$/;
next if $line=~/^\@/;
print STDERR "$i ...\n" if $verbose && $i % 50000 == 0;
$i++;
my $sam = lineToSam ($line);
my $bed = samToBed ($sam, $useRNAStrand);
next unless $bed; #no alignment
my $flagInfo = $bed->{"flagInfo"};
Carp::croak "inconsistency in specifying PE or SE data\n" if ($flagInfo->{'PE'}==0 && $separateBed == 1);
my $read1_or_2 = $flagInfo->{'read_1_or_2'};
my $uniq = 0;
$uniq = 1 if $sam->{"TAGS"}=~/XT:A:U/;
my $primary = $flagInfo->{'primary_alignment'} ? 1 : 0;
my $printRead = 1;
if ($printUniqOnly == 1 && $uniq == 0)
{
$printRead = 0;
}
if ($printPrimaryOnly == 1 && $primary == 0)
{
$printRead = 0;
}
if ($printRead)
{
if ($separateBed && $read1_or_2 == 2)
{
print $fout2 bedToLine ($bed), "\n" unless $flagInfo->{'query_nomap'};
}
else
{
print $fout bedToLine ($bed), "\n" unless $flagInfo->{'query_nomap'};
}
}
}
print STDERR "Done! Totally $i lines processed! \n" if $verbose;
close ($fin) if $inSAMFile ne '-';
close ($fout) if $outBedFile ne '-';
close ($fout2) if $separateBed && $outBedFile2 ne '-';
#subroutines in Align.pm
sub lineToSam
{
my $line = $_[0];
my ($QNAME, $FLAG, $RNAME, $POS, $MAPQ, $CIGAR, $MRNM, $MPOS, $ISIZE, $SEQ, $QUAL, $TAGS) = split (/\s+/, $line, 12);
return {
QNAME => $QNAME,
FLAG=> $FLAG,
RNAME=>$RNAME,
POS=>$POS,
MAPQ=>$MAPQ,
CIGAR=>$CIGAR,
MRNM=>$MRNM,
MPOS=>$MPOS,
ISIZE=>$ISIZE,
SEQ=>$SEQ,
QUAL=>$QUAL,
TAGS=>$TAGS
};
}
#return 0 if no alignment
sub samToBed
{
my ($sam, $useRNAStrand) = @_;
$useRNAStrand = 0 unless $useRNAStrand;
return 0 if $sam->{"CIGAR"} eq '*'; #no alignment
my $flagInfo = decodeSamFlag ($sam->{"FLAG"});
my $strand = $flagInfo->{'query_strand'};
my $TAGS = "";
$TAGS = $sam->{"TAGS"} if $sam->{"TAGS"};
my $read1_or_2 = $flagInfo->{'read_1_or_2'};
#Carp::croak "reverseStrand = $reverseStrand, read1_2=$read1_or_2\n";
if ($reverseStrand > 0 && $read1_or_2 == $reverseStrand)
{
if ($strand eq '+')
{
$strand = '-';
}
elsif ($strand eq '-')
{
$strand = '+';
}
}
if ($useRNAStrand)
{
if ($TAGS=~/XS\:\S*\:([\-\+\.])/)
{
$strand = $1;
$strand = '+' if $strand eq '.';
}
}
my $name = $sam->{"QNAME"};
my $chrom = $sam->{"RNAME"};
my $chromStart = $sam->{"POS"} - 1;
my $score = 0;
if ($TAGS=~/NM\:\S*\:(\d+)/)
{
$score = $1;
}
my $CIGAR = $sam->{"CIGAR"};
my $QNAME = $sam->{"QNAME"};
my $SEQ = $sam->{"SEQ"};
#remove soft cliped nucleotides
if ($CIGAR =~/^\d+S(.*?)$/)
{
$CIGAR = $1;
}
elsif ($CIGAR =~/^\d+H(.*?)$/)
{
$CIGAR = $1;
}
if ($CIGAR =~/^(.*?)\d+S$/)
{
$CIGAR = $1;
}
elsif ($CIGAR =~/^(.*?)\d+H$/)
{
$CIGAR = $1;
}
#deal with the rest
if ($CIGAR=~/[^\d+|M|N|I|D]/g)
{
Carp::croak "unexpected CIGAR string: $CIGAR in $QNAME: $SEQ\n";
}
my (@blockSizes, @blockStarts);
my $currLen = 0;
my $extendBlock = 0;
while ($CIGAR =~/(\d+)([M|N|I|D])/g)
{
my ($size, $type) = ($1, $2);
if ($type eq 'I' || $type eq 'D')
{
#insertion in reads
$extendBlock = 1;
if ($type eq 'D')
{
my $n = @blockSizes;
if ($n < 1)
{
$chromStart += $size;
}
else
{
$blockSizes[$#blockSizes] += $size;
$currLen += $size;
}
}
next;
}
if ($type eq 'M')
{
if ($extendBlock && @blockSizes > 0)
{
#extend the previous block
my $n = @blockSizes;
$blockSizes[$n-1] += $size;
}
else
{
push @blockSizes, $size;
push @blockStarts, $currLen;
}
$extendBlock = 0;
}
$currLen += $size;
}
my $blockCount = @blockSizes;
my $chromEnd = $chromStart + $blockStarts[$blockCount-1] + $blockSizes[$blockCount-1] - 1;
my $bed = {
chrom=>$chrom,
chromStart=>$chromStart,
chromEnd=>$chromEnd,
name=>$name,
score=>$score,
strand=>$strand,
thickStart=>$chromStart,
thickEnd=>$chromEnd,
itemRgb=>0,
blockCount=>$blockCount,
blockSizes=>\@blockSizes,
blockStarts=>\@blockStarts,
flagInfo=>$flagInfo
};
}
sub decodeSamFlag
{
my $flag = $_[0];
$flag = sprintf ("%012b", $flag);
my @flags = split (//, $flag);
my $flagInfo = {
PE=>$flags[11], #1 means paired-end data
PE_map=>$flags[10], #1 means each end is properly aligned according to the aligner
query_nomap=>$flags[9], #1 means this read is unmapped
mate_nomap=>$flags[8], #1 means its mate is unmapped
query_strand=>$flags[7] == 0 ? '+' : '-', #1 means the strand of this read is on the negative strand
mate_strand=>$flags[6] == 0 ? '+' : '-', #1 means its mate is on the negative strand
read_1_or_2=> $flags[5] == 1 ? 1 : 2, #1 means this is read1
primary_alignment=> $flags[3] == 1 ? 0 : 1 # 1 means not a primary alignment
};
return $flagInfo;
}
#subroutine in Bed.pm
sub bedToLine
{
my $region = $_[0];
my @colNames = qw (chrom chromStart chromEnd name score strand thickStart thickEnd itemRgb blockCount blockSizes blockStarts);
my $colNum = 12; #keys %$region;
my %rCopy = %$region;
$rCopy{"chromEnd"} += 1;
if (exists $rCopy{'thickEnd'})
{
$rCopy{'thickEnd'} += 1;
}
if (exists $rCopy{'blockCount'})
{
Carp::croak "no blockSizes\n" unless exists $rCopy {'blockSizes'};
Carp::croak "no blockStarts\n" unless exists $rCopy {'blockStarts'};
$rCopy{'blockSizes'} = join (",", @{$rCopy{'blockSizes'}});
$rCopy{'blockStarts'} = join (",", @{$rCopy{'blockStarts'}});
}
my $ret = join ("\t", $rCopy{"chrom"}, $rCopy{"chromStart"}, $rCopy{"chromEnd"});
for (my $i = 3; $i < $colNum; $i++)
{
my $col = $colNames[$i];
if (exists $rCopy{$col})
{
$ret .= "\t" . $rCopy{$col};
}
else
{
last;
#Carp::croak "col=$col is not defined\n";
}
}
return $ret;
}