File size: 5,120 Bytes
0613483
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Classify each Chroma pose as surface-binding or buried inside the target.

Runs the surface-pose filter from ``utils.pose_filtering`` over the pose PDBs
on disk and writes one verdict per (target, length, pose) to
``benchmark/geometric_pose_classification.csv``. The verdict depends only on the
backbone, so it applies to every sequence designed on that pose.
"""

from __future__ import annotations

import re
from concurrent.futures import ProcessPoolExecutor, as_completed
from pathlib import Path

import pandas as pd

import sys

ROOT = Path(__file__).resolve().parents[2]
if str(ROOT) not in sys.path:
    sys.path.insert(0, str(ROOT))

from utils.pose_filtering import (  # noqa: E402
    DEFAULT_SURFACE_FILTER,
    passes_surface_pose_filter,
    surface_pose_metrics,
)

BENCH = ROOT / "benchmark"

# (target, peptide_mode, designs_root).  ``designs_root`` is the directory that
# holds ``len_*/Poses/Binder_{D,L}_pose_*.pdb``.
SCAN_DIRS = [
    ("TNFalpha", "D_peptide", BENCH / "new_targets" / "designs" / "TNFalpha" / "D_peptide"),
    ("CXCR2", "D_peptide", BENCH / "new_targets" / "designs" / "CXCR2" / "D_peptide"),
    ("CXCR4", "D_peptide", BENCH / "new_targets" / "designs" / "CXCR4" / "D_peptide"),
    ("PDL1", "D_peptide", BENCH / "PDL1" / "D_peptide"),
    ("PDL1", "L_peptide", BENCH / "PDL1" / "L_peptide"),
    ("MDM2", "D_peptide", BENCH / "MDM2" / "D_peptide"),
    ("MDM2", "L_peptide", BENCH / "MDM2" / "L_peptide"),
    ("IL23R", "D_peptide", BENCH / "IL23R" / "D_peptide"),
    ("IL23R", "L_peptide", BENCH / "IL23R" / "L_peptide"),
]

POSE_RE = re.compile(r"Binder_[DL]_pose_(\d+)\.pdb$", re.IGNORECASE)


def discover() -> list[dict]:
    rows = []
    for target, mode, root in SCAN_DIRS:
        if not root.exists():
            print(f"  [skip] missing: {root}")
            continue
        for pose_pdb in sorted(root.glob("len_*/Poses/Binder_[DL]_pose_*.pdb")):
            m = POSE_RE.search(pose_pdb.name)
            if not m:
                continue
            length = int(pose_pdb.parents[1].name.split("_")[1])
            pose = int(m.group(1))
            rows.append(
                {
                    "target": target,
                    "peptide_mode": mode,
                    "length": length,
                    "pose": pose,
                    "pose_pdb": str(pose_pdb.relative_to(ROOT)),
                }
            )
    return rows


def classify_one(row: dict) -> dict:
    pdb = ROOT / row["pose_pdb"]
    try:
        metrics = surface_pose_metrics(
            pdb,
            binder_chain="B",
            nearby_distance=DEFAULT_SURFACE_FILTER["nearby_distance"],
            contact_distance=DEFAULT_SURFACE_FILTER["contact_distance"],
        )
        passed = passes_surface_pose_filter(
            metrics,
            radial_min=DEFAULT_SURFACE_FILTER["radial_min"],
            outward_nearby_max=DEFAULT_SURFACE_FILTER["outward_nearby_max"],
            occupied_octants_max=DEFAULT_SURFACE_FILTER["occupied_octants_max"],
            min_binder_atoms_within_contact=DEFAULT_SURFACE_FILTER[
                "min_binder_atoms_within_contact"
            ],
        )
        out = dict(row)
        out.update(metrics)
        out["passes_surface"] = bool(passed)
        return out
    except Exception as exc:  # pragma: no cover - defensive
        out = dict(row)
        out["error"] = f"{type(exc).__name__}: {exc}"
        out["passes_surface"] = False
        return out


def main():
    jobs = discover()
    print(f"Discovered {len(jobs)} pose PDBs to classify")
    results = []
    with ProcessPoolExecutor(max_workers=16) as ex:
        futs = {ex.submit(classify_one, j): j for j in jobs}
        done = 0
        for fut in as_completed(futs):
            results.append(fut.result())
            done += 1
            if done % 500 == 0:
                print(f"  ...{done}/{len(jobs)}")

    df = pd.DataFrame(results)
    metric_cols = [
        "radial_percentile",
        "outward_nearby_fraction",
        "occupied_octants",
        "binder_atoms_within_contact",
        "min_receptor_distance",
        "median_receptor_distance",
    ]
    cols = ["target", "peptide_mode", "length", "pose", "passes_surface"] + metric_cols + ["pose_pdb"]
    for c in cols:
        if c not in df.columns:
            df[c] = pd.NA
    df = df[cols]

    out = BENCH / "geometric_pose_classification.csv"
    df.to_csv(out, index=False)
    print(f"\nSaved {out}  ({len(df)} rows)")

    print("\nSurface-pose verdict by target/mode:")
    summary = (
        df.groupby(["target", "peptide_mode"])
        .agg(
            n_poses=("pose", "size"),
            n_surface=("passes_surface", "sum"),
        )
        .reset_index()
    )
    summary["n_buried"] = summary["n_poses"] - summary["n_surface"]
    summary["pct_surface"] = (summary["n_surface"] / summary["n_poses"] * 100).round(1)
    print(summary.to_string(index=False))

    errors = df[df["radial_percentile"].isna()]
    if len(errors):
        print(f"\n[warn] {len(errors)} poses failed to compute metrics")


if __name__ == "__main__":
    main()