forked from kundajelab/ataqc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrun_ataqc.py
executable file
·1655 lines (1362 loc) · 56 KB
/
run_ataqc.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
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python2
# Daniel Kim, CS Foo
# 2016-03-28
# Script to run ataqc, all parts
import matplotlib
matplotlib.use('Agg')
import os
import sys
import pysam
import pybedtools
import metaseq
import subprocess
import multiprocessing
import timeit
import datetime
import gzip
import numpy as np
import pandas as pd
import scipy.stats
import argparse
import logging
import re
import signal
from base64 import b64encode
from collections import namedtuple
from collections import OrderedDict
from io import BytesIO
from scipy.signal import find_peaks_cwt
from jinja2 import Template
from matplotlib import pyplot as plt
from matplotlib import mlab
# utils
def run_shell_cmd(cmd):
"""Taken from ENCODE DCC ATAC pipeline
"""
print(cmd)
try:
p = subprocess.Popen(cmd, shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
universal_newlines=True,
preexec_fn=os.setsid)
pid = p.pid
pgid = os.getpgid(pid)
ret = ''
while True:
line = p.stdout.readline()
if line=='' and p.poll() is not None:
break
# log.debug('PID={}: {}'.format(pid,line.strip('\n')))
#print('PID={}: {}'.format(pid,line.strip('\n')))
ret += line
p.communicate() # wait here
if p.returncode > 0:
raise subprocess.CalledProcessError(
p.returncode, cmd)
return ret.strip('\n')
except:
# kill all child processes
os.killpg(pgid, signal.SIGKILL)
p.terminate()
raise Exception('Unknown exception caught. PID={}'.format(pid))
def get_num_lines(f):
"""Taken from ENCODE DCC ATAC pipeline
"""
cmd = 'zcat -f {} | wc -l'.format(f)
return int(run_shell_cmd(cmd))
# QC STUFF
QCResult = namedtuple('QCResult', ['metric', 'qc_pass', 'message'])
INF = float("inf")
class QCCheck(object):
def __init__(self, metric):
self.metric = metric
def check(self, value):
return True
def message(self, value, qc_pass):
return ('{} - OK'.format(value) if qc_pass
else '{} - Failed'.format(value))
def __call__(self, value):
qc_pass = self.check(value)
return QCResult(self.metric, qc_pass, self.message(value, qc_pass))
class QCIntervalCheck(QCCheck):
def __init__(self, metric, lower, upper):
super(QCIntervalCheck, self).__init__(metric)
self.lower = lower
self.upper = upper
def check(self, value):
return self.lower <= value <= self.upper
def message(self, value, qc_pass):
return ('{} - OK'.format(value) if qc_pass else
'{} out of range [{}, {}]'.format(value, self.lower,
self.upper))
class QCLessThanEqualCheck(QCIntervalCheck):
def __init__(self, metric, upper):
super(QCLessThanEqualCheck, self).__init__(metric, -INF, upper)
class QCGreaterThanEqualCheck(QCIntervalCheck):
def __init__(self, metric, lower):
super(QCGreaterThanEqualCheck, self).__init__(metric, lower, INF)
class QCHasElementInRange(QCCheck):
def __init__(self, metric, lower, upper):
super(QCHasElementInRange, self).__init__(metric)
self.lower = lower
self.upper = upper
def check(self, elems):
return (len([elem for elem in elems
if self.lower <= elem <= self.upper]) > 0)
def message(self, elems, qc_pass):
return ('OK' if qc_pass else
'Cannot find element in range [{}, {}]'.format(
self.lower, self.upper))
# HELPER FUNCTIONS
def getFileHandle(filename, mode="r"):
if (re.search('.gz$',filename) or re.search('.gzip',filename)):
if (mode=="r"):
mode="rb";
return gzip.open(filename,mode)
else:
return open(filename,mode)
# QC FUNCTIONS
def determine_paired(bam_file):
'''
Quick function to determine if the BAM file is paired end or single end
'''
num_paired_reads = int(subprocess.check_output(['samtools',
'view', '-f', '0x1',
'-c', bam_file]).strip())
if num_paired_reads > 1:
return "Paired-ended"
else:
return "Single-ended"
def get_read_length(fastq_file):
'''
Get read length out of fastq file
'''
total_reads_to_consider = 1000000
line_num = 0
total_reads_considered = 0
max_length = 0
with getFileHandle(fastq_file, 'rb') as fp:
for line in fp:
if line_num % 4 == 1:
if len(line.strip()) > max_length:
max_length = len(line.strip())
total_reads_considered += 1
if total_reads_considered >= total_reads_to_consider:
break
line_num += 1
return int(max_length)
def get_bowtie_stats(bowtie_alignment_log):
'''
From the Bowtie alignment log, get relevant stats and return
the file in a list format where each line is an element in
the list. Can be parsed further if desired.
'''
logging.info('Reading bowtie alignment log...')
bowtie_text = ''
with open(bowtie_alignment_log, 'rb') as fp:
for line in fp:
logging.info(line.strip())
bowtie_text += line
return bowtie_text
def get_chr_m(sorted_bam_file):
'''
Get fraction of reads that are mitochondrial (chr M).
'''
logging.info('Getting mitochondrial chromosome fraction...')
chrom_list = pysam.idxstats(sorted_bam_file, split_lines=True)
tot_reads = 0
for chrom in chrom_list:
chrom_stats = chrom.split('\t')
if chrom_stats[0] == 'chrM':
chr_m_reads = int(chrom_stats[2])
tot_reads += int(chrom_stats[2])
fract_chr_m = float(chr_m_reads) / tot_reads
return chr_m_reads, fract_chr_m
def get_gc(qsorted_bam_file, reference_fasta, prefix):
'''
Uses picard tools (CollectGcBiasMetrics). Note that the reference
MUST be the same fasta file that generated the bowtie indices.
Assumes picard was already loaded into space (module add picard-tools)
'''
logging.info('Getting GC bias...')
output_file = '{0}_gc.txt'.format(prefix)
plot_file = '{0}_gcPlot.pdf'.format(prefix)
summary_file = '{0}_gcSummary.txt'.format(prefix)
get_gc_metrics = ('java -Xmx4G -jar '
'{5}/picard.jar '
'CollectGcBiasMetrics R={0} I={1} O={2} '
'VERBOSITY=ERROR QUIET=TRUE '
'ASSUME_SORTED=FALSE '
'CHART={3} S={4}').format(reference_fasta,
qsorted_bam_file,
output_file,
plot_file,
summary_file,
os.environ['PICARDROOT'])
logging.info(get_gc_metrics)
os.system(get_gc_metrics)
return output_file, plot_file, summary_file
def plot_gc(data_file):
'''
Replot the Picard output as png file to put into the html
'''
# Load data
data = pd.read_table(data_file, comment="#")
# Plot the data
fig = plt.figure()
ax = fig.add_subplot(111)
plt.xlim((0, 100))
lin1 = ax.plot(data['GC'], data['NORMALIZED_COVERAGE'],
label='Normalized coverage', color='r')
ax.set_ylabel('Normalized coverage')
ax2 = ax.twinx()
lin2 = ax2.plot(data['GC'], data['MEAN_BASE_QUALITY'],
label='Mean base quality at GC%', color='b')
ax2.set_ylabel('Mean base quality at GC%')
ax3 = ax.twinx()
lin3 = ax3.plot(data['GC'], data['WINDOWS']/np.sum(data['WINDOWS']),
label='Windows at GC%', color='g')
ax3.get_yaxis().set_visible(False)
lns = lin1 + lin2 + lin3
labs = [l.get_label() for l in lns]
ax.legend(lns, labs, loc='best')
plot_img = BytesIO()
fig.savefig(plot_img, format='png')
return b64encode(plot_img.getvalue())
def run_preseq(bam_w_dups, prefix):
'''
Runs preseq. Look at preseq data output to get PBC/NRF.
'''
# First sort because this file no longer exists...
sort_bam = 'samtools sort -o {1}.sorted.bam -T {1} -@ 2 {0}'.format(
bam_w_dups, prefix)
os.system(sort_bam)
logging.info('Running preseq...')
preseq_data = '{0}.preseq.dat'.format(prefix)
preseq_log = '{0}.preseq.log'.format(prefix)
preseq = ('preseq lc_extrap '
'-P -B -o {0} {1}.sorted.bam -seed 1 -v 2> {2}').format(preseq_data,
prefix,
preseq_log)
logging.info(preseq)
os.system(preseq)
os.system('rm {0}.sorted.bam'.format(prefix))
return preseq_data, preseq_log
def get_encode_complexity_measures(pbc_output):
'''
Gets the unique count statistics from the filtered bam file,
which is consistent with ENCODE metrics for ChIP-seq
'''
with open(pbc_output, 'rb') as fp:
for line in fp:
l_list = line.strip().split('\t')
NRF = float(l_list[4])
PBC1 = float(l_list[5])
PBC2 = float(l_list[6])
break
# QC check
results = []
results.append(QCGreaterThanEqualCheck('NRF', 0.8)(NRF))
results.append(QCGreaterThanEqualCheck('PBC1', 0.8)(PBC1))
results.append(QCGreaterThanEqualCheck('PBC2', 1.0)(PBC2))
return results
def get_encode_complexity_measures_OLD(preseq_log):
'''
Use info from the preseq log to calculate NRF, PBC1, and PBC2
'''
with open(preseq_log, 'rb') as fp:
for line in fp:
if line.startswith('TOTAL READS'):
tot_reads = float(line.strip().split("= ")[1])
elif line.startswith('DISTINCT READS'):
distinct_reads = float(line.strip().split('= ')[1])
elif line.startswith('1\t'):
one_pair = float(line.strip().split()[1])
elif line.startswith('2\t'):
two_pair = float(line.strip().split()[1])
NRF = distinct_reads/tot_reads
PBC1 = one_pair/distinct_reads
PBC2 = one_pair/two_pair
# QC check
results = []
results.append(QCGreaterThanEqualCheck('NRF', 0.8)(NRF))
results.append(QCGreaterThanEqualCheck('PBC1', 0.8)(PBC1))
results.append(QCGreaterThanEqualCheck('PBC2', 1.0)(PBC2))
return results
def get_picard_complexity_metrics(aligned_bam, prefix):
'''
Picard EsimateLibraryComplexity
'''
out_file = '{0}.picardcomplexity.qc'.format(prefix)
get_gc_metrics = ('java -Xmx4G -jar '
'{2}/picard.jar '
'EstimateLibraryComplexity INPUT={0} OUTPUT={1} '
'VERBOSITY=ERROR '
'QUIET=TRUE').format(aligned_bam,
out_file,
os.environ['PICARDROOT'])
os.system(get_gc_metrics)
# Extract the actual estimated library size
header_seen = False
est_library_size = 0
with open(out_file, 'rb') as fp:
for line in fp:
if header_seen:
est_library_size = int(float(line.strip().split()[-1]))
break
if 'ESTIMATED_LIBRARY_SIZE' in line:
header_seen = True
return est_library_size
def preseq_plot(data_file):
'''
Generate a preseq plot
'''
try:
data = np.loadtxt(data_file, skiprows=1)
except IOError:
return ''
data /= 1e6 # scale to millions of reads
fig = plt.figure()
# Plot the average expected yield
plt.plot(data[:, 0], data[:, 1], 'r-')
# Plot confidence intervals
ci_lower, = plt.plot(data[:, 0], data[:, 2], 'b--')
ci_upper, = plt.plot(data[:, 0], data[:, 3], 'b--')
plt.legend([ci_lower], ['95% confidence interval'], loc=4)
plt.title('Preseq estimated yield')
plt.xlabel('Sequenced fragments [ millions ]')
plt.ylabel('Expected distinct fragments [ millions ]')
plot_img = BytesIO()
fig.savefig(plot_img, format='png')
return b64encode(plot_img.getvalue())
def make_tss_plot(bam_file, tss, prefix, chromsizes, read_len, bins=400, bp_edge=2000,
processes=8, greenleaf_norm=True):
'''
Take bootstraps, generate tss plots, and get a mean and
standard deviation on the plot. Produces 2 plots. One is the
aggregation plot alone, while the other also shows the signal
at each TSS ordered by strength.
'''
logging.info('Generating tss plot...')
tss_plot_file = '{0}_tss-enrich.png'.format(prefix)
tss_plot_large_file = '{0}_large_tss-enrich.png'.format(prefix)
# Load the TSS file
tss = pybedtools.BedTool(tss)
tss_ext = tss.slop(b=bp_edge, g=chromsizes)
# Load the bam file
bam = metaseq.genomic_signal(bam_file, 'bam') # Need to shift reads and just get ends, just load bed file?
bam_array = bam.array(tss_ext, bins=bins, shift_width = -read_len/2, # Shift to center the read on the cut site
processes=processes, stranded=True)
# Actually first build an "ends" file
#get_ends = '''zcat {0} | awk -F '\t' 'BEGIN {{OFS="\t"}} {{if ($6 == "-") {{$2=$3-1; print}} else {{$3=$2+1; print}} }}' | gzip -c > {1}_ends.bed.gz'''.format(bed_file, prefix)
#print(get_ends)
#os.system(get_ends)
#bed_reads = metaseq.genomic_signal('{0}_ends.bed.gz'.format(prefix), 'bed')
#bam_array = bed_reads.array(tss_ext, bins=bins,
# processes=processes, stranded=True)
# Normalization (Greenleaf style): Find the avg height
# at the end bins and take fold change over that
if greenleaf_norm:
# Use enough bins to cover 100 bp on either end
num_edge_bins = int(100/(2*bp_edge/bins))
bin_means = bam_array.mean(axis=0)
avg_noise = (sum(bin_means[:num_edge_bins]) +
sum(bin_means[-num_edge_bins:]))/(2*num_edge_bins)
bam_array /= avg_noise
else:
bam_array /= bam.mapped_read_count() / 1e6
# Generate a line plot
fig = plt.figure()
ax = fig.add_subplot(111)
x = np.linspace(-bp_edge, bp_edge, bins)
ax.plot(x, bam_array.mean(axis=0), color='r', label='Mean')
ax.axvline(0, linestyle=':', color='k')
# Note the middle high point (TSS)
tss_point_val = max(bam_array.mean(axis=0))
ax.set_xlabel('Distance from TSS (bp)')
ax.set_ylabel('Average read coverage (per million mapped reads)')
ax.legend(loc='best')
fig.savefig(tss_plot_file)
# Print a more complicated plot with lots of info
# Find a safe upper percentile - we can't use X if the Xth percentile is 0
upper_prct = 99
if mlab.prctile(bam_array.ravel(), upper_prct) == 0.0:
upper_prct = 100.0
plt.rcParams['font.size'] = 8
fig = metaseq.plotutils.imshow(bam_array,
x=x,
figsize=(5, 10),
vmin=5, vmax=upper_prct, percentile=True,
line_kwargs=dict(color='k', label='All'),
fill_kwargs=dict(color='k', alpha=0.3),
sort_by=bam_array.mean(axis=1))
# And save the file
fig.savefig(tss_plot_large_file)
return tss_plot_file, tss_plot_large_file, tss_point_val
def get_picard_dup_stats(picard_dup_file, paired_status):
'''
Parse Picard's MarkDuplicates metrics file
'''
logging.info('Running Picard MarkDuplicates...')
mark = 0
dup_stats = {}
with open(picard_dup_file) as fp:
for line in fp:
if '##' in line:
if 'METRICS CLASS' in line:
mark = 1
continue
if mark == 2:
line_elems = line.strip().split('\t')
dup_stats['PERCENT_DUPLICATION'] = line_elems[7]
dup_stats['READ_PAIR_DUPLICATES'] = line_elems[5]
dup_stats['READ_PAIRS_EXAMINED'] = line_elems[2]
if paired_status == 'Paired-ended':
return float(line_elems[5]), float(line_elems[7])
else:
return float(line_elems[4]), float(line_elems[7])
if mark > 0:
mark += 1
return None
def get_sambamba_dup_stats(sambamba_dup_file, paired_status):
'''
Parse sambamba markdup's metrics file
'''
logging.info('Running sambamba markdup...')
with open(sambamba_dup_file, 'r') as fp:
lines = fp.readlines()
end_pairs = int(lines[1].strip().split()[1])
single_ends = int(lines[2].strip().split()[1])
ends_marked_dup = int(lines[4].strip().split()[1])
if paired_status == 'Paired-ended':
pairs_marked_dup = 0.5 * float(ends_marked_dup)
prct_dup = pairs_marked_dup / float(end_pairs)
return pairs_marked_dup, prct_dup
else:
prct_dup = float(ends_marked_dup) / float(single_ends)
return ends_marked_dup, prct_dup
def get_mito_dups(sorted_bam, prefix, endedness='Paired-ended', use_sambamba=False):
'''
Marks duplicates in the original aligned bam file and then determines
how many reads are duplicates AND from chrM
To use sambamba markdup instead of picard MarkDuplicates, set
use_sambamba to True (default False).
'''
out_file = '{0}.dupmark.ataqc.bam'.format(prefix)
metrics_file = '{0}.dup.ataqc'.format(prefix)
# Filter bam on the flag 0x002
tmp_filtered_bam = '{0}.filt.bam'.format(prefix)
tmp_filtered_bam_prefix = tmp_filtered_bam.replace('.bam', '')
if endedness == 'Paired-ended':
filter_bam = ('samtools view -F 1804 -f 2 -u {0} | '
'samtools sort - {1}'.format(sorted_bam, tmp_filtered_bam_prefix))
else:
filter_bam = ('samtools view -F 1804 -u {0} | '
'samtools sort - {1}'.format(sorted_bam, tmp_filtered_bam_prefix))
os.system(filter_bam)
# Run Picard MarkDuplicates
mark_duplicates = ('java -Xmx4G -jar '
'{0}/picard.jar '
'MarkDuplicates INPUT={1} OUTPUT={2} '
'METRICS_FILE={3} '
'VALIDATION_STRINGENCY=LENIENT '
'ASSUME_SORTED=TRUE '
'REMOVE_DUPLICATES=FALSE '
'VERBOSITY=ERROR '
'QUIET=TRUE').format(os.environ['PICARDROOT'],
tmp_filtered_bam,
out_file,
metrics_file)
if use_sambamba:
mark_duplicates = ('sambamba markdup -t 8 '
'--hash-table-size=17592186044416 '
'--overflow-list-size=20000000 '
'--io-buffer-size=256 '
'{0} '
'{1} '
'2> {2}').format(tmp_filtered_bam,
out_file,
metrics_file)
os.system(mark_duplicates)
# Index the file
index_file = 'samtools index {0}'.format(out_file)
os.system(index_file)
# Get the mitochondrial reads that are marked duplicates
mito_dups = int(subprocess.check_output(['samtools',
'view', '-f', '1024',
'-c', out_file, 'chrM']).strip())
total_dups = int(subprocess.check_output(['samtools',
'view', '-f', '1024',
'-c', out_file]).strip())
# Clean up
remove_bam = 'rm {0}'.format(out_file)
os.system(remove_bam)
remove_metrics_file = 'rm {0}'.format(metrics_file)
os.system(remove_metrics_file)
remove_tmp_filtered_bam = 'rm {0}'.format(tmp_filtered_bam)
os.system(remove_tmp_filtered_bam)
return mito_dups, float(mito_dups) / total_dups
def get_samtools_flagstat(bam_file):
'''
Runs samtools flagstat to get read metrics
'''
logging.info('samtools flagstat...')
results = pysam.flagstat(bam_file, split_lines=True)
flagstat = ''
for line in results:
logging.info(line.strip())
flagstat += line
if "mapped" in line and "mate" not in line:
mapped_reads = int(line.split('+')[0].strip())
return flagstat, mapped_reads
def get_fract_mapq(bam_file, q=30):
'''
Runs samtools view to get the fraction of reads of a certain
map quality.
'''
# Current bug in pysam.view module...
logging.info('samtools mapq 30...')
# There is a bug in pysam.view('-c'), so just use subprocess
num_qreads = int(subprocess.check_output(['samtools',
'view', '-c',
'-q', str(q), bam_file]).strip())
tot_reads = int(subprocess.check_output(['samtools',
'view', '-c',
bam_file]).strip())
fract_good_mapq = float(num_qreads)/tot_reads
return num_qreads, fract_good_mapq
def get_final_read_count(first_bam, last_bam):
'''
Get final mapped reads compared to initial reads
'''
logging.info('final read counts...')
# Bug in pysam.view
num_reads_last_bam = int(subprocess.check_output(['samtools',
'view', '-c',
last_bam]).strip())
num_reads_first_bam = int(subprocess.check_output(['samtools',
'view', '-c',
first_bam]).strip())
fract_reads_left = float(num_reads_last_bam)/num_reads_first_bam
return num_reads_first_bam, num_reads_last_bam, fract_reads_left
def get_insert_distribution(final_bam, prefix):
'''
Calls Picard CollectInsertSizeMetrics
'''
logging.info('insert size distribution...')
insert_data = '{0}.inserts.hist_data.log'.format(prefix)
insert_plot = '{0}.inserts.hist_graph.pdf'.format(prefix)
graph_insert_dist = ('java -Xmx4G -jar '
'{3}/picard.jar '
'CollectInsertSizeMetrics '
'INPUT={0} OUTPUT={1} H={2} '
'VERBOSITY=ERROR QUIET=TRUE '
'W=1000 STOP_AFTER=5000000').format(final_bam,
insert_data,
insert_plot,
os.environ['PICARDROOT'])
logging.info(graph_insert_dist)
os.system(graph_insert_dist)
return insert_data, insert_plot
def get_fract_reads_in_regions_old(reads_bed, regions_bed):
'''
Function that takes in bed file of reads and bed file of regions and
gets fraction of reads sitting in said regions
'''
reads_bedtool = pybedtools.BedTool(reads_bed)
regions_bedtool = pybedtools.BedTool(regions_bed)
reads = regions_bedtool.sort().merge().intersect(reads_bedtool, c=True, nonamecheck=True)
read_count = 0
for interval in reads:
read_count += int(interval[-1])
fract_reads = float(read_count)/reads_bedtool.count()
return read_count, fract_reads
def get_fract_reads_in_regions(reads_bed, regions_bed):
"""Function that takes in bed file of reads and bed file of regions and
gets fraction of reads sitting in said regions
"""
# uses new run_shell_cmd
cmd = "bedtools sort -i {} | "
cmd += "bedtools merge -i stdin | "
cmd += "bedtools intersect -u -nonamecheck -a {} -b stdin | "
cmd += "wc -l"
#cmd += "bedtools intersect -c -nonamecheck -a stdin -b {} | "
#cmd += "awk '{{ sum+=$4 }} END {{ print sum }}'"
cmd = cmd.format(regions_bed, reads_bed)
intersect_read_count = int(run_shell_cmd(cmd))
total_read_count = get_num_lines(reads_bed)
fract_reads = float(intersect_read_count) / total_read_count
return intersect_read_count, fract_reads
def get_signal_to_noise(final_bed, dnase_regions, blacklist_regions,
prom_regions, enh_regions, peaks):
'''
Given region sets, determine whether reads are
falling in or outside these regions
'''
logging.info('signal to noise...')
# Dnase regions
reads_dnase, fract_dnase = get_fract_reads_in_regions(final_bed,
dnase_regions)
# Blacklist regions
reads_blacklist, \
fract_blacklist = get_fract_reads_in_regions(final_bed,
blacklist_regions)
# Prom regions
reads_prom, fract_prom = get_fract_reads_in_regions(final_bed,
prom_regions)
# Enh regions
reads_enh, fract_enh = get_fract_reads_in_regions(final_bed, enh_regions)
# Peak regions
reads_peaks, fract_peaks = get_fract_reads_in_regions(final_bed, peaks)
return reads_dnase, fract_dnase, reads_blacklist, fract_blacklist, \
reads_prom, fract_prom, reads_enh, fract_enh, reads_peaks, \
fract_peaks
def get_region_size_metrics(peak_file):
'''
From the peak file, return a plot of the region size distribution and
the quartile metrics (summary from R)
'''
peak_size_summ = OrderedDict([
('Min size', 0),
('25 percentile', 0),
('50 percentile (median)', 0),
('75 percentile', 0),
('Max size', 0),
('Mean', 0),
])
# If peak file is none, return nothing
if peak_file == None:
return peak_size_summ, ''
# Load peak file. If it fails, return nothing as above
try:
peak_df = pd.read_table(peak_file, compression='gzip', header=None)
except:
return peak_size_summ, ''
# Subtract third column from second to get summary
region_sizes = peak_df.ix[:,2] - peak_df.ix[:,1]
# Summarize and store in ordered dict
peak_summary_stats = region_sizes.describe()
peak_size_summ = OrderedDict([
('Min size', peak_summary_stats['min']),
('25 percentile', peak_summary_stats['25%']),
('50 percentile (median)', peak_summary_stats['50%']),
('75 percentile', peak_summary_stats['75%']),
('Max size', peak_summary_stats['max']),
('Mean', peak_summary_stats['mean']),
])
# Plot density diagram using matplotlib
fig = plt.figure()
ax = fig.add_subplot(111)
y, binEdges = np.histogram(region_sizes, bins=100)
bincenters = 0.5 * (binEdges[1:] + binEdges[:-1])
# density = gaussian_kde(y) # from scipy.stats import gaussian_kde
# density.covariance_factor = lambda : .25
# density._compute_covariance()
plt.plot(bincenters, y, '-')
filename = peak_file.split('/')[-1]
ax.set_title('Peak width distribution for {0}'.format(filename))
#ax.set_yscale('log')
plot_img = BytesIO()
fig.savefig(plot_img, format='png')
return peak_size_summ, b64encode(plot_img.getvalue())
def get_peak_counts(raw_peaks, naive_overlap_peaks=None, idr_peaks=None):
'''
Return a table with counts for raw peaks, IDR peaks, and naive
overlap peaks
'''
# Count peaks
raw_count = sum(1 for line in getFileHandle(raw_peaks))
if naive_overlap_peaks != None:
naive_count = sum(1 for line in getFileHandle(naive_overlap_peaks))
else:
naive_count = 0
if idr_peaks != None:
idr_count = sum(1 for line in getFileHandle(idr_peaks))
else:
idr_count = 0
# Literally just throw these into a QC table
results = []
results.append(QCGreaterThanEqualCheck('Raw peaks', 10000)(raw_count))
results.append(QCGreaterThanEqualCheck('Naive overlap peaks',
10000)(naive_count))
results.append(QCGreaterThanEqualCheck('IDR peaks', 10000)(idr_count))
return results
def track_reads(reads_list, labels):
'''
This function takes in read counts for different stages
and generates a bar chart to show where reads are lost
'''
# Initial bam, filters (q30), dups, chrM
ind = np.arange(len(reads_list))
width = 0.35
fig, ax = plt.subplots()
ax.bar(ind, reads_list, width, color='b')
ax.set_ylabel('Read count')
ax.set_title('Reads at each processing step')
ax.set_xticks(ind+width)
ax.set_xticklabels(labels)
plot_img = BytesIO()
fig.savefig(plot_img, format='png')
return b64encode(plot_img.getvalue())
def read_picard_histogram(data_file):
with open(data_file) as fp:
for line in fp:
if line.startswith('## HISTOGRAM'):
break
data = np.loadtxt(fp, skiprows=1)
return data
def fragment_length_qc(data):
results = []
NFR_UPPER_LIMIT = 150
MONO_NUC_LOWER_LIMIT = 150
MONO_NUC_UPPER_LIMIT = 300
# % of NFR vs res
percent_nfr = data[:NFR_UPPER_LIMIT].sum() / data.sum()
results.append(
QCGreaterThanEqualCheck('Fraction of reads in NFR', 0.4)(percent_nfr))
# % of NFR vs mononucleosome
percent_nfr_vs_mono_nuc = (
data[:NFR_UPPER_LIMIT].sum() /
data[MONO_NUC_LOWER_LIMIT:MONO_NUC_UPPER_LIMIT + 1].sum())
results.append(
QCGreaterThanEqualCheck('NFR / mono-nuc reads', 2.5)(
percent_nfr_vs_mono_nuc))
# peak locations
peaks = find_peaks_cwt(data[:, 1], np.array([25]))
nuc_range_metrics = [('Presence of NFR peak', 20, 90),
('Presence of Mono-Nuc peak', 120, 250),
('Presence of Di-Nuc peak', 300, 500)]
for range_metric in nuc_range_metrics:
results.append(QCHasElementInRange(*range_metric)(peaks))
return results
def fragment_length_plot(data_file, peaks=None):
try:
data = read_picard_histogram(data_file)
except IOError:
return ''
except TypeError:
return ''
fig = plt.figure()
plt.bar(data[:, 0], data[:, 1])
plt.xlim((0, 1000))
if peaks:
peak_vals = [data[peak_x, 1] for peak_x in peaks]
plt.plot(peaks, peak_vals, 'ro')
plot_img = BytesIO()
fig.savefig(plot_img, format='png')
return b64encode(plot_img.getvalue())
def compare_to_roadmap(bw_file, regions_file, reg2map_file,
metadata, output_prefix):
'''
Takes a bigwig file and signal file, gets the bwAverageOverBed,
then compares that signal with the signal in the Roadmap
regions
'''
out_file = '{0}.signal'.format(output_prefix)
# First get the signal vals for the peak regions
# remember to use a UCSC formatted bed file for regions
bw_average_over_bed = 'bigWigAverageOverBed {0} {1} {2}'.format(
bw_file, regions_file, out_file)
logging.info(bw_average_over_bed)
os.system(bw_average_over_bed)
# Read the file back in
sample_data = pd.read_table(out_file, header=None)
sample_mean0_col = np.array(sample_data.iloc[:, 5])
# Then, calculate correlations with all other Roadmap samples and rank
# the correlations
roadmap_signals = pd.read_table(reg2map_file, compression='gzip')
(nrow, ncol) = roadmap_signals.shape
results = pd.DataFrame(columns=('eid', 'corr'))
for i in range(ncol):
# Slice, run correlation
roadmap_i = roadmap_signals.iloc[:, i]
spearman_corr = scipy.stats.spearmanr(np.array(roadmap_i),
sample_mean0_col)
results.loc[i] = [roadmap_i.name, spearman_corr[0]]
logging.info('{0}\t{1}'.format(roadmap_i.name, spearman_corr))
# Read in metadata to make the chart more understandable
metadata = pd.read_table(metadata)
metadata.columns = ['eid', 'mnemonic']
merged = pd.merge(metadata, results, on='eid')
sorted_results = merged.sort_values('corr', ascending=True)
# Plot results
pos = np.array(range(ncol)) + 0.5
fig = plt.figure(figsize=(5,int(ncol/4)))
plt.barh(pos, sorted_results['corr'], align='center', height=1.0)
plt.yticks(pos, sorted_results['mnemonic'].tolist(), fontsize=7)
plt.xlabel('Spearmans correlation')
plt.title('Signal correlation to Roadmap DNase')
plt.axis('tight')
ax = plt.axes()
ax.yaxis.set_ticks_position('none')
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
plot_img = BytesIO()
fig.savefig(plot_img, format='png', bbox_inches='tight')
fig.savefig('test.png', format='png', bbox_inches='tight')
return b64encode(plot_img.getvalue())
html_template = Template("""
{% macro inline_img(base64_img, img_type='png') -%}
{% if base64_img == '' %}
<pre>Metric failed.</pre>
{% else %}
<img src="data:image/{{ img_type }};base64,{{ base64_img }}">
{% endif %}
{%- endmacro %}