-
Notifications
You must be signed in to change notification settings - Fork 0
/
hf_aligner2.py
4506 lines (3654 loc) · 164 KB
/
hf_aligner2.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
#!/usr/bin/env python3
import torch
from transformers import AutoTokenizer, AutoModel
import numpy as np
from sklearn.metrics.pairwise import cosine_similarity
import random
from transformer_infrastructure.hf_utils import build_index_flat, build_index_voronoi
from transformer_infrastructure.run_tests import run_tests
from transformer_infrastructure.hf_embed import parse_fasta_for_embed, get_embeddings
from transformer_infrastructure.hf_seqsim import get_seqsims
# Printing for debugging with icecream
try:
from icecream import ic
ic.configureOutput(includeContext=True, outputFunction=print) # Prints line number and function
except ImportError: # Graceful fallback if IceCream isn't installed.
ic = lambda *a: None if not a else (a[0] if len(a) == 1 else a) # noqa
# This is combat with patsy requirement removed
from transformer_infrastructure.combat2 import combat
#import line_profiler
#import atexit
#profile = line_profiler.LineProfiler()
#atexit.register(profile.ic_stats)
import copy
from Bio import SeqIO
from Bio.Align import MultipleSeqAlignment
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
from sklearn.preprocessing import normalize
import faiss
import pickle
import argparse
import os
import shutil
import sys
import igraph
from pandas.core.common import flatten
import pandas as pd
from collections import Counter
import matplotlib.pyplot as plt
import logging
from sklearn.metrics.pairwise import cosine_similarity
class AA:
def __init__(self):
self.seqnum = ""
self.seqindex = ""
self.seqpos = ""
self.seqaa = ""
self.index = ""
self.clustid = ""
self.prevaa = ""
self.nextaa = ""
#__str__ and __repr__ are for pretty printing
def __str__(self):
return("{}-{}-{}".format(self.seqnum, self.seqpos, self.seqaa))
def __repr__(self):
return str(self)
class Alignment:
def __init__(self, alignment, seqnames = []):
self.alignment = alignment
if not seqnames:
self.seqnames = list(range(0, len(self.alignment)))
else:
self.seqnames = seqnames
self.numseqs = len(self.alignment)
self.width = len(self.alignment[0])
self.numassigned = len([x for x in flatten(self.alignment) if x != "-"])
self.numgaps = len([x for x in flatten(self.alignment) if x == "-"])
self.str_formatted = self.str_format(alignment)
def str_format(self, alignment):
str_alignment = []
for line in alignment:
row_str = ""
for aa in line:
if aa == "-":
row_str = row_str + aa
else:
row_str = row_str + aa.seqaa
str_alignment.append(row_str)
return(str_alignment)
def format_aln(self, style = "clustal"):
records = []
for i in range(len(self.str_formatted)):
ic(self.str_formatted[i])
alignment_str = "".join([self.str_formatted[i]])
records.append(SeqRecord(Seq(alignment_str), id=str(self.seqnames[i]), description = "", name = ""))
align = MultipleSeqAlignment(records)
if style == "clustal":
formatted = format(align, 'clustal')
elif style == "fasta":
formatted = format(align, 'fasta')
return(formatted)
def __str__(self):
return(self.format_aln( "clustal"))
def __repr__(self):
return str(self)
def get_seqs_aas(seqs, seqnums):
seqs_aas = []
seq_to_length = {}
for i in range(len(seqs)):
seq_aas = []
seqnum = seqnums[i]
seq_to_length[i] = len(seqs[i])
for j in range(len(seqs[i])):
# If first round, start new AA
# Otherwise, use the next aa as the current aa
if j == 0:
aa = AA()
aa.seqnum = seqnum
aa.seqpos = j
aa.seqaa = seqs[i][j]
else:
aa = nextaa
aa.prevaa = prevaa
prevaa = aa
if j < len(seqs[i]) - 1:
nextaa = AA()
nextaa.seqnum = seqnum
nextaa.seqpos = j + 1
nextaa.seqaa = seqs[i][j + 1]
aa.nextaa = nextaa
seq_aas.append(aa)
seqs_aas.append(seq_aas)
return(seqs_aas, seq_to_length)
def remove_maxlen_padding(hidden_states, seqs_aas, padded_seqlen):
# Initial index to remove maxlen padding from input embeddings
index_to_aa = {}
aa_indices = []
ic(seqs_aas)
seqlens = [len(x) for x in seqs_aas]
for i in range(len(seqs_aas)):
for j in range(padded_seqlen):
if j >= seqlens[i]:
continue
print(i, j)
aa = seqs_aas[i][j]
index_num = i * padded_seqlen + j
index_to_aa[index_num] = aa
aa_indices.append(index_num)
# Remove maxlen padding from aa embeddings
ic(hidden_states.shape)
hidden_states = np.take(hidden_states, list(index_to_aa.keys()), 0)
ic(hidden_states.shape)
index_to_aa = {}
count_index = 0
batch_list = []
seqnum_to_index = {}
for i in range(len(seqs_aas)):
seqnum_to_index[i] = []
for j in range(0, seqlens[i]):
batch_list.append(i)
aa = seqs_aas[i][j]
aa.index = count_index
aa.seqindex = i
seqnum_to_index[i].append(count_index)
index_to_aa[count_index] = aa
count_index = count_index + 1
#ic(index_to_aa)
logging.info("Build index of amino acid embeddings")
ic(batch_list)
return(index_to_aa, hidden_states, seqnum_to_index, batch_list)
def do_batch_correct(hidden_states, levels, batch_list):
hidden_states_pd = pd.DataFrame(hidden_states.T) # So that each aa in a column
ic(hidden_states_pd)
batch_series = pd.Series(batch_list)
#levels = list(range(len(seqs_aas)))
design_list = [(batch_series == level) * 1 for level in levels]
design = pd.concat(design_list, axis = 1)
hidden_states_batch = combat(hidden_states_pd, batch_list, design)
ic(hidden_states_batch)
hidden_states_corrected = np.array(hidden_states_batch).T.astype(np.float32)
return(hidden_states_corrected)
#@profile
def graph_from_cluster_orders(cluster_orders_lol):
order_edges = []
for order in cluster_orders_lol:
for i in range(len(order) - 1):
edge = (order[i], order[i + 1])
#if edge not in order_edges:
order_edges.append(edge)
#ic(edge)
G_order = igraph.Graph.TupleList(edges=order_edges, directed=True)
return(G_order, order_edges)
#@profile
def get_topological_sort(cluster_orders_lol):
#ic("start topological sort")
cluster_orders_nonempty = [x for x in cluster_orders_lol if len(x) > 0]
#with open("tester2.txt", "w") as f:
# for x in cluster_orders_nonempty:
# f.write("{}\n". format(x))
dag_or_not = graph_from_cluster_orders(cluster_orders_nonempty)[0].simplify().is_dag()
#
#ic ("Dag or Not?, dag check immediately before topogical sort", dag_or_not)
G_order = graph_from_cluster_orders(cluster_orders_nonempty)[0]
G_order = G_order.simplify()
topo_sort_indices = G_order.topological_sorting()
cluster_order = []
# Note: this is in vertex indices. Need to convert to name to get clustid
for i in topo_sort_indices:
cluster_order.append(G_order.vs[i]['name'])
return(cluster_order) #, clustid_to_clust_dag)
#@profile
def remove_order_conflicts(cluster_order, seqs_aas, pos_to_clustid):
#ic("remove_order_conflicts, before: ", cluster_order)
bad_clustids = []
for x in seqs_aas:
prevpos = -1
for posid in x:
try:
clustid = pos_to_clustid[posid]
except Exception as E:
continue
pos = posid.seqpos
if pos < prevpos:
#ic("Order violation", posid, clustid)
bad_clustids.append(clustid)
cluster_order = [x for x in cluster_order if x not in bad_clustids]
return(cluster_order)
#@profile
def candidate_to_remove(G, v_names,z = -5):
weights = {}
num_prots = len(G.vs())
ic("num_prots")
if num_prots <=3:
return([])
for i in v_names:
# Potentially put in function
g_new = G.copy()
vs = g_new.vs.find(name = i)
weight = sum(g_new.es.select(_source=vs)['weight'])
weights[i] = weight
#weights.append(weight)
questionable_z = []
#ic("Sequence z scores, current threshold: ", z)
for i in v_names:
others = []
for key,value in weights.items():
if key == i:
own_value = value
else:
others.append(value)
#others = [weights[x] for x in range(len(weights)) if x != i]
ic(own_value, others)
seq_z = (own_value - np.mean(others))/np.std(others)
#seq_z = (weights[i] - np.mean(others))/np.std(others)
ic("sequence ", i, " zscore ", seq_z)
# This should scale with # of sequences?
# If on average high similarity, don't call as questionable even if high z
# Avoid 1.65, 1.72, 1.71 three protein case.
#if (own_value / (num_prots - 1)) < 0.7:
if seq_z < z:
questionable_z.append(i)
ic("questionalbe_z", questionable_z)
return(questionable_z)
#@profile
def make_alignment(cluster_order, seqnums, clustid_to_clust, seqnames):
# Set up a bunch of vectors of "-"
# Replace with matches
# cluster_order = list in the order that clusters go
ic("Alignment clusters")
for clustid, clust in clustid_to_clust.items():
ic(clustid, clust)
numseqs = len(seqnums)
alignment_lol = [["-"] * len(cluster_order) for i in range(numseqs)]
#ic(cluster_order)
# #ic("test cluster order", cluster_order)
for order in range(len(cluster_order)):
cluster = clustid_to_clust[cluster_order[order]]
c_dict = {}
for x in cluster:
#for pos in x:
c_dict[x.seqnum] = x # x.seqaa
for seqnum_index in range(numseqs):
try:
# convert list index position to actual seqnum
seqnum = seqnums[seqnum_index]
alignment_lol[seqnum_index][order] = c_dict[seqnum]
except Exception as E:
continue
#ic a preview)
alignment_str = ""
print("Alignment")
alignment = Alignment(alignment_lol, seqnames)
str_alignment = alignment.str_formatted
for row_str in str_alignment:
print("Align: ", row_str[0:170])
return(alignment)
##@profile
#def alignment_ic(alignment, seq_names):
#
# records = []
# #alignment = ["".join(x) for x in alignment]
# alignment = obj_aln_to_str(alignment)
#
# for i in range(len(alignment)):
# #ic(seq_names[i], alignment[i])
# #ic(alignment[i], seq_names[i])
# records.append(SeqRecord(Seq(alignment[i]), id=seq_names[i]))
# align = MultipleSeqAlignment(records)
# clustal_form = format(align, 'clustal')
# fasta_form = format(align, 'fasta')
# return(clustal_form, fasta_form)
#@profile
def get_ranges(seqs_aas, cluster_order, starting_clustid, ending_clustid, pos_to_clustid):
#ic("start get ranges")
#ic(cluster_order, starting_clustid, ending_clustid)
#ic('get_ranges:', seqs_aas)
#ic('get_ranges: start, end', starting_clustid, ending_clustid)
# if not x evaluates to true if x is zero
# If unassigned sequence goes to the end of the sequence
if not ending_clustid and ending_clustid != 0:
ending_clustid = np.inf
# If unassigned sequence extends before the sequence
if not starting_clustid and starting_clustid != 0:
starting_clustid = -np.inf
#ic('get_ranges: start, end', starting_clustid, ending_clustid)
# cluster_order must be zero:n
# Add assertion
pos_lists = []
for x in seqs_aas:
#ic('get_ranges:x:', x)
pos_list = []
startfound = False
#ic("aa", x)
# If no starting clustid, add sequence until hit ending_clustid
if starting_clustid == -np.inf:
startfound = True
prevclust = ""
for pos in x:
if pos in pos_to_clustid.keys():
pos_clust = pos_to_clustid[pos]
prevclust = pos_clust
# Stop looking if clustid after ending clustid
if pos_clust >= ending_clustid:
break
# If the clustid is between start and end, append the position
elif pos_clust > starting_clustid and pos_clust < ending_clustid:
pos_list.append(pos)
startfound = True
# If no overlap (total gap) make sure next gap sequence added
elif pos_clust == starting_clustid:
startfound = True
#ic(pos_clust, starting_clustid, ending_clustid)
else:
#ic(startfound, "exception", pos, prevclust, starting_clustid, ending_clustid)
if startfound == True or prevclust == cluster_order[-1]:
if prevclust:
if prevclust >= starting_clustid and prevclust <= ending_clustid:
pos_list.append(pos)
else:
pos_list.append(pos)
pos_lists.append(pos_list)
return(pos_lists)
#@profile
def get_unassigned_aas(seqs_aas, pos_to_clustid, too_small = []):
'''
Get amino acids that aren't in a sequence
'''
too_small_list = list(flatten(too_small))
#ic(pos_to_clustid)
unassigned = []
for i in range(len(seqs_aas)):
prevclust = []
nextclust = []
unsorted = []
last_unsorted = -1
for j in range(len(seqs_aas[i])):
if j <= last_unsorted:
continue
key = seqs_aas[i][j]
if key in pos_to_clustid.keys():
# Read to first cluster hit
clust = pos_to_clustid[key]
prevclust = clust
# If it's not in a clust, it's unsorted
else:
unsorted = []
unsorted.append(key)
for k in range(j + 1, len(seqs_aas[i])):
key = seqs_aas[i][k]
if key in pos_to_clustid.keys():
nextclust = pos_to_clustid[key]
#ic(nextclust)
break
# Go until you hit next clust or end of seq
else:
unsorted.append(key)
last_unsorted = k
unsorted = [x for x in unsorted if x not in too_small_list]
unassigned.append([prevclust, unsorted, nextclust, i])
nextclust = []
prevclust = []
return(unassigned)
#@profile
def get_looser_scores(aa, index, hidden_states):
'''Get all scores with a particular amino acid'''
hidden_state_aa = np.take(hidden_states, [aa.index], axis = 0)
# Search the total number of amino acids
n_aa = hidden_states.shape[0]
D_aa, I_aa = index.search(hidden_state_aa, k = n_aa)
return(list(zip(D_aa.tolist()[0], I_aa.tolist()[0])))
#@profile
def get_particular_score(D, I, aa1, aa2):
''' Use with squish, replace with get_looser_scores '''
#ic(aa1, aa2)
#seqnum different_from index
#ic(D.shape)
#ic(aa1.index)
#ic(aa2.index)
scores = D[aa1.index][aa1.seqpos][aa2.index]
#ic(scores)
ids = I[aa1.index][aa1.seqpos][aa2.index]
#ic(ids)
for i in range(len(ids)):
#ic(aa1, score_aa, scores[i])
if ids[i] == aa2:
#ic(aa1, aa2, ids[i], scores[i])
return(scores[i])
else:
return(0)
#@profile
def address_isolated_aas(unassigned_aa, cohort_aas, D, I, minscore):
'''
Maybe overwrite score?
Or match to cluster with higher degree
'''
#ic("Address isolated aas")
connections = []
for cohort_aa in cohort_aas:
score = get_particular_score(unassigned_aa, cohort_aa, D, I)
#ic(unassigned_aa, cohort_aa, score)
return(cluster)
#@profile
def clusts_from_alignment(alignment):
# Pass alignment object around.
# Contains both cluster order and clustid_to_clust info
clustid_to_clust = {}
#align_length = len(alignment[0])
cluster_order = range(0, alignment.width)
for i in cluster_order:
clust = [x[i] for x in alignment.alignment if not x[i] == "-"]
clustid_to_clust[i] = clust
return(cluster_order, clustid_to_clust)
#@profile
def address_stranded3(alignment):
cluster_order, clustid_to_clust = clusts_from_alignment(alignment)
to_remove =[]
#clustered_aas = list(flatten(clustid_to_clust.values()))
new_cluster_order = []
new_clustid_to_clust = {}
#ic(clustered_aas)
for i in range(0, len(cluster_order)):
# If it's the first cluster
if i == 0:
prevclust = []
else:
prevclustid =cluster_order[i - 1]
prevclust = clustid_to_clust[prevclustid]
# If it's the last cluster
if i == len(cluster_order) - 1:
nextclust = []
else:
nextclustid =cluster_order[i + 1]
nextclust = clustid_to_clust[nextclustid]
currclustid =cluster_order[i]
currclust = clustid_to_clust[currclustid]
removeclust = False
# DON'T do stranding before bestmatch
# Because a good column can be sorted into gaps
for aa in currclust:
#ic("cluster ", i, aa.prevaa, aa.nextaa,prevclust,nextclust)
if aa.prevaa not in prevclust and aa.nextaa not in nextclust:
ic("cluster ", i, aa.prevaa, aa.nextaa,prevclust,nextclust)
ic(aa, "in clust", currclust, "is stranded")
ic("removing")
removeclust = True
if removeclust == False:
new_cluster_order.append(currclustid)
new_clustid_to_clust[currclustid] = currclust
else:
ic("Found stranding, Removing stranded clust", currclust)
return(new_cluster_order, new_clustid_to_clust)
#@profile
def squish_clusters2(alignment, index, hidden_states, index_to_aa):
'''
There are cases where adjacent clusters should be one cluster.
If any quality scores, squish them together(tetris style)
XA-X -> XAX
X-AX -> XAX
XA-X -> XAX
Start with doing this at the end
With checks for unassigned aa's could do earlier
Get total score between adjacent clusters
Only record if no conflicts
Set up network
Merge highest score out edge fom each cluster
Repeat a few times
'''
ic("attempt squish")
cluster_order, clustid_to_clust = clusts_from_alignment(alignment)
candidate_merge_list = []
for i in range(len(cluster_order)-1):
c1 = clustid_to_clust[cluster_order[i]]
# skip cluster that was 2nd half of previous squish
if len(c1) == 0:
continue
c2 = clustid_to_clust[cluster_order[i + 1]]
c1_seqnums = [x.seqnum for x in c1]
c2_seqnums = [x.seqnum for x in c2]
seqnum_overlap = set(c1_seqnums).intersection(set(c2_seqnums))
# Can't merge if two clusters already have same sequences represented
if len(seqnum_overlap) > 0:
continue
else:
intra_clust_hits= []
for aa1 in c1:
candidates = get_looser_scores(aa1, index, hidden_states)
for candidate in candidates:
#try:
score = candidate[0]
candidate_index = candidate[1]
if candidate_index == -1:
continue
target_aa = index_to_aa[candidate_index]
#ic("target_aa", target_aa)
if target_aa in c2:
if score > 0:
intra_clust_hits.append(score )
ic(aa1, target_aa, score)
#except Exception as E:
# # Not all indices correspond to an aa, yes they do
# continue
ic("intra clust hits", intra_clust_hits)
ic("c1", c1)
ic("c2", c2)
combo = c1 + c2
#scores = [x[2] for x in intra_clust_hits if x is not None]
candidate_merge_list.append([cluster_order[i], cluster_order[i + 1], sum(intra_clust_hits)])
ic("candidate merge list", candidate_merge_list)
removed_clustids = []
edges = []
weights = []
for x in candidate_merge_list:
edges.append((x[0], x[1]))
weights.append(x[2])
to_merge = []
# Repititions deal with particular case
# 1-2:0.5 2-3:0.4 3-4:0.3
# which simplifies to
# 1-2:0.5 2-3:0.4
# (best hit for 2 best hit for 3)
for squish in [1,2, 3, 4, 5, 6, 7, 8, 9, 10]:
# Start with scores between adjacent clusters
# Want to merge the higher score when there's a choice
#ic(edges)
G = igraph.Graph.TupleList(edges=edges, directed=False)
G.es['weight'] = weights
islands = G.clusters(mode = "weak")
edges = []
weights = []
for sub_G in islands.subgraphs():
n = len(sub_G.vs())
ic(sub_G)
#ic(n)
node_highest = {}
# If isolated pair, no choice needed
if n == 2:
to_merge.append([x['name'] for x in sub_G.vs()])
for vertex in sub_G.vs():
node_highest[vertex['name']] = 0
if vertex.degree() == 1:
continue
vertex_id= vertex.index
sub_edges = sub_G.es.select(_source = vertex_id)
max_weight = max(sub_edges['weight'])
#ic(max_weight)
maybe = sub_edges.select(weight_eq = max_weight)
ic(vertex)
for e in maybe:
highest_edge = [x['name'] for x in sub_G.vs() if x.index in e.tuple]
ic(highest_edge, max_weight)
#if max_weight > node_highest[highest_edge[0]]:
# node_highest[highest_edge[0]] = max_weight
if highest_edge not in edges:
edges.append(highest_edge)
weights.append(max_weight)
#ic(highest_edge)
#ic(node_highest)
#if highest_edge not in to_merge:
# to_merge.append(highest_edge)
ic("to_merge", to_merge)
for c in to_merge:
#c = [cluster1, cluster2]
removed_clustids.append(c[1])
clustid_to_clust[c[0]] = clustid_to_clust[c[0]] + clustid_to_clust[c[1]]
clustid_to_clust[c[1]] = []
#ic("Old cluster order", cluster_order)
cluster_order = [x for x in cluster_order if x not in removed_clustids]
#ifor vs in sub_G.vs():
return(cluster_order, clustid_to_clust)
#@profile
def remove_overlap_with_old_clusters(new_clusters, prior_clusters):
'''
Discard any new clusters that contain elements of old clusters
Only modify new clusters in best match-to-cluster process
'''
aas_in_prior_clusters = list(flatten(prior_clusters))
#ic("aas in prior", aas_in_prior_clusters)
final_new_clusters = []
for n in new_clusters:
#for p in prior_clusters:
overlap = list(set(aas_in_prior_clusters).intersection(set(n)))
if len(overlap) > 0:
#ic("prior", p)
#ic("new with overlap of old ", n)
continue
elif n in final_new_clusters:
continue
else:
final_new_clusters.append(n)
return(final_new_clusters)
#@profile
def remove_feedback_edges(cluster_orders_dict, clustid_to_clust, gapfilling_attempt, remove_both = True, alignment_group = 0, attempt = 0, all_alternates_dict = {}, args = None):
"""
Remove both improves quality of initial alignment by remove both aas that are found out of order
For final refinement, only remove the first one that occurs out of order
"""
ic("argssss", args)
record_dir = args.record_dir
outfile_name = args.outfile_name
ic("before feedback_edges")
ic(clustid_to_clust)
G_order, order_edges = graph_from_cluster_orders(list(cluster_orders_dict.values()))
#ic(G_order)
weights = [1] * len(G_order.es)
# Remove multiedges and self loops
#ic(G_order)
G_order.es['weight'] = weights
G_order = G_order.simplify(combine_edges=sum)
ic("after combine")
#ic(G_order)
dag_or_not = G_order.is_dag()
# The edges to remove to make a directed acyclical graph
# Corresponds to "look backs"
# With weight, fas, with try to remove lighter edges
# Feedback arc sets are edges that point backward in directed graph
fas = G_order.feedback_arc_set(weights = 'weight')
ic("feedback arc set")
for x in fas:
ic("arc", x)
write_ordernet = True
if write_ordernet == True:
outnet = "{}/{}.ordernet_{}_attempt-{}_gapfilling-{:04}.csv".format(record_dir, outfile_name, alignment_group, attempt, gapfilling_attempt)
ic("outnet", outnet, gapfilling_attempt)
with open(outnet, "w") as outfile:
outfile.write("c1,c2,aas1,aas2,gidx1,gidx2,weight,feedback\n")
# If do reverse first, don't have to do second resort
for edge in G_order.es():
feedback = "no"
if edge.index in fas:
feedback = "yes"
source_name = G_order.vs[edge.source]["name"]
target_name = G_order.vs[edge.target]["name"]
source_aas = "_".join([str(x) for x in clustid_to_clust[source_name]])
target_aas = "_".join([str(x) for x in clustid_to_clust[target_name]])
outstring = "{},{},{},{},{},{},{},{}\n".format(source_name, target_name, source_aas, target_aas , edge.source, edge.target, edge['weight'], feedback)
outfile.write(outstring)
#i = 0
to_remove = []
removed_edges = []
removed_clustids = []
for feedback_arc in fas:
edge = G_order.es()[feedback_arc]
source_name = G_order.vs[edge.source]["name"]
target_name = G_order.vs[edge.target]["name"]
ic("Feedback edge {}, index {}, edge.source {} edge.target {} source_name {}, target_name {}" .format(edge, edge.index, edge.source, edge.target, source_name, target_name))
# If one node in the feedback edges is significantly stronger (i.e. more incumbent edges"
# Actually just use degree
strength_source = G_order.strength(edge.source, weights = "weight")
strength_target = G_order.strength(edge.target, weights = "weight")
print("STRENGTH source", source_name, strength_source)
print("STRENGTH target", target_name, strength_target)
if strength_source >= 2* strength_target:
#G_order.delete_vertex(edge.target)
print("keeping ", source_name)
removed_clustids.append(target_name)
#to_remove.append([[edge.target]])
elif strength_target >= 2* strength_source:
#G_order.delete_vertex(edge.source)
print("keeping ", target_name)
removed_clustids.append(source_name)
#to_remove.append([[edge.source]]))
else:
removed_edges.append((edge.source, edge.target, source_name, target_name))
# Delete feed back arc edges
G_order.delete_edges(fas)
# Check if graph is still dag if edge is added back.
# If so, keep it
for removed_edge in removed_edges:
ic("try to return", removed_edge[2:])
G_order.add_edges( [removed_edge[0:2]]) # vertex id pairs
#G_order.add_edges([removed_edge[2:]]) # vertex id pairs
ic(G_order.is_dag())
# Retain edges that aren't actually feedback loops
# Some edges identified by feedback_arc aren't actually cycles (???)
if not G_order.is_dag():
G_order.delete_edges([removed_edge[0:2]])
# Compare vertex strengths to decide which node to keep.
#G_order.delete_edges([removed_edge[2:]])
# try alternate cluster conformations
to_remove.append(removed_edge[2:4]) # list of clustid pairs
#ic(G_order)
ic("to_remove", to_remove)
remove_dict = {}
#ic("cluster_orders_dict", cluster_orders_dict)
if remove_both == True:
to_remove_flat = list(flatten(to_remove))
else:
to_remove_flat = [x[0] for x in to_remove]
#ic("to_remove 2", to_remove_flat)
clusters_to_add_back = {} # Dictionary of list of lists containing pairs of clusters to add back with modifications
#group_count = 0
for seqnum, clustorder in cluster_orders_dict.items():
remove_dict[seqnum] = []
remove = []
if len(clustorder) == 1:
if clustorder[0] in to_remove_flat:
remove_dict[seqnum] = [clustorder[0]]
#ic(clustorder)
for j in range(len(clustorder) - 1):
new_clusts_i = []
new_clusts_j = []
if (clustorder[j], clustorder[j +1]) in to_remove:
clust_i = clustid_to_clust[clustorder[j]]
clust_j = clustid_to_clust[clustorder[j + 1]]
clusters_to_add_back_list = []
for aa in clust_i:
if aa in all_alternates_dict.keys():
for alternate in all_alternates_dict[aa]:
ic("replacing {} with {}".format(aa, alternate))
new_clust_i = [x for x in clust_i if x != aa] + [alternate]
new_clusts_i.append(new_clust_i)
#clusters_to_add_back.append([new_clust_i, clust_j])
for aa in clust_j:
if aa in all_alternates_dict.keys():
for alternate in all_alternates_dict[aa]:
ic("replacing {} with {}".format(aa, alternate))
new_clust_j = [x for x in clust_j if x != aa] + [alternate]
new_clusts_j.append(new_clust_j)
for new_clust_i in new_clusts_i:
clusters_to_add_back_list.append([new_clust_i, clust_j])
for new_clust_j in new_clusts_j:
clusters_to_add_back_list.append([clust_i, new_clust_j])
clusters_to_add_back_list.append([new_clust_i, new_clust_j])
clusters_to_add_back[frozenset([j, j + 1])] = clusters_to_add_back_list
#ic(cluster_orders[i])
#ic(remove_both)
#ic(cluster_orders[i][j], cluster_orders[i][j + 1])
if remove_both == True:
remove.append(clustorder[j])
remove.append(clustorder[j + 1])
remove_dict[seqnum] = list(set(remove))
ic("remove_dict", remove_dict)
#clusters_filt_dag = []
#ic(clusters_filt)
ic("Doing remove")
reduced_clusters = []
#too_small_clusters = []
removed_clustids = removed_clustids + list(flatten(list(remove_dict.values())))
ic("removed clusters", removed_clustids)