forked from brianpenghe/bamsam-scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
makewigglefromSAM.py
335 lines (310 loc) · 12.7 KB
/
makewigglefromSAM.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
##################################
# #
# Last modified 12/20/2011 #
# #
# Georgi Marinov #
# #
##################################
import sys
import string
import pysam
def main(argv):
if len(argv) < 3:
print 'usage: python %s title SAMfilename outputfilename [-stranded + | -] [-nomulti] [-noNH] [-multiReadCorrection] [-RPM] [-notitle] [-bam chrom.sizes] [-singlebasepair] [-chr chrN1(,chrN2....)]' % argv[0]
print ' Note: the script is designed to work with constant length reads; if the read length varies, then the weighted average of the length will be used'
print ' Note: only run it on BAM files with NH filed indicating multiread multiplicity present; the -noNH option does not work on BAM files'
print ' Note: -multiReadCorrection option deprecated and correcting for multireads is the default now'
print ' Note: do not use the -chr subset option together with the RPM option - the script will not consider all reads in this case'
sys.exit(1)
cachePages = 2000000
doSingleBP=False
if '-singlebasepair' in argv:
doSingleBP=True
doTitle=True
if '-notitle' in argv:
doTitle=False
title = argv[1]
SAM = argv[2]
outfilename = argv[3]
doChrSubset=False
if '-chr' in argv:
doChrSubset=True
WantedChrDict={}
for chr in argv[argv.index('-chr')+1].split(','):
WantedChrDict[chr]=''
doBAM=False
if '-bam' in argv:
doBAM=True
chrominfo=argv[argv.index('-bam')+1]
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))
noMulti=False
if '-nomulti' in argv:
noMulti=True
doRPM=False
if '-RPM' in argv:
doRPM=True
multireads=0
noNH=False
if '-noNH' in argv:
noNH=True
CorrectionDict={}
CorrectionDict['paired']={}
CorrectionDict['single']={}
i=0
if doBAM:
samfile = pysam.Samfile(SAM, "rb" )
for (chr,start,end) in chromInfoList:
try:
for alignedread in samfile.fetch(chr, 0, 100):
a='b'
except:
print 'region', chr,start,end, 'not found in bam file, skipping'
continue
print chr,start,end
for alignedread in samfile.fetch(chr, start, end):
i+=1
if i % 1000000 == 0:
print 'examining read multiplicity', str(i/1000000) + 'M alignments processed processed', len(CorrectionDict['paired'].keys()), 'paired multireads', len(CorrectionDict['single'].keys()), 'reads', multireads, 'multiread alignments'
fields=str(alignedread).split('\t')
ID=fields[0]
if alignedread.is_read1:
ID = ID + '/1'
if alignedread.is_read2:
ID = ID + '/2'
if CorrectionDict['single'].has_key(ID):
multireads+=1
pass
else:
CorrectionDict['single'][ID]=0
CorrectionDict['single'][ID]+=1
else:
i=0
linelist = open(SAM)
for line in linelist:
i+=1
if i % 5000000 == 0:
print 'examining read multiplicity', str(i/1000000) + 'M alignments processed', len(CorrectionDict['paired'].keys()), 'paired multireads', len(CorrectionDict['single'].keys()), 'unpaired multireads'
if line.startswith('@'):
continue
fields=line.strip().split('\t')
ID=fields[0]
if fields[4]=='255':
continue
if fields[7]!='0':
if CorrectionDict['paired'].has_key(ID):
pass
else:
CorrectionDict['paired'][ID]=0
CorrectionDict['paired'][ID]+=1
else:
if CorrectionDict['single'].has_key(ID):
pass
else:
CorrectionDict['single'][ID]=0
CorrectionDict['single'][ID]+=1
doStranded=False
if '-stranded' in argv:
doStranded=True
strand=argv[argv.index('-stranded')+1]
print 'will only consider', strand, 'strand reads'
coverageDict={}
cumSumCoverage=0.0
i=0
r=0
if doBAM:
samfile = pysam.Samfile(SAM, "rb" )
for (chr,start,end) in chromInfoList:
if doChrSubset:
if WantedChrDict.has_key(chr):
pass
else:
continue
try:
for alignedread in samfile.fetch(chr, 0, 100):
a='b'
except:
print 'region', chr,start,end, 'not found in bam file, skipping'
continue
print chr,start,end
for alignedread in samfile.fetch(chr, start, end):
i+=1
if i % 5000000 == 0:
print str(i/1000000) + 'M alignments processed'
fields=str(alignedread).split('\t')
if noNH:
if alignedread.is_read1:
ID = ID + '/1'
if alignedread.is_read2:
ID = ID + '/2'
scaleby = float(CorrectionDict['single'][ID])
else:
try:
scaleby = alignedread.opt('NH')
except:
print 'multireads not specified with the NH tag, exiting'
sys.exit(1)
if noMulti and scaleby > 1:
continue
r+=1.0/scaleby
if doStranded:
if 'XS' in fields[8]:
s = fields[8].split("'XS', '")[1].split("')")[0]
if s!=strand:
length=0
for (m,bp) in alignedread.cigar:
if m == 0:
cumSumCoverage+=bp/scaleby
continue
else:
print 'BAM file does not have XS tags for all reads, exiting'
sys.exit(1)
chr=samfile.getrname(alignedread.rname)
if coverageDict.has_key(chr):
pass
else:
coverageDict[chr]={}
start=alignedread.pos
currentPos=start
for (m,bp) in alignedread.cigar:
if m == 0:
cumSumCoverage+=bp/scaleby
for j in range(currentPos,currentPos+bp):
if coverageDict[chr].has_key(j+1):
coverageDict[chr][j+1]+=1/scaleby
else:
coverageDict[chr][j+1]=1/scaleby
elif m == 2:
pass
elif m == 3:
pass
else:
continue
currentPos=currentPos+bp
else:
linelist = open(SAM)
for line in linelist:
if line.startswith('@'):
continue
fields=line.strip().split('\t')
chr=fields[2]
if doChrSubset:
if WantedChrDict.has_key(chr):
pass
else:
continue
start=int(fields[3])
i+=1
if i % 5000000 == 0:
print str(i/1000000) + 'M alignments processed'
if noNH:
ID=fields[0]
if CorrectionDict['single'].has_key(ID):
scaleby = float(CorrectionDict['single'][ID])
elif CorrectionDict['paired'].has_key(ID):
scaleby = CorrectionDict['paired'][ID]/2.0
else:
scaleby = 1.0
else:
if 'NH:i:' not in line:
print 'multireads not specified with the NH tag, exiting'
sys.exit(1)
scaleby = float(line.split('NH:i:')[1].split('\t')[0].strip())
if noMulti and scaleby > 1:
continue
r+=1.0/scaleby
if doStranded:
if 'XS:A:' not in line:
print 'SAM file does not have strand assignment that can be parsed by this script, '
sys.exit(1)
s = line.split('XS:A:')[1].split('\t')[0].strip()
if s != strand:
length=0
alignFields=fields[5].replace('D','N').split('N')
for a in alignFields:
length+=int(a.split('M')[0])
cumSumCoverage+=length/scaleby
continue
if coverageDict.has_key(chr):
pass
else:
coverageDict[chr]={}
alignFields=fields[5].replace('D','N').split('N')
current=start
for AF in alignFields:
ExonMatch=int(AF.split('M')[0])
stop=current+ExonMatch
for j in range(current,stop):
cumSumCoverage+=1.0/scaleby
if coverageDict[chr].has_key(j):
coverageDict[chr][j]+=1.0/scaleby
else:
coverageDict[chr][j]=1.0/scaleby
current=current+ExonMatch
if AF.split('M')[1]!='':
intron=int(AF.split('M')[1])
current=current+intron
readNumber=r
if noNH:
readNumber=i
for ID in CorrectionDict['paired']:
readNumber = readNumber - CorrectionDict['paired'][ID]/2.0 +1
for ID in CorrectionDict['single']:
readNumber = readNumber - CorrectionDict['single'][ID] + 1
print 'read number', r
print 'cumulative coverage', cumSumCoverage
readLength=cumSumCoverage/readNumber
print 'Estimated read length', readLength
if doRPM:
normFactor = readNumber/1000000.0
outfile = open(outfilename, 'w')
if doTitle:
outline='track type=bedGraph name="' + title + '"'
outfile.write(outline+'\n')
chromosomes=coverageDict.keys()
chromosomes.sort()
for chr in chromosomes:
print chr
posKeys=coverageDict[chr].keys()
posKeys.sort()
initial=(posKeys[0],coverageDict[chr][posKeys[0]])
previous=(posKeys[0],coverageDict[chr][posKeys[0]])
written=['']
if doSingleBP:
for i in range(1,max(posKeys)+1):
if coverageDict[chr].has_key(i):
outline = chr + '\t' + str(i) + '\t' + str(i+1) + str(coverageDict[chr][i])
outfile.write(outline+'\n')
else:
outline = chr + '\t' + str(i) + '\t' + str(i+1) + str(0)
outfile.write(outline+'\n')
else:
for i in posKeys[1:len(posKeys)]:
if previous[0]+1 == i and previous[1]==coverageDict[chr][i]:
previous=(i,coverageDict[chr][i])
else:
if written[0]==initial[0]:
print written, initial, previous
if doStranded and strand == '-':
if doRPM:
outline=chr+'\t'+str(initial[0])+'\t'+str(previous[0]+1)+'\t-'+str(initial[1]/normFactor)
else:
outline=chr+'\t'+str(initial[0])+'\t'+str(previous[0]+1)+'\t-'+str(initial[1])
else:
if doRPM:
outline=chr+'\t'+str(initial[0])+'\t'+str(previous[0]+1)+'\t'+str(initial[1]/normFactor)
else:
outline=chr+'\t'+str(initial[0])+'\t'+str(previous[0]+1)+'\t'+str(initial[1])
written=(initial[0],previous[0]+1)
outfile.write(outline+'\n')
initial=(i,coverageDict[chr][i])
previous=(i,coverageDict[chr][i])
outfile.close()
if __name__ == '__main__':
main(sys.argv)