-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmicrobiome_main.py
executable file
·2325 lines (2060 loc) · 106 KB
/
microbiome_main.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 python
import argparse
import pandas as pd
pd.options.mode.chained_assignment = None # default='warn'
import csv
import numpy as np
import os
import re
import pickle as pic
import subprocess
import subprocess
# from fusion_distribution import isFusion,geneFusions
# from fusion_dist_dir import isFusion,genDict
from fusion import isFusion, geneFusions, genDict, setGenome, check_overlap, fusion_TMS_count
from parseXML import parse
from pprint import pprint
from find_protein import find, extract_all, find_mistake
GENOME = ''
TMS_THRESH_GREEN = 0.7
TMS_THRESH_YELLOW = 0.5
EXCELLENT_EVAL = 1e-30
E_VAL_GREEN = 1e-10
E_VAL_YELLOW = 1e-3
Q_COV_THRESH = 80
S_COV_THRESH = 80
LOW_COV = 50
AUTO_RED = 20
Membraneprotein_threshold=3
Hit_TMS_Diff= 2
MIN_PROTEINS = 0.5
MIN_HIT_THRESH = 100
FEATURE_TABLE = ''
GBFF_FILE = ''
superfamilies = ['1.A.17', '2.A.7', '1.E.11', '1.E.36', '1.C.12', '1.A.72', '2.A.29', '2.A.66','3.A.3', '1.C.41', '8.A.180', '2.A.6']
tcdbSystems = {}
red = {}
green = {}
yellow = {}
hmmtop_df = pd.DataFrame(columns=['Hit_tcid', 'Hit_xid', 'Hit_n_TMS','Match_length'])
geneFusions={}
df = None
id_dict = {}
tcid_assignments = {}
columns = ['Hit_tcid', 'Hit_xid', '#Query_id','Match_length','e-value','%_identity','Query_Length','Hit_Length','Q_start',
'Q_end','S_start','S_end','Query_Coverage','Hit_Coverage','Query_n_TMS','Hit_n_TMS','TM_Overlap_Score','Family_Abrv'
,'Predicted_Substrate','Query_Pfam','Subject_Pfam', 'isFusion', 'Missing_components', 'Initial_decision']
green_df = pd.DataFrame(columns=columns)
yellow_df = pd.DataFrame(columns=columns)
red_df = pd.DataFrame(columns=columns)
family_assignments = {}
proteins_found = {}
tcdb_pfams = {}
genome_pfams = {}
qids = []
multi_system_assignments = {}
missing = []
missing_info = {}
queries = {}
fam_not_found = []
move_to_green = []
move_to_red = []
completed_info = {}
written = []
query_assignments = {}
tcid_queries = {}
matches = {}
new_genomic_context_matches = {}
multicomp_queries = []
curr_hit = {}
mistakes = {}
missing_overlap_dict = {}
missing_tms_dict = {}
already_swapped = {}
new_matches = {}
operons = {}
tcids_genome_change = []
mcs = {}
# assign genome pfams in function that ids missing components isMultiComp(row)
def assign_tcdb_pfams():
# this file never changes so if it exists we would just use that
if not os.path.exists(GENOME + '/analysis/tcdb_pfam.out'):
cmd = f"bzcat $TCDBPFAM | grep -v '#' | perl -pe 's/ +/\t/g;' | cut -f 2,4 > {GENOME}/analysis/tcdb_pfam.out"
os.system(cmd)
with open(GENOME + '/analysis/tcdb_pfam.out', 'r') as f:
lines = f.readlines()
for line in lines:
line = line.strip()
content = line.split('\t')
if content[1] in tcdb_pfams:
tcdb_pfams[content[1]].append(content[0].split('.')[0])
else:
tcdb_pfams[content[1]] = [content[0].split('.')[0]]
# This function gives each family an assignment to be used when identifying if a family is in green
# creates the family_assignents dictionary that contains all info for missing component analysis
def assign_family(row, color):
row_index = 0
row_as_list = row.iloc[row_index].to_dict()
tcid = row['Hit_tcid'].tolist()[0]
xid = row_as_list['Hit_xid']
# if the tcid is not found, we want to instantiate the array
if tcid not in proteins_found:
proteins_found[tcid] = []
# if the protein is already in use in a family, we dont need to assign it again
if xid in proteins_found[tcid]:
return
else:
proteins_found[tcid].append(xid)
temp = tcid.split('.')
# define a family either on the first 3 characters of tcid or first 4
fam = temp[0] + '.' + temp[1] + '.' + temp[2]
if fam in superfamilies:
fam = temp[0] + '.' + temp[1] + '.' + temp[2] + '.' + temp[3]
# assign families to colors
if color not in family_assignments:
family_assignments[color] = {}
if fam not in family_assignments[color]:
family_assignments[color][fam] = {}
if tcid in family_assignments[color][fam]:
family_assignments[color][fam][tcid].append(row_as_list)
else:
family_assignments[color][fam][tcid] = [row_as_list]
else:
if fam not in family_assignments[color]:
family_assignments[color][fam] = {}
if tcid in family_assignments[color][fam]:
family_assignments[color][fam][tcid].append(row_as_list)
else:
family_assignments[color][fam][tcid] = [row_as_list]
'''
def create_id_dict(df):
if df == None:
return {}
id_df = df[['Hit_tcid', 'Hit_xid', '#Query_id','Match_length','e-value','%_identity','Query_Length','Hit_Length','Q_start',
'Q_end','S_start','S_end','Query_Coverage','Hit_Coverage','Query_n_TMS','Hit_n_TMS','TM_Overlap_Score','Family_Abrv'
,'Predicted_Substrate','Query_Pfam','Subject_Pfam']]
id_dict = {}
for index, row in id_df.iterrows():
if row['Hit_tcid'] in id_dict:
id_dict[row['Hit_tcid']].append(row)
else:
id_dict[row['Hit_tcid']] = [row]
return id_dict
'''
# there is an error in gblast's calculation of tms overlap so this uses parseXML to calculate correct values to be changed in df
def adjustOverlapScore(df):
print(GENOME)
# this calls the parseXML script to adjust overlap scores of tmss
overlap_dict = parse(GENOME + '/hmmtop.db', GENOME + '/xml/' ,GENOME + '/results.tsv', 8)
score_dict = {}
# corrects the overlap score in the table itself
for k in overlap_dict:
score_dict[k] = overlap_dict[k]['alignedTMS']
for index, row in df.iterrows():
if row['#Query_id'] in score_dict:
df.at[index, 'TM_Overlap_Score'] = score_dict[row['#Query_id']]
else:
df.at[index, 'TM_Overlap_Score'] = 0
print('finished')
#This function will fill the dictionary tcdbSystems with data.
def parseTCDBcontent(input):
for line in input:
if(">" in line):
first = line.split("-")[0][1:]
if(first in tcdbSystems):
tcdbSystems.get(first).append(line.strip(">\n"))
else:
tcdbSystems[first] = [line.strip(">\n")]
#This is a helper function for finding common pFam domains and can be used to check if a value is a float
def isfloat(num):
try:
float(num)
return True
except ValueError:
return False
# this function returns the query coverage of the given row
def qCoverage(row):
return float(row.get(key='Query_Coverage'))
# this function returns the target coverage of the given row
def hCoverage(row):
return float(row.get(key='Hit_Coverage'))
# this function returns the evalue of the given row
def eVal(row):
return float(row.get(key='e-value'))
# this function returns the common pfam domains of the given row
def pfamDoms(row):
doms = []
if isfloat(row.get(key='Query_Pfam')):
return doms
elif isfloat(row.get(key='Subject_Pfam')):
return doms
q_pfam = row.get(key='Query_Pfam').split(',')
s_pfam = row.get(key='Subject_Pfam').split(',')
# if there are no pfams on either protein mark as NA
if len(q_pfam) == 0 and len(s_pfam) == 0:
return ['N/A']
for q_domain in q_pfam:
for s_domain in s_pfam:
if q_domain == s_domain:
doms.append(q_domain)
common_doms = [*set(doms)]
return common_doms
# this function makes a decision based on the tms overlap of the proteins
def tm_overlap_decision(row):
q_tmss = int(row.get(key='Query_n_TMS'))
t_tmss = int(row.get(key='Hit_n_TMS'))
# if there are no tms regions in the tcdb protein tms regions are irrelevant in decision making
if t_tmss == 0 and q_tmss == 0:
return True
# calculates the percent overlap of tms regions relative to tcdb proteins
def tmoverlap_percent(row):
overlap_percent = int(row.get(key='TM_Overlap_Score')) / t_tmss
return overlap_percent
# if there are under 3 tmss then theres a possibility of there being mishits
if t_tmss > 3:
# if there is great overlap return true
if tmoverlap_percent(row) >= TMS_THRESH_GREEN:
return True
else:
# could potentially have a fusion candid so should be placed into yellow
if q_tmss >= 1 and t_tmss >= 1:
return True
return False
# This function calculates the tms overlap percentage between the 2 proteins relative to the tcdb protein
def overlap_percent(row):
q_tmss = int(row.get(key='Query_n_TMS'))
t_tmss = int(row.get(key='Hit_n_TMS'))
if q_tmss == 0 or t_tmss == 0:
return 0
overlap_percent = int(row.get(key='TM_Overlap_Score')) / max(q_tmss, t_tmss)
return overlap_percent
# this makes a decision based on the coverage of the fused proteins together
def assign_if_fusion(fusions, tcdb_tms):
# need to check that the combined tms count from all fusions meets threshold if ritvik can add to output
tot_cov = 0
# print(fusions)
if len(fusions) == 0:
return 'red'
tot_cov = int(fusions[0]['send']) - int(fusions[0]['sstart'])
for i in range(1, len(fusions)):
# caluculate overlap
overlap = 0
if fusions[i]['sstart'] < fusions[i-1]['send']:
overlap = fusions[i-1]['send'] - fusions[i]['sstart']
tot_cov += fusions[i]['send'] - fusions[i]['sstart'] - overlap
if fusions[i]['send'] < fusions[i-1]['send']:
return 'red'
if fusions[i]['sstart'] == fusions[i-1]['sstart']:
return 'red'
# if there are no tmss assume theres 100% overlap
if tcdb_tms == 0:
overlap_percent_fus = 1
else:
net_overlap = fusion_TMS_count(fusions)
overlap_percent_fus = net_overlap / tcdb_tms
tot_cov = float(tot_cov / int(fusions[0]['hit_length'])) * 100
# if the overall coverage covers most of the protein and there is good tms overlap its a green
if tot_cov >= S_COV_THRESH and overlap_percent_fus >= TMS_THRESH_GREEN:
return 'green'
elif tot_cov >= LOW_COV and overlap_percent_fus >= TMS_THRESH_YELLOW:
return 'yellow'
else:
return 'red'
# this is the decision making algorithm based on all essential values from blast results
def make_decision(row, fusions, tcdb_tms):
eval = eVal(row)
qcov = qCoverage(row)
scov = hCoverage(row)
pfam_doms = pfamDoms(row)
tmoverlap = overlap_percent(row)
# automatic green if e-val is 0 or extremely good with okay coverage and has some tms coverage
if (eval == 0.0 or eval <= EXCELLENT_EVAL) and (qcov > LOW_COV and scov > LOW_COV) and tcdb_tms > 0:
return 'green'
elif (eval == 0.0 or eval <= EXCELLENT_EVAL) and (qcov > Q_COV_THRESH and scov > S_COV_THRESH):
return 'green'
# if coverage is less than a very low number it is impossible for it to be a good hit
if qcov <= AUTO_RED or scov <= AUTO_RED and len(fusions) == 0:
return 'red'
# if there are less than 3 tms, there is a possiblity of mischaracterizing tms regions
if tcdb_tms > 3:
# if cov is too low it is automatically red
if qcov < AUTO_RED or scov < AUTO_RED and len(fusions) == 0:
return 'red'
# great e val, there are common pfam domains, good cov and high tms overlap means good hit
if eval <= E_VAL_GREEN and len(pfam_doms) > 0 and qcov >= Q_COV_THRESH and scov >= S_COV_THRESH and tmoverlap >= TMS_THRESH_GREEN:
return 'green'
# great e val, common doms, has good coverage or there is a high tms overlap means good hit
if eval <= E_VAL_GREEN and len(pfam_doms) > 0 and ((qcov >= Q_COV_THRESH and scov >= S_COV_THRESH) or tmoverlap >= TMS_THRESH_GREEN):
return 'green'
# great e value, has good coverage or there is a high tms overlap means good hit
if eval <= E_VAL_GREEN and len(pfam_doms) > 0 and ((qcov >= Q_COV_THRESH and scov >= S_COV_THRESH) or tmoverlap >= TMS_THRESH_GREEN):
return 'green'
# okay e value, has good coverage and there is a high tms overlap means good hit
if eval <= E_VAL_YELLOW and ((qcov >= Q_COV_THRESH and scov >= S_COV_THRESH) and tm_overlap_decision(row) == True):
return 'green'
# great e-val no matching pfam domains but has goood coverage or good tmoverlap its a good hit
if eval <= E_VAL_GREEN and ((qcov >= Q_COV_THRESH and scov >= S_COV_THRESH) or tmoverlap >= TMS_THRESH_GREEN):
return 'green'
# okay eval, full tms overlap w tcdb, matching pfam doms, even if coverage isnt great is a green
if eval <= E_VAL_GREEN and ((qcov >= LOW_COV and scov >= LOW_COV) and tm_overlap_decision(row) == True) and len(pfam_doms) > 0:
return 'green'
# okay eval, good tms overlap and ok coverage is a green
if eval <= E_VAL_YELLOW and (qcov >= LOW_COV and scov >= LOW_COV) and tm_overlap_decision(row) == True:
return 'green'
# ok eval with some tms overlap should be green
if eval <= E_VAL_YELLOW and (qcov >= AUTO_RED and scov >= AUTO_RED) and tmoverlap >= TMS_THRESH_YELLOW:
return 'green'
# if there is a fusion found we need to do further analysis
if len(fusions) > 0:
return 'fusion found'
# ok e-val, no common doms, has good coverage or there is a good tms overlap means yellow hit
if eval <= E_VAL_YELLOW and ((qcov >= Q_COV_THRESH and scov >= S_COV_THRESH) or tmoverlap >= TMS_THRESH_YELLOW):
return 'yellow'
# okay e val, and com dom tms overlap is good and the coverage is not too terrible > 50% its a yellow hit
if eval <= E_VAL_YELLOW and len(pfam_doms) > 0 and (qcov > LOW_COV or scov > LOW_COV) and tmoverlap >= TMS_THRESH_YELLOW:
return 'yellow'
# okay e val, common domains, with good tms overlap even if coverage is low is yellow
if eval <= E_VAL_YELLOW and len(pfam_doms) > 0 and tm_overlap_decision(row) == True:
return 'yellow'
# okay eval, good tms overlap is yellow could have fusion not listed
if eval <= E_VAL_YELLOW and ((qcov >= LOW_COV and scov >= LOW_COV) and tm_overlap_decision(row) == True):
return 'yellow'
# if low e-val, has low coverage and there are low tms overlap
if eval <= E_VAL_YELLOW and (qcov < LOW_COV or scov < LOW_COV) and tmoverlap < TMS_THRESH_YELLOW:
return 'red'
else: # considering possibility of mischaracterization of tms
# is a fusion candidate, has great e value and has good cov is good hit
if eval <= E_VAL_GREEN and (qcov >= Q_COV_THRESH and scov >= S_COV_THRESH) and len(pfam_doms) > 0:
return 'green'
# good e value, common doms match, good cov is good hit
if eval <= E_VAL_GREEN and len(pfam_doms) > 0 and (qcov >= Q_COV_THRESH and scov >= S_COV_THRESH):
return 'green'
# great e-val no matching pfam domains but has goood coverage or good tmoverlap its a good hit
if eval <= E_VAL_YELLOW and ((qcov >= Q_COV_THRESH and scov >= S_COV_THRESH) and tm_overlap_decision(row) == True):
return 'green'
# ok evalue with matching pfam domains should be green
if eval <= E_VAL_YELLOW and (qcov >= LOW_COV and scov >= LOW_COV) and len(pfam_doms) > 0:
return 'green'
# if there is a fusion found we need to do further analysis
if len(fusions) > 0:
return 'fusion found'
# has ok e value, common doms match, good cov is good hit
if eval <= E_VAL_YELLOW and len(pfam_doms) > 0 and (qcov >= LOW_COV and scov >= LOW_COV):
return 'yellow'
# is fusion, ok e value and good coverage but not good tms overlap
if eval <= E_VAL_YELLOW and qcov >= Q_COV_THRESH and scov >= S_COV_THRESH:
return 'yellow'
# great e val, and com dom but not good coverage is yellow hit
if eval <= E_VAL_GREEN and len(pfam_doms) > 0:
return 'yellow'
# okay e val, and com dom but not good coverage is yellow hit
if eval <= E_VAL_YELLOW and len(pfam_doms) > 0:
return 'yellow'
# okay e val, no common doms, good tms overlap
if eval <= E_VAL_YELLOW and tmoverlap >= TMS_THRESH_GREEN:
return 'yellow'
return 'red'
# based on all factors and using make_decision as a helper, it makes a final decision on the hit
def final_decision(row, fusions, tcdb_tms):
eval = eVal(row)
qcov = qCoverage(row)
scov = hCoverage(row)
pfam_doms = pfamDoms(row)
tmoverlap = overlap_percent(row)
decision = make_decision(row, fusions, tcdb_tms)
# if theres a fusion found we have to decide differently based on overall coverage
if decision == 'fusion found':
# if assign_if_fusion returns red its a false fusion or unlikely
if assign_if_fusion(fusions, tcdb_tms) == 'red':
return make_decision(eval, qcov, scov, pfam_doms, [], tmoverlap, tcdb_tms)
else:
return assign_if_fusion(fusions, tcdb_tms)
else:
return decision
# This function will check the tcdbSystems dictionary for the tcid given
def isSingleComp(row):
tcid = row["Hit_tcid"]
tc_arr = tcdbSystems.get(tcid)
if(len(tc_arr) == 1):
return True
else:
return False
def categorizeSingleComp(row):
row_to_write = row.tolist()
sortedGeneArr = []
fusions = ''
tcid = row['Hit_tcid']
tcdb_tms = row['Hit_n_TMS']
fus_list = []
fusion_results= geneFusions[row["Hit_tcid"] + "-" + row["Hit_xid"]]
# check to see if potential fusion
if(len(fusion_results) !=1):
sortedGeneArr = sorted(fusion_results, key=lambda x: x['sstart'])
if(len(isFusion(sortedGeneArr))!=0):
sortedGeneArr = isFusion(sortedGeneArr)
# for any potential fusion append to fusions list
for k in range(0, len(sortedGeneArr)):
fusions += sortedGeneArr[k]['query'] + ' '
row_to_write.append(fusions)
else:
sortedGeneArr = []
row_to_write.append(fusions)
else:
row_to_write.append(fusions)
if assign_if_fusion(sortedGeneArr, tcdb_tms) == 'red':
sortedGeneArr = []
if len(fusions) > 0:
fus_list = fusions.split(' ')
if row['#Query_id'] not in fus_list:
row_to_write.pop()
row_to_write.append('')
fus_color = ''
if len(fusions) != 0:
fus_color = assign_if_fusion(sortedGeneArr, tcdb_tms)
# if there is a copy we need to assign it to the same color as the other copies
if tcid in tcid_assignments:
return (tcid_assignments[tcid], row_to_write)
decision = final_decision(row, sortedGeneArr, tcdb_tms)
# based on the decision send it to the appropriate file
if decision == 'green':
green[row.get(key='#Query_id')] = row_to_write
tcid_assignments[row.get(key='Hit_tcid')] = 'Green'
queries[row['#Query_id']] = 'Green'
return ('Green', row_to_write)
elif decision == 'yellow':
yellow[row.get(key='#Query_id')] = row_to_write
tcid_assignments[row.get(key='Hit_tcid')] = 'Yellow'
queries[row['#Query_id']] = 'Yellow'
return ('Yellow', row_to_write)
elif decision == 'red':
red[row.get(key='#Query_id')] = row_to_write
tcid_assignments[row.get(key='Hit_tcid')] = 'Red'
queries[row['#Query_id']] = 'Red'
return ('Red', row_to_write)
# This command executes bash commands on the command line
def execute_command(command):
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
while True:
output = process.stdout.readline()
if output == '' and process.poll() is not None:
break
if output:
print(output.strip())
process.wait()
if process.returncode == 0:
print(f"command'{command}'success")
else:
print(f"command'{command}'fail")
# returns empty list when there are no membrane proteins found.
# otherwise returns list of membrane protein accessions.
def FindMembraneProtein(row,df):
if isSingleComp(row): ##get rid of single comp system first
return ([])
tcid = row["Hit_tcid"]
tc_arr = tcdbSystems.get(tcid)##This contains all the proteins with their system name
tc_all_arr= [arr.split("-")[1] for arr in tc_arr] ##All the proteins that TCDB provide
##if tcid.split(".")[1]=="B":##and
if tcid[0:3]=="1.B":##If there is a beta barrel, we assume they are membrane proteins
return (tc_all_arr)
tc_filter_arr= list(filter(lambda x: (len(df.query(f"Hit_xid=='{x}' and Hit_tcid=='{tcid}'"))) !=0, tc_all_arr))
##tc_filter_arr includes the proteins that showed up in the gblast result
tc_Notfind_arr=list(set(tc_all_arr)-set(tc_filter_arr))##This is the missing proteins in actual result
find_df = pd.concat([df.query(f"Hit_xid=='{arr}' and Hit_tcid=='{tcid}'") for arr in tc_all_arr])
##This is the whole line for tc_filter_arr in gblast result
unfind_df = pd.concat([hmmtop_df.query(f"Hit_xid=='{arr}' and Hit_tcid=='{tcid}'") for arr in tc_all_arr])
##This is the whole line for tc_all_arr in hmmtop file
if find_df['Hit_n_TMS'].nunique() == 1 and unfind_df['Hit_n_TMS'].nunique() == 1 :
##If all the proteins have same Hit TMS in both files, we say they are membrane proteins
if str(find_df['Hit_n_TMS'].unique()[0]) == str(unfind_df['Hit_n_TMS'].unique()[0]):
return (tc_all_arr)
Found_arr_gblast = find_df[(find_df['Hit_n_TMS'] >= Membraneprotein_threshold) & (abs(find_df['Hit_n_TMS'] - find_df['Query_n_TMS']) <= Hit_TMS_Diff)]["Hit_xid"].tolist()
##If there are proteins that has Hit TMS >=3 and difference with its query TMS <=2, we say it's membrane proteins
tcdb_arr= Found_arr_gblast +tc_Notfind_arr##This arr contains the possible output proteins
if len(tcdb_arr)==0:
return([])
tcdb_df = pd.concat([hmmtop_df.query(f"Hit_xid=='{arr}' and Hit_tcid=='{tcid}'") for arr in tcdb_arr])
Final_return = tcdb_df[(tcdb_df['Hit_n_TMS']>= Membraneprotein_threshold)]
##print(tc_all_arr)
##print(find_df)
##print(unfind_df)
##print(Final_return["Hit_xid"].tolist())
# return((Final_return['Hit_tcid'] + '-' + Final_return["Hit_xid"]).tolist())
return Final_return.to_dict()
##final_df = pd.concat([df.query(f"Hit_xid=='{arr}'") for arr in tc_filter_arr])
# determines if membrane protein dict is empty
def isEmpty(dict):
if type(dict) is list:
return len(dict) == 0
count = 0
for key in dict:
if not bool(dict[key]):
count += 1
return count == 4
# if there are missing components we need to to take a different decision determining the importance of the components that are missing
def multicomp_decision(tcdb_proteins, tcid, mem_dict, tc_filter_arr, missing_comps, has_file):
#find_pfams(missing_comps, tcid)
protein_type = tcid.split('.')[0] + '.' + tcid.split('.')[1]
max_tms = 0
tcid = tcdb_proteins[0].split('-')[0]
# if there are no membrane proteins and we hit the min protein threshold
if (isEmpty(mem_dict) or len(mem_dict) == 0) and (len(tc_filter_arr)/len(tcdb_proteins)) < MIN_PROTEINS:
return 'red'
# if there are no membrane proteins keep in yellow for now
elif isEmpty(mem_dict) or len(mem_dict) == 0:
return 'yellow'
membrane_protein_tms = {}
# put membrane proteins into a dict sorted by number of tmss
membrane_proteins = []
if type(mem_dict) is list:
membrane_proteins = mem_dict
else:
membrane_proteins_accessions = list(mem_dict["Hit_xid"].values())
membrane_proteins_tcids = list(mem_dict["Hit_tcid"].values())
membrane_tmss = list(mem_dict["Hit_n_TMS"].values())
membrane_proteins = membrane_proteins_accessions
for i in range(0, len(membrane_proteins_accessions)):
protein = membrane_proteins_tcids[i] + '-' + membrane_proteins_accessions[i]
membrane_protein_tms[protein] = membrane_tmss[i]
membrane_tmss = list(mem_dict['Hit_n_TMS'].values())
# sorts the dictionary based on ascending tms values
membrane_protein_tms = {k: membrane_protein_tms[k] for k in sorted(membrane_protein_tms, key=membrane_protein_tms.get, reverse=True)}
for key in membrane_protein_tms:
max_tms = membrane_protein_tms[key]
break
# if beta barrell and most proteins are in the system should be yellow->green because ALL are membrane proteins
if protein_type == '1.B' and abs(len(tcdb_proteins) - len(tc_filter_arr)) <= 2:
return 'Green'
all_mems_found = True
# determine if all membrane proteins are found if so its a green
if type(mem_dict) is list:
for protein in membrane_proteins:
if protein not in tc_filter_arr:
all_mems_found = False
break
else:
for protein in membrane_proteins:
accession = protein
if accession not in tc_filter_arr:
all_mems_found = False
break
# if we have all the membrane proteins we can confidently say the system exists or performs the same function
if all_mems_found == True:
return 'Green'
# if we dont have enough proteins under 50% usually
if len(tcdb_proteins) > 3 and (len(tc_filter_arr)/len(tcdb_proteins)) < MIN_PROTEINS:
return 'red'
genome_membrane_accessions = tc_filter_arr
num_membrane_proteins = len(genome_membrane_accessions)
# it is an instant red if NONE of the membrane proteins are found
if num_membrane_proteins == 0:
return 'red'
# check to see if the tms with equal or most tms is found
for protein in genome_membrane_accessions:
key = tcid + '-' + protein
# if we find the most significant membrane protein it is worth considering for green
if key in membrane_protein_tms:
if max_tms - membrane_protein_tms[key] < 2:
return 'yellow'
return 'red'
# Goal of this function is to run pfam.sh on ALL missing components for the second iteration
def run_query_pfam(has_file):
genome = ''
# extract genome name to be used to find blast results
for comp in GENOME.split('/'):
if 'GCF' in comp:
genome = comp
if not has_file:
# write query ids to an output file to be used later
with open(GENOME + '/analysis/query_ids.txt', 'w') as f:
for q in missing_info:
if len(missing_info[q]) == 0:
continue
qid = ''
for i in missing_info[q]['query_id'].split('/'):
if '.xml' in i:
qid = i.split('.')[0] + '.' + i.split('.')[1]
f.write(qid + '\n')
if not os.path.exists(GENOME + '/analysis/query_pfam.out'):
if not os.path.isdir(GENOME + '/analysis/blastdb'):
create_blastdb = f'gunzip -c /ResearchData/Microbiome/Assemblies/{genome}/*.faa.gz | makeblastdb -dbtype prot -input_type fasta -parse_seqids -hash_index -title {genome} -out blastdb/{genome} -in -; mkdir {GENOME}/analysis/blastdb; mv blastdb/* {GENOME}/analysis/blastdb'
print(create_blastdb)
os.system(create_blastdb)
cmd1 = f'blastdbcmd -db {GENOME}/analysis/blastdb/{genome} -entry_batch {GENOME}/analysis/query_ids.txt -target_only > {GENOME}/analysis/queries.faa'
print(cmd1)
os.system(cmd1)
# get command to run pfam with a list of query sequences
cmd2 = f'run_pfam.sh {GENOME}/analysis/queries.faa {GENOME}/analysis/query_pfam.out'
print(cmd2)
os.system(cmd2)
cmd3 = f"cat {GENOME}/analysis/query_pfam.out | grep -v '#' | perl -pe 's/ +/\\t/g;' | cut -f 2,4 > {GENOME}/analysis/query_pfam_filtered.out"
print(cmd3)
os.system(cmd3)
with open(GENOME + '/analysis/query_pfam_filtered.out', 'r') as f:
lines = f.readlines()
for line in lines:
line = line.strip()
content = line.split('\t')
if content[1] in genome_pfams:
genome_pfams[content[1]].append(content[0].split('.')[0])
else:
genome_pfams[content[1]] = [content[0].split('.')[0]]
# On the first iteration we want a relative decision for multicomp systems before checking missing_comp data
def assign_multicomp_sys(row,df,input,has_file):
tcid = row["Hit_tcid"]
Fusion_Add=[]
accession = row["Hit_tcid"] + "-" + row["Hit_xid"]
Fusion_results= geneFusions[row["Hit_tcid"] + "-" + row["Hit_xid"]]
sortedGeneArr = []
if(len(Fusion_results) !=1):
sortedGeneArr = sorted(Fusion_results, key=lambda x: x['sstart'])
if len(isFusion(sortedGeneArr)) != 0:
Fusion_Add=[x["query"] for x in isFusion(sortedGeneArr)]
else:
sortedGeneArr = []
tc_arr = tcdbSystems.get(tcid)
tc_all_arr= [arr.split("-")[1] for arr in tc_arr] ##All the proteins that TCDB provide
tc_filter_arr= list(filter(lambda x: (len(df.query(f"Hit_xid=='{x}' and Hit_tcid=='{tcid}'"))) !=0, tc_all_arr))
tc_missing_arr= list(set(tc_all_arr) - set(tc_filter_arr))
tc_id_acc = row["Hit_tcid"] + "-" + row["Hit_xid"]
query = row['#Query_id']
mcs[tc_id_acc] = query
if tcid in tcid_queries:
tcid_queries[tcid].append(query)
else:
tcid_queries[tcid] = [query]
matches[query] = row["Hit_tcid"] + "-" + row["Hit_xid"]
# This function gets the multicomp decision in the first iteration
def isMultiComp(row,df,input,has_file):
if isSingleComp(row):
return (False)
##get rid of single comp system first
tcid = row["Hit_tcid"]
Fusion_Add=[]
accession = row["Hit_tcid"] + "-" + row["Hit_xid"]
Fusion_results= geneFusions[row["Hit_tcid"] + "-" + row["Hit_xid"]]
sortedGeneArr = []
if(len(Fusion_results) !=1):
sortedGeneArr = sorted(Fusion_results, key=lambda x: x['sstart'])
if len(isFusion(sortedGeneArr)) != 0:
Fusion_Add=[x["query"] for x in isFusion(sortedGeneArr)]
else:
sortedGeneArr = []
tc_arr = tcdbSystems.get(tcid)
tc_all_arr= [arr.split("-")[1] for arr in tc_arr] ##All the proteins that TCDB provide
tc_filter_arr= list(filter(lambda x: (len(df.query(f"Hit_xid=='{x}' and Hit_tcid=='{tcid}'"))) !=0, tc_all_arr))
tc_missing_arr= list(set(tc_all_arr) - set(tc_filter_arr))
tc_id_acc = row["Hit_tcid"] + "-" + row["Hit_xid"]
fusions = ''
qid = row['#Query_id']
if len(Fusion_Add) > 0:
if qid not in Fusion_Add:
Fusion_Add = []
protein_type = row['Hit_tcid'].split('.')[0] + '.' + row['Hit_tcid'].split('.')[1]
tcdb_tms = row['Hit_n_TMS']
# if the tcid has already been assigned, assign this protein to the same file
if row['Hit_tcid'] in tcid_assignments:
if tcid_assignments[row['Hit_tcid']] == 'Green':
matches[row['#Query_id']] = row['Hit_tcid'] + '-' + row['Hit_xid']
curr_hit[tc_id_acc] = row['#Query_id']
if len(tc_missing_arr) > 0:
for missing in tc_missing_arr:
if len(missing) > 0:
missing_info[row['Hit_tcid'] + '-' + missing] = {}
queries[row['#Query_id']] = tcid_assignments[row['Hit_tcid']]
tcid_queries[row['Hit_tcid']].append(row['#Query_id'])
return({"color": tcid_assignments[row['Hit_tcid']],
"Found_proteins":tc_filter_arr,
"All_proteins":tc_arr,
'Missing_proteins':tc_missing_arr,
"Fusion_results":Fusion_Add,
"isFusion":len(Fusion_Add)>0,
"Initial_decision": tcid_assignments[row['Hit_tcid']]})
# This redecides mcs after looking at genomic context
def isMultiCompSecondIteration(row,df,input,has_file):
if isSingleComp(row):
return (False)
##get rid of single comp system first
tcid = row["Hit_tcid"]
Fusion_Add=[]
accession = row["Hit_tcid"] + "-" + row["Hit_xid"]
Fusion_results= geneFusions[row["Hit_tcid"] + "-" + row["Hit_xid"]]
sortedGeneArr = []
if(len(Fusion_results) !=1):
sortedGeneArr = sorted(Fusion_results, key=lambda x: x['sstart'])
if len(isFusion(sortedGeneArr)) != 0:
Fusion_Add=[x["query"] for x in isFusion(sortedGeneArr)]
else:
sortedGeneArr = []
tc_arr = tcdbSystems.get(tcid)
tc_all_arr= [arr.split("-")[1] for arr in tc_arr] ##All the proteins that TCDB provide
tc_filter_arr= list(filter(lambda x: (len(df.query(f"Hit_xid=='{x}' and Hit_tcid=='{tcid}'"))) !=0, tc_all_arr))
tc_missing_arr= list(set(tc_all_arr) - set(tc_filter_arr))
tc_id_acc = row["Hit_tcid"] + "-" + row["Hit_xid"]
fusions = ''
qid = row['#Query_id']
if len(Fusion_Add) > 0:
if qid not in Fusion_Add:
Fusion_Add = []
protein_type = row['Hit_tcid'].split('.')[0] + '.' + row['Hit_tcid'].split('.')[1]
tcdb_tms = row['Hit_n_TMS']
mismatched_query = ''
# if the system has been determined to be an operon we have to find a way to complete the system with the right proteins
if tcid in operons and operons[tcid] == 'possible operon':
MembraneProteins= FindMembraneProtein(row, df)
decision = multicomp_decision(tc_arr, row['Hit_tcid'], MembraneProteins, tc_filter_arr, tc_missing_arr, has_file)
if tcid in mistakes and decision != 'red':
for m in range(0, len(mistakes[tcid])):
mismatched_query = mistakes[tcid][m]
corrected_protein_assignment = matches[mismatched_query]
if len(corrected_protein_assignment) == 0:
continue
# should be corrected_protein is tcid-component with correct query
# that current assignment in row is the wrong query
# we need to remove that entire row and create a new one with new values
protein_to_remove = corrected_protein_assignment.split('-')[1]
if protein_to_remove in tc_filter_arr:
tc_filter_arr.remove(protein_to_remove)
tc_missing_arr.append(protein_to_remove)
new_matches[corrected_protein_assignment] = mismatched_query
# add queries and tcid to dict and figure out if we can just automatically classify in green if part of operon according to genomic context
# If the system has been previously assigned to a file just assign the protein to the same file
if row['Hit_tcid'] in tcid_assignments:
if tcid_assignments[row['Hit_tcid']] == 'Green':
matches[row['#Query_id']] = row['Hit_tcid'] + '-' + row['Hit_xid']
curr_hit[tc_id_acc] = row['#Query_id']
if len(tc_missing_arr) > 0:
for missing in tc_missing_arr:
if len(missing) > 0:
missing_info[row['Hit_tcid'] + '-' + missing] = {}
queries[row['#Query_id']] = tcid_assignments[row['Hit_tcid']]
tcid_queries[row['Hit_tcid']].append(row['#Query_id'])
return({"color": tcid_assignments[row['Hit_tcid']],
"Found_proteins":tc_filter_arr,
"All_proteins":tc_arr,
'Missing_proteins':tc_missing_arr,
"Fusion_results":Fusion_Add,
"isFusion":len(Fusion_Add)>0,
"Initial_decision": tcid_assignments[row['Hit_tcid']]})
if(set(tc_all_arr)==set(tc_filter_arr)):##If all the proteins in that system can be found, then green
#print(tc_arr)
#print("green",tc_filter_arr,"Fusion Results:",Fusion_Add)
#if tcid == '3.A.1.12.4':
# print(eVal(row) <= E_VAL_GREEN and qCoverage(row) >= Q_COV_THRESH and hCoverage(row) >= S_COV_THRESH and len(pfamDoms(row)) != 0 and tm_overlap_decision(row) == True)
#if(eVal(row) <= E_VAL_GREEN and qCoverage(row) >= Q_COV_THRESH and hCoverage(row) >= S_COV_THRESH and len(pfamDoms(row)) != 0 and tm_overlap_decision(row) == True):
if(eVal(row) <= E_VAL_GREEN and qCoverage(row) >= Q_COV_THRESH and hCoverage(row) >= S_COV_THRESH and len(pfamDoms(row)) != 0 and tm_overlap_decision(row) == True):
tcid_assignments[row['Hit_tcid']] = 'Green'
queries[row['#Query_id']] = 'Green'
curr_hit[tc_id_acc] = row['#Query_id']
for protein in tc_filter_arr:
if protein in multi_system_assignments:
multi_system_assignments[protein].append(tcid, 'Green')
else:
multi_system_assignments[protein] = (tcid, 'Green')
tcid_queries[row['Hit_tcid']] = [row['#Query_id']]
matches[row['#Query_id']] = row['Hit_tcid'] + '-' + row['Hit_xid']
return({"color":"Green",
"Found_proteins":tc_filter_arr,
"All_proteins":tc_arr,
'Missing_proteins':tc_missing_arr,
"Fusion_results":Fusion_Add,
"isFusion":len(Fusion_Add)>0,
"Initial_decision": 'green'})
# if this is a new match determined by genomic context has to become green
if tc_id_acc in new_matches:
matches[new_matches[tc_id_acc]] = row['Hit_tcid'] + '-' + row['Hit_xid']
curr_hit[tc_id_acc] = new_matches[tc_id_acc]
if len(tc_missing_arr) > 0:
for missing in tc_missing_arr:
if len(missing) > 0:
missing_info[row['Hit_tcid'] + '-' + missing] = {}
tcid_assignments[row['Hit_tcid']] = 'Green'
queries[new_matches[tc_id_acc]] = tcid_assignments[row['Hit_tcid']]
tcid_queries[row['Hit_tcid']] = [new_matches[tc_id_acc]]
return({"color":"Green",
"Found_proteins":tc_filter_arr,
"All_proteins":tc_arr,
'Missing_proteins':tc_missing_arr,
"Fusion_results":Fusion_Add,
"isFusion":len(Fusion_Add)>0,
"Initial_decision": 'green'})
# get list of membrane proteins in the system
MembraneProteins= FindMembraneProtein(row, df)
count_mem = 0
total_tcmem = 0
# count the number of membrane proteins to be compared later
if len(MembraneProteins) > 0 or not isEmpty(MembraneProteins):
if type(MembraneProteins) is not list:
mem_proteins = list(MembraneProteins['Hit_xid'].values())
total_tcmem = len(mem_proteins)
else:
mem_proteins = MembraneProteins
total_tcmem = len(MembraneProteins)
for p in mem_proteins:
if p in tc_filter_arr:
count_mem += 1
# Determine how essential the missing components are before assignment
decision = multicomp_decision(tc_arr, row['Hit_tcid'], MembraneProteins, tc_filter_arr, tc_missing_arr, has_file)
if len(tc_missing_arr) == 0 and final_decision(row, sortedGeneArr, tcdb_tms) == 'yellow':
tcid_assignments[row['Hit_tcid']] = 'Yellow'
for protein in tc_filter_arr:
queries[row['#Query_id']] = 'Yellow'
if protein in multi_system_assignments:
multi_system_assignments[protein].append(tcid, 'Yellow')
else:
multi_system_assignments[protein] = (tcid, 'Yellow')
tcid_queries[row['Hit_tcid']] = [row['#Query_id']]
return({"color":"Yellow",
"Found_proteins":tc_filter_arr,
"All_proteins":tc_arr,
'Missing_proteins':tc_missing_arr,
"Fusion_results":Fusion_Add,
"isFusion":len(Fusion_Add)>0,
'Initial_decision': 'Yellow'})
# if(input*len(tc_all_arr)<=len(tc_filter_arr)) and len(set(MembraneProteins) & set(tc_filter_arr))>0:
if (total_tcmem > 0 and input <= float(count_mem / total_tcmem)) or (len(set(tc_filter_arr))>0 and isEmpty(MembraneProteins)):
##given some proteins can be found while containing the membrane proteins
if final_decision(row, sortedGeneArr, tcdb_tms) == 'yellow' or final_decision(row, sortedGeneArr, tcdb_tms) == 'green':
if decision == 'yellow':
queries[row['#Query_id']] = 'Yellow'
tcid_assignments[row['Hit_tcid']] = 'Yellow'
for protein in tc_filter_arr:
if protein in multi_system_assignments:
multi_system_assignments[protein].append(tcid, 'Yellow')
else:
multi_system_assignments[protein] = (tcid, 'Yellow')
tcid_queries[row['Hit_tcid']] = [row['#Query_id']]
return({"color":"Yellow",
"Found_proteins":tc_filter_arr,
"All_proteins":tc_arr,
'Missing_proteins':tc_missing_arr,
"Fusion_results":Fusion_Add,
"isFusion":len(Fusion_Add)>0,
'Initial_decision': 'Yellow'})
elif decision == 'Green':
queries[row['#Query_id']] = 'Green'
tcid_assignments[tcid] = 'Green'
curr_hit[tc_id_acc] = row['#Query_id']
for protein in tc_filter_arr:
if protein in multi_system_assignments:
multi_system_assignments[protein].append(tcid, 'Green')
else:
multi_system_assignments[protein] = (tcid, 'Green')
tcid_queries[row['Hit_tcid']] = [row['#Query_id']]
matches[row['#Query_id']] = row['Hit_tcid'] + '-' + row['Hit_xid']
return({"color":"Green",
"Found_proteins":tc_filter_arr,
"All_proteins":tc_arr,
'Missing_proteins':tc_missing_arr,
"Fusion_results":Fusion_Add,
"isFusion":len(Fusion_Add)>0,
'Initial_decision': 'Yellow'})
tcid_assignments[row['Hit_tcid']] = 'Red'
queries[row['#Query_id']] = 'Red'
for protein in tc_filter_arr:
if protein in multi_system_assignments:
multi_system_assignments[protein].append(tcid, 'Red')
else:
multi_system_assignments[protein] = (tcid, 'Red')
tcid_queries[row['Hit_tcid']] = [row['#Query_id']]
return({"color":"Red",
"Found_proteins":tc_filter_arr,
"All_proteins":tc_arr,
'Missing_proteins':tc_missing_arr,
"Fusion_results":Fusion_Add,
"isFusion":len(Fusion_Add)>0,
'Initial_decision': 'Red'})
# This function checks if the replicon exists
def found_replicon(gene_ranking, tcid, replicon):
qs = tcid_queries[tcid]
for query in qs:
if query not in gene_ranking[replicon]:
return False
return True
# checks if teh gene rank is within the window
def find_number_outside_range(ranking, range_limit):
arr = ranking.keys()
for i in range(len(arr) - 1):
if abs(arr[i] - arr[i + 1]) > range_limit:
return ranking[arr[i + 1]]
return None # If all numbers are within the range, return None
# This function completes operons by looking at genomic context
def getGenomicContext(min_distance, min_missing_comps):
# Check if FEATURE_TABLE and GBFF_FILE exist before proceeding
if not os.path.isfile(FEATURE_TABLE):
raise FileNotFoundError(f"The file {FEATURE_TABLE} does not exist.")
if not os.path.isfile(GBFF_FILE):
raise FileNotFoundError(f"The file {GBFF_FILE} does not exist.")
# commands to get important values from feature table and shape of the replicon
cmd1 = f'zgrep CDS {FEATURE_TABLE} | cut -f 7-11 | sort -k1,1 -k2,2n'