-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathclasses.py
More file actions
1428 lines (1281 loc) · 64 KB
/
classes.py
File metadata and controls
1428 lines (1281 loc) · 64 KB
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 bisect
import sys
from functools import total_ordering
import math
from collections import Counter
from scipy import interpolate
from scipy import spatial
import numpy as np
import copy
import random
# enum for haplotypes
class Haplotypes:
minus_infinity = -3
conflict = -2
unknown = -1
paternal = 0
maternal = 1
infinity = 2
def is_known_haplotype(haplotype):
return haplotype >= 0
# the operations below will set "." for all unphased haplotypes
def haplotype_to_string(haplotype):
return str(haplotype) if is_known_haplotype(haplotype) else "."
def string_to_haplotype(haplotype_string):
return Haplotypes.unknown if haplotype_string == "." else int(haplotype_string)
def known_haplotypes():
yield Haplotypes.paternal
yield Haplotypes.maternal
def homologous_haplotype(haplotype):
if haplotype == Haplotypes.paternal:
return Haplotypes.maternal
elif haplotype == Haplotypes.maternal:
return Haplotypes.paternal
return None
def ref_name_haplotype_to_hom_name(ref_name_haplotype):
return ref_name_haplotype[0] + "(" + ("pat" if ref_name_haplotype[1] == Haplotypes.paternal else "mat") + ")"
def hom_name_to_ref_name_haplotype(hom_name):
ref_name, haplotype = hom_name.split("(")
haplotype = haplotype.strip(")")
haplotype = Haplotypes.paternal if haplotype == "pat" else Haplotypes.maternal
return (ref_name, haplotype)
def homologous_ref_name_haplotype(ref_name_haplotype):
ref_name = ref_name_haplotype[0]
haplotype = homologous_haplotype(ref_name_haplotype[1])
return (ref_name, haplotype)
def homologous_hom_name(hom_name):
return ref_name_haplotype_to_hom_name(homologous_ref_name_haplotype(hom_name_to_ref_name_haplotype(hom_name)))
# rules for updating one haplotype with another (merging)
def update_haplotype(haplotype_1, haplotype_2):
if haplotype_1 == haplotype_2:
return haplotype_1
elif haplotype_1 == Haplotypes.unknown:
return haplotype_2
elif haplotype_2 == Haplotypes.unknown:
return haplotype_1
return Haplotypes.conflict
# a read segment (alignment)
@total_ordering
class Seg:
def __init__(self, is_read2, query_start, query_end, ref_name, ref_start, ref_end, is_reverse, haplotype = Haplotypes.unknown):
self.is_read2 = is_read2
self.query_start = query_start
self.query_end = query_end
self.ref_name = ref_name
self.ref_start = ref_start
self.ref_end = ref_end
self.is_reverse = is_reverse
self.haplotype = haplotype # if not given, default is unknown
# order: from left to right on the fragment
# namely, read 1 before read 2
# on read 1, order by left side
# on read 2, order by minus right side
def __lt__(self, other):
return (self.is_read2, (-self.query_end if self.is_read2 else self.query_start)) < (other.is_read2, (-other.query_end if other.is_read2 else other.query_start))
def __eq__(self, other):
return (self.is_read2, (-self.query_end if self.is_read2 else self.query_start)) == (other.is_read2, (-other.query_end if other.is_read2 else other.query_start))
def update_haplotype(self, is_read2, ref_name, ref_locus, haplotype):
if self.is_read2 == is_read2 and self.ref_name == ref_name and ref_locus - 1 >= self.ref_start and ref_locus <= self.ref_end:
self.haplotype = update_haplotype(self.haplotype, haplotype)
def is_phased(self):
return is_known_haplotype(self.haplotype)
# output mapped loci of the left and right ends (ordered based on fragment)
def ref_left(self):
if self.is_read2 == self.is_reverse:
return self.ref_start
return self.ref_end
def ref_right(self):
if self.is_read2 == self.is_reverse:
return self.ref_end
return self.ref_start
def set_ref_left(self, ref_left):
if self.is_read2 == self.is_reverse:
self.ref_start = ref_left
else:
self.ref_end = ref_left
def set_ref_right(self, ref_right):
if self.is_read2 == self.is_reverse:
self.ref_end = ref_right
else:
self.ref_start = ref_right
def to_con_with(self, other):
return Con(Leg(self.ref_name, self.ref_right(), self.haplotype), Leg(other.ref_name, other.ref_left(), other.haplotype))
def to_string(self): # "m" is for mate
return ",".join(["m" if self.is_read2 else ".", str(self.query_start), str(self.query_end), self.ref_name, str(self.ref_start), str(self.ref_end), "-" if self.is_reverse else "+", haplotype_to_string(self.haplotype)])
# create a segment from a string ("." will be set to unknown)
def string_to_seg(seg_string):
is_read2, query_start, query_end, ref_name, ref_start, ref_end, is_reverse, haplotype = seg_string.split(",")
is_read2 = True if is_read2 == "m" else False
query_start = int(query_start)
query_end = int(query_end)
ref_start = int(ref_start)
ref_end = int(ref_end)
is_reverse = True if is_reverse == "-" else False
haplotype = string_to_haplotype(haplotype)
return Seg(is_read2, query_start, query_end, ref_name, ref_start, ref_end, is_reverse, haplotype)
# a read, containing all its segments
class Read:
def __init__(self, name):
self.name = name
self.segs = []
def add_seg(self, seg):
self.segs.append(seg)
def add_segs_from_read(self, read):
self.segs += read.segs
def num_segs(self):
return len(self.segs)
def num_phased_segs(self):
num_phased_segs = 0
for seg in self.segs:
if seg.is_phased():
num_phased_segs += 1
return num_phased_segs
def update_haplotype(self, is_read2, ref_name, ref_locus, haplotype):
for seg in self.segs:
seg.update_haplotype(is_read2, ref_name, ref_locus, haplotype)
def sort_segs(self):
self.segs.sort()
def to_con_data(self, adjacent_only):
self.sort_segs()
con_data = ConData()
for i in range(self.num_segs() - 1):
for j in range(i + 1, self.num_segs()):
if adjacent_only and j > i + 1:
break
con_data.add_con(self.segs[i].to_con_with(self.segs[j]))
return con_data
def to_string(self):
return self.name + "\t" + "\t".join([seg.to_string() for seg in self.segs])
# create a read from a string
def string_to_read(read_string):
read_string_data = read_string.split("\t")
read = Read(read_string_data[0])
for seg_string in read_string_data[1:]:
read.add_seg(string_to_seg(seg_string))
return read
# a hash map of reads (a SEG file)
class SegData:
def __init__(self):
self.reads = {}
def contains_read_name(self, name):
return name in self.reads
# add a read; merge if exists; ignore if empty
def add_read(self, read):
if read.num_segs() == 0:
return # ignore empty reads
if read.name not in self.reads: # add a new read
self.reads[read.name] = read
else: # add segments to an existing read
self.reads[read.name].add_segs_from_read(read)
# discard reads with a single segments
def clean(self):
for name in self.reads.keys():
if self.reads[name].num_segs() < 2:
del self.reads[name]
# update haplotype for a specific read, if exists
def update_haplotype(self, name, is_read2, ref_name, ref_locus, haplotype):
if name in self.reads:
self.reads[name].update_haplotype(is_read2, ref_name, ref_locus, haplotype)
def num_reads(self):
return len(self.reads)
def num_segs(self):
num_segs = 0
for read in self.reads.values():
num_segs += read.num_segs()
return num_segs
def num_phased_segs(self):
num_phased_segs = 0
for read in self.reads.values():
num_phased_segs += read.num_phased_segs()
return num_phased_segs
def to_string(self): # no tailing new line
return "\n".join(read.to_string() for read in self.reads.values())
# a leg
@total_ordering
class Leg:
def __init__(self, ref_name, ref_locus, haplotype):
self.ref_name = ref_name
self.ref_locus = ref_locus
self.haplotype = haplotype
def __repr__(self):
return self.to_string()
def __lt__(self, other):
return (self.ref_name, self.ref_locus, self.haplotype) < (other.ref_name, other.ref_locus, other.haplotype)
def __eq__(self, other):
return (self.ref_name, self.ref_locus, self.haplotype) == (other.ref_name, other.ref_locus, other.haplotype)
def __hash__(self):
return hash((self.ref_name, self.ref_locus, self.haplotype))
def get_ref_name(self):
return self.ref_name
def get_ref_locus(self):
return self.ref_locus
def get_haplotype(self):
return self.haplotype
def set_haplotype(self, haplotype):
self.haplotype = haplotype
def in_x(self, par_data):
return self.ref_name == par_data.get_x_name()
def in_y(self, par_data):
return self.ref_name == par_data.get_y_name()
def ref_name_haplotype(self):
return (self.ref_name, self.haplotype)
# a list of compatible haplotypes for imputation
def compatible_haps(self):
return [haplotype for haplotype in ([self.haplotype] if self.is_phased() else known_haplotypes())]
# a list of compatible phased legs
def compatible_legs_female(self):
return [Leg(self.ref_name, self.ref_locus, haplotype) for haplotype in ([self.haplotype] if self.is_phased() else known_haplotypes())]
def compatible_legs_male(self, par_data):
return par_data.compatible_legs_male(self)
def compatible_legs(self, is_male, par_data):
return self.compatible_legs_male(par_data) if is_male else self.compatible_legs_female()
def is_phased(self):
return is_known_haplotype(self.haplotype)
def is_conflict(self):
return self.haplotype == Haplotypes.conflict
def merge_with(self, other):
self.ref_locus = (self.ref_locus + other.ref_locus)/2
self.haplotype = update_haplotype(self.haplotype, other.haplotype)
def same_chr_with(self, other):
return self.ref_name == other.ref_name
def separation_with(self, other):
return abs(self.ref_locus - other.ref_locus)
def signed_separation_with(self, other):
return self.ref_locus - other.ref_locus
# check if a leg is in a region
def in_reg(self, reg):
if self.ref_name != reg.ref_name:
return False
if reg.has_haplotype and self.haplotype != reg.haplotype:
return False
if reg.has_start and self.ref_locus < reg.start:
return False
if reg.has_end and self.ref_locus > reg.end:
return False
return True
# check if a leg is in a list of regions
def in_regs(self, regs):
for reg in regs:
if self.in_reg(reg):
return True
return False
# check if a leg is in a list of included regions, but not in a list of excluded regions
def satisfy_regs(self, inc_regs, exc_regs):
return self.in_regs(inc_regs) and not self.in_regs(exc_regs)
# set haplotypes for a haploid region
def set_haplotype_in_hap_reg(self, reg):
unphased_reg = reg.get_unphased()
if self.in_reg(unphased_reg):
self.set_haplotype(reg.haplotype)
def set_haplotype_in_hap_regs(self, regs):
for reg in regs:
self.set_haplotype_in_hap_reg(reg)
def to_string(self):
return ",".join([self.ref_name, str(self.ref_locus), haplotype_to_string(self.haplotype)])
def string_to_leg(leg_string):
ref_name, ref_locus, haplotype = leg_string.split(",")
ref_locus = int(ref_locus)
haplotype = string_to_haplotype(haplotype)
return Leg(ref_name, ref_locus, haplotype)
# a list of legs, can be sorted to query number of legs in a region
class LegList:
def __init__(self):
self.legs = []
def num_legs(self):
return(len(self.legs))
def sort_legs(self):
self.legs.sort()
def add_leg(self, leg):
self.legs.append(leg)
def add_con_data(self, con_data):
for con in con_data.get_cons():
self.add_con(con)
def get_random_leg(self):
return random.choice(self.legs)
# query a leg, regardless of haplotypes, assume sorted and that the list includes the leg itself
def is_leg_promiscuous(self, leg, max_leg_distance, max_leg_count):
index_to_check = bisect.bisect_left(self.legs, Leg(leg.get_ref_name(), leg.get_ref_locus() - max_leg_distance, Haplotypes.minus_infinity)) + max_leg_count
if index_to_check >= len(self.legs):
return False
return self.legs[index_to_check] <= Leg(leg.get_ref_name(), leg.get_ref_locus() + max_leg_distance, Haplotypes.infinity)
## clean3
# sort fully phased legs
def sort_phased_legs(self):
self.legs.sort(key = lambda x:(x.get_ref_name(), x.get_haplotype(), x.get_ref_locus()))
# return num of legs near a G3dParticle, assume fully phased and sorted
def num_legs_near_g3d_particle(self, g3d_particle, max_distance):
# modified from bisect to support key
lo = 0
hi = len(self.legs)
while lo < hi:
mid = (lo + hi) // 2
if (self.legs[mid].get_ref_name(), self.legs[mid].get_haplotype(), self.legs[mid].get_ref_locus()) < (g3d_particle.get_ref_name(), g3d_particle.get_haplotype(), g3d_particle.get_ref_locus() - max_distance):
lo = mid + 1
else:
hi = mid
left_index = lo
hi = len(self.legs)
while lo < hi:
mid = (lo + hi) // 2
if (g3d_particle.get_ref_name(), g3d_particle.get_haplotype(), g3d_particle.get_ref_locus() + max_distance) < (self.legs[mid].get_ref_name(), self.legs[mid].get_haplotype(), self.legs[mid].get_ref_locus()):
hi = mid
else:
lo = mid + 1
return lo - left_index
def is_g3d_particle_leg_poor(self, g3d_particle, max_distance, min_leg_count):
# modified from bisect to support key
lo = 0
hi = len(self.legs)
while lo < hi:
mid = (lo + hi) // 2
if (self.legs[mid].get_ref_name(), self.legs[mid].get_haplotype(), self.legs[mid].get_ref_locus()) < (g3d_particle.get_ref_name(), g3d_particle.get_haplotype(), g3d_particle.get_ref_locus() - max_distance):
lo = mid + 1
else:
hi = mid
index_to_check = lo + min_leg_count - 1
if index_to_check >= len(self.legs):
return True
return (g3d_particle.get_ref_name(), g3d_particle.get_haplotype(), g3d_particle.get_ref_locus() + max_distance) < (self.legs[index_to_check].get_ref_name(), self.legs[index_to_check].get_haplotype(), self.legs[index_to_check].get_ref_locus())
def to_string(self):
return "\n".join([leg.to_string() for leg in self.legs])
class LegData:
def __init__(self):
self.leg_lists = {}
def num_legs(self):
num_legs = 0
for leg_list in self.leg_lists.values():
num_legs += leg_list.num_legs()
return num_legs
def add_empty_leg_list(self, ref_name):
self.leg_lists[ref_name] = LegList()
def add_leg(self, leg):
if leg.get_ref_name() not in self.leg_lists:
self.add_empty_leg_list(leg.get_ref_name())
self.leg_lists[leg.get_ref_name()].add_leg(leg)
def add_con(self, con):
self.add_leg(con.leg_1())
self.add_leg(con.leg_2())
def add_con_data(self, con_data):
for con in con_data.get_cons():
self.add_con(con)
def sort_legs(self):
for leg_list in self.leg_lists.values():
leg_list.sort_legs()
def sort_phased_legs(self):
for leg_list in self.leg_lists.values():
leg_list.sort_phased_legs()
def is_leg_promiscuous(self, leg, max_leg_distance, max_leg_count):
return self.leg_lists[leg.get_ref_name()].is_leg_promiscuous(leg, max_leg_distance, max_leg_count)
def num_legs_near_g3d_particle(self, g3d_particle, max_distance):
return self.leg_lists[g3d_particle.get_ref_name()].num_legs_near_g3d_particle(g3d_particle, max_distance)
def is_g3d_particle_leg_poor(self, g3d_particle, max_distance, min_leg_count):
return self.leg_lists[g3d_particle.get_ref_name()].is_g3d_particle_leg_poor(g3d_particle, max_distance, min_leg_count)
def to_string(self):
return "\n".join([self.leg_lists[ref_name].to_string() for ref_name in sorted(self.leg_lists.keys())])
# a contact (legs always sorted)
@total_ordering
class Con:
def __init__(self, leg_1, leg_2):
self.legs = sorted([leg_1, leg_2])
def __repr__(self):
return self.to_string()
def __eq__(self, other):
return (self.legs[0], self.legs[1]) == (other.legs[0], other.legs[1])
def __lt__(self, other):
return (self.legs[0], self.legs[1]) < (other.legs[0], other.legs[1])
def __hash__(self):
return hash((self.legs[0], self.legs[1]))
def deep_copy_from_con(self, other):
self.legs = copy.deepcopy(other.legs)
def leg_1(self):
return self.legs[0]
def leg_2(self):
return self.legs[1]
def num_phased_legs(self):
num_phased_legs = 0
for i in range(2):
if self.legs[i].is_phased():
num_phased_legs += 1
return num_phased_legs
def num_conflict_legs(self):
num_conflict_legs = 0
for i in range(2):
if self.legs[i].is_conflict():
num_conflict_legs += 1
return num_conflict_legs
def ref_name_tuple(self):
return tuple([leg.get_ref_name() for leg in self.legs])
def hap_tuple(self):
return tuple([leg.get_haplotype() for leg in self.legs])
def compatible_hap_tuples(self):
return [(haplotype_1, haplotype_2) for haplotype_1 in self.legs[0].compatible_haps() for haplotype_2 in self.legs[1].compatible_haps()]
def compatible_cons(self, is_male, par_data):
return [Con(leg_1, leg_2) for leg_1 in self.legs[0].compatible_legs(is_male, par_data) for leg_2 in self.legs[1].compatible_legs(is_male, par_data)]
## impute based on nearby contacts in a ConData
def votes_from_con_data(self, con_data, max_impute_distance):
compatible_hap_tuples = self.compatible_hap_tuples()
voted_hap_tuples = []
for con in con_data.get_cons_near(self, max_impute_distance):
voted_hap_tuple = vote_from_hap_tuples(compatible_hap_tuples, con.compatible_hap_tuples())
if not voted_hap_tuple is None:
voted_hap_tuples.append(voted_hap_tuple)
return voted_hap_tuples
def set_hap_tuple_from_votes(self, voted_hap_tuples, min_impute_votes, min_impute_vote_fraction):
hap_tuple = winning_vote(voted_hap_tuples, min_impute_votes, min_impute_vote_fraction)
if not hap_tuple is None:
self.set_hap_tuple(hap_tuple)
def impute_from_con_data(self, con_data, max_impute_distance, min_impute_votes, min_impute_vote_fraction, max_intra_hom_separation):
if self.num_phased_legs() == 2:
# already phased
return
if self.num_phased_legs() == 1 and self.is_intra_chr() and self.separation() <= max_intra_hom_separation:
# assume intra-homologous
if self.legs[0].is_phased():
self.legs[1].set_haplotype(self.legs[0].get_haplotype())
else:
self.legs[0].set_haplotype(self.legs[1].get_haplotype())
return
self.set_hap_tuple_from_votes(self.votes_from_con_data(con_data, max_impute_distance), min_impute_votes, min_impute_vote_fraction)
## impute based on 3D structure in a G3dData
# for a fully phased contact, return whether both legs are out of bounds, and the 3D distance between the two legs
def distance_in_g3d_data(self, g3d_data):
is_leg_1_out, leg_1_position = g3d_data.interpolate_leg(self.legs[0])
is_leg_2_out, leg_2_position = g3d_data.interpolate_leg(self.legs[1])
is_both_out = is_leg_1_out and is_leg_2_out
if leg_1_position is None or leg_2_position is None:
return True, None
distance = spatial.distance.euclidean(leg_1_position, leg_2_position)
return is_both_out, distance
def impute_from_g3d_data(self, g3d_data, max_impute3_distance, max_impute3_ratio, min_impute3_separation, is_male, par_data, vio_file = None):
compatible_cons = self.compatible_cons(is_male, par_data)
num_compatible_cons = len(compatible_cons)
skip_ratio_calculation = False
if num_compatible_cons == 1:
# already phased (copy in case of X and Y)
self.deep_copy_from_con(compatible_cons[0])
skip_ratio_calculation = True
elif num_compatible_cons == 4 and self.is_intra_chr() and self.separation() < min_impute3_separation:
# too close and completely unphased, cannot impute
skip_ratio_calculation = True
con_distance_tuples = []
any_is_both_out = False
for con in compatible_cons:
is_both_out, distance = con.distance_in_g3d_data(g3d_data)
if is_both_out:
any_is_both_out = True
con_distance_tuples.append((con, distance))
if self.is_intra_chr() and any_is_both_out:
# intra-chromosomal, and both legs are out of range (in any of the compatible), cannot impute (this does not work for CNV loss)
skip_ratio_calculation = True
# core imputation
con_distance_tuples.sort(key = lambda x:x[1])
impute3_con, impute3_distance = con_distance_tuples[0]
if skip_ratio_calculation:
impute3_ratio = -1
else:
impute3_ratio = impute3_distance / con_distance_tuples[1][1]
if not vio_file is None:
vio_file.write("\t".join([self.to_string(), str(num_compatible_cons), str(impute3_distance), str(impute3_ratio)]) + "\n")
if not skip_ratio_calculation and impute3_distance <= max_impute3_distance and impute3_ratio <= max_impute3_ratio:
self.deep_copy_from_con(impute3_con)
def set_hap_tuple(self, hap_tuple):
for i in range(2):
self.legs[i].set_haplotype(hap_tuple[i])
def set_non_par_hap_tuple_male(self, par_data):
for i in range(2):
par_data.set_non_par_leg_haplotype_male(self.legs[i])
def in_par(self, par_data):
return par_data.contain_leg(self.legs[0]) or par_data.contain_leg(self.legs[1])
def sort_legs(self):
self.legs.sort()
def is_intra_chr(self):
return self.leg_1().same_chr_with(self.leg_2())
def is_inter_hom(self):
return self.is_intra_chr() and self.num_phased_legs() == 2 and self.leg_1().get_haplotype() != self.leg_2().get_haplotype()
def separation(self):
return self.leg_2().get_ref_locus() - self.leg_1().get_ref_locus()
def merge_with(self, other):
for i in range(2):
self.legs[i].merge_with(other.legs[i])
self.sort_legs()
# different distance functions w. r. t. another contact, assuming the same chromosome
def distance_leg_1_with(self, other):
return self.leg_1().separation_with(other.leg_1())
def distance_leg_2_with(self, other):
return self.leg_2().separation_with(other.leg_2())
def distance_inf_with(self, other): # L-inf norm
return max(self.distance_leg_1_with(other), self.distance_leg_2_with(other))
def distance_half_with(self, other): # L-1/2 norm
return (math.sqrt(self.distance_leg_1_with(other)) + math.sqrt(self.distance_leg_2_with(other))) ** 2
def satisfy_regs(self, inc_regs, exc_regs):
return self.leg_1().satisfy_regs(inc_regs, exc_regs) and self.leg_2().satisfy_regs(inc_regs, exc_regs)
def set_haplotype_in_hap_regs(self, regs):
self.leg_1().set_haplotype_in_hap_regs(regs)
self.leg_2().set_haplotype_in_hap_regs(regs)
def is_promiscuous(self, leg_data, max_leg_distance, max_leg_count):
return leg_data.is_leg_promiscuous(self.leg_1(), max_leg_distance, max_leg_count) or leg_data.is_leg_promiscuous(self.leg_2(), max_leg_distance, max_leg_count)
def is_isolated(self, con_data, max_clean_distance, min_clean_count):
num_neighbors = 0
for con in con_data.get_cons_near(self, max_clean_distance):
num_neighbors += 1
if num_neighbors >= min_clean_count + 1: # assume con is included in ConData, thus plus 1
return False
return True
def test_isolated(self, con_data, max_clean_distance, min_clean_count):
num_neighbors = 0
for con in con_data.get_cons_near(self, max_clean_distance):
num_neighbors += 1
if num_neighbors >= min_clean_count + 1: # assume con is included in ConData, thus plus 1
break
return num_neighbors - 1
def is_isolated_phased(self, con_data, max_clean_distance, min_clean_count):
num_neighbors = 0
for con in con_data.get_cons_near(self, max_clean_distance):
if self.hap_tuple() != con.hap_tuple():
continue # count only if hap_tuples match
num_neighbors += 1
if num_neighbors >= min_clean_count + 1: # assume con is included in ConData, thus plus 1
return False
return True
def to_string(self):
return "\t".join([leg.to_string() for leg in self.legs])
# ard: print relative locus with respect to a reference point
def to_rel_locus_around(self, other):
return (self.leg_1().signed_separation_with(other.leg_1())), self.leg_2().signed_separation_with(other.leg_2())
def to_string_around(self, other):
return str(self.leg_1().signed_separation_with(other.leg_1())) + "\t" + str(self.leg_2().signed_separation_with(other.leg_2()))
def ref_name_tuple_to_string(ref_name_tuple):
return ",".join(ref_name_tuple)
def string_to_con(con_string):
leg_1, leg_2 = con_string.split("\t")
return Con(string_to_leg(leg_1), string_to_leg(leg_2))
## voting during imputation
# a list (self) being voted by another list (other), return None if not compatible or more than one compatible
def vote_from_hap_tuples(self_hap_tuples, other_hap_tuples):
compatible_hap_tuples = set(self_hap_tuples) & set(other_hap_tuples)
if len(compatible_hap_tuples) == 1:
return compatible_hap_tuples.pop()
return None
# return the voted winner, None if not meeting criteria
def winning_vote(hap_tuples, min_impute_votes, min_impute_vote_fraction):
if len(hap_tuples) == 0:
return None
hap_tuple_counter = Counter(hap_tuples)
hap_tuple, vote = hap_tuple_counter.most_common(1)[0]
if vote >= min_impute_votes and float(vote) / len(hap_tuples) >= min_impute_vote_fraction:
return hap_tuple
return None
# a sorted list of contacts
class ConList:
def __init__(self):
self.cons = []
# generator for all its contacts
def get_cons(self):
for con in self.cons:
yield con
# generator for contacts near a given contact (L-1/2 norm), assume sorted
def get_cons_near(self, con, max_distance):
start_index = bisect.bisect_left(self.cons, con)
for i in range(start_index, len(self.cons)):
if self.cons[i].distance_leg_1_with(con) > max_distance:
break
if self.cons[i].distance_half_with(con) <= max_distance:
yield self.cons[i]
for i in range(start_index - 1, -1, -1):
if self.cons[i].distance_leg_1_with(con) > max_distance:
break
if self.cons[i].distance_half_with(con) <= max_distance:
yield self.cons[i]
# generator for contacts near a given contact (L-inf norm), assume sorted
def get_cons_near_inf(self, con, max_distance):
start_index = bisect.bisect_left(self.cons, con)
for i in range(start_index, len(self.cons)):
if self.cons[i].distance_leg_1_with(con) > max_distance:
break
if self.cons[i].distance_leg_2_with(con) <= max_distance:
yield self.cons[i]
for i in range(start_index - 1, -1, -1):
if self.cons[i].distance_leg_1_with(con) > max_distance:
break
if self.cons[i].distance_leg_2_with(con) <= max_distance:
yield self.cons[i]
def num_cons(self):
return(len(self.cons))
def num_phased_legs(self):
num_phased_legs = 0
for con in self.cons:
num_phased_legs += con.num_phased_legs()
return num_phased_legs
def num_phased_cons(self):
num_phased_con = 0
for con in self.cons:
if con.num_phased_legs() == 2:
num_phased_con += 1
return num_phased_con
def num_conflict_legs(self):
num_conflict_legs = 0
for con in self.cons:
num_conflict_legs += con.num_conflict_legs()
return num_conflict_legs
def num_intra_chr(self):
num_intra_chr = 0
for con in self.cons:
if con.is_intra_chr():
num_intra_chr += 1
return num_intra_chr
def sort_cons(self):
self.cons.sort()
def add_con(self, con):
self.cons.append(con)
def merge_with(self, other):
self.cons += other.cons
# remove intra-chromosomal contacts with small separations
def clean_separation(self, min_separation):
self.cons[:] = [con for con in self.cons if not con.is_intra_chr() or con.separation() >= min_separation]
# remove contacts containing promiscuous legs
def clean_promiscuous(self, leg_data, max_leg_distance, max_leg_count):
self.cons[:] = [con for con in self.cons if not con.is_promiscuous(leg_data, max_leg_distance, max_leg_count)]
# remove isolated contacts
def clean_isolated(self, con_data, max_clean_distance, min_clean_count):
self.cons[:] = [con for con in self.cons if not con.is_isolated(con_data, max_clean_distance, min_clean_count)]
def test_isolated(self, con_data, max_clean_distance, min_clean_count):
return [con.test_isolated(con_data, max_clean_distance, min_clean_count) for con in self.cons]
# remove contacts in PARs
def clean_in_par(self, par_data):
self.cons[:] = [con for con in self.cons if not con.in_par(par_data)]
# set haplotypes in haploid regions of male
def set_non_par_hap_tuple_male(self, par_data):
for con in self.cons:
con.set_non_par_hap_tuple_male(par_data)
# remove inter-homologous contacts with small separations
def clean_separation_hom(self, min_separation):
self.cons[:] = [con for con in self.cons if not con.is_inter_hom() or con.separation() >= min_separation]
# impute
def impute_from_con_data(self, con_data, max_impute_distance, min_impute_votes, min_impute_vote_fraction, max_intra_hom_separation, min_inter_hom_separation):
for con in self.cons:
con.impute_from_con_data(con_data, max_impute_distance, min_impute_votes, min_impute_vote_fraction, max_intra_hom_separation)
self.clean_separation_hom(min_inter_hom_separation)
# remove everything but fully phased contacts
def clean_unphased(self):
self.cons[:] = [con for con in self.cons if con.num_phased_legs() == 2]
# remove isolated contacts for fully phased contacts
def clean_isolated_phased(self, con_data, max_clean_distance, min_clean_count):
self.cons[:] = [con for con in self.cons if not con.is_isolated_phased(con_data, max_clean_distance, min_clean_count)]
# impute3
def impute_from_g3d_data(self, g3d_data, max_impute3_distance, max_impute3_ratio, min_impute3_separation, is_male, par_data, vio_file = None):
for con in self.cons:
con.impute_from_g3d_data(g3d_data, max_impute3_distance, max_impute3_ratio, min_impute3_separation, is_male, par_data, vio_file)
# simple dedup within a read (no binary search), assuming the same chromosome
def dedup_within_read(self, max_distance):
while True:
merged = False
for i in range(len(self.cons)):
for j in range(i + 1, len(self.cons)):
if self.cons[i].distance_inf_with(self.cons[j]) <= max_distance:
self.cons[i].merge_with(self.cons[j])
self.cons.pop(j)
merged = True
break
if merged == False:
break
# faster dedup, assuming the same chromosome
def dedup(self, max_distance):
self.cons.sort()
while True:
merged = False
for i in range(len(self.cons)):
for j in range(i + 1, len(self.cons)):
if self.cons[i].distance_leg_1_with(self.cons[j]) > max_distance:
break
if self.cons[i].distance_leg_2_with(self.cons[j]) <= max_distance:
self.cons[i].merge_with(self.cons[j])
self.cons.pop(j)
merged = True
break
if merged == False:
break
self.cons[i:j] = sorted(self.cons[i:j])
def apply_regs(self, inc_regs, exc_regs, hap_regs):
self.cons[:] = [con for con in self.cons if con.satisfy_regs(inc_regs, exc_regs)]
for con in self.cons:
con.set_haplotype_in_hap_regs(hap_regs)
def to_string(self):
return "\n".join([con.to_string() for con in self.cons])
# a hashmap (tuples of two sorted chromosome names) of lists of contacts (a CON file)
class ConData:
def __init__(self):
self.con_lists = {}
# generator for all its cons, with ref_name_tuple sorted
def get_cons(self):
for ref_name_tuple in sorted(self.con_lists.keys()):
for con in self.con_lists[ref_name_tuple].get_cons():
yield con
# wrappers for generators
def get_cons_near(self, con, max_distance):
if con.ref_name_tuple() in self.con_lists:
for con in self.con_lists[con.ref_name_tuple()].get_cons_near(con, max_distance):
yield con
def get_cons_near_inf(self, con, max_distance):
if con.ref_name_tuple() in self.con_lists:
for con in self.con_lists[con.ref_name_tuple()].get_cons_near_inf(con, max_distance):
yield con
def add_empty_con_list(self, ref_name_tuple):
self.con_lists[ref_name_tuple] = ConList()
def add_con(self, con):
if con.ref_name_tuple() not in self.con_lists:
self.add_empty_con_list(con.ref_name_tuple())
self.con_lists[con.ref_name_tuple()].add_con(con)
def merge_with(self, other):
for ref_name_tuple in other.con_lists.keys():
if ref_name_tuple in self.con_lists:
self.con_lists[ref_name_tuple].merge_with(other.con_lists[ref_name_tuple])
else:
self.con_lists[ref_name_tuple] = other.con_lists[ref_name_tuple]
# remove all intra-chromosomal contacts
def clean_intra_chr(self):
for ref_name_tuple in self.con_lists.keys():
if ref_name_tuple[0] == ref_name_tuple[1]:
del self.con_lists[ref_name_tuple]
# remove all inter-chromosomal contacts
def clean_inter_chr(self):
for ref_name_tuple in self.con_lists.keys():
if ref_name_tuple[0] != ref_name_tuple[1]:
del self.con_lists[ref_name_tuple]
# wrappers for all ConList operations
def sort_cons(self):
for con_list in self.con_lists.values():
con_list.sort_cons()
def clean_separation(self, min_separation):
for ref_name_tuple in self.con_lists.keys():
self.con_lists[ref_name_tuple].clean_separation(min_separation)
if self.con_lists[ref_name_tuple].num_cons() == 0:
del self.con_lists[ref_name_tuple]
def clean_promiscuous(self, leg_data, max_leg_distance, max_leg_count):
for ref_name_tuple in self.con_lists.keys():
self.con_lists[ref_name_tuple].clean_promiscuous(leg_data, max_leg_distance, max_leg_count)
if self.con_lists[ref_name_tuple].num_cons() == 0:
del self.con_lists[ref_name_tuple]
def clean_isolated(self, con_data, max_clean_distance, min_clean_count):
for ref_name_tuple in self.con_lists.keys():
original_num_cons = self.con_lists[ref_name_tuple].num_cons()
self.con_lists[ref_name_tuple].clean_isolated(con_data, max_clean_distance, min_clean_count)
sys.stderr.write("[M::" + __name__ + "] cleaned isolated contacts for chromosome pair (" + ref_name_tuple_to_string(ref_name_tuple) + "): " + str(original_num_cons) + " -> " + str(self.con_lists[ref_name_tuple].num_cons()) + " contacts\n")
if self.con_lists[ref_name_tuple].num_cons() == 0:
del self.con_lists[ref_name_tuple]
def test_isolated(self, con_data, max_clean_distance, min_clean_count):
neighbor_counts = []
for ref_name_tuple in self.con_lists.keys():
original_num_cons = self.con_lists[ref_name_tuple].num_cons()
neighbor_counts.extend(self.con_lists[ref_name_tuple].test_isolated(con_data, max_clean_distance, min_clean_count))
sys.stderr.write("[M::" + __name__ + "] tested isolated contacts for chromosome pair (" + ref_name_tuple_to_string(ref_name_tuple) + "): " + str(original_num_cons) + " contacts\n")
return neighbor_counts
def clean_in_par(self, par_data):
for ref_name_tuple in self.con_lists.keys():
if par_data.get_x_name() not in ref_name_tuple and par_data.get_y_name() not in ref_name_tuple:
continue
self.con_lists[ref_name_tuple].clean_in_par(par_data)
if self.con_lists[ref_name_tuple].num_cons() == 0:
del self.con_lists[ref_name_tuple]
def clean_unphased(self):
for ref_name_tuple in self.con_lists.keys():
self.con_lists[ref_name_tuple].clean_unphased()
if self.con_lists[ref_name_tuple].num_cons() == 0:
del self.con_lists[ref_name_tuple]
def clean_isolated_phased(self, con_data, max_clean_distance, min_clean_count):
for ref_name_tuple in self.con_lists.keys():
original_num_cons = self.con_lists[ref_name_tuple].num_cons()
self.con_lists[ref_name_tuple].clean_isolated_phased(con_data, max_clean_distance, min_clean_count)
#sys.stderr.write("[M::" + __name__ + "] cleaned isolated contacts for chromosome pair (" + ref_name_tuple_to_string(ref_name_tuple) + "): " + str(original_num_cons) + " -> " + str(self.con_lists[ref_name_tuple].num_cons()) + " contacts\n")
if self.con_lists[ref_name_tuple].num_cons() == 0:
del self.con_lists[ref_name_tuple]
def set_non_par_hap_tuple_male(self, par_data):
for ref_name_tuple in self.con_lists.keys():
if par_data.get_x_name() not in ref_name_tuple and par_data.get_y_name() not in ref_name_tuple:
continue
self.con_lists[ref_name_tuple].set_non_par_hap_tuple_male(par_data)
def impute_from_con_data(self, con_data, max_impute_distance, min_impute_votes, min_impute_vote_fraction, max_intra_hom_separation, min_inter_hom_separation):
for ref_name_tuple in self.con_lists.keys():
self.con_lists[ref_name_tuple].impute_from_con_data(con_data, max_impute_distance, min_impute_votes, min_impute_vote_fraction, max_intra_hom_separation, min_inter_hom_separation)
#sys.stderr.write("[M::" + __name__ + "] imputed haplotypes for chromosome pair (" + ref_name_tuple_to_string(ref_name_tuple) + "): " + str(self.con_lists[ref_name_tuple].num_cons()) + " contacts\n")
def impute_from_g3d_data(self, g3d_data, max_impute3_distance, max_impute3_ratio, min_impute3_separation, is_male, par_data, vio_file = None):
for ref_name_tuple in self.con_lists.keys():
self.con_lists[ref_name_tuple].impute_from_g3d_data(g3d_data, max_impute3_distance, max_impute3_ratio, min_impute3_separation, is_male, par_data, vio_file)
sys.stderr.write("[M::" + __name__ + "] imputed haplotypes for chromosome pair (" + ref_name_tuple_to_string(ref_name_tuple) + "): " + str(self.con_lists[ref_name_tuple].num_cons()) + " contacts (" + str(round(100.0 * self.con_lists[ref_name_tuple].num_phased_cons() / self.con_lists[ref_name_tuple].num_cons(), 2)) + "% phased)\n")
def dedup_within_read(self, max_distance):
for con_list in self.con_lists.values():
con_list.dedup_within_read(max_distance)
def dedup(self, max_distance):
for ref_name_tuple in self.con_lists.keys():
sys.stderr.write("[M::" + __name__ + "] merging duplicates for chromosome pair (" + ref_name_tuple_to_string(ref_name_tuple) + "): " + str(self.con_lists[ref_name_tuple].num_cons()) + " putative contacts\n")
self.con_lists[ref_name_tuple].dedup(max_distance)
def apply_regs(self, inc_regs, exc_regs, hap_regs):
for ref_name_tuple in self.con_lists.keys():
self.con_lists[ref_name_tuple].apply_regs(inc_regs, exc_regs, hap_regs)
if self.con_lists[ref_name_tuple].num_cons() == 0:
del self.con_lists[ref_name_tuple]
def num_cons(self):
num_cons = 0
for con_list in self.con_lists.values():
num_cons += con_list.num_cons()
return num_cons
def num_phased_cons(self):
num_cons = 0
for con_list in self.con_lists.values():
num_cons += con_list.num_phased_cons()
return num_cons
def num_phased_legs(self):
num_phased_legs = 0
for con_list in self.con_lists.values():
num_phased_legs += con_list.num_phased_legs()
return num_phased_legs
def num_conflict_legs(self):
num_conflict_legs = 0
for con_list in self.con_lists.values():
num_conflict_legs += con_list.num_conflict_legs()
return num_conflict_legs
def num_intra_chr(self):
num_intra_chr = 0
for con_list in self.con_lists.values():
num_intra_chr += con_list.num_intra_chr()
return num_intra_chr
def to_string(self): # no tailing new line
return "\n".join([self.con_lists[ref_name_tuple].to_string() for ref_name_tuple in sorted(self.con_lists.keys())])
def file_to_con_data(con_file):
con_data = ConData()
for con_file_line in con_file:
con_data.add_con(string_to_con(con_file_line.strip()))
return con_data
# augmented data for dedup: each leg records haplotypes of all duplicates
class DupLeg(Leg):
def __init__(self, leg):
Leg.__init__(self, leg.ref_name, leg.ref_locus, leg.haplotype)
self.dups = {Haplotypes.unknown: 0, Haplotypes.paternal: 0, Haplotypes.maternal: 0}
self.dups[leg.haplotype] += 1
def num_dups(self):
return sum(self.dups.values())
def merge_with(self, other):
Leg.merge_with(self, other)
for haplotype in self.dups.keys():
self.dups[haplotype] += other.dups[haplotype]
#def to_string(self):
#if self.haplotype != Haplotypes.conflict:
#return ""
#return Leg.to_string(self) + "(" + ",".join([str(self.dups[Haplotypes.unknown]), str(self.dups[Haplotypes.paternal]), str(self.dups[Haplotypes.maternal])]) + ")"
class DupCon(Con):
def __init__(self, con):
Con.__init__(self, DupLeg(con.legs[0]), DupLeg(con.legs[1]))
def num_dups(self):
return self.legs[0].num_dups() # should be the same for both legs
class DupConList(ConList):
def __init__(self, con_list):
ConList.__init__(self)
for con in con_list.cons:
self.add_con(DupCon(con))
def dup_stats(self, display_max_num_dups):
hist_num_dups = [0] * display_max_num_dups
for dup_con in self.cons:
hist_num_dups[min(dup_con.num_dups(), display_max_num_dups) - 1] += 1
return hist_num_dups
class DupConData(ConData):
def __init__(self, con_data):
ConData.__init__(self)
for ref_name_tuple in con_data.con_lists.keys():
self.con_lists[ref_name_tuple] = DupConList(con_data.con_lists[ref_name_tuple])
def dup_stats(self, display_max_num_dups):
hist_num_dups = [0] * display_max_num_dups
for con_list in self.con_lists.values():