-
Notifications
You must be signed in to change notification settings - Fork 0
/
compute_features.py
2277 lines (2094 loc) · 119 KB
/
compute_features.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/python
#EVmutation uses approximately (1/486)^2*len(ntseq)^2 for amino acid sequences, and (1/806)^2*len(ntseq)^2 for nt sequences
import random, subprocess, re, os, sys, os.path, warnings, math, time, argparse, mygene, warnings, inspect, string, traceback, requests, json, shutil, psutil, pickle, statistics, bio_tools, hgvs, copy, tools
import numpy as np
import pandas as pd
import align_codons
import hmmlearn.hmm
from collections import Counter
from Bio import SeqIO, pairwise2, Entrez, SearchIO
from Bio.Blast import NCBIWWW
from urllib.request import urlopen
import urllib.parse
from multiprocessing import Queue, Process, Manager, Value
try:
from BeautifulSoup import BeautifulSoup
except ImportError:
from bs4 import BeautifulSoup
#update the following variables to match the locations in your path
pos = "ORF nt#" #column name of location of variant in coding sequence
gene = "GENE" #column name of gene
nt_wt = "nt (WT)" #column name of wild type nucleotide
nt_mut = "nt (mut)" #column name of mutant nucleotide
remuRNA_cmd = "/media/home/software/remuRNA/remuRNA" #path to remuRNA executable
uniclust = "/media/home/software/hh-suite/data/uniclust30_2018_08" #path to uniclust for NetSurfP2
hhsuite_model = "/media/home/software/NetSurfP/models/hhsuite.pb"
sys.path.insert(0, './EVmutation')
sys.path.insert(0, './rc_enrichment')
Entrez.email = ""
Entrez.api_key = ""
ram_disk = "/media/temp/"
import create_analysis
import calc_codon_usage, calc_rare_enrichment
#dict containing BLOSUM62 values for amino acid sequences
blosum = {'A': {'A': 4, 'R': -1, 'N': -2, 'D': -2, 'C': 0, 'Q': -1, 'E': -1, 'G': 0, 'H': -2, 'I': -1, 'L': -1, 'K': -1, 'M': -1, 'F': -2, 'P': -1, 'S': 1, 'T': 0, 'W': -3, 'Y': -2, 'V': 0, 'B': -2, 'Z': -1, 'X': 0, '*': -4}, \
'R': {'A': -1, 'R': 5, 'N': 0, 'D': -2, 'C': -3, 'Q': 1, 'E': 0, 'G': -2, 'H': 0, 'I': -3, 'L': -2, 'K': 2, 'M': -1, 'F': -3, 'P': -2, 'S': -1, 'T': -1, 'W': -3, 'Y': -2, 'V': -3, 'B': -1, 'Z': 0, 'X': -1, '*': -4}, \
'N': {'A': -2, 'R': 0, 'N': 6, 'D': 1, 'C': -3, 'Q': 0, 'E': 0, 'G': 0, 'H': 1, 'I': -3, 'L': -3, 'K': 0, 'M': -2, 'F': -3, 'P': -2, 'S': 1, 'T': 0, 'W': -4, 'Y': -2, 'V': -3, 'B': 3, 'Z': 0, 'X': -1, '*': -4}, \
'D': {'A': -2, 'R': -2, 'N': 1, 'D': 6, 'C': -3, 'Q': 0, 'E': 2, 'G': -1, 'H': -1, 'I': -3, 'L': -4, 'K': -1, 'M': -3, 'F': -3, 'P': -1, 'S': 0, 'T': -1, 'W': -4, 'Y': -3, 'V': -3, 'B': 4, 'Z': 1, 'X': -1, '*': -4}, \
'C': {'A': 0, 'R': -3, 'N': -3, 'D': -3, 'C': 9, 'Q': -3, 'E': -4, 'G': -3, 'H': -3, 'I': -1, 'L': -1, 'K': -3, 'M': -1, 'F': -2, 'P': -3, 'S': -1, 'T': -1, 'W': -2, 'Y': -2, 'V': -1, 'B': -3, 'Z': -3, 'X': -2, '*': -4}, \
'Q': {'A': -1, 'R': 1, 'N': 0, 'D': 0, 'C': -3, 'Q': 5, 'E': 2, 'G': -2, 'H': 0, 'I': -3, 'L': -2, 'K': 1, 'M': 0, 'F': -3, 'P': -1, 'S': 0, 'T': -1, 'W': -2, 'Y': -1, 'V': -2, 'B': 0, 'Z': 3, 'X': -1, '*': -4}, \
'E': {'A': -1, 'R': 0, 'N': 0, 'D': 2, 'C': -4, 'Q': 2, 'E': 5, 'G': -2, 'H': 0, 'I': -3, 'L': -3, 'K': 1, 'M': -2, 'F': -3, 'P': -1, 'S': 0, 'T': -1, 'W': -3, 'Y': -2, 'V': -2, 'B': 1, 'Z': 4, 'X': -1, '*': -4}, \
'G': {'A': 0, 'R': -2, 'N': 0, 'D': -1, 'C': -3, 'Q': -2, 'E': -2, 'G': 6, 'H': -2, 'I': -4, 'L': -4, 'K': -2, 'M': -3, 'F': -3, 'P': -2, 'S': 0, 'T': -2, 'W': -2, 'Y': -3, 'V': -3, 'B': -1, 'Z': -2, 'X': -1, '*': -4}, \
'H': {'A': -2, 'R': 0, 'N': 1, 'D': -1, 'C': -3, 'Q': 0, 'E': 0, 'G': -2, 'H': 8, 'I': -3, 'L': -3, 'K': -1, 'M': -2, 'F': -1, 'P': -2, 'S': -1, 'T': -2, 'W': -2, 'Y': 2, 'V': -3, 'B': 0, 'Z': 0, 'X': -1, '*': -4}, \
'I': {'A': -1, 'R': -3, 'N': -3, 'D': -3, 'C': -1, 'Q': -3, 'E': -3, 'G': -4, 'H': -3, 'I': 4, 'L': 2, 'K': -3, 'M': 1, 'F': 0, 'P': -3, 'S': -2, 'T': -1, 'W': -3, 'Y': -1, 'V': 3, 'B': -3, 'Z': -3, 'X': -1, '*': -4}, \
'L': {'A': -1, 'R': -2, 'N': -3, 'D': -4, 'C': -1, 'Q': -2, 'E': -3, 'G': -4, 'H': -3, 'I': 2, 'L': 4, 'K': -2, 'M': 2, 'F': 0, 'P': -3, 'S': -2, 'T': -1, 'W': -2, 'Y': -1, 'V': 1, 'B': -4, 'Z': -3, 'X': -1, '*': -4}, \
'K': {'A': -1, 'R': 2, 'N': 0, 'D': -1, 'C': -3, 'Q': 1, 'E': 1, 'G': -2, 'H': -1, 'I': -3, 'L': -2, 'K': 5, 'M': -1, 'F': -3, 'P': -1, 'S': 0, 'T': -1, 'W': -3, 'Y': -2, 'V': -2, 'B': 0, 'Z': 1, 'X': -1, '*': -4}, \
'M': {'A': -1, 'R': -1, 'N': -2, 'D': -3, 'C': -1, 'Q': 0, 'E': -2, 'G': -3, 'H': -2, 'I': 1, 'L': 2, 'K': -1, 'M': 5, 'F': 0, 'P': -2, 'S': -1, 'T': -1, 'W': -1, 'Y': -1, 'V': 1, 'B': -3, 'Z': -1, 'X': -1, '*': -4}, \
'F': {'A': -2, 'R': -3, 'N': -3, 'D': -3, 'C': -2, 'Q': -3, 'E': -3, 'G': -3, 'H': -1, 'I': 0, 'L': 0, 'K': -3, 'M': 0, 'F': 6, 'P': -4, 'S': -2, 'T': -2, 'W': 1, 'Y': 3, 'V': -1, 'B': -3, 'Z': -3, 'X': -1, '*': -4}, \
'P': {'A': -1, 'R': -2, 'N': -2, 'D': -1, 'C': -3, 'Q': -1, 'E': -1, 'G': -2, 'H': -2, 'I': -3, 'L': -3, 'K': -1, 'M': -2, 'F': -4, 'P': 7, 'S': -1, 'T': -1, 'W': -4, 'Y': -3, 'V': -2, 'B': -2, 'Z': -1, 'X': -2, '*': -4}, \
'S': {'A': 1, 'R': -1, 'N': 1, 'D': 0, 'C': -1, 'Q': 0, 'E': 0, 'G': 0, 'H': -1, 'I': -2, 'L': -2, 'K': 0, 'M': -1, 'F': -2, 'P': -1, 'S': 4, 'T': 1, 'W': -3, 'Y': -2, 'V': -2, 'B': 0, 'Z': 0, 'X': 0, '*': -4}, \
'T': {'A': 0, 'R': -1, 'N': 0, 'D': -1, 'C': -1, 'Q': -1, 'E': -1, 'G': -2, 'H': -2, 'I': -1, 'L': -1, 'K': -1, 'M': -1, 'F': -2, 'P': -1, 'S': 1, 'T': 5, 'W': -2, 'Y': -2, 'V': 0, 'B': -1, 'Z': -1, 'X': 0, '*': -4}, \
'W': {'A': -3, 'R': -3, 'N': -4, 'D': -4, 'C': -2, 'Q': -2, 'E': -3, 'G': -2, 'H': -2, 'I': -3, 'L': -2, 'K': -3, 'M': -1, 'F': 1, 'P': -4, 'S': -3, 'T': -2, 'W': 11, 'Y': 2, 'V': -3, 'B': -4, 'Z': -3, 'X': -2, '*': -4}, \
'Y': {'A': -2, 'R': -2, 'N': -2, 'D': -3, 'C': -2, 'Q': -1, 'E': -2, 'G': -3, 'H': 2, 'I': -1, 'L': -1, 'K': -2, 'M': -1, 'F': 3, 'P': -3, 'S': -2, 'T': -2, 'W': 2, 'Y': 7, 'V': -1, 'B': -3, 'Z': -2, 'X': -1, '*': -4}, \
'V': {'A': 0, 'R': -3, 'N': -3, 'D': -3, 'C': -1, 'Q': -2, 'E': -2, 'G': -3, 'H': -3, 'I': 3, 'L': 1, 'K': -2, 'M': 1, 'F': -1, 'P': -2, 'S': -2, 'T': 0, 'W': -3, 'Y': -1, 'V': 4, 'B': -3, 'Z': -2, 'X': -1, '*': -4}, \
'B': {'A': -2, 'R': -1, 'N': 3, 'D': 4, 'C': -3, 'Q': 0, 'E': 1, 'G': -1, 'H': 0, 'I': -3, 'L': -4, 'K': 0, 'M': -3, 'F': -3, 'P': -2, 'S': 0, 'T': -1, 'W': -4, 'Y': -3, 'V': -3, 'B': 4, 'Z': 1, 'X': -1, '*': -4}, \
'Z': {'A': -1, 'R': 0, 'N': 0, 'D': 1, 'C': -3, 'Q': 3, 'E': 4, 'G': -2, 'H': 0, 'I': -3, 'L': -3, 'K': 1, 'M': -1, 'F': -3, 'P': -1, 'S': 0, 'T': -1, 'W': -3, 'Y': -2, 'V': -2, 'B': 1, 'Z': 4, 'X': -1, '*': -4}, \
'X': {'A': 0, 'R': -1, 'N': -1, 'D': -1, 'C': -2, 'Q': -1, 'E': -1, 'G': -1, 'H': -1, 'I': -1, 'L': -1, 'K': -1, 'M': -1, 'F': -1, 'P': -2, 'S': 0, 'T': 0, 'W': -2, 'Y': -1, 'V': -1, 'B': -1, 'Z': -1, 'X': -1, '*': -4}, \
'*': {'A': -4, 'R': -4, 'N': -4, 'D': -4, 'C': -4, 'Q': -4, 'E': -4, 'G': -4, 'H': -4, 'I': -4, 'L': -4, 'K': -4, 'M': -4, 'F': -4, 'P': -4, 'S': -4, 'T': -4, 'W': -4, 'Y': -4, 'V': -4, 'B': -4, 'Z': -4, 'X': -4, '*': 1}}
rev_translate = {'I' : ['ATT', 'ATC', 'ATA'],
'L' : ['CTT', 'CTC', 'CTA', 'CTG', 'TTA', 'TTG'],
'V' : ['GTT', 'GTC', 'GTA', 'GTG'],
'F' : ['TTT', 'TTC'],
'M' : ['ATG'],
'C' : ['TGT', 'TGC'],
'A' : ['GCT', 'GCC', 'GCA', 'GCG'],
'G' : ['GGT', 'GGC', 'GGA', 'GGG'],
'P' : ['CCT', 'CCC', 'CCA', 'CCG'],
'T' : ['ACT', 'ACC', 'ACA', 'ACG'],
'S' : ['TCT', 'TCC', 'TCA', 'TCG', 'AGT', 'AGC'],
'Y' : ['TAT', 'TAC'],
'W' : ['TGG'],
'Q' : ['CAA', 'CAG'],
'N' : ['AAT', 'AAC'],
'H' : ['CAT', 'CAC'],
'E' : ['GAA', 'GAG'],
'D' : ['GAT', 'GAC'],
'K' : ['AAA', 'AAG'],
'R' : ['CGT', 'CGC', 'CGA', 'CGG', 'AGA', 'AGG'],
'*' : ['TAA', 'TAG', 'TGA']}
translate = {codon : aa for aa,v in rev_translate.items() for codon in v}
aa_to_3aa = {'A': 'ALA', 'R': 'ARG', 'N': 'ASN', 'D': 'ASP', 'B': 'ASX', 'C': 'CYS', 'E': 'GLU', 'Q': 'GLN', 'Z': 'GLX', 'G': 'GLY', 'H': 'HIS', 'I': 'ILE', 'L': 'LEU', 'K': 'LYS', 'M': 'MET', 'F': 'PHE', 'P': 'PRO', 'S': 'SER', 'T': 'THR', 'W': 'TRP', 'Y': 'TYR', 'V': 'VAL'}
triple_to_aa = {'ALA': 'A', 'ARG': 'R', 'ASN': 'N', 'ASP': 'D', 'ASX': 'B', 'CYS': 'C', 'GLU': 'E', 'GLN': 'Q', 'GLX': 'Z', 'GLY': 'G', 'HIS': 'H', 'ILE': 'I', 'LEU': 'L', 'LYS': 'K', 'MET': 'M', 'PHE': 'F', 'PRO': 'P', 'SER': 'S', 'THR': 'T', 'TRP': 'W', 'TYR': 'Y', 'VAL': 'V', 'CSD': 'C', 'HYP': 'P', 'BMT': 'T', '5HP': 'E', 'ABA': 'A', 'AIB': 'A', 'CSW': 'C', 'OCS': 'C', 'DAL': 'A', 'DAR': 'R', 'DSG': 'N', 'DSP': 'D', 'DCY': 'C', 'DGL': 'E', 'DGN': 'Q', 'DHI': 'H', 'DIL': 'I', 'DIV': 'V', 'DLE': 'L', 'DLY': 'K', 'DPN': 'F', 'DPR': 'P', 'DSN': 'S', 'DTH': 'T', 'DTY': 'Y', 'DVA': 'V', 'CGU': 'E', 'KCX': 'K', 'LLP': 'K', 'CXM': 'M', 'FME': 'M', 'MLE': 'L', 'MVA': 'V', 'NLE': 'L', 'PTR': 'Y', 'ORN': 'A', 'SEP': 'S', 'TPO': 'T', 'PCA': 'E', 'SAR': 'G', 'CEA': 'C', 'CSO': 'C', 'CSS': 'C', 'CSX': 'C', 'CME': 'C', 'TYS': 'Y', 'TPQ': 'F', 'STY': 'Y'}
#amino acid data
aa_data = {
'A' : {"Charge": 0, "Polar Neutral": 0, "Aromatic": 0, "Large": 0, "Small": 1, "Hydrophobicity": 1.8},
'C' : {"Charge": 0, "Polar Neutral": 1, "Aromatic": 0, "Large": 0, "Small": 0, "Hydrophobicity": 2.5},
'D' : {"Charge": -1, "Polar Neutral": 0, "Aromatic": 0, "Large": 0, "Small": 1, "Hydrophobicity": -3.5},
'E' : {"Charge": -1, "Polar Neutral": 0, "Aromatic": 0, "Large": 0, "Small": 0, "Hydrophobicity": -3.5},
'F' : {"Charge": 0, "Polar Neutral": 0, "Aromatic": 1, "Large": 1, "Small": 0, "Hydrophobicity": 2.8},
'G' : {"Charge": 0, "Polar Neutral": 0, "Aromatic": 0, "Large": 0, "Small": 1, "Hydrophobicity": -0.4},
'H' : {"Charge": 1, "Polar Neutral": 0, "Aromatic": 1, "Large": 1, "Small": 0, "Hydrophobicity": -3.2},
'I' : {"Charge": 0, "Polar Neutral": 0, "Aromatic": 0, "Large": 0, "Small": 0, "Hydrophobicity": 4.5},
'K' : {"Charge": 1, "Polar Neutral": 0, "Aromatic": 0, "Large": 1, "Small": 0, "Hydrophobicity": -3.9},
'L' : {"Charge": 0, "Polar Neutral": 0, "Aromatic": 0, "Large": 0, "Small": 0, "Hydrophobicity": 3.8},
'M' : {"Charge": 0, "Polar Neutral": 0, "Aromatic": 0, "Large": 1, "Small": 0, "Hydrophobicity": 1.9},
'N' : {"Charge": 0, "Polar Neutral": 1, "Aromatic": 0, "Large": 0, "Small": 1, "Hydrophobicity": -3.5},
'P' : {"Charge": 0, "Polar Neutral": 0, "Aromatic": 0, "Large": 0, "Small": 1, "Hydrophobicity": -1.6},
'Q' : {"Charge": 0, "Polar Neutral": 1, "Aromatic": 0, "Large": 1, "Small": 0, "Hydrophobicity": -3.5},
'R' : {"Charge": 1, "Polar Neutral": 0, "Aromatic": 0, "Large": 1, "Small": 0, "Hydrophobicity": -4.5},
'S' : {"Charge": 0, "Polar Neutral": 1, "Aromatic": 0, "Large": 0, "Small": 1, "Hydrophobicity": -0.8},
'T' : {"Charge": 0, "Polar Neutral": 1, "Aromatic": 0, "Large": 0, "Small": 1, "Hydrophobicity": -0.7},
'V' : {"Charge": 0, "Polar Neutral": 0, "Aromatic": 0, "Large": 0, "Small": 0, "Hydrophobicity": 4.2},
'W' : {"Charge": 0, "Polar Neutral": 0, "Aromatic": 1, "Large": 1, "Small": 0, "Hydrophobicity": -0.9},
'Y' : {"Charge": 0, "Polar Neutral": 0, "Aromatic": 1, "Large": 1, "Small": 0, "Hydrophobicity": -1.3}
}
dbfeats = ['Non-synonimous-1, Synonymous-2', 'Disease-associated (1-yes, 2-no)', 'Mutation Code# (WTnt & nt# & Mutnt)', 'nt (WT)', 'nt (mut)', 'Amino Acid #', 'Position in the codon', 'RS #', 'Duplicates within section', 'Duplicates across sections', 'Entered manually', 'Done through program', 'AA (WT)', 'AA (mut)', 'Codon (WT)', 'Codon (mut)', 'Codon Pair-1 (WT)', 'Codon Pair-2 (WT)', 'Codon Pair-1 (mut)', 'Codon Pair-2 (mut)', 'ORF nt# (A of ATG=1)', 'Exon#', 'Known mechanisms (if any)', 'Reference paper (First_Last authors_JournalName_Year_XXX)', 'Does mutation remove or create CpG? (1-Yes, 0-No)', 'Type of nt change (0-Transition, 1-Transversion)', 'Near Splice Junction (< 7 nt)? (1-Yes, 0-No)', 'Alpha Helix', 'Beta Sheet', 'Turn', 'No Structure Predicted', 'Domain from Uniprot', 'Binding site', 'Metal binding', 'Active Site', 'Cleavage site', 'Site', 'Phosphorylation', 'Glycosylation', 'Disulfide bond', 'Lipidation', 'Cross-link', 'Other modified residues', 'Free column', 'Free column.1', 'Other PTM', 'Cystein (in WT)(1-Yes, 0-No) 21 yes', 'Prolin (in WT) (1-Yes, 2-No) 3 yes', 'Cysteine Involved? 1-Yes 0-No', 'Proline Involved? 1-Yes 2-No', 'Final Amino Acid (WT)', 'Charge (WT)', 'Polar Neutral: Y, N, C, Q, S, T', 'Aromatic: F, W, Y', 'Large: M, F, W, Y, Q, R, H, K', 'Small: A, G', 'Hydrophobicity Scale (WT)', 'Phosphorylation Potential (WT)', 'Final Amino Acid (mut)', 'Charge (mut)', 'Hydrophobicity Scale (Mut)', 'Positive to Negative', 'Negative to Positive', 'Positive/Negative to Neutral', 'Neutral to Positive/Negative', 'No change', '∆Charge (mut-WT)', '∆Hydrophobicity Scale (mut-WT)', '∆Phosphorylation Potential (mut-WT)', 'GC content of 151 nt (WT)', 'GC content of 151 nt (Mut)', 'ΔGC content of 151 nt (mut-WT)', 'Codon (WT).1', 'Codon (mut).1', 'Amino Acid (WT)', 'Amino Acid (mut)', 'WT RSCU (genome)', 'Mutant RSCU (genome)', 'ΔRSCU (mut - WT) (genome)', 'WT RSCU (genome) < 0.75', 'WT W (genome)', 'Mutant W (genome)', 'ΔW (mut - WT)(genome)', 'Bicodon-1 (WT-upstream)', 'Bicodon-2 (WT-downstream)', 'Bi-amino acids-1 (WT)', 'Bi-amino acids-2 (WT)', 'RSBCU-1 (WT)', 'RSBCU-2 (WT)', 'Bicodon-1 (mutated codon and upstream)', 'Bicodon-2 (mutated codon and downstream)', 'Bi-amino acids-1 (Mut)', 'Bi-amino acids-2 (Mut)', 'RSBCU-1 (Mut)', 'RSBCU-2 (Mut)', 'ΔRSBCU-1 (mut - WT)(genome)', 'ΔRSBCU-2 (mut - WT)(genome)', 'CPS-1 (WT)', 'CPS-2 (WT)', 'CPS-1 (Mut)', 'CPS-2 (Mut)', 'ΔCPS-1 (mut - WT)(genome)', 'ΔCPS-2 (mut - WT)(genome)', 'Noln: CPS-1 (WT)', 'Noln: CPS-2 (WT)', 'Noln: CPS-1 (Mut)', 'Noln: CPS-2 (Mut)', 'Noln: ΔCPS-1 (mut - WT)(genome)', 'Noln: ΔCPS-2 (mut - WT)(genome)', 'A RSCU, WT data (gene)', 'B RSCU, WT data (gene)', 'A RSCU, Mut data (gene)', 'B RSCU, Mut data (gene)', 'ΔRSCU (WT B - WT A) (gene)', 'ΔRSCU (Mut B - WT A) (gene)', 'ΔRSCU (Mut A - WT A) (gene)', 'ΔRSCU (Mut B - WT B) (gene)', 'A W, WT data (gene)', 'B W, WT data (gene)', 'A W, Mut data (gene)', 'B W, Mut data (gene)', 'ΔW (WT B - WT A) (gene)', 'ΔW (Mut B - WT A) (gene)', 'ΔW (Mut A - WT A) (gene)', 'ΔW (Mut B - WT B) (gene)', 'A RSBCU-1, WT data (gene)', 'A RSBCU-2, WT data (gene)', 'B RSBCU-1, WT data (gene)', 'B RSBCU-2, WT data (gene)', 'A RSBCU-1, Mut data (gene)', 'A RSBCU-2, Mut data (gene)', 'B RSBCU-1, Mut data (gene)', 'B RSBCU-2, Mut data (gene)', 'ΔRSCBU 1 (WT B - WT A) (gene)', 'ΔRSCBU 1 (Mut B - WT A) (gene)', 'ΔRSCBU 1 (Mut A - WT A) (gene)', 'ΔRSCBU 1 (Mut B - WT B) (gene)', 'ΔRSCBU 2 (WT B - WT A) (gene)', 'ΔRSCBU 2 (Mut B - WT A) (gene)', 'ΔRSCBU 2 (Mut A - WT A) (gene)', 'ΔRSCBU 2 (Mut B - WT B) (gene)', 'CPS: 1-A WT data (gene)', 'CPS: 2-A WT data (gene)', 'CPS: 1-B WT data (gene)', 'CPS: 2-B WT data (gene)', 'CPS: 1-A Mut data (gene)', 'CPS: 2-A Mut data (gene)', 'CPS: 1-B Mut data (gene)', 'CPS: 2-B Mut data (gene)', 'ΔCPS 1 (WT B - WT A) (gene)', 'ΔCPS 1 (Mut B - WT A) (gene)', 'ΔCPS 1 (Mut A - WT A) (gene)', 'ΔCPS 1 (Mut B - WT B) (gene)', 'ΔCPS 2 (WT B - WT A) (gene)', 'ΔCPS 2 (Mut B - WT A) (gene)', 'ΔCPS 2 (Mut A - WT A) (gene)', 'ΔCPS 2 (Mut B - WT B) (gene)', 'A Noln: 1 WT data (gene)', 'A Noln: 2 WT data (gene)', 'B Noln: 1 WT data (gene)', 'B Noln: 2 WT data (gene)', 'A Noln: 1 Mut data (gene)', 'A Noln: 2 Mut data (gene)', 'B Noln: 1 Mut data (gene)', 'B Noln: 2 Mut data (gene)', 'ΔNoln 1 (WT B - WT A) (gene)', 'ΔNoln 1 (Mut B - WT A) (gene)', 'ΔNoln 1 (Mut A - WT A) (gene)', 'ΔNoln 1 (Mut B - WT B) (gene)', 'ΔNoln 2 (WT B - WT A) (gene)', 'ΔNoln 2 (Mut B - WT A) (gene)', 'ΔNoln 2 (Mut A - WT A) (gene)', 'ΔNoln 2 (Mut B - WT B) (gene)', 'ESR WT1', 'ESR WT2', 'ESR Mut1', 'ESR Mut2', 'ESR_seq delta 1', 'ESR_seq delta 2', 'Z_EI WT1', 'Z_EI WT2', 'Z_EI Mut1', 'Z_EI Mut2', 'Z_EI delta 1', 'Z_EI delta 2', 'Z_WS WT 1', 'Z_WS WT 2', 'Z_WS Mut 1', 'Z_WS Mut 2', 'Z_WS delta 1', 'Z_WS delta 2']
#finds distribution of characters at each position of alignment
def compute_distribution(seqs, genename, space="-", alphabet="", freq=True):
joined_seqs = "".join(seqs.values()).replace(space, "")
alphabet = sorted(set([alphabet[i] for i in range(len(alphabet))] + [joined_seqs[i] for i in range(len(joined_seqs))]))
alphabetsize = len(alphabet)
#print(seqs)
inverted_seqs = {i:"".join([seqs[name][i] for name in seqs]) for i in range(len(seqs[genename]))}
location = 1
distribution = {}
for i in range(len(seqs[genename])):
if seqs[genename][i] != space:
distribution[location] = {alpha:0 for alpha in alphabet}
for j in range(len(inverted_seqs[i])):
if inverted_seqs[i][j] != space:
distribution[location][inverted_seqs[i][j]] += 1
total = sum(distribution[location].values())
if freq:
distribution[location] = {k:v/float(total) for k,v in distribution[location].items()}
location += 1
return(distribution)
def getoutput_timer(cmd, t=60, interval=0.1):
def getoutput(cmd, q):
output = subprocess.getoutput(cmd)
q.put(output)
def waiter(t, q):
for i in range(math.ceil(t/interval)):
if not q.empty():
return
else:
time.sleep(interval)
return
q = Queue()
t1 = Process(target=getoutput, args=(cmd, q))
t2 = Process(target=waiter, args=(t, q))
t1.start()
t2.start()
t2.join()
if not q.empty():
output = q.get()
t1.terminate()
t2.terminate()
return(output)
else:
t1.terminate()
t2.terminate()
return(None)
def translate_seq(seq):
aaseq = ""
for i in range(len(seq)//3):
try:
aaseq += translate[seq[3*i:3*(i+1)]]
except KeyError as e:
aaseq += "X"
return(aaseq)
#return("".join([translate[seq[3*i:3*(i+1)]] for i in range(len(seq)//3)]))
#Process which iteratively takes genes from queue and computes features (can use multiprocessing)
def work(q, data, ids={}, seqdir="./gene_data", path=ram_disk, outdir="./gene_data/", skip_done=False, pdb=None, space="-", quiet=False):
while not q.empty():
genename = q.get()
seqs = parse_seqs(seqdir, genename)
try:
geneids = ids[genename]
except KeyError as e:
print("Accession IDs not found for " + genename)
geneids = {}
if not skip_done or genename + ".tsv" not in os.listdir(seqdir):
try:
data[genename], geneids = precompute(genename, seqs, ids=geneids, path=path, outdir=outdir, space=space, quiet=quiet)
except Exception as e:
tb = traceback.format_exc()
print("\033[93m" + str(tb) + "\033[0m")
print("\033[93m" + str(e) + "\033[0m")
finally:
#remove temp files for current gene
for f in os.listdir(path):
if genename in f:
if os.path.isfile(path + f):
os.remove(path + f)
elif os.path.isdir(path + f):
shutil.rmtree(path + f)
ids[genename] = geneids
pd.DataFrame(ids).to_csv(outdir + "gene_info_updated.tsv", sep="\t")
#runs mfold
def run_mfold(seq, genename="pholder", t=60, path=ram_disk):
pwd = os.getcwd()
os.chdir(path)
tools.write_fasta({genename:seq}, path + "tmp.fasta")
output = getoutput_timer("mfold SEQ='" + path + "tmp.fasta'", t=t)
if "Segmentation fault (core dumped)" in output:
raise RuntimeError("Segmentation fault while running mFold.")
energy = re.findall("Minimum folding energy is (\-?\d+\.?\d*) kcal\/mol", output)
os.chdir(pwd)
if len(energy) > 0:
return(float(energy[0]))
else:
return(None)
def run_nupack(seq, genename="", t=60, path=ram_disk):
with open(os.path.join(path, "tmp.in"), "w") as outf:
outf.write(seq)
output = getoutput_timer("mfe -pseudo " + os.path.join(path, "tmp") + " > " + os.path.join(path, "tmp.mfe"), t=t)
if output != None:
with open(os.path.join(path, "tmp.mfe"), "r") as inf:
startflag = False
lines = [line.strip() for line in inf.readlines()]
for line in lines:
if re.match("^\-?\d+\.?\d*$", line):
if not startflag and int(float(line)) == len(seq):
startflag = True
else:
return(float(line))
#calls kinefold on a sequence
#memory folders are preferred as path, as it writes multiple temporary files
def run_kinefold(seq, path=ram_disk, t=60, seed=None):
if not isinstance(seed, int):
seed = random.randint(1, 5000)
#write sequence file
with open(path + "tmp.dat", "w") as outf:
outf.write("< tmp\n")
outf.write(seq)
#write configuration file
with open(path + "tmp.req", "w") as outf:
outf.write(str(seed) + "\n")
outf.write(path + "tmp.p\n" + \
path + "tmp.e\n" + \
path + "tmp.rnm\n" + \
path + "tmp.rnms\n" + \
path + "tmp.rnml\n" + \
path + "tmp.rnm2\n" + \
path + "tmp.dat\n" + \
"0 # 0=RNA ; 1=DN A\n" + \
"6.3460741 # helix minimum free energy in kcal/mol: 6.3460741=10kT \n" + \
"10000000 # NA \n" + \
"1000 # folding time requested in msec \n" + \
"1 # pseudoknots 1=yes 0=no \n" + \
"0 # entanglements 1=yes 0=no \n" + \
"2 3 # simulation type: 1=renaturation; 2 20=cotrans. @ 20msec/nt \n" + \
" # add T i j k or F i j k options here \n" + \
"\n" + \
"tmp\n" + \
"tmp.zip\n" + \
"<SEQNAME>tmp" + "_" + str(seed) + " \n" + \
"<BASE>tmp\n" + \
"<SEQUENCE>" + seq + "\n" + \
"<ZIPFILE>tmp.zip")
output = getoutput_timer("kinefold_long_static " + path + "tmp.req", t=t)
if output == None or "Segmentation fault (core dumped)" in output:
raise RuntimeError("Segmentation fault while running Kinefold.")
#parse output
m = re.findall("(-?\d+\.?\d*) kcal/mol", output)
try:
energy = float(m[-1])
except IndexError as e:
print(output)
raise(e)
return(energy)
def get_seblastian(seq, genename, path=ram_disk, wait_time=60, give_up=12):
r = tools.retry_request(requests.post, ["https://seblastian.crg.es/cgi-bin/seblastian_cgi.py"], {'data':{"routine": "Seblastian", "seblastian_mode": "knownSP", "seblastian_upstream_length": "5000", "seblastian_blast_evalue": "1e-3", "seblastian_max_distance": "3000", "search_complement": "on", "secis_filter": "secis_filter", "make_images": "make_images", "image_resolution": "150", "use_infernal": "infernal", "infernal_threshold": "10", "use_covels": "covels", "covels_threshold": 5, "use_secisearch1": "secisearch", "secisearch_pattern": "default", "sequence_filename": "(binary)", "sequence_fasta": seq}})
html = re.findall("https\:\/\/seblastian\.crg\.es\/results\/\d+\/index\.html", r.text)
if html != None and len(html) > 0:
html = max(html, key=len)
else:
return(None)
#wait until success or time out (defaults to 12 hours)
def wait_for_seblastian(seq, genename, html, path=ram_disk, wait_time=60, give_up=12, quiet=True):
retry_counter = 1
success = False
while retry_counter < give_up*60*(60/wait_time) and not success:
results = tools.retry_request(requests.get, [html])
if results != None and "FAILED" in results.text.upper(): #failure
retry_counter += give_up*60*(60/wait_time)
warnings.warn("\033[93m" + "Seblastian failed on " + genename + "\033[0m")
return(False)
elif results != None and results.status_code == 200 and "Results will be displayed here when they are ready." not in results.text: #success!
results = results.text.split("<candidate_supertitle> SECIS prediction</candidate_supertitle>")[-1]
scores = re.findall("Infernal\s\(score\s(\d+\.?\d*)\)\sCovels\s\(score\s(\d+\.?\d*)\)\sSECISearch1\.0\s\((.+)\)\<br\>", results)
location = re.findall("\<candidate\_titles\>Positions\son\starget\:\<\/candidate\_titles\>\s(\d+\-\d+)", results)
if location != None and len(location) > 0:
location = [list(re.findall("\d+", location[i])) for i in range(len(location))]
if scores == None or len(scores) < 1 or location == None or len(location) < 1:
success = False
if len(scores) != len(location) or any([True for i in range(len(scores)) if len(scores[i]) < 3]):
warnings.warn("Unequal numbers of scores and locations read from Seblastian output")
if len(scores[0]) >= 3 and len(location) >= 2:
with open(path + genename + "_seblastian.out", "w") as outf:
for i in range(len(scores)):
outf.write("Infernal\t" + scores[i][0] + "\tCovels\t" + scores[i][1] + "\tSECISearch1.0\t" + scores[i][2] + "\n")
outf.write("Location\t" + location[i][0] + "\t" + location[i][1])
return(True)
else:
retry_counter += 1
time.sleep(wait_time)
elapsed = retry_counter*wait_time
if not quiet:
print("Waiting on Seblastian for " + str(elapsed/60) + " minutes, " + str(elapsed % 60) + " seconds" + " " * 20, end="\r")
#start the process and return (we can do other stuff while it waits)
p = Process(target=wait_for_seblastian, args=(seq, genename, html, path, wait_time, give_up, True))
p.start()
return(p)
def run_genesplicer(seqs, mut, directory="/media/home/software/GeneSplicer/human/", path=ram_disk):
pos, nts = tools.get_mutation_data(mut)
genomicpos, error = convert_position(seqs["ORF_aligned"], seqs["genomic_aligned"], pos)
tools.write_fasta({"WT":seqs["genomic"]}, path + "tmp.fasta")
wtoutput = getoutput_timer("genesplicer " + path + "tmp.fasta " + directory).split("\n")
tools.check_mut((genomicpos, nts), seqs["genomic"], index=1)
mutseq = tools.update_str(seqs["genomic"], nts[1], genomicpos+1)
tools.write_fasta({"mut":mutseq}, path + "tmp.fasta")
mutoutput = getoutput_timer("genesplicer " + path + "tmp.fasta " + directory).split("\n")
wtscores = {}
for line in wtoutput:
pieces = line.strip().split()
if len(pieces) >= 4:
wtscores[(pieces[0], pieces[1])] = {"score":pieces[2], "confidence":pieces[3], "type":pieces[4]}
mutscores = {}
for line in mutoutput:
pieces = line.strip().split()
if len(pieces) >= 4:
mutscores[(pieces[0], pieces[1])] = {"score":pieces[2], "confidence":pieces[3], "type":pieces[4]}
dif = {"Gained":{k:v for k,v in mutscores.items() if k not in wtscores.keys()}, "Lost":{k:v for k,v in wtscores.items() if k not in mutscores.keys()}, "Changes":{k:(wtscores[k], mutscores[k]) for k in wtscores.keys() if k in mutscores and mutscores[k] != wtscores[k]}}
return(dif)
def get_minmax(ORF, genename):
headers = {"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9", "Accept-Encoding": "gzip, deflate", "Accept-Language": "en-US,en;q=0.9", "Cache-Control": "max-age=0", "Connection": "keep-alive", "Content-Length": "2518", "Content-Type": "application/x-www-form-urlencoded", "Host": "www.codons.org", "Origin": "http://www.codons.org", "Referer": "http://www.codons.org/index.html", "Upgrade-Insecure-Requests": "1", "User-Agent": "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36"}
data = {"Gene_Sequence": ">" + genename + "\n" + ORF, "Get_Codon_Usage": "CI-horfeome31.fa", "User_Codon_Usage_Text": "", "RRT_Check_Box": "On"}
r = tools.retry_request(requests.post, positional_arguments=["http://www.codons.org/RCC.cgi"], keyword_arguments={'headers':headers, 'data':data})
link = max(re.findall("\<a href\=\"(.+)\"\>DOWNLOAD RESULTS\<a\>", r.text), key=len)
headers = {"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9", "Accept-Encoding": "gzip, deflate", "Accept-Language": "en-US,en;q=0.9", "Connection": "keep-alive", "Host": "www.codons.org", "If-Modified-Since": "Wed, 08 Apr 2020 18:15:44 GMT", "If-None-Match": "\"3ebb-5a2cb7d12d400\"", "Referer": "http://www.codons.org/RCC.cgi", "Upgrade-Insecure-Requests": "1", "User-Agent": "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36"}
r = tools.retry_request(requests.get, ["http://www.codons.org/" + link], {'headers':headers})
if ">" + genename in r.text:
lines = r.text.split("\n")
lines = [l for l in lines if len(re.findall("\d+\.?\d*", l)) >= 3]
data = {}
for l in lines:
nums = [float(i) for i in l.split(", ")]
data[int(nums[0])+8] = {"%minmax": nums[1], "control %minmax": nums[2]}
else:
raise Exception("Error when parsing output")
newdata = {"%minmax":[], "%minmax control":[]}
for k in range(len(ORF)//3):
if k in data.keys():
newdata["%minmax"].append(data[k]["%minmax"])
newdata["%minmax control"].append(data[k]["control %minmax"])
else:
newdata["%minmax"].append("")
newdata["%minmax control"].append("")
return(newdata)
#calls remuRNA on a sequence
#memory folders are preferred as path, as it writes multiple temporary files
def run_remuRNA(seq, mut, path=ram_disk):
with open(path + "tmp.fa", "w") as outf:
outf.write(">tmp\n")
outf.write(seq + "\n")
outf.write("*" + mut)
output = getoutput_timer(remuRNA_cmd + " " + path + "tmp.fa")
retvals = (output.split("\n")[-1]).split()
if len(retvals) < 6:
raise ValueError("remuRNA encountered errors, or output incorrectly parsed for " + mut)
print(output)
return(float(retvals[1]), float(retvals[2]), float(retvals[4]), float(retvals[5]))
#computes mRNA sequences along sequence, scaling it to in [0,1]
def relative_mRNA_MFE(ORF_aligned, transcript_aligned, l=75, space="-"):
ORF = ORF_aligned.replace(space, "")
transcript = transcript_aligned.replace(space, "")
energies = []
tail = math.floor(l/2.0)
init_time = time.time()
for i in range(1, len(ORF)+1):
j, error = convert_position(ORF_aligned, transcript_aligned, i)
if not error:
subseq = transcript[max(0,j-tail):min(len(transcript),j+tail+1)]
energies.append(run_kinefold(subseq, seed=0))
else:
energies.append("")
tools.update_time(i, len(ORF), init_time, func_name="mRNA MFE")
maxenergy = max(energies, key=abs)
minenergy = min(energies, key=abs)
energies = [(energies[i] - minenergy)/(maxenergy - minenergy) for i in range(len(energies))]
return(energies)
#calls blast, returns sequences found
def run_blast(seq, genename, mode=None, db=None, write=False, forbidden=None, path=ram_disk, space="-", size=2000, quiet=False, args={}):
if mode == None:
mode = tools.infer_alphabet(seq)
elif mode in ["p", "protein", "amino acid", "aa"] and tools.infer_alphabet(seq) == "nt":
try:
seq = translate_seq(seq)
except KeyError as e:
pass
if db == None:
if ["p", "protein", "amino acid", "aa"]:
db = "nr"
else:
db = "nt"
instr = ">" + genename + "\n" + seq
if mode in ["p", "protein", "amino acid", "aa"]:
handle = NCBIWWW.qblast("blastp", db, instr, hitlist_size=size)
else:
handle = NCBIWWW.qblast("blastn", db, instr, hitlist_size=size)
outstr = handle.read()
handle.close()
soup = BeautifulSoup(outstr, "lxml")
hits = soup.find_all("hit")
seqs = {}
for hit in hits:
accession = hit.find("hit_accession").get_text()
name = hit.find("hit_def").get_text()
if forbidden != None and ((isinstance(forbidden, (list, tuple,)) and not any([True for i in range(len(forbidden)) if forbidden[i] in name])) or (isinstance(forbidden, str) and forbidden in name)):
#print(name)
continue
hsps = hit.find_all("hsp")
for hsp in hsps:
start = hsp.find("hsp_query-from").get_text()
end = hsp.find("hsp_query-to").get_text()
subseq = hsp.find("hsp_hseq").get_text()
seqs[accession + ":" + start + "-" + end] = subseq
seqs = tools.agglomerate_seqs(seqs)
seqs[genename] = seq
if not quiet:
print("Number of sequences returned from BLAST for " + genename + " with mode " + str(mode) + ": " + str(len(hits)) + (" "*20))
#write out results
if write:
tools.write_fasta(seqs, os.path.join(path, mode + "_msa.fasta"))
return(seqs)
#calls blast, downloads accession ids, returns sequences
def run_blast_gb(seq, genename, mode=None, write=False, forbidden=None, path=ram_disk, space="-", size=2000, email=Entrez.email, apikey=Entrez.api_key, quiet=False):
Entrez.email = email
Entrez.api_key = apikey
if mode in ["p", "protein", "amino acid", "aa"] and tools.infer_alphabet(seq) == "nt":
try:
seq = translate_seq(seq)
except KeyError as e:
pass
inputs = run_blast(seq, genename, mode=mode, write=write, forbidden=forbidden, path=path, space=space, size=size)
accids = list(inputs.keys())[:-1]
seqs = get_accid_seqs(accids, mode=mode, email=email, apikey=apikey)
seqs[genename] = seq
if not quiet:
print("Number of sequences returned from BLAST with mode " + str(mode) + " for " + genename + ": " + str(len(hits)) + (" "*20))
#write out results
if write:
tools.write_fasta(seqs, path + mode + "_msa.fasta")
return(seqs)
def get_accid_seqs(accids, mode, email=Entrez.email, apikey=Entrez.api_key):
Entrez.email = email
Entrez.api_key = apikey
seqs = {}
while len(seqs) < 0.8*len(accids):
try:
for accid in accids:
if accid not in seqs:
if mode in ["p", "protein", "amino acid", "aa"]:
handle = Entrez.efetch(db='protein',id=accid, rettype='fasta', retmode='text')
else:
handle = Entrez.efetch(db='nucleotide',id=accid, rettype='fasta', retmode='text')
hseq = handle.read().split("\n")
hseq = "".join([hseq[i].strip() for i in range(len(hseq)) if not hseq[i].startswith(">")])
seqs[accid] = hseq
time.sleep(1)
except urllib.error.HTTPError as e:
print(e.code)
print(e.reason)
if e.code == 429:
time.sleep(5)
else:
break
return(seqs)
def align_blast(seqs, genename, space="-", minlength=0.25, minsubset=0.5):
'''
seqs = {k:v.replace(space, "") for k,v in seqs}
seqs = sorted(seqs.items(), key=lambda kv: len(kv[1]))
seqs = {k:v for i, (k,v) in enumerate(seqs) if len(v) >= minlength*len(seqs[genename].replace(space, "")) or i >= minsubset*len(seqs) or k == genename}
'''
seqs = tools.align_sequences(seqs)
seqs = {k:v for k,v in seqs.items() if "query" not in k}
return(seqs)
#aligns sequences, then computes conservation measures
def compute_conservation(seqs, genename, space="-", mode="nt"):
overall_p = {}
for name, seq in seqs.items():
counter = Counter(seq)
for key in counter:
if key != space:
if key in overall_p:
overall_p[key] += counter[key]
else:
overall_p[key] = counter[key]
total = sum(overall_p.values())
overall_p = {alpha:overall_p[alpha]/total for alpha in overall_p}
alphabetsize = len(overall_p.keys())
seqs = align_blast(seqs, genename)
inverted_seqs = {i:"".join([seqs[name][i] for name in seqs]) for i in range(len(seqs[genename]))}
identity = []
entropy = []
variance = []
sum_of_pairs = []
for i in range(len(seqs[genename])):
if seqs[genename][i] != space:
#compute percent identity
pcnt = inverted_seqs[i].count(seqs[genename][i])/len(inverted_seqs[i].replace(space, ""))
identity.append(pcnt)
#compute entropy
counts = Counter(inverted_seqs[i])
del counts[space]
alphabet = set(counter.keys()).difference(set([space]))
p = {alpha:0 for alpha in alphabet}
H = 0
for i, alpha in enumerate(alphabet):
p[alpha] = counts[alpha]/sum(counts.values())
if p[alpha] != 0:
H += p[alpha] * math.log(p[alpha]*alphabetsize)
entropy.append(H)
#compute variance
sigma = 0
for alpha in alphabet:
sigma += (p[alpha]-overall_p[alpha])**2
sigma = math.sqrt(sigma)
variance.append(sigma)
if mode in ["p", "protein", "amino acid", "aa"]:
S = 0
for alpha in alphabet:
for beta in alphabet:
if alpha in blosum and beta in blosum[alpha]:
S += p[alpha]*p[beta]*blosum[alpha][beta]
else:
warnings.warn("\033[93m" + "Amino acids not found in BLOSUM dict: " + alpha + " " + beta + "\033[0m")
sum_of_pairs.append(S)
if mode in ["p", "protein", "amino acid", "aa"]:
return(seqs, identity, entropy, variance, sum_of_pairs)
else:
return(seqs, identity, entropy, variance)
def get_vep(pos, nts, genename, epsilon=0.001):
mutscores = {"Polyphen":[], "SIFT":[], "GnomAD":[], "dbSNP":None, "rsid":None}
mutlist = [genename + ":c." + str(pos) + nts[0] + ">" + nts[1]]
server = "https://rest.ensembl.org"
ext = "/vep/human/hgvs"
headers={ "Content-Type" : "application/json", "Accept" : "application/json"}
r = tools.retry_request(requests.post, positional_arguments=[server+ext], keyword_arguments={'headers':headers, 'data':'{ "hgvs_notations" : ' + str(mutlist).replace("\'", "\"") + ' }'})
if r != None:
decoded = r.json()
if "transcript_consequences" in decoded[0]:
for j in range(len(decoded[0]["transcript_consequences"])):
if "polyphen_score" in decoded[0]["transcript_consequences"][j]:
mutscores["Polyphen"].append(1-decoded[0]["transcript_consequences"][j]["polyphen_score"])
if "sift_score" in decoded[0]["transcript_consequences"][j]:
mutscores["SIFT"].append(decoded[0]["transcript_consequences"][j]["sift_score"])
if "colocated_variants" in decoded[0]:
for j in range(len(decoded[0]["colocated_variants"])):
if "frequencies" in decoded[0]["colocated_variants"][j]:
try:
mutscores["GnomAD"].append(decoded[0]["colocated_variants"][j]["frequencies"][nts[1]]["gnomad"])
except KeyError as e:
pass
if "id" in decoded[0]["colocated_variants"][j] and "rs" in decoded[0]["colocated_variants"][j]["id"]:
try:
mutscores["rsid"] = decoded[0]["colocated_variants"][j]["id"]
except:
pass
try:
rsid = max(re.findall("\d+", mutscores["rsid"]))
r = tools.retry_request(requests.get, positional_arguments=["https://api.ncbi.nlm.nih.gov/variation/v0/refsnp/" + rsid])
mutscores["dbSNP"] = score_variants.parse_dict(r.json(), "clinical_significances")
mutscores["dbSNP"] = [score_variants.sigdict(val) for val in mutscores["dbSNP"]]
except:
mutscores["dbSNP"] = [0.5]
for t in ["Polyphen","SIFT","GnomAD", "dbSNP"]:
mutscores[t] = func_or_default(mutscores[t], func=statistics.mean, default=0.5, verbose=False)
time.sleep(1)
return(mutscores)
return({"Polyphen":"", "SIFT":"", "GnomAD":"", "dbSNP":"", "rsid":""})
def func_or_default(l, func=statistics.mean, default=0.5, verbose=False):
try:
return(func(l))
except Exception as e:
if verbose:
print(e)
return(default)
#looks up a gene on Uniprot, gets the best match (for human genes), and reads through secondary structures, and binding sites, and post-translational modifications
def parse_uniprot(genename, ntseq, accession=None, taxid=9606):
preferences = ["Domain", "Region", "Topological domain", "Transmembrane"]
tmpdomain = {pref:{} for pref in preferences}
data = {"Helix":[], "Beta strand":[], "Turn":[], "Binding site":[], "Metal binding":[], "Active site":[], "Glycosylation (N-linked)":[], "Glycosylation (O-linked)":[], "Disulfide bond":[], "Phosphorylation site":[], "Cleavage site":[], "Other modification":[], "Domain":{}}
if accession == None or len(accession) < 1:
response = tools.retry_request(requests.get, ["https://www.uniprot.org/uniprot/?query=" + genename + "+AND+organism:" + str(taxid) + "&columns=id,entry%20name,protein%20names,genes,organism,length&format=tab"])
query = response.text
accession = ""
for line in query.split("\n"):
if len(line.split("\t")) > 3 and genename in line.split("\t")[3].split():
accession = line.split("\t")[0].strip()
break
if accession != "" and accession != None:
response = tools.retry_request(requests.get, ["https://www.uniprot.org/uniprot/" + accession + ".fasta"])
uniprotseq = "".join(response.text.split("\n")[1:])
aaseq = translate_seq(ntseq)
aligned_seqs = tools.align_sequences({"Uniprot":uniprotseq, "ORF":aaseq})
response = tools.retry_request(requests.get, ["https://www.uniprot.org/uniprot/" + accession + ".gff"])
table = response.text
for line in table.split("\n"):
pieces = line.split("\t")
if len(pieces) >= 10:
feat = pieces[2].strip()
pos1, error1 = convert_position(aligned_seqs["Uniprot"], aligned_seqs["ORF"], pieces[3])
pos2, error2 = convert_position(aligned_seqs["Uniprot"], aligned_seqs["ORF"], pieces[4])
if not error1 and not error2:
feat_lower = feat.lower()
additional_lower = pieces[8].lower()
r = [pos1, pos2]
if "glycosylation" in feat_lower:
if "o-linked" in additional_lower:
data["Glycosylation (O-linked)"].append(r)
elif "n-linked" in additional_lower:
data["Glycosylation (N-linked)"].append(r)
elif "modified residue" in feat_lower:
if "phospho" in additional_lower:
data["Phosphorylation site"].append(r)
else:
data["Other modification"].append(r)
elif "disulfide bond" in feat_lower:
data["Disulfide bond"].append(r)
elif "active site" in feat_lower:
data["Active site"].append(r)
elif "site" in feat_lower and "cleavage" in additional_lower:
data["Cleavage site"].append(r)
if "domain" in feat_lower or "region" in feat_lower:
try:
name = pieces[8].split("=")[1].split(";")[0]
for (feat2, oldname, r2) in sorted([(feat2, k, v) for feat2 in tmpdomain for k,v in tmpdomain[feat2].items()], key=lambda kv: kv[2][0]): #check if duplicate names
if oldname == name:
name = name + "_2"
elif name in oldname and re.match(".+\_\d+", oldname):
num = max(re.findall(".+\_(\d+)", oldname), key=len)
name = name + "_" + str(int(num)+1)
if feat in tmpdomain:
tmpdomain[feat][name] = r
else:
tmpdomain[feat] = {name:r}
except IndexError as e:
print(e)
elif feat in data.keys():
data[feat].append(r)
for feat in sorted(tmpdomain.keys(), key=lambda kv: preferences.index(kv) if kv in preferences else np.inf):
for name1, r1 in sorted(tmpdomain[feat].items(), key=lambda kv: kv[1][0]):
overlap = False
for name2, r2 in sorted(data["Domain"].items(), key=lambda kv: kv[1][0]):
if (r1[0] < r2[0] and r1[1] > r2[0]) or (r1[0] >= r2[0] and r1[1] <= r2[1]) or (r1[0] < r2[1] and r1[1] > r2[1]):
overlap = True
if not overlap:
data["Domain"][name1] = r1
else:
print("No matches found.")
data["Accession"] = accession
return(data)
def query_pdb(query, quiet=False):
url = 'https://search.rcsb.org/rcsbsearch/v1/query'
req = tools.retry_func(requests.post, [url], {'data':json.dumps(query)})
d = json.loads(req.text)["result_set"]
data = {}
for result in d:
if "identifier" in result and len(result["identifier"].split(".")) > 1:
pdb = result["identifier"].split(".")[0]
chain = result["identifier"].split(".")[1]
if pdb not in data.keys():
data[pdb] = {chain:float(result["score"])}
else:
data[pdb][chain] = float(result["score"])
return(data)
#search PDBs based on a Uniprot accession, and return the best match based on sequence length, additional chains (proteins), and number of ligands
def parse_pdb(acc, genename, ORF="", quiet=False):
aaseq = translate_seq(ORF)
options = ["Uniprot", "Genename", "Sequence"]
pdbs = {}
for option in options:
try:
if option == "Uniprot":
jsonval = {"query": {"type": "terminal","service": "text","parameters": {"attribute": "rcsb_polymer_entity_container_identifiers.reference_sequence_identifiers.database_accession","operator": "exact_match","value": acc}},"request_options": {"return_all_hits": True, "sort": [{"sort_by": "rcsb_polymer_entity_feature_summary.maximum_length","direction": "desc"}]},"return_type": "polymer_instance"}
tmppdbs = query_pdb(jsonval, quiet=quiet)
elif option == "Genename":
jsonval = {"query": {"type": "terminal","service": "text","parameters": {"attribute": "rcsb_entity_source_organism.rcsb_gene_name.value","operator": "exact_match","value": genename}},"request_options": {"return_all_hits": True, "sort": [{"sort_by": "rcsb_polymer_entity_feature_summary.maximum_length","direction": "desc"}]},"return_type": "polymer_instance"}
tmppdbs = query_pdb(jsonval, quiet=quiet)
elif option == "Sequence" and ORF != None and len(ORF) > 0:
jsonval = {"query": {"type": "terminal", "service": "sequence","parameters": {"evalue_cutoff": 0.5, "identity_cutoff": 0.9,"target": "pdb_protein_sequence","value": aaseq}},"request_options": {"return_all_hits": True, "scoring_strategy": "sequence"},"return_type": "polymer_instance"}
aaseq = translate_seq(ORF)
tmppdbs = query_pdb(jsonval, quiet=quiet)
for pdb in tmppdbs:
if pdb not in pdbs:
pdbs[pdb] = tmppdbs[pdb]
except Exception as e:
pass
pdbs = [(k, sorted(pdbs[k].keys(), key=lambda kv: pdbs[k][kv])) for k in pdbs]
if not quiet:
if len(pdbs) > 0:
print("PDB selected for " + genename + ": " + pdbs[0][0] + ", with chain(s) " + ", ".join(pdbs[0][1]))
else:
print("No PDBs found for " + acc + " or " + genename)
return(pdbs)
def parse_dali(html, genename, path=ram_disk, write=True):
if not html.endswith(".html") or html.endswith("/"):
html = html + "s001A-25.html"
matches = tools.retry_request(requests.get, [html])
if matches == None or matches.status_code != 200:
return(None)
pdbs = re.findall("Sbjct\=\w{5}\sZ\-score\=\d+\.?\d*", matches.text)
pdbs = {max(re.findall("Sbjct\=(\w{5})", i), key=len):float(max(re.findall("Z\-score\=(\d+\.?\d*)", i), key=len)) for i in pdbs}
data = {}
for k in pdbs:
try:
data[k] = max(re.findall(k[:-1].lower() + "\-" + k[-1].upper() + "\s+(\d+\.?\d*\s+\d+\.?\d*\s+\d+\s+\d+\s+\d+)", matches.text), key=len)
except ValueError as e:
pass
newdata = {}
for k,v in data.items():
vstr = v.split()
if len(vstr) >= 5:
newdata[k[:-1]] = {"chain":k[-1], "Z-score":float(vstr[0]), "rmsd":float(vstr[1]), "lali":int(vstr[2]), "nres":int(vstr[3]), "%id":int(vstr[4])}
if write:
df = pd.DataFrame.from_dict(newdata, dtype=str)
df.T.to_csv(path + genename + "_dali.tsv", sep="\t")
return(newdata)
def query_dali(pdb, genename, match=25, email=Entrez.email, path=ram_disk, space="-", wait_time=60, give_up=12):
pdbstr = pdb[0].lower() + pdb[1][0].upper()
headers = {"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9", "Accept-Encoding": "gzip, deflate", "Accept-Language": "en-US,en;q=0.9", "Cache-Control": "max-age=0", "Connection": "keep-alive", "Content-Length": "703", "Content-Type": "multipart/form-data; boundary=----WebKitFormBoundaryOVadri1CnKBpmrIC", "Host": "ekhidna2.biocenter.helsinki.fi", "Origin": "http://ekhidna2.biocenter.helsinki.fi", "Referer": "http://ekhidna2.biocenter.helsinki.fi/dali/", "Upgrade-Insecure-Requests": "1", "User-Agent": "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.163 Safari/537.36"}
r = tools.retry_request(requests.post, ["http://ekhidna2.biocenter.helsinki.fi/cgi-bin/sans/dump.cgi"], {'data':{'cd1':pdbstr, 'file1':'(binary)', 'title':genename, 'address':email, 'method':'search', 'submit':'Submit'}})
#wait until success or time out (defaults to 12 hours)
def wait_for_dali(pdbstr, genename, match=25, path=ram_disk, space="-", wait_time=60, give_up=12, quiet=True):
retry_counter = 1
success = False
while retry_counter < give_up*60*(60/wait_time) and not success:
results = tools.retry_request(requests.get, ["http://ekhidna2.biocenter.helsinki.fi/barcosel/tmp//" + pdbstr + "/"])
if results != None and "FAILED" in results.text.upper(): #failure
retry_counter += give_up*60*(60/wait_time)
warnings.warn("\033[93m" + "Dali failed on " + genename + "\033[0m")
return(False)
if match in [25, 50, 90]:
html = "http://ekhidna2.biocenter.helsinki.fi/barcosel/tmp//" + pdbstr + "/" + pdbstr + "-" + str(match) + ".html"
else:
html = "http://ekhidna2.biocenter.helsinki.fi/barcosel/tmp//" + pdbstr + "/" + pdbstr + ".html"
newdata = parse_dali(html, genename, write=True)
if newdata != None: #success!
success = True
else:
retry_counter += 1
time.sleep(wait_time)
elapsed = retry_counter*wait_time
if not quiet:
print("Waiting on Dali for " + str(elapsed/60) + " minutes, " + str(elapsed % 60) + " seconds" + " " * 20, end="\r")
return(success)
#start the process and return (we can do other stuff while it waits)
p = Process(target=wait_for_dali, args=(pdbstr, genename, match, path, space, wait_time, give_up, True))
p.start()
return(p)
#creates a set from a list while maintaining order
def sorted_set(l):
new_l = []
for li in l:
if li not in new_l:
new_l.append(li)
return(new_l)
#aligns data (keys are chains, next level of keys are positions, one of the included subkeys is aa), to ORF and generates new data
#generates data for each chain based on best alignment with sequence (we can't assume anything about chain ordering)
def get_aligned_data(data, ORF):
wtseq = translate_seq(ORF)
newdata = {}
for chain in data:
pdbseq = ""
for i in range(min(data[chain].keys()), max(data[chain].keys())):
if i in data[chain].keys():
pdbseq += data[chain][i]["aa"]
else: #between indices, mark with ambiguity
pdbseq += "X"
aligned_seqs = tools.align_sequences({"wtseq":wtseq, "pdbseq":pdbseq})
for i in range(len(wtseq)):
j, error = convert_position(aligned_seqs["wtseq"], aligned_seqs["pdbseq"], i) #position i in wtseq corresponds to j in pdbseq
if j + min(data[chain].keys()) in data[chain] and wtseq[i] == data[chain][j + min(data[chain].keys())]["aa"] and not error: #position j in pdbseq corresponds to j+min(data[chain].keys() in the original data numbering
newdata[i] = data[chain][j + min(data[chain].keys())]
for i in range(len(ORF)//3): #fill out newdata with blanks
if i not in newdata:
newdata[i] = {key:"" for key in newdata[min(newdata.keys())]}
return(newdata)
#parses ConsurfDB, given a pdb and associated chains
def get_consurf(pdb, chains, ORF):
data = {}
prevpos = -1
for chain in chains:
data[chain] = {}
response = requests.get("https://consurfdb.tau.ac.il/DB/" + pdb.upper() + chain.upper() + "/consurf_summary.txt")
for i, line in enumerate(response.text.split("\n")):
pieces = line.split("\t")
if i >= 15 and len(pieces) >= 9:
try:
aa = pieces[1].strip()
pos = int(max(re.findall(r'\d+', pieces[2].strip()), key=len)) #read amino acid position
data[chain][pos] = {"aa": aa, "Conservation score":float(pieces[3].strip())}
prevpos = pos
except ValueError as e: #aa position was not parsed from line
if prevpos >= 0: #previous line was associated with an aa position
pos = prevpos + 1
data[chain][pos] = {"aa": aa, "Conservation score":float(pieces[3].strip())}
prevpos = pos
newdata = get_aligned_data(data, ORF)
scores = [newdata[i]["Conservation score"] for i in range(len(ORF)//3)]
return(scores)
#queries Consurf based on the AA sequence, returns a process which waits for the data and eventually writes to file when Consurf is finished
def get_consurf_seq(ORF, genename, path=ram_disk, space="-", wait_time=60, give_up=12, quiet=True):
aaseq = max(re.findall("[ACDEFGHIKLMNPQRSTVWY]+", translate_seq(ORF)), key=len) #maximal length protein sequence with only aa symbols
response = tools.retry_request(requests.post, ["http://consurf.tau.ac.il/cgi-bin/consurf.cgi"], {"data":{"DNA_AA": "AA", "pdb_ID": "", "pdb_FILE": "", "PDB_chain": "", "PDB_yes_no": "yes", "modeller_key": "", "MSA_yes_no": "yes", "msa_FILE_ajax": "(binary)", "MAX_FILE_SIZE": "300000", "msa_SEQNAME_ajax": "", "msa_FILE": "(binary)", "msa_SEQNAME": "", "FASTA_text": genename + "\n" + aaseq, "Homolog_search_algorithm": "HMMER", "ITERATIONS": "1", "E_VALUE": "0.01", "proteins_DB": "UNIREF90", "user_select_seq": "no", "MAX_NUM_HOMOL": "250", "best_uniform_sequences": "uniform", "MAX_REDUNDANCY": 95, "MIN_IDENTITY": 35, "MSAprogram": "MAFFT", "tree_FILE": "(binary)", "ALGORITHM": "Bayes", "SUB_MATRIX": "BEST", "JOB_TITLE": genename, "user_email": "", "submitForm": "Submit"}})
if response.status_code == 200: #response went through
jobnum = max(re.findall("ConSurf is now processing your job number (\d+)", response.text), key=len)
else: #failed for some reason
warnings.warn("\033[93m" + "Consurf failed on " + genename + "\033[0m")
return(False)
#wait until we get a response
print("Running Consurf on " + genename + ". Job num is " + jobnum)
#wait until success or time out (defaults to 12 hours)
def wait_for_consurf(jobnum, genename, path=ram_disk, space="-", wait_time=60, give_up=12, quiet=True):
retry_counter = 1
success = False
while retry_counter < give_up*60*(60/wait_time) and not success:
results = tools.retry_request(requests.get, ["http://consurf.tau.ac.il/results/" + jobnum + "/output.php"])
if results != None and "FAILED" in results.text: #failure
retry_counter += give_up*60*(60/wait_time)
warnings.warn("\033[93m" + "Consurf failed on " + genename + "\033[0m")
return(False)
conservation_page = requests.get("http://consurf.tau.ac.il/results/" + jobnum + "/consurf.grades")
aln_page = requests.get("http://consurf.tau.ac.il/results/" + jobnum + "/query_msa.aln")
if conservation_page.status_code == 200 and aln_page.status_code == 200: #success!
#get the MSA
alnment = {}
seqs = aln_page.text.split(">")
for entry in seqs:
try:
seq = max(re.findall("[ACDEFGHIKLMNPQRSTVWY\\" + space + "\s]+", entry), key=len)
name = entry.split(seq)[0]
seq = re.sub("\s+", "", seq)
alnment[name] = seq
except ValueError as e:
pass
#read the conservation scores
data = parse_consurf(conservation_page.text)
success = True
else:
retry_counter += 1
time.sleep(wait_time)
elapsed = retry_counter*wait_time
if not quiet:
print("Waiting on Consurf for " + str(elapsed/60) + " minutes, " + str(elapsed % 60) + " seconds" + " " * 20, end="\r")
if success: #write results to temp file
df = pd.DataFrame.from_dict(data, dtype=str)
df.T.to_csv(path + genename + "_consurf.tsv", sep="\t")
tools.write_fasta(alnment, path + genename + "_consurf.fasta")
return(True)
else:
return(False)
#start the process and return (we can do other stuff while it waits)
p = Process(target=wait_for_consurf, args=(jobnum, genename, path, space, wait_time, give_up, True))
p.start()
return(p)
def parse_consurf(text):
data = {}
for i, line in enumerate(text.split("\n")):
pieces = re.split(" {2,}|\t+", line.strip())
if i >= 16 and len(pieces) >= 11:
try:
score = float(pieces[3])
b_e = ""
if pieces[10].strip() == "b":
b_e = 0
elif pieces[10].strip() == "e":
b_e = 1
data[int(pieces[0])] = {"char":pieces[2], "score":score, "buried/exposed":b_e}
except ValueError as e:
pass
return(data)
#queries Consurf based on the AA sequence, returns a process which waits for the data and eventually writes to file when Consurf is finished
def get_rnafold(seq, genename, path=ram_disk, space="-", wait_time=60, give_up=12, quiet=True):
response = tools.retry_request(requests.post, ["http://rna.tbi.univie.ac.at//cgi-bin/RNAWebSuite/RNAfold.cgi"], {"data":{"PAGE":2, "SCREEN":seq, "CONSTRAINT":"", "FILE": "(binary)", "method": "mfe", "noLP": "on", "dangling": "d2", "param": "rna2004", "SHAPEDATA": "", "SHAPEFILE": "(binary)", "shapemethod": "deigan", "shape_slope": "1.9", "shape_intercept": "-0.7", "shape_beta": "0.8", "deigan_conversion": "linearlog", "shape_conv_cutoff": "0.25", "shape_conv_linear_s": "0.68", "shape_conv_linear_i": "0.2", "shape_conv_linearlog_s": "1.6", "shape_conv_linearlog_i": "-2.29", "Temp": "37", "svg": "on", "reliability": "on", "mountain": "on", "EMAIL": "", "proceed": ""}})
if response.status_code == 200: #response went through
jobnum = max(re.findall("ConSurf is now processing your job number (\d+)", response.text), key=len)
else: #failed for some reason
warnings.warn("\033[93m" + "Consurf failed on " + genename + "\033[0m")
return(False)
#wait until we get a response
print("Running Consurf on " + genename + ". Job num is " + jobnum)
#wait until success or time out (defaults to 12 hours)
def wait_for_consurf(jobnum, genename, path=ram_disk, space="-", wait_time=60, give_up=12, quiet=True):
retry_counter = 1
success = False
while retry_counter < give_up*60*(60/wait_time) and not success:
results = tools.retry_request(requests.get, ["http://consurf.tau.ac.il/results/" + jobnum + "/output.php"])
if results != None and "FAILED" in results.text: #failure
retry_counter += give_up*60*(60/wait_time)
warnings.warn("\033[93m" + "Consurf failed on " + genename + "\033[0m")
return(False)
conservation_page = requests.get("http://consurf.tau.ac.il/results/" + jobnum + "/consurf.grades")
aln_page = requests.get("http://consurf.tau.ac.il/results/" + jobnum + "/query_msa.aln")
if conservation_page.status_code == 200 and aln_page.status_code == 200: #success!
#get the MSA
alnment = {}
seqs = aln_page.text.split(">")
for entry in seqs:
try:
seq = max(re.findall("[ACDEFGHIKLMNPQRSTVWY\\" + space + "\s]+", entry), key=len)
name = entry.split(seq)[0]
seq = re.sub("\s+", "", seq)
alnment[name] = seq
except ValueError as e:
pass
#read the conservation scores
data = parse_consurf(conservation_page.text)
success = True
else:
retry_counter += 1
time.sleep(wait_time)
elapsed = retry_counter*wait_time
if not quiet:
print("Waiting on Consurf for " + str(elapsed/60) + " minutes, " + str(elapsed % 60) + " seconds" + " " * 20, end="\r")
if success: #write results to temp file
df = pd.DataFrame.from_dict(data, dtype=str)
df.T.to_csv(path + genename + "_consurf.tsv", sep="\t")
tools.write_fasta(alnment, path + genename + "_consurf.fasta")
return(True)
else:
return(False)
#start the process and return (we can do other stuff while it waits)
p = Process(target=wait_for_consurf, args=(jobnum, genename, path, space, wait_time, give_up, True))
p.start()
return(p)
#aligns the NT MSA file based on codons (codons align with ORF sequence), then computes standard conservation measures based on alignment
def codon_conservation(filename, genename, alphabet=["T","C", "A", "G", "t", "c", "a", "g"], path=ram_disk, space="-"):
output = path + os.path.splitext(filename)[0] + "_aligned.fasta"
align_codons.pre_align_codons(path+filename, genename, output = output, space=space)