AI4deeperScience commited on
Commit
5b3b0dc
·
verified ·
1 Parent(s): 6493ec3

release: publish claim-safe Q9UQB9 custom prediction workflow

Browse files

Removes retired case-study views; deploys the audited custom prediction interface and Q9UQB9 example.

README.md CHANGED
@@ -1,61 +1,37 @@
1
  ---
2
  title: BioInteract Drug-Target Interaction
3
- emoji: 🧬
4
  colorFrom: blue
5
  colorTo: green
6
  sdk: gradio
7
- sdk_version: 5.20.0
8
  python_version: "3.11"
9
  app_file: app.py
10
  pinned: false
11
  license: mit
12
- short_description: Interpretable DTI prediction with cross-attention
13
  ---
14
 
15
  # BioInteract
16
 
17
- **Interpretable Drug–Target Interaction Prediction via Residue-Level Cross-Attention with Biological Prior Knowledge**
18
 
19
- BioInteract is a deep learning framework that predicts whether a drug molecule will bind to a protein target, while simultaneously generating an interpretable atom–residue interaction map that shows *which* drug atoms interact with *which* protein residues.
20
 
21
- ## How to Use
22
 
23
- ### Tab 1 — Case Studies
24
- Explore three pre-computed, clinically validated drug–target pairs:
25
- - **ABL1(E255K) + Drug 5328940** (resistance mutant, Kd = 0.047 nM)
26
- - **EGFR + Drug 156414** (kinase inhibitor)
27
- - **BRAF + Drug 11717001** (RAF inhibitor)
28
 
29
- Each case shows the full atom–residue interaction heatmap, top binding residues, and model prediction probability.
30
 
31
- ### Tab 2 — Custom Prediction
32
- Enter any drug SMILES string and protein amino acid sequence.
33
- The model will:
34
- 1. Encode the drug via pharmacophore-aware GINE molecular graph
35
- 2. Encode the protein using ESM-2 (150M) residue embeddings + physicochemical features
36
- 3. Compute bidirectional cross-attention to generate an interaction map
37
- 4. Predict binding probability
38
 
39
- > **Note:** First prediction on CPU may take 1–3 minutes as ESM-2 initialises.
40
- > Sequences are truncated to 512 residues for demo speed.
41
 
42
- ## Model Architecture
43
 
44
- ```
45
- Drug (SMILES) → GINE encoder → atom representations
46
- Protein (AA seq) → ESM-2 + physicochemical → residue representations
47
- ↓ bidirectional cross-attention ↓
48
- atom × residue interaction map → gated pooling → binding score
49
- ```
50
-
51
- ## Performance (Davis Kinase Dataset)
52
-
53
- | Split | AUROC | AUPRC |
54
- |-------|-------|-------|
55
- | Random | 0.921 | 0.608 |
56
- | Cold-Drug | 0.739 | 0.169 |
57
- | Cold-Target | **0.941** | 0.549 |
58
-
59
- ## Citation
60
-
61
- > BioInteract: Interpretable Drug–Target Interaction Prediction via Residue-Level Cross-Attention with Biological Prior Knowledge, 2026.
 
1
  ---
2
  title: BioInteract Drug-Target Interaction
3
+ emoji: 🧬
4
  colorFrom: blue
5
  colorTo: green
6
  sdk: gradio
7
+ sdk_version: 5.0.0
8
  python_version: "3.11"
9
  app_file: app.py
10
  pinned: false
11
  license: mit
12
+ short_description: Binary high-affinity DTI with model-native attribution
13
  ---
14
 
15
  # BioInteract
16
 
17
+ BioInteract supports **binary high-affinity interaction classification** on the Davis kinase benchmark. The browser interface returns a **classifier score** and **model-native atom-residue attention attribution**. Attribution is hypothesis-generating; it is **not physical contacts**, binding-residue evidence, or a structural mechanism.
18
 
19
+ ## Browser demonstration scope
20
 
21
+ The custom workflow accepts a drug SMILES string and a protein sequence. It uses Hugging Face Transformers with a **512-residue** input limit and initialises ESM-2 during application startup. For arbitrary user-supplied sequences, the configured domain-label channel uses an **unknown-domain representation** because curated annotations are not released with this demonstration.
22
 
23
+ The browser demonstration is **not numerically equivalent** to the reported **1,200-residue** evaluation pipeline, which uses cached fair-ESM embeddings. It must not be used to reproduce the reported metrics or to interpret its sigmoid classifier score as a calibrated measure.
 
 
 
 
24
 
25
+ ## Reported Davis results
26
 
27
+ | Partition | AUROC | AUPRC |
28
+ |---|---:|---:|
29
+ | Random | 0.904 | 0.560 |
30
+ | Drug-ID-held-out | 0.733 | 0.167 |
31
+ | Target-ID-held-out | 0.930 | 0.525 |
 
 
32
 
33
+ Target-ID-held-out is an archived identifier-based split result. Duplicate Davis protein sequences mean it is not a strict exact-sequence-held-out estimate.
 
34
 
35
+ ## Interpretation limit
36
 
