-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathligysis_custom.py
1946 lines (1633 loc) · 82.6 KB
/
ligysis_custom.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 Bio
import sys
import math
import scipy
import pickle
import shutil
import logging
import argparse
import requests
import Bio.SeqIO
import prointvar
import Bio.AlignIO
import numpy as np
import configparser
import pandas as pd
from Bio.Seq import Seq
from Bio import SeqUtils
from Bio import pairwise2
from scipy import cluster
import varalign.alignments
import scipy.stats as stats
import varalign.align_variants
from prointvar.pdbx import PDBXreader
from prointvar.pdbx import PDBXwriter
from scipy.spatial.distance import squareform
from prointvar.dssp import DSSPrunner, DSSPreader
## UTILITIES
def dump_pickle(data, pickle_out):
"""
Dumps pickle.
"""
with open(pickle_out, "wb") as f:
pickle.dump(data, f)
def load_pickle(pickle_in):
"""
Loads pickle.
"""
with open(pickle_in, "rb") as f:
data = pickle.load(f)
return data
### DICTIONARIES AND LISTS
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_1l= [
"A", "R", "N", "D", "C", "Q", "E", "G", "H", "I",
"L", "K", "M", "F", "P", "S", "T", "W", "Y", "V",
"-"
]
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',
}
cif_cols_order = [
"group_PDB", "id", "type_symbol", "label_atom_id", "label_alt_id", "label_comp_id", "label_asym_id",
# "label_entity_id",
"label_seq_id", "pdbx_PDB_ins_code", "Cartn_x", "Cartn_y", "Cartn_z", "occupancy",
"B_iso_or_equiv", "pdbx_formal_charge", "auth_seq_id", "auth_comp_id", "auth_asym_id", "auth_atom_id", "pdbx_PDB_model_num"
]
chimeraX_commands = [
"color white; set bgColor white",
"set silhouette ON; set silhouetteWidth 2; set silhouetteColor black",
"~disp; select ~protein; ~select : HOH; ~select ::binding_site==-1; disp sel; ~sel",
"surf; surface color white; transparency 70 s;"
]
consvar_class_colours = [
"royalblue", "green", "grey", "firebrick", "orange"
]
interaction_to_color = { # following Arpeggio's colour scheme
'clash': '#000000',
'covalent':'#999999',
'vdw_clash': '#999999',
'vdw': '#999999',
'proximal': '#999999',
'hbond': '#f04646',
'weak_hbond': '#fc7600',
'xbond': '#3977db', #halogen bond
'ionic': '#e3e159',
'metal_complex': '#800080',
'aromatic': '#00ccff',
'hydrophobic': '#006633',
'carbonyl': '#ff007f',
'polar': '#f04646',
'weak_polar': '#fc7600',
}
bss_colors = load_pickle("./OTHER/colors.pkl") # sample colors
headings = ["ID", "RSA", "DS", "MES", "Size", "Cluster", "FS"]
wd = os.getcwd()
### CONFIG FILE READING AND VARIABLE SAVING
config = configparser.ConfigParser()
config.read("ligysis_config.txt")
stamp_bin = config["paths"].get("stamp_bin")
transform_bin = config["paths"].get("transform_bin")
clean_pdb_python_bin = config["paths"].get("clean_pdb_python_bin")
clean_pdb_bin = config["paths"].get("clean_pdb_bin")
arpeggio_python_bin = config["paths"].get("arpeggio_python_bin")
arpeggio_bin = config["paths"].get("arpeggio_bin")
gnomad_vcf = config["paths"].get("gnomad_vcf")
swissprot_path = config["paths"].get("swissprot")
ensembl_sqlite_path = config["paths"].get("ensembl_sqlite")
stampdir = config["paths"].get("stampdir")
### FUNCTIONS
## UTILITIES FUNCTIONS
def add_double_quotes_for_single_quote(df, columns = ["auth_atom_id", "label_atom_id"]):
"""
Adds double quotes to values with single quotes. This is needed for atoms with single quotes in their names.
"""
for column in columns:
df[column] = df[column].apply(
lambda x: x if str(x).startswith('"') and str(x).endswith('"') else f'"{x}"' if "'" in str(x) else x
)
return df
## SETUP FUNCTIONS
def setup_dirs(dirs):
"""
Creates directories if they do not exist.
"""
for dirr in dirs:
if os.path.isdir(dirr):
continue
else:
os.mkdir(dirr)
## UNIPROT NAMES FUNCTION
def get_uniprot_info(uniprot_id):
"""
Fetches UniProt ID, UniProt entry, and protein name for the given UniProt ID.
Parameters:
uniprot_id (str): UniProt ID to fetch the information for.
Returns:
dict: A dictionary with UniProt ID, UniProt entry, and protein name.
"""
url = f"https://rest.uniprot.org/uniprotkb/{uniprot_id}.json"
try:
response = requests.get(url)
response.raise_for_status()
data = response.json()
uniprot_id = data.get('primaryAccession', 'N/A')
uniprot_entry = data.get('uniProtkbId', 'N/A')
protein_name = data.get('proteinDescription', {}).get('recommendedName', {}).get('fullName', {}).get('value', 'N/A')
return {
'up_id': uniprot_id,
'up_entry': uniprot_entry,
'prot_name': protein_name
}
except:
return {"up_id": uniprot_id, "up_entry": "", "prot_name": ""}
## STAMPING FUNCTIONS
def generate_STAMP_domains(wd, pdbs_dir, domains_out, roi = "ALL"):
"""
Genereates domains file, needed to run STAMP.
"""
pdb_files = [file for file in os.listdir(pdbs_dir) if file.endswith(".pdb")]
if pdb_files == []:
pdb_files = [file for file in os.listdir(pdbs_dir) if file.endswith(".ent")] # trying .ent
rel_pdbs_dir = os.path.relpath(pdbs_dir, wd)
with open(domains_out, "w+") as fh:
for pdb in pdb_files: # THIS SHOULD ALWAYS BE EITHER .PDB OR .ENT
pdb_root, pdb_ext = os.path.splitext(pdb)
pdb_name = pdb_root.replace(".clean", "") # can't rely on the split, as the pdb might have a . in the name
fh.write("{} {} {{{}}}\n".format(os.path.join(rel_pdbs_dir, pdb), pdb_name + ".supp", 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", ### STAMP STILL CRASHES IF PATHS ARE TOO LONG ###
str(2), "-prefix", prefix, ">", out
]
cmd = " ".join(args)
exit_code = os.system(cmd)
return cmd, exit_code
def transform(matrix):
"""
Runs TRANSFORM to obtain set of transformed coordinates.
"""
if "STAMPDIR" not in os.environ:
os.environ["STAMPDIR"] = stampdir
args = [transform_bin, "-f", matrix, "-het"]
cmd = " ".join(args)
exit_code = os.system(cmd)
return cmd, exit_code
def fnames_from_domains(domains_out):
"""
Returns a list of the pdb file names from the STAMP domains file.
"""
with open(domains_out) as f:
lines = f.readlines()
fnames = []
for line in lines:
fnames.append(line.split()[1] + ".pdb")
return fnames
def move_supp_files(struc_files, supp_pdbs_dir, cwd):
"""
Moves set of supperimposed coordinate files to appropriate directory.
"""
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(prefix, stamp_out_dir, cwd):
"""
Moves STAMP output files to appropriate directory.
"""
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(cwd, prefix + ".out")
out_to = os.path.join(stamp_out_dir, prefix + ".out")
doms_from = os.path.join(cwd, 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)
def simplify_pdb(supp_file, simple_file, struc_fmt = "mmcif"):
"""
Simplifies pdb file by removing all non-ATOM records.
"""
df = PDBXreader(inputfile = supp_file).atoms(format_type = struc_fmt, excluded=())
df = add_double_quotes_for_single_quote(df)
df_hetatm = df.query('group_PDB != "ATOM"')
if df_hetatm.empty:
return # no HETATM records, no simple file is written
else:
w = PDBXwriter(outputfile = simple_file)
w.run(df_hetatm, format_type = struc_fmt, category = "auth")
## LIGAND FUNCTIONS
def get_lig_data(cifs_dir, ligs_df_path, struc_fmt = "mmcif"):
"""
From a directory containing a set of structurally superimposed pdbs,
writes a .pkl file indicating the name, chain and residue number of the
ligand(s) of interest in every cif.
"""
ligs_df = pd.DataFrame([])
simple_cif_files = [file for file in os.listdir(cifs_dir) if file.endswith(".cif")]
for struc in simple_cif_files:
struc_path = os.path.join(cifs_dir, struc)
df = PDBXreader(inputfile = struc_path).atoms(format_type = struc_fmt, excluded=())
hetatm_df = df.query('group_PDB == "HETATM"')
ligs = hetatm_df.label_comp_id.unique().tolist()
#lois = [lig for lig in ligs if lig not in non_relevant]
lois = ligs #currently taking all ligands
for loi in lois:
loi_df = hetatm_df.query('label_comp_id == @loi')
#lois_df_un = loi_df.drop_duplicates(["label_comp_id", "label_asym_id"])[["label_comp_id", "label_asym_id", "auth_seq_id"]]
lois_df_un = loi_df.drop_duplicates(["label_comp_id", "auth_asym_id", "auth_seq_id"])[["label_comp_id", "auth_asym_id", "auth_seq_id"]] # changing this to auth, cause it seems pdbe-arpeggio uses auth (except for _com_id).
lois_df_un["struc_name"] = struc
ligs_df = ligs_df.append(lois_df_un)
ligs_df = ligs_df[["struc_name", "label_comp_id", "auth_asym_id", "auth_seq_id"]]
ligs_df.to_pickle(ligs_df_path)
return ligs_df
## SIFTS FUNCTIONS
def get_protein_sequence(uniprot_id):
"""
Retrieves the protein sequence for a given UniProt ID.
"""
url = f"https://www.uniprot.org/uniprot/{uniprot_id}.fasta"
response = requests.get(url)
if response.ok:
fasta_data = response.text
sequence = ''.join(fasta_data.split('\n')[1:]) # Removing the description line (first line starting with ">")
return sequence
else:
raise ValueError(f"Error fetching data for UniProt ID {uniprot_id}")
def retrieve_mapping_from_struc(struc, uniprot_id, struc_dir, mappings_dir, struc_fmt = "mmcif"):
"""
Retrieves the mapping between the UniProt sequence and the PDB sequence by doing an alignment.
"""
input_struct = os.path.join(struc_dir, struc)
pdb_structure = PDBXreader(inputfile = input_struct).atoms(format_type = struc_fmt, excluded=()) # ProIntVar reads the local file
sequence = get_protein_sequence(uniprot_id)
pps = pdb_structure.query('group_PDB == "ATOM"')[['label_comp_id', 'auth_asym_id', 'auth_seq_id']].drop_duplicates().groupby('auth_asym_id') # groupby chain
pdb_chain_seqs = [(chain, SeqUtils.seq1(''.join(seq['label_comp_id'].values)), seq['auth_seq_id'].values) for chain, seq in pps] # list of tuples like: [(chain_id, chain_seq, [chain resnums])]
alignments = [pairwise2.align.globalxs(sequence, chain_seq[1], -5, -1) for chain_seq in pdb_chain_seqs] # list of lists of tuples containing SwissProt seq - PDB chain seq pairwise alignment
maps = []
for pdb_chain_seq, alignment in zip(pdb_chain_seqs, alignments):
PDB_UniProt_map = pd.DataFrame(
[(i, x) for i, x in enumerate(alignment[0][1], start=1)], # create aligned PDB sequences to dataframe
columns=['UniProt_ResNum', 'PDB_ResName']
)
PDB_UniProt_map = PDB_UniProt_map.assign(UniProt_ResName = list(alignment[0][0]))
PDB_index = PDB_UniProt_map.query('PDB_ResName != "-"').index
PDB_UniProt_map = PDB_UniProt_map.assign(PDB_ResNum = pd.Series(pdb_chain_seq[2], index = PDB_index)) # adds PDB_ResNum column
PDB_UniProt_map = PDB_UniProt_map.assign(PDB_ChainID = pd.Series(pdb_chain_seq[0], index = PDB_index)) # adds PDB_ChainId column
maps.append(PDB_UniProt_map)
prointvar_mapping = pd.concat(maps)
prointvar_mapping = prointvar_mapping[['UniProt_ResNum','UniProt_ResName','PDB_ResName','PDB_ResNum','PDB_ChainID']]
prointvar_mapping = prointvar_mapping[~prointvar_mapping.PDB_ResNum.isnull()]
struc_root, _ = os.path.splitext(struc)
struc_name = struc_root.replace(".supp", "") # can't rely on the split, as the pdb might have a . in the name
prointvar_mapping_csv = os.path.join(mappings_dir, struc_name + "_mapping.csv")
prointvar_mapping.PDB_ResNum = prointvar_mapping.PDB_ResNum.astype(str) # PDB_ResNum is a string, not an integer
prointvar_mapping.to_csv(prointvar_mapping_csv, index = False)
return prointvar_mapping
def get_pseudo_mapping_from_struc(struc, struc_dir, mappings_dir, struc_fmt = "mmcif"):
"""
Retrieves a pseudo-mapping for each structure when a UniProt ID is not provided.
"""
input_struct = os.path.join(struc_dir, struc)
pdb_structure = PDBXreader(inputfile = input_struct).atoms(format_type = struc_fmt, excluded=()) # ProIntVar reads the local file
pps = pdb_structure.query('group_PDB == "ATOM"')[['label_comp_id', 'auth_asym_id', 'auth_seq_id']].drop_duplicates().groupby('auth_asym_id') # groupby chain
pdb_chain_seqs = [(chain, SeqUtils.seq1(''.join(seq['label_comp_id'].values)), seq['auth_seq_id'].values) for chain, seq in pps] # list of tuples like: [(chain_id, chain_seq, [chain resnums])]
data = {
"UniProt_ResNum": [],
"UniProt_ResName": [],
"PDB_ResName": [],
"PDB_ResNum": [],
"PDB_ChainID": [],
}
for chain in pdb_chain_seqs:
data["UniProt_ResNum"].extend([int(el) for el in chain[2]]) # not changing column names, but not actually UniProt
data["UniProt_ResName"].extend(list(chain[1])) # not changing column names, but not actually UniProt
data["PDB_ResName"].extend(list(chain[1]))
data["PDB_ResNum"].extend(chain[2])
data["PDB_ChainID"].extend(chain[0]*len(chain[2]))
pseudo_mapping = pd.DataFrame(data)
pseudo_mapping = pseudo_mapping[~pseudo_mapping.PDB_ResNum.isnull()]
struc_root, _ = os.path.splitext(struc)
struc_name = struc_root.replace(".supp", "") # can't rely on the split, as the pdb might have a . in the name
pseudo_mapping_csv = os.path.join(mappings_dir, struc_name + "_mapping.csv")
pseudo_mapping.to_csv(pseudo_mapping_csv, index = False)
return pseudo_mapping
## DSSP FUNCTIONS
def run_dssp(struc, supp_pdbs_dir, dssp_dir):
"""
Runs DSSP, saves and return resulting output dataframe
"""
struc_root, _ = os.path.splitext(struc)
dssp_csv = os.path.join(dssp_dir, struc_root + ".csv") # output csv filepath
dssp_out = os.path.join(dssp_dir, struc_root + ".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]
## ARPEGGIO FUNCTIONS
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
]
cmd = " ".join(args)
exit_code = os.system(cmd)
return cmd, exit_code
def run_arpeggio(pdb_path, lig_sel, out_dir):
"""
runs Arpeggio
"""
args = [
arpeggio_python_bin, arpeggio_bin, pdb_path,
"-s", lig_sel, "-o", out_dir, "--mute"
]
cmd = " ".join(args)
exit_code = os.system(cmd)
return exit_code, cmd
def switch_columns(df, names):
"""
Switches columns in Arpeggio DataFrame, so that ligand atoms and protein
atoms are always on the same column.
"""
columns_to_switch = [
'auth_asym_id', 'auth_atom_id',
'auth_seq_id', 'label_comp_id'
]
for index, row in df.iterrows(): # Iterate through the DataFrame and switch columns where necessary
if row['label_comp_id_end'] in names:
for col in columns_to_switch:
bgn_col = f"{col}_bgn"
end_col = f"{col}_end"
df.at[index, bgn_col], df.at[index, end_col] = df.at[index, end_col], df.at[index, bgn_col]
return df
def map_values(row, pdb2up):
"""
maps UniProt ResNums from SIFTS dictionary from CIF file to Arpeggio dataframe.
"""
try:
return pdb2up[row.auth_asym_id_end][row.auth_seq_id_end]
except KeyError:
log.debug(f'Residue {row.auth_seq_id_end} chain {row.auth_asym_id_end} has no mapping to UniProt')
return np.nan # if there is no mapping, return NaN
def create_resnum_mapping_dicts(df):
"""
Creates a dictionary with the mapping between PDB_ResNum and UniProt_ResNum
froma previously created dataframe.
"""
pdb2up = {}
up2pdb = {}
for index, row in df.iterrows():
chain_id = row['PDB_ChainID']
pdb_resnum = row['PDB_ResNum']
uniprot_resnum = row['UniProt_ResNum']
if chain_id not in pdb2up: # Initialise dictionary for the chain ID if it doesn't exist
pdb2up[chain_id] = {}
if uniprot_resnum not in up2pdb:
up2pdb[uniprot_resnum] = []
pdb2up[chain_id][str(pdb_resnum)] = uniprot_resnum
up2pdb[uniprot_resnum].append((chain_id, str(pdb_resnum)))
return pdb2up, up2pdb
def process_arpeggio_df(arp_df, pdb_id, ligand_names, pdb2up):
"""
Process Arpeggio Df to put in appropriate
format to extract fingerprings. Also filter out
non-relevant interactions.
"""
arp_df_end_expanded = arp_df['end'].apply(pd.Series)
arp_df_bgn_expanded = arp_df['bgn'].apply(pd.Series)
arp_df = arp_df.join(arp_df_end_expanded).drop(labels='end', axis=1)
arp_df = arp_df.join(arp_df_bgn_expanded, lsuffix = "_end", rsuffix = "_bgn").drop(labels='bgn', axis = 1)
arp_df.auth_seq_id_bgn = arp_df.auth_seq_id_bgn.astype(str)
arp_df.auth_seq_id_end = arp_df.auth_seq_id_end.astype(str)
inter_df = arp_df.query('interacting_entities == "INTER" & type == "atom-atom"').copy().reset_index(drop = True)
inter_df = inter_df[inter_df['contact'].apply(lambda x: 'clash' not in x)].copy().reset_index(drop = True) # filtering out clashes
inter_df = inter_df.query('label_comp_id_bgn in @pdb_resnames or label_comp_id_end in @pdb_resnames').copy().reset_index(drop = True) # filtering out ligand-ligand interactions
if inter_df.empty:
log.warning("No protein-ligand interaction for {}".format(pdb_id))
return inter_df, "no-PL-inters"
inter_df = inter_df.query('label_comp_id_bgn in @ligand_names or label_comp_id_end in @ligand_names').copy().reset_index(drop = True) # filtering out non-LOI interactions (only to avoid re-running Arpeggio, once it has been run with wrong selection)
switched_df = switch_columns(inter_df, ligand_names)
switched_df = switched_df.query('label_comp_id_end in @pdb_resnames').copy() # filtering out non-protein-ligand interactions
switched_df["UniProt_ResNum_end"] = switched_df.apply(lambda row: map_values(row, pdb2up), axis=1) # Apply the function and create a new column
switched_df = switched_df.sort_values(by=["auth_asym_id_end", "UniProt_ResNum_end", "auth_atom_id_end"]).reset_index(drop = True)
return switched_df, "OK"
def get_inters(fingerprints_dict):
"""
Returns all ligand fingerprints from fingerprints dict.
"""
return [v for v in fingerprints_dict.values()]
def get_labs(fingerprints_dict):
"""
Returns all ligand labels from fingerprints dict.
"""
return [k for k in fingerprints_dict.keys()]
## mmcif dict with ProIntVar
def generate_dictionary(mmcif_file):
"""
Generates a dictionary of coordinates from an mmcif file.
"""
cif_df = PDBXreader(inputfile = mmcif_file).atoms(format_type = "mmcif", excluded=())
keys = list(zip(cif_df['auth_asym_id'], cif_df['label_comp_id'], cif_df['auth_seq_id'], cif_df['auth_atom_id'])) # Create the keys using vectorised operations
values = cif_df[['Cartn_x', 'Cartn_y', 'Cartn_z']].to_numpy().tolist() # Create the values as a list of lists (x, y, z)
result = dict(zip(keys, values)) # Combine the keys and values into a dictionary
return result
def determine_width(interactions):
"""
Generates cylinder width for 3DMol.js interaction
representation depending on Arpeggio contact
fingerprint.
"""
return 0.125 if 'vdw_clash' in interactions else 0.0625
def determine_color(interactions):
"""
Generates cylinder colour for 3DMol.js interaction
representation depending on Arpeggio contact
fingerprint.
"""
undef = ['covalent', 'vdw', 'vdw_clash', 'proximal']
if len(interactions) == 1 and interactions[0] in undef:
return '#999999'
else:
colors = [interaction_to_color[interaction] for interaction in interactions if interaction in interaction_to_color and interaction not in undef]
if colors:
return colors[0]
else:
log.critical("No color found for {}".format(interactions))
return None # Return the first color found, or None if no match
### FUNCTIONS FOR SITE DEFINITION
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 write_chimeraX_attr(cluster_id_dict, trans_dir, attr_out): # cluster_id_dict is now the new one with orig_label_asym_id
"""
Gets chimeraX atom specs, binding site ids, and paths
to pdb files to generate the attribute files later, and
eventually colour models.
"""
trans_files = [f for f in os.listdir(trans_dir) if f.endswith(".cif")]
order_dict = {k : i+1 for i, k in enumerate(trans_files)}
defattr_lines = []
for k, v in cluster_id_dict.items():
ld = k.split("_") # stands for lig data
struc_id, lig_resname, lig_chain_id, lig_resnum = ["_".join(ld[:-3]), ld[-3], ld[-2], ld[-1]] # this way, indexing from the end should cope with any struc_ids
if k in cluster_id_dict:
defattr_line = "\t#{}/{}:{}\t{}\n\n".format(order_dict[f'{struc_id}.simp.cif'], lig_chain_id, lig_resnum, v)
else:
defattr_line = "\t#{}/{}:{}\t{}\n\n".format(order_dict[f'{struc_id}.simp.cif'], lig_chain_id, lig_resnum, "-1")
defattr_lines.append(defattr_line)
with open(attr_out, "w") as out:
out.write("attribute: binding_site\n\n")
out.write("match mode: 1-to-1\n\n")
out.write("recipient: residues\n\n")
for i in sorted(defattr_lines):
out.write(i)
return
def write_chimeraX_script(chimera_script_out, trans_dir, attr_out, chX_session_out, chimeraX_commands, cluster_ids):
"""
Writes a chimeraX script to colour and format.
"""
trans_files = [f for f in os.listdir(trans_dir) if f.endswith(".cif")] ### FIXME format
with open(chimera_script_out, "w") as out:
out.write("# opening files\n\n")
for f in trans_files:
out.write("open {}\n\n".format(f))
out.write("# opening attribute file\n\n")
out.write("open {}\n\n".format(attr_out))
out.write("# colouring and formatting for visualisation\n\n")
for cmxcmd in chimeraX_commands:
out.write("{}\n\n".format(cmxcmd))
for cluster_id in cluster_ids:
out.write(f'col ::binding_site=={cluster_id} {bss_colors[cluster_id]};\n')
out.write("save {}\n\n".format(chX_session_out))
return
def get_residue_bs_membership(cluster_ress):
"""
Returns a dictionary indicating to which ligand binding
site each ligand binding residue is found in. A residue
might contribute to more than one adjacent binding site.
"""
all_bs_ress = []
for v in cluster_ress.values():
all_bs_ress.extend(v)
all_bs_ress = sorted(list(set(all_bs_ress)))
bs_ress_membership_dict = {}
for bs_res in all_bs_ress:
bs_ress_membership_dict[bs_res] = []
for k, v in cluster_ress.items():
if bs_res in v:
bs_ress_membership_dict[bs_res].append(k) # which binding site each residue belongs to
return bs_ress_membership_dict
def get_cluster_membership(cluster_id_dict):
"""
Creates a dictionary indicating to which cluster
each ligand binds to.
"""
membership_dict = {}
for k, v in cluster_id_dict.items():
if v not in membership_dict:
membership_dict[v] = []
membership_dict[v].append(k)
return membership_dict
def get_all_cluster_ress(membership_dict, fingerprints_dict):
"""
Given a membership dict and a fingerprint dictionary,
returns a dictionary that indicates the protein residues
forming each binding site.
"""
binding_site_res_dict = {}
for k, v in membership_dict.items():
if k not in binding_site_res_dict:
binding_site_res_dict[k] = []
for v1 in v:
binding_site_res_dict[k].extend(fingerprints_dict[v1])
binding_site_res_dict = {k: sorted(list(set(v))) for k, v in binding_site_res_dict.items()}
return binding_site_res_dict
### CONSERVATION + VARIATION FUNCTIONS
def create_alignment_from_struc(example_struc, fasta_path, struc_fmt = "mmcif", n_it = 3, seqdb = swissprot_path):
"""
Given an example structure, creates and reformats an MSA.
"""
main_chain_seq = get_seq_from_pdb(example_struc, struc_fmt = struc_fmt)
create_fasta_from_seq(main_chain_seq, fasta_path) # CREATES FASTA FILE FROM PDB FILE
fasta_root, _ = os.path.splitext(fasta_path)
hits_out = "{}.out".format(fasta_root)
hits_aln = "{}.sto".format(fasta_root)
hits_aln_rf = "{}_rf.sto".format(fasta_root)
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, struc_fmt = "mmcif"): # SELECTS FIRST CHAIN. CURRENTLY ONLY WORKS WITH ONE CHAIN
"""
Generates aa sequence string from a pdb coordinates file.
"""
struc = PDBXreader(pdb_path).atoms(format_type = struc_fmt, excluded=())
chains = sorted(list(struc.auth_asym_id.unique())) ### TODO: we generate sequence only for the first chain. this means this will only work for MONOMERIC PROTEINS
main_chain = chains[0]
main_chain_seq = "".join([aa_code[aa] for aa in struc.query('group_PDB == "ATOM" & auth_asym_id == @main_chain').drop_duplicates(["auth_seq_id"]).label_comp_id.tolist()])
return main_chain_seq
def create_fasta_from_seq(seq, out):
"""
Saves input sequence to fasta file to use as input for jackhmmer.
"""
with open(out, "w+") as fh:
fh.write(">query\n{}\n".format(seq))
def jackhmmer(seq, hits_out, hits_aln, n_it = 3, seqdb = swissprot_path):
"""
Runs jackhmmer on an input seq for a number of iterations and returns exit code, should be 0 if all is OK.
"""
args = ["jackhmmer", "-N", str(n_it), "-o", hits_out, "-A", hits_aln, seq, seqdb]
cmd = " ".join(args)
exit_code = os.system(cmd)
return cmd, exit_code
def add_acc2msa(aln_in, aln_out, fmt_in = "stockholm"):
"""
Modifies AC field of jackhmmer alignment in stockholm format.
:param aln_in: path of input alignment
:type aln_in: str, required
:param aln_out: path of output alignment
:type aln_in: str, required
:param fmt_in: input and output MSA format
:type aln_in: str, defaults to stockholm
"""
aln = Bio.SeqIO.parse(aln_in, fmt_in)
recs = []
for rec in aln:
if rec.id == "query":
rec.annotations["accession"] = "QUERYSEQ" # ADDS ACCESSION FIELD TO QUERY SEQUENCE
rec.annotations["start"] = 1
rec.annotations["end"] = len(rec.seq)
else:
rec.annotations["accession"] = rec.id.split("|")[1]
recs.append(rec)
Bio.SeqIO.write(recs, aln_out, fmt_in)
def get_target_prot_cols(msa_in, msa_fmt = "stockholm"):
"""
Returns list of MSA col idx that are popualted on the protein target.
"""
seqs = [str(rec.seq) for rec in Bio.SeqIO.parse(msa_in, msa_fmt) if "query" in rec.id]
occupied_cols = [i+1 for seq in seqs for i, el in enumerate(seq) if el != "-"]
return sorted(list(set(occupied_cols)))
def calculate_shenkin(aln_in, aln_fmt, out = None):
"""
Given an MSA, calculates Shenkin ans occupancy, gap
percentage for all columns.
"""
cols = in_columns(aln_in, aln_fmt)
scores = []
occ = []
gaps = []
occ_pct = []
gaps_pct = []
for k, v in cols.items():
scores.append(get_shenkin(k, v))
stats = (get_stats(v))
occ.append(stats[0])
gaps.append(stats[1])
occ_pct.append(stats[2])
gaps_pct.append(stats[3])
df = pd.DataFrame(list(zip(list(range(1,len(scores)+1)),scores, occ,gaps, occ_pct, gaps_pct)), columns = ["col", "shenkin", "occ", "gaps", "occ_pct", "gaps_pct"])
if out != None:
df.to_pickle(out)
return df
def get_stats(col):
"""
for a given MSA column, calculates some basic statistics
such as column residue occupancy ang gaps
"""
n_seqs = len(col)
gaps = col.count("-")
occ = n_seqs - gaps
occ_pct = round(100*(occ/n_seqs), 2)
gaps_pct = round(100-occ_pct, 2)
return occ, gaps, occ_pct, gaps_pct
def in_columns(aln_in, infmt):
"""
Returns dictionary in which column idx are the key
and a list containing all aas aligned to that column
is the value.
"""
aln = Bio.AlignIO.read(aln_in, infmt)
n_cols = len(aln[0])
cols = {}
for col in range(1,n_cols+1):
cols[col] = []
for row in aln:
seq = str(row.seq)
for i in range(0, len(seq)):
cols[i+1].append(seq[i])
return cols
def get_shenkin(i_col, col):
"""
Calculates Shenkin score for an MSA column.
"""
S = get_entropy(get_freqs(i_col, col))
return round((2**S)*6,2)
def get_freqs(i_col, col):
"""
Calculates amino acid frequences for a given MSA column.
"""
abs_freqs = {aa: 0 for aa in aas_1l}
non_standard_aas = {}
for aa in col:
aa = aa.upper()
if col.count("-") == len(col):
abs_freqs["-"] = 1
return abs_freqs
if aa in aas_1l:
abs_freqs[aa] += 1
else:
if aa not in non_standard_aas:
non_standard_aas[aa] = 0
non_standard_aas[aa] += 1
all_ns_aas = sum(non_standard_aas.values())
if all_ns_aas != 0:
log.warning("Column {} presents non-standard AAs: {}".format(str(i_col), non_standard_aas))
rel_freqs = {k: v/(len(col) - all_ns_aas) for k, v in abs_freqs.items()}
return rel_freqs
def get_entropy(freqs):
"""
Calculates Shannon's entropy from a set of aa frequencies.
"""
S = 0
for f in freqs.values():
if f != 0:
S += f*math.log2(f)
return -S
def format_shenkin(shenkin, prot_cols, out = None):
"""
Formats conservation dataframe and also
calculates two normalised versions of it.
"""
shenkin_filt = shenkin[shenkin.col.isin(prot_cols)].copy()
shenkin_filt.index = range(1, len(shenkin_filt) + 1) # CONTAINS SHENKIN SCORE, OCCUPANCY/GAP PROPORTION OF CONSENSUS COLUMNS
min_shenkin = min(shenkin_filt.shenkin)
max_shenkin = max(shenkin_filt.shenkin)
shenkin_filt.loc[:, "rel_norm_shenkin"] = round(100*(shenkin_filt.shenkin - min_shenkin)/(max_shenkin - min_shenkin), 2) # ADDING NEW COLUMNS WITH DIFFERENT NORMALISED SCORES
shenkin_filt.loc[:, "abs_norm_shenkin"] = round(100*(shenkin_filt.shenkin - 6)/(120 - 6), 2)
if out != None:
shenkin_filt.to_pickle(out)
return shenkin_filt
def get_human_subset_msa(aln_in, human_msa_out, fmt_in = "stockholm"):
"""
Creates a subset MSA containing only human sequences.
"""
msa = Bio.AlignIO.read(aln_in, fmt_in)
human_recs = []
for rec in msa:
if "HUMAN" in rec.name:
human_recs.append(rec)
Bio.SeqIO.write(human_recs, human_msa_out, fmt_in)
def cp_sqlite(wd, og_path = ensembl_sqlite_path):
"""
Copies ensembl_cache.sqlite
to execution directory.
"""
hidden_var_dir = os.path.join(wd, ".varalign")
sqlite_name = os.path.basename(og_path)
if not os.path.isdir(hidden_var_dir):
os.mkdir(hidden_var_dir)
else:
pass
cp_path = os.path.join(hidden_var_dir, sqlite_name)
shutil.copy(og_path, cp_path)
return cp_path
def rm_sqlite(cp_path):
"""
Removes ensembl_cache.sqlite
from execution directory.
"""
hidden_var_dir = os.path.dirname(cp_path)
os.remove(cp_path)
os.rmdir(hidden_var_dir)
def format_variant_table(df, col_mask, vep_mask = ["missense_variant"], tab_format = "gnomad"):
"""
Formats variant table, by gettint rid of empty rows that are not human sequences,
changning column names and only keeping those variants that are of interest and
are present in columns of interest.
"""
df_filt = df.copy(deep = True)
df_filt.reset_index(inplace = True)
if tab_format == "gnomad":
df_filt.columns = [" ".join(col).strip() for col in df_filt.columns.tolist()]
df_filt.columns = [col.lower().replace(" ", "_") for col in df_filt.columns.tolist()]
df_filt = df_filt[df_filt.source_id.str.contains("HUMAN")]
df_filt = df_filt.dropna(subset = ["vep_consequence"])
df_filt = df_filt[df_filt.vep_consequence.isin(vep_mask)]
df_filt = df_filt[df_filt.alignment_column.isin(col_mask)]
return df_filt
def get_missense_df(aln_in, variants_df, shenkin_aln, prot_cols, aln_out, aln_fmt = "stockholm", get_or = True):
"""
Generates a dataframe for the subset of human sequences with variants
mapping to them. Calculates shenkin, and occupancy data, and then
enrichment in variants.
"""
variants_aln = generate_subset_aln(aln_in, aln_fmt, variants_df, aln_out)
if variants_aln == "":
return pd.DataFrame()
variants_aln_info = calculate_shenkin(variants_aln, aln_fmt)
variants_aln_info = variants_aln_info[variants_aln_info.col.isin(prot_cols)]
vars_df = pd.DataFrame(variants_df.alignment_column.value_counts().reindex(prot_cols, fill_value = 0).sort_index()).reset_index()
vars_df.index = range(1, len(prot_cols) + 1)
vars_df.columns = ["col", "variants"]
merged = pd.merge(variants_aln_info, vars_df, on = "col", how = "left")
merged.index = range(1, len(vars_df) + 1)
merged["shenkin"] = shenkin_aln["shenkin"]
merged["rel_norm_shenkin"] = shenkin_aln["rel_norm_shenkin"]
merged["abs_norm_shenkin"] = shenkin_aln["abs_norm_shenkin"]
if get_or == True:
merged_or = get_OR(merged)
return merged_or
else:
return merged
def generate_subset_aln(aln_in, aln_fmt, df, aln_out = None):
"""
Creates a subset MSA containing only human sequences that present
missense variants and returns the path of such MSA.
"""
seqs_ids = df.source_id.unique().tolist()
aln = Bio.SeqIO.parse(aln_in, aln_fmt)
variant_seqs = [rec for rec in aln if rec.id in seqs_ids]
n_variant_seqs = len(variant_seqs)
if n_variant_seqs == 0:
return ""
else:
log.info("There are {} sequences with variants for {}".format(str(n_variant_seqs), aln_in))
if aln_out == None:
aln_root, aln_ext = os.path.splitext(aln_in)
aln_out = "{}_variant_seqs{}".format(aln_root, aln_ext)
Bio.SeqIO.write(variant_seqs, aln_out, aln_fmt)
return aln_out
def get_OR(df, variant_col = "variants"):
"""
Calculates OR, and associated p-value and CI,
given a missense dataframe with variants and occupancy.
"""
tot_occ = sum(df.occ)
tot_vars = sum(df[variant_col])
idx = df.index.tolist()