-
Notifications
You must be signed in to change notification settings - Fork 0
/
DRS_summary.py
489 lines (368 loc) · 15.6 KB
/
DRS_summary.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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
#!/usr/bin/python
'''
--------------------------
ONTdrstools.DRS_summary.py
--------------------------
This script parses an aligned set of ONT DRS data, generating several sets of
summary statistics, making several plots, and generating a wig file for the
pileup of 3' ends of the reads.
.. moduleauthor:: Nick Schurch <[email protected]>
:module_version: 1.0
:created_on: 2017-12-18
Command-line Arguments
======================
**usage\:**
DRS_summary.py
:param: <input bam file>
:option:`-l|--log` *<file>*
[:option:`-p|--prefix` <str>]
[:option:`-v|--verbose`]
[:option:`--version`]
[:option:`--help`]
Required Parameters
-------------------
:para: <input bam file>
The input bam file
:option:`--logfile|-l`
The name (inc. path) of the log file from the wrapper.
Optional Parameter
------------------
:option: `--prefix|-p` <str>
Prefix string for output filenames. Can optionally include a full path.
Defaults to the input filename.
:option:`--help|-h`
Print a basic description of the tool and its options to STDOUT.
:option:`--version`
Show program's version number and exit.
:option:`--verbose|-v`
Turn on verbose logging (recommended).
Output
======
Undefined, as yet :D
'''
ver=1.30
__scriptname__= "DRS_summary"
__version__ = str(ver)
__usage__ = "\n\t%s <input bam file> -l|--logfile [-p|--prefix <str>]\n\t" \
"[--version][-v|--verbose][--help]"
__progdesc__ = '''
This script parses an aligned set of ONT DRS data, generating several sets of
summary statistics, making several plots, and generating a wig file for the
pileup of 3' ends of the reads..
'''
__progepi__ = '''
--------------------------
ONTdrstools.DRS_summary.py
--------------------------
'''
import sys, pysam, numpy
import script_options.standard_parsers as sp
import script_logging.standard_logging as sl
import matplotlib.pyplot as plt
import matplotlib.colors as colors
import matplotlib.lines as mlines
import matplotlib.transforms as mtransforms
from parsing_routines.gff_gtf_tools import annotation
def addScriptOptions(parser, pos_args, kw_args):
""" add script-specific script options """
script_options_group = parser.add_argument_group('Options')
hlpstr = "Prefix string for output filenames. Can optionally include a " \
"full path. Defaults to the input filename."
option_short_name = "p"
option_name = "prefix"
options_default = None
script_options_group.add_argument('-%s' % option_short_name,
'--%s' % option_name,
action = 'store',
dest = option_name,
type = str,
help = hlpstr,
)
kw_args.append((option_name, option_name, options_default))
return(parser, pos_args, kw_args)
def parseBam(filename, region=None, LOG_EVERY_N=10000):
"""parses a bam file gathering statistics
Returns a dictionary of various gathered statistics."""
thisbam = pysam.AlignmentFile(filename, "rb")
refs = thisbam.references
read_lengths={}
read_lens=[]
read_aligned_lengths={}
aligned_len=[]
read_end_pos={}
tprime_skipped=[]
threeprime_skipped={}
fprime_skipped=[]
fiveprime_skipped={}
if region is None:
read_iterator = thisbam.fetch()
else:
read_iterator = thisbam.fetch(str(region[0]), int(region[1]), int(region[2]))
counter=0
nlogs=1
for read in read_iterator:
this_read_len = read.query_length
if this_read_len==0:
this_read_len = read.infer_query_length()
read_lens.append(this_read_len)
try:
read_lengths[read.query_length].append(read.query_name)
except KeyError:
read_lengths[read.query_length]=[read.query_name]
aligned_len.append(read.query_alignment_length)
try:
read_aligned_lengths[read.query_alignment_length].append(read.query_name)
except KeyError:
read_aligned_lengths[read.query_alignment_length]=[read.query_name]
read_ref = refs[read.reference_id]
if read_ref not in read_end_pos.keys():
read_end_pos[read_ref]={}
tp_skipped = 0
fp_skipped = 0
if read.is_reverse:
read_end = read.reference_start
if read.cigar[0][0]==4:
tp_skipped = read.cigar[0][1]
if read.cigar[-1][0]==4:
fp_skipped = read.cigar[-1][1]
else:
read_end = read.reference_end
if read.cigar[-1][0]==4:
tp_skipped = read.cigar[-1][1]
if read.cigar[0][0]==4:
fp_skipped = read.cigar[0][1]
try:
read_end_pos[read_ref][read_end].append(read.query_name)
except KeyError:
read_end_pos[read_ref][read_end]=[read.query_name]
tprime_skipped.append(tp_skipped)
try:
threeprime_skipped[tp_skipped].append(read.query_name)
except KeyError:
threeprime_skipped[tp_skipped]=[read.query_name]
fprime_skipped.append(fp_skipped)
try:
fiveprime_skipped[fp_skipped].append(read.query_name)
except KeyError:
fiveprime_skipped[fp_skipped]=[read.query_name]
counter+=1
if (counter % LOG_EVERY_N)==0:
print "processed %i reads..." % (nlogs*LOG_EVERY_N)
nlogs+=1
print "Finished. Processed %i reads." % counter
return({"read_lengths": numpy.array(read_lens),
"read_lengths_detail": read_lengths,
"aligned_lengths": numpy.array(aligned_len),
"aligned_lengths_detail": read_aligned_lengths,
"3p_ends": read_end_pos,
"3p_end_skips": numpy.array(tprime_skipped),
"3p_end_skips_detail":threeprime_skipped,
"5p_end_skips": numpy.array(fprime_skipped),
"5p_end_skips_details": fiveprime_skipped})
def plotReadLengthHist(stats_data, binwidth=20, alpha=0.5):
""" plot the read length histograms """
fig = plt.figure(figsize=(12,8))
common_params = dict(
bins=numpy.arange(0, max(stats_data["aligned_lengths"])+binwidth, binwidth),
log=True,
alpha=alpha
)
plt.hist(stats_data["read_lengths"],
color="darkblue", label="Read length", **common_params)
plt.hist(stats_data["aligned_lengths"],
color="darkgreen", label="aligned length", **common_params)
plt.legend(loc=1)
plt.xlabel("length (bp)")
plt.ylabel("number of reads")
return(fig)
def plotLengthDensity(stats_data, gridsize=100):
""" plot the read length histograms """
fig = plt.figure(figsize=(16,12))
plt.hexbin(stats_data["aligned_lengths"], stats_data["read_lengths"],
gridsize=gridsize, xscale="log", yscale="log", bins="log",
cmap="Greens")
axes = plt.gca()
mins = [axes.get_xlim()[0], axes.get_ylim()[0]]
maxs = [axes.get_xlim()[1], axes.get_ylim()[1]]
plt.plot([min(mins),min(maxs)],[min(mins),min(maxs)], color="black")
cbar = plt.colorbar(shrink=0.4)
cbar.set_label('# of reads', rotation=270, labelpad=15)
plt.xlabel("aligned length (bp)")
plt.ylabel("read length (bp)")
return(fig)
def plotSkipLengthHist(stats_data, binwidth=20, alpha=1.0):
""" plot the read length histograms """
fig = plt.figure(figsize=(12,8))
common_params = dict(
bins=numpy.arange(0, max(stats_data["3p_end_skips"])+binwidth, binwidth),
log=True,
alpha=alpha
)
plt.subplot(2,1,1)
plt.hist(stats_data["3p_end_skips"],
color="darkblue", label="3' end skipped bases", **common_params)
plt.ylabel("number of reads")
plt.legend(loc=1)
plt.subplot(2,1,2)
plt.hist(stats_data["5p_end_skips"],
color="darkgreen", label="5' end skipped bases", **common_params)
plt.ylabel("number of reads")
plt.xlabel("read length (bp)")
plt.legend(loc=1)
return(fig)
def annotCount(annot_filename, bam_filename, feature="genes", annot_fmt="gff3"):
""" count the number of reads mapping to each feature """
# load annotation
print "loading annotation..."
annot = annotation(annot_filename, filetype=annot_fmt)
annot.set_feature(feature)
afeats = annot.get_selection()
print "counting reads..."
# pointer to the bam file (again)
thisbam = pysam.AlignmentFile(bam_filename, "rb")
def getRevReads(bamfile, chrid, start, stop):
""" Make a generator object that returns only rev strand reads"""
return(read for read in bamfile.fetch(chrid, start, stop) if read.is_reverse)
def getFwdReads(bamfile, chrid, start, stop):
""" Make a generator object that returns only rev strand reads"""
return(read for read in bamfile.fetch(chrid, start, stop) if not read.is_reverse)
counts = numpy.zeros(len(afeats),
dtype=[("name","|S20"),("count","int"),("frac_read_coverage","float")])
i=0
for afeat in afeats:
if afeat.strand=="+":
reads = getFwdReads(thisbam, afeat.chrid, afeat.start, afeat.stop)
elif afeat.strand=="-":
reads = getRevReads(thisbam, afeat.chrid, afeat.start, afeat.stop)
count=0
bases_covered=0
for read in reads:
count+=1
start = afeat.start
stop = afeat.stop
if read.reference_start>start:
start = read.reference_start
if read.reference_end<stop:
stop = read.reference_end
bases_covered = bases_covered+(stop-start)
if count>0:
mean_coverage = float(bases_covered)/(afeat.stop-afeat.start)
frac_coverage = float(mean_coverage)/count
counts["name"][i] = afeat.desc["gene_id"]
counts["count"][i] = count
counts["frac_read_coverage"][i] = frac_coverage
i+=1
if i%500 == 0:
print i
return(counts)
def plotAnnotCountvCov(counts, log=True, bins=50, feature_label="genes"):
"""plots the counts vs the fractional coverage for a dataset
uses output from annotCount.
"""
fig = plt.figure(figsize=(12,8))
ind = numpy.where(counts["count"]>0)[0]
xscale="linear"
if log:
xscale="log"
plt.hexbin(counts["count"][ind], counts["frac_read_coverage"][ind],
gridsize=bins, bins="log", xscale=xscale, marginals=False, cmap='Greens')
cbar = plt.colorbar(shrink=0.4)
cbar.set_label('# of %s' % feature_label, rotation=270, labelpad=15)
plt.ylabel(r"mean fractional read coverage")
plt.xlabel(r"read counts")
return(fig)
def plotAnnotCountScatter(counts1, counts2, c1label="", c2label="",
log=True, xylog=True, bins=50, feature_label="genes"):
"""plots the read counts for two datasets for the same annotation
uses output from annotCount. Make sure the same annotation was used
to generate both sets of counts - that way things will all be in the right order
"""
fig = plt.figure(figsize=(10,8))
xscale="linear"
yscale="linear"
x=counts1["count"]
y=counts2["count"]
if xylog:
ind1 = counts1["count"]>0
ind2 = counts2["count"]>0
ind=ind1*ind2
x=counts1["count"][ind]
y=counts2["count"][ind]
xscale="log"
yscale="log"
plt.hexbin(x, y, gridsize=bins, bins="log", xscale=xscale,
yscale=yscale, marginals=False,cmap='Greens')
axes = plt.gca()
mins = [axes.get_xlim()[0], axes.get_ylim()[0]]
maxs = [axes.get_xlim()[1], axes.get_ylim()[1]]
plt.plot([min(mins),min(maxs)*2],[min(mins),min(maxs)*2], color="black")
cbar = plt.colorbar(shrink=0.4)
cbar.set_label('# of %s' % feature_label, rotation=270, labelpad=15)
plt.ylabel(r"%s read counts" % c1label)
plt.xlabel(r"%s read counts" % c2label)
return(fig)
def plotAnnotCovScatter(counts1, counts2, c1label="", c2label="",
log=True, bins=50, feature_label="genes"):
"""plots the fractional read coverage for two datasets for the same annotation
uses output from annotCount. Make sure the same annotation was used
to generate both sets of counts - that way things will all be in the right order
"""
fig = plt.figure(figsize=(10,8))
plt.hexbin(counts1["frac_read_coverage"], counts2["frac_read_coverage"],
gridsize=bins, bins="log", xscale="linear", marginals=False,
cmap='Greens')
plt.plot([0,1],[0,1], color="black")
cbar = plt.colorbar(shrink=0.4)
cbar.set_label('# of %s' % feature_label, rotation=270, labelpad=15)
plt.ylabel(r"%s mean fractional read coverage" % c1label)
plt.xlabel(r"%s mean fractional read coverage" % c2label)
return(fig)
if __name__ == '__main__':
# parse command line options
# Set standard parser
parser, pos_args, kw_args = sp.standard_parser(__version__,
prog = __scriptname__,
usage = __usage__,
description = __progdesc__,
epilog = __progepi__,
infile = True,
outfile = False,
tmpdir = False)
parser, pos_args, kw_args = addScriptOptions(parser, pos_args, kw_args)
args = parser.parse_args()
# setup standard logging information
script_logger = sl.standard_logger(__version__, sys.argv, args, pos_args,
kw_args, script_name=__scriptname__)
script_logger.info("Parsing alignment data from %s..." % args.infile)
thisbam = pysam.AlignmentFile(args.infile, "rb")
refs = thisbam.references
read_lengths={}
read_lens=[]
read_aligned_lengths={}
aligned_len=[]
read_end_pos={}
for read in thisbam.fetch("1",0,10000):
print read.query_name
read_lens.append(read.query_length)
try:
read_lengths[read.query_length].append(read.query_name)
except KeyError:
read_lengths[read.query_length]=[read.query_name]
aligned_len.append(read.reference_length)
try:
read_aligned_lengths[read.reference_length].append(read.query_name)
except KeyError:
read_aligned_lengths[read.reference_length]=[read.query_name]
read_ref = refs[read.reference_id]
if read_ref not in read_end_pos.keys():
read_end_pos[read_ref]={}
if read.is_reverse:
read_end = read.reference_start
else:
read_end = read.reference_end
try:
read_end_pos[read_ref][read_end].append(read.query_name)
except KeyError:
read_end_pos[read_ref][read_end]=[read.query_name]
print
script_logger.info("Finished. Have a nice day! ;)")