"""Inference core for the DPP-4 Kd LTN app. Model: tuned LTN (Logic Tensor Network style MLP) for DPP-4 binding affinity (Kd) prediction, from the DPP-4 Kd transfer suite. - Features (identical to the training code, code/kd_common.py): Morgan fingerprint (radius 2, 2048 bits) + ESM-2 650M protein embedding of the target (1280 dims) = 3,328 inputs. The target is fixed to human DPP-4 (UniProt P27487 / ChEMBL CHEMBL284); its ESM-2 vector is computed once and bundled in dpp4_esm2.npz. - Architecture (code/train_kd_ltn.py): trunk 768-384-192 (GELU, dropout 0.1), regression head -> predicted pKd. The potency class is the band of the predicted pKd, exactly as in the suite's external-test grid: potent pKd >= 7, moderate 6-7, weak < 6. - Training: stage 1 pre-trained on the all-target Kd corpus (86,569 compound-target rows), stage 2 fine-tuned on DPP-4 Ki (555 compounds). The 15 DPP-4 Kd compounds were never trained on; on that external set the model scores RMSE 1.604 / MAE 1.276 / class accuracy 0.867. Outputs per compound: predicted pKd, Kd (nM) = 10^(9 - pKd), deltaG (kcal/mol) = -1.3642 * pKd (RT*ln10 at 298.15 K), potency class. """ import os import numpy as np import torch import torch.nn as nn HERE = os.path.dirname(os.path.abspath(__file__)) WEIGHTS = os.path.join(HERE, "kd_ltn_stage2.pt") ESM_NPZ = os.path.join(HERE, "dpp4_esm2.npz") DPP4_KEY = "ChEMBL:CHEMBL284" # human DPP-4, UniProt P27487 IN_DIM = 3328 # 2048 Morgan FP + 1280 ESM-2 class LtnNet(nn.Module): """Identical to train_kd_ltn.py's LtnNet.""" def __init__(self, in_dim): super().__init__() self.trunk = nn.Sequential( nn.Linear(in_dim, 768), nn.GELU(), nn.Dropout(0.1), nn.Linear(768, 384), nn.GELU(), nn.Dropout(0.1), nn.Linear(384, 192), nn.GELU()) self.reg = nn.Linear(192, 1) self.clf = nn.Linear(192, 3) def forward(self, x): h = self.trunk(x) return self.reg(h).squeeze(-1), self.clf(h) def load_esm_vector(): z = np.load(ESM_NPZ, allow_pickle=True) keys = z["target_keys"].tolist() vec = z["embeddings"][keys.index(DPP4_KEY)].astype(np.float32) assert vec.shape == (1280,), vec.shape return vec def load_model(): net = LtnNet(IN_DIM) state = torch.load(WEIGHTS, map_location="cpu") net.load_state_dict(state) net.eval() return net def class_of(pkd): return "potent" if pkd >= 7.0 else ("moderate" if pkd >= 6.0 else "weak") def featurize(smiles, esm_vec): """Morgan FP (r=2, 2048) ++ DPP-4 ESM-2 vector. None if SMILES invalid.""" from rdkit import Chem from rdkit.Chem import rdFingerprintGenerator mol = Chem.MolFromSmiles(smiles) if mol is None: return None gen = rdFingerprintGenerator.GetMorganGenerator(radius=2, fpSize=2048) fp = np.asarray(gen.GetFingerprint(mol), dtype=np.float32) return np.concatenate([fp, esm_vec]).astype(np.float32) @torch.no_grad() def predict_pkd(net, X): return net(torch.tensor(np.stack(X)))[0].cpu().numpy() def result_row(smiles, pkd): return { "smiles": smiles, "predicted_pKd": round(float(pkd), 4), "predicted_Kd_nM": round(float(10 ** (9 - pkd)), 4), "predicted_deltaG_kcal_mol": round(float(-1.3642 * pkd), 3), "predicted_class": class_of(float(pkd)), "status": "ok", } def predict_smiles_list(net, esm_vec, smiles_list): """One result dict per input SMILES; invalid SMILES are flagged, not fatal.""" feats, rows = [], [] for s in smiles_list: x = featurize(str(s).strip(), esm_vec) if s is not None else None if x is None: rows.append({"smiles": s, "predicted_pKd": None, "predicted_Kd_nM": None, "predicted_deltaG_kcal_mol": None, "predicted_class": None, "status": "invalid_smiles"}) else: feats.append((len(rows), x)) rows.append(None) if feats: preds = predict_pkd(net, [x for _, x in feats]) for (i, _), p in zip(feats, preds): rows[i] = result_row(smiles_list[i], p) return rows