-
Notifications
You must be signed in to change notification settings - Fork 0
/
hf_aligner.py
2112 lines (1612 loc) · 72.2 KB
/
hf_aligner.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
from transformer_infrastructure.hf_utils import build_index
from transformer_infrastructure.run_tests import run_tests
from transformer_infrastructure.hf_embed import parse_fasta_for_embed, embed_sequences
from Bio import SeqIO
#from Bio.Seq import Seq
from Bio.Align import MultipleSeqAlignment
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
import faiss
#import unittest
fasta = '/scratch/gpfs/cmcwhite/quantest2/QuanTest2/Test/zf-CCHH.vie'
from sentence_transformers import util
#from iteration_utilities import duplicates
import pickle
import argparse
import numpy as np
import torch
from transformers import AutoTokenizer, AutoModel
import os
import igraph
from pandas.core.common import flatten
import pandas as pd
from collections import Counter
import logging
class AA:
def __init__(self):
self.seqnum = ""
self.seqpos = ""
self.seqaa = ""
self.index = ""
#self.clustid = ""
#__str__ and __repr__ are for pretty printing
def __str__(self):
return("s{}-{}-{}".format(self.seqnum, self.seqpos, self.seqaa))
def __repr__(self):
return str(self)
# This is in the goal of finding sequences that poorly match before aligning
def graph_from_distindex(index, dist):
edges = []
weights = []
for i in range(len(index)):
for j in range(len(index[i])):
edge = (i, index[i, j])
#if edge not in order_edges:
edges.append(edge)
weights.append(dist[i,j])
for i in range(len(edges)):
print(edges[i], weights[i])
G = igraph.Graph.TupleList(edges=edges, directed=False)
G.es['weight'] = weights
return(G)
# If removing a protein leads to less of a drop in total edgeweight that other proteins
def candidate_to_remove(G, numseqs):
weights = []
for i in range(numseqs):
g_new = G.copy()
vs = g_new.vs.find(name = i)
weight = sum(g_new.es.select(_source=vs)['weight'])
weights.append(weight)
questionable_z = []
print("Sequence z scores")
for i in range(numseqs):
others = [weights[x] for x in range(len(weights)) if x != i]
z = (weights[i] - np.mean(others))/np.std(others)
print(i,z)
if z < -3:
questionable_z.append(i)
#print(questionable_z)
return(questionable_z)
def graph_from_cluster_orders(cluster_orders):
order_edges = []
for order in cluster_orders:
for i in range(len(order) - 1):
edge = (order[i], order[i + 1])
#if edge not in order_edges:
order_edges.append(edge)
#print(edge)
G_order = igraph.Graph.TupleList(edges=order_edges, directed=True)
return(G_order)
def get_topological_sort(cluster_orders):
print("start topological sort")
cluster_orders_nonempty = [x for x in cluster_orders if len(x) > 0]
dag_or_not = graph_from_cluster_orders(cluster_orders_nonempty).simplify().is_dag()
#
print ("Dag or Not?, dag check immediately before topogical sort", dag_or_not)
if dag_or_not == False:
for x in cluster_orders_nonempty:
print(x)
G_order = graph_from_cluster_orders(cluster_orders_nonempty)
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)
def remove_order_conflicts(cluster_order, seqs_aas, pos_to_clustid_dag):
print("remove_order_conflicts, before: ", cluster_order)
bad_clustids = []
for i in range(len(seqs_aas)):
prevpos = -1
for posid in seqs_aas[i]:
try:
clustid = pos_to_clustid_dag[posid]
except Exception as E:
continue
pos = posid.seqpos
if pos < prevpos:
print("Order violation", posid, clustid)
bad_clustids.append(clustid)
cluster_order = [x for x in cluster_order if x not in bad_clustids]
print("remove_order_conflicts, after: ", cluster_order)
return(cluster_order)
def remove_order_conflicts2(cluster_order, seqs_aas,numseqs, pos_to_clustid_dag):
"""
After topological sort,
remove any clusters that conflict with sequence order
This doesn't seem to be working?
"""
print("pos_to_clustid", pos_to_clustid_dag)
print("cluster-order remove_order_conflict", cluster_order)
clusters_w_order_conflict= []
for i in range(numseqs):
prev_cluster = 0
for j in range(len(seqs_aas[i])):
key = seqs_aas[i][j]
try:
clust = pos_to_clustid_dag[key]
except Exception as E:
continue
order_index = cluster_order.index(clust)
#print(key, clust, order_index)
if order_index < prev_cluster:
clusters_w_order_conflict.append(clust)
print("order_violation", order_index, clust)
prev_cluster = order_index
#print(cluster_order)
#print(clusters_w_order_conflict)
cluster_order = [x for x in cluster_order if x not in clusters_w_order_conflict]
return(cluster_order)
def make_alignment(cluster_order, numseqs, clustid_to_clust):
# Set up a bunch of vectors of "-"
# Replace with matches
# cluster_order = list in the order that clusters go
alignment = [["-"] * len(cluster_order) for i in range(numseqs)]
print(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.seqaa
for seqnum in range(numseqs):
try:
alignment[seqnum][order] = c_dict[seqnum]
except Exception as E:
continue
alignment_str = ""
print("Alignment")
for line in alignment:
row_str = "".join(line)
print(row_str[0:150])
alignment_str = alignment_str + row_str + "\n"
alignment_str_list = ["".join(x) for x in alignment]
return(alignment_str_list)
def alignment_print(alignment, seq_names):
records = []
for i in range(len(alignment)):
#print(seq_names[i], alignment[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)
def get_ranges(seqs_aas, cluster_order, starting_clustid, ending_clustid, pos_to_clustid):
#print("start get ranges")
#print(cluster_order, 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
# cluster_order must be zero:n
# Add assertion
pos_lists = []
for i in range(len(seqs_aas)):
pos_list = []
startfound = False
# If no starting clustid, add sequence until hit ending_clustid
if starting_clustid == -np.inf:
startfound = True
prevclust = ""
for pos in seqs_aas[i]:
try:
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
#print(pos_clust, starting_clustid, ending_clustid)
except Exception as E:
#print(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)
def get_unassigned_aas(seqs_aas, pos_to_clustid_dag):
'''
Get amino acids that aren't in a sequence
'''
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]
try:
# Read to first cluster hit
clust = pos_to_clustid_dag[key]
prevclust = clust
# If it's not in a clust, it's unsorted
except Exception as E:
unsorted = []
unsorted.append(key)
for k in range(j + 1, len(seqs_aas[i])):
key = seqs_aas[i][k]
try:
nextclust = pos_to_clustid_dag[key]
#print(nextclust)
break
# Go until you hit next clust or end of seq
except Exception as E:
unsorted.append(key)
last_unsorted = k
unassigned.append([prevclust, unsorted, nextclust, i])
nextclust = []
prevclust = []
return(unassigned)
def address_unassigned(gap, seqs, seqs_aas, pos_to_clustid, cluster_order, clustid_to_clust, numseqs, I2, D2, to_exclude, minscore = 0.1, ignore_betweenness = False, betweenness_cutoff = 0.45):
new_clusters = []
starting_clustid = gap[0]
ending_clustid = gap[2]
gap_seqnum = gap[3]
gap_seqaas = gap[1]
if gap_seqnum in to_exclude:
return([], [])
target_seqs_list = get_ranges(seqs_aas, cluster_order, starting_clustid, ending_clustid, pos_to_clustid)
target_seqs_list[gap_seqnum] = gap_seqaas
#for x in to_exclude:
# target_seqs_list[x] = []
#print("these are the target seqs")
#for x in target_seqs_list:
# print(x)
target_seqs = list(flatten(target_seqs_list))
#print("For each of the unassigned seqs, get their top hits from the previously computed distances/indices")
new_hitlist = []
for seq in target_seqs_list:
for query_id in seq:
query_seqnum = query_id.seqnum
seqpos = query_id.seqpos
ind = I2[query_seqnum][seqpos]
dist = D2[query_seqnum][seqpos]
for j in range(len(ind)):
ids = ind[j]
#print(query_id)
#scores = dist[j]
good_indices = [x for x in range(len(ids)) if ids[x] in target_seqs]
ids_target = [ids[g] for g in good_indices]
scores_target = [dist[j][g] for g in good_indices]
if len(ids_target) > 0:
bestscore = scores_target[0]
bestmatch_id = ids_target[0]
if query_seqnum == bestmatch_id.seqnum:
continue
if bestmatch_id in target_seqs:
if bestscore >= minscore:
new_hitlist.append([query_id, bestmatch_id, bestscore])#, pos_to_clustid_dag[bestmatch_id]])
new_rbh = get_rbhs(new_hitlist)
#print("gapfilling rbh")
#for x in new_rbh:
# print(x)
new_clusters, hb_list = first_clustering(new_rbh, betweenness_cutoff = betweenness_cutoff, minclustsize = 2, ignore_betweenness = ignore_betweenness)
clustered_aas = list(flatten(new_clusters))
unmatched = [x for x in gap_seqaas if not x in clustered_aas]
hopelessly_unmatched = []
#This means that's it's the last cycle
if ignore_betweenness == True:
# If no reciprocal best hits
for aa in unmatched:
#print("its index, ", aa.index)
hopelessly_unmatched.append(aa)
#new_clusters.append([aa])
return(new_clusters, hopelessly_unmatched)
def get_looser_scores(aa, index, hidden_states):
'''Get all scores with a particular amino acid'''
#print(hidden_states)
#print(hidden_states.shape)
#print(index)
hidden_state_aa = np.take(hidden_states, [aa.index], axis = 0)
# Search the total number of amino acids
# Cost of returning higher n is minimal
#print(hidden_state_aa)
n_aa = hidden_states.shape[0]
D_aa, I_aa = index.search(hidden_state_aa, k = n_aa)
#print(aa)
#print(D_aa.tolist())
#print(I_aa.tolist())
return(list(zip(D_aa.tolist()[0], I_aa.tolist()[0])))
def get_particular_score(D, I, aa1, aa2):
''' Not used yet '''
#print(aa1, aa2)
scores = D[aa1.seqnum][aa1.seqpos][aa2.seqnum]
#print(scores)
ids = I[aa1.seqnum][aa1.seqpos][aa2.seqnum]
#print(ids)
for i in range(len(ids)):
#print(aa1, score_aa, scores[i])
if ids[i] == aa2:
#print(aa1, aa2, ids[i], scores[i])
return(scores[i])
else:
return(0)
def address_isolated_aas(unassigned_aa, cohort_aas, D, I, minscore):
'''
Maybe overwrite score?
Or match to cluster with higher degree
'''
print("Address isolated aas")
connections = []
for cohort_aa in cohort_aas:
score = get_particular_score(unassigned_aa, cohort_aa, D, I)
print(unassigned_aa, cohort_aa, score)
return(cluster)
def squish_clusters(cluster_order, clustid_to_clust, D, I, full_cov_numseq):
'''
This will probably not necessary
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
'''
removed_clustids = []
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))
#if len(list(seqnum_overlap)) < target_n:
#continue
# Can't merge if two clusters already have same sequences represented
if len(seqnum_overlap) > 0:
continue
else:
#combo = c1 + c2
## Only allow full coverage for now
#if len(combo) < target_n:
# continue
intra_clust_hits= []
for aa1 in c1:
for aa2 in c2:
score = get_particular_score(D, I, aa1, aa2)
if score > 0.001:
intra_clust_hits.append([aa1,aa2,score] )
# intra_clust_hits.append(x)
print("c1", c1)
print("c2", c2)
combo = c1 + c2
#for x in intra_clust_hits:
# print(x)
scores = [x[2] for x in intra_clust_hits if x is not None]
# Ad hoc, get ones where multiple acceptable hits to second column
if len(scores) > (0.5 * len(c1) * len(c2)):
print("An acceptable squish")
removed_clustids.append(cluster_order[i + 1])
clustid_to_clust[cluster_order[i]] = combo
clustid_to_clust[cluster_order[i + 1]] = []
# If full tetris effect.
# If complete, doesn't matter
# Change? don't worry with score?
elif len(combo) == full_cov_numseq:
removed_clustids.append(cluster_order[i + 1])
clustid_to_clust[cluster_order[i]] = combo
clustid_to_clust[cluster_order[i + 1]] = []
print("Old cluster order", cluster_order)
cluster_order = [x for x in cluster_order if x not in removed_clustids]
print("New cluster order", cluster_order)
return(cluster_order, clustid_to_clust)
def merge_clusters(new_clusters, prior_clusters):
'''
Need to add situation where overlap = an unassigned
'''
combined_clusters = []
accounted_for = []
for p in prior_clusters:
if p in accounted_for:
continue
overlaps_new = False
for n in new_clusters:
if n in accounted_for:
continue
overlap = list(set(p).intersection(set(n)))
if len(overlap) > 0:
print("overlap", overlap)
# If the new cluster fully contains the old cluster, overwrite it
if len(overlap) == len(p):
print("p_old", p)
print("n ", n)
print("contained in previous")
combined_clusters.append(n)
accounted_for.append(n)
overlaps_new = True
continue
# If overlap is less than the prior cluster,
# It means resorting occured.
# Only keep things from old cluster that are in new cluster
# And add the new cluster
elif len(overlap) < len(p):
print("modified clustering found")
print("p_old", p)
print("n ", n)
p_new = [x for x in p if x in n]
print("p_new", p_new)
combined_clusters.append(p_new)
accounted_for.append(n)
overlaps_new = True
#combined_clusters.append(n)
continue
if overlaps_new == False:
print("Not found to overlap with new clusters, appending", p)
combined_clusters.append(p)
# If a new cluster has no overlap with previous clusters
for x in new_clusters:
if x not in accounted_for:
combined_clusters.append(x)
#for x in prior_clusters:
# print("prior ", x)
#for x in combined_clusters:
# print("combo ", x)
combined_clusters = merge_clusters_no_overlaps(combined_clusters)
return(combined_clusters)
def merge_clusters_no_overlaps(combined_clusters):
''' Merge clusters using graph
Must have no overlaps
'''
# If slow, try alternate https://stackoverflow.com/questions/9110837/python-simple-list-merging-based-on-intersections
reduced_edgelist = []
# Add edge from first component of each cluster to rest of components in cluster
# Simplifies clique determination
#print("reduced edgelist")
for cluster in combined_clusters:
for i in range(0,len(cluster)):
reduced_edgelist.append([cluster[0],cluster[i]])
#for x in reduced_edgelist:
# print(x)
new_G = igraph.Graph.TupleList(edges=reduced_edgelist, directed=False)
#new_G = new_G.simplify()
merged_clustering = new_G.clusters(mode = "weak")
clusters_merged = clustering_to_clusterlist(new_G, merged_clustering)
clusters_merged = [remove_doubles(x) for x in clusters_merged]
#print("change: ", len(combined_clusters), len(clusters_merged))
return(clusters_merged)
#def get_next_clustid(seq_aa, seq_aas, pos_to_clustid):
def remove_feedback_edges(cluster_orders, clusters_filt, remove_both):
"""
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
"""
for x in cluster_orders:
print(x)
G_order = graph_from_cluster_orders(cluster_orders)
weights = [1] * len(G_order.es)
# Remove multiedges and self loops
#print(G_order)
G_order.es['weight'] = weights
G_order = G_order.simplify(combine_edges=sum)
dag_or_not = G_order.is_dag()
print ("Dag or Not before remove_feedback?, ", dag_or_not)
# 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')
i = 0
to_remove = []
for edge in G_order.es():
source_vertex = G_order.vs[edge.source]["name"]
target_vertex = G_order.vs[edge.target]["name"]
if i in fas:
to_remove.append([source_vertex, target_vertex])
i = i + 1
#cluster_orders_dag = []
remove_dict = {}
for i in range(len(cluster_orders)):
remove = []
for j in range(len(cluster_orders[i]) - 1):
if [cluster_orders[i][j], cluster_orders[i][j +1]] in to_remove:
#print(cluster_orders[i])
#print(remove_both)
#print(cluster_orders[i][j], cluster_orders[i][j + 1])
if remove_both == True:
remove.append(cluster_orders[i][j])
remove.append(cluster_orders[i][j + 1])
remove_dict[i] = list(set(remove))
print("remove_dict", remove_dict)
clusters_filt_dag = []
#print(clusters_filt)
for i in range(len(clusters_filt)):
clust = []
for aa in clusters_filt[i]:
seqnum = aa.seqnum
#seqsplit = seq.split("-")
#seqnum = int(seqsplit[0].replace("s", ""))
remove_from = remove_dict[seqnum]
if i in remove_from:
print("removing ", i, seqnum)
else:
clust.append(aa)
clusters_filt_dag.append(clust)
print("remove feedback")
#dag_or_not = graph_from_cluster_orders(cluster_orders_dag).is_dag()
#print ("Dag or Not?, ", dag_or_not)
for x in clusters_filt_dag:
print(x)
return(clusters_filt_dag)
def remove_streakbreakers(hitlist, seqs_aas, seqlens, streakmin = 3):
# Remove initial RBHs that cross a streak of matches
# Simplify network for feedback search
filtered_hitlist = []
for i in range(len(seqs_aas)):
query_prot = [x for x in hitlist if x[0].seqnum == i]
for j in range(len(seqs_aas)):
target_prot = [x for x in query_prot if x[1].seqnum == j]
# check shy this is happening extra at ends of sequence
#print("remove lookbehinds")
prevmatch = 0
seq_start = -1
streak = 0
no_lookbehinds = []
for match_state in target_prot:
#print(match_state)
if match_state[1].seqpos <= seq_start:
#print("lookbehind prevented")
streak = 0
continue
no_lookbehinds.append(match_state)
if match_state[1].seqpos - prevmatch == 1:
streak = streak + 1
if streak >= streakmin:
seq_start = match_state[1].seqpos
else:
streak = 0
prevmatch = match_state[1].seqpos
#print("remove lookaheads")
prevmatch = seqlens[j]
seq_end = seqlens[j]
streak = 0
filtered_target_prot = []
for match_state in no_lookbehinds[::-1]:
#print(match_state, streak, prevmatch)
if match_state[1].seqpos >= seq_end:
#print("lookahead prevented")
streak = 0
continue
filtered_target_prot.append(match_state)
if prevmatch - match_state[1].seqpos == 1:
streak = streak + 1
if streak >= streakmin:
seq_end = match_state[1].seqpos
else:
streak = 0
prevmatch = match_state[1].seqpos
filtered_hitlist = filtered_hitlist + filtered_target_prot
return(filtered_hitlist)
def remove_doubles(cluster, minclustsize = 0, keep_higher_degree = False, rbh_list = [], check_order_consistency = False):
''' If a cluster contains more 1 amino acid from the same sequence, remove that sequence from cluster'''
'''
If
'''
print("cluster", cluster)
seqnums = [x.seqnum for x in cluster]
clustcounts = Counter(seqnums)
#print(clustcounts)
to_remove = []
for key, value in clustcounts.items():
if value > 1:
to_remove.append(key)
#print(cluster)
#print(keep_higher_degree, to_remove)
# If there's anything in to_remove, keep the one with highest degree
if len(to_remove) > 0 and keep_higher_degree == True:
rbh_sel = [x for x in rbh_list if x[0] in cluster and x[1] in cluster]
G = igraph.Graph.TupleList(edges=rbh_sel, directed = False)
G = G.simplify()
#print("edges in cluster", rbh_sel)
for seqnum in to_remove:
cluster = remove_lower_degree(cluster, seqnum, G)
# Otherwise, remove any aa's from to_remove sequence
else:
for x in to_remove:
print("Removing sequence {} from cluster".format(x))
print("what")
print(cluster)
print(seqnums)
print(clustcounts)
cluster = [x for x in cluster if x.seqnum not in to_remove]
if len(cluster) < minclustsize:
return([])
else:
return(cluster)
#def resolve_conflicting_clusters(clusters)
def remove_lower_degree(cluster, seqnum, G):
target_aas = [x for x in cluster if x.seqnum == seqnum]
#print(aas)
degrees = []
for aa in target_aas:
degrees.append(G.vs.find(name = aa).degree())
# This doesn't
#degrees.append(G.degree( aa))
# TODO: Get rbh to return scores
# get highest score if degree tie
# gap_scores.append(G
highest_degree = target_aas[np.argmax(degrees)]
to_remove = [x for x in target_aas if x != highest_degree]
cluster_filt = [x for x in cluster if x not in to_remove]
return(cluster_filt)
def remove_doubles2(cluster, rbh_list, numseqs, minclustsize):
"""
Will need to resolve ties with scores
"""
seqcounts = [0] * numseqs # Will each one replicated like with [[]] * n?
for pos in cluster:
seqnum = get_seqnum(pos)
#print(seq, seqnum)
seqcounts[seqnum] = seqcounts[seqnum] + 1
#doubled = [i for i in range(len(seqcounts)) if seqcounts[i] > 1]
G = igraph.Graph.TupleList(edges=rbh_list, directed = False)
G = G.simplify()
# To do: check if doing extra access hashing other places
for seqnum in range(len(seqcounts)):
if seqcounts[seqnum] > 1:
aas = [x for x in cluster if get_seqnum(x) == seqnum]
#print(aas)
degrees = []
for aa in aas:
degrees.append(G.degree(aa))
# TODO: Get rbh to return scores
# get highest score if degree tie
# gap_scores.append(G
#print(degrees)
highest_degree = aas[np.argmax(degrees)]
to_remove = [x for x in aas if x != highest_degree]
cluster = [x for x in cluster if x not in to_remove]
if len(cluster) < minclustsize:
return([])
else:
return(cluster)
def remove_doubles_old(cluster, numseqs, minclustsize = 3):
"""
If a cluster has two aas from the same sequence, remove from cluster
Also removes clusters smaller than a minimum size (default: 3)
Parameters:
clusters (list): [aa1, aa2, aa3, aa4]
with aa format of sX-X-N
numseqs (int): Total number of sequence in alignment
minclustsize (int):
Returns:
filtered cluster_list
Could do this with cluster orders instead
"""
#clusters_filt = []
#for i in range(len(clusters_list)):
seqcounts = [0] * numseqs # Will each one replicated like with [[]] * n?
for pos in cluster:
seqnum = get_seqnum(pos)
#print(seq, seqnum)
seqcounts[seqnum] = seqcounts[seqnum] + 1
remove_list = [i for i in range(len(seqcounts)) if seqcounts[i] > 1]
clust = []
for pos in cluster:
seqnum = get_seqnum(pos)
if seqnum in remove_list:
print("{} removed from cluster {}".format(seq, i))
continue
else:
clust.append(pos)
if len(clust) < minclustsize:
return([])
else:
return(clust)
def remove_low_match_prots(numseqs, seqlens, clusters, threshold_min = 0.5):
############## No badly aligning sequences check
# Remove sequences that have a low proportion of matches from cluster
# Do another one of these after ordering criteria
matched_count = [0] * numseqs
for pos in flatten(clusters):
seqnum = get_seqnum(pos)
matched_count[seqnum] = matched_count[seqnum] + 1
matched_prop = [matched_count[x]/seqlens[x] for x in range(0, numseqs)]
poor_seqs = []
for i in range(0, numseqs):
if matched_prop[i] < threshold_min:
print("Seq {} is poorly matching, fraction positions matched {}, removing until later".format(i, matched_prop[i]))
poor_seqs.append(i)
clusters_tmp = []
for clust in clusters:
clust_tmp = []
for pos in clust:
if not get_seqnum(pos) in poor_seqs:
clust_tmp.append(pos)
clusters_tmp.append(clust_tmp)
clusters = clusters_tmp
return(clusters)
def reshape_flat(hstates_list):
# Go from (numseqs, seqlen, emb) to (numseqs * seqlen, emb)
hidden_states = np.reshape(hstates_list, (hstates_list.shape[0]*hstates_list.shape[1], hstates_list.shape[2]))
return(hidden_states)
def split_distances_to_sequence(D, I, index_to_aa, numseqs, padded_seqlen):
I_tmp = []
D_tmp = []
print(D.shape)
# For each amino acid...
for i in range(len(I)):
#print(i)
# Make empty list of lists, one per sequence
I_query = [[] for i in range(numseqs)]
D_query = [[] for i in range(numseqs)]
for j in range(len(I[i])):
try:
aa = index_to_aa[I[i][j]]
seqnum = aa.seqnum
I_query[seqnum].append(aa)
D_query[seqnum].append(D[i][j])
except Exception as E:
continue
I_tmp.append(I_query)
D_tmp.append(D_query)
print(padded_seqlen)
D = [D_tmp[i:i + padded_seqlen] for i in range(0, len(D_tmp), padded_seqlen)]
I = [I_tmp[i:i + padded_seqlen] for i in range(0, len(I_tmp), padded_seqlen)]
return(D, I)
def get_besthits(D, I, index_to_aa, padded_seqlen, minscore = 0.1, to_exclude = [] ):
#aa_to_index = {value: key for key, value in index_to_aa.items()}
hitlist = []
for query_seq in range(len(D)):
if query_seq in to_exclude:
continue
for query_aa in range(len(D[query_seq])):
# Non-sequence padding isn't in dictionary
try:
query_id = index_to_aa[query_seq * padded_seqlen + query_aa]
except Exception as E:
continue
for target_seq in range(len(D[query_seq][query_aa])):
scores = D[query_seq][query_aa][target_seq]
if len(scores) == 0:
continue
ids = I[query_seq][query_aa][target_seq]
bestscore = scores[0]
bestmatch_id = ids[0]
if bestscore >= minscore:
hitlist.append([query_id, bestmatch_id, bestscore])
return(hitlist)
def get_rbhs(hitlist_top):
'''