-
Notifications
You must be signed in to change notification settings - Fork 1
/
methphasing
executable file
·1471 lines (1386 loc) · 55.8 KB
/
methphasing
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 python
from pkg_resources import require
import pysam
import re
import warnings
import argparse
import sys
import os
import pandas as pd
# from tqdm.auto import tqdm
from scipy import stats
from matplotlib import pyplot
from collections import Counter
import numpy as np
from pysam import VariantFile
warnings.filterwarnings("ignore")
"""
methphaser: phase reads based on methlytion informaiton
@author: Yilei Fu
@Email: [email protected], [email protected]
"""
def parse_arg(argv):
"""
Function for pasing arguments
"""
parser = argparse.ArgumentParser(
description="methphaser: phase reads based on methlytion informaiton"
)
required_args = parser.add_argument_group("Required arguments")
# input set
required_args.add_argument(
"-b",
"--bam_file",
type=str,
help="input methylation annotated bam file",
required=True,
metavar="",
)
required_args.add_argument(
"-r",
"--reference",
type=str,
help="reference genome",
required=True,
metavar="",
)
required_args.add_argument(
"-p",
"--phased_blocks",
type=str,
help="gtf file from whatshap visualization",
required=True,
metavar="",
)
required_args.add_argument(
"-vc",
"--vcf_called",
type=str,
help="called vcf file from HapCUT2",
required=True,
metavar="",
)
parser.add_argument(
"-t", "--threads", type=int, help="threads, default 1", default=1, metavar=""
)
parser.add_argument(
"-vt",
"--vcf_truth",
type=str,
help="GIAB truth vcf file for benchmarking",
default="",
metavar="",
)
parser.add_argument(
"-c",
"--cut_off",
type=float,
help="the minimum percentage of vote to determine a read's haplotype, default 0.65",
default=0.65,
metavar="",
)
parser.add_argument(
"-a",
"--assignment_min",
type=int,
help="minimum assigned read number for ranksum test, default 2",
default=2,
metavar="",
)
parser.add_argument(
"-m",
"--chromosome",
type=str,
help="the chromosome for read phasing, default chr1",
default="chr1",
metavar="",
)
parser.add_argument(
"-n",
"--targeting_blocks",
type=str,
help="only process the blocks from <m, n>, for testing,, default: all",
default="all",
metavar="",
)
parser.add_argument(
"-o",
"--output_csv",
type=str,
help="comparison csv file, default: meth_truth_comparison.csv",
default="meth_truth_comparison.csv",
metavar="",
)
parser.add_argument(
"-s",
"--skipping_pair",
type=str,
help="a list of number [a, b, ...]. The program will skip the block pair of <a, a+1>, <b, b+1>, ... mainly for avoiding centromere region.",
default="[0]",
metavar="",
)
parser.add_argument(
"-k",
"--k_iterations",
type=int,
help="use at most k iterations, default: 10, use -1 for unlimited iterations",
default="10",
metavar="",
)
parser.add_argument(
"-ra",
"--read_assignment",
type=str,
help="output read assignment csv folder. The output csv will be folder/phase-block.csv",
default=None,
metavar="",
)
parser.add_argument(
"-ms",
"--max_SNPs",
type=int,
help="max SNPs number to the edge of SNP pahsed block, default is unlimited",
default=None,
metavar="",
)
parser.add_argument(
"-bo",
"--bridge_only",
type=bool,
help="bridge gaps only, do not phase reads.",
default=False,
metavar="",
)
if len(argv) == 0:
parser.print_help(sys.stderr)
sys.exit(1)
args = parser.parse_args(argv)
return args
def get_base_modification_dictionary(
bam_file, ref_seq, chromosome, phase_region, snp_phase_region
):
"""
This is for the first time phasing within SNP phased block
Return value: a dictionary that contains cpg location and its haplotype related base modification score
"""
methylation_identifier_0 = ('C', 0, 'm') # We only care about 5mc!!!
methylation_identifier_1 = ('C', 1, 'm')
phase_region_start = phase_region[0]
phase_region_end = phase_region[1]
phased_block_ref = ref_seq.fetch(
chromosome, phase_region_start, phase_region_end)
cg_loc = [
m.start(0) for m in re.finditer("CG", str(phased_block_ref))
] # Use regular expression to find all CpG locations on the reference
# record G locatioon of 'CG's
cg_loc = [x + phase_region_start + 1 for x in cg_loc]
hp_myth_dict = dict()
"""
Data structure:
{i:[[], [], [], [0, 0, 0]]}
i: CpG locations
[]: per haplotype base modification score, max 255
0: per haplotype base coverage
Use dictionary so that when querying CpG locations the time complexity is O(1)
"""
for i in cg_loc:
# build the dictionary
hp_myth_dict.update({i: [[], [], [], [0, 0, 0]]})
phased_block_alignment = bam_file.fetch(
chromosome, snp_phase_region[0], snp_phase_region[1], multiple_iterators=True
)
for reads in phased_block_alignment:
read_base_ref_loc = reads.get_reference_positions(
full_length=True
) # use full_length=True or the positions won't match
mm = (
reads.modified_bases
) # mm is a dictionary that contains {score type: [(location, score)]}. score is 255-based
HP = 0
if reads.has_tag("HP"): # update read number list
if reads.get_tag("HP") == 1:
HP = 1
for i in read_base_ref_loc:
if i in hp_myth_dict.keys(): # O(1) search
hp_myth_dict[i][3][
1
] += 1 # increase the per haplotype base coverage on each CpG locaitons
else:
HP = 2
for i in read_base_ref_loc:
if i in hp_myth_dict.keys():
hp_myth_dict[i][3][2] += 1
else:
HP = 0
for i in read_base_ref_loc:
if i in hp_myth_dict.keys():
hp_myth_dict[i][3][0] += 1
if (mm != -1) and (mm != {}): # update base modification scores list
if methylation_identifier_0 in list(mm.keys()):
methylation_identifier = methylation_identifier_0
else:
methylation_identifier = methylation_identifier_1
for i in mm[methylation_identifier]: # Remora only output one type of score: c 1 m/c 0 m, but this part can be improved for other methlyation callers
if read_base_ref_loc[i[0]]: # i format: (loc, score)
if reads.is_forward: # cg/gc on forward and reverse reads
mm_ref_loc = read_base_ref_loc[i[0]] + 1
else:
mm_ref_loc = read_base_ref_loc[i[0]]
if mm_ref_loc in hp_myth_dict.keys():
modification_chance = i[1] # 0 - 255 based
if HP == 1:
hp_myth_dict[mm_ref_loc][1].append(
modification_chance
) # add the score to the list
elif HP == 2:
hp_myth_dict[mm_ref_loc][2].append(
modification_chance)
else:
hp_myth_dict[mm_ref_loc][0].append(
modification_chance)
return hp_myth_dict
def get_modified_list(assignment_df, phase_region, sam_file, chromosome, ref_seq):
"""
Build the same dictionary as SNP phased region one,
and update this one during the iterations
difference between get_base_modification_dictionary:
different regions, different HP0 filtering
"""
methylation_identifier_0 = ('C', 0, 'm') # We only care about 5mc!!!
methylation_identifier_1 = ('C', 1, 'm')
# methylation_identifier = ('C', 0, 'm')
phase_region_start = phase_region[0]
phase_region_end = phase_region[1]
phased_block_ref = ref_seq.fetch(
chromosome, phase_region_start, phase_region_end)
cg_loc = [m.start(0) for m in re.finditer("CG", str(phased_block_ref))]
cg_loc = [x + phase_region_start + 1 for x in cg_loc]
hp_myth_dict = dict()
for i in cg_loc:
hp_myth_dict.update({i: [[], [], [], [0, 0, 0]]})
phased_block_alignment = sam_file.fetch(
chromosome, phase_region_start, phase_region_end
)
for reads in phased_block_alignment:
read_base_ref_loc = reads.get_reference_positions(full_length=True)
mm = reads.modified_bases
HP = 0
if reads.query_name in list(
assignment_df.read_id
): # which means the read was marked as HP 0 by Whatshap
read_row = assignment_df[assignment_df.read_id == reads.query_name]
read_reassign_haplotype = read_row.iloc[0].haplotype
if read_reassign_haplotype == 1:
HP = 1
for i in read_base_ref_loc:
if i in hp_myth_dict.keys():
hp_myth_dict[i][3][1] += 1
elif read_reassign_haplotype == 2:
HP = 2
for i in read_base_ref_loc:
if i in hp_myth_dict.keys():
hp_myth_dict[i][3][2] += 1
else:
HP = 0
for i in read_base_ref_loc:
if i in hp_myth_dict.keys():
hp_myth_dict[i][3][0] += 1
if mm != -1 and mm != {} :
if methylation_identifier_0 in list(mm.keys()):
methylation_identifier = methylation_identifier_0
else:
methylation_identifier = methylation_identifier_1
for i in mm[methylation_identifier]:
if read_base_ref_loc[i[0]]:
if reads.is_forward:
mm_ref_loc = read_base_ref_loc[i[0]] + 1
else:
mm_ref_loc = read_base_ref_loc[i[0]]
if mm_ref_loc in hp_myth_dict.keys():
modification_chance = i[1]
if HP == 1:
hp_myth_dict[mm_ref_loc][1].append(
modification_chance)
elif HP == 2:
hp_myth_dict[mm_ref_loc][2].append(
modification_chance)
else:
hp_myth_dict[mm_ref_loc][0].append(
modification_chance)
return hp_myth_dict
def build_df(previous_assignment_df, hp_list):
for i in hp_list:
if i[0] not in list(previous_assignment_df.read_id):
previous_assignment_df.loc[len(previous_assignment_df.index)] = i
else:
previous_assignment_df[previous_assignment_df.read_id == i[0]] = i
return previous_assignment_df
def get_base_modification_list(
bam_file,
ref_seq,
chromosome,
phase_region,
hp_base_modification_probablity,
previous_assignment_df,
assignmet_threshold,
assignment_min_number,
):
"""
This funciton takes the CpG locations' hp based base modificaiton score dictionary as input
outputs a dataframe that have read assignment information.
This function is included in the iterations.
args:
phase_region: extended regions for read phasing
outputs:
"""
# methylation_identifier = ('C', 0, 'm')
methylation_identifier_0 = ('C', 0, 'm') # We only care about 5mc!!!
methylation_identifier_1 = ('C', 1, 'm')
phase_region_start = phase_region[0]
phase_region_end = phase_region[1]
phased_block_alignment = bam_file.fetch(
chromosome, phase_region_start, phase_region_end, multiple_iterators=True
)
assignment_list = []
previous_assignment_df_hp_0 = previous_assignment_df[
previous_assignment_df.haplotype == 0
] # get all un-assigned reads from previous iterations
for reads in phased_block_alignment:
if reads.query_name in list(previous_assignment_df_hp_0.read_id):
hp_0_probablity = dict() # init a new dictionary to store the
read_base_ref_loc = reads.get_reference_positions(full_length=True)
read_base_ref_loc_aligned = reads.get_reference_positions(
full_length=False
) # For display
mm = reads.modified_bases
read_length = reads.query_length
if mm != -1 and mm != {}:
if methylation_identifier_0 in list(mm.keys()):
methylation_identifier = methylation_identifier_0
else:
methylation_identifier = methylation_identifier_1
for i in mm[methylation_identifier]:
if read_base_ref_loc[i[0]]:
if reads.is_forward:
mm_ref_loc = read_base_ref_loc[i[0]] + 1
else:
mm_ref_loc = read_base_ref_loc[i[0]]
if mm_ref_loc in hp_base_modification_probablity.keys():
modification_chance = i[1] / 255
hp_1_prob = hp_base_modification_probablity[mm_ref_loc][0]
hp_2_prob = hp_base_modification_probablity[mm_ref_loc][1]
assignment = 0
if hp_1_prob != None and hp_2_prob != None:
if abs(hp_1_prob - modification_chance) > abs(
hp_2_prob - modification_chance
):
assignment = 2
elif abs(hp_1_prob - modification_chance) < abs(
hp_2_prob - modification_chance
):
assignment = 1
probablity_result = hp_base_modification_probablity[
mm_ref_loc
] + [modification_chance, assignment]
hp_0_probablity.update(
{mm_ref_loc: probablity_result})
assignment_df = pd.DataFrame.from_dict(
hp_0_probablity,
orient="index",
columns=[
"hp_1_prob",
"hp_2_prob",
"p-value",
"hp_0_prob",
"assignment",
],
)
# final_assignment_df.append(assignment_df)
if len(assignment_df) == 0:
assignment_list.append(
[
reads.query_name,
read_length,
phase_region_start,
read_base_ref_loc_aligned[0],
read_base_ref_loc_aligned[-1],
0,
None,
len(assignment_df),
None,
]
)
elif len(assignment_df) <= assignment_min_number:
if len(assignment_df[assignment_df.assignment == 1]) / len(
assignment_df
) >= len(assignment_df[assignment_df.assignment == 2]) / len(
assignment_df
):
assignment_list.append(
[
reads.query_name,
read_length,
phase_region_start,
read_base_ref_loc_aligned[0],
read_base_ref_loc_aligned[-1],
0,
len(assignment_df[assignment_df.assignment == 1]),
len(assignment_df),
len(assignment_df[assignment_df.assignment == 1])
/ len(assignment_df),
]
)
else:
assignment_list.append(
[
reads.query_name,
read_length,
phase_region_start,
read_base_ref_loc_aligned[0],
read_base_ref_loc_aligned[-1],
0,
len(assignment_df[assignment_df.assignment == 2]),
len(assignment_df),
len(assignment_df[assignment_df.assignment == 2])
/ len(assignment_df),
]
)
continue
elif (
len(assignment_df[assignment_df.assignment == 1])
/ len(assignment_df)
>= assignmet_threshold
):
assignment_list.append(
[
reads.query_name,
read_length,
phase_region_start,
read_base_ref_loc_aligned[0],
read_base_ref_loc_aligned[-1],
1,
len(assignment_df[assignment_df.assignment == 1]),
len(assignment_df),
len(assignment_df[assignment_df.assignment == 1])
/ len(assignment_df),
]
)
elif (
len(assignment_df[assignment_df.assignment == 2])
/ len(assignment_df)
>= assignmet_threshold
):
assignment_list.append(
[
reads.query_name,
read_length,
phase_region_start,
read_base_ref_loc_aligned[0],
read_base_ref_loc_aligned[-1],
2,
len(assignment_df[assignment_df.assignment == 2]),
len(assignment_df),
len(assignment_df[assignment_df.assignment == 2])
/ len(assignment_df),
]
)
else:
if len(assignment_df[assignment_df.assignment == 1]) / len(
assignment_df
) >= len(assignment_df[assignment_df.assignment == 2]) / len(
assignment_df
):
assignment_list.append(
[
reads.query_name,
read_length,
phase_region_start,
read_base_ref_loc_aligned[0],
read_base_ref_loc_aligned[-1],
0,
len(assignment_df[assignment_df.assignment == 1]),
len(assignment_df),
len(assignment_df[assignment_df.assignment == 1])
/ len(assignment_df),
]
)
else:
assignment_list.append(
[
reads.query_name,
read_length,
phase_region_start,
read_base_ref_loc_aligned[0],
read_base_ref_loc_aligned[-1],
0,
len(assignment_df[assignment_df.assignment == 2]),
len(assignment_df),
len(assignment_df[assignment_df.assignment == 2])
/ len(assignment_df),
]
)
continue
return build_df(previous_assignment_df, assignment_list)
def get_base_modification_list_snp_block(
bam_file,
ref_seq,
chromosome,
phase_region,
hp_base_modification_probablity,
previous_assignment_df,
assignmet_threshold,
assignment_min_number,
):
"""
Assign reads.
- Get reads' CpGs' base modification probablity
- Collect votes
"""
# methylation_identifier = ('C', 0, 'm')
methylation_identifier_0 = ('C', 0, 'm') # We only care about 5mc!!!
methylation_identifier_1 = ('C', 1, 'm')
phase_region_start = phase_region[0]
phase_region_end = phase_region[1]
phased_block_alignment = bam_file.fetch(
chromosome, phase_region_start, phase_region_end, multiple_iterators=True
)
assignment_list = []
for reads in phased_block_alignment:
if (
reads.has_tag("HP")
) == False: # Does not have hp tag means it's SNP unphased read
hp_0_probablity = dict()
read_base_ref_loc = reads.get_reference_positions(full_length=True)
read_base_ref_loc_aligned = reads.get_reference_positions(
full_length=False)
mm = reads.modified_bases
read_length = reads.query_length
if mm != -1 and mm != {}:
if methylation_identifier_0 in list(mm.keys()):
methylation_identifier = methylation_identifier_0
else:
methylation_identifier = methylation_identifier_1
for i in mm[methylation_identifier]:
if read_base_ref_loc[i[0]]:
if reads.is_forward:
mm_ref_loc = read_base_ref_loc[i[0]] + 1
else:
mm_ref_loc = read_base_ref_loc[i[0]]
if mm_ref_loc in hp_base_modification_probablity.keys():
modification_chance = (
i[1] / 255
) # The modificaiton score / 255, per read
hp_1_prob = hp_base_modification_probablity[mm_ref_loc][0]
hp_2_prob = hp_base_modification_probablity[mm_ref_loc][1]
assignment = 0
if hp_1_prob != None and hp_2_prob != None:
# determine the probablity is closer to which
if abs(hp_1_prob - modification_chance) > abs(
hp_2_prob - modification_chance
):
assignment = 2
elif abs(hp_1_prob - modification_chance) < abs(
hp_2_prob - modification_chance
):
assignment = 1
probablity_result = hp_base_modification_probablity[
mm_ref_loc
] + [
modification_chance,
assignment,
] # see dataframe column
hp_0_probablity.update(
{mm_ref_loc: probablity_result})
assignment_df = pd.DataFrame.from_dict(
hp_0_probablity,
orient="index",
columns=[
"hp_1_prob",
"hp_2_prob",
"p-value",
"hp_0_prob",
"assignment",
],
)
# final_assignment_df.append(assignment_df)
if len(assignment_df) == 0:
assignment_list.append(
[
reads.query_name,
read_length,
phase_region_start,
read_base_ref_loc_aligned[0],
read_base_ref_loc_aligned[-1],
0,
None,
len(assignment_df),
None,
]
)
# the haplotype coverage is not enough
elif len(assignment_df) <= assignment_min_number:
if len(assignment_df[assignment_df.assignment == 1]) / len(
assignment_df
) >= len(assignment_df[assignment_df.assignment == 2]) / len(
assignment_df
):
assignment_list.append(
[
reads.query_name,
read_length,
phase_region_start,
read_base_ref_loc_aligned[0],
read_base_ref_loc_aligned[-1],
0, # The haplotypes are lesser than required number, so add 0
len(assignment_df[assignment_df.assignment == 1]),
len(assignment_df),
len(assignment_df[assignment_df.assignment == 1])
/ len(assignment_df),
]
)
else:
assignment_list.append(
[
reads.query_name,
read_length,
phase_region_start,
read_base_ref_loc_aligned[0],
read_base_ref_loc_aligned[-1],
0,
len(assignment_df[assignment_df.assignment == 2]),
len(assignment_df),
len(assignment_df[assignment_df.assignment == 2])
/ len(assignment_df),
]
)
continue
elif (
len(assignment_df[assignment_df.assignment == 1])
/ len(assignment_df)
>= assignmet_threshold
): # enough haplotype coverage, calculate the vote
assignment_list.append(
[
reads.query_name,
read_length,
phase_region_start,
read_base_ref_loc_aligned[0],
read_base_ref_loc_aligned[-1],
1, # assign the haplotype
len(assignment_df[assignment_df.assignment == 1]),
len(assignment_df),
len(assignment_df[assignment_df.assignment == 1])
/ len(assignment_df),
]
)
elif (
len(assignment_df[assignment_df.assignment == 2])
/ len(assignment_df)
>= assignmet_threshold
):
assignment_list.append(
[
reads.query_name,
read_length,
phase_region_start,
read_base_ref_loc_aligned[0],
read_base_ref_loc_aligned[-1],
2,
len(assignment_df[assignment_df.assignment == 2]),
len(assignment_df),
len(assignment_df[assignment_df.assignment == 2])
/ len(assignment_df),
]
)
else:
if len(assignment_df[assignment_df.assignment == 1]) / len(
assignment_df
) >= len(assignment_df[assignment_df.assignment == 2]) / len(
assignment_df
):
assignment_list.append(
[
reads.query_name,
read_length,
phase_region_start,
read_base_ref_loc_aligned[0],
read_base_ref_loc_aligned[-1],
0,
len(assignment_df[assignment_df.assignment == 1]),
len(assignment_df),
len(assignment_df[assignment_df.assignment == 1])
/ len(assignment_df),
]
)
else:
assignment_list.append(
[
reads.query_name,
read_length,
phase_region_start,
read_base_ref_loc_aligned[0],
read_base_ref_loc_aligned[-1],
0,
len(assignment_df[assignment_df.assignment == 2]),
len(assignment_df),
len(assignment_df[assignment_df.assignment == 2])
/ len(assignment_df),
]
)
continue
return build_df(previous_assignment_df, assignment_list)
def get_siginificant_probablity_dict(hp_myth_dict, hp_myth_list_new={}, hp_min_num=3):
"""
This function takes base modificaiton score list as input, output a dict that
also contains base modification probablity with SNP unphased reads
In this function, we perform ranksum test
data structure: {i:[hp_1_prob, hp_2_prob, p-value]}
i: CpG locations
hp_1/2_prob = sum(base modification score)/(per-base per-haplotype coverage)
p-value: calculated with scipy package
args:
hp_myth_list_new: the base modificaiton list from last iteration
hp_myth_dict: format
{
location: ([[hp0_scores], [hp1_scores], [hp2_scores], [hp0_read_n, hp1_read_n, hp2_read_n]] )
}
outputs:
hp_base_modification_probablity: a dictionary that contians the locations where the 2 hps have siginificant
different behaves
"""
hp_base_modification_probablity = dict()
for index, (location, modifications) in enumerate(hp_myth_dict.items()): # see args
# the aggregated score of hp1
hp_1_probablity_sum = sum(modifications[1])
hp_2_probablity_sum = sum(modifications[2])
hp_1_new_num = 0
hp_2_new_num = 0
hps = [[], [], []]
if (
location in hp_myth_list_new.keys()
): # new and old should have the same index (CpG locations)
hps = hp_myth_list_new[location]
# the aggregated score of hp1
hp_1_probablity_sum_new = sum(hps[1])
hp_1_probablity_sum += hp_1_probablity_sum_new # old + new
hp_2_probablity_sum_new = sum(hps[2])
hp_2_probablity_sum += hp_2_probablity_sum_new
# hp_1_new_num = hps[3][1] # new read number
# hp_2_new_num = hps[3][2]
# hp_1_num = modifications[3][1] + hp_1_new_num
# hp_2_num = modifications[3][2] + hp_2_new_num
h1_full_list = modifications[1] + hps[1]
h2_full_list = modifications[2] + hps[2]
if (len(h1_full_list) >= hp_min_num) and (
len(h2_full_list) >= hp_min_num
): # enough hp info in this location
hp_1_probablity = hp_1_probablity_sum / (255 * len(h1_full_list))
hp_2_probablity = hp_2_probablity_sum / (255 * len(h2_full_list))
ttest_value = stats.ranksums(
h1_full_list, h2_full_list
) # Do a ranksums test of two hp score lists
if (
ttest_value.pvalue < 0.05
): # if two score sets are significantly different
# if abs(hp_1_probablity-hp_2_probablity) >= 0.5:
hp_base_modification_probablity.update(
{
location: [
hp_1_probablity,
hp_2_probablity,
ttest_value.pvalue,
# abs(hp_1_probablity-hp_2_probablity)
]
}
)
return hp_base_modification_probablity
def get_assignment_max(
chromosome,
tagged_bam,
ref_seq,
phased_region_l,
snp_phased_region_l,
hp_threshold,
assignment_threshold,
k_iterations,
):
'''
The main function of the program: assign reads and assign relationships between phased blocks.
'''
all_not_assigned_reads_increasing_dict = {}
hp0_assignment_df_dict = {}
modif_d = {}
hp_prob_d = {}
assignment_d = {}
if k_iterations == -1:
k_iterations = float("inf")
for index, phased_regions in enumerate(phased_region_l):
# test
modif_l = []
hp_prob_l = []
assignment_list = []
not_assigned_reads_list = []
increasing_assigned_num = float("inf")
cnt = 0
hp0_cnt = float("inf")
hp0_cnt_new = 0
modified_list = {}
assignment_df = pd.DataFrame(
columns=[
"read_id",
"read_len",
"phase_block",
"ref_start",
"ref_end",
"haplotype",
"hp_supportring_cgs",
"total_cgs",
"voting",
]
)
# only add snp phased region first
cnt += 1
snp_phased_region = snp_phased_region_l[index] # get snp phased block
# print(
# f"processing phased region:{snp_phased_region[0]}-{snp_phased_region[1]}, iteration {cnt}",
# end="\r",
# )
base_modification_list = get_base_modification_dictionary( # build the dictionary with snp phased reads
tagged_bam, ref_seq, chromosome, phased_regions, snp_phased_region
)
hp_base_modification_prob = get_siginificant_probablity_dict( # calculate the statistically significantly different CpGs
base_modification_list, modified_list, hp_min_num=hp_threshold
)
assignment_df = get_base_modification_list_snp_block(
tagged_bam,
ref_seq,
chromosome,
phased_regions,
hp_base_modification_prob,
assignment_df,
assignment_threshold,
hp_threshold,
)
modified_list = get_modified_list(
assignment_df, phased_regions, tagged_bam, chromosome, ref_seq
)
hp0_cnt_new = len(assignment_df[assignment_df.haplotype == 0])
increasing_assigned_num = hp0_cnt_new - hp0_cnt
hp0_cnt = hp0_cnt_new
not_assigned_reads_list.append(hp0_cnt)
while (increasing_assigned_num < 0) and (cnt <= k_iterations):
'''
start the iteration
'''
modif_l.append(modified_list)
hp_prob_l.append(hp_base_modification_prob)
assignment_list.append(assignment_df)
cnt += 1
# print(
# f"processing unphased region:{phased_regions[0]}-{phased_regions[1]}, iteration {cnt}",
# end="\r",
# )
hp_base_modification_prob = get_siginificant_probablity_dict(
base_modification_list, modified_list, hp_min_num=hp_threshold
)
assignment_df = get_base_modification_list(
tagged_bam,
ref_seq,
chromosome,
phased_regions,
hp_base_modification_prob,
assignment_df,
assignment_threshold,
hp_threshold,
)
modified_list = get_modified_list(
assignment_df, phased_regions, tagged_bam, chromosome, ref_seq
)
hp0_cnt_new = len(assignment_df[assignment_df.haplotype == 0])
increasing_assigned_num = hp0_cnt_new - hp0_cnt
# print(
# f"increasing hp assignment: {hp0_cnt_new} - {hp0_cnt} = {increasing_assigned_num}",
# end="\r",
# )
hp0_cnt = hp0_cnt_new
not_assigned_reads_list.append(hp0_cnt)
assignment_list.append(assignment_df)
modif_l.append(modified_list)
hp_prob_l.append(hp_base_modification_prob)
modif_d.update({index: modif_l})
hp_prob_d.update({index: hp_prob_l})
assignment_d.update({index: assignment_list})
all_not_assigned_reads_increasing_dict.update(
{phased_regions: not_assigned_reads_list}
)
hp0_assignment_df_dict.update({phased_regions: assignment_df})
return (
all_not_assigned_reads_increasing_dict,
hp0_assignment_df_dict,
modif_d,
hp_prob_d,
assignment_d,
)
'''
Benchmarking functions
'''
def get_overlap_reads_df(region_1, region_2, assignment_df):
df1 = assignment_df[region_1]
df2 = assignment_df[region_2]
df2_overlap = df2[df2.read_id.isin(df1.read_id)]
another_hap = []
for i in df2_overlap.read_id:
another_hap.append(df1[df1.read_id == i].iloc[0].haplotype)
df2_overlap["haplotype_in_connected_block"] = another_hap
overlap_df = df2_overlap[
(df2_overlap.haplotype != 0) & (
df2_overlap.haplotype_in_connected_block != 0)
]
same_assignment_num = len(