-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfragsys.py
1740 lines (1549 loc) · 73.3 KB
/
fragsys.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
### IMPORTS ###
import os
import re
import Bio
import math
import scipy
import shutil
import Bio.SeqIO
import importlib
import prointvar
import statistics
import subprocess
import Bio.AlignIO
import numpy as np
import configparser
import pandas as pd
import seaborn as sns
from Bio.Seq import Seq
from Bio import pairwise2
from scipy import cluster
import varalign.alignments
import scipy.stats as stats
import varalign.align_variants
import matplotlib.pyplot as plt
from prointvar.pdbx import PDBXreader
from prointvar.pdbx import PDBXwriter
import matplotlib.patches as mpatches
from prointvar.sifts import SIFTSreader
from prointvar.config import config as cfg
from prointvar.dssp import DSSPrunner, DSSPreader
from scipy.spatial.distance import squareform, pdist
from prointvar.fetchers import download_sifts_from_ebi
from prointvar.fetchers import download_structure_from_pdbe
### DICTIONARIES AND LISTS ###
arpeggio_suffixes = [
"atomtypes", "bs_contacts", "contacts", "specific.sift",
"sift","specific.siftmatch", "siftmatch", "specific.polarmatch",
"polarmatch", "ri", "rings", "ari", "amri", "amam", "residue_sifts"
]
pdb_clean_suffixes = ["break_residues", "breaks"]
simple_ions = [
"ZN", "MN", "CL", "MG", "CD", "NI", "NA", "IOD", "CA", "BR", "XE"
]
acidic_ions = [
"PO4", "ACT", "SO4", "MLI", "CIT", "ACY", "VO4"
]
non_relevant_ligs_manual = [
"DMS", "EDO", "HOH", "TRS", "GOL", "OGA", "FMN", "PG4", "PGR",
"MPD", "TPP", "MES", "PLP", "HYP", "CSO", "UNX", "EPE", "PEG",
"PGE", "DOD", "SUI"
]
non_relevant = non_relevant_ligs_manual + simple_ions + acidic_ions
pdb_resnames = [
"ALA", "CYS", "ASP", "GLU", "PHE", "GLY", "HIS", "ILE", "LYS", "LEU", ### ONE OF THESE MIGHT BE ENOUGH ###
"MET", "ASN", "PRO", "GLN", "ARG", "SER", "THR", "VAL", "TRP", "TYR"
]
aas = [
'ALA', 'ARG', 'ASN', 'ASP', 'CYS', 'GLN', 'GLU', 'GLY',
'HIS', 'ILE', 'LEU', 'LYS', 'MET', 'PHE', 'PRO', 'SER', ### ONE OF THESE MIGHT BE ENOUGH ###
'THR', 'TRP', 'TYR', 'VAL', 'GLX', 'GLI', 'NLE', 'CYC'
]
bbone = ["N", "CA", "C", "O"]
aa_code = {
"ALA" : 'A', "CYS" : 'C', "ASP" : 'D', "GLU" : 'E',
"PHE" : 'F', "GLY" : 'G', "HIS" : 'H', "ILE" : 'I',
"LYS" : 'K', "LEU" : 'L', "MET" : 'M', "ASN" : 'N',
"PRO" : 'P', "GLN" : 'Q', "ARG" : 'R', "SER" : 'S',
"THR" : 'T', "VAL" : 'V', "TRP" : 'W', "TYR" : 'Y',
"PYL" : 'O', "SEC" : 'U', "HYP" : 'P', "CSO" : 'C', # WEIRD ONES
"SUI" : 'D',
}
### CONFIG FILE READING AND VARIABLE SAVING ###
config = configparser.ConfigParser()
config.read("fragsys_config.txt")
dssp_bin = config["binaries"].get("dssp_bin")
oc_bin = config["binaries"].get("oc_bin")
stamp_bin = config["binaries"].get("stamp_bin")
transform_bin = config["binaries"].get("transform_bin")
clean_pdb_python_bin = config["binaries"].get("clean_pdb_python_bin")
clean_pdb_bin = config["binaries"].get("clean_pdb_bin")
arpeggio_python_bin = config["binaries"].get("arpeggio_python_bin")
arpeggio_bin = config["binaries"].get("arpeggio_bin")
gnomad_vcf = config["dbs"].get("gnomad_vcf")
swissprot = config["dbs"].get("swissprot")
stampdir = config["other"].get("stampdir")
oc_dist = float(config["clustering"].get("oc_dist"))
oc_metric = config["clustering"].get("oc_metric")
oc_method = config["clustering"].get("oc_method")
mes_sig_t = float(config["other"].get("mes_sig_t"))
### PRE-PROCESSING DATA CODE ###
def dump_pickle(data, f_out):
"""
dumps pickle
"""
with open(f_out, "wb") as f:
pickle.dump(data, f)
def load_pickle(f_in):
"""
loads pickle
"""
with open(f_in, "rb") as f:
data = pickle.load(f)
return data
def setup_fragsys_start(main_dir, prot, df):
"""
given a main directory, protein accession and structures dataframe,
downloads all biological assemblies of such structures if they have
not already been downloaded and classified in subdirectories
"""
wd = os.path.join(main_dir, prot)
unsupp_cifs_dir = os.path.join(wd, "unsupp_cifs")
if not os.path.isdir(wd):
os.mkdir(wd)
else:
pass
if not os.path.isdir(unsupp_cifs_dir):
os.mkdir(unsupp_cifs_dir)
else:
pass
prot_df = df.query('entry_uniprot_accession == @prot').copy()
prot_strucs = prot_df.pdb_id.unique().tolist()
struc_files = []
unsupp_cifs_subirs = os.listdir(unsupp_cifs_dir)
if len(unsupp_cifs_subirs) == 0: #it's empty, need to download
pass
else: #not empty
for element in unsupp_cifs_subirs:
element_path = os.path.join(unsupp_cifs_dir, element)
if os.path.isfile(element_path):
pass
elif os.path.isdir(element_path):
element_files = os.listdir(element_path)
for element_file in element_files:
prot_strucs.remove(element_file[:4])
unsupp_file_path = os.path.join(unsupp_cifs_dir, element_file)
if os.path.isfile(unsupp_file_path):
os.remove(unsupp_file_path)
for struc in prot_strucs: #only those that are downloaded or have yet to be (not those classified already)
input_struc = os.path.join(cfg.db_root, cfg.db_pdbx, struc + "_bio.cif")
input_struc_moved = os.path.join(unsupp_cifs_dir, os.path.basename(input_struc))
if os.path.isfile(input_struc) or os.path.isfile(input_struc_moved):
pass
else:
try:
download_structure_from_pdbe(struc, bio = True) # downloads only files missing
except:
print("Error with {}".format(struc))
struc_files.append(input_struc)
for file in struc_files:
if os.path.isfile(file):
shutil.move(file, os.path.join(unsupp_cifs_dir, os.path.basename(file))) #moves downloaded cif files
pdbx_files = os.listdir(os.path.join(cfg.db_root, cfg.db_pdbx))
if len(pdbx_files) != 0:
for pdbx in pdbx_files:
os.remove(os.path.join(cfg.db_root, cfg.db_pdbx, pdbx)) # removes any leftover files?
def setup_dirs(dirs):
"""
sets up the directories for the program to tun
"""
for dirr in dirs:
if os.path.isdir(dirr):
continue
else:
os.mkdir(dirr)
def classify_pdbs(prot, main_dir, h = 0.2, show = False):
"""
Classifies a group of cif files into different
folders according to their amino acid sequence
"""
z, un_seqs, seqs_df = cluster_protein_sequences(prot, main_dir, h, show)
seqs_df = assign_seqs_clusters(z, un_seqs, seqs_df)
create_cluster_dirs(main_dir, prot, seqs_df)
def cluster_protein_sequences(prot, main_dir, h = 0.2, show = False):
"""
Extracts sequences from PDB structures of a certain UniProt accession,
calculates distances between them, genereates matrix, dendrogram and
clustermap.
"""
wd = os.path.join(main_dir, prot)
unsupp_cifs_dir = os.path.join(wd, "unsupp_cifs")
cif_paths = []
for file in os.listdir(unsupp_cifs_dir):
if os.path.isfile(os.path.join(unsupp_cifs_dir, file)): #cifs without classifying
cif_paths.append(os.path.join(unsupp_cifs_dir, file))
elif os.path.isdir(os.path.join(unsupp_cifs_dir, file)): #checking for directories, might have classified PDBs already
for file2 in os.listdir(os.path.join(unsupp_cifs_dir, file)):
cif_paths.append(os.path.join(unsupp_cifs_dir, file, file2))
else:
pass
seqs_df_path = os.path.join(wd, "{}_seqs_df.csv".format(prot))
if os.path.isfile(seqs_df_path):
seqs_df = pd.read_csv(seqs_df_path)
else:
seqs = {}
for cif_path in cif_paths:
seq = get_seq_from_pdb(cif_path, pdb_fmt = "mmcif")
cif_id = cif_path.split("/")[-1][:4]
seqs[cif_id] = seq
seqs_df = pd.DataFrame(list(seqs.items()), index = None, columns = ["pdb_id", "seq"])
seqs_df.to_csv(seqs_df_path, index = False)
un_seqs = seqs_df.drop_duplicates("seq").seq.tolist()
msa_df_out = os.path.join(wd, "{}_msa_dists.csv".format(prot))
if os.path.isfile(msa_df_out):
msa_df_norm = pd.read_csv(msa_df_out)
else:
msa_mat_norm = get_msa_matrix(un_seqs)
msa_df_norm = pd.DataFrame(msa_mat_norm)
msa_df_norm.to_csv(msa_df_out, index = False)
if len(un_seqs) == 1:
return np.array([]), un_seqs, seqs_df
else:
pass
condensed_matrix = scipy.spatial.distance.squareform(msa_df_norm)
z = scipy.cluster.hierarchy.linkage(condensed_matrix, method = "complete")
plot_clustermap(msa_df_norm, z, prot, wd, show)
plot_dendrogram(z, msa_df_norm, wd, prot, h, show)
return z, un_seqs, seqs_df
def get_msa_matrix(seqs_list, norm = True):
"""
Given a list of sequences, calculates all pairwise global sequence alignments
and from the scores, generates a distance from 0-1.
"""
scores = {i: {} for i in range(len(seqs_list))}
for i in range(len(seqs_list)):
scores[i][i] = pairwise2.align.globalxx(seqs_list[i], seqs_list[i])[0][2]
for j in range(i+1, len(seqs_list)):
scores[i][j] = pairwise2.align.globalxx(seqs_list[i], seqs_list[j])[0][2]
scores[j][i] = scores[i][j]
if norm == True:
scores_norm = {i: {} for i in range(len(seqs_list))}
for i in range(len(seqs_list)):
scores_norm[i][i] = abs(scores[i][i] - scores[i][i])/scores[i][i]
for j in range(i+1, len(seqs_list)):
scores_norm[i][j] = abs(scores[i][j] - scores[i][i])/scores[i][i]
scores_norm[j][i] = abs(scores[j][i] - scores[i][i])/scores[i][i]
return scores_norm
else:
return scores
def plot_clustermap(msa_df_norm, linkage, prot, wd, show = False):
"""
Plots a clustermap given a matrix of distances between sequences
"""
plt.rcParams['figure.dpi'] = 300
g = sns.clustermap(
msa_df_norm, row_linkage=linkage, col_linkage=linkage,
cmap = "viridis_r", linewidths = 1, linecolor = "k",
vmin = 0, vmax = 1
)
fig_out = os.path.join(wd, "{}_unique_seqs_clustermap.png".format(prot))
if os.path.isfile(fig_out):
pass
else:
plt.savefig(fig_out)
if show == True:
plt.show()
plt.close()
def plot_dendrogram(z, msa_df_norm, wd, prot, h, show = False):
"""
Plots a dendrogram of the complete linkage hierarchical clustering
calculated from the matrix of distances between sequences
"""
plt.figure(figsize = (7.5, 4), dpi = 300)
d = scipy.cluster.hierarchy.dendrogram(
z, labels = msa_df_norm.index, color_threshold = h
)
plt.title("Complete linkage clustering of unique sequences", fontsize = 15)
plt.xlabel("Unique sequence ID", fontsize = 10)
plt.ylabel("Alignment score distance", fontsize = 10)
plt.axhline(y = 0.2, linestyle = "--", color = "k", linewidth = 1)
fig_out = os.path.join(wd, "{}_unique_seqs_dendrogram.png".format(prot))
if os.path.isfile(fig_out):
pass
else:
plt.savefig(fig_out)
if show == True:
plt.show()
plt.close()
def assign_seqs_clusters(z, unique_seqs, seqs_df, h = 0.2):
"""
Given a dendrogram and group of sequences,
assigns a cluster ID to those sequences
"""
if z.size == 0:
print("This condition is being met") # only one sequence
seqs_df["seq_id"] = [0 for i in range(len(seqs_df))]
seqs_df["cluster_id"] = [0 for i in range(len(seqs_df))]
else:
cutree = scipy.cluster.hierarchy.cut_tree(z, height = h) # clusters coordinates
cluster_ids = [int(cut) for cut in cutree]
un_seqs_dict = {el: i for i, el in enumerate(unique_seqs)}
cluster_id_dict = {i: el for i, el in enumerate(cluster_ids)}
seqs_df["seq_id"] = seqs_df.seq.map(un_seqs_dict)
seqs_df["cluster_id"] = seqs_df.seq_id.map(cluster_id_dict)
return seqs_df
def create_cluster_dirs(main_dir, prot, seqs_df):
"""
Once sequences have been assigned a cluster ID, the .cif files
are divided into subdirectories
"""
unsupp_cifs_dir = os.path.join(main_dir, prot, "unsupp_cifs")
cluster_ids = sorted([str(cluster_id) for cluster_id in seqs_df.cluster_id.unique().tolist()])
unsupp_files = sorted(os.listdir(unsupp_cifs_dir))
if unsupp_files == cluster_ids:
return
for cluster_id in cluster_ids:
cluster_unsupp_dir = os.path.join(unsupp_cifs_dir, str(cluster_id))
if not os.path.isdir(cluster_unsupp_dir):
os.mkdir(cluster_unsupp_dir)
cluster_pdbs = seqs_df[seqs_df.cluster_id == int(cluster_id)].pdb_id.tolist()
cluster_pdb_paths = ["{}_bio.cif".format(cluster_pdb) for cluster_pdb in cluster_pdbs]
for cluster_pdb_path in cluster_pdb_paths:
if os.path.isfile(os.path.join(unsupp_cifs_dir, cluster_pdb_path)):
shutil.move(
os.path.join(unsupp_cifs_dir, cluster_pdb_path),
os.path.join(cluster_unsupp_dir, cluster_pdb_path)
)
def get_swissprot():
"""
Retrieves sequences and their data from Swiss-Prot
:param db: absolute path to a fasta file containing sequences, Swiss-Prot database by default
:type db: str
:returns: dictionary containing the sequence id, description and sequence for all proteins in Swiss-Prot
:rtpe: dict
"""
swissprot_dict = Bio.SeqIO.parse(swissprot, "fasta")
proteins = {}
for protein in swissprot_dict:
acc = protein.id.split("|")[1]
proteins[acc] = {}
proteins[acc]["id"] = protein.id
proteins[acc]["desc"] = protein.description
proteins[acc]["seq"] = protein.seq
return proteins
### STAMP SUPERIMPOSITION CODE ###
def cif2pdb(cif_in, pdb_out):
"""
converts cif to pdb format, needed to run STAMP
"""
cif_df = PDBXreader(inputfile = cif_in).atoms(format_type = "mmcif", excluded=())
w = PDBXwriter(outputfile = pdb_out)
id_equiv_dict = w.run(cif_df, format_type = "pdb", category = 'auth')
return id_equiv_dict
def get_chain_dict(cif_path):
"""
Creates an equivalence dict between asymemtric unit chain IDs and biological assembly chain IDs
"""
cif_df = PDBXreader(inputfile = cif_path).atoms(format_type = "mmcif", excluded=())
orig_chains = cif_df.query('group_PDB == "ATOM"').copy()[['orig_auth_asym_id', 'auth_asym_id']].drop_duplicates().orig_auth_asym_id.tolist()
new_chains = cif_df.query('group_PDB == "ATOM"').copy()[['orig_auth_asym_id', 'auth_asym_id']].drop_duplicates().auth_asym_id.tolist()
chain_dict = {new_chains[i]: orig_chains[i] for i in range(len(orig_chains))}
return chain_dict
def generate_domains(pdbs_dir, domains_out, roi = "ALL"):
"""
Genereates domains file, needed to run STAMP
"""
with open(domains_out, "w+") as fh:
for pdb in os.listdir(pdbs_dir):
fh.write("{} {} {{{}}}\n".format(os.path.join(pdbs_dir, pdb), pdb[:-4], roi))
def stamp(domains, prefix, out):
"""
runs stamp using the domains file as input
"""
if "STAMPDIR" not in os.environ:
os.environ["STAMPDIR"] = stampdir
args = [
stamp_bin, "-l", domains, "-rough", "-n",
str(2), "-prefix", prefix, ">", out
]
exit_code = os.system(" ".join(args))
if exit_code != 0:
print(" ".join(args))
return exit_code
def transform(matrix):
"""
runs transform to obtain set of transformed coordinates
"""
if "STAMPDIR" not in os.environ:
os.environ["STAMPDIR"] = stampdir
#print(stampdir)
args = [transform_bin, "-f", matrix, "-het"]
#print(" ".join(args))
exit_code = os.system(" ".join(args))
if exit_code != 0:
print(" ".join(args))
return exit_code
def move_supp_files(unsupp_pdbs_dir, supp_pdbs_dir):
"""
moves set of supperimposed coordinate files to appropriate directory
"""
struc_files = os.listdir(unsupp_pdbs_dir)
cwd = os.getcwd()
for file in struc_files:
if os.path.isfile(os.path.join(cwd, file)):
shutil.move(
os.path.join(cwd, file),
os.path.join(supp_pdbs_dir, file)
)
def move_stamp_output(wd, prefix, stamp_out_dir):
"""
moves STAMP output files to appropriate directory
"""
cwd = os.getcwd()
stamp_files = sorted([file for file in os.listdir(cwd) if prefix in file]) + ["stamp_rough.trans"]
for file in stamp_files:
filepath = os.path.join(cwd, file)
if os.path.isfile(filepath):
shutil.move(filepath, os.path.join(stamp_out_dir, file))
out_from = os.path.join(wd, prefix + ".out")
out_to = os.path.join(stamp_out_dir, prefix + ".out")
doms_from = os.path.join(wd, prefix + ".domains")
doms_to = os.path.join(stamp_out_dir, prefix + ".domains")
if os.path.isfile(out_from):
shutil.move(out_from, out_to)
if os.path.isfile(doms_from):
shutil.move(doms_from, doms_to)
### DSSP + SIFTS + ARPEGGIO ###
def get_lig_data(supp_pdbs_dir, ligs_df_path):
"""
From a directory containing a set of structurally superimposed pdbs,
writes a csv file indicating the name, chain and residue number of the
ligand(s) of interest in every pdb
"""
ligs_df = pd.DataFrame([])
for struc in os.listdir(supp_pdbs_dir):
struc_path = os.path.join(supp_pdbs_dir, struc)
df = PDBXreader(inputfile = struc_path).atoms(format_type = "pdb", excluded=())
hetatm_df = df.query('group_PDB == "HETATM"').copy()
ligs = hetatm_df.label_comp_id.unique().tolist()
lois = [lig for lig in ligs if lig not in non_relevant]
for loi in lois:
loi_df = hetatm_df.query('label_comp_id == @loi').copy()
lois_df_un = loi_df.copy().drop_duplicates(["label_comp_id", "label_asym_id"])[["label_comp_id", "label_asym_id", "auth_seq_id"]]
lois_df_un["struc_name"] = struc
ligs_df = ligs_df.append(lois_df_un)
ligs_df = ligs_df[["struc_name","label_comp_id", "label_asym_id", "auth_seq_id"]]
ligs_df.to_csv(ligs_df_path, index = False)
return ligs_df
def run_dssp(struc, supp_pdbs_dir, dssp_dir):
"""
runs DSSP, saves and return resulting output dataframe
"""
dssp_csv = os.path.join(dssp_dir, "dssp_" + struc.replace("pdb", "csv")) # output csv filepath
dssp_out = os.path.join(dssp_dir, struc.replace("pdb", "dssp"))
struc_in = os.path.join(supp_pdbs_dir, struc)
DSSPrunner(inputfile = struc_in, outputfile = dssp_out).write() # runs DSSP
dssp_data = DSSPreader(inputfile = dssp_out).read() # reads DSSP output
dssp_data = dssp_data.rename(index = str, columns = {"RES": "PDB_ResNum"})
dssp_data.PDB_ResNum = dssp_data.PDB_ResNum.astype(str)
dssp_cols = ["PDB_ResNum", "SS", "ACC", "KAPPA", "ALPHA", "PHI", "PSI", "RSA"] # selects subset of columns
dssp_data.to_csv(dssp_csv, index = False)
return dssp_data[dssp_cols]
def process_sifts_data(input_sifts, sifts_dir, pdb_id):
"""
processes SIFTS table, saves and returns the processed tables
"""
sifts_data = SIFTSreader(inputfile = input_sifts).read() # read sifts data
sifts_mapping = sifts_data[[
"UniProt_dbResNum", "UniProt_dbResName", "PDB_dbResName",
"PDB_dbResNum", "PDB_dbChainId"
]] # subsetting sifts table
sifts_mapping = sifts_mapping.rename(index = str, columns = {
"UniProt_dbResNum":"UniProt_ResNum", "UniProt_dbResName":"UniProt_ResName",
"PDB_dbResName":"PDB_ResName", "PDB_dbResNum":"PDB_ResNum",
"PDB_dbChainId":"PDB_ChainID"
}) # renaming table columns
try:
sifts_mapping = sifts_mapping[sifts_mapping.UniProt_ResNum != "null"]
except:
pass
try:
sifts_mapping = sifts_mapping[~sifts_mapping.UniProt_ResNum.isnull()]
except:
pass
sifts_mapping = sifts_mapping[sifts_mapping.PDB_ResNum != "null"]
sifts_mapping.UniProt_ResNum = sifts_mapping.UniProt_ResNum.astype(int)
sifts_mapping.PDB_ResNum = sifts_mapping.PDB_ResNum.astype(str)
sifts_csv = os.path.join(sifts_dir, "sifts_" + pdb_id + ".csv") # sifts output csv file
sifts_data.to_csv(sifts_csv, index = False) # write sifts table to csv
sifts_csv2 = os.path.join(sifts_dir, "sifts_mapping_" + pdb_id + ".csv")
sifts_mapping.to_csv(sifts_csv2, index = False)
shutil.move(input_sifts, os.path.join(sifts_dir, os.path.basename(input_sifts)))
return sifts_data, sifts_mapping
### ARPEGGIO ###
def run_clean_pdb(pdb_path):
"""
runs pdb_clean.py to prepare files for arpeggio
"""
args = [
clean_pdb_python_bin, clean_pdb_bin, pdb_path
]
#print(args)
exit_code = os.system(" ".join(args))
if exit_code != 0:
print(" ".join(args))
return exit_code
def run_arpeggio(pdb_path, lig_name, dist = 5):
"""
runs Arpeggio
"""
args = [
arpeggio_python_bin, arpeggio_bin, pdb_path, "-s",
"RESNAME:{}".format(lig_name), "-i", str(dist), "-v"
]
exit_code = os.system(" ".join(args))
if exit_code != 0:
print(" ".join(args))
return exit_code
def move_arpeggio_output(wd, subdir, strucs, supp_pdbs_subdir, clean_pdbs_subdir, struc2ligs):
"""
moves pdb_clean.py and Arpeggio output files to appropriate directory
"""
for struc in strucs:
clean_struc = struc.replace(".pdb", ".clean.pdb")
clean_struc_path_from = os.path.join(supp_pdbs_subdir, clean_struc)
clean_struc_path_to = os.path.join(clean_pdbs_subdir, clean_struc)
if os.path.isfile(clean_struc_path_from):
shutil.move(clean_struc_path_from, clean_struc_path_to)
for arpeggio_suff in arpeggio_suffixes:
for the_lig in struc2ligs[struc]:
arpeggio_file_from_supp = os.path.join(supp_pdbs_subdir, struc[:-3] + "clean_{}".format(the_lig) + "." + arpeggio_suff)
arpeggio_file_to = os.path.join(wd, "results/arpeggio/", subdir, struc[:-3] + "clean_{}".format(the_lig) + "." + arpeggio_suff)
arpeggio_file_from_clean = os.path.join(clean_pdbs_subdir, struc[:-3] + "clean_{}".format(the_lig) + "." + arpeggio_suff)
if os.path.isfile(arpeggio_file_from_supp):
shutil.move(arpeggio_file_from_supp, arpeggio_file_to)
elif os.path.isfile(arpeggio_file_from_clean):
shutil.move(arpeggio_file_from_clean, arpeggio_file_to)
for pdb_clean_suff in pdb_clean_suffixes:
pdb_clean_file_from = os.path.join(supp_pdbs_subdir, struc + "." + pdb_clean_suff)
pdb_clean_file_to = os.path.join(wd, "results/pdb_clean/", subdir, struc + "." + pdb_clean_suff)
if os.path.isfile(pdb_clean_file_from):
shutil.move(pdb_clean_file_from, pdb_clean_file_to)
elif os.path.isfile(os.path.join(wd, "results/pdb_clean", struc + "." + pdb_clean_suff)):
shutil.move(os.path.join(wd, "results/pdb_clean", struc + "." + pdb_clean_suff), pdb_clean_file_to)
def process_arpeggio(struc, all_ligs, clean_pdbs_dir, arpeggio_dir, sifts_dir, bio2asym_chain_dict, cif2pdb_chain_dict):
"""
processes arpeggio output to generate the two tables that will
be used later in the analysis
"""
lig_cons_splits = []
arpeggio_lig_conss = []
for lig in all_ligs:
arpeggio_out_path_lig = os.path.join(arpeggio_dir, struc.replace("pdb", "clean_{}.bs_contacts".format(lig)))
all_cons_lig = pd.read_table(arpeggio_out_path_lig, header = None)
lig_cons_split_lig = reformat_arpeggio(all_cons_lig)
lig_cons_split_lig = add_resnames_to_arpeggio_table(struc, clean_pdbs_dir, lig_cons_split_lig)
lig_cons_split_lig = ligand_to_atom2(lig_cons_split_lig, lig)
lig_cons_split_lig["contact_type"] = lig_cons_split_lig.apply(lambda row: contact_type(row), axis = 1)
arpeggio_lig_cons_lig = lig_cons_split_lig.sort_values(by = ["Chain (Atom1)", "ResNum (Atom1)"])
arpeggio_lig_cons_lig = arpeggio_lig_cons_lig[["ResNum (Atom1)","Chain (Atom1)", 'ResName (Atom1)']]
arpeggio_lig_cons_lig = arpeggio_lig_cons_lig.drop_duplicates(subset = ["ResNum (Atom1)", "Chain (Atom1)"])
arpeggio_lig_cons_lig = arpeggio_lig_cons_lig.rename(index = str, columns = {"ResNum (Atom1)": "PDB_ResNum", "Chain (Atom1)": "PDB_ChainID"})
arpeggio_lig_cons_lig = arpeggio_lig_cons_lig.astype({"PDB_ResNum": int})
lig_cons_splits.append(lig_cons_split_lig)
arpeggio_lig_conss.append(arpeggio_lig_cons_lig)
lig_cons_split = pd.concat(lig_cons_splits)
arpeggio_lig_cons = pd.concat(arpeggio_lig_conss)
########################### ADDED TO AVOID INCORRECT BS DEFINITION DUE TO PDB RESNUMS ###########################
pdb_id = struc[:4]
sifts_mapping = pd.read_csv(os.path.join(sifts_dir, "sifts_mapping_{}.csv".format(pdb_id)))
sifts_dict = {}
for chain, chain_df in sifts_mapping.groupby("PDB_ChainID"):
for i, row in chain_df.iterrows():
sifts_dict[(chain, str(row["PDB_ResNum"]))] = row["UniProt_ResNum"]
sifts_dict = extend_sifts_mapping_dict(sifts_dict, bio2asym_chain_dict, cif2pdb_chain_dict)
lig_cons_split['ResNum (Atom1)'] = lig_cons_split['ResNum (Atom1)'].astype(str)
arpeggio_lig_cons['PDB_ResNum'] = arpeggio_lig_cons['PDB_ResNum'].astype(str)
lig_cons_split["UniProt_Resnum"] = lig_cons_split.set_index(['Chain (Atom1)', 'ResNum (Atom1)']).index.map(sifts_dict.get)
arpeggio_lig_cons["UniProt_Resnum"] = arpeggio_lig_cons.set_index(['PDB_ChainID', 'PDB_ResNum']).index.map(sifts_dict.get)
########################### ADDED TO AVOID INCORRECT BS DEFINITION DUE TO PDB RESNUMS ###########################
old_len1 = len(arpeggio_lig_cons)
old_len2 = len(lig_cons_split)
lig_cons_split = lig_cons_split[~lig_cons_split.UniProt_Resnum.isnull()].copy()
arpeggio_lig_cons = arpeggio_lig_cons[~arpeggio_lig_cons.UniProt_Resnum.isnull()].copy()
new_len1 = len(arpeggio_lig_cons)
new_len2 = len(lig_cons_split)
if new_len1 != old_len1:
print("WARNING!!! {} residues lacked mapping from PDB to UniProt at arpeggio_lig_cons for {}".format(new_len1-old_len1, pdb_id))
if new_len2 != old_len2:
print("WARNING!!! {} residues lacked mapping from PDB to UniProt at lig_cons_split for {}".format(new_len2-old_len2, pdb_id))
########################### ADDED TO AVOID INCORRECT BS DEFINITION DUE TO LACKING MAPPING TO PDB RESNUMS ###########################
lig_cons_split.to_csv(os.path.join(arpeggio_dir, "arpeggio_all_cons_split_" + struc[:4] + ".csv"), index = False)
arpeggio_lig_cons.to_csv(os.path.join(arpeggio_dir, "arpeggio_lig_cons_" + struc[:4] + ".csv"), index = False)
return lig_cons_split, arpeggio_lig_cons
def reformat_arpeggio(arpeggio_df):
"""
starts formatting arpeggio table
"""
arpeggio_df.columns = [
'Atom_1', 'Atom_2', 'Clash', 'Covalent', 'VdW Clash', 'Vdw', 'Proximal', 'Hydrogen Bond',
'Weak Hydrogen Bond', 'Halogen bond', 'Ionic', 'Metal Complex', 'Aromatic', 'Hydrophobic',
'Carbonyl', 'Polar', 'Weak Polar', 'Atom proximity', 'Vdw proximity', 'Interacting entities'
]
lig_cons = arpeggio_df.loc[arpeggio_df["Interacting entities"] == "INTER"].copy() # Selecting only the interactions between our specified atoms (i.e ligands) and other selections
lig_cons = lig_cons.sort_values(by = ["Atom_1"])
split_atom1 = lig_cons.Atom_1.str.split("/", expand = True) # splits atom1 column into three new columns: chain, resnum and atom
split_atom1.columns = ["Chain (Atom1)", "ResNum (Atom1)", "Atom (Atom1)"]
split_atom2 = lig_cons.Atom_2.str.split("/", expand = True) # splits atom2 column into three new columns: chain, resnum and atom
split_atom2.columns = ["Chain (Atom2)", "ResNum (Atom2)", "Atom (Atom2)"]
lig_cons_split = pd.merge(split_atom2, lig_cons, left_index = True, right_index = True) # Making a table of the contacts, but with the atom identifier split into chain, resnum, and atom
lig_cons_split = pd.merge(split_atom1, lig_cons_split, left_index = True, right_index = True) # Making a table of the contacts, but with the atom identifier split into chain, resnum, and atom
lig_cons_split = lig_cons_split.drop(axis = 1, labels = ["Atom_1", "Atom_2"])
lig_cons_split["ResNum (Atom1)"] = lig_cons_split["ResNum (Atom1)"].astype(int)
lig_cons_split["ResNum (Atom2)"] = lig_cons_split["ResNum (Atom2)"].astype(int)
return lig_cons_split
def add_resnames_to_arpeggio_table(structure, clean_pdbs_dir, arpeggio_cons_split):
"""
adds residue names to arpeggio table, needed for later table mergings
"""
structure_path = os.path.join(clean_pdbs_dir, structure.replace("pdb", "clean.pdb"))
pdb_structure = PDBXreader(inputfile = structure_path).atoms(format_type = "pdb", excluded=())
resnames_dict = {(row.label_asym_id, int(row.label_seq_id)): row.label_comp_id for index, row in pdb_structure.drop_duplicates(['label_asym_id', 'label_seq_id']).iterrows()}
arpeggio_cons_split["ResName (Atom1)"] = arpeggio_cons_split.set_index(["Chain (Atom1)", "ResNum (Atom1)"]).index.map(resnames_dict.get)
arpeggio_cons_split["ResName (Atom2)"] = arpeggio_cons_split.set_index(["Chain (Atom2)", "ResNum (Atom2)"]).index.map(resnames_dict.get)
return arpeggio_cons_split
def ligand_to_atom2(lig_cons_split, lig):
"""
formats arpeggio table so that the ligand atoms are always Atom2
"""
ordered_cols = [
'Chain (Atom1)', 'ResNum (Atom1)', 'ResName (Atom1)', 'Atom (Atom1)',
'Chain (Atom2)', 'ResNum (Atom2)', 'ResName (Atom2)', 'Atom (Atom2)',
'Clash', 'Covalent', 'VdW Clash', 'Vdw', 'Proximal', 'Hydrogen Bond',
'Weak Hydrogen Bond', 'Halogen bond', 'Ionic', 'Metal Complex', 'Aromatic',
'Hydrophobic', 'Carbonyl', 'Polar', 'Weak Polar','Atom proximity',
'Vdw proximity', 'Interacting entities'
]
lig_is_atom1 = lig_cons_split[lig_cons_split["ResName (Atom1)"] == lig].copy().sort_values("ResNum (Atom2)")
lig_is_atom2 = lig_cons_split[lig_cons_split["ResName (Atom2)"] == lig].copy().sort_values("ResNum (Atom1)")
lig_is_atom1.rename(columns = {
'Chain (Atom1)': 'Chain (Atom2)', 'Chain (Atom2)': 'Chain (Atom1)',
'ResNum (Atom1)': 'ResNum (Atom2)', 'ResNum (Atom2)': 'ResNum (Atom1)',
'Atom (Atom1)': 'Atom (Atom2)', 'Atom (Atom2)': 'Atom (Atom1)',
'ResName (Atom1)': 'ResName (Atom2)', 'ResName (Atom2)': 'ResName (Atom1)'
}, inplace = True)
lig_cons_split_rf = pd.concat([lig_is_atom1[ordered_cols], lig_is_atom2[ordered_cols]]) # new dataframe so ligand is always atom2
lig_cons_split_rf = lig_cons_split_rf[lig_cons_split_rf["ResName (Atom1)"].isin(aas)]
return lig_cons_split_rf
def extend_sifts_mapping_dict(sifts_dict, bio2asym_chain_dict, cif2pdb_chain_dict):
"""
extends PDB-UniProt residue number mapping so ALL chains in preferred biological assembly
are present and a UniProt residue number can be obtained
"""
unique_sifts_chains = list(set([k[0] for k in list(sifts_dict.keys())]))
for bio_chain, asym_chain in bio2asym_chain_dict.items():
if bio_chain not in unique_sifts_chains:
asym_chain_ks = [k for k in list(sifts_dict.keys()) if k[0] == asym_chain]
for asym_chain_k in asym_chain_ks:
sifts_dict[(cif2pdb_chain_dict[bio_chain], asym_chain_k[1])] = sifts_dict[asym_chain_k]
return sifts_dict
def contact_type(row):
"""
determines whether a row is backbone or sidechain contact
"""
if row["Atom (Atom1)"] in bbone:
return "backbone"
else:
return "sidechain"
### BINDING SITE DEFINITION ###
def def_bs_oc(results_dir, pdb_files, prot, subdir, lig_names, bs_def_out, attr_out, chimera_script_out, arpeggio_dir, metric = oc_metric, dist = oc_dist, method = oc_method, alt_fmt = False):
"""
given a set of pdb structures, and other arguments, clusters ligands in space,
defines binding sites and writes chimera attribute files and chimera script to
format the superimposed structures to facilitate visualisation
alt_fmt is a boolean I added so it works with slightly different input. Still PDB
files, but some which coordinates were transformed using PDBe-KB transformation
matrices. They have different nomenclature and therefore indices to get pdb_files_dict
must be different
"""
lig_data_df, labs = generate_ligs_res_df(arpeggio_dir, alt_fmt = alt_fmt)
if len(lig_data_df) == 1: #should only happen in the case of only one LOI
lig_data_df["binding_site"] = 0
else:
dis_out = os.path.join(results_dir, "{}_{}_{}.dis".format(prot, subdir, metric))
get_dis_file(lig_data_df, labs, dis_out, metric = metric)
ocout, ec = oc(dis_out, method = method, cut_t = dist)
oc_dict = oc2dict(ocout)
cluster_id_dict = {}
for k, v in oc_dict.items():
for member in v["members"]:
cluster_id_dict[member] = v["new_id"]
sample_colors = list(itertools.islice(rgbs(), 200)) # new_colours
lig_data_df["lab"] = labs
lig_data_df["binding_site"] = lig_data_df.lab.map(cluster_id_dict)
if alt_fmt == True:
pdb_files_dict = {f[-16:-10]: f.split("/")[-1] for f in pdb_files}
lig_data_df["pdb_id2"] = lig_data_df.pdb_id + "_" + lig_data_df.lig_chain
lig_data_df["pdb_path"] = lig_data_df.pdb_id2.map(pdb_files_dict)
else:
pdb_files_dict = {f[-18:-14]: f.split("/")[-1] for f in pdb_files}
lig_data_df["pdb_path"] = lig_data_df.pdb_id.map(pdb_files_dict)
write_bs_files(lig_data_df, bs_def_out, attr_out, chimera_script_out)
return lig_data_df, labs
def generate_ligs_res_df(arpeggio_dir, alt_fmt = False):
"""
Given a directory containing processed Arpeggio output files,
returns a dataset containing information about the ligands of
interest binding the protein and their labels.
"""
lig_files = sorted([file for file in os.listdir(arpeggio_dir) if file.startswith("arpeggio_all_cons_split")])
pdbs, ligs, resnums, chains, ligs_ress = [[], [], [], [], []]
for file in lig_files:
if alt_fmt == True:
pdb_id = file[-10:-6]
else:
pdb_id = file[-8:-4]
df = pd.read_csv(os.path.join(arpeggio_dir, file))
for lig, lig_df in df.groupby(["ResName (Atom2)", "ResNum (Atom2)", "Chain (Atom2)"]):
lig_ress = lig_df["UniProt_Resnum"].unique().tolist()
pdbs.append(pdb_id)
ligs.append(lig[0])
resnums.append(lig[1])
chains.append(lig[2])
ligs_ress.append(lig_ress)
lig_data_df = pd.DataFrame(list(zip(pdbs, ligs, resnums, chains, ligs_ress)), columns = ["pdb_id", "lig_name", "lig_resnum", "lig_chain", "binding_res"])
labs = [pdbs[i] + "_" + str(ligs[i]) + "_" + str(resnums[i]) + "_" + str(chains[i]) for i in range(len(ligs))]
return lig_data_df, labs
def get_dis_file(lig_data_df, labs, out, metric = oc_metric):
"""
creates dis file to be fed to OC
"""
lig_res = lig_data_df.binding_res.tolist() #this is a list of lists, each list contains residue numbers interacting with ligand
if metric == "i_rel":
intersect_dict = get_intersect_rel_matrix(lig_res)
elif metric == "i_abs":
intersect_dict = get_intersect_matrix(lig_res)
n_ligs = len(lig_res)
with open(out, "w+") as fh:
fh.write(str(n_ligs) + "\n")
for lab in labs: #labs contain unique identifier for a ligand
fh.write(lab + "\n")
for i in range(n_ligs):
for j in range(i+1, n_ligs):
fh.write(str(intersect_dict[i][j]) + "\n")
def get_intersect_rel_matrix(binding_ress):
"""
Given a set of ligand binding residues, calcualtes a
similarity matrix between all the different sets of ligand
binding residues.
"""
inters = {i: {} for i in range(len(binding_ress))}
for i in range(len(binding_ress)):
inters[i][i] = intersection_rel(binding_ress[i], binding_ress[i])
for j in range(i+1, len(binding_ress)):
inters[i][j] = intersection_rel(binding_ress[i], binding_ress[j])
inters[j][i] = inters[i][j]
return inters
def intersection_rel(l1, l2):
"""
Calculates relative intersection.
"""
len1 = len(l1)
len2 = len(l2)
I_max = min([len1, len2])
I = len(list(set(l1).intersection(l2)))
return I/I_max
def get_intersect_matrix(binding_ress):
"""
Given a set of ligand binding residues, calcualtes a
similarity matrix between all the different sets of ligand
binding residues.
"""
inters = {i: {} for i in range(len(binding_ress))}
for i in range(len(binding_ress)):
inters[i][i] = intersection(binding_ress[i], binding_ress[i])
for j in range(i+1, len(binding_ress)):
inters[i][j] = intersection(binding_ress[i], binding_ress[j])
inters[j][i] = inters[i][j]
return inters
def intersection(l1, l2):
"""
Calculates intersection.
"""
I = len(list(set(l1).intersection(l2)))
return I
def oc(oc_in, type_mat = "sim", method = oc_method, cut_t = oc_dist):
"""
runs OC and returns exit code, should be 0 if all is ok
"""
oc_out = oc_in.replace(".dis", "_{}_{}_cut_{}.ocout".format(type_mat, method, cut_t))
args = [
oc_bin, type_mat, method, "id", "cut", str(cut_t),
"ps", oc_out[:-6], "<", oc_in, ">", oc_out
]
exit_code = os.system(" ".join(args))
return oc_out, exit_code
def oc2dict(ocout):
"""
parses OC output to generate dict
"""
oc_dict = {}
re_cluster = re.compile("""##\s+(\d+)\s(\d+\.*\d*)\s(\d+)\s*""")
with open (ocout, "r") as fh:
s = 0
n_singleton = 0
n_cluster = 0
for line in fh:
if s == 0:
if line.startswith("##"):
m = re_cluster.match(line)
cluster_id, score, cluster_size = m.groups()
oc_dict[cluster_id] = {"score": float(score), "size": int(cluster_size), "new_id": n_cluster}
n_cluster += 1
elif line.startswith(" "):
oc_dict[cluster_id]["members"] = line.strip().split(" ")
else:
if line.strip() == "":
pass
elif line.strip() == "UNCLUSTERED ENTITIES":
s = 1
else:
oc_dict["singleton_{}".format(n_singleton)] = {"score": "", "size": 1, "members": [line.strip(),], "new_id": n_cluster}
n_singleton += 1
n_cluster += 1
return oc_dict
def write_bs_files(frag_mean_coords, bs_def_out, attr_out, chimera_script_out):
"""
doc
"""
frag_mean_coords = frag_mean_coords.dropna()
frag_mean_coords.binding_site = frag_mean_coords.binding_site.astype(int)
frag_mean_coords.lig_resnum = frag_mean_coords.lig_resnum.astype(int)
chimera_atom_spec = (':'+ frag_mean_coords.lig_resnum.astype(str) +
'.'+ frag_mean_coords.lig_chain +
'&#/name==' + frag_mean_coords.pdb_path)
frag_mean_coords = frag_mean_coords.assign(chimera_atom_spec = chimera_atom_spec)
frag_mean_coords.to_csv(bs_def_out, index = False) # saves table to csv
write_bs_attribute_file(frag_mean_coords, attr_out)
bs_labs = frag_mean_coords.binding_site.unique().tolist()
write_chimera_script(chimera_script_out, bs_labs)
def write_bs_attribute_file(clustered_fragments, attr_out):
"""
writes Chimera attribute file to later colour ligands
according to the binding site they bind to
"""
with open(attr_out, "w") as out:
out.write("attribute: binding_site\n")
out.write("match mode: 1-to-1\n")
out.write("recipient: residues\n")
out.write("\n".join("\t" + clustered_fragments.chimera_atom_spec.values + "\t" + clustered_fragments.binding_site.astype(str)))
def write_chimera_script(chimera_script_out, bs_labels):
"""
writes Chimera script that will format the superimposed structures
as well as colour ligands according to their binding site
"""
sample_colors = list(itertools.islice(rgbs(), 200)) # new_colours
chimera_rgb_string = [','.join(map(str, rgb)) for rgb in sample_colors]
cmds = [
"~rib", "rib #0", "ksdssp", "set silhouette", "set silhouettewidth 3",
"background solid white", "~dis", "sel ~@/color=white", "dis sel", "namesel lois",
"~sel"
]
with open(chimera_script_out, 'w') as out:
out.write('# neutral colour for everything not assigned a cluster\n')
out.write('colour white\n')
out.write('# colour each binding site\n')
for i in range(0, len(bs_labels)):
out.write('colour {} :/binding_site=={}\n'.format(','.join(list(map(str, list(sample_colors[i])))), i))
out.write("### SOME FORMATTING ###\n")
out.write("\n".join(cmds))
print("Chimera script successfully created!")
### CONSERVATION AND VARIATION ###
def create_alignment_from_struc(example_struc, fasta_path, pdb_fmt = "pdb", n_it = 3, seqdb = swissprot):
"""
given an example structure, creates and reformats an MSA
"""
create_fasta_from_seq(get_seq_from_pdb(example_struc, pdb_fmt = pdb_fmt), fasta_path) # CREATES FASTA FILE FROM PDB FILE
hits_out = fasta_path.replace("fa", "out")
hits_aln = fasta_path.replace("fa", "sto")
hits_aln_rf = fasta_path.replace(".fa", "_rf.sto")
jackhmmer(fasta_path, hits_out, hits_aln , n_it = n_it, seqdb = seqdb,) # RUNS JACKHAMMER USING AS INPUT THE SEQUENCE FROM THE PDB AND GENERATES ALIGNMENT
add_acc2msa(hits_aln, hits_aln_rf)
def get_seq_from_pdb(pdb_path, pdb_fmt = "mmcif"): # MIGHT NEED TO BE MORE SELECTIVE WITH CHAIN, ETC
"""
generates aa sequence string from a pdb coordinates file
"""
struc = PDBXreader(pdb_path).atoms(format_type = pdb_fmt, excluded=())
return "".join([aa_code[aa] for aa in struc[struc.group_PDB == "ATOM"].drop_duplicates(["auth_seq_id"]).auth_comp_id.tolist()])