-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathDRUID_functions.py
1531 lines (1322 loc) · 68.8 KB
/
DRUID_functions.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 itertools
import networkx as nx
import copy
from DRUID_graph_interaction import *
from DRUID_all_rel import *
global total_genome, chrom_name_to_idx, chrom_idx_to_name, num_chrs
degrees = {'MZ': 1/2.0**(3.0/2), 1: 1/2.0**(5.0/2), 2: 1/2.0**(7.0/2), 3: 1/2.0**(9.0/2), 4: 1/2.0**(11.0/2), 5: 1/2.0**(13.0/2), 6: 1/2.0**(15.0/2), 7: 1/2.0**(17.0/2), 8: 1/2.0**(19.0/2), 9: 1/2.0**(21.0/2), 10: 1/2.0**(23.0/2), 11: 1/2.0**(25.0/2), 12: 1/2.0**(27/2.0), 13: 1/2.0**(29.0/2)} # threshold values for each degree of relatedness
def forceFamInfo(rel_graph, faminfo):
#force the provided faminfo file information into rel_graph
for i1 in faminfo.keys():
for i2 in faminfo[i1].keys():
rel_graph.add_edge(i1,i2)
rel_graph[i1][i2]['type'] = faminfo[i1][i2]
def inferFirst(rel_graph, rel_graph_tmp, all_rel, first, second, C):
#build graphs using first degree relative inferences
for [i1,i2] in first+second: #iterate through currently inferred first and second degree pairs
if C:
fs_IBD2 = 1/2.0**(5/2.0)
fs_kin = 1/2.0**(5/2.0)
else:
fs_IBD2 = 1/2.0**(11/4.0)
fs_kin = 1/2.0**(7/2.0)
ibd2 = getIBD2(i1, i2, all_rel)
kinship = getPairwiseK(i1, i2, all_rel)
if ibd2 >= fs_IBD2 and kinship >= fs_kin: #if IBD2 meets minimum threshold
if kinship < 1/2.0**(3/2.0): #not twin
if ibd2 < 1/2.0**(5/2.0): #lower IBD2 than expected
print("Warning: " + i1 + ' and ' + i2 + ' have low levels of IBD2 for siblings, may be 3/4 sibs')
addEdgeType(i1, i2, 'FS', 'FS', rel_graph)
else: #twin
addEdgeType(i1, i2, 'T', 'T', rel_graph)
else:
if getPairwiseD(i1, i2, all_rel) == 1:
addEdgeType(i1, i2, '1U', '1U', rel_graph)
# ensure subgraphs of siblings are connected
checked = set()
sibsets = [] #collect list of sets of siblings
for node in rel_graph.nodes():
if not node in checked:
#print(node+'\n')
siblings = getSibsFromGraph(rel_graph,node)
siblings.add(node)
# get sibs to add to subgraph, and individuals to remove from sibling subgraph
[add_sibs,remove] = checkSiblingSubgraph(rel_graph,siblings.copy(),C) #edit siblings list, return removed sibs
# remove the individuals no longer believed to be siblings
for ind in remove:
for sib in siblings:
if rel_graph.has_edge(ind,sib):
rel_graph[ind][sib]['type'] = '1U'
rel_graph[sib][ind]['type'] = '1U'
if ind in siblings:
siblings.remove(ind)
# add in missing siblings
for [ind1,ind2] in itertools.combinations(add_sibs, 2):
addEdgeType(ind1, ind2, 'FS', 'FS', rel_graph)
#get updated set of siblings, add to checked list
siblings = getSibsFromGraph(rel_graph,node)
siblings.add(node)
for sib in siblings:
checked.add(sib)
sibsets.append(siblings)
#now that sibling set is completed, look for parents
#find neighbors of first sibling set labeled as '1'
inds_to_check = set()
for sib in siblings:
neighbors = rel_graph.neighbors(sib)
for sib_neighbor in neighbors:
if rel_graph.get_edge_data(sib,sib_neighbor)['type'] == '1U':
inds_to_check.add(sib_neighbor)
#check if other siblings also have this neighbor and are labeled as '1'
if len(inds_to_check):
for ind in inds_to_check:
if checkIfParent(rel_graph, all_rel, siblings, ind, C):
if len(siblings) == 1: #only 1 parent or child, give the pair generic PC label
siblings_pc = getSibsFromGraph(rel_graph, ind)
if len(siblings_pc) and not any([x in inds_to_check for x in siblings]): #if the other individual has siblings, then the individual in "siblings" must be the child of "ind"
for s in siblings_pc: #add ind and his/her siblings as child of siblings[0]
addEdgeType(list(siblings)[0], s, 'P', 'C', rel_graph)
else:
addEdgeType(ind, list(siblings)[0], 'PC', 'PC', rel_graph)
else:
for sib in siblings: #add ind as parent for each sibling
addEdgeType(ind, sib, 'P', 'C', rel_graph)
for sibset in sibsets:
sibset = list(sibset)
pars = getParent(rel_graph,sibset[0]) #parents of sibset
for par in pars:
[sib_par,par_par] = getSibsParentsFromGraph(rel_graph,par) #parents of parents of sibset (gp)
for sib in sibset:
for sp in sib_par: #for each sibling of the parent
if not rel_graph.has_edge(sib,sp):
addEdgeType(sib,sp,'NN','AU',rel_graph)
for pp in par_par: #for each parent of the parent
if not rel_graph.has_edge(sib, pp):
addEdgeType(sib,pp,'GC','GP',rel_graph)
# compare inferred graph to provided graph
for edge in rel_graph_tmp.edges():
if not edge in rel_graph.edges():
print("Warning: Unable to confirm " + edge[0] + " and " + edge[1] + " as " + str(rel_graph_tmp.get_edge_data(edge[0], edge[1])['type']) + " but including as such")
rel_graph.add_edge(edge[0],edge[1])
rel_graph[edge[0]][edge[1]]['type'] = rel_graph_tmp.get_edge_data(edge[0], edge[1])['type']
elif rel_graph_tmp.get_edge_data(edge[0], edge[1])['type'] != rel_graph.get_edge_data(edge[0], edge[1])['type']:
print("Warning: Unable to confirm " + edge[0] + " and " + edge[1] + " as " + str(rel_graph_tmp.get_edge_data(edge[0], edge[1])['type']) + " but including as such")
rel_graph[edge[0]][edge[1]]['type'] = rel_graph_tmp.get_edge_data(edge[0], edge[1])['type']
# #ensure sibsets have same relatives
# for sibset in sibsets:
# #collect neighbors of the sibs
# neighbor_set = set()
# for ind in sibset:
# nei = rel_graph.neighbors(ind)
# for n in nei:
# neighbor_set = neighbor_set.union((set(n,rel_graph.get_edge_data(ind,n)['type'])))
# for n in neighbor_set:
# for ind in sibset:
# if not rel_graph.has_edge(ind,n):
# addEdgeType
def readSegments(file_for_segments):
all_segs = {}
IBD_file = open(file_for_segments, 'r')
for line in IBD_file:
l = str.split(line.rstrip())
if l[0] < l[1]:
ids = [ l[0], l[1] ]
else:
ids = [ l[1], l[0] ]
if not ids[0] in all_segs:
all_segs[ ids[0] ] = \
{ ids[1]: [ { chr : [] for chr in range(num_chrs) } for _ in range(2) ] }
elif not ids[1] in all_segs[ ids[0] ]:
all_segs[ ids[0] ][ ids[1] ] = \
[ { chr : [] for chr in range(num_chrs) } for _ in range(2) ]
chrom_name = l[2]
chr = chrom_name_to_idx[chrom_name]
ibd_type = int(l[3][3]) # chop "IBD" off, get integer type IBD_1_ or 2
all_segs[ ids[0] ][ ids[1] ][ibd_type - 1][chr].append([float(l[4]), float(l[5])])
IBD_file.close()
return all_segs
def inferSecondPath(rel_graph, rel_graph_tmp, all_rel, second, all_segs, outfile, C):
# infer and add 2nd degree relationships
dc_lower = 1/2.0**(9/2.0) #minimum IBD2 for DC classification
for [i1, i2] in second:
if not rel_graph.has_edge(i1, i2):
if getIBD2(i1, i2, all_rel) < dc_lower: #proportion IBD2 less than requirement for DC classification
addEdgeType(i1, i2, '2', '2', rel_graph)
else: #proportion IBD2 within requirement for DC classification
sib1 = getSibsFromGraph(rel_graph,i1)
sib2 = getSibsFromGraph(rel_graph,i2)
sib1.add(i1)
sib2.add(i2)
#if one i1 is a DC of i2, then siblings of i1 are DC of siblings of i2 (and i2)
for s1 in sib1:
for s2 in sib2:
addEdgeType(s1, s2, 'DC', 'DC', rel_graph)
checked = set()
for node in rel_graph.nodes():
if not node in checked:
[sibs, halfsibs, par] = getSibsHalfSibsParentsFromGraph(rel_graph, node)
sibs.add(node)
if len(sibs) > 1:
#print('TESTING '+" ".join(sibs)+'\n')
second_av = getSecondDegreeRelatives(rel_graph, second, sibs, par, all_rel)
[avunc, avunc_hs_all] = getAuntsUncles_IBD011_nonoverlapping_pairs(sibs, halfsibs, second_av, all_rel, all_segs, rel_graph)
# add the inferred avuncular relationships to graph
for av in avunc:
for sib in sibs:
if not rel_graph_tmp.has_edge(av,sib):
addEdgeType(av,sib,'AU','NN',rel_graph) # if the provided family information doesn't contain this relationship, add it
else:
print(av+" inferred as aunt/uncle of "+sib+", but will continue using provided relationship type "+rel_graph_tmp[av][sib]['type']+'\n')
if len(avunc_hs_all):
for hs in range(0,len(avunc_hs_all)):
for av in avunc_hs_all[hs]:
for sib in sibs.union(set(halfsibs[hs])):
if not rel_graph_tmp.has_edge(av, sib):
addEdgeType(av, sib, 'AU', 'NN', rel_graph) # if the provided family information doesn't contain this relationship, add it
else:
print(av + " inferred as aunt/uncle of " + sib + ", but will continue using provided relationship type " + rel_graph_tmp[av][sib]['type'] + '\n')
checked = checked.union(sibs)
checked = set()
for node in rel_graph.nodes():
if not node in checked:
[siblings, avunc_bothsides, nn, par, child, pc, gp, gc, halfsib_sets, twins] = pullFamily(rel_graph, node)
siblings.add(node)
checkAuntUncleGPRelationships(rel_graph, siblings, par)
checked = checked.union(siblings)
def getFamInfo(famfile, inds):
#read in faminfo file
global faminfo
faminfo = {}
file = open(famfile,'r')
for line in file:
l = str.split(line.rstrip())
if l != []:
if l[0] in inds and l[1] in inds:
if not l[0] in faminfo.keys():
faminfo[l[0]] = {}
if not l[1] in faminfo.keys():
faminfo[l[1]] = {}
faminfo[l[0]][l[1]] = l[2]
if l[2] == 'FS' or l[2] == 'HS':
faminfo[l[1]][l[0]] = l[2]
elif l[2] == 'P':
faminfo[l[1]][l[0]] = 'C'
elif l[2] == 'C':
faminfo[l[1]][l[0]] = 'P'
elif l[2] == 'AU':
faminfo[l[1]][l[0]] = 'NN'
elif l[2] == 'NN':
faminfo[l[1]][l[0]] = 'AU'
elif l[2] == 'GC':
faminfo[l[1]][l[0]] = 'GP'
elif l[2] == 'GP':
faminfo[l[1]][l[0]] = 'GC'
else:
file.close()
raise ValueError(str(l[2]) + ' is not an accepted relationship type (FS, P, C, AU, NN, GC, GP, HS)')
else:
if not l[0] in inds:
print("Warning: "+l[0]+" not included in .inds file, not including "+l[2]+" relationship with "+l[1])
if not l[1] in inds:
print("Warning: "+l[1]+" not included in .inds file, not including "+l[2]+" relationship with "+l[0])
file.close()
return faminfo
def getChrInfo(mapfile):
#read in information from .map file
global total_genome, chrom_name_to_idx, chrom_idx_to_name, chrom_starts, chrom_ends, num_chrs
chrom_name_to_idx = {}
chrom_idx_to_name = []
chrom_starts = []
chrom_ends = []
num_chrs = 0
file = open(mapfile,'r')
for line in file:
l = str.split(line.rstrip())
chr_name = l[0]
if not chr_name in chrom_name_to_idx.keys():
chrom_name_to_idx[chr_name] = chr = num_chrs
chrom_idx_to_name.append(chr_name)
num_chrs += 1
chrom_starts.append(99999999)
chrom_ends.append(0)
else:
chr = chrom_name_to_idx[chr_name]
pos = float(l[2])
if chrom_starts[chr] > pos:
chrom_starts[chr] = pos
if chrom_ends[chr] < pos:
chrom_ends[chr] = pos
file.close()
total_genome = 0
for chr in range(num_chrs):
total_genome += chrom_ends[chr] - chrom_starts[chr]
return [total_genome, chrom_name_to_idx, chrom_idx_to_name, chrom_starts, chrom_ends, num_chrs]
def getInferredFromK(K):
# Return inferred degree of relatedness using kinship coefficient K
if K >= degrees['MZ']:
return 0
if K >= degrees[1]:
return 1
elif K >= degrees[2]:
return 2
elif K >= degrees[3]:
return 3
elif K >= degrees[4]:
return 4
elif K >= degrees[5]:
return 5
elif K >= degrees[6]:
return 6
elif K >= degrees[7]:
return 7
elif K >= degrees[8]:
return 8
elif K >= degrees[9]:
return 9
elif K >= degrees[10]:
return 10
elif K >= degrees[11]:
return 11
else:
return -1
def getIBDsegments(ind1, ind2, all_segs):
# get IBD segments between ind1 and ind2, sorting segments by IBD2, IBD1, and IBD0
if ind1 < ind2:
ids = [ ind1, ind2 ]
else:
ids = [ ind2, ind1 ]
if not ids[0] in all_segs.keys() or not ids[1] in all_segs[ ids[0] ].keys():
return [ { chr : [] for chr in range(num_chrs) } for _ in range(2) ]
return all_segs[ ids[0] ][ ids[1] ]
def getIBD0(IBD1,IBD2):
#IBD12 = regions that are IBD (IBD1 or IBD2)
IBD12 = { chr : mergeIntervals(IBD1[chr] + IBD2[chr])
for chr in range(num_chrs) }
IBD0 = { chr : [] for chr in range(num_chrs) }
for chr in range(num_chrs):
if len(IBD12[chr]) > 0:
if IBD12[chr][0][0] > chrom_starts[chr]:
IBD0[chr].append([chrom_starts[chr], IBD12[chr][0][0]])
if len(IBD12[chr]) > 1:
for k in range(1, len(IBD12[chr])):
if IBD12[chr][k - 1][1] != IBD12[chr][k][0]:
IBD0[chr].append([IBD12[chr][k - 1][1], IBD12[chr][k][0]])
if IBD12[chr][k][1] < chrom_ends[chr]:
IBD0[chr].append([IBD12[chr][k][1], chrom_ends[chr]])
else:
IBD0[chr].append([IBD12[chr][0][1], chrom_ends[chr]])
return IBD0
def mergeIntervals(intervals):
#given a list of intervals, merge them where they overlap
sorted_by_lower_bound = sorted(intervals, key=lambda tup: tup[0])
merged = []
for higher in sorted_by_lower_bound:
if not merged:
merged.append(higher)
else:
lower = merged[-1]
# test for intersection between lower and higher:
# we know via sorting that lower[0] <= higher[0]
if higher[0] <= lower[1]:
upper_bound = max(lower[1], higher[1])
merged[-1] = [lower[0], upper_bound] # replace by merged interval
else:
merged.append(higher)
return merged
def collectIBDsegments(sibset, all_segs):
# collect pairwise IBD0,1,2 regions between all pairs of siblings
IBD_all = {}
for [ind1, ind2] in itertools.combinations(sibset, 2):
if not ind1 in IBD_all.keys():
IBD_all[ind1] = {}
IBD_all[ind1][ind2] = None
tmp = getIBDsegments(ind1, ind2, all_segs)
tmp0 = getIBD0(tmp[0],tmp[1])
for chr in range(num_chrs):
tmp0[chr].sort()
tmp[0][chr].sort()
tmp[1][chr].sort()
IBD_all[ind1][ind2] = [tmp0, tmp[0], tmp[1]]
return IBD_all
any_in = lambda a, b: any(i in b for i in a)
def collectAllIBDsegments(sibset):
# greedily collect IBD0 regions, then add IBD1 regions, then add IBD2 regions
IBD0 = { chr : [] for chr in range(num_chrs) }
IBD1 = { chr : [] for chr in range(num_chrs) }
IBD2 = { chr : [] for chr in range(num_chrs) }
for [ind1, ind2] in itertools.combinations(sibset, 2):
tmp = getIBDsegments(ind1, ind2)
tmp0 = getIBD0(tmp[0],tmp[1])
for chr in range(num_chrs):
IBD0[chr] += tmp0[chr]
IBD1[chr] += tmp[0][chr]
IBD2[chr] += tmp[1][chr]
for chr in range(num_chrs):
IBD0[chr] = mergeIntervals(IBD0[chr][:])
IBD1[chr] = mergeIntervals(IBD1[chr][:])
IBD2[chr] = mergeIntervals(IBD2[chr][:])
return [IBD0,IBD1,IBD2]
def collectIBDsegmentsSibsAvuncular(sibset, avunc, all_segs): # n is number of individuals
# greedily collect IBD0 regions, then add IBD1 regions, then add IBD2 regions
IBD_all = {}
# Collect IBD0/1/2 between sibs and avuncular
for ind1 in sibset:
if not ind1 in IBD_all.keys():
IBD_all[ind1] = {}
for ind2 in avunc:
if not ind2 in IBD_all[ind1].keys():
IBD_all[ind1][ind2] = None
tmp = getIBDsegments(ind1, ind2, all_segs)
#tmp0 = getIBD0(tmp[0],tmp[1])
for chr in range(num_chrs):
#tmp0[chr].sort()
tmp[0][chr].sort()
tmp[1][chr].sort()
IBD_all[ind1][ind2] = [[],tmp[0],tmp[1]]
return IBD_all
def collectIBDsegmentsSibsAvuncularCombine(sibset, avunc, all_segs):
# greedily collect IBD0 regions, then add IBD1 regions, then add IBD2 regions
# also merge IBD0/1/2 intervals
IBD_all = {}
# Collect IBD0/1/2 between sibs and avuncular
for ind1 in sibset:
IBD_all[ind1] = {}
IBD_all[ind1]['A'] = []
tmp_ind1 = [ { chr : [] for chr in range(num_chrs) } for _ in range(2) ]
for ind2 in avunc:
tmp = getIBDsegments(ind1, ind2, all_segs) #[IBD1, IBD2]
# for chr in range(num_chrs):
# tmp[0][chr].sort()
# for chr in range(num_chrs):
# tmp[1][chr].sort()
for chr in range(num_chrs):
tmp_ind1[0][chr] += tmp[0][chr]
tmp_ind1[1][chr] += tmp[1][chr]
for chr in range(num_chrs):
tmp_ind1[0][chr] = mergeIntervals(tmp_ind1[0][chr][:])
tmp_ind1[1][chr] = mergeIntervals(tmp_ind1[1][chr][:])
IBD_all[ind1]['A'] = [{},tmp_ind1[0],tmp_ind1[1]] #return IBD1, IBD2
return IBD_all
def checkOverlap(range1, range2):
#check if two numerical ranges overlap
if not range1[1] <= range2[0] and not range2[1] <= range1[0]: # one range doesn't end before start of other range
return 1
else:
return 0
def findOverlap(sibseg, avsib, ss1, sa1, sa2, Eval):
# Find regions of the genome which have sibling and avuncular IBD states as defined by ss1, sa1, sa2
# ranges = ranges we already have in place and therefore cannot overlap; we update and return ranges with added info
# Eval = expected amount of parent genome we get with this ss1/sa1/sa2 combination
# sibseg = pairwise IBD segments between siblings
# avsib = pairwise IBD segments between siblings and avuncular
# ss1 = IBD type (0/1/2) between siblings
# sa1 = IBD type (0/1/2) between one of those siblings and avuncular
# sa2 = IBD type (0/1/2) between the other sibling and the avuncular
# Eval=1
# ss1 = 0
# sa1 = 0
# sa2 = 0
#
# For IBD2 between cousins' parents (siblings):
# sibseg = collectIBDsegments(sib1, all_segs)
# avsib = collectIBDsegmentsSibsAvuncularCombine(sib1, sib2, all_segs)
# IBD011 = findOverlap(sibseg, avsib, 0, 1, 1, 0.5)
all_seg = { chr : [] for chr in range(num_chrs) }
ranges = { chr : [] for chr in range(num_chrs) }
for chr in range(num_chrs):
for sib1 in sibseg.keys():
for sib2 in sibseg[sib1].keys():
for av in avsib[sib1].keys(): # avsib[sib1].keys() and avsib[sib2].keys() are the same
ranges_to_append = []
ksib = 0
kav1 = 0
kav2 = 0
krange_cont = 0
while ksib < len(sibseg[sib1][sib2][ss1][chr]) and kav1 < len(avsib[sib1][av][sa1][chr]) and kav2 < len(avsib[sib2][av][sa2][chr]):
if checkOverlap(sibseg[sib1][sib2][ss1][chr][ksib],
avsib[sib1][av][sa1][chr][kav1]) and checkOverlap(
sibseg[sib1][sib2][ss1][chr][ksib], avsib[sib2][av][sa2][chr][kav2]) and checkOverlap(
avsib[sib2][av][sa2][chr][kav2], avsib[sib1][av][sa1][chr][kav1]):
# if all three segments overlap
range_add = [max(sibseg[sib1][sib2][ss1][chr][ksib][0], avsib[sib1][av][sa1][chr][kav1][0],
avsib[sib2][av][sa2][chr][kav2][0]),
min(sibseg[sib1][sib2][ss1][chr][ksib][1], avsib[sib1][av][sa1][chr][kav1][1],
avsib[sib2][av][sa2][chr][kav2][1]), Eval, sib1, sib2, av]
to_append = [range_add[0],range_add[1],sib1,sib2,av]
all_seg[chr].append(to_append)
if not krange_cont:
krange = 0
while krange < len(ranges[chr]) and ranges[chr][krange][1] <= range_add[0]:
krange = krange + 1
if krange < len(ranges[chr]):
if range_add[0:2] != ranges[chr][krange][0:2]:
if checkOverlap(range_add, ranges[chr][krange]):
range_new = []
if range_add[0] < ranges[chr][krange][0]: # new range starts before ranges[krange]
if krange > 0:
range_new.append([max(range_add[0], ranges[chr][krange - 1][1]),
ranges[chr][krange][0], Eval, sib1, sib2, av])
else:
range_new.append(
[range_add[0], ranges[chr][krange][0], Eval, sib1, sib2, av])
if range_add[1] > ranges[chr][krange][1]: # new range ends after krange
if krange < len(ranges[chr]) - 1:
new_range = [ranges[chr][krange][1],
min(range_add[1], ranges[chr][krange + 1][0]), Eval, sib1,
sib2, av]
if new_range[0] != new_range[1]:
range_new.append(new_range)
if new_range[0] > new_range[1]:
chr_name = chrom_idx_to_name[chr]
print('ERROR: '+sib1+'\t'+sib2+'\t'+av+'\t'+ chr_name + '\t' + str(ranges[chr][krange][1]) + '\t' + str(
ranges[chr][krange + 1][0]) + '\n')
else:
range_new.append(
[ranges[chr][krange][1], range_add[1], Eval, sib1, sib2, av])
# krange = krange + 1
for seg in range_new:
if not seg in ranges_to_append and not seg[0] == seg[1]:
ranges_to_append.append(seg)
else: # no overlap between range_add and ranges[chr][krange]
if krange > 0:
range_add = [max(ranges[chr][krange - 1][1], range_add[0]), range_add[1],
Eval, sib1, sib2, av]
if not range_add in ranges_to_append and not range_add[0] == range_add[1]:
ranges_to_append.append(range_add)
else:
if not range_add in ranges_to_append:
ranges_to_append.append(range_add)
else:
if krange > 0:
range_add = [max(ranges[chr][krange - 1][1], range_add[0]), range_add[1], Eval,
sib1, sib2, av]
if not range_add in ranges_to_append and not range_add[0] == range_add[1]:
ranges_to_append.append(range_add)
else:
if not range_add in ranges_to_append and not range_add[0] == range_add[1]:
ranges_to_append.append(range_add)
if krange < len(ranges[chr]):
if sibseg[sib1][sib2][ss1][chr][ksib][1] <= avsib[sib1][av][sa1][chr][kav1][1] and \
sibseg[sib1][sib2][ss1][chr][ksib][1] <= \
avsib[sib2][av][sa2][chr][kav2][1] and \
sibseg[sib1][sib2][ss1][chr][ksib][1] <= ranges[chr][krange][1]:
ksib = ksib + 1
krange_cont = 0
elif avsib[sib1][av][sa1][chr][kav1][1] <= sibseg[sib1][sib2][ss1][chr][ksib][1] and \
avsib[sib1][av][sa1][chr][kav1][1] <= avsib[sib2][av][sa2][chr][kav2][
1] and avsib[sib1][av][sa1][chr][kav1][1] <= ranges[chr][krange][1]:
kav1 = kav1 + 1
krange_cont = 0
elif avsib[sib2][av][sa2][chr][kav2][1] <= sibseg[sib1][sib2][ss1][chr][ksib][1] and \
avsib[sib2][av][sa2][chr][kav2][1] <= avsib[sib1][av][sa1][chr][kav1][
1] and avsib[sib2][av][sa2][chr][kav2][1] <= ranges[chr][krange][1]:
kav2 = kav2 + 1
krange_cont = 0
elif ranges[chr][krange][1] <= sibseg[sib1][sib2][ss1][chr][ksib][1] and \
ranges[chr][krange][1] <= avsib[sib1][av][sa1][chr][kav1][1] and \
ranges[chr][krange][1] <= avsib[sib2][av][sa2][chr][kav2][1]:
krange = krange + 1
krange_cont = 1
else:
if sibseg[sib1][sib2][ss1][chr][ksib][1] <= avsib[sib1][av][sa1][chr][kav1][1] and \
sibseg[sib1][sib2][ss1][chr][ksib][1] <= \
avsib[sib2][av][sa2][chr][kav2][1]:
ksib = ksib + 1
krange_cont = 0
elif avsib[sib1][av][sa1][chr][kav1][1] <= sibseg[sib1][sib2][ss1][chr][ksib][1] and \
avsib[sib1][av][sa1][chr][kav1][1] <= avsib[sib2][av][sa2][chr][kav2][
1]:
kav1 = kav1 + 1
krange_cont = 0
elif avsib[sib2][av][sa2][chr][kav2][1] <= sibseg[sib1][sib2][ss1][chr][ksib][1] and \
avsib[sib2][av][sa2][chr][kav2][1] <= avsib[sib1][av][sa1][chr][kav1][
1]:
kav2 = kav2 + 1
krange_cont = 0
elif sibseg[sib1][sib2][ss1][chr][ksib][1] <= avsib[sib1][av][sa1][chr][kav1][1] and \
sibseg[sib1][sib2][ss1][chr][ksib][1] <= avsib[sib2][av][sa2][chr][kav2][1]:
ksib = ksib + 1
krange_cont = 0
elif avsib[sib1][av][sa1][chr][kav1][1] <= sibseg[sib1][sib2][ss1][chr][ksib][1] and \
avsib[sib1][av][sa1][chr][kav1][1] <= avsib[sib2][av][sa2][chr][kav2][1]:
kav1 = kav1 + 1
krange_cont = 0
elif avsib[sib2][av][sa2][chr][kav2][1] <= sibseg[sib1][sib2][ss1][chr][ksib][1] and \
avsib[sib2][av][sa2][chr][kav2][1] <= avsib[sib1][av][sa1][chr][kav1][1]:
kav2 = kav2 + 1
krange_cont = 0
ranges[chr] += ranges_to_append
ranges[chr].sort()
return ranges
def getSiblingRelativeFamIBDLengthIBD2(sib1, sib2, avunc1, avunc2, all_segs):
#get total IBD length between two sets of relatives (sib1+avunc1 and sib2+avunc2)
#return length and number of individuals in each set with IBD segments
sibandav = sib1.copy()
for avunc in avunc1:
sibandav.add(avunc)
sibandav_rel = sib2.copy()
for avunc in avunc2:
sibandav_rel.add(avunc)
all_seg_IBD1 = { chr : [] for chr in range(num_chrs) }
all_seg_IBD2 = { chr : [] for chr in range(num_chrs) }
has_seg_sib1 = [0 for x in range(len(sib1))]
has_seg_sib2 = [0 for x in range(len(sib2))]
has_seg_avunc1 = [0 for x in range(len(avunc1))]
has_seg_avunc2 = [0 for x in range(len(avunc2))]
sib1 = list(sib1)
sib2 = list(sib2)
avunc1 = list(avunc1)
avunc2 = list(avunc2)
for ind1 in sibandav:
for ind2 in sibandav_rel:
tmp = getIBDsegments(ind1, ind2, all_segs)
for chr in range(num_chrs): # add IBD1
if len(tmp[0][chr]) > 0 or len(tmp[1][chr]) > 0:
# mark if these individuals have segments that were used
if ind1 in sib1:
has_seg_sib1[sib1.index(ind1)] = 1
elif ind1 in avunc1:
has_seg_avunc1[avunc1.index(ind1)] = 1
if ind2 in sib2:
has_seg_sib2[sib2.index(ind2)] = 1
elif ind2 in avunc2:
has_seg_avunc2[avunc2.index(ind2)] = 1
all_seg_IBD1[chr] += tmp[0][chr]
all_seg_IBD2[chr] += tmp[1][chr]
IBD_sum = 0
for chr in range(num_chrs):
all_seg_IBD1[chr] = mergeIntervals(all_seg_IBD1[chr][:])
for seg in all_seg_IBD1[chr]:
IBD_sum += seg[1] - seg[0]
all_seg_IBD2[chr] = mergeIntervals(all_seg_IBD2[chr][:])
for seg in all_seg_IBD2[chr]:
IBD_sum += 2.0*(seg[1] - seg[0])
return [IBD_sum, sum(has_seg_sib1), sum(has_seg_sib2), sum(has_seg_avunc1), sum(has_seg_avunc2)]
def getInferredWithRel(total_IBD, pct_par, pct_par_rel):
# using total length of IBD (in cM) and expected percentage of parent genome present in sibling set or percentage of grandparent genome present in sib + aunt/uncle set, calculate estimated K
if pct_par != 0 and pct_par_rel != 0:
K = total_IBD / total_genome / 4 * 1 / pct_par * 1 / pct_par_rel
elif pct_par == 0:
K = total_IBD / total_genome / 4 * 1 / pct_par_rel
elif pct_par_rel == 0:
K = total_IBD / total_genome / 4 * 1 / pct_par
return K # input getSiblingRelativeIBDLength
def getExpectedGP(num_sibs,num_avunc):
return (1.0 - 1.0/2.0**(num_avunc)) + (1.0/2.0**(num_avunc+1))*(1.0-1.0/2.0**num_sibs)
def getExpectedPar(num_sibs):
return (1.0-1.0/2.0**num_sibs)
def combineBothGPsKeepProportionOnlyExpectation(sib1, avunc1, pc1, sib2, avunc2, pc2, all_rel, all_segs, results_file, rel_graph):
# perform ancestral genome reconstruction between two groups of related individuals (sib1+avunc1 and sib2+avunc2)
# infers relatedness between all individuals within the two groups
# TODO! use any neice/nephews of sib1, sib2 as well
# TODO: handle twins in this?
if len(sib1) == 1 and len(sib2) == 1 and len(avunc1) == 0 and len(avunc2) == 0:
i1 = next(iter(sib1))
i2 = next(iter(sib2))
degree = getPairwiseD(i1, i2, all_rel)
return [[i1,i2, degree, degree]]
# Caller ensures this intersection is empty:
assert avunc1.intersection(avunc2) == set()
# returns total length of genome IBD between sibandav and sibandav_rel, number of sibs in sib1 with IBD segments, number of sibs in sib2 with IBD segments
[tmpsibav, sib1_len, sib2_len, av1_len, av2_len] = getSiblingRelativeFamIBDLengthIBD2(sib1, sib2, avunc1, avunc2, all_segs)
#get proportion of ancestor genome information expected on side 1
if av1_len != 0:
proportion_gp_exp = getExpectedGP(len(sib1),len(avunc1))
proportion_par_exp = 0
elif sib1_len > 1:
proportion_gp_exp = 0
proportion_par_exp = getExpectedPar(len(sib1))
else:
proportion_par_exp = 0
proportion_gp_exp = 0
#get proportion of ancestor genome information expectedo n side2
if av2_len != 0:
proportion_gp_rel_exp = getExpectedGP(len(sib2), len(avunc2))
proportion_par_rel_exp = 0
elif sib2_len > 1:
proportion_gp_rel_exp = 0
proportion_par_rel_exp = getExpectedPar(len(sib2))
else:
proportion_par_rel_exp = 0
proportion_gp_rel_exp = 0
bothSides = True
if proportion_gp_exp != 0:
if proportion_gp_rel_exp != 0: #both grandparents reconstructed
K_exp = getInferredWithRel(tmpsibav, proportion_gp_exp, proportion_gp_rel_exp)
base = 4
elif proportion_par_rel_exp != 0: #gp1 reconstructed, par2 reconstructed
K_exp = getInferredWithRel(tmpsibav, proportion_gp_exp, proportion_par_rel_exp)
base = 3
else: #gp1 reconstructed, nothing for sib2
K_exp = getInferredWithRel(tmpsibav, proportion_gp_exp, 0)
base = 2
bothSides = False
elif proportion_par_exp != 0:
if proportion_gp_rel_exp != 0: #par1 reconstructed, gp2 reconstructed
K_exp = getInferredWithRel(tmpsibav, proportion_par_exp, proportion_gp_rel_exp)
base = 3
elif proportion_par_rel_exp != 0: #par1 reconstructed, par2 reconstructed
K_exp = getInferredWithRel(tmpsibav, proportion_par_exp, proportion_par_rel_exp)
base = 2
else: #par1 reconstructed, nothing for sib2
K_exp = getInferredWithRel(tmpsibav, proportion_par_exp, 0)
base = 1
bothSides = False
else:
bothSides = False # nothing for sib1
if proportion_gp_rel_exp != 0: #gp2 reconstructed
K_exp = getInferredWithRel(tmpsibav, 0, proportion_gp_rel_exp)
base = 2
elif proportion_par_rel_exp != 0: #par2 reconstructed
K_exp = getInferredWithRel(tmpsibav, 0, proportion_par_rel_exp)
base = 1
else: # neither side reconstructed
i1 = list(sib1)[0]
i2 = list(sib2)[0]
K_exp = getPairwiseK(i1, i2, all_rel)
base = 0
estimated_exp = getInferredFromK(K_exp)
IBD2 = 0
if bothSides and estimated_exp != 1 and K_exp > 1/2.0**(9.0/2): #check for IBD2 if both sides are being reconstructed, might be reconstructing two sibs; K_exp is 3rd degree or closer
if len(avunc1) and len(avunc2):
sibseg = collectIBDsegments(avunc1, all_segs)
sibsib = collectIBDsegmentsSibsAvuncularCombine(avunc1, avunc2, all_segs)
IBD011 = findOverlap(sibseg, sibsib, 0, 1, 1, 0.5)
if len(sib2) > 1: # could be the case that we have one sib and his/her aunts/uncles
sibseg2 = collectIBDsegments(avunc2, all_segs)
sibsib2 = collectIBDsegmentsSibsAvuncularCombine(avunc2, avunc1, all_segs)
IBD011_2 = findOverlap(sibseg2, sibsib2, 0, 1, 1, 0.5)
for chr in range(num_chrs):
IBD011[chr] += IBD011_2[chr]
IBD011[chr] = mergeIntervals(IBD011[chr])
IBD2 = getTotalLength(IBD011)
# TODO: if avunc1 or avunc2 have data, want to compare them with the sibs from the other side
elif not len(avunc1) and not len(avunc2):
sibseg = collectIBDsegments(sib1, all_segs)
sibsib = collectIBDsegmentsSibsAvuncularCombine(sib1, sib2, all_segs)
IBD011 = findOverlap(sibseg, sibsib, 0, 1, 1, 0.5)
if len(sib2) > 1: #could be the case that we have one sib and his/her aunts/uncles
sibseg2 = collectIBDsegments(sib2, all_segs)
sibsib2 = collectIBDsegmentsSibsAvuncularCombine(sib2, sib1, all_segs)
IBD011_2 = findOverlap(sibseg2, sibsib2, 0, 1, 1, 0.5)
for chr in range(num_chrs):
IBD011[chr] += IBD011_2[chr]
IBD011[chr] = mergeIntervals(IBD011[chr])
IBD2 = getTotalLength(IBD011)
if proportion_par_exp != 0:
IBD2 = IBD2 / proportion_par_exp
elif proportion_gp_exp != 0:
IBD2 = IBD2 / proportion_gp_exp
if proportion_par_rel_exp != 0:
IBD2 = IBD2 / proportion_par_rel_exp
elif proportion_gp_rel_exp != 0:
IBD2 = IBD2 / proportion_gp_rel_exp
if IBD2 != 0:
# Note: this counts IBD1 with the IBD2 via the fact that we only count IBD2 as if it
# were IBD1
estimated_exp = getInferredFromK(K_exp + IBD2 / total_genome / 2.0)
result = []
if estimated_exp >= 0:
estimated_exp = estimated_exp + base
#get all combinations of pairs for results
for sib_rel in sib2:
# same degree for siblings:
estimated_out_exp = estimated_exp
for sib in sib1:
refined = getPairwiseD(sib_rel, sib, all_rel)
to_add = [sib_rel, sib, estimated_out_exp, refined, 'combine1']
result.append(to_add)
# avunc1 samples 1 degree closer to sib2:
if estimated_exp > 0:
estimated_out_exp = estimated_exp - 1
else:
estimated_out_exp = -1
for avunc in avunc1:
refined = getPairwiseD(sib_rel, avunc, all_rel)
to_add = [sib_rel, avunc, estimated_out_exp, refined, 'combine2']
result.append(to_add)
for avunc_rel in avunc2:
# sib1 samples 1 degree closer to avunc2:
if estimated_exp > 0:
estimated_out_exp = estimated_exp - 1
else:
estimated_out_exp = -1
for sib in sib1:
refined = getPairwiseD(sib, avunc_rel, all_rel)
to_add = [sib, avunc_rel, estimated_out_exp, refined, 'combine3']
result.append(to_add)
# avunc1 samples 2 degrees closer to avunc2:
if estimated_exp > 0:
estimated_out_exp = estimated_exp - 2
else:
estimated_out_exp = -1
for avunc in avunc1:
refined = getPairwiseD(avunc, avunc_rel, all_rel)
to_add = [avunc, avunc_rel, estimated_out_exp, refined, 'combine4']
result.append(to_add)
return result
def checkRelevantAuntsUncles(sibset1, sibset2, avunc1_bothsides, avunc2_bothsides, par1, par2, all_rel):
# check whether aunt/uncle should be included in analysis
avunc1 = set()
avunc2 = set()
for avset1 in avunc1_bothsides:
avunc1 = avunc1.union(avset1)
for avset2 in avunc2_bothsides:
avunc2 = avunc2.union(avset2)
if avunc1.intersection(avunc2) != set():
#sibset1's aunt/uncles are the same as sibset2's
return ['same', '']
if avunc1.intersection(par2) != set():
#sibset1's aunt/uncles contain sibset2's parent
return ['avsib', '']
if avunc1.intersection(sibset2) != set():
#sibset1's aunt/uncle is in sibset2 (sibset2 = aunts/uncles of sibset1)
return ['av', '']
if avunc2.intersection(par1) != set():
#sibset2's aunt/uncles contain sibset1's parent
return ['', 'avsib']
if avunc2.intersection(sibset1) != set():
#sibset2's aunt/uncle is in sibset1 (sibset1 = aunts/uncles of sibset2)
return ['av', '']
minsib = 50 # impossible value will be updated
for s1 in sibset1:
for s2 in sibset2:
kinship = getPairwiseK(s1, s2, all_rel)
if kinship < minsib:
minsib = kinship
# for av1 in avunc1:
# for av2 in avunc2:
# if getPairwiseD(av1, av2, all_rel) == 1:
# if getIBD1(av1, av2, all_rel) > 0.9:
# return ['avparent',[av1,av2], [], []]
# elif getIBD2(av1, av2, all_rel) > 1/2.0**(3.0/2):
# return ['sib', [av1,av2], [], []]
relavunc1 = set()
relavunc2 = set()
for s1 in sibset1:
for a2 in avunc2:
# if getPairwiseD(s1, a2, all_rel) == 1:
# if getIBD1(s1, a2, all_rel) + getIBD2(s1, a2, all_rel) > 0.9: # a2 is parent of s1
# return ['sibparent',[s1,a2], [], []]
kinship = getPairwiseK(s1, a2, all_rel)
if kinship > minsib:
relavunc2.add(a2)
for s2 in sibset2:
for a1 in avunc1:
# if getPairwiseD(s2, a1, all_rel) == 1:
# if getIBD1(s2, a1, all_rel) + getIBD2(s2, a1, all_rel) > 0.9: # a1 is parent of s2
# return [[s2,a1],'sibparent', [], []]
kinship = getPairwiseK(s2, a1, all_rel)
if kinship > minsib:
relavunc1.add(a1)
if len(avunc1_bothsides):
for avset1 in avunc1_bothsides:
if avset1.intersection(relavunc1):
relavunc1 = relavunc1.union(avset1)
if len(avunc2_bothsides):
for avset2 in avunc2_bothsides:
if avset2.intersection(relavunc2):
relavunc2 = relavunc2.union(avset2)
return [relavunc1, relavunc2]
def getTotalLength(IBD):
# get length of IBD segments
total = 0
for chr in range(num_chrs):
for seg in IBD[chr]:
total += seg[1] - seg[0]
return total
def getAllRel(results_file, inds_file):
# read in results file:
# all_rel: dict of ind1, dict of ind2, list of [IBD1, IBD2, K, D
# store pairwise relatedness information
global inds
first = [] #list of first degree relative pairs according to Refined IBD results
second = [] #list of second degree relative pairs according to Refined IBD results
third = [] #list of third degree relative pairs according to Refined IBD results
inds = set()
if inds_file != '':
file = open(inds_file,'r')
for line in file:
l = str.split(line.rstrip())
if len(l):
inds.add(l[0])
file.close()
all_rel = {}
file = open(results_file,'r')
for line in file: