File size: 4,362 Bytes
568a378
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Standalone inference for the hERG Phase-5 XGBoost models (Delower/herg-xgboost).

Takes SMILES, builds the exact Phase-5 feature blocks with feature_extraction.py,
applies the fitted preprocessing stored inside each model pickle (fold-fitted
ContPrep states: column keep-mask, median imputation, standardisation; log1p for
count blocks), and predicts with the XGBoost model stored in the same pickle.

Usage:
  python predict_herg.py --model models/<cls_scaffold.pkl> "CCOc1ccc..." [...]
  python predict_herg.py --model models/<reg_scaffold.pkl> --csv compounds.csv
      (CSV must have a 'smiles' column; output adds pred_pIC50 / prob_blocker)

Classification pickles output blocker probability at the locked 10 uM cutoff
(call = prob >= 0.5). Regression pickles output predicted pIC50
(derived 10 uM call = pIC50 >= 5.0).

Dependencies: see requirements.txt (rdkit, xgboost, scikit-learn, numpy).
"""
import argparse, csv, json, pickle, sys
import numpy as np

from feature_extraction import featurize_smiles

BLOCK_KIND = {"morgan": "bits", "maccs": "bits", "desc": "cont",
              "physchem_extra": "cont", "morgan_counts": "counts",
              "ecfp6": "bits", "fcfp4": "bits", "herg": "cont",
              "pharm": "counts", "cdk": "bits",
              "morgan1024": "bits", "morgan1024_counts": "counts"}


def apply_prep(raw, state):
    """Replicates p5_common.ContPrep.transform from its stored state dict."""
    X = np.asarray(raw, dtype=float).reshape(1, -1)
    X = np.where(np.isfinite(X), X, np.nan)
    if state["log1p"]:
        X = np.log1p(np.clip(X, 0, None))
    X = X[:, np.asarray(state["keep"], dtype=bool)]
    med = np.asarray(state["med"], dtype=float)
    X = np.where(np.isnan(X), med, X)
    mu = np.asarray(state["mu"], dtype=float)
    sd = np.asarray(state["sd"], dtype=float)
    return ((X - mu) / sd).astype(np.float32)


def design_row(blocks, combo, preps):
    parts = []
    for b in combo:
        raw = np.asarray(blocks[b], dtype=np.float32)
        if b in preps:
            parts.append(apply_prep(raw, preps[b]))
        else:
            parts.append(raw.reshape(1, -1).astype(np.float32))
    return np.hstack(parts)


def load_bundle(path):
    with open(path, "rb") as fh:
        return pickle.load(fh)


def predict(bundle, smiles_list):
    out = []
    for smi in smiles_list:
        _, blocks = featurize_smiles(smi)
        if blocks is None:
            out.append(None)
            continue
        X = design_row(blocks, bundle["blocks"], bundle["preps"])
        model = bundle["model"]
        if bundle["task"] == "cls":
            out.append(float(model.predict_proba(X)[0, 1]))
        else:
            out.append(float(model.predict(X)[0]))
    return out


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--model", required=True, help="path to a model pickle from models/")
    ap.add_argument("--csv", help="input CSV with a 'smiles' column")
    ap.add_argument("--out", help="output CSV (default: stdout summary)")
    ap.add_argument("smiles", nargs="*", help="SMILES strings")
    args = ap.parse_args()

    bundle = load_bundle(args.model)
    rows = []
    if args.csv:
        with open(args.csv) as fh:
            for r in csv.DictReader(fh):
                rows.append(r)
        smiles = [r["smiles"] for r in rows]
    else:
        smiles = args.smiles
        rows = [{"smiles": s} for s in smiles]
    if not smiles:
        print("no SMILES given", file=sys.stderr)
        return 2
    preds = predict(bundle, smiles)
    col = "prob_blocker" if bundle["task"] == "cls" else "pred_pIC50"
    for r, p in zip(rows, preds):
        r[col] = "" if p is None else f"{p:.4f}"
        if bundle["task"] == "cls":
            r["call_10uM"] = "" if p is None else int(p >= 0.5)
        else:
            r["derived_call_10uM"] = "" if p is None else int(p >= 5.0)
    if args.out:
        with open(args.out, "w", newline="") as fh:
            w = csv.DictWriter(fh, fieldnames=list(rows[0].keys()))
            w.writeheader()
            w.writerows(rows)
        print(f"wrote {args.out} ({len(rows)} rows, model task={bundle['task']}, "
              f"protocol={bundle['protocol']})")
    else:
        for r in rows:
            print(json.dumps(r))
    return 0


if __name__ == "__main__":
    sys.exit(main())