-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathBAMtoFASTQ.py
369 lines (349 loc) · 13.4 KB
/
BAMtoFASTQ.py
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
##################################
# #
# Last modified 12/12/2014 #
# #
# Georgi Marinov #
# #
##################################
import sys
import pysam
import string
from sets import Set
import os
def getReverseComplement(preliminarysequence):
DNA = {'A':'T','T':'A','G':'C','C':'G','N':'N','a':'t','t':'a','g':'c','c':'g','n':'n'}
sequence=''
for i in range(len(preliminarysequence)):
sequence=sequence+DNA[preliminarysequence[len(preliminarysequence)-i-1]]
return sequence
def main(argv):
if len(argv) < 3:
print 'usage: python %s BAM chrom.sizes outfilename [-ignoreChromSizes] [-OneEndOnly 1 2] [-alignedOnly] [-chr chrN1[,....,chrNN]] [-withinRegions regions_file chrFieldID leftFieldID rightFieldID] [-noNH samtools]' % argv[0]
print '\tNote: the script assumes no duplicate readIDs'
print '\t-withinRegions option does not work together with the -ignoreChromSizes option'
print '\tuse the -ignoreChromSizes option to also get the unaligned reads'
print '\tthe -chr option will output all alignments on the set of chromosomes indicate and will override the -withinRegions option'
print '\tuse the -noNH option and supply a path to samtools in order to have the file converted to one that has NH tags'
print '\tuse - for outfilename if you want to print to standard output'
sys.exit(1)
BAM = argv[1]
outputfilename = argv[3]
chrominfo=argv[2]
chromInfoList=[]
linelist=open(chrominfo)
for line in linelist:
fields=line.strip().split('\t')
chr=fields[0]
start=0
end=int(fields[1])
chromInfoList.append((chr,start,end))
doStdOut = False
if outputfilename == '-':
doStdOut = True
doEnd = False
if '-OneEndOnly' in argv:
doEnd = True
End = int(argv[argv.index('-OneEndOnly')+1])
doChr=False
if '-chr' in argv:
doChr=True
WantedChrDict={}
for chr in argv[argv.index('-chr')+1].split(','):
WantedChrDict[chr]=''
if not doStdOut:
print 'will output all reads aligning to the following chromosomes:'
print WantedChrDict.keys()
doIgnoreChromSizes=False
if '-ignoreChromSizes' in argv:
doIgnoreChromSizes=True
if not doStdOut:
print 'will ignore chrom.sizes file'
doAlignedOnly=False
if '-alignedOnly' in argv:
doAlignedOnly=True
if not doStdOut:
print 'will only output aligned reads'
if not doStdOut:
print 'will write reads into: ', outputfilename
ReadDict={}
samfile = pysam.Samfile(BAM, "rb" )
try:
for read in samfile.fetch():
multiplicity = read.opt('NH')
if not doStdOut:
print 'file has NH tags'
break
except:
if '-noNH' in argv:
print 'no NH: tags in BAM file, will replace with a new BAM file with NH tags'
samtools = argv[argv.index('-noNH')+1]
BAMpreporcessingScript = argv[0].rpartition('/')[0] + '/bamPreprocessing.py'
cmd = 'python ' + BAMpreporcessingScript + ' ' + BAM + ' ' + BAM + '.NH'
os.system(cmd)
cmd = 'rm ' + BAM
os.system(cmd)
cmd = 'mv ' + BAM + '.NH' + ' ' + BAM
os.system(cmd)
cmd = samtools + ' index ' + BAM
os.system(cmd)
else:
print 'no NH: tags in BAM file, exiting'
sys.exit(1)
if not doStdOut:
outfile = open(outputfilename, "w")
i=0
samfile = pysam.Samfile(BAM, "rb" )
if doIgnoreChromSizes:
for read in samfile.fetch(until_eof=True):
i+=1
if i % 5000000 == 0:
if not doStdOut:
print 'examining read multiplicity and inputting reads', str(i/1000000) + 'M alignments processed processed'
fields=str(read).split('\t')
if doAlignedOnly:
try:
chr = samfile.getrname(read.tid)
except:
print fields
sys.exit(1)
ID = read.qname
if read.is_read1:
ID = ID + '/1'
if doEnd and End == 2:
continue
if read.is_read2:
ID = ID + '/2'
if doEnd and End == 1:
continue
sequence = read.seq
quality = read.qual
if read.is_reverse:
sequence = getReverseComplement(sequence)
quality=quality[::-1]
if read.is_unmapped:
if not doStdOut:
outfile.write('@' + ID + '\n')
outfile.write(sequence + '\n')
outfile.write('+\n')
outfile.write(quality + '\n')
else:
print '@' + ID
print sequence
print '+'
print quality
continue
if read.opt('NH') == 1:
if not doStdOut:
outfile.write('@' + ID + '\n')
outfile.write(sequence + '\n')
outfile.write('+\n')
outfile.write(quality + '\n')
else:
print '@' + ID
print sequence
print '+'
print quality
continue
if ReadDict.has_key(ID):
if ReadDict[ID] != (sequence,quality):
sequence = getReverseComplement(sequence)
quality=quality[::-1]
if ReadDict[ID] != (sequence,quality):
print ID, sequence, quality
print ReadDict[ID]
print 'duplicate read ID detected, exiting'
sys.exit(1)
else:
pass
else:
ReadDict[ID] = (sequence,quality)
elif doChr:
for (chr,start,end) in chromInfoList:
if WantedChrDict.has_key(chr):
pass
else:
continue
try:
for read in samfile.fetch(chr, 0, 100):
a='b'
except:
continue
for read in samfile.fetch(chr, start, end):
i+=1
if i % 5000000 == 0:
if not doStdOut:
print str(i/1000000) + 'M alignments processed processed', chr,start,read.pos,end
fields=str(read).split('\t')
ID = read.qname
if read.is_read1:
ID = ID + '/1'
if doEnd and End == 2:
continue
if read.is_read2:
ID = ID + '/2'
if doEnd and End == 2:
continue
sequence = read.seq
quality = read.qual
if read.is_reverse:
sequence = getReverseComplement(sequence)
quality=quality[::-1]
if read.opt('NH') == 1:
if not doStdOut:
outfile.write('@' + ID + '\n')
outfile.write(sequence + '\n')
outfile.write('+\n')
outfile.write(quality + '\n')
else:
print '@' + ID
print sequence
print '+'
print quality
continue
if ReadDict.has_key(ID):
if ReadDict[ID] != (sequence,quality):
print ID, sequence, qualtiy
print ReadDict[ID]
print 'duplicate read ID detected, exiting'
sys.exit(1)
else:
pass
else:
ReadDict[ID] = (sequence,quality)
elif '-withinRegions' in argv:
regionDict={}
if not doStdOut:
print 'will only output reads with alignments within regions defined in', argv[argv.index('-withinRegions')+1]
linelist = open(argv[argv.index('-withinRegions')+1])
chrFieldID = int(argv[argv.index('-withinRegions')+2])
leftFieldID = int(argv[argv.index('-withinRegions')+3])
rightFieldID = int(argv[argv.index('-withinRegions')+4])
for line in linelist:
if line.startswith('#'):
continue
fields = line.strip().split('\t')
chr = fields[chrFieldID]
if regionDict.has_key(chr):
pass
else:
regionDict[chr]={}
left = int(fields[leftFieldID])
right = int(fields[rightFieldID])
test = 0
try:
for read in samfile.fetch(chr, left, right):
test+=1
if test == 1:
break
except:
continue
for read in samfile.fetch(chr, left, right):
i+=1
if i % 5000000 == 0:
if not doStdOut:
print 'examining read multiplicity and inputting reads', str(i/1000000) + 'M alignments processed processed', chr,start,read.pos,end
fields=str(read).split('\t')
ID = read.qname
if read.is_read1:
ID = ID + '/1'
if doEnd and End == 2:
continue
if read.is_read2:
ID = ID + '/2'
if doEnd and End == 2:
continue
sequence = read.seq
quality = read.qual
if read.is_reverse:
sequence = getReverseComplement(sequence)
quality=quality[::-1]
if read.opt('NH') == 1:
if not doStdOut:
outfile.write('@' + ID + '\n')
outfile.write(sequence + '\n')
outfile.write('+\n')
outfile.write(quality + '\n')
else:
print '@' + ID
print sequence
print '+'
print quality
continue
if ReadDict.has_key(ID):
if ReadDict[ID] != (sequence,quality):
print ID, sequence, qualtiy
print ReadDict[ID]
print 'duplicate read ID detected, exiting'
sys.exit(1)
else:
pass
else:
ReadDict[ID] = (sequence,quality)
else:
for (chr,start,end) in chromInfoList:
try:
for read in samfile.fetch(chr, 0, 100):
a='b'
except:
continue
for read in samfile.fetch(chr, start, end):
i+=1
if i % 5000000 == 0:
if not doStdOut:
print 'examining read multiplicity and inputting reads', str(i/1000000) + 'M alignments processed processed', chr,start,read.pos,end
fields=str(read).split('\t')
ID = read.qname
if read.is_read1:
ID = ID + '/1'
if doEnd and End == 2:
continue
if read.is_read2:
ID = ID + '/2'
if doEnd and End == 2:
continue
sequence = read.seq
quality = read.qual
if read.is_reverse:
sequence = getReverseComplement(sequence)
quality=quality[::-1]
if read.opt('NH') == 1:
if not doStdOut:
outfile.write('@' + ID + '\n')
outfile.write(sequence + '\n')
outfile.write('+\n')
outfile.write(quality + '\n')
else:
print '@' + ID
print sequence
print '+'
print quality
continue
if ReadDict.has_key(ID):
if ReadDict[ID] != (sequence,quality):
print ID, sequence, qualtiy
print ReadDict[ID]
print 'duplicate read ID detected, exiting'
sys.exit(1)
else:
pass
else:
ReadDict[ID] = (sequence,quality)
if not doStdOut:
print i
if not doStdOut:
for readID in ReadDict.keys():
(sequence,quality) = ReadDict[readID]
outfile.write('@' + readID + '\n')
outfile.write(sequence + '\n')
outfile.write('+\n')
outfile.write(quality + '\n')
outfile.close()
else:
for readID in ReadDict.keys():
(sequence,quality) = ReadDict[readID]
print '@' + readID
print sequence
print '+'
print quality
if __name__ == '__main__':
main(sys.argv)