-
Notifications
You must be signed in to change notification settings - Fork 0
/
methyl_utils.py
1555 lines (1156 loc) · 49.3 KB
/
methyl_utils.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
import pysam
import os
import numpy as np
import pandas as pd
import edlib
import json
import subprocess
import gzip
import re
import mappy
import matplotlib.pyplot as plt
import seaborn as sns
import scipy.io
from scipy.sparse import csr_matrix
from scipy.sparse import vstack
import concurrent.futures
from anndata import AnnData
import scanpy as sc
import time
import pybedtools
N_read_extract = 3e5 # maximum reads for limited moded in testing
N_interval_log = 1e6 # interval for logging
print(N_read_extract)
def seq_counter(seq_dict, seq_instance):
if seq_instance in seq_dict:
seq_dict[seq_instance] += 1
else:
seq_dict[seq_instance] = 1
def quad_dict_store(quad_dict, quad_key, quad_items):
if quad_key in quad_dict:
quad_dict[quad_key].extend([quad_items])
else:
quad_dict[quad_key] = [quad_items]
def quality_calc(seq, quals, bases_dict, quals_dict):
for i in range(len(seq)):
if i in bases_dict:
seq_counter(bases_dict[i], seq[i])
else:
bases_dict[i] = {}
seq_counter(bases_dict[i], seq[i])
if i in quals_dict:
seq_counter(quals_dict[i], quals[i])
else:
quals_dict[i] = {}
seq_counter(quals_dict[i], quals[i])
def string_position_count(seq, seqs_dict):
for i in range(len(seq)):
if i in seqs_dict:
seq_counter(seqs_dict[i], seq[i])
else:
seqs_dict[i] = {}
seq_counter(seqs_dict[i], seq[i])
def quality_df(quals_dict):
quals_df = pd.DataFrame(quals_dict)
quals_df = quals_df.T
quals_df = quals_df.fillna(0)
quals_df = quals_df.stack()
quals_df = quals_df.reset_index()
# quals_df.columns = ['base', 'quality', 'tot_count']
# quals_df['mult'] = quals_df.quality * quals_df.tot_count
# quals_df_grouped = quals_df.groupby('base').sum()
quals_df.columns = ["position", "quantity", "total_cnt"]
quals_df.position = quals_df.position.astype("int")
# quals_df[quals_df.position.isin(np.arange(10))]
counts_df = quals_df.groupby("position").sum()
quals_df["position_cnt"] = quals_df.position.apply(
lambda x: counts_df.loc[x].total_cnt
)
quals_df["frequency"] = quals_df.total_cnt / quals_df.position_cnt * 100
return quals_df
def edit_match(input_seq, target_seq, max_dist):
if input_seq == target_seq:
dist = 0
match = True
else:
edit = edlib.align(input_seq, target_seq, "NW", "path", max_dist)
dist = edit["editDistance"]
if dist >= 0 and dist <= max_dist:
cigar = edit["cigar"]
if "D" in cigar or "I" in cigar:
match = False
dist = "indel"
else:
match = True
else:
match = False
return (match, dist)
def find_sub_fastq_parts(indir, sample):
pattern = re.compile(r"_R1.part_(.*?)\.fastq")
all_files = os.listdir(f"{indir}/{sample}/split/")
parts = sorted(
[
f.split(".part_")[1].split(".fastq")[0]
for f in all_files
if pattern.search(f)
]
)
parts = sorted(
np.unique([f.split(".part_")[1][:3] for f in all_files if pattern.search(f)])
)
# part + 3 digits because we did split suffix with 3 digits
return parts
def run_command(command):
subprocess.run(command, shell=True)
def split_fastq_by_lines(indir, sample, lines=4e6):
splitted_file = f"{indir}/{sample}/split/{sample}_R1.part_000.fastq"
if os.path.isfile(splitted_file):
print(splitted_file, " splitted fastq exists, skip splitting")
else:
print(splitted_file, " splitted fastq does not exist")
R1 = f"{indir}/{sample}_R1_001.fastq.gz"
split_dir = f"{indir}/{sample}/split"
if not os.path.exists(split_dir):
os.makedirs(split_dir)
print(f"{split_dir} created")
else:
print(f"{split_dir} already exists")
split_R1_name = f"{split_dir}/{sample}_R1.part_"
# pigz -p 8 -d --stdout {R1} #potential minor speed gain instead of zcat:
command_R1 = f"zcat {R1} | split -a 3 -l {int(lines)} -d --additional-suffix=.fastq - {split_R1_name}"
command_R2 = command_R1.replace("_R1", "_R2")
command_R3 = command_R1.replace("_R1", "_R3")
from concurrent.futures import ThreadPoolExecutor
commands = [command_R1, command_R2, command_R3]
with ThreadPoolExecutor() as executor:
executor.map(run_command, commands)
def extract_clean_fastq(indir, sample, part, limit):
total_reads = 0
start_time = time.time()
R1_fastq = f"{indir}/{sample}/split/{sample}_R1.part_{part}.fastq"
R2_fastq = R1_fastq.replace("_R1.", "_R2.")
R3_fastq = R1_fastq.replace("_R1.", "_R3.")
R1_fastq_clean = f"{indir}/{sample}/split/{sample}_R1.part_{part}_clean.fastq"
R3_fastq_clean = R1_fastq_clean.replace("_R1.", "_R3.")
bcs_json = f"{indir}/{sample}/split/{sample}.part_{part}_bcs.json"
if os.path.isfile(bcs_json):
print(bcs_json, " exists, skip")
return
bcs_dict = {}
R1_clean = open(R1_fastq_clean, "w")
R3_clean = open(R3_fastq_clean, "w")
r1_qual_dict = {}
r2_qual_dict = {}
r3_qual_dict = {}
r1_base_dict = {}
r2_base_dict = {}
r3_base_dict = {}
# store_bases = False
# store_quals = True
do_qc = True
with pysam.FastxFile(R1_fastq) as R1, pysam.FastxFile(
R2_fastq
) as R2, pysam.FastxFile(R3_fastq) as R3:
for r1, r2, r3 in zip(R1, R2, R3):
total_reads += 1
seq1 = r1.sequence
seq2 = r2.sequence
seq3 = r3.sequence
len1 = len(seq1)
len3 = len(seq3)
# bc = seq2 for sciMET data, matched already
# seq_counter(bcs_dict,bc)
if do_qc and total_reads % 500 == 0:
quals1 = r1.get_quality_array()
quality_calc(seq1, quals1, r1_base_dict, r1_qual_dict)
quals2 = r2.get_quality_array()
quality_calc(seq2, quals2, r2_base_dict, r2_qual_dict)
quals3 = r3.get_quality_array()
quality_calc(seq3, quals3, r3_base_dict, r3_qual_dict)
if len1 >= 40 and len3 >= 40:
bc = seq2[8:24]
match, dist = edit_match(seq2[:8], "CAGACGCG", 2)
if match:
seq_counter(bcs_dict, bc)
R1_clean.write(f"@{r1.name}_{bc} r1\n")
R1_clean.write(f"{r1.sequence}\n")
R1_clean.write("+\n")
R1_clean.write(f"{r1.quality}\n")
R3_clean.write(f"@{r3.name}_{bc} r2\n")
R3_clean.write(f"{r3.sequence}\n")
R3_clean.write("+\n")
R3_clean.write(f"{r3.quality}\n")
if total_reads % N_interval_log == 0:
elapsed_time = time.time() - start_time
message = f"Processed {total_reads} reads in {elapsed_time:.2f}s"
print(f"{message} in part {part}", flush=True)
if total_reads > N_read_extract and limit:
break
r1_qual_df = quality_df(r1_qual_dict)
r2_qual_df = quality_df(r2_qual_dict)
r3_qual_df = quality_df(r3_qual_dict)
r1_base_df = quality_df(r1_base_dict)
r2_base_df = quality_df(r2_base_dict)
r3_base_df = quality_df(r3_base_dict)
r1_qual_df.to_csv(R1_fastq.replace(".fastq", "_quals.csv"))
r2_qual_df.to_csv(R2_fastq.replace(".fastq", "_quals.csv"))
r3_qual_df.to_csv(R3_fastq.replace(".fastq", "_quals.csv"))
r1_base_df.to_csv(R1_fastq.replace(".fastq", "_bases.csv"))
r2_base_df.to_csv(R2_fastq.replace(".fastq", "_bases.csv"))
r3_base_df.to_csv(R3_fastq.replace(".fastq", "_bases.csv"))
R1_clean.close()
R3_clean.close()
with open(bcs_json, "w") as json_file:
json.dump(bcs_dict, json_file)
def extract_bc_from_bam(indir, sample, part, limit):
i = 0
bam = f"{indir}/{sample}/split/output_{part}/{sample}_R1.part_{part}_clean_bismark_bt2_pe.bam"
bcs_json = f"{indir}/{sample}/split/{sample}.part_{part}_bcs.json"
if os.path.isfile(bcs_json):
print(bcs_json, " exists, skip")
# return
bcs_dict = {}
samfile = pysam.AlignmentFile(bam, "r")
for read in samfile.fetch(until_eof=True):
i += 1
bc = read.qname.split("_")[-2]
seq_counter(bcs_dict, bc)
if i > N_read_extract and limit:
break
with open(bcs_json, "w") as json_file:
json.dump(bcs_dict, json_file)
def tag_bismark_bam_with_whitelist_barcodes(indir, sample, part, limit):
matching_csv = pd.read_csv(f"{indir}/{sample}/{sample}_raw_to_tenx_whitelist.csv")
raw_to_tenx = dict(zip(matching_csv.bc, matching_csv.tenx_whitelist))
sam_tag = f"{indir}/{sample}/split/{sample}.part_{part}_tagged.bam"
sam = f"{indir}/{sample}/split/output_{part}/{sample}_R1.part_{part}_clean_trim_bismark_bt2_pe.bam"
#if os.path.isfile(sam_tag):
# print(sam_tag, " exists, skip")
# return
samfile = pysam.AlignmentFile(sam, "rb")
tagged_bam = pysam.AlignmentFile(sam_tag, "wb", template=samfile)
total_reads = 0
start_time = time.time()
for read in samfile.fetch(until_eof=True):
total_reads += 1
raw_barcode = read.qname.split("_")[-2]
if raw_barcode in raw_to_tenx:
matched_barcode = raw_to_tenx[raw_barcode]
read.set_tag("CB", matched_barcode)
tagged_bam.write(read)
if total_reads % N_interval_log == 0:
elapsed_time = time.time() - start_time
print(f"Processed {total_reads} reads of part {part} in {elapsed_time:.2f}s", flush=True)
if total_reads > N_read_extract and limit:
break
tagged_bam.close()
samfile.close()
def tag_minimap_bam_with_all_barcodes(indir, sample, part, limit):
matching_csv = pd.read_csv(f"{indir}/{sample}/{sample}_matching_raw_to_tenx_passing.csv")
raw_to_tenx = dict(zip(matching_csv.bc, matching_csv.tenx_whitelist))
sam_tag = f"{indir}/{sample}/split/{sample}.part_{part}_tagged.bam"
sam = f"{indir}/{sample}/split/{sample}_part_{part}.bam"
if os.path.isfile(sam_tag):
print(sam_tag, " exists, skip")
return
samfile = pysam.AlignmentFile(sam, "rb")
tagged_bam = pysam.AlignmentFile(sam_tag, "wb", template=samfile)
total_reads = 0
start_time = time.time()
for read in samfile.fetch(until_eof=True):
total_reads += 1
if read.is_proper_pair and read.mapq > 5:
raw_barcode = read.qname.split("_")[-1]
if raw_barcode in raw_to_tenx:
matched_barcode = raw_to_tenx[raw_barcode]
read.set_tag("CB", matched_barcode)
tagged_bam.write(read)
if total_reads % N_interval_log == 0:
elapsed_time = time.time() - start_time
print(f"Processed {total_reads} reads of part {part} in {elapsed_time:.2f}s", flush=True)
if total_reads > N_read_extract and limit:
break
tagged_bam.close()
samfile.close()
def compute_dup_rate(indir, sample, chrom, limit):
N_interval_log = 1e6
sam = f"{indir}/{sample}/{sample}_markdup.bam"
if not os.path.isfile(sam):
sam = f"{indir}/{sample}/{sample}_markdup_piped.bam"
samfile = pysam.AlignmentFile(sam, "rb")
BC_dup_count = {}
BC_unique_count = {}
start_time = time.time()
total_reads = 0
for read in samfile.fetch(chrom):
total_reads += 1
bc = read.get_tag("CB")
if read.is_duplicate:
seq_counter(BC_dup_count, bc)
else:
seq_counter(BC_unique_count, bc)
if total_reads % N_interval_log == 0:
elapsed_time = time.time() - start_time
print(
f"Processed {total_reads} reads of {chrom} in {elapsed_time:.2f}s",
flush=True,
)
if total_reads > N_read_extract and limit:
break
samfile.close()
BC_dup_df = pd.Series(BC_dup_count)
BC_uni_df = pd.Series(BC_unique_count)
BC_dup_df.name = "dup_cnt"
BC_uni_df.name = "uniq_cnt"
mrg = pd.merge(BC_uni_df, BC_dup_df, how="outer", left_index=True, right_index=True)
mrg["total_cnt"] = mrg.sum(axis=1)
mrg["dup_rate"] = mrg.total_cnt / mrg.uniq_cnt
mrg["log10cnt"] = np.log10(mrg.total_cnt)
mrg["log10cnt_uniq"] = np.log10(mrg.uniq_cnt)
mrg.to_csv(f"{indir}/{sample}/{sample}_dup_rate_{chrom}.csv")
def aggregate_bc_dicts(indir, sample):
dir_split = f"{indir}/{sample}/split"
files = os.listdir(dir_split)
jsons = sorted([f for f in files if "_bcs.json" in f])
agg_read_csv = f"{indir}/{sample}/{sample}_agg_cnt_raw_bcs.csv"
if os.path.isfile(agg_read_csv):
print(agg_read_csv, " exists, skip")
return
data_agg = {}
for jsn in jsons:
jsn_to_load = f"{dir_split}/{jsn}"
with open(jsn_to_load, "r") as json_file:
data_sub = json.load(json_file)
for k in data_sub:
if data_agg.get(k) is not None:
data_agg[k] += data_sub[k]
else:
data_agg[k] = data_sub[k]
pd.Series(data_agg).to_csv(agg_read_csv)
def write_bc_whitelist(indir, sample, bc_file):
fasta_file = f"{indir}/{sample}/{sample}_bc_whitelist.fasta"
if os.path.isfile(fasta_file):
print(fasta_file, " exists, skip")
return
bcs = pd.read_table(bc_file, names=["bc"])
bcs = pd.DataFrame(bcs.bc.apply(lambda x: x.split("-")[0]))
bcs = bcs.sort_values(by="bc")
bcs["rev_bc"] = bcs.bc.apply(lambda x: mappy.revcomp(x))
with open(fasta_file, "w") as f:
for bc in bcs.rev_bc:
f.write(f">{bc}\n")
f.write(f"{bc}\n")
def calling_whitelist_DNA_RNA(indir, sample, dna_10x_wl_file, rna_10x_wl_file):
from matplotlib.backends.backend_pdf import PdfPages
#if os.path.isfile(fasta_file):
# print(fasta_file, " exists, skip")
# return
qc_pdf_file = f"{indir}/{sample}/{sample}_QC.pdf"
#if os.path.isfile(qc_pdf_file):
# print(qc_pdf_file, " exists, skip")
#else:
qc_pdfs = PdfPages(qc_pdf_file)
atac = pd.read_table(dna_10x_wl_file, names=["atac"])
rna = pd.read_table(rna_10x_wl_file, names=["rna"])
all_bcs = atac.join(rna)
all_bcs['rev_comp_atac'] = all_bcs.atac.apply(lambda x: mappy.revcomp(x))
import csv
N_interval_log = 2e5
raw_bcs_DNA_csv = f"{indir}/{sample}/{sample}_agg_cnt_raw_bcs.csv"
rev_comp_atac_dict = dict.fromkeys(all_bcs['rev_comp_atac'], None)
with open(raw_bcs_DNA_csv, "r") as f:
reader = csv.reader(f, delimiter=",")
for i, line in enumerate(reader):
if line[0] in rev_comp_atac_dict:
rev_comp_atac_dict[line[0]] = int(line[1])
if i % N_interval_log == 0:
print(i, line)
#if i>10000000:
# break
raw_bcs_RNA_csv = f"{indir}/{sample}/{sample}_agg_cnt_raw_bcs_RNA.csv"
rna_dict = dict.fromkeys(all_bcs['rna'], None)
with open(raw_bcs_RNA_csv, "r") as f:
reader = csv.reader(f, delimiter=",")
for i, line in enumerate(reader):
if line[0] in rna_dict:
rna_dict[line[0]] = int(line[1])
if i % N_interval_log == 0:
print(i, line)
#if i>10000000:
# break
all_bcs['RNA_cnt'] = all_bcs.rna.apply(lambda x: rna_dict[x])
all_bcs['DNA_cnt'] = all_bcs.rev_comp_atac.apply(lambda x: rev_comp_atac_dict[x])
all_bcs = all_bcs[ (all_bcs.RNA_cnt>0) & (all_bcs.DNA_cnt>0) ].copy()
all_bcs['log10_RNA_cnt'] = np.log10(all_bcs['RNA_cnt'])
all_bcs['log10_DNA_cnt'] = np.log10(all_bcs['DNA_cnt'])
from scipy.ndimage import gaussian_filter1d
from scipy.signal import find_peaks
import matplotlib.pyplot as plt
bins = 100
rna_sorted = all_bcs.log10_RNA_cnt.sort_values(ascending=False)
sub = rna_sorted.iloc[100:].copy()
x = np.histogram(sub, bins)
smooth = gaussian_filter1d(x[0], 3)
# find the local minimum
peak_idx, _ = find_peaks(-smooth)
# take the mid point of point before and after
print(peak_idx, x[1][:-1][peak_idx])
mean_hist = (x[1][1:][peak_idx] + x[1][:-1][peak_idx]) / 2
# take the last value in list of local minima (could be more than one)
mean_hist = mean_hist[-1]
plt.figure(figsize=(4, 3))
plt.plot(x[1][:-1], x[0], label="Raw Histogram")
plt.plot(x[1][:-1], smooth, label="Gaussian Smoothed")
plt.xlabel("Log10 Read Counts")
plt.ylabel("Bin Height")
plt.title(f"{sample}\n RNA raw reads")
plt.plot(
[mean_hist, mean_hist],
[0, np.max(x[0])],
linewidth=2,
label="Whitelist Threshold",
)
plt.legend(loc="best")
dna_sorted = all_bcs[all_bcs.log10_RNA_cnt>=mean_hist].log10_DNA_cnt.sort_values(ascending=False)
#sub = dna_sorted.iloc[100:30000].copy()
x = np.histogram(dna_sorted, bins)
smooth = gaussian_filter1d(x[0], 3)
peak_idx, _ = find_peaks(-smooth)
print(peak_idx, x[1][:-1][peak_idx])
mean_hist = (x[1][1:][peak_idx] + x[1][:-1][peak_idx]) / 2
mean_hist = mean_hist[-1]
#with open(fasta_file, "w") as f:
# for bc in bcs.rev_bc:
# f.write(f">{bc}\n")
# f.write(f"{bc}\n")
def write_bc_raw_reads(indir, sample, threshold):
fasta_file = f"{indir}/{sample}/{sample}_bc_raw_reads.fasta"
if os.path.isfile(fasta_file):
print(fasta_file, " exists, skip")
return
bc_file = f"{indir}/{sample}/{sample}_agg_cnt_raw_bcs.csv"
bcs = pd.read_csv(bc_file)
bcs.columns = ["bc", "read_cnt"]
bcs = bcs[bcs.read_cnt > threshold].copy()
bcs = bcs.sort_values(by="bc", ascending=False)
with open(fasta_file, "w") as f:
for bc in bcs.bc:
f.write(f">{bc}\n")
f.write(f"{bc}\n")
def processing_matching(indir, sample, AS_min=12):
all_AS = []
all_pairs = []
samfile = pysam.AlignmentFile(f"{indir}/{sample}/{sample}_matching.sam", "rb")
matched_csv = f"{indir}/{sample}/{sample}_matching_raw_to_tenx_passing.csv"
if os.path.isfile(matched_csv):
print(matched_csv, " exists, skip")
return
for read in samfile.fetch():
AS = read.get_tag("AS")
all_AS.append([AS, read.flag])
if read.flag == 0:
bc = read.reference_name
seq = read.query
all_pairs.append([AS, bc, seq])
print("making all_pairs DF")
all_pairs = pd.DataFrame(all_pairs)
bc = pd.read_csv(f"{indir}/{sample}/{sample}_agg_cnt_raw_bcs.csv")
bc.columns = ["bc", "read_cnt"]
all_pairs.columns = ["AS", "tenx_whitelist", "bc"]
matched = bc.merge(all_pairs, how="left", on="bc")
print("saving matching_raw_to_tenx DF")
matched.to_csv(f"{indir}/{sample}/{sample}_matching_raw_to_tenx.csv", index=None)
matched = matched[matched.AS >= AS_min].copy()
print("saving tenx_passin")
matched.to_csv(matched_csv, index=None
)
def filered_barcodes(indir, sample, max_expected_barcodes=50000, bins=100):
from scipy.ndimage import gaussian_filter1d
from scipy.signal import find_peaks
from matplotlib.backends.backend_pdf import PdfPages
print("opening raw_to_tenx_passing_AS DF")
matched = pd.read_csv(f"{indir}/{sample}/{sample}_matching_raw_to_tenx_passing.csv")
matched_sub = matched[["read_cnt", "tenx_whitelist"]]
matched_sub_grouped = matched_sub.groupby("tenx_whitelist").sum()
qc_pdf_file = f"{indir}/{sample}/{sample}_QC.pdf"
#if os.path.isfile(qc_pdf_file):
# print(qc_pdf_file, " exists, skip")
#else:
qc_pdfs = PdfPages(qc_pdf_file)
agg_bcs = matched_sub_grouped.sort_values(by="read_cnt", ascending=False)
agg_bcs["log10_read_cnt"] = np.log10(agg_bcs.read_cnt)
# select top max_bc except first 100
sub = agg_bcs.iloc[20:max_expected_barcodes].copy()
# fit a histogram
x = np.histogram(sub.log10_read_cnt, bins)
# smooth histogram
smooth = gaussian_filter1d(x[0], 3)
# find the local minimum
peak_idx, _ = find_peaks(-smooth)
# take the mid point of point before and after
print(peak_idx, x[1][:-1][peak_idx])
mean_hist = (x[1][1:][peak_idx] + x[1][:-1][peak_idx]) / 2
# take the last value in list of local minima (could be more than one)
mean_hist = mean_hist[-1]
print(f"filtering for final whitelist with min log10={round(mean_hist,4)} counts")
wl_df = agg_bcs[agg_bcs.log10_read_cnt >= mean_hist].copy()
wl_df.to_csv(f"{indir}/{sample}/{sample}_whitelist.csv")
# wl_reads=wl_df.read_cnt.sum()
matched_filtered = matched[matched.tenx_whitelist.isin(wl_df.index)].copy()
print("saving raw_to_tenx_whitelist")
matched_filtered.to_csv(
f"{indir}/{sample}/{sample}_raw_to_tenx_whitelist.csv", index=None
)
white_list_size = wl_df.shape[0]
print("plotting rankplot and histogram of 10x matched read counts")
plt.figure(figsize=(4, 3))
log10_ranks = np.log10(np.arange(1, len(agg_bcs) + 1))
log10_cnts = agg_bcs.log10_read_cnt
plt.plot(log10_ranks, log10_cnts) # ,label='Rank Plot of Reads')
plt.xlabel("Log10 Ranks")
plt.ylabel("Log10 Read Counts")
reads_in_wh = round(wl_df.read_cnt.sum()/1e6,1)
matche_reads = round(agg_bcs.read_cnt.sum()/1e6,1)
print(reads_in_wh,matche_reads,reads_in_wh/matche_reads*100)
plt.title(f"{sample}\n {white_list_size} white listed")
plt.plot(
[0, log10_ranks[-1]],
[mean_hist, mean_hist],
linewidth=1,
label="log10 threshold",
c="tab:green",
)
log10_wl = np.log10(white_list_size)
plt.plot(
[log10_wl, log10_wl],
[log10_cnts.min(), log10_cnts.max()],
linewidth=1,
label="log10 size",
c="tab:orange",
)
plt.legend(loc="best")
qc_pdfs.savefig(bbox_inches="tight")
plt.figure(figsize=(4, 3))
plt.plot(x[1][:-1], x[0], label="Raw Histogram")
plt.plot(x[1][:-1], smooth, label="Gaussian Smoothed")
plt.xlabel("Log10 Read Counts")
plt.ylabel("Bin Height")
plt.title(f"{sample}\n in_whitelist={reads_in_wh}m \n bc_matched={matche_reads}m")
plt.plot(
[mean_hist, mean_hist],
[0, np.max(x[0])],
linewidth=2,
label="Whitelist Threshold",
)
plt.legend(loc="best")
qc_pdfs.savefig(bbox_inches="tight")
plt.figure(figsize=(4, 3))
#plt.hist(sub.log10_read_cnt, 100);
sns.histplot(sub.log10_read_cnt,bins=bins);
plt.title(f"{sample}\n")
qc_pdfs.savefig(bbox_inches="tight")
qc_pdfs.close()
def split_bcs_to_batches(indir, sample):
bcs = pd.read_csv(f"{indir}/{sample}/{sample}_whitelist.csv", index_col=0)
sub_batch_N = int(bcs.read_cnt.sum()/1e6/15)
print(f'total batches of 15m reads {sub_batch_N}')
# Initialize N batches and their sums
batches = [[] for _ in range(sub_batch_N)]
batch_sums = [0] * sub_batch_N
# Distribute numbers to batches based on value, but store original indices
for index, number in enumerate(bcs["read_cnt"]):
# Find the batch with the minimum sum
min_batch_index = batch_sums.index(min(batch_sums))
# Add the index to this batch
batches[min_batch_index].append(index)
# Update the batch sum with the number's value
batch_sums[min_batch_index] += number
bc_batches = []
for b in batches:
print(len(b), bcs.iloc[b]["read_cnt"].sum())
bc_batches.append(bcs.iloc[b].index.tolist())
with open(f"{indir}/{sample}/{sample}_whitelist_batches.json", "w") as file:
json.dump(bc_batches, file)
def save_quad_batch_json(indir, sample, part, context, limit):
dir_split = f"{indir}/{sample}/split"
meth_file = f"{dir_split}/output_{part}/{context}_{sample}_R1.part_{part}_clean_bismark_bt2_pe.txt.gz"
batch = str(1).zfill(3)
batch_json = f"{dir_split}/quads_part_{part}_batch_{batch}_{context}.json"
if os.path.isfile(batch_json):
print(batch_json, " exists, skip")
# return
matching_csv = pd.read_csv(f"{indir}/{sample}/{sample}_raw_to_tenx_whitelist.csv")
raw_to_tenx = dict(zip(matching_csv.bc, matching_csv.tenx_whitelist))
with open(f"{indir}/{sample}/{sample}_whitelist_batches.json", "r") as file:
bc_splits = json.load(file)
sub_batch_N = len(bc_splits)
quad_dict = {}
conversion = False
if context == "Non_CpG_context":
conversion = True
Non_CpG_to_CpG_dict = {"x": "z", "h": "z", "X": "Z", "H": "Z"}
all_failed_bc = []
i = 0
with gzip.open(meth_file, "rt") as f:
for line in f:
i += 1
split_line = line.strip().split("\t")
# print(split_line)
if conversion:
split_line[-1] = Non_CpG_to_CpG_dict[split_line[-1]]
# print('converted', split_line)
# raw_bc = split_line[0].split(':')[0] # sciMET fastqs
raw_bc = split_line[0].split("_")[-1] # raw bc added to name fastqs
if raw_bc in raw_to_tenx:
matched_bc = raw_to_tenx[raw_bc]
quad_dict_store(quad_dict, matched_bc, "_".join(split_line[-3:]))
else:
all_failed_bc.append(raw_bc)
if i > N_read_extract and limit:
break
print(len(all_failed_bc))
for j in range(sub_batch_N):
batch = str(j + 1).zfill(3)
batch_json = f"{dir_split}/quads_part_{part}_batch_{batch}_{context}.json"
sub_agg = {}
for a in bc_splits[j]:
if a in quad_dict:
sub_agg[a] = quad_dict[a]
with open(batch_json, "w") as json_file:
json.dump(sub_agg, json_file)
def save_quad_batch_from_bam(indir, sample, part, limit):
dir_split = f"{indir}/{sample}/split"
suffix = "clean_trim_bismark_bt2_pe.nonCG_filtered.bam"
#suffix = "clean_trim_bismark_bt2_pe.bam"
bam_file = f"{dir_split}/output_{part}/{sample}_R1.part_{part}_{suffix}"
bias_meth_file = (
f"{dir_split}/output_{part}/{sample}_part_{part}_bias_methylation.csv"
)
if os.path.isfile(bias_meth_file):
print(bias_meth_file, " exists, skip")
# return
matching_csv = pd.read_csv(f"{indir}/{sample}/{sample}_raw_to_tenx_whitelist.csv")
raw_to_tenx = dict(zip(matching_csv.bc, matching_csv.tenx_whitelist))
with open(f"{indir}/{sample}/{sample}_whitelist_batches.json", "r") as file:
bc_splits = json.load(file)
sub_batch_N = len(bc_splits)
R1_meth_dict = {}
R2_meth_dict = {}
context_conversion = {"x": "z", "h": "z", "X": "Z", "H": "Z"}
quad_dict_CpG = {}
quad_dict_Non_CpG = {}
total_failed_reads = 0
diffs = []
# frags = {}
bam = pysam.AlignmentFile(bam_file, "r")
start_time = time.time()
total_reads = 0
for read in bam.fetch(until_eof=True):
total_reads += 1
# frag_size = read.template_length
chrom = read.reference_name
if read.is_reverse:
meth = read.get_tag("XM")[::-1]
chrom_pos = read.get_reference_positions()[::-1]
else:
meth = read.get_tag("XM")
chrom_pos = read.get_reference_positions()
r1_left_clip = 15
r1_right_clip = 2
r2_left_clip = 2
r2_right_clip = 15
r1_trim_after = 150
r2_trim_after = 1000
if read.is_read1: # mean it's R2
meth = meth[r2_left_clip:-r2_right_clip][:r2_trim_after]
chrom_pos = chrom_pos[r2_left_clip:-r2_right_clip][:r2_trim_after]
string_position_count(meth, R2_meth_dict)
else:
meth = meth[r1_left_clip:-r1_right_clip][:r1_trim_after]
chrom_pos = chrom_pos[r1_left_clip:-r1_right_clip][:r1_trim_after]
string_position_count(meth, R1_meth_dict)
if len(chrom_pos) != len(meth):
diff = len(chrom_pos) - len(meth)
diffs.append(diff)
# print()
# break
# if diff<-10:
# print(read.cigar,diff,len(read.get_tag('XM')),len(read.get_reference_positions()))
# break
else:
raw_bc = read.qname.split("_")[-2]
if raw_bc in raw_to_tenx:
matched_bc = raw_to_tenx[raw_bc]
for i, char in enumerate(meth):
if char in ["H", "X", "x", "h"]:
quad_dict_store(
quad_dict_Non_CpG,
matched_bc,
f"{chrom}_{chrom_pos[i]+1}_{context_conversion[char]}",
)
elif char in ["z", "Z"]:
quad_dict_store(
quad_dict_CpG,
matched_bc,
f"{chrom}_{chrom_pos[i]+1}_{char}",
)
else:
total_failed_reads += 1
if total_reads % N_interval_log == 0:
elapsed_time = time.time() - start_time
print(f"Processed {total_reads} reads in {elapsed_time:.2f} seconds.", flush=True)
if total_reads > N_read_extract and limit:
break
print("total bc fail reads = ", total_failed_reads, "total reads = ", total_reads)
context = "Non_CpG_context"
for j in range(sub_batch_N):
batch = str(j + 1).zfill(3)
batch_json = f"{dir_split}/quads_part_{part}_batch_{batch}_{context}.json"
sub_agg = {}
for a in bc_splits[j]:
if a in quad_dict_Non_CpG:
sub_agg[a] = quad_dict_Non_CpG[a]
with open(batch_json, "w") as json_file:
json.dump(sub_agg, json_file)
context = "CpG_context"
for j in range(sub_batch_N):
batch = str(j + 1).zfill(3)
batch_json = f"{dir_split}/quads_part_{part}_batch_{batch}_{context}.json"
sub_agg = {}
for a in bc_splits[j]:
if a in quad_dict_CpG:
sub_agg[a] = quad_dict_CpG[a]
with open(batch_json, "w") as json_file:
json.dump(sub_agg, json_file)
R1_meth_df = quality_df(R1_meth_dict)
R2_meth_df = quality_df(R2_meth_dict)
R1_meth_df.to_csv(bias_meth_file.replace("_bias_", "_R1_"), index=None)
R2_meth_df.to_csv(bias_meth_file.replace("_bias_", "_R2_"), index=None)
all_dfs = []
for r, df in enumerate([R1_meth_df, R2_meth_df]):
for context in ["X", "Z", "H"]:
h_count = (
df[df.quantity.isin([context.lower(), context])]
.groupby("position")
.sum()
)
h_count_meth = df[df.quantity == context].groupby("position").sum()
meth_frac = h_count_meth.total_cnt / h_count.total_cnt
meth_frac = meth_frac.reset_index()
meth_frac["read"] = f"{r+1}_{context}"
all_dfs.append(meth_frac)
all_dfs = pd.concat(all_dfs)
all_dfs = all_dfs.reset_index()
all_dfs.total_cnt = all_dfs.total_cnt * 100