openadmet-physics 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,28 @@
1
+ """OpenADMET-PhysNet: Zero-leakage physics-grounded ADMET drug safety & metabolism engine."""
2
+
3
+ from __future__ import annotations
4
+
5
+ __version__ = "0.1.0"
6
+
7
+ from .curate_datasets import canonical_connectivity, canonicalize_smiles, inchi_key14
8
+ from .featurizers import smiles_to_maplight_fp, smiles_to_morgan_fp, smiles_to_rdkit2d_mqn
9
+ from .metrics_and_stats import bootstrap_ci, compute_metric, paired_bootstrap_test, st_rae
10
+ from .physics_features import compute_physics_dataframe, featurize_single_smiles
11
+ from .predict_cli import mechanistic_flags
12
+
13
+ __all__ = [
14
+ "__version__",
15
+ "bootstrap_ci",
16
+ "canonical_connectivity",
17
+ "canonicalize_smiles",
18
+ "compute_metric",
19
+ "compute_physics_dataframe",
20
+ "featurize_single_smiles",
21
+ "inchi_key14",
22
+ "mechanistic_flags",
23
+ "paired_bootstrap_test",
24
+ "smiles_to_maplight_fp",
25
+ "smiles_to_morgan_fp",
26
+ "smiles_to_rdkit2d_mqn",
27
+ "st_rae",
28
+ ]
@@ -0,0 +1,188 @@
1
+ #!/usr/bin/env python3
2
+ """Hill-Equation Selection-Bias Correction for OpenADMET CYP Inhibition & TDI Training Splits.
3
+
4
+ Scientific Rationale:
5
+ In `openadmet/cyp-challenge-train-test`, full 8-point dose-response curves
6
+ (`cyp-challenge-TRAIN_inhibition.csv` & `cyp-challenge-TRAIN_TDI.csv`) were primarily
7
+ triggered only for single-concentration hits (e.g., 0 compounds with log2fc >= -0.5
8
+ in CYP2D6 DRC train, vs ~60% inactive compounds in the blind test set).
9
+ OpenADMET officially released `cyp-challenge-single-concentration-TRAIN.csv` (4,376
10
+ training molecules screened at 49.5 uM across all 4 isoforms; 0 overlap with test!)
11
+ specifically so models can observe true single-concentration inactives.
12
+
13
+ Strictly Zero-Leakage Implementation:
14
+ 1. Verifies exact 0 canonical & connectivity SMILES overlap between
15
+ `cyp-challenge-single-concentration-TRAIN.csv` and both blind test splits.
16
+ 2. Fits a 3-parameter physical Hill isotherm (`log2fc_estimate -> pIC50`) per enzyme
17
+ STRICTLY on overlapping TRAIN DRC compounds (never touching test labels).
18
+ 3. Imputes ONLY missing (`NaN`) training entries in `cyp_inhibition_train.parquet`
19
+ for compounds already present in `cyp_inhibition_train.parquet` with lower
20
+ precision weight (`std = 0.55`), assigning the physical censored assay floor
21
+ (`pIC50 = 2.15`) to FDR-insignificant non-inhibitors (`log2fc_fdr > 0.05` or
22
+ `log2fc_estimate >= -0.15`).
23
+ 4. Imputes ONLY missing (`NaN`) training entries in `cyp_tdi_train.parquet` for
24
+ confirmed non-binding single-concentration inactives (`log2fc_fdr > 0.05` or
25
+ `log2fc_estimate >= -0.15`) as `is_TDI = 0.0`.
26
+ """
27
+ from __future__ import annotations
28
+
29
+ import json
30
+ import urllib.request
31
+ from pathlib import Path
32
+
33
+ import numpy as np
34
+ import pandas as pd
35
+ from scipy.optimize import minimize
36
+
37
+ from .curate_datasets import canonical_connectivity, canonicalize_smiles, inchi_key14
38
+
39
+ ROOT = Path(__file__).resolve().parents[2]
40
+ RAW = ROOT / "data" / "raw" / "openadmet"
41
+ CUR = ROOT / "data" / "curated" / "openadmet"
42
+
43
+ CONC_M = 49.5049505e-6
44
+ PC = float(-np.log10(CONC_M)) # 4.30535
45
+ ASSAY_FLOOR_PIC50 = 2.15
46
+
47
+
48
+ def pred_hill(params: np.ndarray, l2fc: np.ndarray) -> np.ndarray:
49
+ b, delta, slope = params
50
+ frac_inh = np.clip(1.0 - 2.0 ** (slope * (l2fc - b)), 0.004, 0.996)
51
+ return np.clip(PC + np.log10(frac_inh / (1.0 - frac_inh)) + delta, ASSAY_FLOOR_PIC50, 7.0)
52
+
53
+
54
+ def main():
55
+ sc_p = RAW / "cyp_single_conc_train.csv"
56
+ if not sc_p.exists():
57
+ url = "https://huggingface.co/datasets/openadmet/cyp-challenge-train-test/resolve/main/cyp-challenge-single-concentration-TRAIN.csv"
58
+ urllib.request.urlretrieve(url, sc_p)
59
+
60
+ sc = pd.read_csv(sc_p)
61
+ parsed = [canonicalize_smiles(s) for s in sc["SMILES"]]
62
+ sc["can_smiles"] = [p[0] for p in parsed]
63
+ sc["conn_smiles"] = [canonical_connectivity(s) if s else None for s in sc["can_smiles"]]
64
+ sc = sc[sc["can_smiles"].notna()].copy()
65
+
66
+ # Load existing curated train & test splits
67
+ tr_inh = pd.read_parquet(CUR / "cyp_inhibition_train.parquet")
68
+ te_inh = pd.read_parquet(CUR / "cyp_inhibition_test.parquet")
69
+ tr_tdi = pd.read_parquet(CUR / "cyp_tdi_train.parquet")
70
+ te_tdi = pd.read_parquet(CUR / "cyp_tdi_test.parquet")
71
+
72
+ # Strict zero-leakage assertion against BOTH blind test sets (can + conn + InChIKey-14)
73
+ te_conn = set(te_inh["conn_smiles"].dropna()) | set(te_tdi["conn_smiles"].dropna())
74
+ te_can = set(te_inh["can_smiles"].dropna()) | set(te_tdi["can_smiles"].dropna())
75
+ te_ik14 = ({inchi_key14(s) for s in te_can} | {inchi_key14(s) for s in te_conn}) - {None}
76
+ sc_ik14 = ({inchi_key14(s) for s in sc["can_smiles"].dropna()} | {inchi_key14(s) for s in sc["conn_smiles"].dropna()}) - {None}
77
+ ov_conn = int(sc["conn_smiles"].isin(te_conn).sum())
78
+ ov_can = int(sc["can_smiles"].isin(te_can).sum())
79
+ ov_ik14 = len(sc_ik14 & te_ik14)
80
+ assert ov_conn == 0 and ov_can == 0 and ov_ik14 == 0, f"Leakage detected between single-conc TRAIN and test: {ov_can}/{ov_conn}/{ov_ik14}"
81
+
82
+ # Backup original DRC-only train files if not already backed up
83
+ raw_inh_bak = CUR / "cyp_inhibition_train_drc_only.parquet"
84
+ raw_tdi_bak = CUR / "cyp_tdi_train_drc_only.parquet"
85
+ if not raw_inh_bak.exists():
86
+ tr_inh.to_parquet(raw_inh_bak, index=False)
87
+ else:
88
+ tr_inh = pd.read_parquet(raw_inh_bak)
89
+ if not raw_tdi_bak.exists():
90
+ tr_tdi.to_parquet(raw_tdi_bak, index=False)
91
+ else:
92
+ tr_tdi = pd.read_parquet(raw_tdi_bak)
93
+
94
+ report = {
95
+ "source": "openadmet/cyp-challenge-train-test/cyp-challenge-single-concentration-TRAIN.csv",
96
+ "screening_conc_uM": 49.5,
97
+ "test_canonical_overlap": ov_can,
98
+ "test_connectivity_overlap": ov_conn,
99
+ "test_ik14_overlap": ov_ik14,
100
+ "inhibition_calibration": {},
101
+ "tdi_inactive_imputation": {},
102
+ }
103
+
104
+ # 1. Calibrate & fill missing training pIC50 entries in cyp_inhibition_train
105
+ for enz in ("CYP1A2", "CYP2C9", "CYP2D6", "CYP3A4"):
106
+ col = f"{enz}_pIC50_direct_inhibition"
107
+ std_col = f"{enz}_pIC50_direct_inhibition_std"
108
+ sub = (
109
+ sc[sc["enzyme"] == enz]
110
+ .groupby("can_smiles", as_index=False)
111
+ .agg({"log2fc_estimate": "median", "log2fc_fdr": "min"})
112
+ )
113
+ m = tr_inh[["can_smiles", col]].dropna().merge(sub, on="can_smiles")
114
+ l2_fit = m["log2fc_estimate"].values.astype(float)
115
+ y_fit = m[col].values.astype(float)
116
+ res = minimize(
117
+ lambda p: float(np.mean(np.abs(y_fit - pred_hill(p, l2_fit)))),
118
+ x0=np.array([0.0, 0.0, 1.0]),
119
+ bounds=[(-0.5, 0.8), (-1.5, 1.5), (0.4, 2.0)],
120
+ method="L-BFGS-B",
121
+ )
122
+ fit_mae = float(np.mean(np.abs(y_fit - pred_hill(res.x, l2_fit))))
123
+
124
+ # Build lookup of calibrated single-conc pIC50
125
+ sc_vals = pred_hill(res.x, sub["log2fc_estimate"].values.astype(float))
126
+ # Enforce physical assay detection floor for FDR-insignificant / non-inhibiting compounds
127
+ is_inactive = (sub["log2fc_fdr"].values > 0.05) | (sub["log2fc_estimate"].values >= -0.15)
128
+ sc_vals = np.where(is_inactive, ASSAY_FLOOR_PIC50, sc_vals)
129
+ sc_map = dict(zip(sub["can_smiles"].tolist(), sc_vals.tolist()))
130
+
131
+ n_before = int(tr_inh[col].notna().sum())
132
+ miss_mask = tr_inh[col].isna() & tr_inh["can_smiles"].isin(sc_map)
133
+ n_filled = int(miss_mask.sum())
134
+ tr_inh.loc[miss_mask, col] = tr_inh.loc[miss_mask, "can_smiles"].map(sc_map).values
135
+ if std_col in tr_inh.columns:
136
+ # Soft precision downweight (std=0.55 -> w ~ 0.29 vs w ~ 0.90 for sharp DRC curves)
137
+ tr_inh.loc[miss_mask, std_col] = 0.55
138
+
139
+ report["inhibition_calibration"][enz] = {
140
+ "n_drc_before": n_before,
141
+ "n_single_conc_imputed": n_filled,
142
+ "n_total_after": int(tr_inh[col].notna().sum()),
143
+ "hill_params_b_delta_slope": [round(float(x), 4) for x in res.x],
144
+ "train_drc_hill_fit_mae": round(fit_mae, 4),
145
+ "post_train_median_pIC50": round(float(tr_inh[col].median()), 3),
146
+ }
147
+ print(
148
+ f"[HILL-CAL] {enz}: DRC={n_before} + SC_imputed={n_filled} -> total={int(tr_inh[col].notna().sum())} | "
149
+ f"fit_MAE={fit_mae:.3f} | new_train_median={tr_inh[col].median():.2f}"
150
+ )
151
+
152
+ # 2. Fill missing confirmed single-conc non-binders as is_TDI = 0 in cyp_tdi_train
153
+ for enz in ("CYP2D6", "CYP3A4"):
154
+ col = f"{enz}_is_TDI"
155
+ sub = (
156
+ sc[sc["enzyme"] == enz]
157
+ .groupby("can_smiles", as_index=False)
158
+ .agg({"log2fc_estimate": "median", "log2fc_fdr": "min"})
159
+ )
160
+ inactive_set = set(
161
+ sub.loc[(sub["log2fc_fdr"] > 0.05) | (sub["log2fc_estimate"] >= -0.15), "can_smiles"].tolist()
162
+ )
163
+ n_before = int(tr_tdi[col].notna().sum())
164
+ pos_before = float(tr_tdi[col].mean())
165
+ miss_inact = tr_tdi[col].isna() & tr_tdi["can_smiles"].isin(inactive_set)
166
+ n_filled = int(miss_inact.sum())
167
+ tr_tdi.loc[miss_inact, col] = 0.0
168
+ report["tdi_inactive_imputation"][enz] = {
169
+ "n_before": n_before,
170
+ "pos_rate_before": round(pos_before, 4),
171
+ "n_confirmed_inactive_imputed": n_filled,
172
+ "n_after": int(tr_tdi[col].notna().sum()),
173
+ "pos_rate_after": round(float(tr_tdi[col].mean()), 4),
174
+ }
175
+ print(
176
+ f"[TDI-DEBIAS] {enz}: n={n_before} (pos={pos_before:.3f}) + inactive_0={n_filled} -> "
177
+ f"n={int(tr_tdi[col].notna().sum())} (pos={tr_tdi[col].mean():.3f})"
178
+ )
179
+
180
+ tr_inh.to_parquet(CUR / "cyp_inhibition_train.parquet", index=False)
181
+ tr_tdi.to_parquet(CUR / "cyp_tdi_train.parquet", index=False)
182
+ out_j = ROOT / "data" / "curated" / "openadmet_cyp_hill_calibration.json"
183
+ out_j.write_text(json.dumps(report, indent=2))
184
+ print(f"Saved Hill calibration audit -> {out_j}")
185
+
186
+
187
+ if __name__ == "__main__":
188
+ main()