-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathngs_modules.py
1855 lines (1604 loc) · 69.1 KB
/
ngs_modules.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
from __future__ import print_function
import os
import sys
import re
import math
import numpy as np
import pandas as pd
import csv
import multiprocessing
import time
import pickle
import scipy.stats
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as pyplot
from matplotlib_venn import venn2
from matplotlib_venn import venn3
matplotlib.rcParams.update({'font.size': 11})
from Bio import SeqIO
from Bio.SeqIO import FastaIO
def preprocessing_per_sample(io_list):
"""fastqc | trim | align | sort | dedup | index
"""
r1_r2, index, dir_tuple, read_group_dict = io_list
r1, r2 = r1_r2
fastqc_dir, trim_paired_dir, trim_unpaired_dir, bam_dir = dir_tuple
sample_id = r1.split('/')[-1].split('_')[0]
num_threads = 4
java_xmx = "-Xmx16G"
# fastqc
command_fastqc = ["fastqc"]
command_fastqc += [r1, r2]
command_fastqc += ["-o", fastqc_dir]
command_fastqc += ["-t", str(2)] # cannot be more than number of input files
command_fastqc += ["--quiet"]
command_fastqc = " ".join(command_fastqc)
os.system(command_fastqc)
# trim
trim_r1_paired = trim_paired_dir + sample_id + ".R1.paired.fastq.gz"
trim_r1_unpaired = trim_unpaired_dir + sample_id + ".R1.unpaired.fastq.gz"
trim_r2_paired = trim_paired_dir + sample_id + ".R2.paired.fastq.gz"
trim_r2_unpaired = trim_unpaired_dir + sample_id + ".R2.unpaired.fastq.gz"
command_trim = ["java {0:s} -jar $trimmomatic PE".format(java_xmx)]
command_trim += [r1, r2]
command_trim += [trim_r1_paired, trim_r1_unpaired, trim_r2_paired, trim_r2_unpaired]
command_trim += ["ILLUMINACLIP:/data/nh2tran/GeneSolutions/tools/trimmomatic/adapters/TruSeq3-PE-2.fa:2:30:10"]
command_trim += ["LEADING:3"]
command_trim += ["TRAILING:3"]
command_trim += ["SLIDINGWINDOW:4:15"]
command_trim += ["CROP:75"]
command_trim += ["MINLEN:36"]
command_trim += ["-threads", str(num_threads)]
command_trim = " ".join(command_trim)
os.system(command_trim)
# piping align | sort
temp_file = bam_dir + sample_id + ".sorted.sam"
read_group = ["@RG"]
read_group.append("ID:" + sample_id)
read_group.append("LB:" + sample_id)
read_group.append("SM:" + read_group_dict['SM'])
read_group.append("PL:" + read_group_dict['PL'])
read_group.append("PU:" + read_group_dict['PU'])
read_group = "\\t".join(read_group)
read_group = "\'" + read_group + "\'"
command_bwa = ["bwa mem"]
command_bwa += [index, trim_r1_paired, trim_r2_paired]
command_bwa += ["-M"]
command_bwa += ["-R", read_group]
command_bwa += ["-t", str(num_threads)]
command_bwa = " ".join(command_bwa)
command_sort = ["samtools sort"]
command_sort += ["-O", "SAM"]
command_sort += ["-@", str(num_threads)]
command_sort += [">", temp_file]
command_sort = " ".join(command_sort)
pipe_bwa_sort = " | ".join([command_bwa, command_sort])
os.system(pipe_bwa_sort)
# dedup and index
bam_file = bam_dir + sample_id + ".sorted.deduped.bam"
metrics_file = bam_file + ".metrics.txt"
command_dedup = ["gatk --java-options '{0:s}' MarkDuplicates".format(java_xmx)]
command_dedup += ["-I", temp_file]
command_dedup += ["-O", bam_file]
command_dedup += ["-M", metrics_file]
command_dedup += ["--CREATE_INDEX", "true"]
command_dedup += ["--QUIET", "true"]
command_dedup += ["--VERBOSITY", "ERROR"]
command_dedup = " ".join(command_dedup)
os.system(command_dedup)
# remove temp files
os.system("rm " + trim_r1_paired)
os.system("rm " + trim_r2_paired)
os.system("rm " + temp_file)
def preprocessing(index, fastq_dir, output_dir, read_group_dict, num_samples, num_test):
"""fastqc | trim | align | sort | dedup | index
Parallel on num_samples
Usage:
index = "/data/nh2tran/GeneSolutions/indexes/hg38_selected"
fastq_dir = "/data/nh2tran/GeneSolutions/fastq/NIPT_700/"
output_dir = "/data/nh2tran/GeneSolutions/temp/preprocessing/"
read_group_dict = {'SM': "NIPT_700", 'PL': "unknown", 'PU': "unknown"}
num_samples = 1 # default 4 threads, 16G per sample
num_test = 1
preprocessing(index, fastq_dir, output_dir, read_group_dict, num_samples, num_test)
"""
print("".join(["="] * 80)) # section-separating line
print("preprocessing()")
print("index =", index)
print("fastq_dir =", fastq_dir)
print("output_dir =", output_dir)
print("read_group_dict =", read_group_dict)
print("num_samples =", num_samples)
print("num_test =", num_test)
print("".join(["="] * 80)) # section-separating line
# get paired-end fastq and check if they match
fastq_list = [os.path.join(fastq_dir, x) for x in os.listdir(fastq_dir)]
r1_list = [x for x in fastq_list if 'R1' in x]
r2_list = [x for x in fastq_list if 'R2' in x]
r1_list.sort()
r2_list.sort()
if num_test is not None:
r1_list = r1_list[:num_test]
r2_list = r2_list[:num_test]
for r1, r2 in zip(r1_list, r2_list):
assert r1 == r2.replace('_R2_', '_R1_'), "Error: R1 and R2 not matched"
print("Number of paired-end fastq:", len(r1_list))
print()
# prepare the output folders
fastqc_dir = output_dir + "fastqc/"
# after trimming, paired reads are kept separately to be removed after alignment
trim_paired_dir = output_dir + "trim_paired/"
trim_unpaired_dir = output_dir + "trim_unpaired/"
bam_dir = output_dir + "bam/"
dir_tuple = (fastqc_dir, trim_paired_dir, trim_unpaired_dir, bam_dir)
os.system("mkdir " + output_dir)
os.system("mkdir " + fastqc_dir)
os.system("mkdir " + trim_paired_dir)
os.system("mkdir " + trim_unpaired_dir)
os.system("mkdir " + bam_dir)
# preprocessing num_samples in parallel
r1_r2_list = zip(r1_list, r2_list)
args_list = [[r1_r2, index, dir_tuple, read_group_dict] for r1_r2 in r1_r2_list]
pool = multiprocessing.Pool(processes=num_samples)
pool.map(preprocessing_per_sample, args_list)
pool.close()
pool.join()
def process_multi_samples(function, bam_list_file, output_dir, num_samples, num_test):
"""Process multiple samples in parallel.
Usage:
function = samtools_flagstat_per_bam
bam_list_file = "/data/nh2tran/GeneSolutions/temp/bam_list.txt"
output_dir = "/data/nh2tran/GeneSolutions/temp/samtools_flagstat/"
num_samples = 1
num_test = 1
process_multi_samples(function, bam_list_file, output_dir, num_samples, num_test)
"""
print("".join(["="] * 80)) # section-separating line
print("process_multi_samples()")
print("function =", function.__name__)
print("bam_list_file =", bam_list_file)
print("output_dir =", output_dir)
print("num_samples =", num_samples)
print("num_test =", num_test)
print("".join(["="] * 80)) # section-separating line
with open(bam_list_file, 'r') as file_handle:
bam_list = [line.strip() for line in file_handle.readlines()]
print("Number of bam files:", len(bam_list))
# limite the number of bam files in test mode
if num_test is not None:
bam_list = bam_list[:num_test]
output_dir_list = [output_dir] * len(bam_list)
argument_list = zip(bam_list, output_dir_list)
pool = multiprocessing.Pool(processes=num_samples)
pool.map(function, argument_list)
pool.close()
pool.join()
print("multiprocessing.Pool() finished.")
def genomecov_hist_per_bam(io_tuple):
"""Run bedtools genomecov hist on 1 bam file, and extract genome lines.
bedtools can only use 1 thread.
"""
bam_file, output_dir = io_tuple
bam_file_name = bam_file.split('/')[-1]
hist_file = output_dir + bam_file_name + ".genomecov_hist"
command = ["bedtools genomecov"]
command += ["-ibam", bam_file]
command += ["| grep -w \"^genome\""]
command += [">", hist_file]
command = " ".join(command)
os.system(command)
def genomecov_hist(bam_list_file, output_dir, num_samples, num_test):
"""Run bedtools genomecov hist on a list of bam files.
Summarize percentage of nonzero, 1x, 2x, etc, and depth per bam.
Usage:
bam_list_file = "/data/nh2tran/GeneSolutions/temp/bam.list"
output_dir = "/data/nh2tran/GeneSolutions/temp/genomecov_hist/"
num_samples = 1
num_test = 1
genomecov_hist(bam_list_file, output_dir, num_samples, num_test)
"""
print("".join(["="] * 80)) # section-separating line
print("genomecov_hist()")
print("bam_list_file =", bam_list_file)
print("output_dir =", output_dir)
print("num_samples =", num_samples)
print("num_test =", num_test)
print("".join(["="] * 80)) # section-separating line
# run bedtools genomecov hist on num_samples in parallel
os.system("mkdir " + output_dir)
process_multi_samples(genomecov_hist_per_bam, bam_list_file, output_dir, num_samples, num_test)
# summarize coverage from genomecov_hist
hist_file_list = [output_dir + x for x in os.listdir(output_dir) if ".genomecov_hist" in x]
print("len(hist_file_list) =", len(hist_file_list))
frequency_zero_4plus= []
mean_depth = []
for hist_file in hist_file_list:
hist_array = np.loadtxt(hist_file, usecols=(1,2))
depth = hist_array[:,0]
frequency = hist_array[:,1]
mean_depth.append(np.average(depth, weights=frequency))
# record frequency of zero, 1x, 2x, 3x, 4plus coverage
max_depth = len(frequency) - 1
if max_depth < 4:
frequency = np.append(frequency, [0]*(4-max_depth))
frequency[4] = np.sum(frequency[4:])
frequency_zero_4plus.append(frequency[:5])
frequency_zero_4plus = np.array(frequency_zero_4plus)
mean_depth = np.array(mean_depth)
ref_length = frequency_zero_4plus[0,:].sum()
print("ref_length =", ref_length)
# genome coverage per bam
pct_nonzero = np.mean((ref_length - frequency_zero_4plus[:,0]) / ref_length)
pct_1x = np.mean(frequency_zero_4plus[:,1] / ref_length)
pct_2x = np.mean(frequency_zero_4plus[:,2] / ref_length)
pct_3x = np.mean(frequency_zero_4plus[:,3] / ref_length)
pct_4plus = np.mean(frequency_zero_4plus[:,4] / ref_length)
print("pct_nonzero =", pct_nonzero)
print("pct_1x =", pct_1x)
print("pct_2x =", pct_2x)
print("pct_3x =", pct_3x)
print("pct_4plus =", pct_4plus)
# depth per bam
print("mean_depth =", np.average(mean_depth))
def genomecov_hist_sum(hist_file):
"""Summarize coverage and depth from a bedtools genomecov hist file.
Usage:
hist_file = "/data/nh2tran/GeneSolutions/temp/NIPT_700.q_10.bam.genomecov_hist"
genomecov_hist_sum(hist_file)
"""
print("".join(["="] * 80)) # section-separating line
print("genomecov_hist_sum()")
print("hist_file =", hist_file)
print("".join(["="] * 80)) # section-separating line
depth_dict = {}
with open(hist_file, 'r') as filehandle:
for line in filehandle:
chr_name, depth, frequency = line.split()
depth = int(depth)
frequency = int(frequency)
if chr_name in depth_dict:
depth_dict[chr_name].append([depth, frequency])
else:
depth_dict[chr_name] = [[depth, frequency]]
# genome depth
depth = np.array([x[0] for x in depth_dict["genome"]])
frequency = np.array([x[1] for x in depth_dict["genome"]])
# depth mean/median
mean_depth = np.average(depth, weights=frequency)
frequency_cumsum = np.cumsum(frequency)
median_index = np.searchsorted(frequency_cumsum, frequency_cumsum[-1]/2.0)
median_depth = depth[median_index]
# depth sd mean/median
error2 = np.square(depth - mean_depth)
mean_sd = np.sqrt(np.average(error2, weights=frequency))
#error2 = np.square(depth - median_depth)
sorted_indices = np.argsort(error2)
error2_sorted = error2[sorted_indices]
frequency_sorted = frequency[sorted_indices]
frequency_sorted_cumsum = np.cumsum(frequency_sorted)
median_index = np.searchsorted(frequency_sorted_cumsum, frequency_sorted_cumsum[-1]/2.0)
median_sd = np.sqrt(error2_sorted[median_index])
# depth percentiles
depth_zero_pct = frequency[0] / frequency_cumsum[-1]
pct_10_depth = np.flatnonzero(frequency_cumsum / frequency_cumsum[-1] >= 0.1)[0]
pct_99_depth = np.flatnonzero(frequency_cumsum / frequency_cumsum[-1] >= 0.99)[0]
print("mean_depth =", mean_depth)
print("median_depth =", median_depth)
print("mean_sd =", mean_sd)
print("median_sd =", median_sd)
print("depth_zero_pct =", depth_zero_pct)
print("depth_nonzero_pct =", 1-depth_zero_pct)
print("pct_10_depth =", pct_10_depth)
print("pct_99_depth =", pct_99_depth)
print("max_depth", depth[-1])
depth_lower_bound = median_depth - 3 * median_sd
depth_upper_bound = median_depth + 3 * median_sd #float('inf')
depth_bound_count = sum([y for x, y in zip(depth, frequency) if (x >= depth_lower_bound and x <= depth_upper_bound)])
depth_bound_pct = depth_bound_count / frequency_cumsum[-1]
print("depth_lower_bound =", depth_lower_bound)
print("depth_upper_bound =", depth_upper_bound)
print("depth_bound_pct =", depth_bound_pct)
# depth distribution
png_file = "plot_depth_distr.png"
fig, ax = pyplot.subplots()
pyplot.hist(depth, weights=frequency, bins=50, range=(0, 800),
facecolor='salmon', alpha=0.8, rwidth=0.8)
pyplot.ylabel("Number of genome positions")
pyplot.xlabel("Sequencing depth")
pyplot.text(475, 2.5e8, 'average=364, error=67')
pyplot.grid(axis='y', alpha=0.8)
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
pyplot.savefig(png_file)
print(png_file)
chr_list = ['chr' + str(x) for x in range(1, 23)] + ['chrX', 'chrY']
for chr_name in chr_list:
depth = np.array([x[0] for x in depth_dict[chr_name]])
frequency = np.array([x[1] for x in depth_dict[chr_name]])
# depth mean/median
mean_depth = np.average(depth, weights=frequency)
frequency_cumsum = np.cumsum(frequency)
median_index = np.searchsorted(frequency_cumsum, frequency_cumsum[-1]/2.0)
median_depth = depth[median_index]
# depth sd mean/median
error2 = np.square(depth - mean_depth)
mean_sd = np.sqrt(np.average(error2, weights=frequency))
error2 = np.square(depth - median_depth)
sorted_indices = np.argsort(error2)
error2_sorted = error2[sorted_indices]
frequency_sorted = frequency[sorted_indices]
frequency_sorted_cumsum = np.cumsum(frequency_sorted)
median_index = np.searchsorted(frequency_sorted_cumsum, frequency_sorted_cumsum[-1]/2.0)
median_sd = np.sqrt(error2_sorted[median_index])
print(chr_name, mean_depth, mean_sd, median_depth, median_sd)
def genomecov_2x_per_bam(io_tuple):
"""Run bedtools genomecov bg on 1 bam file, and extract 2x regions.
bedtools can only use 1 thread.
"""
bam_file, output_dir = io_tuple
bam_file_name = bam_file.split('/')[-1]
bed_file = output_dir + bam_file_name + ".genomecov_2x"
command = ["bedtools genomecov"]
command += ["-bg"]
command += ["-ibam", bam_file]
command += ["| grep -w \"2$\""]
command += [">", bed_file]
command = " ".join(command)
os.system(command)
def genomecov_2x(hg38_selected_genome, bam_list_file, output_dir, num_samples, num_test):
"""Run bedtools genomecov bg on a list of bam files.
Summarize distribution of 2x regions across genome and samples.
Usage:
hg38_selected_genome = "/data/nh2tran/GeneSolutions/references/hg38_selected.genome"
bam_list_file = "/data/nh2tran/GeneSolutions/temp/bam.list"
output_dir = "/data/nh2tran/GeneSolutions/temp/genomecov_2x/"
num_samples = 1
num_test = 1
genomecov_2x(hg38_selected_genome, bam_list_file, output_dir, num_samples, num_test)
"""
print("".join(["="] * 80)) # section-separating line
print("genomecov_2x()")
print("hg38_selected_genome =", hg38_selected_genome)
print("bam_list_file =", bam_list_file)
print("output_dir =", output_dir)
print("num_samples =", num_samples)
print("num_test =", num_test)
print("".join(["="] * 80)) # section-separating line
# run bedtools genomecov bg on num_samples in parallel
os.system("mkdir " + output_dir)
process_multi_samples(genomecov_2x_per_bam, bam_list_file, output_dir, num_samples, num_test)
# use {chr_name: array} to represent genome positions
genome_array = {}
chr_list = ['chr' + str(x) for x in range(1, 23)] + ['chrX', 'chrY']
with open(hg38_selected_genome, 'r') as file_handle:
for line in file_handle:
chr_name, chr_length = line.split()
chr_length = int(chr_length)
genome_array[chr_name] = np.zeros(chr_length, dtype='int16')
ref_length = sum([len(x) for x in genome_array.values()])
# summarize #samples with depth 2x at each genome position
# limit the analysis to only chr1
chr_name = "chr1"
bed_file_list = [output_dir + x for x in os.listdir(output_dir) if ".genomecov_2x" in x]
print("len(bed_file_list) =", len(bed_file_list))
for bed_file in bed_file_list:
with open(bed_file, 'r') as file_handle:
for line in file_handle:
if chr_name in line:
chr_name, start, end, depth = line.split()
start, end, depth = [int(x) for x in [start, end, depth]]
genome_array[chr_name][start:end] += 1
else:
break
np_file = output_dir + chr_name + "_depth_2x_distr.npy"
np.save(np_file, genome_array[chr_name])
#genome_array[chr_name] = np.load(np_file)
print(np_file)
# print histogram and summary
print("chr_name =", chr_name)
print("len(genome_array[chr_name]) =", len(genome_array[chr_name]))
print("np.sum(genome_array[chr_name] >= 1) =", np.sum(genome_array[chr_name] >= 1))
print("np.max(genome_array[chr_name]) =", np.max(genome_array[chr_name]))
print("np.median(genome_array[chr_name]) =", np.median(genome_array[chr_name]))
png_file = output_dir + chr_name + "_depth_2x_distr.png"
fig, ax = pyplot.subplots()
pyplot.hist(genome_array[chr_name], bins=range(1, 3*int(np.median(genome_array[chr_name]))),
facecolor='mediumblue', alpha=1.0, rwidth=1.0)
ax.set_ylabel("Number of genome positions")
ax.set_xlabel("Number of bam files with 2 reads at a genome position")
pyplot.savefig(png_file)
print(png_file)
# print bed file
bed_file = output_dir + chr_name + "_depth_2x_distr.bed"
nonzero_index = np.flatnonzero(genome_array[chr_name])
current_start = nonzero_index[0]
current_end = current_start
current_depth = genome_array[chr_name][current_start]
with open(bed_file, 'w') as file_handle:
for index in nonzero_index[1:]:
depth = genome_array[chr_name][index]
if (current_end == index - 1 and current_depth == depth):
current_end = index
else:
line = '\t'.join([chr_name, str(current_start), str(current_end+1), str(current_depth)])
line += '\n'
file_handle.write(line)
current_start = index
current_end = current_start
current_depth = genome_array[chr_name][current_start]
line = '\t'.join([chr_name, str(current_start), str(current_end+1), str(current_depth)])
line += '\n'
file_handle.write(line)
print(bed_file)
def genomecov_bg_per_bam(io_tuple):
"""Run bedtools genomecov bg on 1 bam file.
bedtools can only use 1 thread.
"""
bam_file, output_dir = io_tuple
bam_file_name = bam_file.split('/')[-1]
bed_file = output_dir + bam_file_name + ".bg"
command = ["bedtools genomecov"]
command += ["-bg"]
command += ["-ibam", bam_file]
command += [">", bed_file]
command = " ".join(command)
os.system(command)
def genomecov_bg_depth_per_chr(io_tuple):
"""
"""
chr_name, chr_length, output_dir = io_tuple
chr_array = np.zeros(chr_length, dtype='int32')
chr_name_len = len(chr_name)
bed_file_list = [output_dir + x for x in os.listdir(output_dir) if ".bam.bg" in x]
depth_1x = np.zeros(len(bed_file_list))
depth_2plus = np.zeros(len(bed_file_list))
for index, bed_file in enumerate(bed_file_list):
with open(bed_file, 'r') as file_handle:
for line in file_handle:
name, start, end, depth = line.split()
if chr_name == name:
start, end, depth = [int(x) for x in [start, end, depth]]
chr_array[start:end] += depth
num_positions = end - start
if depth == 1:
depth_1x[index] += num_positions
elif depth >= 2:
depth_2plus[index] += num_positions
depth_nonzero = depth_1x + depth_2plus
return chr_name, chr_array, depth_1x, depth_2plus, depth_nonzero
def genomecov_bg_write_per_chr(io_tuple):
"""
"""
chr_name, chr_bw_file, chr_array, hg38_selected_genome = io_tuple
temp_bg_file = chr_bw_file + ".bg"
with open(temp_bg_file, 'w') as file_handle:
nonzero_index = np.flatnonzero(chr_array)
current_start = nonzero_index[0]
current_end = current_start
current_depth = chr_array[current_start]
for index in nonzero_index[1:]:
depth = chr_array[index]
if (index == current_end + 1 and depth == current_depth):
current_end = index
else:
line = '\t'.join([chr_name, str(current_start), str(current_end+1), str(current_depth)])
line += '\n'
file_handle.write(line)
current_start = index
current_end = current_start
current_depth = chr_array[current_start]
line = '\t'.join([chr_name, str(current_start), str(current_end+1), str(current_depth)])
line += '\n'
file_handle.write(line)
os.system("bedGraphToBigWig {0:s} {1:s} {2:s}".format(temp_bg_file, hg38_selected_genome, chr_bw_file))
os.system("rm {0:s}".format(temp_bg_file))
def genomecov_bg(hg38_selected_genome, bam_list_file, output_dir, num_samples, num_test):
"""Run bedtools genomecov bg on a list of bam files.
Calculate merged bed graph and sequencing depth.
Usage:
hg38_selected_genome = "/data/nh2tran/GeneSolutions/references/hg38_selected.genome"
bam_list_file = "/data/nh2tran/GeneSolutions/temp/bam.list"
output_dir = "/data/nh2tran/GeneSolutions/temp/genomecov_bg/"
num_samples = 1
num_test = 1
genomecov_bg(hg38_selected_genome, bam_list_file, output_dir, num_samples, num_test)
"""
print("".join(["="] * 80)) # section-separating line
print("genomecov_bg()")
print("hg38_selected_genome =", hg38_selected_genome)
print("bam_list_file =", bam_list_file)
print("output_dir =", output_dir)
print("num_samples =", num_samples)
print("num_test =", num_test)
print("".join(["="] * 80)) # section-separating line
start_time = time.time()
# run bedtools genomecov bg on num_samples in parallel
os.system("mkdir " + output_dir)
process_multi_samples(genomecov_bg_per_bam, bam_list_file, output_dir, num_samples, num_test)
print("time.time() - start_time =", time.time() - start_time)
print("".join(["="] * 80)) # section-separating line
start_time = time.time()
# aggregate depth along bed- and genome- dimentions
# parallel over chr
chr_list = ['chr' + str(x) for x in range(1, 23)] + ['chrX', 'chrY']
chr_length = []
with open(hg38_selected_genome, 'r') as file_handle:
for line in file_handle:
_, length = line.split()
chr_length.append(int(length))
output_dir_list = [output_dir] * len(chr_list)
argument_list = zip(chr_list, chr_length, output_dir_list)
pool = multiprocessing.Pool(processes=num_samples)
result_batch = pool.map(genomecov_bg_depth_per_chr, argument_list)
pool.close()
pool.join()
genome_array = {}
depth_1x, depth_2plus, depth_nonzero = 0, 0, 0
for result in result_batch: # chr_name, chr_array, depth_1x, depth_2plus, depth_nonzero
genome_array[result[0]] = result[1]
depth_1x += result[2]
depth_2plus += result[3]
depth_nonzero += result[4]
# make sure no overlapping reads left per bam
ref_length = sum(chr_length)
pct_nonzero = np.mean(depth_nonzero / ref_length)
pct_1x = np.mean(depth_1x / ref_length)
pct_2plus = np.mean(depth_2plus / ref_length)
print("pct_nonzero per bam =", pct_nonzero)
print("pct_1x =", pct_1x)
print("pct_2plus =", pct_2plus)
print("time.time() - start_time =", time.time() - start_time)
print("".join(["="] * 80)) # section-separating line
start_time = time.time()
# calculate distribution of sequencing depth
genomecov_hist_file = output_dir + "merged.genomecov_hist.full"
with open(genomecov_hist_file, 'w') as file_handle:
genome_hist = {}
for chr_name in chr_list:
depth, frequency = np.unique(genome_array[chr_name], return_counts=True)
for x, y in zip(depth, frequency):
line = '\t'.join([chr_name, str(x), str(y)])
line += '\n'
file_handle.write(line)
if x in genome_hist:
genome_hist[x] += y
else:
genome_hist[x] = y
genome_depth = sorted(genome_hist.keys())
for depth in genome_depth:
line = '\t'.join(["genome", str(depth), str(genome_hist[depth])])
line += '\n'
file_handle.write(line)
print("genomecov_hist_file =", genomecov_hist_file)
print("time.time() - start_time =", time.time() - start_time)
print("".join(["="] * 80)) # section-separating line
start_time = time.time()
# print bigwig file
argument_list = [[chr_name, output_dir + "merged_" + chr_name + ".bw", genome_array[chr_name], hg38_selected_genome]
for chr_name in chr_list]
pool = multiprocessing.Pool(processes=num_samples)
pool.map(genomecov_bg_write_per_chr, argument_list)
pool.close()
pool.join()
print("write merged_chr*.bw")
print("time.time() - start_time =", time.time() - start_time)
print("".join(["="] * 80)) # section-separating line
start_time = time.time()
def filter_q30_1read(io_tuple):
"""Filter alignments with mapq >= 30.
Sample 1 overlapping read (also remove secondary alignments).
Usage:
bam_list_file = "/data/nh2tran/GeneSolutions/temp/bam.list"
output_dir = "/data/nh2tran/GeneSolutions/temp/filter_q30_1read/"
num_samples = 1 # 1 threads
num_test = 1
filter_q30_1read(bam_list_file, output_dir, num_samples, num_test)
"""
start_time = time.time()
bam_file, output_dir = io_tuple
bam_file_name = bam_file.split('/')[-1]
prefix = bam_file_name[:-4]
num_threads = 1
# bam to sam, filter alignments with mapq >= 30
temp_q30_sam = output_dir + prefix + ".q30.sam"
command = ["samtools view -h"]
command += ["-q", "30"]
command += ["-F", "0x100"] # skip secondary alignments
command += ["-@", str(num_threads)]
command += [bam_file]
command += ["-o", temp_q30_sam]
command = " ".join(command)
os.system(command)
# use {chr_name: array} to represent genome regions, 0-based
genome_array = {}
with open("/data/nh2tran/GeneSolutions/references/hg38_selected.genome", 'r') as file_handle:
for line in file_handle:
chr_name, chr_length = line.split()
chr_length = int(chr_length)
genome_array[chr_name] = np.zeros(chr_length, dtype=bool)
# if a read falls into an empty region, write it and mark the region as True;
# otherwise skip it
temp_q30_1read_sam = output_dir + prefix + ".q30.1read.sam"
with open(temp_q30_sam, 'r') as input_handle:
with open(temp_q30_1read_sam, 'w') as output_handle:
for line in input_handle:
if line[0] == "@": # write header line
output_handle.write(line)
else:
line_split = line.split()
chr_name = line_split[2]
if chr_name == "*": # unmapped read without coordinate, just write, don't mark anything
output_handle.write(line)
else:
chr_pos = int(line_split[3]) - 1 # convert coordinate from 1-based to 0-based
if np.any(genome_array[chr_name][chr_pos:chr_pos+75]): # skip overlapping read
continue
else: # empty region, write read and mark the region as True;
output_handle.write(line)
genome_array[chr_name][chr_pos:chr_pos+75] = True
# sam to bam and index
output_bam = output_dir + prefix + ".q30.1read.bam"
command_view = ["samtools view"]
command_view += ["-@", str(num_threads)]
command_view += [temp_q30_1read_sam]
command_view += ["-b -o", output_bam]
command_view = " ".join(command_view)
os.system(command_view)
command_index = ["samtools index"]
command_index += [output_bam]
command_index = " ".join(command_index)
os.system(command_index)
# remove temp files
os.system("rm " + temp_q30_sam)
os.system("rm " + temp_q30_1read_sam)
def samtools_flagstat_per_bam(io_tuple):
bam_file, output_dir = io_tuple
bam_file_name = bam_file.split('/')[-1]
num_threads = 4
log_file = output_dir + bam_file_name + ".flagstat"
command = ["samtools flagstat"]
command += ["-@", str(num_threads)]
command += [bam_file]
command += [">", log_file]
command = " ".join(command)
os.system(command)
def samtools_flagstat(bam_list_file, output_dir, num_samples=1, num_test=1):
"""Summarize flagstat of a list bam files.
Usage:
bam_list_file = "/data/nh2tran/GeneSolutions/temp/step_3_filter_q20_1read.bam_list"
output_dir = "/data/nh2tran/GeneSolutions/temp/step_5_flagstat/"
num_samples = 1 # 4 threads
num_test = 1
samtools_flagstat(bam_list_file, output_dir, num_samples, num_test)
"""
print("".join(["="] * 80)) # section-separating line
print("samtools_flagstat()")
print("bam_list_file =", bam_list_file)
print("".join(["="] * 80)) # section-separating line
os.system("mkdir " + output_dir)
process_multi_samples(samtools_flagstat_per_bam, bam_list_file, output_dir, num_samples, num_test)
log_file_list = [output_dir + x for x in os.listdir(output_dir) if ".bam.flagstat" in x]
total_count_list = []
for log_file in log_file_list:
count_pair_list = []
with open(log_file, 'r') as file_handle:
for line in file_handle.readlines():
line_split = line.split(' ')
count_pair_list.append([int(line_split[0]), int(line_split[2])])
total_count_list.append(count_pair_list)
# sum up counts over samples
total_count_array = np.array(total_count_list)
total_count_array = np.sum(total_count_array, axis=0)
print("num_total =", total_count_array[0])
print("num_secondary =", total_count_array[1])
print("num_supplementary =", total_count_array[2])
print("num_duplicate =", total_count_array[3])
print("num_mapped =", total_count_array[4])
print("num_paired =", total_count_array[5])
print("num_read1 =", total_count_array[6])
print("num_read2 =", total_count_array[7])
print("num_properly_paired =", total_count_array[8])
print("num_itself_mate_mapped =", total_count_array[9])
print("num_singleton =", total_count_array[10])
print("num_mate_mapped_diff_chr =", total_count_array[11])
print("num_mate_mapped_diff_chr_mapq_5 =", total_count_array[12])
mapped_rate = float(total_count_array[4][0]) / total_count_array[0][0]
properly_paired_rate = float(total_count_array[8][0]) / total_count_array[5][0]
duplicate_rate = float(total_count_array[3][0]) / total_count_array[4][0]
print("mapped_rate =", mapped_rate)
print("properly_paired_rate =", properly_paired_rate)
print("duplicate_rate =", duplicate_rate)
def gatk_per_chromosome(args):
bam_list_file, reference_file, chromosome = args
command_list = ["gatk --java-options '-Xmx8G'"]
# ~ command_list += ["HaplotypeCaller"]
# Ploidy (number of chromosomes) per sample.
# For pooled data, set to (Number of samples in each pool * Sample Ploidy).
# Default value: 2.
# ~ command_list += ["--sample-ploidy", str(10)]
command_list.append("Mutect2")
command_list.append("--tumor-sample NIPT_700")
command_list += ["--input", bam_list_file]
command_list += ["--reference", reference_file]
command_list += ["--intervals", chromosome]
command_list += ["--output", "temp_" + chromosome + ".vcf.gz"]
command = " ".join(command_list)
os.system(command)
def gatk_multi_chromosome(bam_list_file, reference_file, output_file, num_threads=1):
"""Parallel gatk on multiple chromosomes via multiprocessing threads.
Usage:
bam_list_file = "/data/nh2tran/GeneSolutions/temp/bam.list"
reference_file = "/data/nh2tran/GeneSolutions/references/hg38_selected.fa"
output_file = "/data/nh2tran/GeneSolutions/temp/sample.vcf.gz"
gatk_multi_chromosome(bam_path, output_file, num_threads=8)
"""
print("".join(["="] * 80)) # section-separating line
print("gatk_multi_chromosome()")
print("bam_list_file =", bam_list_file)
print("output_file =", output_file)
print("num_threads =", num_threads)
print("".join(["="] * 80)) # section-separating line
chr_list = ["chr" + str(x) for x in range(1, 22+1)] + ["chrX", "chrY"]
bam_list = [bam_list_file] * len(chr_list)
reference_list = [reference_file] * len(chr_list)
args_list = zip(bam_list, reference_list, chr_list)
pool = multiprocessing.Pool(processes=num_threads)
pool.map(gatk_per_chromosome, args_list)
pool.close()
pool.join()
temp_vcf_list = ["temp_" + x + ".vcf.gz" for x in chr_list]
os.system("bcftools concat {0} -Oz > {1}".format(" ".join(temp_vcf_list), output_file))
#os.system("rm temp_chr*")
def extract_sample_variants_per_chromosome(argument):
chromosome = argument[0]
input_1000genomes = argument[1]
population = argument[2]
sample_file = argument[3]
output_dir = argument[4]
in_vcf = input_1000genomes + "ALL." + chromosome + "_GRCh38.genotypes.20170504.vcf.gz"
out_vcf = output_dir + population + "." + chromosome + ".vcf.gz"
# extract sample variants, update AC, AN
command_subset = ["bcftools view"]
command_subset += [in_vcf]
command_subset += ["--samples-file", sample_file]
command_subset += ["--min-ac 1"] # only variants that have non-reference allele in the subset samples
command_subset += ["--trim-alt-alleles"] # from multi-allele sites: C,T AC=198,0;AF=1,0;
#command_subset += ["--private"] # variants carried only by the subset samples
#command_subset += ["--no-update"] # no update AC, AN
command_subset += ["--force-samples"]
command_subset = " ".join(command_subset)
# update allele frequency
command_af = "bcftools +fill-tags -- -t AF"
# drop genotypes and output
command_output = ["bcftools view"]
command_output += ["--drop-genotypes"]
command_output += ["-Oz >", out_vcf]
command_output = " ".join(command_output)
# stream 3 commands to 1 pipe
command = " | ".join([command_subset, command_af, command_output])
os.system(command)
os.system("tabix -p vcf " + out_vcf)
def extract_sample_variants(input_1000genomes, population, sample_file, output_dir, num_threads):
"""Extract variants of population-specific samples from 1000 genomes project.
Update AC, AN, AF.
Drop sample genotypes, chromosome-merge to one vcf.
Usage:
input_1000genomes = "/data/nh2tran/GeneSolutions/1000genomes/release_20130502_GRCh38_positions/"
population = "khv"
sample_file = "/data/nh2tran/GeneSolutions/1000genomes/khv/khv_samples.txt"
output_dir = "/data/nh2tran/GeneSolutions/1000genomes/temp/"
num_threads = 1
extract_sample_variants(input_1000genomes, population, sample_file, output_dir, num_threads)
"""
print("".join(["="] * 80)) # section-separating line
print("extract_sample_variants()")
print("input_1000genomes =", input_1000genomes)
print("population =", population)
print("sample_file =", sample_file)
print("output_dir =", output_dir)
print("num_threads =", num_threads)
print("".join(["="] * 80)) # section-separating line
# run parallel per chromosome
chr_list = ["chr" + str(x) for x in range(1, 22+1)] + ["chrX", "chrY"]
input_1000genomes_list = [input_1000genomes] * len(chr_list)
population_list = [population] * len(chr_list)
sample_file_list = [sample_file] * len(chr_list)
output_dir_list = [output_dir] * len(chr_list)
argument_list = list(zip(chr_list, input_1000genomes_list, population_list, sample_file_list, output_dir_list))
pool = multiprocessing.Pool(processes=num_threads)
pool.map(extract_sample_variants_per_chromosome, argument_list)
pool.close()
pool.join()
# chromosome-merge to one vcf
vcf_list = [output_dir + population + "." + chromosome + ".vcf.gz" for chromosome in chr_list]
out_vcf = output_dir + population + ".vcf.gz"
command = ["bcftools concat"]
command += vcf_list
command += ["-Oz >", out_vcf]
command = " ".join(command)
os.system(command)
os.system("tabix -p vcf " + out_vcf)
def draw_figure_2_venn():
print("".join(["="] * 80)) # section-separating line
print("draw_figure_2_venn()")
print("".join(["="] * 80)) # section-separating line
subsets = [597342,
0,
0,
9947022,
67153,
5320214,
7390020]
nipt_snps = 8054515
khv_snps = 12710234
eas_snps = 22724409
set_labels = ['A', 'B', 'C']
venn_plot = venn3(subsets=subsets, set_labels=set_labels, set_colors=['r', 'b', 'g'])
venn_plot.get_label_by_id('A').set_text('NIPT: {0:,} SNPs'.format(nipt_snps))
venn_plot.get_label_by_id('B').set_text('KHV: {0:,} SNPs'.format(khv_snps))
venn_plot.get_label_by_id('C').set_text('EAS: {0:,} SNPs'.format(eas_snps))
venn_plot.get_label_by_id('A').set_color('r')
venn_plot.get_label_by_id('A').set_alpha(1.0)
venn_plot.get_label_by_id('B').set_color('b')
venn_plot.get_label_by_id('B').set_alpha(1.0)
venn_plot.get_label_by_id('C').set_color('g')
venn_plot.get_label_by_id('C').set_alpha(1.0)
venn_plot.get_label_by_id('100').set_text('{0:,}\n({1:.1%})'.format(subsets[0], subsets[0]/nipt_snps))
venn_plot.get_label_by_id('101').set_text('{0:,}\n({1:.1%})'.format(subsets[4], subsets[4]/nipt_snps))
venn_plot.get_label_by_id('111').set_text('{0:,}\n({1:.1%})'.format(subsets[6], subsets[6]/nipt_snps))
venn_plot.get_label_by_id('011').set_text('')
venn_plot.get_label_by_id('001').set_text('')
pyplot.savefig("plot_figure_2_venn.png")
pyplot.close()
subsets = [664495,
0,
0,
4599704,
501004,
720510,
6889016]
nipt_snps = 8054515
khv_2pct_snps = 7609526
khv_snps = 12710234
set_labels = ['A', 'B', 'C']
venn_plot = venn3(subsets=subsets, set_labels=set_labels, set_colors=['r', 'black', 'dodgerblue'])
venn_plot.get_label_by_id('A').set_text('NIPT: {0:,} SNPs'.format(nipt_snps))