-
Notifications
You must be signed in to change notification settings - Fork 0
/
predictors.py
810 lines (666 loc) · 30.2 KB
/
predictors.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
"""
This implementation focuses on gathering known antibody paratope predictor methods.
The responsibility of creating the subsystems falls under each concrete Predictor.
In this module, the main focus is not the performance of forward pass but rather the ease of usage
and the reproducibility of the original method's predictions.
The second main focus is the provisioning of a similar interface between end-to-end models.
"""
import os
import sys
from pathlib import Path
from abc import ABC, abstractmethod
if sys.version_info >= (3, 11):
from enum import StrEnum, auto
else:
from backports.strenum import StrEnum
from backports import auto
import torch
import numpy as np
import pandas as pd
import polars as pl
from tqdm import tqdm
from joblib import Parallel, delayed
from sklearn.ensemble import RandomForestClassifier, HistGradientBoostingClassifier
from topefind.utils import TOPEFIND_PATH, get_device
from topefind.vendored.parapred_pytorch.parapred import model as parapred_model
from topefind.vendored.parapred_pytorch.parapred import preprocessing as parapred_preproc
from topefind.vendored.Paragraph.Paragraph.model import EGNN_Model as EGNN_Model_paragraph
from topefind.vendored.Paragraph.Paragraph.predict import get_dataloader, evaluate_model
from topefind.data_hub import SabdabHub
from topefind import utils, embedders
PARAPRED_PATH = utils.TOPEFIND_PATH / "vendored/parapred_pytorch/parapred/weights/parapred_pytorch.h5"
PARAGRAPH_PATH = utils.TOPEFIND_PATH / "vendored/Paragraph/Paragraph/trained_model/pretrained_weights.pt"
PARAGRAPH_H_PATH = utils.TOPEFIND_PATH / "vendored/Paragraph/Paragraph/trained_model/pretrained_weights_heavy.pt"
PARAGRAPH_L_PATH = utils.TOPEFIND_PATH / "vendored/Paragraph/Paragraph/trained_model/pretrained_weights_light.pt"
# To use `torch.use_deterministic_algorithms` on CUDA >= 10.2 you need to set CUBLAS_WORKSPACE_CONFIG=:4096:8
# This happens because several utilities are running on cuBLAS!
np.random.seed(42)
torch.manual_seed(42)
torch.use_deterministic_algorithms(True)
os.environ["CUBLAS_WORKSPACE_CONFIG"] = ":4096:8"
class EndToEndPredictorName(StrEnum):
parapred = auto()
paragraph_untrained = auto()
paragraph_unpaired = auto()
paragraph_paired = auto()
pppred = auto()
af2_multimer = auto()
esm_fold_multimer = auto()
seq_to_cdr = auto()
aa_freq = auto()
pos_freq = auto()
aa_pos_freq = auto()
class Predictor(ABC):
name: str
@abstractmethod
def predict(self, an_input):
...
@abstractmethod
def predict_multiple(self, some_inputs):
...
@abstractmethod
def prepare_dataset(self, dataset):
...
class Parapred(Predictor):
def __init__(
self,
name: EndToEndPredictorName = EndToEndPredictorName.parapred,
max_cdr_length: int = 40,
device: str = "cpu"
):
"""
Model initialization and configuration.
Parameters
----------
name: Name of the predictor.
max_cdr_length : Maximum accepted CDR length, to match the original value this is set to 40.
"""
self.name = name
self.max_cdr_length = max_cdr_length
self.device = get_device(device)
self._model = parapred_model.Parapred()
state_dict = torch.load(PARAPRED_PATH, map_location=torch.device(device))
self._model.load_state_dict(state_dict)
self._model.eval()
@torch.no_grad()
def predict(self, sequence: str) -> np.ndarray:
"""
Predicts the paratope of an antibody.
Following the Parapred implementation, the inputs to the model should be sequences of regions.
To achieve this, the sequence is firstly numbered with ANARCI.
Then each region is predicted with the `parapred_pytorch` model.
Parameters
----------
sequence: The full amino acid sequence of an antibody (Fv region)
Returns
-------
paratope_probs: Paratope probabilities for each amino acid.
"""
cdrs, fmks = utils.get_antibody_regions(sequence)
paratope_probs = np.zeros(0)
for fmk, cdr in zip(fmks[:-1], cdrs):
max_len = self.max_cdr_length if len(cdr) > self.max_cdr_length else len(cdr)
encoded, lengths = parapred_preproc.encode_batch([cdr], max_length=max_len)
no_mask = torch.ones_like(encoded)
probs = self._model(encoded, no_mask, lengths)
# Cleaning up probs from padded
probs = [parapred_model.clean_output(pr, lengths[i]).numpy() for i, pr in enumerate(probs)]
paratope_probs = np.concatenate([paratope_probs, np.zeros(len(fmk)), probs[0]])
# Matching initial sequence length
paratope_probs = np.concatenate([paratope_probs, np.zeros(len(fmks[-1]))])
return paratope_probs
def predict_multiple(self, sequences: list[str], verbose: bool = False, n_jobs: int = 1) -> list[np.ndarray]:
"""
Dummy parallelization of single predictions.
Parameters
----------
sequences: list of strings that contain antibody sequences.
verbose: If True shows tqdm progress bar.
n_jobs: Number of jobs for joblib.
Returns
-------
list of predictions
"""
return Parallel(n_jobs)(delayed(self.predict)(seq) for seq in tqdm(sequences, disable=(not verbose)))
def prepare_dataset(
self,
dataset: pl.DataFrame,
) -> tuple[list[str], list[bool]]:
"""
Prepares a given DataFrame to be consumed.
Parameters
----------
dataset: A DataFrame that has to contain the following columns: "antibody_sequence" and "full_paratope_labels"
Returns
-------
inputs, labels: These are grouped by protein i.e. each element in the inputs is an antibody, and each element
in labels is list of labels for each amino acid of the antibody sequence in the inputs.
"""
inputs = dataset.get_column("antibody_sequence").to_list()
labels = dataset.get_column("full_paratope_labels").to_list()
return inputs, labels
class Paragraph(Predictor):
def __init__(
self,
name: EndToEndPredictorName,
pdbs_path: Path | str,
device: str = "cpu",
):
"""
Model initialization and configuration.
To match the usage of Paragraph CSV paths and PDBs paths are included.
Parameters
----------
name: Name of the predictor.
pdbs_path : Path to the directory containing all the pdbs.
"""
self.name = name
self.pdbs_path = Path(pdbs_path)
self.device = get_device(device)
if name == EndToEndPredictorName.paragraph_paired:
# Getting settings for original model used by authors and initializing model
# 20D for of AA type and 2D for chain ID
self._model = EGNN_Model_paragraph(
num_feats=22,
graph_hidden_layer_output_dims=[22] * 6,
linear_hidden_layer_output_dims=[10] * 2,
)
state_dict = torch.load(PARAGRAPH_PATH, map_location=torch.device(self.device))
self._model.load_state_dict(state_dict)
else:
self._model_h = EGNN_Model_paragraph(
num_feats=22,
graph_hidden_layer_output_dims=[22] * 6,
linear_hidden_layer_output_dims=[10] * 2,
)
self._model_l = EGNN_Model_paragraph(
num_feats=22,
graph_hidden_layer_output_dims=[22] * 6,
linear_hidden_layer_output_dims=[10] * 2,
)
if name != EndToEndPredictorName.paragraph_untrained:
state_dict = torch.load(PARAGRAPH_H_PATH, map_location=torch.device(self.device))
self._model_h.load_state_dict(state_dict)
state_dict = torch.load(PARAGRAPH_L_PATH, map_location=torch.device(self.device))
self._model_l.load_state_dict(state_dict)
def predict(self, pdb_chains: dict) -> np.ndarray:
"""
Predicts the paratope of an antibody.
This implementation follows the authors' way of predicting and calls functions from vendored packages.
More specifically, this includes the creation of a torch.utils.data.DataLoader and calls the originals
`get_dataloader()` and the `evaluate_model()`.
Some minor modifications are included in `topefind.vendored.Paragraph` to allow DataFrames as input.
Parameters
----------
pdb_chains: dict that contains {pdb_code, H_id, L_id, focus}
Returns
-------
predictions
"""
h_id = pdb_chains["H_id"][0]
l_id = pdb_chains["L_id"][0]
pdb_code = pdb_chains["pdb_code"][0]
chain_id = pdb_chains["focus"]
if h_id == "" and l_id == "":
raise ValueError("Wrong input, specify one chain not zero.")
# Loading and cleaning atoms.
atoms = SabdabHub.read_pdb(self.pdbs_path / Path(pdb_code + ".pdb"))
atoms = SabdabHub.select_non_hetero_atoms(atoms)
atoms = SabdabHub.select_non_h_atoms(atoms)
atoms = SabdabHub.select_chain_in_atoms(atoms, chain_id)
res_ids_w_ins = SabdabHub.get_atom_res_ins(atoms)
_, idx = np.unique(res_ids_w_ins, return_index=True)
res_ids_w_ins = res_ids_w_ins[np.sort(idx)]
# Initialize output probs to zeros.
paratope_probs = np.zeros(len(res_ids_w_ins))
# Pass now everything through the original Paragraph.
df_input = pd.DataFrame(pdb_chains)
dl = get_dataloader(df_input, self.pdbs_path)
if self.name == EndToEndPredictorName.paragraph_paired:
df_out = evaluate_model(self._model, dl, self.device)
else:
if l_id == "":
df_out = evaluate_model(self._model_h, dl, self.device)
else:
df_out = evaluate_model(self._model_l, dl, self.device)
df_out = df_out[df_out["chain_id"] == chain_id]
probs_out = df_out["pred"].to_numpy()
# We need to fill in only the CDR regions predicted.
paragraph_used_res_ids = df_out["IMGT"].to_numpy().flatten()
mask = np.isin(res_ids_w_ins, paragraph_used_res_ids)
paratope_probs[mask] = probs_out
return paratope_probs
def predict_multiple(self, pdb_chains: list[dict], verbose: bool = False, n_jobs: int = 1) -> list[np.ndarray]:
"""
Dummy parallelization of single predictions.
Parameters
----------
pdb_chains: list of dicts that contains pdb name, heavy chain id, light chain id and focus.
verbose: If True shows tqdm progress bar.
n_jobs: Number of jobs for joblib.
Returns
-------
list of predictions
"""
return Parallel(n_jobs)(delayed(self.predict)(d) for d in tqdm(pdb_chains, disable=(not verbose)))
def prepare_dataset(
self,
dataset: pl.DataFrame,
) -> tuple[list[dict], list[bool]]:
"""
Prepares a given DataFrame to be consumed.
Parameters
----------
dataset: A DataFrame that has to contain the following columns:
"antibody_sequence",
"full_paratope_labels",
"chain_type",
"pdb",
Returns
-------
inputs, labels: These are grouped by protein i.e. each element in the inputs is an antibody, and each element
in labels is list of labels for each amino acid of the antibody sequence in the inputs.
"""
inputs = []
pdbs = dataset.get_column("pdb").to_list()
ab_chains = dataset.get_column("antibody_chain").to_list()
chain_types = dataset.get_column("chain_type").to_list()
labels = dataset.get_column("full_paratope_labels").to_list()
if self.name == EndToEndPredictorName.paragraph_paired:
heavys = dataset.filter(pl.col("chain_type").is_in(["heavy"]))
lights = dataset.filter(pl.col("chain_type").is_in(["light"]))
paired_inputs = heavys.join(lights, on="pdb").rename({"antibody_chain": "H", "antibody_chain_right": "L"})
paired_inputs = paired_inputs.select(["pdb", "H", "L"])
for pdb, ab_chain, chain_type in zip(pdbs, ab_chains, chain_types):
inputs.append({
"pdb_code": [pdb],
"H_id": paired_inputs.filter(pl.col("pdb") == pdb).select("H").item(),
"L_id": paired_inputs.filter(pl.col("pdb") == pdb).select("L").item(),
"focus": ab_chain
})
else:
for pdb, ab_chain, chain_type in zip(pdbs, ab_chains, chain_types):
inputs.append({
"pdb_code": [pdb],
"H_id": ["" if chain_type == "light" else ab_chain],
"L_id": ["" if chain_type == "heavy" else ab_chain],
"focus": ab_chain
})
return inputs, labels
# noinspection PyPep8Naming
class PLMSKClassifier(Predictor):
"""
A composition of a Protein Language Model in the format provided by embedders.Embedder and a sklearn classifier
that outputs probabilities. In this class embeddings are provided "as is", i.e. no fine-tuning is done.
"""
def __init__(
self,
embedder: embedders.Embedder | embedders.MultiChainAwareEmbedder,
classifier: RandomForestClassifier | HistGradientBoostingClassifier,
save_path: Path | str | None = None,
de_bias: bool = False,
):
self.name = embedder.name
self.embedder = embedder
self.classifier = classifier
self.save_path = save_path
self.de_bias = de_bias
def train(self, X_train: list[str] | list[tuple[str, str]], y_train: list[list[bool]]):
"""
Trains self.classifier on the embeddings computed with a given classifier.
Parameters
----------
X_train: list of str where each string is an antibody amino acidic sequence.
y_train: list of boolean arrays that represent the labels corresponding to the paratope.
"""
# First get the embedding from the embedder
print(f"Computing embeddings for: {self.embedder.name}")
X_train_embs = [self.embedder.embed(inputs)[0].to("cpu").numpy() for inputs in tqdm(X_train)]
X_train_embs = np.vstack(X_train_embs).astype(float)
y_train = np.concatenate(y_train)
if self.de_bias:
# One could theoretically de-bias by first clustering, in this case we know that the distribution of AAs
# is tilted towards Y, i.e. Tyrosines. So we could hope to cluster by amino acid the embeddings and
# equal out the classes.
# Unfortunately, this does not work that well
"""
print("Fitting clustering algorithm")
kmeans = KMeans(n_clusters=20, random_state=42).fit(X_train_embs)
_, counts_clust = np.unique(kmeans.labels_, return_counts=True)
# median = np.median(counts_clust)
# median_counts_clust_idx = np.argmin([median - counts for counts in counts_clust])
X_train_embs_de_biased = []
y_train_de_biased = []
print("Calculating the new de-biased training set")
for x, y in zip(X_train_embs, y_train):
pred_clust = kmeans.predict([x])
counts_clust[pred_clust] -= 1
X_train_embs_de_biased.append(x)
y_train_de_biased.append(y)
# Break when the smallest cluster is consumed
if counts_clust[pred_clust] == 0:
break
# Break when the median cluster is consumed
# if counts_clust[median_counts_clust_idx] == 0:
# break
else:
raise NotImplementedError("There was not a full digestion of at least one class")
X_train_embs = X_train_embs_de_biased
y_train = y_train_de_biased
"""
# Let's use a hard de-biasing, handcrafted, without clustering.
aas = np.array([aa for aa in "".join(X_train)])
unique_aas, counts_aas = np.unique(aas, return_counts=True)
aa_to_counts = {ua: ca for ua, ca in zip(unique_aas, counts_aas)}
X_train_embs_de_biased = []
y_train_de_biased = []
print("Calculating the new de-biased training set")
for x, aa, y in zip(X_train_embs, aas, y_train):
aa_to_counts[aa] -= 1
X_train_embs_de_biased.append(x)
y_train_de_biased.append(y)
# Break when the less frequent aa class is consumed.
if aa_to_counts[aa] == 0:
break
X_train_embs = X_train_embs_de_biased
y_train = y_train_de_biased
print(f"Fitting classification head: {self.classifier.__class__.__name__}")
self.classifier.fit(X_train_embs, y_train)
return self
def predict(self, an_input: str | tuple[str, str]) -> np.ndarray:
"""
Predicts the paratope by computing embeddings and running a trained classifier on top of them.
Parameters
----------
an_input: an amino acidic sequence
Returns
-------
Predicted probabilities
"""
emb = self.embedder.embed(an_input)[0].to("cpu").numpy()
output = self.classifier.predict_proba(emb)[:, -1]
return output.flatten()
def predict_multiple(self, some_inputs: list[str] | list[tuple[str, str]]) -> list[np.ndarray]:
return [self.predict(inputs) for inputs in some_inputs]
def prepare_dataset(
self,
dataset: pl.DataFrame,
) -> tuple[list[str], list[list[bool]]]:
"""
Prepares a given DataFrame to be consumed.
Parameters
----------
dataset: A DataFrame that has to contain the following columns: "antibody_sequence" and "full_paratope_labels"
Returns
-------
inputs, labels: These are grouped by protein i.e. each element in the inputs is an antibody, and each element
in labels is list of labels for each amino acid of the antibody sequence in the inputs.
"""
inputs = []
pdbs = dataset.get_column("pdb").to_list()
ab_seqs = dataset.get_column("antibody_sequence").to_list()
ag_seqs = dataset.get_column("antigen_sequence").to_list()
labels = dataset.get_column("full_paratope_labels").to_list()
if "ag_aware" in self.name:
for pdb, ab_seq, ag_seq in zip(pdbs, ab_seqs, ag_seqs):
inputs.append(tuple([ab_seq, ag_seq]))
# TODO: implement paired
else:
inputs = ab_seqs
return inputs, labels
class ContactsClassifier(Predictor):
"""
Structure for protein complexes can be computed through the usage of AlphaFold Multimer or ESMFold.-
These precomputed complexes can be labelled according to the SabdabHub.label_dimer, thus making them comparable to
other predictors.
"""
def __init__(self, name: EndToEndPredictorName = EndToEndPredictorName.af2_multimer):
self.name = name
def predict(self, an_input: Path | str) -> np.ndarray:
"""
Provides paratope labels to a predicted structure of a dimer.
Parameters
----------
an_input: a Path to a PDB file.
Returns
-------
The array containing the computed residues that correspond to the paratope of the predicted structure.
"""
df = SabdabHub.label_dimer(
pdb_path=an_input,
chain_1="A",
chain_2="B",
contact_threshold=4.5,
invalid_chains={""},
)
paratope = df.select("paratope_labels").to_numpy().flatten()[0]
return paratope.astype(int).astype(float)
def predict_multiple(self, some_inputs: list[Path | str]) -> list[np.ndarray]:
"""
Parameters
----------
some_inputs: list of PDB file Paths.
Returns
-------
The list of arrays containing the computed residues that correspond to the paratope of the predicted structure.
"""
return [self.predict(an_input) for an_input in some_inputs]
def prepare_dataset(
self,
dataset: pl.DataFrame,
) -> tuple[list[str], list[bool]]:
"""
Prepares a given DataFrame to be consumed.
This is a mock version of a true prepare_dataset, since it loads already computed
pdb files from AF2 Multimer for example, for simplicity.
Consider implementing a true forward pass into a multimer structure prediction model for future use cases.
Parameters
----------
dataset: A DataFrame that has to contain the following columns: "antibody_sequence" and "full_paratope_labels"
Returns
-------
inputs, labels: These are grouped by protein i.e. each element in the inputs is an antibody, and each element
in labels is list of labels for each amino acid of the antibody sequence in the inputs.
"""
inputs = []
labels = dataset.get_column("full_paratope_labels").to_list()
pdbs = dataset.get_column("pdb").to_list()
chain_types = dataset.get_column("chain_type").to_list()
# Overkill, but ensures the order is the same.
# FIXME: find a proper way
def get_pdb_idx(pdbs_paths, _pdb_name):
for i, p_path in enumerate(pdbs_paths):
if _pdb_name.upper() in p_path:
return i
vhag_af = TOPEFIND_PATH / "resources/computed_structures_paragraph_test/vhag/AF_structures"
vlag_af = TOPEFIND_PATH / "resources/computed_structures_paragraph_test/vlag/AF_structures"
pdbs_paths_test_af_h = [str(p) for p in list(vhag_af.glob("*.pdb"))]
pdbs_paths_test_af_l = [str(p) for p in list(vlag_af.glob("*.pdb"))]
for pdb_name, chain_type in zip(pdbs, chain_types):
try:
if chain_type == "heavy":
inputs.append(pdbs_paths_test_af_h[get_pdb_idx(pdbs_paths_test_af_h, pdb_name)])
else:
inputs.append(pdbs_paths_test_af_l[get_pdb_idx(pdbs_paths_test_af_l, pdb_name)])
except TypeError as e:
print(f"You might have not computed some files with AF2, missing: {pdb_name} {chain_type}")
print(e)
return inputs, labels
class Seq2ParatopeCDR(Predictor):
def __init__(self, name: EndToEndPredictorName = EndToEndPredictorName.seq_to_cdr):
self.name = name
def predict(self, an_input: str) -> np.ndarray:
"""
Provides paratope labels by setting as paratope the CDR regions.
Parameters
----------
an_input: an amino acidic sequence of an antibody.
Returns
-------
The array containing the computed residues that correspond to the paratope of the predicted structure.
"""
cdrs, fmks = utils.get_antibody_regions(an_input, scheme="imgt")
paratope = np.zeros(len(fmks[0]))
for cdr, fmk in zip(cdrs, fmks[1:]):
paratope = np.concatenate([paratope, np.ones(len(cdr)), np.zeros(len(fmk))])
return paratope
def predict_multiple(self, some_inputs: list[str]) -> list[np.ndarray]:
"""
Parameters
----------
some_inputs: list of PDB file Paths.
Returns
-------
The list of arrays containing the computed residues that correspond to the paratope of the predicted structure.
"""
return [self.predict(an_input) for an_input in some_inputs]
def prepare_dataset(
self,
dataset: pl.DataFrame,
) -> tuple[list[str], list[bool]]:
"""
Prepares a given DataFrame to be consumed.
Parameters
----------
dataset: A DataFrame that has to contain the following columns: "antibody_sequence" and "full_paratope_labels"
Returns
-------
inputs, labels: These are grouped by protein i.e. each element in the inputs is an antibody, and each element
in labels is list of labels for each amino acid of the antibody sequence in the inputs.
"""
inputs = dataset.get_column("antibody_sequence").to_list()
labels = dataset.get_column("full_paratope_labels").to_list()
return inputs, labels
class AAFrequency(Predictor):
def __init__(
self,
name: EndToEndPredictorName = EndToEndPredictorName.aa_freq,
):
self.name = name
self.aa_to_paratope = {aa: 0 for aa in utils.AAs}
def train(
self,
X: list[str],
y: list[list[bool]]
):
for seq, labs in tqdm(zip(X, y), total=len(X)):
for aa, lab in zip(seq, labs):
if lab:
self.aa_to_paratope[aa] += 1
summed_freqs = sum(list(self.aa_to_paratope.values()))
self.aa_to_paratope = {k: v / summed_freqs for k, v in self.aa_to_paratope.items()}
def predict(self, an_input: str) -> np.ndarray:
return np.array([self.aa_to_paratope[aa] for aa in an_input])
def predict_multiple(self, some_inputs: list[str]) -> list[np.ndarray]:
return [self.predict(an_input) for an_input in some_inputs]
def prepare_dataset(
self,
dataset: pl.DataFrame,
) -> tuple[list[str], list[bool]]:
inputs = dataset.get_column("antibody_sequence").to_list()
labels = dataset.get_column("full_paratope_labels").to_list()
return inputs, labels
class PosFrequency(Predictor):
"""Very ugly coded... please review"""
def __init__(
self,
name: EndToEndPredictorName = EndToEndPredictorName.pos_freq,
):
self.name = name
self.imgt_to_paratope = {imgt: 0 for imgt in utils.VALID_IMGT_IDS}
def train(
self,
X: list[str],
y: list[list[bool]]
):
print("Computing IMGTs")
for seq, labs in tqdm(zip(X, y), total=len(X)):
try:
imgts = utils.get_antibody_numbering(seq)
for imgt, lab in zip(imgts, labs):
if lab:
self.imgt_to_paratope[imgt] += 1
except ValueError:
... # If ANARCI gives a strange IMGT to an AA we don't include that sequence
summed_freqs = sum(list(self.imgt_to_paratope.values()))
self.imgt_to_paratope = {k: v / summed_freqs for k, v in self.imgt_to_paratope.items()}
def predict(self, an_input: str) -> np.ndarray:
imgt_input = utils.get_antibody_numbering(an_input)
return np.array([self.imgt_to_paratope[imgt] for imgt in imgt_input])
def predict_multiple(self, some_inputs: list[str]) -> list[np.ndarray]:
return [self.predict(an_input) for an_input in some_inputs]
def prepare_dataset(
self,
dataset: pl.DataFrame,
) -> tuple[list[str], list[bool]]:
inputs = dataset.get_column("antibody_sequence").to_list()
labels = dataset.get_column("full_paratope_labels").to_list()
return inputs, labels
class AAPosFrequency(Predictor):
"""Very ugly coded... please review, especially the usage of .index()!!!"""
def __init__(
self,
name: EndToEndPredictorName = EndToEndPredictorName.aa_pos_freq,
):
self.name = name
self.avail_aas = list(utils.AAs)
self.avail_imgts = list(utils.VALID_IMGT_IDS)
self.aa_imgt_to_paratope = np.zeros((len(self.avail_imgts), len(self.avail_aas)))
def train(
self,
X: list[str],
y: list[list[bool]]
):
print("Computing IMGTs")
for seq, labs in tqdm(zip(X, y), total=len(X)):
try:
imgts = utils.get_antibody_numbering(seq)
for aa, imgt, lab in zip(seq, imgts, labs):
if lab:
self.aa_imgt_to_paratope[self.avail_imgts.index(imgt), self.avail_aas.index(aa)] += 1
except ValueError:
... # If ANARCI gives a strange IMGT to an AA we don't include that sequence
summed_freqs = self.aa_imgt_to_paratope.sum()
self.aa_imgt_to_paratope /= summed_freqs
def predict(self, an_input: str) -> np.ndarray:
imgt_input = utils.get_antibody_numbering(an_input)
return np.array([
self.aa_imgt_to_paratope[self.avail_imgts.index(imgt), self.avail_aas.index(aa)]
for aa, imgt in zip(an_input, imgt_input)])
def predict_multiple(self, some_inputs: list[str]) -> list[np.ndarray]:
return [self.predict(an_input) for an_input in some_inputs]
def prepare_dataset(
self,
dataset: pl.DataFrame,
) -> tuple[list[str], list[bool]]:
inputs = dataset.get_column("antibody_sequence").to_list()
labels = dataset.get_column("full_paratope_labels").to_list()
return inputs, labels
if __name__ == '__main__':
df_train = pd.read_parquet(
TOPEFIND_PATH.parent / "resources" / "paragraph_train.parquet",
columns=["antibody_sequence", "full_paratope_labels"]
)
df_test = pd.read_parquet(
TOPEFIND_PATH.parent / "resources" / "paragraph_test.parquet",
columns=["antibody_sequence", "full_paratope_labels"]
)
train_seqs = df_train.antibody_sequence.values.tolist()
train_labs = df_train.full_paratope_labels.values.tolist()
test_seqs = df_test.antibody_sequence.values.tolist()
test_labs = df_test.full_paratope_labels.values.tolist()
test_labs = [np.array(t, dtype=int) for t in test_labs]
predictor = AAPosFrequency()
predictor.train(train_seqs, train_labs)
predictions = [predictor.predict(seq) for seq in test_seqs]
y_preds, y_trues = [], []
not_counted = 0
for yp, yt in zip(predictions, test_labs):
if len(yp) == len(yt):
y_preds.append(yp)
y_trues.append(yt)
else:
not_counted += 1
from sklearn.metrics import average_precision_score
print(np.mean([average_precision_score(yt, yp) for yt, yp in zip(y_trues, y_preds)]))
print(f"Not considered: {not_counted}")