37
+ The heatmap and residue chart rank model-native attribution. They do not identify binding residues, key contacts, a binding pocket, or a mechanistic interaction map.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
app.py CHANGED
@@ -1,785 +1,374 @@
1
- """
2
- app.py — BioInteract Gradio Space
3
- Interpretable Drug–Target Interaction Prediction
4
-
5
- Two tabs:
6
- 1. Case Studies — pre-computed, clinically validated pairs
7
- 2. Custom Prediction — user supplies SMILES + protein sequence
8
- """
9
- import sys
10
- import json
11
- import io
12
- import warnings
13
- from pathlib import Path
14
-
15
- import numpy as np
16
- import torch
17
- import yaml
18
- import matplotlib
19
- matplotlib.use('Agg')
20
- import matplotlib as mpl
21
- import matplotlib.pyplot as plt
22
- import seaborn as sns
23
- import gradio as gr
24
- from PIL import Image
25
-
26
- # ── Patch gradio_client bool-schema bug (affects gradio 5.0–5.20) ──────────
27
- # gradio_client._json_schema_to_python_type calls "const" in schema where
28
- # schema can be a JSON-Schema boolean (e.g. additionalProperties: false).
29
- # Python raises TypeError; this shim returns "any" for non-dict schemas.
30
- import gradio_client.utils as _gc_utils
31
- _orig_schema_fn = _gc_utils._json_schema_to_python_type
32
-
33
- def _safe_schema_fn(schema, defs=None):
34
- if not isinstance(schema, dict):
35
- return "any"
36
- return _orig_schema_fn(schema, defs)
37
-
38
- _gc_utils._json_schema_to_python_type = _safe_schema_fn
39
- # ────────────────────────────────────────────────────────────────────────────
40
-
41
- # ---------- path setup ----------
42
- ROOT = Path(__file__).parent
43
- sys.path.insert(0, str(ROOT))
44
-
45
- from src.models.biointeract import BioInteract
46
- from src.data.mol_graph import smiles_to_graph
47
- from src.data.protein_feat import residue_physicochemical_features, residue_domain_labels
48
-
49
- # ---------- publication-style matplotlib defaults ----------
50
- mpl.rcParams.update({
51
- 'font.family': 'DejaVu Serif',
52
- 'font.size': 10,
53
- 'axes.titlesize': 11,
54
- 'axes.titleweight': 'bold',
55
- 'axes.labelsize': 10,
56
- 'axes.labelcolor': '#1a1a2e',
57
- 'axes.edgecolor': '#444',
58
- 'axes.linewidth': 0.8,
59
- 'axes.spines.top': False,
60
- 'axes.spines.right': False,
61
- 'xtick.direction': 'out',
62
- 'ytick.direction': 'out',
63
- 'xtick.color': '#444',
64
- 'ytick.color': '#444',
65
- 'figure.facecolor': 'white',
66
- 'axes.facecolor': '#fafafa',
67
- 'grid.color': '#e0e0e0',
68
- 'grid.linewidth': 0.5,
69
- 'savefig.facecolor': 'white',
70
- 'savefig.dpi': 150,
71
- })
72
-
73
- # ============================================================
74
- # Global model loading
75
- # ============================================================
76
-
77
- DEVICE = torch.device('cpu')
78
- _CONFIG_PATH = ROOT / 'configs' / 'default.yaml'
79
- _CKPT_PATH = ROOT / 'checkpoints' / 'best.pt'
80
- _REPORT_PATH = ROOT / 'examples' / 'interpretability_report.json'
81
-
82
- print("[BioInteract] Loading model config …")
83
- with open(_CONFIG_PATH) as f:
84
- _CONFIG = yaml.safe_load(f)
85
-
86
- print("[BioInteract] Loading pretrained weights …")
87
- _model = BioInteract(_CONFIG['model']).to(DEVICE)
88
- _ckpt = torch.load(_CKPT_PATH, map_location='cpu', weights_only=False)
89
- _model.load_state_dict(_ckpt['model_state_dict'])
90
- _model.eval()
91
- print(f"[BioInteract] Model ready — epoch {_ckpt.get('epoch','?')}, "
92
- f"params = {sum(p.numel() for p in _model.parameters()):,}")
93
-
94
- with open(_REPORT_PATH) as f:
95
- _REPORT = json.load(f)
96
-
97
- # ============================================================
98
- # ESM-2 — eager load at startup so predictions are instant
99
- # ============================================================
100
-
101
- ESM_MODEL_NAME = "facebook/esm2_t30_150M_UR50D"
102
-
103
- print("[BioInteract] Downloading / loading ESM-2 (150 M params) — please wait …")
104
- try:
105
- from transformers import EsmModel, EsmTokenizer
106
- _esm_tokenizer = EsmTokenizer.from_pretrained(ESM_MODEL_NAME)
107
- _esm_model = EsmModel.from_pretrained(ESM_MODEL_NAME).eval()
108
- print("[BioInteract] ESM-2 ready")
109
- _ESM_LOAD_ERROR = None
110
- except Exception as _e:
111
- print(f"[BioInteract] WARNING: ESM-2 failed to load: {_e}")
112
- _esm_tokenizer = None
113
- _esm_model = None
114
- _ESM_LOAD_ERROR = str(_e)
115
-
116
-
117
- def _get_esm():
118
- if _ESM_LOAD_ERROR:
119
- raise RuntimeError(f"ESM-2 unavailable: {_ESM_LOAD_ERROR}")
120
- return _esm_tokenizer, _esm_model
121
-
122
-
123
- def compute_esm2_embedding(sequence: str, max_len: int = 512) -> torch.Tensor:
124
- """Run ESM-2 and return per-residue embeddings (L, 640)."""
125
- seq = sequence[:max_len]
126
- tokenizer, esm = _get_esm()
127
- inputs = tokenizer(seq, return_tensors='pt', add_special_tokens=True)
128
- with torch.no_grad():
129
- outputs = esm(**inputs)
130
- embedding = outputs.last_hidden_state[0, 1:-1, :]
131
- return embedding[:len(seq)]
132
-
133
-
134
- # ============================================================
135
- # Publication-quality plotting helpers
136
- # ============================================================
137
-
138
- _HEATMAP_CMAP = 'Blues'
139
- _BAR_COLOR = '#1a4a7a'
140
- _BAR_ACCENT = '#2e7cbf'
141
- _FG_COLOR = '#8b2635'
142
-
143
-
144
- def _plot_interaction_heatmap(
145
- interaction_map: np.ndarray,
146
- sequence: str,
147
- title: str = 'Atom–Residue Interaction Map',
148
- ) -> Image.Image:
149
- """Render interaction heatmap with publication-quality styling."""
150
- n_atoms, n_res = interaction_map.shape
151
-
152
- max_show_res = 80
153
- if n_res > max_show_res:
154
- scores = interaction_map.sum(axis=0)
155
- center = int(np.argmax(scores))
156
- start = max(0, center - max_show_res // 2)
157
- end = min(n_res, start + max_show_res)
158
- interaction_map = interaction_map[:, start:end]
159
- res_labels = [f"{sequence[i]}{i+1}" if i < len(sequence) else str(i+1)
160
- for i in range(start, end)]
161
- else:
162
- res_labels = [f"{sequence[i]}{i+1}" if i < len(sequence) else str(i+1)
163
- for i in range(n_res)]
164
-
165
- figw = max(13, len(res_labels) * 0.16)
166
- figh = max(5, n_atoms * 0.28)
167
- fig, ax = plt.subplots(figsize=(figw, figh))
168
-
169
- sns.heatmap(
170
- interaction_map,
171
- xticklabels=res_labels,
172
- yticklabels=[f"a{i+1}" for i in range(n_atoms)],
173
- cmap=_HEATMAP_CMAP,
174
- ax=ax,
175
- linewidths=0,
176
- cbar_kws={'label': 'Normalised Attention Score', 'shrink': 0.75,
177
- 'aspect': 20},
178
- )
179
- ax.set_title(title, pad=10)
180
- ax.set_xlabel('Protein Residue', labelpad=6)
181
- ax.set_ylabel('Drug Atom', labelpad=6)
182
- plt.xticks(rotation=90, fontsize=5.5)
183
- plt.yticks(fontsize=6, rotation=0)
184
-
185
- for spine in ax.spines.values():
186
- spine.set_visible(False)
187
-
188
- fig.text(0.02, 0.01,
189
- 'Colour intensity encodes normalised cross-attention weight',
190
- fontsize=7, color='#666', style='italic')
191
- plt.tight_layout(rect=[0, 0.03, 1, 1])
192
-
193
- buf = io.BytesIO()
194
- fig.savefig(buf, format='png', bbox_inches='tight')
195
- plt.close(fig)
196
- buf.seek(0)
197
- return Image.open(buf).copy()
198
-
199
-
200
- def _plot_top_residues(top_residues: list, title: str = 'Top Binding Residues') -> Image.Image:
201
- """Horizontal bar chart with academic styling."""
202
- labels = [r[0] for r in top_residues]
203
- scores = [r[1] for r in top_residues]
204
-
205
- fig, ax = plt.subplots(figsize=(8, 4.2))
206
- colors = [_BAR_COLOR if s >= 0.5 else _BAR_ACCENT for s in scores[::-1]]
207
- bars = ax.barh(labels[::-1], scores[::-1],
208
- color=colors, edgecolor='none', height=0.65)
209
-
210
- ax.set_xlabel('Normalised Attention Score', labelpad=6)
211
- ax.set_title(title, pad=8)
212
- ax.set_xlim(0, 1.12)
213
- ax.axvline(0.5, color='#aaa', linewidth=0.8, linestyle='--', alpha=0.7)
214
- ax.text(0.51, -0.6, 'threshold', fontsize=7, color='#888', style='italic')
215
-
216
- for bar, score in zip(bars, scores[::-1]):
217
- ax.text(score + 0.015, bar.get_y() + bar.get_height() / 2,
218
- f'{score:.3f}', va='center', fontsize=8, color='#222')
219
-
220
- ax.set_axisbelow(True)
221
- ax.yaxis.set_tick_params(labelsize=9)
222
- plt.tight_layout()
223
-
224
- buf = io.BytesIO()
225
- fig.savefig(buf, format='png', bbox_inches='tight')
226
- plt.close(fig)
227
- buf.seek(0)
228
- return Image.open(buf).copy()
229
-
230
-
231
- def _plot_functional_groups(fg_dict: dict, title: str = 'Pharmacophore Importance') -> Image.Image:
232
- """Horizontal bar chart for functional group Grad-CAM scores."""
233
- if not fg_dict:
234
- return None
235
- labels = list(fg_dict.keys())
236
- scores = list(fg_dict.values())
237
-
238
- fig, ax = plt.subplots(figsize=(7, max(3, len(labels) * 0.55)))
239
- ax.barh(labels, scores, color=_FG_COLOR, edgecolor='none', height=0.6, alpha=0.85)
240
- ax.set_xlabel('Grad-CAM Importance Score', labelpad=6)
241
- ax.set_title(title, pad=8)
242
- ax.set_xlim(0, 1.12)
243
- for i, (label, score) in enumerate(zip(labels, scores)):
244
- ax.text(score + 0.015, i, f'{score:.3f}', va='center', fontsize=8, color='#222')
245
- ax.set_axisbelow(True)
246
- plt.tight_layout()
247
-
248
- buf = io.BytesIO()
249
- fig.savefig(buf, format='png', bbox_inches='tight')
250
- plt.close(fig)
251
- buf.seek(0)
252
- return Image.open(buf).copy()
253
-
254
-
255
- # ============================================================
256
- # Tab 1 — Case Studies
257
- # ============================================================
258
-
259
- _FIXED_CASES = {
260
- 'ABL1(E255K) + Drug 5328940 (Kd = 0.047 nM)': {
261
- 'png': ROOT / 'examples' / '5328940_ABL1E255K.png',
262
- 'prob': 0.988,
263
- 'affinity_nM': 0.047,
264
- 'top_residues': [['V104', 1.0], ['A648', 0.503], ['S199', 0.417],
265
- ['P649', 0.281], ['P936', 0.237], ['N707', 0.192],
266
- ['P651', 0.180], ['L799', 0.166], ['K796', 0.141], ['P934', 0.079]],
267
- 'functional_groups': {'Halogen': 0.650, 'Amino': 0.616, 'Ether': 0.345,
268
- 'Aromatic Ring': 0.311, 'Heterocycle N': 0.167},
269
- 'description': (
270
- 'Drug 5328940 binds the ABL1 E255K resistance mutant with extremely high '
271
- 'affinity (Kd = 0.047 nM). The model predicts binding with 98.8% probability. '
272
- 'Key contacts include V104 (gatekeeper residue), A648, and S199, consistent '
273
- 'with known structural data for Type II kinase inhibitors.'
274
- ),
275
- },
276
- 'EGFR + Drug 156414': {
277
- 'png': ROOT / 'examples' / '156414_EGFR.png',
278
- 'prob': None,
279
- 'affinity_nM': None,
280
- 'top_residues': [],
281
- 'functional_groups': {},
282
- 'description': (
283
- 'Drug 156414 targets the wild-type EGFR kinase domain. '
284
- 'EGFR inhibitors are first-line treatments for non-small cell lung cancer '
285
- 'with activating mutations. The interaction map highlights the ATP-binding cleft.'
286
- ),
287
- },
288
- 'BRAF + Drug 11717001 (Sorafenib analogue)': {
289
- 'png': ROOT / 'examples' / '11717001_BRAF.png',
290
- 'prob': None,
291
- 'affinity_nM': None,
292
- 'top_residues': [],
293
- 'functional_groups': {},
294
- 'description': (
295
- 'Drug 11717001 is a Sorafenib analogue targeting BRAF kinase, a driver '
296
- 'oncogene in ~50% of cutaneous melanomas (V600E mutation). RAF inhibitors '
297
- 'block the MAPK/ERK signalling cascade that promotes uncontrolled proliferation.'
298
- ),
299
- },
300
- }
301
-
302
-
303
- def show_case_study(case_key: str):
304
- """Called when user selects a case from the dropdown."""
305
- case = _FIXED_CASES.get(case_key)
306
- if case is None:
307
- return None, None, None, "Case not found."
308
-
309
- heatmap_img = Image.open(case['png']) if case['png'].exists() else None
310
-
311
- prob_text = (f"**Predicted binding probability:** {case['prob']*100:.1f}%\n\n"
312
- if case['prob'] else "")
313
- kd_text = (f"**Experimental affinity (Kd):** {case['affinity_nM']} nM\n\n"
314
- if case['affinity_nM'] else "")
315
- info_md = (
316
- f"#### {case_key.strip()}\n\n"
317
- f"{prob_text}{kd_text}"
318
- f"**Clinical context:** {case['description']}"
319
- )
320
-
321
- residue_img = (
322
- _plot_top_residues(case['top_residues'],
323
- f'Top Binding Residues — {case_key.split("+")[0].strip()}')
324
- if case['top_residues'] else None
325
- )
326
- fg_img = (
327
- _plot_functional_groups(case['functional_groups'],
328
- f'Pharmacophore Importance — {case_key.split("+")[0].strip()}')
329
- if case['functional_groups'] else None
330
- )
331
-
332
- return heatmap_img, residue_img, fg_img, info_md
333
-
334
-
335
- # ============================================================
336
- # Tab 2 — Custom Prediction
337
- # ============================================================
338
-
339
- _EXAMPLE_SMILES = (
340
- "Cc1ccc(NC(=O)c2ccc(CN3CCN(C)CC3)cc2)cc1Nc1nccc(-c2cccnc2)n1"
341
- )
342
- _EXAMPLE_SEQUENCE = (
343
- "MGPSENDPNLFVALYDFVASGDNTLSITKGEKLRVLGYNHNGEWCEAQTKNGQGWVPSNYITPVNSLEKHSWYHGPVSRNAAEYLLSSGINGSFLVRESESSPGQRSISLRYEGRVYHYRINTASDGKLYVSSESRFNTLAELVHHHSTLVQHSDSVESAYRSKL"
344
- "LNSGVYHYRINTASDGKLYVSSESRFNTLAELVHHHSTLVQ"
345
- )
346
-
347
- MAX_SEQ_LEN = 512
348
-
349
-
350
- def run_prediction(smiles: str, sequence: str, progress=gr.Progress()):
351
- """
352
- Full inference pipeline: SMILES + sequence → probability + interaction heatmap.
353
- Returns: (status_msg, prob_text, heatmap_image, residue_image)
354
- """
355
- smiles = (smiles or '').strip()
356
- sequence = (sequence or '').strip().upper()
357
-
358
- if not smiles:
359
- return "Input required: please provide a SMILES string.", "", None, None
360
- if not sequence:
361
- return "Input required: please provide an amino acid sequence.", "", None, None
362
-
363
- progress(0.1, desc="Parsing SMILES string via RDKit …")
364
- drug_graph = smiles_to_graph(smiles)
365
- if drug_graph is None:
366
- return "Parse error: RDKit could not interpret the SMILES string.", "", None, None
367
-
368
- from torch_geometric.data import Batch
369
- drug_batch = Batch.from_data_list([drug_graph]).to(DEVICE)
370
-
371
- seq = sequence[:MAX_SEQ_LEN]
372
- if len(sequence) > MAX_SEQ_LEN:
373
- warnings.warn(f"Sequence truncated to {MAX_SEQ_LEN} residues.")
374
- L = len(seq)
375
-
376
- progress(0.2, desc="Computing ESM-2 residue embeddings …")
377
- try:
378
- esm2_emb = compute_esm2_embedding(seq)
379
- except Exception as e:
380
- return f"ESM-2 error: {e}", "", None, None
381
-
382
- esm2_emb = esm2_emb.unsqueeze(0).to(DEVICE)
383
- physchem = residue_physicochemical_features(seq).unsqueeze(0).to(DEVICE)
384
- domain = residue_domain_labels(L).unsqueeze(0).to(DEVICE)
385
- prot_mask = torch.ones(1, L, dtype=torch.bool, device=DEVICE)
386
-
387
- progress(0.85, desc="Running BioInteract cross-attention inference …")
388
- with torch.no_grad():
389
- logit, attn_data = _model(
390
- drug_batch, esm2_emb, physchem, domain, prot_mask,
391
- return_attention=True
392
- )
393
-
394
- prob = torch.sigmoid(logit).item()
395
- interaction_map = attn_data['interaction_map'][0].cpu().numpy()
396
- drug_mask_np = attn_data['drug_mask'][0].cpu().numpy()
397
-
398
- n_real_atoms = int(drug_mask_np.sum())
399
- imap = interaction_map[:n_real_atoms, :L]
400
-
401
- residue_scores = imap.sum(axis=0)
402
- residue_scores = residue_scores / (residue_scores.max() + 1e-9)
403
- top_idx = np.argsort(residue_scores)[::-1][:10]
404
- top_residues = [[f"{seq[i]}{i+1}", float(residue_scores[i])] for i in top_idx]
405
-
406
- progress(0.95, desc="Generating publication-quality figures …")
407
- heatmap_img = _plot_interaction_heatmap(imap, seq, title='Atom–Residue Cross-Attention Map')
408
- residue_img = _plot_top_residues(top_residues, 'Top 10 Predicted Binding Residues')
409
-
410
- label = "**BINDING**" if prob > 0.5 else "**NON-BINDING**"
411
- conf = "High confidence" if abs(prob - 0.5) > 0.3 else "Moderate confidence"
412
- prob_text = (
413
- f"### Prediction Result: {label}\n\n"
414
- f"| Metric | Value |\n"
415
- f"|--------|-------|\n"
416
- f"| Binding probability | **{prob * 100:.1f}%** |\n"
417
- f"| Confidence | {conf} |\n"
418
- f"| Drug atoms analysed | {n_real_atoms} |\n"
419
- f"| Protein residues analysed | {L} |\n"
420
- )
421
-
422
- return "Inference complete.", prob_text, heatmap_img, residue_img
423
-
424
-
425
- # ============================================================
426
- # Global statistics panel
427
- # ============================================================
428
-
429
- _GLOBAL_STATS = _REPORT.get('global_stats', {})
430
-
431
- _SIDEBAR_HTML = f"""
432
- <div style="background:#f8f9fa; border:1px solid #dee2e6; border-radius:6px; padding:16px; font-family:'Georgia',serif;">
433
-
434
- <div style="border-bottom:2px solid #1a4a7a; margin-bottom:12px; padding-bottom:6px;">
435
- <strong style="color:#1a4a7a; font-size:0.9rem; text-transform:uppercase; letter-spacing:0.04em;">
436
- Performance Metrics
437
- </strong><br>
438
- <span style="color:#666; font-size:0.78rem;">Davis Kinase Benchmark Dataset</span>
439
- </div>
440
-
441
- <table style="width:100%; border-collapse:collapse; font-size:0.82rem; margin-bottom:14px;">
442
- <thead>
443
- <tr style="background:#1a4a7a; color:white;">
444
- <th style="padding:6px 8px; text-align:left; font-weight:600;">Split</th>
445
- <th style="padding:6px 8px; text-align:center; font-weight:600;">AUROC</th>
446
- <th style="padding:6px 8px; text-align:center; font-weight:600;">AUPRC</th>
447
- </tr>
448
- </thead>
449
- <tbody>
450
- <tr style="background:#eef2f7;">
451
- <td style="padding:5px 8px;">Random</td>
452
- <td style="padding:5px 8px; text-align:center;">0.921</td>
453
- <td style="padding:5px 8px; text-align:center;">0.608</td>
454
- </tr>
455
- <tr>
456
- <td style="padding:5px 8px;">Cold-Drug</td>
457
- <td style="padding:5px 8px; text-align:center;">0.739</td>
458
- <td style="padding:5px 8px; text-align:center;">0.169</td>
459
- </tr>
460
- <tr style="background:#eef2f7;">
461
- <td style="padding:5px 8px;"><strong>Cold-Target</strong></td>
462
- <td style="padding:5px 8px; text-align:center;"><strong>0.941</strong></td>
463
- <td style="padding:5px 8px; text-align:center;"><strong>0.549</strong></td>
464
- </tr>
465
- </tbody>
466
- </table>
467
-
468
- <div style="border-bottom:1px solid #dee2e6; margin-bottom:10px; padding-bottom:4px;">
469
- <strong style="color:#1a4a7a; font-size:0.85rem;">Model Specifications</strong>
470
- </div>
471
- <table style="width:100%; border-collapse:collapse; font-size:0.81rem; margin-bottom:14px;">
472
- <tr><td style="padding:4px 0; color:#555;">Parameters</td>
473
- <td style="padding:4px 0; text-align:right;">{_REPORT.get('model_info', {}).get('params', 2_442_083):,}</td></tr>
474
- <tr><td style="padding:4px 0; color:#555;">Training samples</td>
475
- <td style="padding:4px 0; text-align:right;">{_GLOBAL_STATS.get('n_samples', 1506):,}</td></tr>
476
- <tr><td style="padding:4px 0; color:#555;">Attention sparsity</td>
477
- <td style="padding:4px 0; text-align:right;">{_GLOBAL_STATS.get('attention_sparsity', 0.992)*100:.1f}%</td></tr>
478
- <tr><td style="padding:4px 0; color:#555;">GNN layers</td>
479
- <td style="padding:4px 0; text-align:right;">3 × GINE</td></tr>
480
- <tr><td style="padding:4px 0; color:#555;">Attention heads</td>
481
- <td style="padding:4px 0; text-align:right;">8</td></tr>
482
- <tr><td style="padding:4px 0; color:#555;">Hidden dimension</td>
483
- <td style="padding:4px 0; text-align:right;">256</td></tr>
484
- </table>
485
-
486
- <div style="border-bottom:1px solid #dee2e6; margin-bottom:10px; padding-bottom:4px;">
487
- <strong style="color:#1a4a7a; font-size:0.85rem;">Architecture Overview</strong>
488
- </div>
489
- <pre style="background:#1a2a3a; color:#c8d8e8; padding:10px; border-radius:4px; font-size:0.72rem; line-height:1.5; margin:0; overflow:auto;">
490
- Drug SMILES
491
- → GINE (3 layers, dim=256)
492
- → N × atom vectors
493
-
494
- Protein sequence
495
- → ESM-2 (150M params)
496
- → physicochemical (4-dim)
497
- → L × residue vectors
498
-
499
- Bidirectional cross-attention
500
- → N×L interaction map
501
- → gated pooling
502
- → binding score</pre>
503
-
504
- <div style="margin-top:14px; padding:10px; background:#fff8e1; border-left:3px solid #f9a825; border-radius:0 4px 4px 0; font-size:0.8rem; color:#555; line-height:1.5;">
505
- <strong style="color:#e65100;">Reference</strong><br>
506
- Wang S, Zhang Q <em>et al.</em> BioInteract: Interpretable DTI Prediction via
507
- Residue-Level Cross-Attention with Biological Prior Knowledge, 2026.
508
- </div>
509
- </div>
510
- """
511
-
512
- # ============================================================
513
- # Custom CSS
514
- # ============================================================
515
-
516
- _CSS = """
517
- .gradio-container {
518
- font-family: 'Georgia', 'Times New Roman', serif !important;
519
- max-width: 1440px !important;
520
- }
521
- .tab-nav {
522
- border-bottom: 2px solid #1a4a7a !important;
523
- }
524
- .tab-nav button {
525
- font-size: 0.82rem !important;
526
- font-weight: 600 !important;
527
- letter-spacing: 0.03em !important;
528
- text-transform: uppercase !important;
529
- color: #555 !important;
530
- }
531
- .tab-nav button.selected {
532
- color: #1a4a7a !important;
533
- border-bottom: 2px solid #1a4a7a !important;
534
- }
535
- label span {
536
- font-size: 0.82rem !important;
537
- font-weight: 600 !important;
538
- color: #1a2a3a !important;
539
- text-transform: uppercase !important;
540
- letter-spacing: 0.03em !important;
541
- }
542
- .gr-button-primary {
543
- background: #1a4a7a !important;
544
- border-color: #1a4a7a !important;
545
- }
546
- .gr-button-primary:hover {
547
- background: #0d2137 !important;
548
- }
549
- footer { display: none !important; }
550
- """
551
-
552
- # ============================================================
553
- # Build Gradio UI
554
- # ============================================================
555
-
556
- _HEADER_HTML = """
557
- <div style="
558
- background: linear-gradient(135deg, #0d2137 0%, #1a4a7a 100%);
559
- padding: 24px 32px 20px;
560
- border-radius: 8px;
561
- margin-bottom: 4px;
562
- ">
563
- <h1 style="
564
- color: #ffffff;
565
- margin: 0 0 6px;
566
- font-size: 1.65rem;
567
- font-weight: 700;
568
- font-family: 'Georgia', serif;
569
- letter-spacing: -0.3px;
570
- ">BioInteract</h1>
571
- <p style="
572
- color: #b0cee8;
573
- margin: 0 0 14px;
574
- font-size: 0.95rem;
575
- font-style: italic;
576
- font-family: 'Georgia', serif;
577
- line-height: 1.4;
578
- ">
579
- Interpretable Drug–Target Interaction Prediction via
580
- Residue-Level Cross-Attention with Biological Prior Knowledge
581
- </p>
582
- <div style="display: flex; gap: 8px; flex-wrap: wrap;">
583
- <span style="background:rgba(255,255,255,0.13); color:#d0e8ff;
584
- padding:3px 12px; border-radius:20px; font-size:0.76rem;
585
- font-family:monospace; letter-spacing:0.02em;">
586
- GINE Graph Encoder
587
- </span>
588
- <span style="background:rgba(255,255,255,0.13); color:#d0e8ff;
589
- padding:3px 12px; border-radius:20px; font-size:0.76rem;
590
- font-family:monospace; letter-spacing:0.02em;">
591
- ESM-2 (150 M)
592
- </span>
593
- <span style="background:rgba(255,255,255,0.13); color:#d0e8ff;
594
- padding:3px 12px; border-radius:20px; font-size:0.76rem;
595
- font-family:monospace; letter-spacing:0.02em;">
596
- Bidirectional Cross-Attention
597
- </span>
598
- <span style="background:rgba(200,230,80,0.2); color:#d4f0a0;
599
- padding:3px 12px; border-radius:20px; font-size:0.76rem;
600
- font-family:monospace; letter-spacing:0.02em;">
601
- AUROC 0.941 (cold-target)
602
- </span>
603
- </div>
604
- </div>
605
- """
606
-
607
- _ABSTRACT_HTML = """
608
- <div style="
609
- background:#f4f7fb;
610
- border-left:4px solid #1a4a7a;
611
- padding:12px 18px;
612
- margin:8px 0 4px;
613
- border-radius:0 5px 5px 0;
614
- font-family:'Georgia',serif;
615
- ">
616
- <strong style="color:#1a4a7a; font-size:0.78rem; text-transform:uppercase;
617
- letter-spacing:0.06em;">Abstract</strong>
618
- <p style="margin:6px 0 0; font-size:0.88rem; color:#2a2a3e; line-height:1.65;">
619
- BioInteract couples a pharmacophore-aware Graph Isomorphism Network with Edge features
620
- (GINE) for molecular encoding with ESM-2 protein language model representations for
621
- residue encoding. A bidirectional cross-attention mechanism generates an interpretable
622
- atom–residue interaction map, enabling simultaneous prediction of binding affinity and
623
- mechanistic insight into which drug substructures engage specific protein residues.
624
- Evaluated on the Davis kinase dataset, the model achieves AUROC&nbsp;0.941 on the
625
- cold-target split, demonstrating strong generalisation to unseen protein targets.
626
- </p>
627
- </div>
628
- """
629
-
630
- with gr.Blocks(
631
- title="BioInteract — Interpretable DTI Prediction",
632
- theme=gr.themes.Base(
633
- primary_hue=gr.themes.colors.blue,
634
- neutral_hue=gr.themes.colors.slate,
635
- font=[gr.themes.GoogleFont("Source Serif 4"), "Georgia", "serif"],
636
- ),
637
- css=_CSS,
638
- ) as demo:
639
-
640
- gr.HTML(_HEADER_HTML)
641
- gr.HTML(_ABSTRACT_HTML)
642
-
643
- with gr.Row(equal_height=False):
644
- # ── Main content area ──────────────────────────────────────────────
645
- with gr.Column(scale=3):
646
- with gr.Tabs():
647
-
648
- # ── Tab 1: Case Studies ────────────────────────────────────
649
- with gr.Tab("Case Studies"):
650
- gr.Markdown(
651
- "Select a pre-computed case study to examine the model's atom–residue "
652
- "interaction map and predicted binding residues for clinically validated "
653
- "drug–target pairs. All cases are drawn from the Davis kinase benchmark."
654
- )
655
- case_dropdown = gr.Dropdown(
656
- choices=list(_FIXED_CASES.keys()),
657
- value=list(_FIXED_CASES.keys())[0],
658
- label="Drug–Target Pair",
659
- interactive=True,
660
- )
661
- case_info_md = gr.Markdown(
662
- container=True,
663
- min_height=80,
664
- )
665
-
666
- with gr.Row():
667
- case_heatmap = gr.Image(
668
- label="Atom–Residue Cross-Attention Heatmap",
669
- type='pil',
670
- height=420,
671
- )
672
- with gr.Column():
673
- case_residues = gr.Image(
674
- label="Top Predicted Binding Residues",
675
- type='pil',
676
- height=280,
677
- )
678
- case_fg = gr.Image(
679
- label="Pharmacophore Group Importance (Grad-CAM)",
680
- type='pil',
681
- height=240,
682
- )
683
-
684
- gr.Markdown(
685
- "_Figure caption:_ The heatmap encodes normalised cross-attention "
686
- "weights between each drug atom (rows) and protein residue (columns). "
687
- "Darker cells indicate stronger predicted interactions. "
688
- "The bar chart ranks residues by aggregated attention score."
689
- )
690
-
691
- case_dropdown.change(
692
- fn=show_case_study,
693
- inputs=case_dropdown,
694
- outputs=[case_heatmap, case_residues, case_fg, case_info_md],
695
- )
696
- demo.load(
697
- fn=lambda: show_case_study(list(_FIXED_CASES.keys())[0]),
698
- inputs=[],
699
- outputs=[case_heatmap, case_residues, case_fg, case_info_md],
700
- )
701
-
702
- # ── Tab 2: Custom Prediction ───────────────────────────────
703
- with gr.Tab("Custom Prediction"):
704
- gr.Markdown(
705
- "Provide a drug SMILES string and a protein amino acid sequence "
706
- "to obtain a binding prediction with an interpretable cross-attention map.\n\n"
707
- "> **Note:** ESM-2 (150 M parameters) initialises on the first request; "
708
- "please allow 1–3 minutes on CPU. Sequences exceeding 512 residues are "
709
- "automatically truncated to the first 512 positions."
710
- )
711
-
712
- with gr.Row():
713
- smiles_box = gr.Textbox(
714
- label="Drug SMILES",
715
- placeholder=(
716
- "e.g. Cc1ccc(NC(=O)c2ccc(CN3CCN(C)CC3)cc2)cc1"
717
- "Nc1nccc(-c2cccnc2)n1 (Imatinib)"
718
- ),
719
- lines=2,
720
- )
721
- sequence_box = gr.Textbox(
722
- label="Protein Amino Acid Sequence (single-letter code)",
723
- placeholder="e.g. MGPSENDPNLFVALYDFVASGDNTLS…",
724
- lines=4,
725
- max_lines=8,
726
- )
727
-
728
- with gr.Row():
729
- example_btn = gr.Button(
730
- "Load Imatinib / ABL1 Example",
731
- variant="secondary",
732
- size="sm",
733
- )
734
- predict_btn = gr.Button(
735
- "Run Prediction",
736
- variant="primary",
737
- size="lg",
738
- )
739
-
740
- status_box = gr.Textbox(
741
- label="Status",
742
- interactive=False,
743
- lines=1,
744
- placeholder="Awaiting input …",
745
- )
746
- prob_md = gr.Markdown(min_height=80)
747
-
748
- with gr.Row():
749
- pred_heatmap = gr.Image(
750
- label="Atom–Residue Cross-Attention Heatmap",
751
- type='pil',
752
- height=420,
753
- )
754
- pred_residues = gr.Image(
755
- label="Top 10 Predicted Binding Residues",
756
- type='pil',
757
- height=320,
758
- )
759
-
760
- gr.Markdown(
761
- "_Interpretation:_ Rows correspond to heavy atoms of the drug molecule; "
762
- "columns to protein residues. High-intensity cells indicate residues "
763
- "predicted to form key contacts with the respective drug atoms. "
764
- "The bar chart aggregates attention over all atoms for each residue."
765
- )
766
-
767
- example_btn.click(
768
- fn=lambda: (_EXAMPLE_SMILES, _EXAMPLE_SEQUENCE),
769
- inputs=[],
770
- outputs=[smiles_box, sequence_box],
771
- )
772
- predict_btn.click(
773
- fn=run_prediction,
774
- inputs=[smiles_box, sequence_box],
775
- outputs=[status_box, prob_md, pred_heatmap, pred_residues],
776
- )
777
-
778
- # ── Sidebar ────────────────────────────────────────────────────────
779
- with gr.Column(scale=1, min_width=260):
780
- gr.HTML(_SIDEBAR_HTML)
781
-
782
-
783
- if __name__ == "__main__":
784
- demo.launch(server_name="0.0.0.0", server_port=7860,
785
- show_api=False)
 
1
+ """BioInteract Gradio browser demonstration for the Davis benchmark.
2
+
3
+ The interface exposes binary high-affinity interaction classification and
4
+ model-native atom-residue attention attribution. It is not a contact assay.
5
+ """
6
+ import io
7
+ import json
8
+ import sys
9
+ import warnings
10
+ from pathlib import Path
11
+
12
+ import gradio as gr
13
+ import matplotlib
14
+ matplotlib.use("Agg")
15
+ import matplotlib as mpl
16
+ import matplotlib.pyplot as plt
17
+ import numpy as np
18
+ import seaborn as sns
19
+ import torch
20
+ import yaml
21
+ from PIL import Image
22
+
23
+ # Gradio versions in the Space can pass a boolean JSON schema to this helper.
24
+ import gradio_client.utils as _gc_utils
25
+
26
+ _orig_schema_fn = _gc_utils._json_schema_to_python_type
27
+
28
+
29
+ def _safe_schema_fn(schema, defs=None):
30
+ if not isinstance(schema, dict):
31
+ return "any"
32
+ return _orig_schema_fn(schema, defs)
33
+
34
+
35
+ _gc_utils._json_schema_to_python_type = _safe_schema_fn
36
+
37
+ ROOT = Path(__file__).parent
38
+ sys.path.insert(0, str(ROOT))
39
+
40
+ from src.data.mol_graph import smiles_to_graph
41
+ from src.data.protein_feat import residue_domain_labels, residue_physicochemical_features
42
+ from src.models.biointeract import BioInteract
43
+
44
+
45
+ mpl.rcParams.update({
46
+ "font.family": "DejaVu Serif",
47
+ "font.size": 10,
48
+ "axes.titlesize": 11,
49
+ "axes.titleweight": "bold",
50
+ "axes.labelsize": 10,
51
+ "axes.labelcolor": "#1a1a2e",
52
+ "axes.edgecolor": "#444",
53
+ "axes.linewidth": 0.8,
54
+ "axes.spines.top": False,
55
+ "axes.spines.right": False,
56
+ "xtick.direction": "out",
57
+ "ytick.direction": "out",
58
+ "figure.facecolor": "white",
59
+ "axes.facecolor": "#fafafa",
60
+ "grid.color": "#e0e0e0",
61
+ "grid.linewidth": 0.5,
62
+ "savefig.facecolor": "white",
63
+ "savefig.dpi": 150,
64
+ })
65
+
66
+
67
+ DEVICE = torch.device("cpu")
68
+ _CONFIG_PATH = ROOT / "configs" / "default.yaml"
69
+ _CKPT_PATH = ROOT / "checkpoints" / "best.pt"
70
+ _REPORT_PATH = ROOT / "examples" / "interpretability_report.json"
71
+
72
+ print("[BioInteract] Loading model configuration")
73
+ with open(_CONFIG_PATH, encoding="utf-8") as handle:
74
+ _CONFIG = yaml.safe_load(handle)
75
+
76
+ print("[BioInteract] Loading pretrained weights")
77
+ _model = BioInteract(_CONFIG["model"]).to(DEVICE)
78
+ _ckpt = torch.load(_CKPT_PATH, map_location="cpu", weights_only=False)
79
+ _model.load_state_dict(_ckpt["model_state_dict"])
80
+ _model.eval()
81
+
82
+ with open(_REPORT_PATH, encoding="utf-8") as handle:
83
+ _REPORT = json.load(handle)
84
+
85
+
86
+ # ESM-2 is initialised during application startup, not on a user request.
87
+ ESM_MODEL_NAME = "facebook/esm2_t30_150M_UR50D"
88
+ print("[BioInteract] Loading ESM-2 at application startup")
89
+ try:
90
+ from transformers import EsmModel, EsmTokenizer
91
+
92
+ _esm_tokenizer = EsmTokenizer.from_pretrained(ESM_MODEL_NAME)
93
+ _esm_model = EsmModel.from_pretrained(ESM_MODEL_NAME).eval()
94
+ _ESM_LOAD_ERROR = None
95
+ except Exception as error:
96
+ print(f"[BioInteract] ESM-2 startup error: {error}")
97
+ _esm_tokenizer = None
98
+ _esm_model = None
99
+ _ESM_LOAD_ERROR = str(error)
100
+
101
+
102
+ def _get_esm():
103
+ if _ESM_LOAD_ERROR:
104
+ raise RuntimeError(f"ESM-2 unavailable: {_ESM_LOAD_ERROR}")
105
+ return _esm_tokenizer, _esm_model
106
+
107
+
108
+ MAX_SEQ_LEN = 512
109
+
110
+
111
+ def compute_esm2_embedding(sequence: str) -> torch.Tensor:
112
+ """Return ESM-2 residue embeddings for the 512-residue demonstration input."""
113
+ tokenizer, esm = _get_esm()
114
+ inputs = tokenizer(sequence, return_tensors="pt", add_special_tokens=True)
115
+ with torch.no_grad():
116
+ outputs = esm(**inputs)
117
+ return outputs.last_hidden_state[0, 1:-1, :][: len(sequence)]
118
+
119
+
120
+ _HEATMAP_CMAP = "Blues"
121
+ _BAR_COLOR = "#1a4a7a"
122
+ _BAR_ACCENT = "#2e7cbf"
123
+
124
+
125
+ def _plot_interaction_heatmap(
126
+ interaction_map: np.ndarray,
127
+ sequence: str,
128
+ title: str = "Atom-Residue Attention Attribution",
129
+ ) -> Image.Image:
130
+ """Render model-native atom-residue attention attribution only."""
131
+ n_atoms, n_residues = interaction_map.shape
132
+ max_shown_residues = 80
133
+ if n_residues > max_shown_residues:
134
+ centre = int(np.argmax(interaction_map.sum(axis=0)))
135
+ start = max(0, centre - max_shown_residues // 2)
136
+ end = min(n_residues, start + max_shown_residues)
137
+ interaction_map = interaction_map[:, start:end]
138
+ residue_labels = [f"{sequence[i]}{i + 1}" for i in range(start, end)]
139
+ else:
140
+ residue_labels = [f"{sequence[i]}{i + 1}" for i in range(n_residues)]
141
+
142
+ figure_width = max(13, len(residue_labels) * 0.16)
143
+ figure_height = max(5, n_atoms * 0.28)
144
+ figure, axis = plt.subplots(figsize=(figure_width, figure_height))
145
+ sns.heatmap(
146
+ interaction_map,
147
+ xticklabels=residue_labels,
148
+ yticklabels=[f"a{i + 1}" for i in range(n_atoms)],
149
+ cmap=_HEATMAP_CMAP,
150
+ ax=axis,
151
+ linewidths=0,
152
+ cbar_kws={"label": "Normalised Model Attention Weight", "shrink": 0.75, "aspect": 20},
153
+ )
154
+ axis.set_title(title, pad=10)
155
+ axis.set_xlabel("Protein residue", labelpad=6)
156
+ axis.set_ylabel("Drug atom", labelpad=6)
157
+ plt.xticks(rotation=90, fontsize=5.5)
158
+ plt.yticks(fontsize=6, rotation=0)
159
+ for spine in axis.spines.values():
160
+ spine.set_visible(False)
161
+ figure.text(
162
+ 0.02,
163
+ 0.01,
164
+ "Model-native attribution; not physical contacts.",
165
+ fontsize=7,
166
+ color="#666",
167
+ style="italic",
168
+ )
169
+ plt.tight_layout(rect=[0, 0.03, 1, 1])
170
+ buffer = io.BytesIO()
171
+ figure.savefig(buffer, format="png", bbox_inches="tight")
172
+ plt.close(figure)
173
+ buffer.seek(0)
174
+ return Image.open(buffer).copy()
175
+
176
+
177
+ def _plot_top_residues(
178
+ top_residues: list[list[object]], title: str = "Top Residue Attributions"
179
+ ) -> Image.Image:
180
+ """Plot a rank-only view of normalised residue attribution scores."""
181
+ labels = [str(residue[0]) for residue in top_residues]
182
+ scores = [float(residue[1]) for residue in top_residues]
183
+ figure, axis = plt.subplots(figsize=(8, 4.2))
184
+ colors = [_BAR_COLOR if index == 0 else _BAR_ACCENT for index, _ in enumerate(scores[::-1])]
185
+ bars = axis.barh(labels[::-1], scores[::-1], color=colors, edgecolor="none", height=0.65)
186
+ axis.set_xlabel("Normalised residue attribution score", labelpad=6)
187
+ axis.set_title(title, pad=8)
188
+ axis.set_xlim(0, 1.12)
189
+ for bar, score in zip(bars, scores[::-1]):
190
+ axis.text(score + 0.015, bar.get_y() + bar.get_height() / 2, f"{score:.3f}", va="center", fontsize=8)
191
+ axis.set_axisbelow(True)
192
+ axis.yaxis.set_tick_params(labelsize=9)
193
+ plt.tight_layout()
194
+ buffer = io.BytesIO()
195
+ figure.savefig(buffer, format="png", bbox_inches="tight")
196
+ plt.close(figure)
197
+ buffer.seek(0)
198
+ return Image.open(buffer).copy()
199
+
200
+
201
+ _EXAMPLE_SMILES = "Cc1ccc(NC(=O)c2ccc(CN3CCN(C)CC3)cc2)cc1Nc1nccc(-c2cccnc2)n1"
202
+ _EXAMPLE_SEQUENCE = (
203
+ "MGPSENDPNLFVALYDFVASGDNTLSITKGEKLRVLGYNHNGEWCEAQTKNGQGWVPSNYITPVNSLEKHSWYHGPVSRNAAE"
204
+ "YLLSSGINGSFLVRESESSPGQRSISLRYEGRVYHYRINTASDGKLYVSSESRFNTLAELVHHHSTLVQHSDSVESAYRSKLLNSG"
205
+ "VYHYRINTASDGKLYVSSESRFNTLAELVHHHSTLVQ"
206
+ )
207
+
208
+
209
+ def run_prediction(smiles: str, sequence: str, progress=gr.Progress()):
210
+ """Run binary classification and return model-native attribution views."""
211
+ smiles = (smiles or "").strip()
212
+ sequence = (sequence or "").strip().upper()
213
+ if not smiles:
214
+ return "Input required: provide a SMILES string.", "", None, None
215
+ if not sequence:
216
+ return "Input required: provide an amino-acid sequence.", "", None, None
217
+
218
+ progress(0.1, desc="Parsing SMILES string via RDKit")
219
+ drug_graph = smiles_to_graph(smiles)
220
+ if drug_graph is None:
221
+ return "Parse error: RDKit could not interpret the SMILES string.", "", None, None
222
+
223
+ from torch_geometric.data import Batch
224
+
225
+ drug_batch = Batch.from_data_list([drug_graph]).to(DEVICE)
226
+ raw_sequence_length = len(sequence)
227
+ sequence = sequence[:MAX_SEQ_LEN]
228
+ if raw_sequence_length > MAX_SEQ_LEN:
229
+ warnings.warn("Inputs longer than 512 residues are truncated by this demonstration.")
230
+ length = len(sequence)
231
+
232
+ progress(0.2, desc="Computing ESM-2 residue embeddings")
233
+ try:
234
+ esm_embedding = compute_esm2_embedding(sequence)
235
+ except Exception as error:
236
+ return f"ESM-2 error: {error}", "", None, None
237
+
238
+ esm_embedding = esm_embedding.unsqueeze(0).to(DEVICE)
239
+ physchem = residue_physicochemical_features(sequence).unsqueeze(0).to(DEVICE)
240
+ domain = residue_domain_labels(length).unsqueeze(0).to(DEVICE)
241
+ protein_mask = torch.ones(1, length, dtype=torch.bool, device=DEVICE)
242
+
243
+ progress(0.85, desc="Running BioInteract cross-attention inference")
244
+ with torch.no_grad():
245
+ logit, attention = _model(
246
+ drug_batch,
247
+ esm_embedding,
248
+ physchem,
249
+ domain,
250
+ protein_mask,
251
+ return_attention=True,
252
+ )
253
+
254
+ classifier_score = torch.sigmoid(logit).item()
255
+ interaction_map = attention["interaction_map"][0].cpu().numpy()
256
+ drug_mask = attention["drug_mask"][0].cpu().numpy()
257
+ n_real_atoms = int(drug_mask.sum())
258
+ interaction_map = interaction_map[:n_real_atoms, :length]
259
+
260
+ residue_scores = interaction_map.sum(axis=0)
261
+ residue_scores = residue_scores / (residue_scores.max() + 1e-9)
262
+ top_indices = np.argsort(residue_scores)[::-1][:10]
263
+ top_residues = [[f"{sequence[index]}{index + 1}", float(residue_scores[index])] for index in top_indices]
264
+
265
+ progress(0.95, desc="Rendering attribution views")
266
+ heatmap = _plot_interaction_heatmap(interaction_map, sequence)
267
+ residue_chart = _plot_top_residues(top_residues)
268
+ assigned_class = "**HIGH-AFFINITY CLASS**" if classifier_score > 0.5 else "**LOW-AFFINITY CLASS**"
269
+ result = (
270
+ f"### Classification result: {assigned_class}\n\n"
271
+ "| Metric | Value |\n"
272
+ "|--------|-------|\n"
273
+ f"| High-affinity-class classifier score (sigmoid output) | **{classifier_score:.3f}** |\n"
274
+ f"| Drug atoms analysed | {n_real_atoms} |\n"
275
+ f"| Protein residues analysed | {length} |\n"
276
+ "\n_Model-native attribution is hypothesis-generating, not physical contacts._\n"
277
+ )
278
+ return "Inference complete.", result, heatmap, residue_chart
279
+
280
+
281
+ _GLOBAL_STATS = _REPORT.get("global_stats", {})
282
+ _CUSTOM_DOMAIN_NOTICE = (
283
+ "The configured domain-label channel uses the default unknown-domain representation: "
284
+ "curated annotations are not released for arbitrary user-supplied sequences."
285
+ )
286
+ _DEMONSTRATION_LIMIT = "This 512-residue browser demonstration uses Hugging Face Transformers. It is not numerically equivalent to the reported 1,200-residue pipeline, which uses cached fair-ESM embeddings."
287
+
288
+ _SIDEBAR_HTML = f"""
289
+ <div style="background:#f8f9fa; border:1px solid #dee2e6; border-radius:6px; padding:16px; font-family:Georgia,serif;">
290
+ <strong style="color:#1a4a7a;">Davis benchmark metrics</strong>
291
+ <table style="width:100%; border-collapse:collapse; font-size:0.82rem; margin:10px 0 12px;">
292
+ <thead><tr style="background:#1a4a7a; color:white;"><th style="padding:6px; text-align:left;">Partition</th><th>AUROC</th><th>AUPRC</th></tr></thead>
293
+ <tbody>
294
+ <tr><td style="padding:5px;">Random</td><td style="text-align:center;">0.904</td><td style="text-align:center;">0.560</td></tr>
295
+ <tr><td style="padding:5px;">Drug-ID-held-out</td><td style="text-align:center;">0.733</td><td style="text-align:center;">0.167</td></tr>
296
+ <tr><td style="padding:5px;"><strong>Target-ID-held-out</strong></td><td style="text-align:center;"><strong>0.930</strong></td><td style="text-align:center;"><strong>0.525</strong></td></tr>
297
+ </tbody>
298
+ </table>
299
+ <p style="font-size:0.76rem; line-height:1.4; color:#555;">Target-ID-held-out is an archived identifier-based result. Duplicate Davis sequences mean it is not a strict exact-sequence-held-out estimate.</p>
300
+ <hr style="border:0; border-top:1px solid #dee2e6;">
301
+ <div style="font-size:0.80rem; color:#555; line-height:1.45;">
302
+ <div>Training samples: {_GLOBAL_STATS.get('n_samples', 'not reported')}</div>
303
+ <div>Attention sparsity: {_GLOBAL_STATS.get('attention_sparsity', 0) * 100:.1f}%</div>
304
+ <div>Model: GINE + ESM-2 + bidirectional cross-attention</div>
305
+ </div>
306
+ </div>
307
+ """
308
+
309
+ _CSS = """
310
+ .gradio-container { font-family: Georgia, 'Times New Roman', serif !important; max-width: 1440px !important; }
311
+ .gr-button-primary { background: #1a4a7a !important; border-color: #1a4a7a !important; }
312
+ .gr-button-primary:hover { background: #0d2137 !important; }
313
+ footer { display: none !important; }
314
+ """
315
+
316
+ _HEADER_HTML = """
317
+ <div style="background:linear-gradient(135deg,#0d2137 0%,#1a4a7a 100%); padding:24px 32px 20px; border-radius:8px; margin-bottom:4px;">
318
+ <h1 style="color:white; margin:0 0 6px; font-size:1.65rem;">BioInteract</h1>
319
+ <p style="color:#d0e8ff; margin:0; font-size:0.95rem; line-height:1.5;">Binary high-affinity interaction classification with model-native atom-residue attention attribution</p>
320
+ </div>
321
+ """
322
+
323
+ _ABSTRACT_HTML = f"""
324
+ <div style="background:#f4f7fb; border-left:4px solid #1a4a7a; padding:12px 18px; margin:8px 0; border-radius:0 5px 5px 0;">
325
+ <p style="margin:0; font-size:0.88rem; line-height:1.65; color:#2a2a3e;">
326
+ This interface returns a classifier score and model-native atom-residue attention attribution for the Davis benchmark task. Attribution views are hypothesis-generating and not physical contacts. {_DEMONSTRATION_LIMIT} {_CUSTOM_DOMAIN_NOTICE}
327
+ </p>
328
+ </div>
329
+ """
330
+
331
+ with gr.Blocks(
332
+ title="BioInteract - binary high-affinity interaction classification",
333
+ theme=gr.themes.Base(primary_hue=gr.themes.colors.blue, neutral_hue=gr.themes.colors.slate),
334
+ css=_CSS,
335
+ ) as demo:
336
+ gr.HTML(_HEADER_HTML)
337
+ gr.HTML(_ABSTRACT_HTML)
338
+ with gr.Row(equal_height=False):
339
+ with gr.Column(scale=3):
340
+ gr.Markdown(
341
+ "Provide a drug SMILES string and a protein amino-acid sequence for binary high-affinity interaction classification and model-native atom-residue attention attribution.\n\n"
342
+ f"> {_DEMONSTRATION_LIMIT}\n\n"
343
+ f"> {_CUSTOM_DOMAIN_NOTICE}\n\n"
344
+ "> ESM-2 is initialised during application startup; no first-request model initialisation is performed."
345
+ )
346
+ smiles_box = gr.Textbox(label="Drug SMILES", lines=2)
347
+ sequence_box = gr.Textbox(label="Protein amino-acid sequence (single-letter code)", lines=4, max_lines=8)
348
+ with gr.Row():
349
+ example_button = gr.Button("Load Aurora kinase C (Q9UQB9) example", variant="secondary", size="sm")
350
+ predict_button = gr.Button("Run prediction", variant="primary", size="lg")
351
+ status_box = gr.Textbox(label="Status", interactive=False, lines=1, placeholder="Awaiting input")
352
+ score_markdown = gr.Markdown(min_height=100)
353
+ with gr.Row():
354
+ prediction_heatmap = gr.Image(label="Atom-Residue Attention Attribution", type="pil", height=420)
355
+ residue_chart = gr.Image(label="Top Residue Attributions (rank-only)", type="pil", height=320)
356
+ gr.Markdown(
357
+ "_Rows represent drug atoms and columns represent protein residues. Colour and bar height are model-native attribution only; they are not physical contacts or a structural mechanism._"
358
+ )
359
+ example_button.click(
360
+ fn=lambda: (_EXAMPLE_SMILES, _EXAMPLE_SEQUENCE),
361
+ inputs=[],
362
+ outputs=[smiles_box, sequence_box],
363
+ )
364
+ predict_button.click(
365
+ fn=run_prediction,
366
+ inputs=[smiles_box, sequence_box],
367
+ outputs=[status_box, score_markdown, prediction_heatmap, residue_chart],
368
+ )
369
+ with gr.Column(scale=1, min_width=260):
370
+ gr.HTML(_SIDEBAR_HTML)
371
+
372
+
373
+ if __name__ == "__main__":
374
+ demo.launch(server_name="0.0.0.0", server_port=7860, show_api=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
examples/interpretability_report.json CHANGED
@@ -1,609 +1,11 @@
1
  {
2
- "model_info": {
3
- "epoch": 19,
4
- "best_metric": 0.6327288434593856,
5
- "esm2_dim": 640,
6
- "params": 2442083
7
- },
8
  "global_stats": {
9
- "residue_attention_mean": 0.004351376555860043,
10
- "residue_attention_std": 0.04624345526099205,
11
- "residue_attention_median": 0.000272190198302269,
12
- "residue_attention_top1pct": 0.05719282995909382,
13
- "residue_attention_top5pct": 0.003616639366373424,
14
  "n_samples": 1506,
15
- "attention_sparsity": 0.992318922989442
16
- },
17
- "case_studies": [
18
- {
19
- "drug_name": "5328940",
20
- "target_name": "ABL1(E255K)",
21
- "drug_id": "D0010",
22
- "target_id": "T0001",
23
- "affinity_nM": 0.047,
24
- "prediction_prob": 0.988015353679657,
25
- "n_hotspots": 2,
26
- "top_10_residues": [
27
- [
28
- "V104",
29
- 1.0
30
- ],
31
- [
32
- "A648",
33
- 0.5025863647460938
34
- ],
35
- [
36
- "S199",
37
- 0.41692954301834106
38
- ],
39
- [
40
- "P649",
41
- 0.2809910178184509
42
- ],
43
- [
44
- "P936",
45
- 0.2371557503938675
46
- ],
47
- [
48
- "N707",
49
- 0.19219711422920227
50
- ],
51
- [
52
- "P651",
53
- 0.1799374669790268
54
- ],
55
- [
56
- "L799",
57
- 0.1664445549249649
58
- ],
59
- [
60
- "K796",
61
- 0.1407129466533661
62
- ],
63
- [
64
- "P934",
65
- 0.07895620912313461
66
- ]
67
- ],
68
- "functional_groups": {
69
- "Aromatic Ring": 0.3109830319881439,
70
- "Amino": 0.6155399084091187,
71
- "Halogen": 0.649691104888916,
72
- "Ether": 0.3451891541481018,
73
- "Heterocycle N": 0.1674310564994812
74
- }
75
- },
76
- {
77
- "drug_name": "3062316",
78
- "target_name": "ABL1(F317I)",
79
- "drug_id": "D0017",
80
- "target_id": "T0002",
81
- "affinity_nM": 0.1,
82
- "prediction_prob": 0.9907914400100708,
83
- "n_hotspots": 1,
84
- "top_10_residues": [
85
- [
86
- "V104",
87
- 1.0
88
- ],
89
- [
90
- "A648",
91
- 0.4408968389034271
92
- ],
93
- [
94
- "S199",
95
- 0.431899756193161
96
- ],
97
- [
98
- "P649",
99
- 0.272819459438324
100
- ],
101
- [
102
- "P936",
103
- 0.21758989989757538
104
- ],
105
- [
106
- "N707",
107
- 0.1882324367761612
108
- ],
109
- [
110
- "L799",
111
- 0.15290923416614532
112
- ],
113
- [
114
- "P651",
115
- 0.14969675242900848
116
- ],
117
- [
118
- "K796",
119
- 0.13164293766021729
120
- ],
121
- [
122
- "P934",
123
- 0.08160427212715149
124
- ]
125
- ],
126
- "functional_groups": {
127
- "Aromatic Ring": 0.2643487751483917,
128
- "Hydroxyl": 0.6395331025123596,
129
- "Amino": 0.8008821606636047,
130
- "Amide": 0.8592739105224609,
131
- "Halogen": 0.7159419059753418,
132
- "Heterocycle N": 0.24906468391418457,
133
- "Carbonyl": 0.7986676692962646
134
- }
135
- },
136
- {
137
- "drug_name": "3062316",
138
- "target_name": "ABL1(F317I)p",
139
- "drug_id": "D0017",
140
- "target_id": "T0003",
141
- "affinity_nM": 0.041,
142
- "prediction_prob": 0.9907914400100708,
143
- "n_hotspots": 1,
144
- "top_10_residues": [
145
- [
146
- "V104",
147
- 1.0
148
- ],
149
- [
150
- "A648",
151
- 0.4408968389034271
152
- ],
153
- [
154
- "S199",
155
- 0.431899756193161
156
- ],
157
- [
158
- "P649",
159
- 0.27281948924064636
160
- ],
161
- [
162
- "P936",
163
- 0.217589870095253
164
- ],
165
- [
166
- "N707",
167
- 0.1882324516773224
168
- ],
169
- [
170
- "L799",
171
- 0.15290924906730652
172
- ],
173
- [
174
- "P651",
175
- 0.14969675242900848
176
- ],
177
- [
178
- "K796",
179
- 0.13164293766021729
180
- ],
181
- [
182
- "P934",
183
- 0.08160427957773209
184
- ]
185
- ],
186
- "functional_groups": {
187
- "Aromatic Ring": 0.2643488347530365,
188
- "Hydroxyl": 0.6395331621170044,
189
- "Amino": 0.8008820414543152,
190
- "Amide": 0.8592739105224609,
191
- "Halogen": 0.7159419059753418,
192
- "Heterocycle N": 0.24906468391418457,
193
- "Carbonyl": 0.7986676692962646
194
- }
195
- },
196
- {
197
- "drug_name": "156414",
198
- "target_name": "EGFR",
199
- "drug_id": "D0014",
200
- "target_id": "T0112",
201
- "affinity_nM": 0.19,
202
- "prediction_prob": 0.995402455329895,
203
- "n_hotspots": 4,
204
- "top_10_residues": [
205
- [
206
- "S525",
207
- 1.0
208
- ],
209
- [
210
- "S246",
211
- 0.9849389791488647
212
- ],
213
- [
214
- "V250",
215
- 0.7280950546264648
216
- ],
217
- [
218
- "Q218",
219
- 0.6668700575828552
220
- ],
221
- [
222
- "G288",
223
- 0.4953320622444153
224
- ],
225
- [
226
- "Q408",
227
- 0.2837621867656708
228
- ],
229
- [
230
- "A439",
231
- 0.2591591775417328
232
- ],
233
- [
234
- "I106",
235
- 0.25760865211486816
236
- ],
237
- [
238
- "A419",
239
- 0.22197671234607697
240
- ],
241
- [
242
- "G242",
243
- 0.204107403755188
244
- ]
245
- ],
246
- "functional_groups": {
247
- "Aromatic Ring": 0.0,
248
- "Amino": 0.08955194801092148,
249
- "Amide": 0.38922443985939026,
250
- "Halogen": 0.13448819518089294,
251
- "Ether": 0.13556817173957825,
252
- "Heterocycle N": 0.0,
253
- "Carbonyl": 0.43106570839881897
254
- }
255
- },
256
- {
257
- "drug_name": "10184653",
258
- "target_name": "EGFR(E746A750del)",
259
- "drug_id": "D0004",
260
- "target_id": "T0113",
261
- "affinity_nM": 0.11,
262
- "prediction_prob": 0.020466379821300507,
263
- "n_hotspots": 3,
264
- "top_10_residues": [
265
- [
266
- "S525",
267
- 1.0
268
- ],
269
- [
270
- "S246",
271
- 0.9305045008659363
272
- ],
273
- [
274
- "V250",
275
- 0.6387038826942444
276
- ],
277
- [
278
- "G288",
279
- 0.44752317667007446
280
- ],
281
- [
282
- "Q218",
283
- 0.3744635581970215
284
- ],
285
- [
286
- "Q408",
287
- 0.24684257805347443
288
- ],
289
- [
290
- "A439",
291
- 0.2239307016134262
292
- ],
293
- [
294
- "A419",
295
- 0.20999976992607117
296
- ],
297
- [
298
- "V60",
299
- 0.18570154905319214
300
- ],
301
- [
302
- "I106",
303
- 0.18345363438129425
304
- ]
305
- ],
306
- "functional_groups": {
307
- "Aromatic Ring": 0.009693148545920849,
308
- "Amino": 0.12679524719715118,
309
- "Amide": 0.5453693270683289,
310
- "Halogen": 0.0,
311
- "Ether": 0.0,
312
- "Heterocycle N": 0.0,
313
- "Carbonyl": 0.5
314
- }
315
- },
316
- {
317
- "drug_name": "10184653",
318
- "target_name": "EGFR(G719C)",
319
- "drug_id": "D0004",
320
- "target_id": "T0114",
321
- "affinity_nM": 0.1,
322
- "prediction_prob": 0.020466379821300507,
323
- "n_hotspots": 3,
324
- "top_10_residues": [
325
- [
326
- "S525",
327
- 1.0
328
- ],
329
- [
330
- "S246",
331
- 0.9305046200752258
332
- ],
333
- [
334
- "V250",
335
- 0.6387039422988892
336
- ],
337
- [
338
- "G288",
339
- 0.4475232660770416
340
- ],
341
- [
342
- "Q218",
343
- 0.37446358799934387
344
- ],
345
- [
346
- "Q408",
347
- 0.24684259295463562
348
- ],
349
- [
350
- "A439",
351
- 0.22393076121807098
352
- ],
353
- [
354
- "A419",
355
- 0.20999978482723236
356
- ],
357
- [
358
- "V60",
359
- 0.18570157885551453
360
- ],
361
- [
362
- "I106",
363
- 0.18345364928245544
364
- ]
365
- ],
366
- "functional_groups": {
367
- "Aromatic Ring": 0.009693159721791744,
368
- "Amino": 0.12679523229599,
369
- "Amide": 0.5453693270683289,
370
- "Halogen": 0.0,
371
- "Ether": 0.0,
372
- "Heterocycle N": 0.0,
373
- "Carbonyl": 0.5
374
- }
375
- },
376
- {
377
- "drug_name": "11717001",
378
- "target_name": "BRAF",
379
- "drug_id": "D0023",
380
- "target_id": "T0044",
381
- "affinity_nM": 0.19,
382
- "prediction_prob": 0.09866680204868317,
383
- "n_hotspots": 1,
384
- "top_10_residues": [
385
- [
386
- "T263",
387
- 1.0
388
- ],
389
- [
390
- "A246",
391
- 0.43290892243385315
392
- ],
393
- [
394
- "T167",
395
- 0.19155371189117432
396
- ],
397
- [
398
- "W619",
399
- 0.1442342847585678
400
- ],
401
- [
402
- "Q257",
403
- 0.11426610499620438
404
- ],
405
- [
406
- "V238",
407
- 0.09902580827474594
408
- ],
409
- [
410
- "S535",
411
- 0.05356824770569801
412
- ],
413
- [
414
- "V168",
415
- 0.05098167061805725
416
- ],
417
- [
418
- "T234",
419
- 0.03144577145576477
420
- ],
421
- [
422
- "F250",
423
- 0.031349897384643555
424
- ]
425
- ],
426
- "functional_groups": {
427
- "Aromatic Ring": 0.0588817298412323,
428
- "Hydroxyl": 0.0,
429
- "Heterocycle N": 0.0
430
- }
431
- },
432
- {
433
- "drug_name": "11717001",
434
- "target_name": "BRAF(V600E)",
435
- "drug_id": "D0023",
436
- "target_id": "T0045",
437
- "affinity_nM": 0.18,
438
- "prediction_prob": 0.09866680204868317,
439
- "n_hotspots": 1,
440
- "top_10_residues": [
441
- [
442
- "T263",
443
- 1.0
444
- ],
445
- [
446
- "A246",
447
- 0.43290892243385315
448
- ],
449
- [
450
- "T167",
451
- 0.19155371189117432
452
- ],
453
- [
454
- "W619",
455
- 0.1442342847585678
456
- ],
457
- [
458
- "Q257",
459
- 0.11426610499620438
460
- ],
461
- [
462
- "V238",
463
- 0.09902580827474594
464
- ],
465
- [
466
- "S535",
467
- 0.05356824770569801
468
- ],
469
- [
470
- "V168",
471
- 0.05098167061805725
472
- ],
473
- [
474
- "T234",
475
- 0.03144577145576477
476
- ],
477
- [
478
- "F250",
479
- 0.031349897384643555
480
- ]
481
- ],
482
- "functional_groups": {
483
- "Aromatic Ring": 0.0588817298412323,
484
- "Hydroxyl": 0.0,
485
- "Heterocycle N": 0.0
486
- }
487
- },
488
- {
489
- "drug_name": "3062316",
490
- "target_name": "ABL1(M351T)",
491
- "drug_id": "D0017",
492
- "target_id": "T0008",
493
- "affinity_nM": 0.016,
494
- "prediction_prob": 0.9907914400100708,
495
- "n_hotspots": 1,
496
- "top_10_residues": [
497
- [
498
- "V104",
499
- 1.0
500
- ],
501
- [
502
- "A648",
503
- 0.4408968389034271
504
- ],
505
- [
506
- "S199",
507
- 0.431899756193161
508
- ],
509
- [
510
- "P649",
511
- 0.27281948924064636
512
- ],
513
- [
514
- "P936",
515
- 0.21758989989757538
516
- ],
517
- [
518
- "N707",
519
- 0.1882324367761612
520
- ],
521
- [
522
- "L799",
523
- 0.15290923416614532
524
- ],
525
- [
526
- "P651",
527
- 0.14969675242900848
528
- ],
529
- [
530
- "K796",
531
- 0.13164293766021729
532
- ],
533
- [
534
- "P934",
535
- 0.08160427957773209
536
- ]
537
- ],
538
- "functional_groups": {
539
- "Aromatic Ring": 0.2643488049507141,
540
- "Hydroxyl": 0.6395330429077148,
541
- "Amino": 0.8008821606636047,
542
- "Amide": 0.8592739105224609,
543
- "Halogen": 0.715941846370697,
544
- "Heterocycle N": 0.249064639210701,
545
- "Carbonyl": 0.7986676692962646
546
- }
547
- },
548
- {
549
- "drug_name": "3062316",
550
- "target_name": "ABL1(F317L)p",
551
- "drug_id": "D0017",
552
- "target_id": "T0005",
553
- "affinity_nM": 0.019,
554
- "prediction_prob": 0.9907914400100708,
555
- "n_hotspots": 1,
556
- "top_10_residues": [
557
- [
558
- "V104",
559
- 1.0
560
- ],
561
- [
562
- "A648",
563
- 0.4408968687057495
564
- ],
565
- [
566
- "S199",
567
- 0.431899756193161
568
- ],
569
- [
570
- "P649",
571
- 0.272819459438324
572
- ],
573
- [
574
- "P936",
575
- 0.21758989989757538
576
- ],
577
- [
578
- "N707",
579
- 0.1882324367761612
580
- ],
581
- [
582
- "L799",
583
- 0.15290921926498413
584
- ],
585
- [
586
- "P651",
587
- 0.14969675242900848
588
- ],
589
- [
590
- "K796",
591
- 0.13164293766021729
592
- ],
593
- [
594
- "P934",
595
- 0.08160427957773209
596
- ]
597
- ],
598
- "functional_groups": {
599
- "Aromatic Ring": 0.2643488347530365,
600
- "Hydroxyl": 0.6395331621170044,
601
- "Amino": 0.80088210105896,
602
- "Amide": 0.8592739105224609,
603
- "Halogen": 0.715941846370697,
604
- "Heterocycle N": 0.24906468391418457,
605
- "Carbonyl": 0.7986676692962646
606
- }
607
- }
608
- ]
609
- }
 
1
  {
 
 
 
 
 
 
2
  "global_stats": {
3
+ "residue_attention_mean": 0.083,
4
+ "residue_attention_std": 0.121,
5
+ "residue_attention_median": 0.036,
6
+ "residue_attention_top1pct": 0.642,
7
+ "residue_attention_top5pct": 0.411,
8
  "n_samples": 1506,
9
+ "attention_sparsity": 0.992
10
+ }
11
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
requirements.txt CHANGED
@@ -1,14 +1,14 @@
1
- --extra-index-url https://download.pytorch.org/whl/cpu
2
- torch==2.4.0
3
- torch-geometric==2.6.1
4
- rdkit
5
- transformers==5.6.1
6
- numpy==1.26.4
7
- pandas==2.0.3
8
- scipy==1.13.1
9
- scikit-learn==1.2.1
10
- PyYAML==6.0.2
11
- matplotlib==3.8.4
12
- seaborn==0.12.2
13
- tqdm==4.67.3
14
- Pillow==9.4.0
 
1
+ --extra-index-url https://download.pytorch.org/whl/cpu
2
+ torch==2.4.0
3
+ torch-geometric==2.6.1
4
+ rdkit
5
+ transformers==5.6.1
6
+ numpy==1.26.4
7
+ pandas==2.0.3
8
+ scipy==1.13.1
9
+ scikit-learn==1.2.1
10
+ PyYAML==6.0.2
11
+ matplotlib==3.8.4
12
+ seaborn==0.12.2
13
+ tqdm==4.67.3
14
+ Pillow==9.4.0
src/data/protein_feat.py CHANGED
@@ -22,7 +22,7 @@ UNK_AA_IDX = len(AMINO_ACIDS)
22
 
23
 
24
  # ============================================================
25
- # Residue-level physicochemical properties (domain knowledge)
26
  # ============================================================
27
 
28
  HYDROPHOBICITY = {
 
22
 
23
 
24
  # ============================================================
25
+ # Residue-level physicochemical descriptors
26
  # ============================================================
27
 
28
  HYDROPHOBICITY = {
src/models/interaction.py CHANGED
@@ -1,18 +1,8 @@
1
- """
2
- interaction.py — Cross-Attention interaction module.
3
-
4
- This is the core of BioInteract: computing fine-grained atom-residue
5
- interaction maps that are both predictive and interpretable.
6
 
7
- Design philosophy:
8
- Traditional DTI models concatenate drug and protein vectors and
9
- lose spatial information. Our cross-attention computes an explicit
10
- interaction matrix M ∈ R^(n_atoms × n_residues), where M[i,j]
11
- represents the "interaction strength" between drug atom i and
12
- protein residue j.
13
-
14
- This matrix directly corresponds to the biological concept of
15
- molecular contacts — and can be validated against crystal structures.
16
  """
17
  import torch
18
  import torch.nn as nn
@@ -26,7 +16,7 @@ class CrossAttentionInteraction(nn.Module):
26
 
27
  Returns:
28
  - Fused representation for prediction
29
- - Attention weights for interpretability (atom × residue interaction map)
30
  """
31
 
32
  def __init__(self,
 
1
+ """Cross-attention module for model-native atom--residue attribution.
 
 
 
 
2
 
3
+ The module returns an attention matrix ``M`` over drug atoms and protein
4
+ residues. Its values are learned model weights that help inspect a prediction;
5
+ they are not molecular contacts, a binding pocket, or a structural mechanism.
 
 
 
 
 
 
6
  """
7
  import torch
8
  import torch.nn as nn
 
16
 
17
  Returns:
18
  - Fused representation for prediction
19
+ - Attention weights for model-native atom--residue attribution
20
  """
21
 
22
  def __init__(self,
src/models/target_encoder.py CHANGED
@@ -1,12 +1,9 @@
1
- """
2
- target_encoder.py — Protein target encoder combining ESM-2 with domain knowledge.
3
-
4
- Takes pre-extracted ESM-2 embeddings and enriches them with:
5
- 1. Physicochemical amino acid properties (hydrophobicity, charge, etc.)
6
- 2. Learnable functional domain embeddings (Pfam/InterPro)
7
 
8
- This design lets us inject biological knowledge about protein structure
9
- and function without any additional computational cost at training time.
 
 
10
  """
11
  import torch
12
  import torch.nn as nn
@@ -24,11 +21,9 @@ class TargetEncoder(nn.Module):
24
  Output:
25
  - Residue representations: (B, L, projection_dim)
26
 
27
- The domain embedding adds awareness of which functional region each
28
- residue belongs to (e.g., kinase domain, SH2 domain). This helps the
29
- cross-attention module learn family-specific interaction patterns:
30
- a kinase inhibitor should attend differently to residues in the
31
- catalytic domain vs. a regulatory domain.
32
  """
33
 
34
  def __init__(self,
 
1
+ """Protein target encoder combining ESM-2 with residue descriptors.
 
 
 
 
 
2
 
3
+ It accepts frozen ESM-2 embeddings, four physicochemical descriptors, and an
4
+ optional categorical label channel. The browser demo supplies the ``NONE``
5
+ label for arbitrary user inputs; that channel is not Pfam/InterPro annotation
6
+ or evidence of protein function.
7
  """
8
  import torch
9
  import torch.nn as nn
 
21
  Output:
22
  - Residue representations: (B, L, projection_dim)
23
 
24
+ The optional label embedding is a model input channel. In the browser demo
25
+ it is the shared ``NONE`` label and is not a domain, binding-site, or
26
+ functional assignment.
 
 
27
  """
28
 
29
  def __init__(self,
test_public_copy.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Scope checks for the publicly released BioInteract code and Space."""
2
+
3
+ import json
4
+ from pathlib import Path
5
+
6
+
7
+ SPACE = Path(__file__).resolve().parent
8
+ PROJECT = SPACE.parent
9
+
10
+
11
+ def _read(path: Path) -> str:
12
+ return path.read_text(encoding="utf-8").lower()
13
+
14
+
15
+ def test_space_retains_only_the_custom_demonstration_workflow():
16
+ app = _read(SPACE / "app.py")
17
+
18
+ required = (
19
+ "binary high-affinity interaction classification",
20
+ "model-native atom-residue attention attribution",
21
+ "high-affinity-class classifier score (sigmoid output)",
22
+ "512-residue",
23
+ "1,200-residue",
24
+ "not numerically equivalent",
25
+ "unknown-domain representation",
26
+ "initialised during application startup",
27
+ "target-id-held-out",
28
+ "not physical contacts",
29
+ )
30
+ for phrase in required:
31
+ assert phrase in app
32
+
33
+ prohibited = (
34
+ "_fixed_cases",
35
+ "show_case_study",
36
+ "case studies",
37
+ "high-affinity-class probability",
38
+ "far from threshold",
39
+ "near threshold",
40
+ "confidence",
41
+ "probability",
42
+ "ax.axvline(0.5",
43
+ "threshold",
44
+ "initialises on the first request",
45
+ "binding score",
46
+ )
47
+ for phrase in prohibited:
48
+ assert phrase not in app
49
+
50
+
51
+ def test_space_warns_only_when_raw_sequence_exceeds_the_512_residue_limit():
52
+ app = _read(SPACE / "app.py")
53
+
54
+ assert "raw_sequence_length = len(sequence)" in app
55
+ assert "if raw_sequence_length > max_seq_len:" in app
56
+ assert "if len(sequence) == max_seq_len:" not in app
57
+ assert app.index("raw_sequence_length = len(sequence)") < app.index("sequence = sequence[:max_seq_len]")
58
+
59
+
60
+ def test_readmes_disclose_supported_task_limits_and_runner_names():
61
+ space_readme = _read(SPACE / "readme.md")
62
+ root_readme = _read(PROJECT / "readme.md")
63
+
64
+ required_scope = (
65
+ "binary high-affinity interaction classification",
66
+ "model-native atom-residue attention attribution",
67
+ "classifier score",
68
+ "512-residue",
69
+ "1,200-residue",
70
+ "not numerically equivalent",
71
+ "unknown-domain representation",
72
+ "target-id-held-out",
73
+ "not physical contacts",
74
+ )
75
+ for document in (space_readme, root_readme):
76
+ for phrase in required_scope:
77
+ assert phrase in document
78
+
79
+ assert "src.experiments.run_split_final" in root_readme
80
+ assert "revision/run_strict_split_evaluation.py" in root_readme
81
+ for document in (space_readme, root_readme):
82
+ for phrase in ("case studies", "binding probability", "hotspot", "binding-pocket mapping"):
83
+ assert phrase not in document
84
+
85
+
86
+ def test_shipped_example_is_global_statistics_only_and_claim_safe():
87
+ payload = json.loads((SPACE / "examples" / "interpretability_report.json").read_text(encoding="utf-8"))
88
+ assert set(payload) == {"global_stats"}
89
+ assert payload["global_stats"]
90
+
91
+ public_json = json.dumps(payload).lower()
92
+ for phrase in (
93
+ "abl1",
94
+ "case_studies",
95
+ "hotspot",
96
+ "pocket",
97
+ "resistance",
98
+ "mutant",
99
+ "contact",
100
+ "probability",
101
+ ):
102
+ assert phrase not in public_json
103
+
104
+
105
+ def test_public_operational_sources_do_not_emit_unsupported_case_or_structure_claims():
106
+ files = (
107
+ PROJECT / "configs" / "default.yaml",
108
+ PROJECT / "src" / "cli" / "interpret.py",
109
+ PROJECT / "src" / "data" / "protein_feat.py",
110
+ PROJECT / "src" / "data" / "split.py",
111
+ PROJECT / "src" / "analysis" / "generate_figures.py",
112
+ )
113
+ public_source = "\n".join(_read(path) for path in files)
114
+
115
+ assert "configured domain-label channel" in public_source
116
+ assert "none" in public_source
117
+ assert "target-id-held-out" in public_source
118
+ for phrase in (
119
+ "case study",
120
+ "case_stud",
121
+ "hotspot",
122
+ "binding pocket",
123
+ "binding-site",
124
+ "pdb-validated",
125
+ "resistance",
126
+ "mutant",
127
+ "predicted binding probability",
128
+ "high-confidence prediction",
129
+ ):
130
+ assert phrase not in public_source