Delower commited on
Commit
ee82dfc
·
verified ·
1 Parent(s): fee479a

Upload deployment_common.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. deployment_common.py +380 -0
deployment_common.py ADDED
@@ -0,0 +1,380 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # deployment_common.py — shared code for the liver deployment refits.
2
+ # The tox_common block below is copied VERBATIM from the arms' own notebooks
3
+ # (kaggle/notebooks/liver_arch3_lazypredict.py, shared programme conventions
4
+ # cell), and the graph block (ELEMS / mol_to_graph / GATNet) is copied
5
+ # VERBATIM from kaggle/notebooks/liver_arch2_gat.py. Deployment scripts reuse
6
+ # the arms' exact identity, featurization and model code — no re-implementation.
7
+ import os, json, time
8
+ import numpy as np
9
+ import pandas as pd
10
+
11
+ # ---- shared programme conventions (tox_common, inlined verbatim) ----
12
+ """Shared conventions for the organ-toxicity programme (liver + kidney).
13
+
14
+ Binding rules (PROJECT_SPEC.md + READING_NOTES harmonization protocols):
15
+ - classification ONLY; identity = InChIKey connectivity block (first 14 chars)
16
+ of the RDKit-standardized parent structure (largest fragment).
17
+ - seed-42 scaffold-disjoint (Bemis-Murcko) train/val/test split.
18
+ - preprocessing (imputation / scaling) fit on the TRAIN fold only.
19
+ - regulatory benchmark compounds are NEVER in training; lockout verified = 0
20
+ with the dual key (deposited connectivity UNION standardized-parent
21
+ connectivity) against EACH benchmark file separately.
22
+ - benchmark scoring is reported PER SET (withdrawn / clinical failures /
23
+ pass), never pooled; metrics at full coverage.
24
+ """
25
+ import json
26
+ import numpy as np
27
+ import pandas as pd
28
+
29
+ SEED = 42
30
+
31
+ # ---------------------------------------------------------------- identity
32
+ def _inchi_key(mol):
33
+ """InChIKey via whichever RDKit API the installed build provides.
34
+ DEPLOYMENT COMPATIBILITY FIX (2026-11-15): the arms' verbatim code calls
35
+ rdMolDescriptors.CalcInchiKey, which does not exist in RDKit 2024.03.6 or
36
+ 2026.09.1 (it silently made parent_connectivity return None there).
37
+ rdkit.Chem.inchi.MolToInchiKey is the same InChI computation; verified
38
+ byte-identical keys across both installed RDKit builds on a sample set
39
+ (salts, stereo, charged species)."""
40
+ try:
41
+ from rdkit.Chem import inchi
42
+ return inchi.MolToInchiKey(mol)
43
+ except Exception:
44
+ from rdkit.Chem import rdMolDescriptors
45
+ return rdMolDescriptors.CalcInchiKey(mol)
46
+
47
+
48
+ def parent_connectivity(smiles):
49
+ """Connectivity block of the standardized parent (largest fragment)."""
50
+ try:
51
+ from rdkit import Chem
52
+ from rdkit.Chem.MolStandardize import rdMolStandardize
53
+ if smiles is None or (isinstance(smiles, float) and np.isnan(smiles)):
54
+ return None
55
+ mol = Chem.MolFromSmiles(str(smiles))
56
+ if mol is None:
57
+ return None
58
+ parent = rdMolStandardize.LargestFragmentChooser().choose(mol)
59
+ ik = _inchi_key(parent)
60
+ return ik[:14] if ik else None
61
+ except Exception:
62
+ return None
63
+
64
+
65
+ def deposited_connectivity(inchikey):
66
+ if inchikey is None or (isinstance(inchikey, float) and np.isnan(inchikey)):
67
+ return None
68
+ s = str(inchikey).strip()
69
+ return s[:14] if len(s) >= 14 else None
70
+
71
+
72
+ def dual_keys(df, smiles_col="canonical_smiles", inchikey_col="inchikey"):
73
+ """Set of connectivity keys: deposited UNION standardized-parent."""
74
+ keys = set()
75
+ dep = df[inchikey_col].map(deposited_connectivity) if inchikey_col in df else pd.Series([None] * len(df))
76
+ par = df[smiles_col].map(parent_connectivity)
77
+ for a, b in zip(dep, par):
78
+ if a:
79
+ keys.add(a)
80
+ if b:
81
+ keys.add(b)
82
+ return keys
83
+
84
+
85
+ def verify_lockout(train_df, bench_dfs, train_smiles="canonical_smiles"):
86
+ """bench_dfs: dict name -> df (with 'smiles' + 'inchikey' columns).
87
+ Returns dict of overlap counts; every count must be 0."""
88
+ train_keys = dual_keys(train_df, smiles_col=train_smiles)
89
+ out = {}
90
+ for name, bdf in bench_dfs.items():
91
+ bk = dual_keys(bdf, smiles_col="smiles")
92
+ out[name] = len(train_keys & bk)
93
+ return out
94
+
95
+
96
+ # ---------------------------------------------------------------- loading
97
+ def load_train(path):
98
+ df = pd.read_csv(path)
99
+ df = df.rename(columns={"canonical_smiles": "smiles"})
100
+ df["label"] = df["final_label"].astype(int)
101
+ df["name"] = df["drug_name"] if "drug_name" in df else ""
102
+ df["conn"] = df["inchikey_connectivity"]
103
+ keep = ["name", "smiles", "inchikey", "conn", "label"]
104
+ for c in ["sources", "sources_present", "final_label_source"]:
105
+ if c in df.columns:
106
+ keep.append(c)
107
+ return df[keep].reset_index(drop=True)
108
+
109
+
110
+ def load_benchmark(path, expected_label):
111
+ df = pd.read_csv(path)
112
+ name_col = "drug_name" if "drug_name" in df.columns else "compound_name"
113
+ out = pd.DataFrame({
114
+ "name": df[name_col],
115
+ "smiles": df["smiles"] if "smiles" in df else None,
116
+ "inchikey": df["inchikey"] if "inchikey" in df else None,
117
+ })
118
+ if "evidence_grade" in df.columns:
119
+ out["evidence_grade"] = df["evidence_grade"]
120
+ out["label"] = expected_label
121
+ return out
122
+
123
+
124
+ def dedup_benchmark(df):
125
+ """Dedup benchmark rows to unique compounds (deposited connectivity,
126
+ falling back to standardized-parent connectivity). Rows with no usable
127
+ structure are counted as unscored."""
128
+ keys, keep_idx, unscored = {}, [], 0
129
+ for i, row in df.iterrows():
130
+ k = deposited_connectivity(row.get("inchikey")) or parent_connectivity(row.get("smiles"))
131
+ if k is None:
132
+ unscored += 1
133
+ continue
134
+ if k in keys:
135
+ continue
136
+ keys[k] = True
137
+ keep_idx.append(i)
138
+ out = df.loc[keep_idx].copy()
139
+ out["conn"] = [deposited_connectivity(r.get("inchikey")) or parent_connectivity(r.get("smiles"))
140
+ for _, r in out.iterrows()]
141
+ return out.reset_index(drop=True), unscored
142
+
143
+
144
+ # ---------------------------------------------------------------- split
145
+ def scaffold_split(df, seed=SEED, fracs=(0.80, 0.10, 0.10)):
146
+ """Seed-42 Bemis-Murcko scaffold-disjoint train/val/test split."""
147
+ from rdkit import Chem
148
+ from rdkit.Chem.Scaffolds import MurckoScaffold
149
+ rng = np.random.RandomState(seed)
150
+ scaffolds = []
151
+ for smi in df["smiles"]:
152
+ mol = Chem.MolFromSmiles(str(smi))
153
+ try:
154
+ scaf = MurckoScaffold.MurckoScaffoldSmiles(mol=mol) if mol is not None else ""
155
+ except Exception:
156
+ scaf = ""
157
+ scaffolds.append(scaf if scaf else f"ACYCLIC::{smi}")
158
+ groups = {}
159
+ for i, s in enumerate(scaffolds):
160
+ groups.setdefault(s, []).append(i)
161
+ group_list = list(groups.values())
162
+ rng.shuffle(group_list)
163
+ group_list.sort(key=len, reverse=True)
164
+ n = len(df)
165
+ targets = [f * n for f in fracs]
166
+ buckets = [[], [], []]
167
+ counts = [0, 0, 0]
168
+ for g in group_list:
169
+ # assign each scaffold group to the bucket furthest below its target
170
+ j = int(np.argmax([targets[k] - counts[k] for k in range(3)]))
171
+ buckets[j].extend(g)
172
+ counts[j] += len(g)
173
+ names = ["train", "val", "test"]
174
+ split = pd.Series(index=df.index, dtype=object)
175
+ for j, idxs in enumerate(buckets):
176
+ split.iloc[idxs] = names[j]
177
+ # scaffold disjointness assertion
178
+ seen = {}
179
+ for j, idxs in enumerate(buckets):
180
+ for i in idxs:
181
+ s = scaffolds[i]
182
+ assert seen.get(s, j) == j, "scaffold leaked across splits"
183
+ seen[s] = j
184
+ return split
185
+
186
+
187
+ # ---------------------------------------------------------------- features
188
+ PHYSCHEM_NAMES = ["MolWt", "MolLogP", "TPSA", "NumHDonors", "NumHAcceptors",
189
+ "NumRotatableBonds", "RingCount", "NumAromaticRings",
190
+ "NumAliphaticRings", "FractionCSP3", "HeavyAtomCount",
191
+ "NumValenceElectrons", "BertzCT"]
192
+
193
+
194
+ def featurize(smiles_list):
195
+ """Returns dict of float32 blocks + validity mask. Blocks:
196
+ morgan_bits (1024), morgan_counts (1024), maccs (167),
197
+ desc (full RDKit descriptor list), physchem (PHYSCHEM_NAMES subset)."""
198
+ from rdkit import Chem
199
+ from rdkit.Chem import AllChem, MACCSkeys, Descriptors
200
+ from rdkit import RDLogger
201
+ RDLogger.DisableLog("rdApp.*")
202
+ desc_names = [d[0] for d in Descriptors._descList]
203
+ phys_idx = [desc_names.index(n) for n in PHYSCHEM_NAMES]
204
+ n = len(smiles_list)
205
+ blocks = {
206
+ "morgan_bits": np.zeros((n, 1024), dtype=np.float32),
207
+ "morgan_counts": np.zeros((n, 1024), dtype=np.float32),
208
+ "maccs": np.zeros((n, 167), dtype=np.float32),
209
+ "desc": np.full((n, len(desc_names)), np.nan, dtype=np.float32),
210
+ }
211
+ valid = np.zeros(n, dtype=bool)
212
+ from rdkit import DataStructs
213
+ gen_bits = AllChem.GetMorganGenerator(radius=2, fpSize=1024)
214
+ gen_counts = AllChem.GetMorganGenerator(radius=2, fpSize=1024, countSimulation=True)
215
+ for i, smi in enumerate(smiles_list):
216
+ mol = Chem.MolFromSmiles(str(smi)) if smi is not None and str(smi) != "nan" else None
217
+ if mol is None:
218
+ continue
219
+ valid[i] = True
220
+ DataStructs.ConvertToNumpyArray(gen_bits.GetFingerprint(mol), blocks["morgan_bits"][i])
221
+ DataStructs.ConvertToNumpyArray(gen_counts.GetCountFingerprint(mol), blocks["morgan_counts"][i])
222
+ blocks["maccs"][i] = np.asarray(MACCSkeys.GenMACCSKeys(mol), dtype=np.float32)
223
+ # iterate _descList directly: identical values to CalcMolDescriptors
224
+ # at ~1/3 the cost (measured on this VM, RDKit 2026.09)
225
+ blocks["desc"][i] = np.array([fn(mol) for _, fn in Descriptors._descList], dtype=np.float32)
226
+ blocks["physchem"] = blocks["desc"][:, phys_idx].copy()
227
+ blocks["desc_names"] = desc_names
228
+ return blocks, valid
229
+
230
+
231
+ class DescPrep:
232
+ """Train-fold-fitted descriptor preprocessing: drop columns >50% missing
233
+ or near-constant ON TRAIN, median-impute, clip to train 0.1/99.9 pct,
234
+ standardize with train mean/std."""
235
+
236
+ def fit(self, X):
237
+ X = np.asarray(X, dtype=np.float64)
238
+ miss = np.mean(~np.isfinite(X), axis=0)
239
+ std = np.nanstd(np.where(np.isfinite(X), X, np.nan), axis=0)
240
+ self.keep_ = (miss <= 0.5) & (std > 1e-8)
241
+ Xk = X[:, self.keep_]
242
+ self.med_ = np.nanmedian(np.where(np.isfinite(Xk), Xk, np.nan), axis=0)
243
+ Xi = np.where(np.isfinite(Xk), Xk, self.med_)
244
+ self.lo_ = np.percentile(Xi, 0.1, axis=0)
245
+ self.hi_ = np.percentile(Xi, 99.9, axis=0)
246
+ Xc = np.clip(Xi, self.lo_, self.hi_)
247
+ self.mu_ = Xc.mean(axis=0)
248
+ self.sd_ = Xc.std(axis=0) + 1e-9
249
+ return self
250
+
251
+ def transform(self, X):
252
+ X = np.asarray(X, dtype=np.float64)[:, self.keep_]
253
+ Xi = np.where(np.isfinite(X), X, self.med_)
254
+ return ((np.clip(Xi, self.lo_, self.hi_) - self.mu_) / self.sd_).astype(np.float32)
255
+
256
+
257
+ def prep_matrix(blocks, prep, kind):
258
+ """kind: 'fp' (morgan bits) / 'fp_desc' (bits+maccs+desc) /
259
+ 'desc_maccs_counts' (arch-5 block b) / 'physchem' raw physchem."""
260
+ if kind == "fp":
261
+ return blocks["morgan_bits"]
262
+ if kind == "fp_desc":
263
+ return np.hstack([blocks["morgan_bits"], blocks["maccs"], prep.transform(blocks["desc"])]).astype(np.float32)
264
+ if kind == "desc_maccs_counts":
265
+ return np.hstack([prep.transform(blocks["desc"]), blocks["maccs"], blocks["morgan_counts"]]).astype(np.float32)
266
+ if kind == "physchem":
267
+ return blocks["physchem"]
268
+ raise ValueError(kind)
269
+
270
+
271
+ # ---------------------------------------------------------------- metrics
272
+ def metrics_dict(y_true, prob, threshold=0.5):
273
+ from sklearn.metrics import (accuracy_score, balanced_accuracy_score,
274
+ matthews_corrcoef, roc_auc_score, confusion_matrix)
275
+ y_true = np.asarray(y_true, dtype=int)
276
+ prob = np.asarray(prob, dtype=float)
277
+ pred = (prob >= threshold).astype(int)
278
+ out = {"n": int(len(y_true)), "threshold": threshold,
279
+ "accuracy": float(accuracy_score(y_true, pred)),
280
+ "balanced_accuracy": float(balanced_accuracy_score(y_true, pred))}
281
+ tn, fp, fn, tp = confusion_matrix(y_true, pred, labels=[0, 1]).ravel()
282
+ out.update({"tn": int(tn), "fp": int(fp), "fn": int(fn), "tp": int(tp),
283
+ "sensitivity_recall_pos": float(tp / (tp + fn)) if (tp + fn) else None,
284
+ "specificity_recall_neg": float(tn / (tn + fp)) if (tn + fp) else None})
285
+ if len(np.unique(y_true)) == 2 and len(np.unique(pred)) == 2:
286
+ out["mcc"] = float(matthews_corrcoef(y_true, pred))
287
+ else:
288
+ out["mcc"] = None
289
+ out["mcc_note"] = "single-class ground truth or single-class predictions"
290
+ if len(np.unique(y_true)) == 2:
291
+ out["auroc"] = float(roc_auc_score(y_true, prob))
292
+ else:
293
+ out["auroc"] = None
294
+ return out
295
+
296
+
297
+ def score_benchmark_sets(predict_proba_fn, bench_sets):
298
+ """bench_sets: dict name -> deduped df (with 'smiles','label','name').
299
+ predict_proba_fn(smiles_list) -> P(label=1) array (NaN where unparseable).
300
+ Returns (metrics dict per set, predictions dataframe)."""
301
+ all_metrics, pred_frames = {}, []
302
+ for set_name, bdf in bench_sets.items():
303
+ prob = predict_proba_fn(list(bdf["smiles"]))
304
+ scored = np.isfinite(prob)
305
+ m = metrics_dict(bdf.loc[scored, "label"], prob[scored]) if scored.any() else {"n": 0}
306
+ m["n_rows_unique"] = int(len(bdf))
307
+ m["n_scored"] = int(scored.sum())
308
+ m["n_unscored_invalid_structure"] = int((~scored).sum())
309
+ all_metrics[set_name] = m
310
+ pf = bdf[["name", "smiles", "label"]].copy()
311
+ if "evidence_grade" in bdf.columns:
312
+ pf["evidence_grade"] = bdf["evidence_grade"]
313
+ pf["set"] = set_name
314
+ pf["prob_toxic"] = prob
315
+ pf["pred_label"] = np.where(scored, (prob >= 0.5).astype(float), np.nan)
316
+ pf["correct"] = np.where(scored, (pf["pred_label"] == pf["label"]).astype(float), np.nan)
317
+ pred_frames.append(pf)
318
+ return all_metrics, pd.concat(pred_frames, ignore_index=True)
319
+
320
+ # ---- GAT graph code (verbatim from liver_arch2_gat.py) ----
321
+ # Import guard (deployment plumbing only, model code below unchanged): the
322
+ # sklearn-side deployment scripts import this module in an env without
323
+ # torch_geometric; the graph functions are only called in the pyg env.
324
+ try:
325
+ import torch
326
+ import torch.nn.functional as F
327
+ from torch_geometric.data import Data
328
+ from torch_geometric.nn import GATConv, global_mean_pool
329
+ _TORCH_OK = True
330
+ except ImportError:
331
+ torch = None
332
+ _TORCH_OK = False
333
+
334
+ ELEMS = [6, 7, 8, 16, 9, 17, 35, 53, 15, 14]
335
+ def mol_to_graph(smi):
336
+ from rdkit import Chem
337
+ HYB = [Chem.rdchem.HybridizationType.SP, Chem.rdchem.HybridizationType.SP2,
338
+ Chem.rdchem.HybridizationType.SP3, Chem.rdchem.HybridizationType.SP3D,
339
+ Chem.rdchem.HybridizationType.SP3D2]
340
+ BOND = {Chem.rdchem.BondType.SINGLE: 0, Chem.rdchem.BondType.DOUBLE: 1,
341
+ Chem.rdchem.BondType.TRIPLE: 2, Chem.rdchem.BondType.AROMATIC: 3}
342
+ def oh(v, n):
343
+ o = [0.0] * n; o[min(max(v, 0), n - 1)] = 1.0; return o
344
+ mol = Chem.MolFromSmiles(str(smi)) if smi is not None and str(smi) != "nan" else None
345
+ if mol is None or mol.GetNumAtoms() == 0:
346
+ return None
347
+ xs = []
348
+ for a in mol.GetAtoms():
349
+ z = a.GetAtomicNum()
350
+ f = oh(ELEMS.index(z) if z in ELEMS else len(ELEMS), len(ELEMS) + 1)
351
+ f += oh(a.GetDegree(), 6)
352
+ f += oh(a.GetFormalCharge() + 2, 5)
353
+ f += oh(a.GetTotalNumHs(), 5)
354
+ f += oh(HYB.index(a.GetHybridization()) if a.GetHybridization() in HYB else 5, 6)
355
+ f += [1.0 if a.GetIsAromatic() else 0.0, 1.0 if a.IsInRing() else 0.0]
356
+ xs.append(f)
357
+ ei, ea = [], []
358
+ for b in mol.GetBonds():
359
+ i, j = b.GetBeginAtomIdx(), b.GetEndAtomIdx()
360
+ t = BOND.get(b.GetBondType(), 0)
361
+ ei += [[i, j], [j, i]]; ea += [oh(t, 4), oh(t, 4)]
362
+ return Data(x=torch.tensor(xs, dtype=torch.float),
363
+ edge_index=torch.tensor(ei, dtype=torch.long).t().contiguous() if ei else torch.empty((2, 0), dtype=torch.long),
364
+ edge_attr=torch.tensor(ea, dtype=torch.float) if ea else torch.empty((0, 4)))
365
+
366
+ if _TORCH_OK:
367
+ class GATNet(torch.nn.Module):
368
+ def __init__(self, in_dim, hidden, dropout):
369
+ super().__init__()
370
+ self.c1 = GATConv(in_dim, hidden, heads=4, dropout=dropout, edge_dim=4)
371
+ self.c2 = GATConv(hidden * 4, hidden, heads=1, dropout=dropout, edge_dim=4)
372
+ self.head = torch.nn.Sequential(torch.nn.Linear(hidden, hidden // 2), torch.nn.ReLU(),
373
+ torch.nn.Dropout(dropout), torch.nn.Linear(hidden // 2, 1))
374
+ self.dropout = dropout
375
+ def forward(self, data):
376
+ x = F.elu(self.c1(data.x, data.edge_index, data.edge_attr))
377
+ x = F.dropout(x, p=self.dropout, training=self.training)
378
+ x = F.elu(self.c2(x, data.edge_index, data.edge_attr))
379
+ x = global_mean_pool(x, data.batch)
380
+ return self.head(x).ravel()