BindCraft patch-coverage propensity GNN
Browse files- app.py +146 -182
- patches.py +96 -0
- requirements-local.txt +1 -0
- requirements.txt +1 -0
app.py
CHANGED
|
@@ -1,11 +1,12 @@
|
|
| 1 |
"""Gradio front end for the BindCraft patch-coverage propensity GNN.
|
| 2 |
|
| 3 |
Upload a PDB (or give an RCSB id), get the same structure back with the per-residue
|
| 4 |
-
propensity in the B-factor column,
|
|
|
|
| 5 |
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
"""
|
| 10 |
|
| 11 |
# ZeroGPU -- and this import MUST come first, above torch and above anything that
|
|
@@ -28,6 +29,7 @@ else:
|
|
| 28 |
_spaces_error = None
|
| 29 |
|
| 30 |
import html
|
|
|
|
| 31 |
import os
|
| 32 |
import re
|
| 33 |
import tempfile
|
|
@@ -39,6 +41,7 @@ import gradio as gr
|
|
| 39 |
import torch as pt
|
| 40 |
|
| 41 |
from inference import MAX_ATOMS, PropensityPredictor
|
|
|
|
| 42 |
|
| 43 |
# load once, at import, so the first request is not also the first model load
|
| 44 |
PREDICTOR = PropensityPredictor()
|
|
@@ -66,13 +69,17 @@ def _run_model(pdb_path, chain_list, out_pdb):
|
|
| 66 |
RCSB_URL = "https://files.rcsb.org/download/{}.pdb"
|
| 67 |
PDB_ID_RE = re.compile(r"^[0-9][A-Za-z0-9]{3}$")
|
| 68 |
|
| 69 |
-
#
|
|
|
|
|
|
|
| 70 |
RAMP = [
|
| 71 |
-
"#
|
| 72 |
-
"#
|
| 73 |
]
|
| 74 |
-
# residues
|
| 75 |
-
UNSCORED_COLOR = "#
|
|
|
|
|
|
|
| 76 |
|
| 77 |
|
| 78 |
# ---------------------------------------------------------------------------
|
|
@@ -136,85 +143,23 @@ def _ramp_color(v):
|
|
| 136 |
return "#{:02x}{:02x}{:02x}".format(*out)
|
| 137 |
|
| 138 |
|
| 139 |
-
def
|
| 140 |
-
"""
|
| 141 |
-
zero baseline. One series, so no legend box; the colour bar carries the scale."""
|
| 142 |
-
if not records:
|
| 143 |
-
return "<p class='empty'>no protein residues to plot</p>"
|
| 144 |
-
|
| 145 |
-
n = len(records)
|
| 146 |
-
W, H = 1000.0, 190.0
|
| 147 |
-
PAD_L, PAD_R, PAD_T, PAD_B = 46.0, 12.0, 14.0, 34.0
|
| 148 |
-
plot_w = W - PAD_L - PAD_R
|
| 149 |
-
plot_h = H - PAD_T - PAD_B
|
| 150 |
-
step = plot_w / n
|
| 151 |
-
bw = max(0.7, step * 0.86)
|
| 152 |
-
|
| 153 |
-
parts = [
|
| 154 |
-
# uniform scaling only -- stretching the viewBox would distort the tick text
|
| 155 |
-
f"<svg viewBox='0 0 {W:.0f} {H:.0f}' class='profile' role='img' "
|
| 156 |
-
f"aria-label='per-residue propensity along the sequence'>"
|
| 157 |
-
]
|
| 158 |
-
|
| 159 |
-
# recessive gridlines + axis labels
|
| 160 |
-
for gv in (0.0, 0.25, 0.5, 0.75, 1.0):
|
| 161 |
-
y = PAD_T + plot_h * (1.0 - gv)
|
| 162 |
-
cls = "axis-base" if gv == 0.0 else "grid"
|
| 163 |
-
parts.append(f"<line class='{cls}' x1='{PAD_L:.1f}' y1='{y:.1f}' x2='{W - PAD_R:.1f}' y2='{y:.1f}'/>")
|
| 164 |
-
parts.append(f"<text class='tick' x='{PAD_L - 8:.1f}' y='{y + 3.5:.1f}' text-anchor='end'>{gv:.2f}</text>")
|
| 165 |
-
|
| 166 |
-
# chain boundaries, so a multi-chain target does not read as one sequence
|
| 167 |
-
prev_chain = records[0]["chain"]
|
| 168 |
-
chain_start = 0
|
| 169 |
-
boundaries = []
|
| 170 |
-
for i, r in enumerate(records):
|
| 171 |
-
if r["chain"] != prev_chain:
|
| 172 |
-
boundaries.append((chain_start, i, prev_chain))
|
| 173 |
-
chain_start = i
|
| 174 |
-
prev_chain = r["chain"]
|
| 175 |
-
boundaries.append((chain_start, n, prev_chain))
|
| 176 |
-
|
| 177 |
-
for start, end, cname in boundaries:
|
| 178 |
-
if start > 0:
|
| 179 |
-
x = PAD_L + step * start
|
| 180 |
-
parts.append(f"<line class='chain-sep' x1='{x:.1f}' y1='{PAD_T:.1f}' x2='{x:.1f}' y2='{PAD_T + plot_h:.1f}'/>")
|
| 181 |
-
xm = PAD_L + step * (start + end) / 2.0
|
| 182 |
-
parts.append(f"<text class='chain-label' x='{xm:.1f}' y='{H - 10:.1f}' text-anchor='middle'>chain {cname}</text>")
|
| 183 |
-
|
| 184 |
-
# bars
|
| 185 |
-
for i, r in enumerate(records):
|
| 186 |
-
v = max(0.0, float(r["score"]))
|
| 187 |
-
h = max(0.6, plot_h * v)
|
| 188 |
-
x = PAD_L + step * i + (step - bw) / 2.0
|
| 189 |
-
y = PAD_T + plot_h - h
|
| 190 |
-
label = "{}{}{} {}".format(r["chain"], r["resid"], r["icode"], r["resname"])
|
| 191 |
-
parts.append(
|
| 192 |
-
f"<rect class='bar' x='{x:.2f}' y='{y:.2f}' width='{bw:.2f}' height='{h:.2f}' "
|
| 193 |
-
f"fill='{_ramp_color(v)}' data-sel='{r['chain']}|{r['resid']}' "
|
| 194 |
-
f"data-label='{label}' data-score='{v:.3f}'/>"
|
| 195 |
-
)
|
| 196 |
-
|
| 197 |
-
parts.append("</svg>")
|
| 198 |
-
return "".join(parts)
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
def _viewer_document(pdb_text, records, style):
|
| 202 |
-
"""Self-contained page: Mol* view + sequence profile, wired to each other.
|
| 203 |
|
| 204 |
Mol* rather than a lighter viewer for one concrete reason: it derives secondary
|
| 205 |
structure from coordinates. PeSTo-processed files and BindCraft outputs carry no
|
| 206 |
-
HELIX/SHEET records
|
| 207 |
-
|
| 208 |
-
no helices or sheet arrows. Mol* also happens to be the viewer RCSB, PDBe and the
|
| 209 |
-
AlphaFold DB all use, so the result looks like what everyone already reads.
|
| 210 |
-
"""
|
| 211 |
-
profile = _profile_svg(records)
|
| 212 |
|
| 213 |
-
|
|
|
|
|
|
|
|
|
|
| 214 |
ramp_js = "[" + ",".join(f"'{c}'" for c in RAMP) + "]"
|
| 215 |
bar_stops = ", ".join(
|
| 216 |
f"{c} {int(round(100 * i / (len(RAMP) - 1)))}%" for i, c in enumerate(RAMP)
|
| 217 |
)
|
|
|
|
| 218 |
|
| 219 |
return f"""<!doctype html>
|
| 220 |
<html><head><meta charset="utf-8">
|
|
@@ -245,80 +190,87 @@ def _viewer_document(pdb_text, records, style):
|
|
| 245 |
margin: 0; background: var(--surface-1); color: var(--text-primary);
|
| 246 |
font: 13px/1.45 ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
|
| 247 |
}}
|
| 248 |
-
/* Mol*
|
| 249 |
position:relative for the viewer's own absolutely-positioned layers. */
|
| 250 |
-
#view {{ position: relative; width: 100%; height:
|
| 251 |
border: 1px solid var(--hairline); border-radius: 8px; overflow: hidden; }}
|
| 252 |
.viewer-msg {{ padding: 18px; color: var(--text-secondary); font-size: 12px; }}
|
| 253 |
.scalebar {{ display: flex; align-items: center; gap: 8px; margin: 10px 2px 2px;
|
| 254 |
-
color: var(--text-secondary); font-size: 11px; }}
|
| 255 |
.scalebar .ramp {{ flex: 0 0 200px; height: 9px; border-radius: 5px;
|
| 256 |
background: linear-gradient(to right, {bar_stops}); }}
|
| 257 |
-
.
|
| 258 |
-
|
| 259 |
-
.
|
| 260 |
-
.axis-base {{ stroke: var(--text-muted); stroke-width: 1; }}
|
| 261 |
-
.chain-sep {{ stroke: var(--hairline); stroke-width: 1; stroke-dasharray: 3 3; }}
|
| 262 |
-
.tick, .chain-label {{ fill: var(--text-muted); font-size: 10px;
|
| 263 |
-
font-family: ui-sans-serif, system-ui, sans-serif; }}
|
| 264 |
-
.bar {{ cursor: pointer; }}
|
| 265 |
-
.bar:hover {{ stroke: var(--text-primary); stroke-width: 0.8; paint-order: stroke; }}
|
| 266 |
#tip {{ position: fixed; pointer-events: none; opacity: 0; transition: opacity .08s;
|
| 267 |
background: var(--surface-1); color: var(--text-primary);
|
| 268 |
-
border: 1px solid var(--hairline); border-radius: 6px; padding:
|
| 269 |
-
font-size: 12px; box-shadow: 0 2px 10px rgba(0,0,0,.
|
| 270 |
-
|
|
|
|
|
|
|
| 271 |
</style></head>
|
| 272 |
<body>
|
| 273 |
<div id="view"></div>
|
| 274 |
-
<div class="scalebar">
|
| 275 |
-
<span
|
| 276 |
-
|
| 277 |
-
|
|
|
|
| 278 |
<div id="tip"></div>
|
| 279 |
|
| 280 |
-
<!--
|
| 281 |
-
wrong, and the browser hands them back verbatim through .value -->
|
| 282 |
<textarea id="pdbdata" style="display:none">{html.escape(pdb_text)}</textarea>
|
| 283 |
<script>
|
| 284 |
const RAMP = {ramp_js};
|
| 285 |
-
const
|
| 286 |
-
|
| 287 |
-
function rampColor(v) {{
|
| 288 |
-
if (v === undefined || v === null || v < 0) return UNSCORED;
|
| 289 |
-
v = Math.min(Math.max(v, 0), 1);
|
| 290 |
-
const x = v * (RAMP.length - 1);
|
| 291 |
-
const i = Math.min(Math.floor(x), RAMP.length - 2);
|
| 292 |
-
const f = x - i;
|
| 293 |
-
const a = RAMP[i].slice(1), b = RAMP[i + 1].slice(1);
|
| 294 |
-
let out = "#";
|
| 295 |
-
for (let k = 0; k < 6; k += 2) {{
|
| 296 |
-
const ca = parseInt(a.substr(k, 2), 16), cb = parseInt(b.substr(k, 2), 16);
|
| 297 |
-
out += Math.round(ca + (cb - ca) * f).toString(16).padStart(2, "0");
|
| 298 |
-
}}
|
| 299 |
-
return out;
|
| 300 |
-
}}
|
| 301 |
const STYLE = "{style}";
|
|
|
|
|
|
|
|
|
|
|
|
|
| 302 |
const view = document.getElementById("view");
|
|
|
|
| 303 |
|
| 304 |
function fail(msg) {{
|
| 305 |
view.innerHTML = "<div class='viewer-msg'>3D view unavailable: " + msg +
|
| 306 |
-
"<br><small>The
|
| 307 |
}}
|
|
|
|
| 308 |
|
| 309 |
-
|
| 310 |
-
// explicit domain and colour list -- so the propensity ramp maps onto [0,1] exactly,
|
| 311 |
-
// and the structure and the profile below are literally the same scale.
|
| 312 |
const THEME = {{
|
| 313 |
color: "uncertainty",
|
| 314 |
-
colorParams: {{
|
| 315 |
-
domain: [0, 1],
|
| 316 |
-
list: {{ kind: "interpolate", colors: RAMP.map(hexToInt) }},
|
| 317 |
-
}},
|
| 318 |
}};
|
| 319 |
-
function hexToInt(h) {{ return parseInt(h.slice(1), 16); }}
|
| 320 |
|
| 321 |
-
let plugin = null;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 322 |
|
| 323 |
(async () => {{
|
| 324 |
if (typeof molstar === "undefined") return fail("Mol* failed to load from the CDN");
|
|
@@ -343,19 +295,17 @@ def _viewer_document(pdb_text, records, style):
|
|
| 343 |
document.getElementById("pdbdata").value, "pdb", {{ dataLabel: "target" }});
|
| 344 |
}} catch (e) {{ return fail("could not parse the structure: " + e); }}
|
| 345 |
|
| 346 |
-
|
| 347 |
-
|
|
|
|
|
|
|
|
|
|
| 348 |
try {{
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
st.components, THEME);
|
| 352 |
-
}} catch (e) {{
|
| 353 |
-
console.warn("propensity colour theme not applied:", e);
|
| 354 |
-
}}
|
| 355 |
|
| 356 |
if (STYLE === "surface" || STYLE === "both") {{
|
| 357 |
try {{
|
| 358 |
-
const st = plugin.managers.structure.hierarchy.current.structures[0];
|
| 359 |
for (const c of st.components) {{
|
| 360 |
await plugin.builders.structure.representation.addRepresentation(c.cell, {{
|
| 361 |
type: "molecular-surface",
|
|
@@ -365,34 +315,48 @@ def _viewer_document(pdb_text, records, style):
|
|
| 365 |
}}
|
| 366 |
}} catch (e) {{ console.warn("surface representation not added:", e); }}
|
| 367 |
}}
|
| 368 |
-
}})();
|
| 369 |
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
|
| 380 |
-
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
const
|
| 385 |
-
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
|
| 395 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 396 |
</script>
|
| 397 |
</body></html>"""
|
| 398 |
|
|
@@ -437,21 +401,29 @@ def score(pdb_file, pdb_id, chains, style, progress=gr.Progress()):
|
|
| 437 |
raise gr.Error("no amino-acid residues in the selection -- this model scores protein targets")
|
| 438 |
|
| 439 |
s = pred.scores()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 440 |
summary = (
|
| 441 |
f"**{stem}** · {len(prot)} protein residues scored "
|
| 442 |
f" · chains {' '.join(pred.chains)} · {pred.num_atoms} atoms \n"
|
| 443 |
-
f"
|
| 444 |
f"{int((s >= 0.5).sum())} residues ≥ 0.50 · "
|
| 445 |
f"{int((s >= 0.2).sum())} residues ≥ 0.20"
|
| 446 |
)
|
| 447 |
|
| 448 |
-
|
| 449 |
-
|
| 450 |
-
|
| 451 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 452 |
|
| 453 |
-
viewer = _iframe(_viewer_document(pred.pdb_text,
|
| 454 |
-
return viewer, summary,
|
| 455 |
|
| 456 |
|
| 457 |
INTRO = """
|
|
@@ -460,7 +432,7 @@ INTRO = """
|
|
| 460 |
A [PeSTo](https://github.com/LBM-EPFL/PeSTo) geometric transformer that scores **every
|
| 461 |
residue of a target for how well a BindCraft binder could bury it**. Give it a structure;
|
| 462 |
it gives the structure back with the score in the **B-factor column**, ready to open in
|
| 463 |
-
PyMOL or ChimeraX (`spectrum b,
|
| 464 |
|
| 465 |
The score estimates the fraction of independent BindCraft trajectories whose interface
|
| 466 |
would fully cover that residue's local surface patch (7 Å CB–CB, solvent-exposed
|
|
@@ -513,21 +485,13 @@ with gr.Blocks(title="BindCraft propensity GNN", theme=THEME) as demo:
|
|
| 513 |
out_view = gr.HTML()
|
| 514 |
|
| 515 |
with gr.Row():
|
| 516 |
-
|
| 517 |
-
|
| 518 |
-
datatype=["str", "str", "str", "number"],
|
| 519 |
-
label="Top 30 residues",
|
| 520 |
-
interactive=False,
|
| 521 |
-
wrap=True,
|
| 522 |
-
)
|
| 523 |
-
with gr.Column():
|
| 524 |
-
out_pdb = gr.File(label="Scored PDB (propensity in B-factors)")
|
| 525 |
-
out_csv = gr.File(label="Per-residue CSV")
|
| 526 |
|
| 527 |
go.click(
|
| 528 |
score,
|
| 529 |
inputs=[f_in, id_in, ch_in, st_in],
|
| 530 |
-
outputs=[out_view, out_summary,
|
| 531 |
)
|
| 532 |
|
| 533 |
examples_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "examples")
|
|
|
|
| 1 |
"""Gradio front end for the BindCraft patch-coverage propensity GNN.
|
| 2 |
|
| 3 |
Upload a PDB (or give an RCSB id), get the same structure back with the per-residue
|
| 4 |
+
propensity in the B-factor column, a Mol* view coloured by that value, and the scored
|
| 5 |
+
PDB and per-residue CSV to download.
|
| 6 |
|
| 7 |
+
Hovering a residue reports its propensity and outlines the 7 A patch the value is a
|
| 8 |
+
statement about -- the training label is patch coverage, so the number belongs to the
|
| 9 |
+
neighbourhood, not to the residue alone.
|
| 10 |
"""
|
| 11 |
|
| 12 |
# ZeroGPU -- and this import MUST come first, above torch and above anything that
|
|
|
|
| 29 |
_spaces_error = None
|
| 30 |
|
| 31 |
import html
|
| 32 |
+
import json
|
| 33 |
import os
|
| 34 |
import re
|
| 35 |
import tempfile
|
|
|
|
| 41 |
import torch as pt
|
| 42 |
|
| 43 |
from inference import MAX_ATOMS, PropensityPredictor
|
| 44 |
+
from patches import compute_patches
|
| 45 |
|
| 46 |
# load once, at import, so the first request is not also the first model load
|
| 47 |
PREDICTOR = PropensityPredictor()
|
|
|
|
| 69 |
RCSB_URL = "https://files.rcsb.org/download/{}.pdb"
|
| 70 |
PDB_ID_RE = re.compile(r"^[0-9][A-Za-z0-9]{3}$")
|
| 71 |
|
| 72 |
+
# Sequential ramp, neutral grey -> dark red: light = low propensity, dark = high.
|
| 73 |
+
# One hue with a neutral floor, so near-zero recedes and only real signal reads as
|
| 74 |
+
# colour -- the whole surface is near-zero on most targets.
|
| 75 |
RAMP = [
|
| 76 |
+
"#eceae7", "#e8dcd6", "#e6cdc2", "#e3bcac", "#dfa994", "#d9957d",
|
| 77 |
+
"#d18067", "#c66a52", "#b8543f", "#a83f2e", "#95291f", "#7f1712", "#670a09",
|
| 78 |
]
|
| 79 |
+
# residues the model never saw (waters, unselected chains) sit off the ramp entirely
|
| 80 |
+
UNSCORED_COLOR = "#b9b7b2"
|
| 81 |
+
# the patch highlight, deliberately off-ramp so it cannot be read as a propensity value
|
| 82 |
+
PATCH_COLOR = "#1c5cab"
|
| 83 |
|
| 84 |
|
| 85 |
# ---------------------------------------------------------------------------
|
|
|
|
| 143 |
return "#{:02x}{:02x}{:02x}".format(*out)
|
| 144 |
|
| 145 |
|
| 146 |
+
def _viewer_document(pdb_text, patches, style):
|
| 147 |
+
"""Self-contained page: a Mol* view of the scored structure, and nothing else.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 148 |
|
| 149 |
Mol* rather than a lighter viewer for one concrete reason: it derives secondary
|
| 150 |
structure from coordinates. PeSTo-processed files and BindCraft outputs carry no
|
| 151 |
+
HELIX/SHEET records, and a viewer that trusts the file renders every residue as
|
| 152 |
+
coil. Mol* is also what RCSB, PDBe and the AlphaFold DB use, so it reads as familiar.
|
|
|
|
|
|
|
|
|
|
|
|
|
| 153 |
|
| 154 |
+
Hovering a residue reports its propensity *and* outlines the 7 A patch that value is
|
| 155 |
+
a statement about -- the label is patch coverage, so the number belongs to the
|
| 156 |
+
neighbourhood, not to the single residue under the cursor.
|
| 157 |
+
"""
|
| 158 |
ramp_js = "[" + ",".join(f"'{c}'" for c in RAMP) + "]"
|
| 159 |
bar_stops = ", ".join(
|
| 160 |
f"{c} {int(round(100 * i / (len(RAMP) - 1)))}%" for i, c in enumerate(RAMP)
|
| 161 |
)
|
| 162 |
+
patches_js = json.dumps(patches, separators=(",", ":"))
|
| 163 |
|
| 164 |
return f"""<!doctype html>
|
| 165 |
<html><head><meta charset="utf-8">
|
|
|
|
| 190 |
margin: 0; background: var(--surface-1); color: var(--text-primary);
|
| 191 |
font: 13px/1.45 ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
|
| 192 |
}}
|
| 193 |
+
/* Mol* sizes its canvas from this element, so it needs a real height and
|
| 194 |
position:relative for the viewer's own absolutely-positioned layers. */
|
| 195 |
+
#view {{ position: relative; width: 100%; height: 560px; background: var(--surface-2);
|
| 196 |
border: 1px solid var(--hairline); border-radius: 8px; overflow: hidden; }}
|
| 197 |
.viewer-msg {{ padding: 18px; color: var(--text-secondary); font-size: 12px; }}
|
| 198 |
.scalebar {{ display: flex; align-items: center; gap: 8px; margin: 10px 2px 2px;
|
| 199 |
+
color: var(--text-secondary); font-size: 11px; flex-wrap: wrap; }}
|
| 200 |
.scalebar .ramp {{ flex: 0 0 200px; height: 9px; border-radius: 5px;
|
| 201 |
background: linear-gradient(to right, {bar_stops}); }}
|
| 202 |
+
.scalebar .swatch {{ display: inline-block; width: 10px; height: 10px; border-radius: 3px;
|
| 203 |
+
background: {PATCH_COLOR}; vertical-align: -1px; margin-right: 4px; }}
|
| 204 |
+
.hint {{ color: var(--text-muted); }}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 205 |
#tip {{ position: fixed; pointer-events: none; opacity: 0; transition: opacity .08s;
|
| 206 |
background: var(--surface-1); color: var(--text-primary);
|
| 207 |
+
border: 1px solid var(--hairline); border-radius: 6px; padding: 6px 9px;
|
| 208 |
+
font-size: 12px; box-shadow: 0 2px 10px rgba(0,0,0,.16); z-index: 9;
|
| 209 |
+
white-space: nowrap; line-height: 1.5; }}
|
| 210 |
+
#tip b {{ font-weight: 600; }}
|
| 211 |
+
#tip .sub {{ color: var(--text-secondary); }}
|
| 212 |
</style></head>
|
| 213 |
<body>
|
| 214 |
<div id="view"></div>
|
| 215 |
+
<div class="scalebar">
|
| 216 |
+
<span>propensity 0</span><span class="ramp"></span><span>1</span>
|
| 217 |
+
<span style="margin-left:14px"><span class="swatch"></span>7 A patch under the cursor</span>
|
| 218 |
+
<span class="hint" style="margin-left:14px">hover a residue · drag to rotate · scroll to zoom</span>
|
| 219 |
+
</div>
|
| 220 |
<div id="tip"></div>
|
| 221 |
|
| 222 |
+
<!-- coordinates ride in a textarea, not a JS string literal: no quoting to get wrong -->
|
|
|
|
| 223 |
<textarea id="pdbdata" style="display:none">{html.escape(pdb_text)}</textarea>
|
| 224 |
<script>
|
| 225 |
const RAMP = {ramp_js};
|
| 226 |
+
const PATCHES = {patches_js};
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 227 |
const STYLE = "{style}";
|
| 228 |
+
// Mol*'s uncertainty theme walks its colour list from HIGH b-factor to low, so the
|
| 229 |
+
// ramp goes in reversed. Flip this if the structure ever reads inverted again.
|
| 230 |
+
const REVERSE_RAMP = true;
|
| 231 |
+
|
| 232 |
const view = document.getElementById("view");
|
| 233 |
+
const tip = document.getElementById("tip");
|
| 234 |
|
| 235 |
function fail(msg) {{
|
| 236 |
view.innerHTML = "<div class='viewer-msg'>3D view unavailable: " + msg +
|
| 237 |
+
"<br><small>The downloads below are unaffected.</small></div>";
|
| 238 |
}}
|
| 239 |
+
function hexToInt(h) {{ return parseInt(h.slice(1), 16); }}
|
| 240 |
|
| 241 |
+
const colors = (REVERSE_RAMP ? RAMP.slice().reverse() : RAMP).map(hexToInt);
|
|
|
|
|
|
|
| 242 |
const THEME = {{
|
| 243 |
color: "uncertainty",
|
| 244 |
+
colorParams: {{ domain: [0, 1], list: {{ kind: "interpolate", colors: colors }} }},
|
|
|
|
|
|
|
|
|
|
| 245 |
}};
|
|
|
|
| 246 |
|
| 247 |
+
let plugin = null, structureData = null;
|
| 248 |
+
let mouse = {{ x: 0, y: 0 }};
|
| 249 |
+
document.addEventListener("mousemove", e => {{ mouse = {{ x: e.clientX, y: e.clientY }}; }});
|
| 250 |
+
|
| 251 |
+
function showTip(htmlStr) {{
|
| 252 |
+
tip.innerHTML = htmlStr;
|
| 253 |
+
tip.style.left = Math.min(mouse.x + 14, window.innerWidth - 260) + "px";
|
| 254 |
+
tip.style.top = (mouse.y + 14) + "px";
|
| 255 |
+
tip.style.opacity = 1;
|
| 256 |
+
}}
|
| 257 |
+
function hideTip() {{ tip.style.opacity = 0; }}
|
| 258 |
+
|
| 259 |
+
// Build a Mol* loci covering a list of "chain|seq|ins" residue keys.
|
| 260 |
+
function lociForKeys(keys) {{
|
| 261 |
+
if (!structureData || !keys.length) return null;
|
| 262 |
+
const sel = molstar.Script.getStructureSelection(Q => {{
|
| 263 |
+
const groups = keys.map(k => {{
|
| 264 |
+
const [c, s] = k.split("|");
|
| 265 |
+
return Q.struct.generator.atomGroups({{
|
| 266 |
+
"chain-test": Q.core.rel.eq([Q.struct.atomProperty.macromolecular.auth_asym_id(), c]),
|
| 267 |
+
"residue-test": Q.core.rel.eq([Q.struct.atomProperty.macromolecular.auth_seq_id(), parseInt(s, 10)]),
|
| 268 |
+
}});
|
| 269 |
+
}});
|
| 270 |
+
return groups.length === 1 ? groups[0] : Q.struct.combinator.merge(groups);
|
| 271 |
+
}}, structureData);
|
| 272 |
+
return molstar.StructureSelection.toLociWithSourceUnits(sel);
|
| 273 |
+
}}
|
| 274 |
|
| 275 |
(async () => {{
|
| 276 |
if (typeof molstar === "undefined") return fail("Mol* failed to load from the CDN");
|
|
|
|
| 295 |
document.getElementById("pdbdata").value, "pdb", {{ dataLabel: "target" }});
|
| 296 |
}} catch (e) {{ return fail("could not parse the structure: " + e); }}
|
| 297 |
|
| 298 |
+
const st = plugin.managers.structure.hierarchy.current.structures[0];
|
| 299 |
+
try {{ structureData = st.cell.obj.data; }} catch (e) {{ console.warn(e); }}
|
| 300 |
+
|
| 301 |
+
// Recolour the default preset. Wrapped: if the theme params are rejected we keep
|
| 302 |
+
// correctly-shaped cartoons rather than blanking the view.
|
| 303 |
try {{
|
| 304 |
+
await plugin.managers.structure.component.updateRepresentationsTheme(st.components, THEME);
|
| 305 |
+
}} catch (e) {{ console.warn("propensity colour theme not applied:", e); }}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 306 |
|
| 307 |
if (STYLE === "surface" || STYLE === "both") {{
|
| 308 |
try {{
|
|
|
|
| 309 |
for (const c of st.components) {{
|
| 310 |
await plugin.builders.structure.representation.addRepresentation(c.cell, {{
|
| 311 |
type: "molecular-surface",
|
|
|
|
| 315 |
}}
|
| 316 |
}} catch (e) {{ console.warn("surface representation not added:", e); }}
|
| 317 |
}}
|
|
|
|
| 318 |
|
| 319 |
+
// hover -> propensity + the patch the value refers to
|
| 320 |
+
try {{
|
| 321 |
+
const P = molstar.StructureProperties;
|
| 322 |
+
plugin.behaviors.interaction.hover.subscribe(ev => {{
|
| 323 |
+
const loci = ev.current && ev.current.loci;
|
| 324 |
+
if (!loci || loci.kind !== "element-loci") {{ hideTip(); return; }}
|
| 325 |
+
const el = molstar.StructureElement.Loci.firstElement(loci);
|
| 326 |
+
if (!el) {{ hideTip(); return; }}
|
| 327 |
+
const loc = molstar.StructureElement.Location.create(loci.structure, el.unit, el.element);
|
| 328 |
+
|
| 329 |
+
const chain = P.chain.auth_asym_id(loc);
|
| 330 |
+
const seq = P.residue.auth_seq_id(loc);
|
| 331 |
+
let ins = "";
|
| 332 |
+
try {{ ins = (P.residue.pdbx_PDB_ins_code(loc) || "").trim(); }} catch (e) {{}}
|
| 333 |
+
const comp = P.atom.label_comp_id(loc);
|
| 334 |
+
const b = P.atom.B_iso_or_equiv(loc);
|
| 335 |
+
|
| 336 |
+
const key = chain + "|" + seq + "|" + ins;
|
| 337 |
+
const patch = PATCHES[key];
|
| 338 |
+
|
| 339 |
+
let body = "<b>" + comp + " " + chain + seq + ins + "</b><br>";
|
| 340 |
+
if (b < 0) {{
|
| 341 |
+
body += "<span class='sub'>not scored</span>";
|
| 342 |
+
}} else {{
|
| 343 |
+
body += "propensity <b>" + b.toFixed(3) + "</b><br>";
|
| 344 |
+
body += patch
|
| 345 |
+
? "<span class='sub'>7 A patch: " + patch.size + " residues · rASA " + patch.rasa + "</span>"
|
| 346 |
+
: "<span class='sub'>buried (rASA ≤ 0.20) — no patch</span>";
|
| 347 |
+
}}
|
| 348 |
+
showTip(body);
|
| 349 |
+
|
| 350 |
+
if (patch) {{
|
| 351 |
+
try {{
|
| 352 |
+
const l = lociForKeys(patch.members);
|
| 353 |
+
if (l) plugin.managers.interactivity.lociHighlights.highlightOnly({{ loci: l }});
|
| 354 |
+
}} catch (e) {{ /* highlight is a bonus; never break the tooltip */ }}
|
| 355 |
+
}}
|
| 356 |
+
}});
|
| 357 |
+
view.addEventListener("mouseleave", hideTip);
|
| 358 |
+
}} catch (e) {{ console.warn("hover wiring failed:", e); }}
|
| 359 |
+
}})();
|
| 360 |
</script>
|
| 361 |
</body></html>"""
|
| 362 |
|
|
|
|
| 401 |
raise gr.Error("no amino-acid residues in the selection -- this model scores protein targets")
|
| 402 |
|
| 403 |
s = pred.scores()
|
| 404 |
+
# No mean of the scores. Each per-residue value is already an aggregate over that
|
| 405 |
+
# residue's 7 A patch, so averaging them again produces a number that means nothing
|
| 406 |
+
# -- and it would be dominated by the buried majority, which are 0 by construction.
|
| 407 |
+
# The peak and the counts above a threshold are the quantities that read honestly.
|
| 408 |
summary = (
|
| 409 |
f"**{stem}** · {len(prot)} protein residues scored "
|
| 410 |
f" · chains {' '.join(pred.chains)} · {pred.num_atoms} atoms \n"
|
| 411 |
+
f"peak **{s.max():.3f}** · "
|
| 412 |
f"{int((s >= 0.5).sum())} residues ≥ 0.50 · "
|
| 413 |
f"{int((s >= 0.2).sum())} residues ≥ 0.20"
|
| 414 |
)
|
| 415 |
|
| 416 |
+
# the 7 A patch each value refers to, on the scored file so the keys match what the
|
| 417 |
+
# viewer reads back. A failure here costs the hover detail, not the prediction.
|
| 418 |
+
try:
|
| 419 |
+
patch_index = compute_patches(out_pdb)
|
| 420 |
+
except Exception as e:
|
| 421 |
+
traceback.print_exc()
|
| 422 |
+
print(f"[bcprop] patch index unavailable: {type(e).__name__}: {e}")
|
| 423 |
+
patch_index = {}
|
| 424 |
|
| 425 |
+
viewer = _iframe(_viewer_document(pred.pdb_text, patch_index, style))
|
| 426 |
+
return viewer, summary, out_pdb, out_csv
|
| 427 |
|
| 428 |
|
| 429 |
INTRO = """
|
|
|
|
| 432 |
A [PeSTo](https://github.com/LBM-EPFL/PeSTo) geometric transformer that scores **every
|
| 433 |
residue of a target for how well a BindCraft binder could bury it**. Give it a structure;
|
| 434 |
it gives the structure back with the score in the **B-factor column**, ready to open in
|
| 435 |
+
PyMOL or ChimeraX (`spectrum b, grey80_red, minimum=0, maximum=1`).
|
| 436 |
|
| 437 |
The score estimates the fraction of independent BindCraft trajectories whose interface
|
| 438 |
would fully cover that residue's local surface patch (7 Å CB–CB, solvent-exposed
|
|
|
|
| 485 |
out_view = gr.HTML()
|
| 486 |
|
| 487 |
with gr.Row():
|
| 488 |
+
out_pdb = gr.File(label="Scored PDB (propensity in B-factors)")
|
| 489 |
+
out_csv = gr.File(label="Per-residue CSV")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 490 |
|
| 491 |
go.click(
|
| 492 |
score,
|
| 493 |
inputs=[f_in, id_in, ch_in, st_in],
|
| 494 |
+
outputs=[out_view, out_summary, out_pdb, out_csv],
|
| 495 |
)
|
| 496 |
|
| 497 |
examples_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "examples")
|
patches.py
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The 7 A surface patch each propensity value actually refers to.
|
| 2 |
+
|
| 3 |
+
The model's target is *patch coverage*: residue i scores high when a design's interface
|
| 4 |
+
buries all of P(i), not just i itself. So the number on a residue is a statement about a
|
| 5 |
+
neighbourhood, and showing that neighbourhood is the difference between a colour and a
|
| 6 |
+
claim you can check.
|
| 7 |
+
|
| 8 |
+
The definition here is copied from PeSTo's `src/surface.py` and
|
| 9 |
+
`processing/patch_labels.md`, and must not drift from them -- a patch drawn under
|
| 10 |
+
different rules would be illustrating a label the model was never trained on:
|
| 11 |
+
|
| 12 |
+
* accessibility : Bio.PDB Shrake-Rupley, computed on the whole model
|
| 13 |
+
* relative ASA : residue SASA / max-ASA, Sander scale
|
| 14 |
+
* exposed : rASA strictly greater than 0.20
|
| 15 |
+
* representative : CB, falling back to CA (GLY; measured as the only case)
|
| 16 |
+
* patch : P(i) = { j in exposed : d(CB_i, CB_j) <= 7 A } union {i}
|
| 17 |
+
|
| 18 |
+
Buried residues have no patch: they are not centres, and the label is 0 there by
|
| 19 |
+
construction rather than by prediction.
|
| 20 |
+
"""
|
| 21 |
+
|
| 22 |
+
import numpy as np
|
| 23 |
+
|
| 24 |
+
from Bio.Data.PDBData import residue_sasa_scales
|
| 25 |
+
from Bio.PDB import PDBParser
|
| 26 |
+
from Bio.PDB.SASA import ShrakeRupley
|
| 27 |
+
|
| 28 |
+
SASA_SCALE = "Sander"
|
| 29 |
+
RASA_THRESHOLD = 0.20
|
| 30 |
+
PATCH_RADIUS = 7.0
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def _representative_atom(res):
|
| 34 |
+
"""CB if present, else CA. Matches PeSTo's convention exactly."""
|
| 35 |
+
if "CB" in res:
|
| 36 |
+
return res["CB"]
|
| 37 |
+
if "CA" in res:
|
| 38 |
+
return res["CA"]
|
| 39 |
+
return None
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def residue_key(chain_id, seq_id, icode=""):
|
| 43 |
+
return "{}|{}|{}".format(chain_id, seq_id, (icode or "").strip())
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def compute_patches(pdb_filepath, rasa_threshold=RASA_THRESHOLD,
|
| 47 |
+
radius=PATCH_RADIUS, scale_name=SASA_SCALE):
|
| 48 |
+
"""Return {residue_key: {"members": [key, ...], "size": n, "rasa": float}}.
|
| 49 |
+
|
| 50 |
+
Only exposed residues get an entry. Keys are the *input file's* chain id, residue
|
| 51 |
+
number and insertion code, matching what the viewer reads back from the structure.
|
| 52 |
+
"""
|
| 53 |
+
scale = residue_sasa_scales[scale_name]
|
| 54 |
+
|
| 55 |
+
structure = PDBParser(QUIET=True).get_structure("s", pdb_filepath)
|
| 56 |
+
model = structure[0] # first model only, as PeSTo does
|
| 57 |
+
|
| 58 |
+
# burial must be computed with the whole model present, not chain by chain
|
| 59 |
+
ShrakeRupley().compute(model, level="R")
|
| 60 |
+
|
| 61 |
+
keys, coords, rasas = [], [], []
|
| 62 |
+
for chain in model:
|
| 63 |
+
for res in chain:
|
| 64 |
+
if res.id[0] != " ": # skip het/water
|
| 65 |
+
continue
|
| 66 |
+
resname = res.get_resname()
|
| 67 |
+
if resname not in scale: # no reference max-ASA -> not a standard aa
|
| 68 |
+
continue
|
| 69 |
+
atom = _representative_atom(res)
|
| 70 |
+
if atom is None:
|
| 71 |
+
continue
|
| 72 |
+
|
| 73 |
+
rasa = res.sasa / scale[resname]
|
| 74 |
+
if rasa <= rasa_threshold:
|
| 75 |
+
continue
|
| 76 |
+
|
| 77 |
+
keys.append(residue_key(chain.id, res.id[1], res.id[2]))
|
| 78 |
+
coords.append(np.asarray(atom.get_coord(), dtype=np.float64))
|
| 79 |
+
rasas.append(float(rasa))
|
| 80 |
+
|
| 81 |
+
if not keys:
|
| 82 |
+
return {}
|
| 83 |
+
|
| 84 |
+
X = np.asarray(coords)
|
| 85 |
+
# exposed sets are small (hundreds), so the dense distance matrix is cheap and exact
|
| 86 |
+
D = np.linalg.norm(X[:, None, :] - X[None, :, :], axis=2)
|
| 87 |
+
within = D <= radius
|
| 88 |
+
|
| 89 |
+
patches = {}
|
| 90 |
+
for i, k in enumerate(keys):
|
| 91 |
+
members = [keys[j] for j in np.flatnonzero(within[i])]
|
| 92 |
+
if k not in members: # i in P(i) by definition; D[i,i]=0 so this holds
|
| 93 |
+
members.append(k)
|
| 94 |
+
patches[k] = {"members": members, "size": len(members), "rasa": round(rasas[i], 3)}
|
| 95 |
+
|
| 96 |
+
return patches
|
requirements-local.txt
CHANGED
|
@@ -9,3 +9,4 @@ torch>=2.2
|
|
| 9 |
numpy<2
|
| 10 |
gemmi>=0.6
|
| 11 |
gradio>=5.0
|
|
|
|
|
|
| 9 |
numpy<2
|
| 10 |
gemmi>=0.6
|
| 11 |
gradio>=5.0
|
| 12 |
+
biopython>=1.80 # Shrake-Rupley SASA for the 7 A patch index (patches.py)
|
requirements.txt
CHANGED
|
@@ -15,3 +15,4 @@ numpy==1.26.4 # 2.x changes scalar promotion; 1.26 is what the numerics w
|
|
| 15 |
gemmi==0.7.5 # PDB/mmCIF parsing and writing
|
| 16 |
gradio==5.49.1
|
| 17 |
spaces # ZeroGPU decorator; HF preinstalls it, pinned here so it is explicit
|
|
|
|
|
|
| 15 |
gemmi==0.7.5 # PDB/mmCIF parsing and writing
|
| 16 |
gradio==5.49.1
|
| 17 |
spaces # ZeroGPU decorator; HF preinstalls it, pinned here so it is explicit
|
| 18 |
+
biopython>=1.80 # Shrake-Rupley SASA for the 7 A patch index (patches.py)
|