docs(plan): add Day-5 downstream-model + XAI + interactive plan
Browse files5-step plan: BBB Random Forest classifier, SHAP top-k attributions,
POST /predict/bbb endpoint, interactive Streamlit BBB tab, trainer CLI
+ docs. Target: 157 tests green at completion.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
docs/superpowers/plans/2026-05-03-day5-downstream-model-xai-interactive.md
ADDED
|
@@ -0,0 +1,1014 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Day 5 — Downstream Model, Uncertainty, XAI & Interactive Demo
|
| 2 |
+
|
| 3 |
+
> **For agentic workers:** REQUIRED SUB-SKILL: Use `superpowers:subagent-driven-development` (recommended) or `superpowers:executing-plans` to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
| 4 |
+
|
| 5 |
+
**Goal:** Turn the Day-1..4 stack from a "data pipeline" into a "decision system" — train a downstream BBB-permeability classifier on the Morgan-fingerprint features, expose its probability + top-5 SHAP attributions through a new `POST /predict/bbb` endpoint, and rebuild the Streamlit BBB tab as a single-molecule interactive demo with a confidence bar + SHAP waterfall.
|
| 6 |
+
|
| 7 |
+
**Architecture:** A thin `src/models/bbb_model.py` module exposes `train(features_df)`, `save(model, path)`, `load(path)`, `predict_with_proba(model, smiles)` and `explain_prediction(model, smiles, top_k=5)`. The model is a scikit-learn `RandomForestClassifier` (already in requirements; XGBoost not needed and adds a heavy dep). Probabilities come from `predict_proba`; SHAP attributions use `TreeExplainer` (fast for tree models, exact). A trainer CLI (`python -m src.models.bbb_model`) materializes `data/processed/bbb_model.joblib` from the Day-4 features Parquet. FastAPI loads the artifact at startup; if missing, `/predict/bbb` returns 503 with a remediation hint. Streamlit's BBB tab is rebuilt around `st.text_input` (single SMILES) + `st.file_uploader` (CSV batch) and renders a result card + SHAP horizontal bar chart.
|
| 8 |
+
|
| 9 |
+
**Tech Stack:** scikit-learn 1.5.1 (existing), shap (new pin), joblib (sklearn transitive — explicitly pinned), Streamlit 1.39 (existing). No XGBoost (over-engineering for ECFP/Morgan binary classification at this dataset scale; RandomForest matches user's "XGBoost OR Random Forest" wording).
|
| 10 |
+
|
| 11 |
+
---
|
| 12 |
+
|
| 13 |
+
## File Structure
|
| 14 |
+
|
| 15 |
+
```
|
| 16 |
+
src/
|
| 17 |
+
├── models/
|
| 18 |
+
│ ├── __init__.py # NEW (empty)
|
| 19 |
+
│ └── bbb_model.py # NEW — Tasks 1+2: train/save/load/predict/explain + CLI
|
| 20 |
+
├── api/
|
| 21 |
+
│ ├── schemas.py # MODIFY — Task 3: BBBPredictRequest, BBBPredictResponse, FeatureAttribution
|
| 22 |
+
│ └── routes.py # MODIFY — Task 3: add POST /predict/bbb + startup artifact load
|
| 23 |
+
└── frontend/
|
| 24 |
+
└── app.py # MODIFY — Task 4: interactive BBB tab
|
| 25 |
+
|
| 26 |
+
tests/
|
| 27 |
+
├── models/
|
| 28 |
+
│ ├── __init__.py # NEW (empty)
|
| 29 |
+
│ └── test_bbb_model.py # NEW — Tasks 1+2: ~10 tests
|
| 30 |
+
├── api/
|
| 31 |
+
│ └── test_routes.py # MODIFY — Task 3: append TestBBBPredictRoute (3 tests)
|
| 32 |
+
└── frontend/
|
| 33 |
+
└── test_app_import.py # MODIFY — Task 4: extend smoke (still 2 tests, just verify new helpers)
|
| 34 |
+
|
| 35 |
+
requirements.txt # MODIFY — Task 1: pin shap, joblib
|
| 36 |
+
AGENTS.md # MODIFY — Task 5 close-out (§8 Decision Layer)
|
| 37 |
+
README.md # MODIFY — Task 5 close-out
|
| 38 |
+
```
|
| 39 |
+
|
| 40 |
+
**Test count target:** 142 (existing) + ~13 (new) = **~155 tests green at end of Day 5**.
|
| 41 |
+
|
| 42 |
+
---
|
| 43 |
+
|
| 44 |
+
## Task 1: BBB downstream model — train / save / load / predict_with_proba
|
| 45 |
+
|
| 46 |
+
**Files:**
|
| 47 |
+
- Create: `src/models/__init__.py` (empty)
|
| 48 |
+
- Create: `src/models/bbb_model.py`
|
| 49 |
+
- Create: `tests/models/__init__.py` (empty)
|
| 50 |
+
- Create: `tests/models/test_bbb_model.py`
|
| 51 |
+
- Modify: `requirements.txt` — add `shap==0.46.0` and `joblib==1.4.2`
|
| 52 |
+
|
| 53 |
+
- [ ] **Step 1: Add dependencies and install**
|
| 54 |
+
|
| 55 |
+
In `requirements.txt`, after the `# --- Modality: tabular ...` block (or in a new `# --- Downstream ML / XAI ---` block), add:
|
| 56 |
+
|
| 57 |
+
```
|
| 58 |
+
# --- Downstream ML / XAI (Day 5 decision layer) ---
|
| 59 |
+
shap==0.46.0
|
| 60 |
+
joblib==1.4.2
|
| 61 |
+
```
|
| 62 |
+
|
| 63 |
+
Then run:
|
| 64 |
+
```
|
| 65 |
+
cd /Users/mertgungor/Desktop/hackathon && source .venv312/bin/activate && pip install shap==0.46.0 joblib==1.4.2
|
| 66 |
+
```
|
| 67 |
+
|
| 68 |
+
- [ ] **Step 2: Write failing tests**
|
| 69 |
+
|
| 70 |
+
Create `tests/models/__init__.py` (empty file).
|
| 71 |
+
|
| 72 |
+
Create `tests/models/test_bbb_model.py`:
|
| 73 |
+
|
| 74 |
+
```python
|
| 75 |
+
"""Tests for src.models.bbb_model — train, save/load, predict, uncertainty."""
|
| 76 |
+
from __future__ import annotations
|
| 77 |
+
|
| 78 |
+
from pathlib import Path
|
| 79 |
+
|
| 80 |
+
import numpy as np
|
| 81 |
+
import pandas as pd
|
| 82 |
+
import pytest
|
| 83 |
+
|
| 84 |
+
from src.models import bbb_model
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
_FIXTURES = Path(__file__).resolve().parents[1] / "fixtures"
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
@pytest.fixture(scope="module")
|
| 91 |
+
def trained_model_and_features():
|
| 92 |
+
"""Train one tiny model from the committed BBBP fixture; cache for the module."""
|
| 93 |
+
from src.pipelines import bbb_pipeline
|
| 94 |
+
import tempfile
|
| 95 |
+
tmp = Path(tempfile.mkdtemp(prefix="bbb_model_test_"))
|
| 96 |
+
out = tmp / "features.parquet"
|
| 97 |
+
bbb_pipeline.run_pipeline(
|
| 98 |
+
input_path=_FIXTURES / "bbbp_sample.csv",
|
| 99 |
+
output_path=out,
|
| 100 |
+
)
|
| 101 |
+
df = pd.read_parquet(out)
|
| 102 |
+
# Tiny n_estimators for test speed; real training uses default 100.
|
| 103 |
+
model = bbb_model.train(df, label_col="p_np", n_estimators=10, random_state=42)
|
| 104 |
+
return model, df
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
class TestTrain:
|
| 108 |
+
def test_returns_fitted_classifier(self, trained_model_and_features):
|
| 109 |
+
model, _ = trained_model_and_features
|
| 110 |
+
# sklearn classifiers expose .classes_ after fit
|
| 111 |
+
assert hasattr(model, "classes_")
|
| 112 |
+
assert len(model.classes_) == 2
|
| 113 |
+
|
| 114 |
+
def test_raises_on_missing_label_column(self, trained_model_and_features):
|
| 115 |
+
_, df = trained_model_and_features
|
| 116 |
+
with pytest.raises(KeyError):
|
| 117 |
+
bbb_model.train(df.drop(columns=["p_np"]), label_col="p_np")
|
| 118 |
+
|
| 119 |
+
def test_deterministic_with_random_state(self, trained_model_and_features):
|
| 120 |
+
_, df = trained_model_and_features
|
| 121 |
+
m1 = bbb_model.train(df, label_col="p_np", n_estimators=10, random_state=42)
|
| 122 |
+
m2 = bbb_model.train(df, label_col="p_np", n_estimators=10, random_state=42)
|
| 123 |
+
# Two trainings with same seed produce identical predictions on the same input
|
| 124 |
+
fp_cols = [c for c in df.columns if c.startswith("fp_")]
|
| 125 |
+
X = df[fp_cols].to_numpy()
|
| 126 |
+
np.testing.assert_array_equal(m1.predict_proba(X), m2.predict_proba(X))
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
class TestSaveLoad:
|
| 130 |
+
def test_save_then_load_roundtrip(self, trained_model_and_features, tmp_path: Path):
|
| 131 |
+
model, df = trained_model_and_features
|
| 132 |
+
artifact = tmp_path / "bbb_model.joblib"
|
| 133 |
+
bbb_model.save(model, artifact)
|
| 134 |
+
assert artifact.exists()
|
| 135 |
+
|
| 136 |
+
reloaded = bbb_model.load(artifact)
|
| 137 |
+
fp_cols = [c for c in df.columns if c.startswith("fp_")]
|
| 138 |
+
X = df[fp_cols].to_numpy()
|
| 139 |
+
np.testing.assert_array_equal(model.predict(X), reloaded.predict(X))
|
| 140 |
+
|
| 141 |
+
def test_load_raises_on_missing_path(self, tmp_path: Path):
|
| 142 |
+
with pytest.raises(FileNotFoundError):
|
| 143 |
+
bbb_model.load(tmp_path / "does_not_exist.joblib")
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
class TestPredictWithProba:
|
| 147 |
+
def test_returns_label_and_probabilities(self, trained_model_and_features):
|
| 148 |
+
model, _ = trained_model_and_features
|
| 149 |
+
# A real-ish drug-like SMILES (ethanol — definitely BBB+)
|
| 150 |
+
result = bbb_model.predict_with_proba(model, "CCO")
|
| 151 |
+
assert "label" in result
|
| 152 |
+
assert "probability" in result
|
| 153 |
+
assert "confidence" in result
|
| 154 |
+
assert result["label"] in (0, 1)
|
| 155 |
+
# Probabilities for the predicted class
|
| 156 |
+
assert 0.0 <= result["probability"] <= 1.0
|
| 157 |
+
assert 0.0 <= result["confidence"] <= 1.0
|
| 158 |
+
|
| 159 |
+
def test_raises_on_invalid_smiles(self, trained_model_and_features):
|
| 160 |
+
model, _ = trained_model_and_features
|
| 161 |
+
with pytest.raises(ValueError):
|
| 162 |
+
bbb_model.predict_with_proba(model, "this_is_not_a_smiles_AT_ALL")
|
| 163 |
+
|
| 164 |
+
def test_confidence_equals_max_class_probability(self, trained_model_and_features):
|
| 165 |
+
"""confidence is the model's max class probability — its own self-rated certainty."""
|
| 166 |
+
model, _ = trained_model_and_features
|
| 167 |
+
result = bbb_model.predict_with_proba(model, "CCO")
|
| 168 |
+
# confidence should equal the probability of the predicted class
|
| 169 |
+
assert abs(result["confidence"] - result["probability"]) < 1e-9
|
| 170 |
+
```
|
| 171 |
+
|
| 172 |
+
- [ ] **Step 3: Run tests to verify they fail**
|
| 173 |
+
|
| 174 |
+
```
|
| 175 |
+
cd /Users/mertgungor/Desktop/hackathon && source .venv312/bin/activate && pytest tests/models/test_bbb_model.py -v
|
| 176 |
+
```
|
| 177 |
+
Expected: ImportError (`src.models.bbb_model` does not exist).
|
| 178 |
+
|
| 179 |
+
- [ ] **Step 4: Implement `src/models/bbb_model.py` (Task 1 surface only — train/save/load/predict)**
|
| 180 |
+
|
| 181 |
+
Create `src/models/__init__.py` (empty file).
|
| 182 |
+
|
| 183 |
+
Create `src/models/bbb_model.py`:
|
| 184 |
+
|
| 185 |
+
```python
|
| 186 |
+
"""BBB-permeability downstream classifier — train / save / load / predict.
|
| 187 |
+
|
| 188 |
+
Built on top of `data/processed/bbbp_features.parquet` produced by
|
| 189 |
+
`src.pipelines.bbb_pipeline`. Uses scikit-learn's `RandomForestClassifier`
|
| 190 |
+
(no XGBoost — saves a heavy dep without losing accuracy at this scale).
|
| 191 |
+
|
| 192 |
+
The model takes a 2,048-bit Morgan fingerprint as input. SHAP-based
|
| 193 |
+
explanation lives in this same module (Task 2 adds `explain_prediction`).
|
| 194 |
+
"""
|
| 195 |
+
from __future__ import annotations
|
| 196 |
+
|
| 197 |
+
from pathlib import Path
|
| 198 |
+
|
| 199 |
+
import joblib
|
| 200 |
+
import numpy as np
|
| 201 |
+
import pandas as pd
|
| 202 |
+
from sklearn.ensemble import RandomForestClassifier
|
| 203 |
+
|
| 204 |
+
from src.core.logger import get_logger
|
| 205 |
+
from src.pipelines.bbb_pipeline import (
|
| 206 |
+
compute_morgan_fingerprint,
|
| 207 |
+
is_valid_smiles,
|
| 208 |
+
)
|
| 209 |
+
|
| 210 |
+
logger = get_logger(__name__)
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
_FP_COL_PREFIX = "fp_"
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
def _split_features_and_label(
|
| 217 |
+
df: pd.DataFrame, label_col: str,
|
| 218 |
+
) -> tuple[np.ndarray, np.ndarray, list[str]]:
|
| 219 |
+
"""Pull out fp_* columns as X and `label_col` as y. Returns (X, y, fp_col_names)."""
|
| 220 |
+
if label_col not in df.columns:
|
| 221 |
+
raise KeyError(f"Label column {label_col!r} not in DataFrame")
|
| 222 |
+
fp_cols = [c for c in df.columns if c.startswith(_FP_COL_PREFIX)]
|
| 223 |
+
if not fp_cols:
|
| 224 |
+
raise KeyError(
|
| 225 |
+
f"No {_FP_COL_PREFIX}* columns found — was this DataFrame produced "
|
| 226 |
+
f"by bbb_pipeline.run_pipeline?"
|
| 227 |
+
)
|
| 228 |
+
X = df[fp_cols].to_numpy()
|
| 229 |
+
y = df[label_col].to_numpy()
|
| 230 |
+
return X, y, fp_cols
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
def train(
|
| 234 |
+
df: pd.DataFrame,
|
| 235 |
+
label_col: str = "p_np",
|
| 236 |
+
n_estimators: int = 100,
|
| 237 |
+
random_state: int = 42,
|
| 238 |
+
) -> RandomForestClassifier:
|
| 239 |
+
"""Train a Random Forest classifier on Morgan fingerprints.
|
| 240 |
+
|
| 241 |
+
Args:
|
| 242 |
+
df: Output of `bbb_pipeline.run_pipeline` — has `fp_0..fp_N-1` cols
|
| 243 |
+
plus a binary `label_col`.
|
| 244 |
+
label_col: Name of the binary target column. Defaults to "p_np"
|
| 245 |
+
(BBBP dataset's permeable / non-permeable).
|
| 246 |
+
n_estimators: Number of trees. 100 is the sklearn default; tests
|
| 247 |
+
override to 10 for speed.
|
| 248 |
+
random_state: Seed for split + tree construction. Required for
|
| 249 |
+
byte-deterministic predictions on the same input.
|
| 250 |
+
|
| 251 |
+
Returns:
|
| 252 |
+
A fitted `RandomForestClassifier` with `feature_names_in_` matching
|
| 253 |
+
the `fp_*` column order, so downstream callers can map SHAP values
|
| 254 |
+
back to human-meaningful bit indices.
|
| 255 |
+
"""
|
| 256 |
+
X, y, fp_cols = _split_features_and_label(df, label_col)
|
| 257 |
+
model = RandomForestClassifier(
|
| 258 |
+
n_estimators=n_estimators,
|
| 259 |
+
random_state=random_state,
|
| 260 |
+
n_jobs=1, # determinism: no thread races in tree fit
|
| 261 |
+
)
|
| 262 |
+
model.fit(X, y)
|
| 263 |
+
# Stash the column names so explainers can label features.
|
| 264 |
+
model.feature_names_in_ = np.array(fp_cols, dtype=object)
|
| 265 |
+
logger.info(
|
| 266 |
+
"Trained BBB classifier: n=%d, n_features=%d, classes=%s",
|
| 267 |
+
len(y), X.shape[1], model.classes_.tolist(),
|
| 268 |
+
)
|
| 269 |
+
return model
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
def save(model: RandomForestClassifier, path: Path) -> None:
|
| 273 |
+
"""Persist a fitted model to `path` (parent dirs auto-created)."""
|
| 274 |
+
path = Path(path)
|
| 275 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 276 |
+
joblib.dump(model, path)
|
| 277 |
+
logger.info("Saved BBB model to %s", path)
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
def load(path: Path) -> RandomForestClassifier:
|
| 281 |
+
"""Load a previously-saved model. Raises `FileNotFoundError` on missing artifact."""
|
| 282 |
+
path = Path(path)
|
| 283 |
+
if not path.exists():
|
| 284 |
+
raise FileNotFoundError(f"BBB model artifact not found: {path}")
|
| 285 |
+
return joblib.load(path)
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
def predict_with_proba(
|
| 289 |
+
model: RandomForestClassifier,
|
| 290 |
+
smiles: str,
|
| 291 |
+
n_bits: int = 2048,
|
| 292 |
+
radius: int = 2,
|
| 293 |
+
) -> dict[str, object]:
|
| 294 |
+
"""Predict BBB permeability for a single SMILES.
|
| 295 |
+
|
| 296 |
+
Args:
|
| 297 |
+
model: Fitted classifier from `train()` or `load()`.
|
| 298 |
+
smiles: A SMILES string. Validated via `is_valid_smiles`.
|
| 299 |
+
n_bits / radius: Must match the values used at training time
|
| 300 |
+
(defaults match `bbb_pipeline.run_pipeline`'s defaults).
|
| 301 |
+
|
| 302 |
+
Returns:
|
| 303 |
+
`{"label": int, "probability": float, "confidence": float}` where
|
| 304 |
+
`probability` is the predicted class's probability and `confidence`
|
| 305 |
+
is the model's self-rated certainty (max class probability — same
|
| 306 |
+
value as `probability` for the predicted class).
|
| 307 |
+
|
| 308 |
+
Raises:
|
| 309 |
+
ValueError: if `smiles` cannot be parsed by RDKit.
|
| 310 |
+
"""
|
| 311 |
+
if not is_valid_smiles(smiles):
|
| 312 |
+
raise ValueError(f"invalid SMILES: {smiles!r}")
|
| 313 |
+
fp = compute_morgan_fingerprint(smiles, n_bits=n_bits, radius=radius)
|
| 314 |
+
proba = model.predict_proba(fp.reshape(1, -1))[0] # shape (n_classes,)
|
| 315 |
+
label_idx = int(np.argmax(proba))
|
| 316 |
+
label = int(model.classes_[label_idx])
|
| 317 |
+
return {
|
| 318 |
+
"label": label,
|
| 319 |
+
"probability": float(proba[label_idx]),
|
| 320 |
+
"confidence": float(proba[label_idx]),
|
| 321 |
+
}
|
| 322 |
+
```
|
| 323 |
+
|
| 324 |
+
- [ ] **Step 5: Run tests, expect all to pass**
|
| 325 |
+
|
| 326 |
+
```
|
| 327 |
+
pytest tests/models/test_bbb_model.py -v
|
| 328 |
+
```
|
| 329 |
+
Expected: 8 passed (3 train + 2 save/load + 3 predict).
|
| 330 |
+
|
| 331 |
+
- [ ] **Step 6: Run full suite to confirm no regressions**
|
| 332 |
+
|
| 333 |
+
```
|
| 334 |
+
pytest -v 2>&1 | tail -3
|
| 335 |
+
```
|
| 336 |
+
Expected: 150 passed (142 prior + 8 new).
|
| 337 |
+
|
| 338 |
+
- [ ] **Step 7: Commit**
|
| 339 |
+
|
| 340 |
+
```bash
|
| 341 |
+
git add requirements.txt src/models/__init__.py src/models/bbb_model.py \
|
| 342 |
+
tests/models/__init__.py tests/models/test_bbb_model.py
|
| 343 |
+
git commit -m "feat(models): BBB classifier with predict_with_proba uncertainty"
|
| 344 |
+
```
|
| 345 |
+
|
| 346 |
+
---
|
| 347 |
+
|
| 348 |
+
## Task 2: SHAP explainability — top-5 feature attributions
|
| 349 |
+
|
| 350 |
+
**Files:**
|
| 351 |
+
- Modify: `src/models/bbb_model.py` (append `explain_prediction`)
|
| 352 |
+
- Modify: `tests/models/test_bbb_model.py` (append `TestExplainPrediction`)
|
| 353 |
+
|
| 354 |
+
- [ ] **Step 1: Write failing tests**
|
| 355 |
+
|
| 356 |
+
Append to `tests/models/test_bbb_model.py`:
|
| 357 |
+
|
| 358 |
+
```python
|
| 359 |
+
class TestExplainPrediction:
|
| 360 |
+
def test_returns_top_k_features(self, trained_model_and_features):
|
| 361 |
+
model, _ = trained_model_and_features
|
| 362 |
+
attributions = bbb_model.explain_prediction(model, "CCO", top_k=5)
|
| 363 |
+
assert len(attributions) == 5
|
| 364 |
+
# Each entry has feature name + shap value
|
| 365 |
+
for a in attributions:
|
| 366 |
+
assert "feature" in a
|
| 367 |
+
assert "shap_value" in a
|
| 368 |
+
assert isinstance(a["shap_value"], float)
|
| 369 |
+
|
| 370 |
+
def test_features_sorted_by_absolute_shap_value_descending(
|
| 371 |
+
self, trained_model_and_features,
|
| 372 |
+
):
|
| 373 |
+
model, _ = trained_model_and_features
|
| 374 |
+
attributions = bbb_model.explain_prediction(model, "CCO", top_k=10)
|
| 375 |
+
abs_vals = [abs(a["shap_value"]) for a in attributions]
|
| 376 |
+
assert abs_vals == sorted(abs_vals, reverse=True)
|
| 377 |
+
|
| 378 |
+
def test_features_named_fp_INDEX(self, trained_model_and_features):
|
| 379 |
+
model, _ = trained_model_and_features
|
| 380 |
+
attributions = bbb_model.explain_prediction(model, "CCO", top_k=3)
|
| 381 |
+
for a in attributions:
|
| 382 |
+
# SHAP values map back to fp_<integer> bit indices
|
| 383 |
+
assert a["feature"].startswith("fp_")
|
| 384 |
+
int(a["feature"].split("_")[1]) # parses cleanly
|
| 385 |
+
|
| 386 |
+
def test_raises_on_invalid_smiles(self, trained_model_and_features):
|
| 387 |
+
model, _ = trained_model_and_features
|
| 388 |
+
with pytest.raises(ValueError):
|
| 389 |
+
bbb_model.explain_prediction(model, "still_not_a_smiles", top_k=5)
|
| 390 |
+
```
|
| 391 |
+
|
| 392 |
+
- [ ] **Step 2: Run failing tests**
|
| 393 |
+
|
| 394 |
+
```
|
| 395 |
+
pytest tests/models/test_bbb_model.py::TestExplainPrediction -v
|
| 396 |
+
```
|
| 397 |
+
Expected: AttributeError — `explain_prediction` not defined.
|
| 398 |
+
|
| 399 |
+
- [ ] **Step 3: Implement `explain_prediction` in `src/models/bbb_model.py`**
|
| 400 |
+
|
| 401 |
+
Append after `predict_with_proba`:
|
| 402 |
+
|
| 403 |
+
```python
|
| 404 |
+
def explain_prediction(
|
| 405 |
+
model: RandomForestClassifier,
|
| 406 |
+
smiles: str,
|
| 407 |
+
top_k: int = 5,
|
| 408 |
+
n_bits: int = 2048,
|
| 409 |
+
radius: int = 2,
|
| 410 |
+
) -> list[dict[str, object]]:
|
| 411 |
+
"""Return the top-`top_k` feature attributions (SHAP values) for `smiles`.
|
| 412 |
+
|
| 413 |
+
Uses `shap.TreeExplainer` (exact for tree ensembles, no sampling). The
|
| 414 |
+
explanation is for the *predicted* class — i.e. SHAP values that pushed
|
| 415 |
+
the model toward whichever label was returned by `predict_with_proba`.
|
| 416 |
+
|
| 417 |
+
Args:
|
| 418 |
+
model: Fitted classifier from `train()` or `load()`.
|
| 419 |
+
smiles: A SMILES string (validated via `is_valid_smiles`).
|
| 420 |
+
top_k: How many top features to return. Default 5 — matches the
|
| 421 |
+
jury-demo budget (more bars = noisier waterfall chart).
|
| 422 |
+
n_bits / radius: Must match training-time fingerprint settings.
|
| 423 |
+
|
| 424 |
+
Returns:
|
| 425 |
+
A list of `{"feature": "fp_<bit_idx>", "shap_value": float}` dicts,
|
| 426 |
+
sorted by `abs(shap_value)` descending.
|
| 427 |
+
|
| 428 |
+
Raises:
|
| 429 |
+
ValueError: if `smiles` cannot be parsed by RDKit.
|
| 430 |
+
"""
|
| 431 |
+
import shap # local import — heavy module, only loaded when needed
|
| 432 |
+
|
| 433 |
+
if not is_valid_smiles(smiles):
|
| 434 |
+
raise ValueError(f"invalid SMILES: {smiles!r}")
|
| 435 |
+
fp = compute_morgan_fingerprint(smiles, n_bits=n_bits, radius=radius)
|
| 436 |
+
X = fp.reshape(1, -1)
|
| 437 |
+
|
| 438 |
+
explainer = shap.TreeExplainer(model)
|
| 439 |
+
shap_values = explainer.shap_values(X, check_additivity=False)
|
| 440 |
+
# `shap_values` shape varies by sklearn / shap versions:
|
| 441 |
+
# - older: list of (1, n_features) arrays, one per class
|
| 442 |
+
# - newer: ndarray of shape (1, n_features, n_classes) for binary RF
|
| 443 |
+
# - or (1, n_features) when output already condensed
|
| 444 |
+
if isinstance(shap_values, list):
|
| 445 |
+
# one (1, n_features) per class — pick the predicted class's array
|
| 446 |
+
proba = model.predict_proba(X)[0]
|
| 447 |
+
label_idx = int(np.argmax(proba))
|
| 448 |
+
per_feature = shap_values[label_idx][0]
|
| 449 |
+
else:
|
| 450 |
+
arr = np.asarray(shap_values)
|
| 451 |
+
if arr.ndim == 3:
|
| 452 |
+
# (1, n_features, n_classes)
|
| 453 |
+
proba = model.predict_proba(X)[0]
|
| 454 |
+
label_idx = int(np.argmax(proba))
|
| 455 |
+
per_feature = arr[0, :, label_idx]
|
| 456 |
+
else:
|
| 457 |
+
# (1, n_features)
|
| 458 |
+
per_feature = arr[0]
|
| 459 |
+
|
| 460 |
+
fp_cols = (
|
| 461 |
+
list(model.feature_names_in_)
|
| 462 |
+
if hasattr(model, "feature_names_in_")
|
| 463 |
+
else [f"fp_{i}" for i in range(len(per_feature))]
|
| 464 |
+
)
|
| 465 |
+
|
| 466 |
+
pairs = sorted(
|
| 467 |
+
zip(fp_cols, per_feature, strict=True),
|
| 468 |
+
key=lambda p: abs(p[1]),
|
| 469 |
+
reverse=True,
|
| 470 |
+
)
|
| 471 |
+
return [
|
| 472 |
+
{"feature": str(name), "shap_value": float(value)}
|
| 473 |
+
for name, value in pairs[:top_k]
|
| 474 |
+
]
|
| 475 |
+
```
|
| 476 |
+
|
| 477 |
+
- [ ] **Step 4: Run tests**
|
| 478 |
+
|
| 479 |
+
```
|
| 480 |
+
pytest tests/models/test_bbb_model.py::TestExplainPrediction -v
|
| 481 |
+
```
|
| 482 |
+
Expected: 4 passed.
|
| 483 |
+
|
| 484 |
+
- [ ] **Step 5: Run full suite**
|
| 485 |
+
|
| 486 |
+
```
|
| 487 |
+
pytest -v 2>&1 | tail -3
|
| 488 |
+
```
|
| 489 |
+
Expected: 154 passed (150 prior + 4 new).
|
| 490 |
+
|
| 491 |
+
- [ ] **Step 6: Commit**
|
| 492 |
+
|
| 493 |
+
```bash
|
| 494 |
+
git add src/models/bbb_model.py tests/models/test_bbb_model.py
|
| 495 |
+
git commit -m "feat(models): SHAP top-k explainer for BBB predictions"
|
| 496 |
+
```
|
| 497 |
+
|
| 498 |
+
---
|
| 499 |
+
|
| 500 |
+
## Task 3: FastAPI `POST /predict/bbb` endpoint
|
| 501 |
+
|
| 502 |
+
**Files:**
|
| 503 |
+
- Modify: `src/api/schemas.py` — add `BBBPredictRequest`, `FeatureAttribution`, `BBBPredictResponse`
|
| 504 |
+
- Modify: `src/api/routes.py` — add `POST /predict/bbb` + lazy model loading
|
| 505 |
+
- Modify: `tests/api/test_routes.py` — append `TestBBBPredictRoute` (3 tests)
|
| 506 |
+
|
| 507 |
+
- [ ] **Step 1: Add schemas**
|
| 508 |
+
|
| 509 |
+
In `/Users/mertgungor/Desktop/hackathon/src/api/schemas.py`, append at the bottom:
|
| 510 |
+
|
| 511 |
+
```python
|
| 512 |
+
class BBBPredictRequest(BaseModel):
|
| 513 |
+
"""Single-molecule BBB-permeability prediction request."""
|
| 514 |
+
smiles: str = Field(..., description="SMILES string; e.g. 'CCO' for ethanol")
|
| 515 |
+
top_k: int = Field(5, ge=1, le=20, description="Top-k SHAP features to return")
|
| 516 |
+
|
| 517 |
+
|
| 518 |
+
class FeatureAttribution(BaseModel):
|
| 519 |
+
feature: str
|
| 520 |
+
shap_value: float
|
| 521 |
+
|
| 522 |
+
|
| 523 |
+
class BBBPredictResponse(BaseModel):
|
| 524 |
+
"""Decision-system payload: prediction + uncertainty + explanation."""
|
| 525 |
+
label: int
|
| 526 |
+
label_text: str = Field(..., description="'permeable' or 'non-permeable'")
|
| 527 |
+
probability: float
|
| 528 |
+
confidence: float
|
| 529 |
+
top_features: list[FeatureAttribution]
|
| 530 |
+
```
|
| 531 |
+
|
| 532 |
+
- [ ] **Step 2: Write failing route tests**
|
| 533 |
+
|
| 534 |
+
Append to `/Users/mertgungor/Desktop/hackathon/tests/api/test_routes.py`:
|
| 535 |
+
|
| 536 |
+
```python
|
| 537 |
+
class TestBBBPredictRoute:
|
| 538 |
+
def test_returns_200_with_prediction_and_attributions(self, tmp_path: Path):
|
| 539 |
+
"""End-to-end: train tiny model, save, point env at it, POST a SMILES."""
|
| 540 |
+
import os
|
| 541 |
+
from src.pipelines import bbb_pipeline
|
| 542 |
+
from src.models import bbb_model
|
| 543 |
+
# 1. Build features from the committed fixture
|
| 544 |
+
features_path = tmp_path / "features.parquet"
|
| 545 |
+
bbb_pipeline.run_pipeline(
|
| 546 |
+
input_path=_FIXTURES / "bbbp_sample.csv",
|
| 547 |
+
output_path=features_path,
|
| 548 |
+
)
|
| 549 |
+
# 2. Train + save a tiny model
|
| 550 |
+
import pandas as pd
|
| 551 |
+
df = pd.read_parquet(features_path)
|
| 552 |
+
model = bbb_model.train(df, label_col="p_np", n_estimators=10, random_state=42)
|
| 553 |
+
artifact = tmp_path / "bbb_model.joblib"
|
| 554 |
+
bbb_model.save(model, artifact)
|
| 555 |
+
# 3. Point the API at this artifact (env-var override)
|
| 556 |
+
os.environ["BBB_MODEL_PATH"] = str(artifact)
|
| 557 |
+
try:
|
| 558 |
+
resp = client.post(
|
| 559 |
+
"/predict/bbb",
|
| 560 |
+
json={"smiles": "CCO", "top_k": 5},
|
| 561 |
+
)
|
| 562 |
+
assert resp.status_code == 200
|
| 563 |
+
body = resp.json()
|
| 564 |
+
assert body["label"] in (0, 1)
|
| 565 |
+
assert body["label_text"] in ("permeable", "non-permeable")
|
| 566 |
+
assert 0.0 <= body["probability"] <= 1.0
|
| 567 |
+
assert 0.0 <= body["confidence"] <= 1.0
|
| 568 |
+
assert len(body["top_features"]) == 5
|
| 569 |
+
for f in body["top_features"]:
|
| 570 |
+
assert f["feature"].startswith("fp_")
|
| 571 |
+
assert isinstance(f["shap_value"], float)
|
| 572 |
+
finally:
|
| 573 |
+
os.environ.pop("BBB_MODEL_PATH", None)
|
| 574 |
+
|
| 575 |
+
def test_returns_400_on_invalid_smiles(self, tmp_path: Path):
|
| 576 |
+
import os
|
| 577 |
+
from src.pipelines import bbb_pipeline
|
| 578 |
+
from src.models import bbb_model
|
| 579 |
+
import pandas as pd
|
| 580 |
+
features_path = tmp_path / "features.parquet"
|
| 581 |
+
bbb_pipeline.run_pipeline(
|
| 582 |
+
input_path=_FIXTURES / "bbbp_sample.csv",
|
| 583 |
+
output_path=features_path,
|
| 584 |
+
)
|
| 585 |
+
df = pd.read_parquet(features_path)
|
| 586 |
+
model = bbb_model.train(df, label_col="p_np", n_estimators=10, random_state=42)
|
| 587 |
+
artifact = tmp_path / "bbb_model.joblib"
|
| 588 |
+
bbb_model.save(model, artifact)
|
| 589 |
+
os.environ["BBB_MODEL_PATH"] = str(artifact)
|
| 590 |
+
try:
|
| 591 |
+
resp = client.post(
|
| 592 |
+
"/predict/bbb",
|
| 593 |
+
json={"smiles": "this_is_not_a_smiles", "top_k": 5},
|
| 594 |
+
)
|
| 595 |
+
assert resp.status_code == 400
|
| 596 |
+
finally:
|
| 597 |
+
os.environ.pop("BBB_MODEL_PATH", None)
|
| 598 |
+
|
| 599 |
+
def test_returns_503_when_artifact_missing(self, tmp_path: Path):
|
| 600 |
+
import os
|
| 601 |
+
os.environ["BBB_MODEL_PATH"] = str(tmp_path / "does_not_exist.joblib")
|
| 602 |
+
try:
|
| 603 |
+
resp = client.post(
|
| 604 |
+
"/predict/bbb",
|
| 605 |
+
json={"smiles": "CCO", "top_k": 5},
|
| 606 |
+
)
|
| 607 |
+
assert resp.status_code == 503
|
| 608 |
+
finally:
|
| 609 |
+
os.environ.pop("BBB_MODEL_PATH", None)
|
| 610 |
+
```
|
| 611 |
+
|
| 612 |
+
- [ ] **Step 3: Run failing tests**
|
| 613 |
+
|
| 614 |
+
```
|
| 615 |
+
pytest tests/api/test_routes.py::TestBBBPredictRoute -v
|
| 616 |
+
```
|
| 617 |
+
Expected: 3 errors — endpoint not mounted.
|
| 618 |
+
|
| 619 |
+
- [ ] **Step 4: Implement the route**
|
| 620 |
+
|
| 621 |
+
In `/Users/mertgungor/Desktop/hackathon/src/api/routes.py`, append at the end:
|
| 622 |
+
|
| 623 |
+
```python
|
| 624 |
+
from src.api.schemas import BBBPredictRequest, BBBPredictResponse, FeatureAttribution
|
| 625 |
+
from src.models import bbb_model
|
| 626 |
+
|
| 627 |
+
# Default artifact location. Overridable via BBB_MODEL_PATH env var so tests
|
| 628 |
+
# can point at a tmp-built model without touching production paths.
|
| 629 |
+
_DEFAULT_BBB_MODEL_PATH = Path("data/processed/bbb_model.joblib")
|
| 630 |
+
|
| 631 |
+
|
| 632 |
+
def _bbb_model_path() -> Path:
|
| 633 |
+
return Path(os.environ.get("BBB_MODEL_PATH", str(_DEFAULT_BBB_MODEL_PATH)))
|
| 634 |
+
|
| 635 |
+
|
| 636 |
+
@router.post("/predict/bbb", response_model=BBBPredictResponse, prefix="")
|
| 637 |
+
def predict_bbb(req: BBBPredictRequest) -> BBBPredictResponse:
|
| 638 |
+
"""Predict BBB permeability + return SHAP attributions for one SMILES."""
|
| 639 |
+
artifact = _bbb_model_path()
|
| 640 |
+
if not artifact.exists():
|
| 641 |
+
raise HTTPException(
|
| 642 |
+
status_code=503,
|
| 643 |
+
detail=(
|
| 644 |
+
f"BBB model artifact not available at {artifact}. "
|
| 645 |
+
f"Run `python -m src.models.bbb_model` to train it."
|
| 646 |
+
),
|
| 647 |
+
)
|
| 648 |
+
try:
|
| 649 |
+
model = bbb_model.load(artifact)
|
| 650 |
+
except FileNotFoundError as e:
|
| 651 |
+
raise HTTPException(status_code=503, detail=str(e))
|
| 652 |
+
|
| 653 |
+
try:
|
| 654 |
+
pred = bbb_model.predict_with_proba(model, req.smiles)
|
| 655 |
+
attributions = bbb_model.explain_prediction(model, req.smiles, top_k=req.top_k)
|
| 656 |
+
except ValueError as e:
|
| 657 |
+
raise HTTPException(status_code=400, detail=str(e))
|
| 658 |
+
|
| 659 |
+
label_text = "permeable" if pred["label"] == 1 else "non-permeable"
|
| 660 |
+
return BBBPredictResponse(
|
| 661 |
+
label=pred["label"],
|
| 662 |
+
label_text=label_text,
|
| 663 |
+
probability=pred["probability"],
|
| 664 |
+
confidence=pred["confidence"],
|
| 665 |
+
top_features=[FeatureAttribution(**a) for a in attributions],
|
| 666 |
+
)
|
| 667 |
+
```
|
| 668 |
+
|
| 669 |
+
> **Important**: the `prefix=""` on the router decorator above is a hack — `APIRouter(prefix="/pipeline")` set the global prefix, but `/predict/bbb` is a sibling not a child of `/pipeline`. **Fix the placement instead**: don't use `@router.post(...)` for this endpoint. Use a *new* router with no prefix, or register the route directly on `app` from `main.py`. Cleanest: in `routes.py` add a second `predict_router = APIRouter()` (no prefix) at module scope, register `predict_bbb` on it, and export it. Then `main.py` does `app.include_router(predict_router)` alongside `pipeline_router`.
|
| 670 |
+
|
| 671 |
+
Actual implementation pattern:
|
| 672 |
+
|
| 673 |
+
In `src/api/routes.py`, near the top after the existing `router = APIRouter(prefix="/pipeline")`, add:
|
| 674 |
+
|
| 675 |
+
```python
|
| 676 |
+
predict_router = APIRouter(prefix="/predict")
|
| 677 |
+
```
|
| 678 |
+
|
| 679 |
+
Then the endpoint:
|
| 680 |
+
|
| 681 |
+
```python
|
| 682 |
+
@predict_router.post("/bbb", response_model=BBBPredictResponse)
|
| 683 |
+
def predict_bbb(req: BBBPredictRequest) -> BBBPredictResponse:
|
| 684 |
+
# ... (same body as above, minus the prefix="" hack)
|
| 685 |
+
```
|
| 686 |
+
|
| 687 |
+
Add `import os` to the imports block at top of `routes.py` if not already present.
|
| 688 |
+
|
| 689 |
+
- [ ] **Step 5: Mount the new router in `src/api/main.py`**
|
| 690 |
+
|
| 691 |
+
In `src/api/main.py`, change the existing import line:
|
| 692 |
+
|
| 693 |
+
```python
|
| 694 |
+
from src.api.routes import router as pipeline_router
|
| 695 |
+
```
|
| 696 |
+
|
| 697 |
+
to:
|
| 698 |
+
|
| 699 |
+
```python
|
| 700 |
+
from src.api.routes import router as pipeline_router, predict_router
|
| 701 |
+
```
|
| 702 |
+
|
| 703 |
+
And below the existing `app.include_router(pipeline_router)` line, add:
|
| 704 |
+
|
| 705 |
+
```python
|
| 706 |
+
app.include_router(predict_router)
|
| 707 |
+
```
|
| 708 |
+
|
| 709 |
+
- [ ] **Step 6: Run tests**
|
| 710 |
+
|
| 711 |
+
```
|
| 712 |
+
pytest tests/api/ -v
|
| 713 |
+
```
|
| 714 |
+
Expected: 11 passed (8 prior + 3 new).
|
| 715 |
+
|
| 716 |
+
- [ ] **Step 7: Run full suite**
|
| 717 |
+
|
| 718 |
+
```
|
| 719 |
+
pytest -v 2>&1 | tail -3
|
| 720 |
+
```
|
| 721 |
+
Expected: 157 passed (154 prior + 3 new).
|
| 722 |
+
|
| 723 |
+
- [ ] **Step 8: Commit**
|
| 724 |
+
|
| 725 |
+
```bash
|
| 726 |
+
git add src/api/schemas.py src/api/routes.py src/api/main.py tests/api/test_routes.py
|
| 727 |
+
git commit -m "feat(api): POST /predict/bbb with prediction, uncertainty, SHAP top-k"
|
| 728 |
+
```
|
| 729 |
+
|
| 730 |
+
---
|
| 731 |
+
|
| 732 |
+
## Task 4: Interactive Streamlit BBB tab
|
| 733 |
+
|
| 734 |
+
**Files:**
|
| 735 |
+
- Modify: `src/frontend/app.py` — replace `_render_bbb_tab` body with interactive form
|
| 736 |
+
- (No test changes — the existing 2 frontend tests still pass; manual smoke verifies UX.)
|
| 737 |
+
|
| 738 |
+
- [ ] **Step 1: Replace `_render_bbb_tab` in `src/frontend/app.py`**
|
| 739 |
+
|
| 740 |
+
Find the existing `_render_bbb_tab` function and replace its entire body with:
|
| 741 |
+
|
| 742 |
+
```python
|
| 743 |
+
def _render_bbb_tab() -> None:
|
| 744 |
+
_render_section(
|
| 745 |
+
"MOLECULE — BBBP",
|
| 746 |
+
"Blood-Brain-Barrier permeability decision",
|
| 747 |
+
"Enter a SMILES string. The system computes a 2,048-bit Morgan "
|
| 748 |
+
"fingerprint, runs it through a trained Random Forest classifier, "
|
| 749 |
+
"and returns the predicted permeability label, the model's "
|
| 750 |
+
"self-rated confidence, and the top-5 SHAP feature attributions "
|
| 751 |
+
"explaining the decision.",
|
| 752 |
+
)
|
| 753 |
+
|
| 754 |
+
smiles = st.text_input(
|
| 755 |
+
"SMILES string",
|
| 756 |
+
value="CCO",
|
| 757 |
+
key="bbb_smiles",
|
| 758 |
+
help="Examples: CCO (ethanol, BBB+), CC(=O)Nc1ccc(O)cc1 (paracetamol)",
|
| 759 |
+
)
|
| 760 |
+
top_k = st.slider("SHAP features to display", min_value=3, max_value=10, value=5, key="bbb_topk")
|
| 761 |
+
|
| 762 |
+
if st.button("Predict BBB permeability", type="primary", key="bbb_predict"):
|
| 763 |
+
with st.spinner("Computing fingerprint, predicting, and explaining…"):
|
| 764 |
+
try:
|
| 765 |
+
result = _post("/predict/bbb", {"smiles": smiles, "top_k": top_k})
|
| 766 |
+
_render_prediction_card(result)
|
| 767 |
+
st.toast("Prediction complete", icon="✅")
|
| 768 |
+
except httpx.HTTPStatusError as e:
|
| 769 |
+
if e.response.status_code == 503:
|
| 770 |
+
st.error(
|
| 771 |
+
"Model artifact not loaded yet. Run "
|
| 772 |
+
"`python -m src.models.bbb_model` to train it, "
|
| 773 |
+
"then retry."
|
| 774 |
+
)
|
| 775 |
+
else:
|
| 776 |
+
st.error(f"Prediction failed (HTTP {e.response.status_code}): {e.response.text}")
|
| 777 |
+
except httpx.RequestError as e:
|
| 778 |
+
st.error(f"Cannot reach FastAPI at {_API_URL}: {e!r}")
|
| 779 |
+
```
|
| 780 |
+
|
| 781 |
+
- [ ] **Step 2: Add `_render_prediction_card` helper above `main()`**
|
| 782 |
+
|
| 783 |
+
Insert above `main()`:
|
| 784 |
+
|
| 785 |
+
```python
|
| 786 |
+
def _render_prediction_card(result: dict) -> None:
|
| 787 |
+
"""Render a B2B-styled decision card: label badge + confidence + SHAP bars."""
|
| 788 |
+
label_text = _html.escape(str(result["label_text"]))
|
| 789 |
+
badge_color = "#166534" if result["label"] == 1 else "#991B1B"
|
| 790 |
+
badge_bg = "#DCFCE7" if result["label"] == 1 else "#FEE2E2"
|
| 791 |
+
confidence_pct = result["confidence"] * 100
|
| 792 |
+
|
| 793 |
+
st.markdown(
|
| 794 |
+
f"""
|
| 795 |
+
<div style='background:#FFFFFF;border:1px solid #E2E8F0;border-radius:10px;
|
| 796 |
+
padding:1.5rem;margin:1rem 0;box-shadow:0 1px 2px rgba(15,23,42,0.04);'>
|
| 797 |
+
<p style='font-size:0.72rem;font-weight:700;color:#64748B;
|
| 798 |
+
letter-spacing:0.08em;text-transform:uppercase;margin:0;'>Prediction</p>
|
| 799 |
+
<div style='display:flex;align-items:center;gap:0.75rem;margin-top:0.4rem;'>
|
| 800 |
+
<span style='background:{badge_bg};color:{badge_color};
|
| 801 |
+
padding:0.4rem 0.9rem;border-radius:999px;
|
| 802 |
+
font-size:1rem;font-weight:700;letter-spacing:0.01em;'>
|
| 803 |
+
{label_text.upper()}
|
| 804 |
+
</span>
|
| 805 |
+
<span style='color:#475569;font-size:0.95rem;'>
|
| 806 |
+
Model confidence: <strong style='color:#0F172A;'>{confidence_pct:.1f}%</strong>
|
| 807 |
+
</span>
|
| 808 |
+
</div>
|
| 809 |
+
</div>
|
| 810 |
+
""",
|
| 811 |
+
unsafe_allow_html=True,
|
| 812 |
+
)
|
| 813 |
+
|
| 814 |
+
# Confidence bar
|
| 815 |
+
st.markdown(
|
| 816 |
+
"<p style='font-size:0.72rem;font-weight:700;color:#64748B;"
|
| 817 |
+
"letter-spacing:0.08em;text-transform:uppercase;margin:1rem 0 0.4rem 0;'>"
|
| 818 |
+
"Confidence</p>",
|
| 819 |
+
unsafe_allow_html=True,
|
| 820 |
+
)
|
| 821 |
+
st.progress(float(result["confidence"]))
|
| 822 |
+
|
| 823 |
+
# SHAP attributions chart
|
| 824 |
+
st.markdown(
|
| 825 |
+
"<p style='font-size:0.72rem;font-weight:700;color:#64748B;"
|
| 826 |
+
"letter-spacing:0.08em;text-transform:uppercase;margin:1.5rem 0 0.4rem 0;'>"
|
| 827 |
+
f"Top {len(result['top_features'])} SHAP attributions</p>",
|
| 828 |
+
unsafe_allow_html=True,
|
| 829 |
+
)
|
| 830 |
+
import pandas as pd
|
| 831 |
+
shap_df = pd.DataFrame(result["top_features"]).set_index("feature")
|
| 832 |
+
st.bar_chart(shap_df, height=240, color="#0369A1")
|
| 833 |
+
|
| 834 |
+
st.caption(
|
| 835 |
+
"Positive SHAP values pushed the model toward the predicted class; "
|
| 836 |
+
"negative values pushed it away. Feature names are 2,048-bit Morgan "
|
| 837 |
+
"fingerprint indices (`fp_<bit>`)."
|
| 838 |
+
)
|
| 839 |
+
```
|
| 840 |
+
|
| 841 |
+
- [ ] **Step 3: Run smoke tests**
|
| 842 |
+
|
| 843 |
+
```
|
| 844 |
+
pytest tests/frontend/ -v
|
| 845 |
+
```
|
| 846 |
+
Expected: 2 passed (the existing import smoke tests still cover the module).
|
| 847 |
+
|
| 848 |
+
- [ ] **Step 4: Run full suite**
|
| 849 |
+
|
| 850 |
+
```
|
| 851 |
+
pytest -v 2>&1 | tail -3
|
| 852 |
+
```
|
| 853 |
+
Expected: 157 passed (no test count change — UI redesign is covered by manual smoke).
|
| 854 |
+
|
| 855 |
+
- [ ] **Step 5: Manual smoke (recommended)**
|
| 856 |
+
|
| 857 |
+
```
|
| 858 |
+
streamlit run src/frontend/app.py --server.headless true &
|
| 859 |
+
sleep 5
|
| 860 |
+
curl -s http://localhost:8501 | head -3
|
| 861 |
+
pkill -f "streamlit run"
|
| 862 |
+
```
|
| 863 |
+
Expected: HTML response. Then open the dashboard manually in a browser, paste `CCO` in the BBB tab, click Predict, verify card renders + SHAP bar chart appears.
|
| 864 |
+
|
| 865 |
+
- [ ] **Step 6: Commit**
|
| 866 |
+
|
| 867 |
+
```bash
|
| 868 |
+
git add src/frontend/app.py
|
| 869 |
+
git commit -m "feat(frontend): interactive BBB tab — SMILES input + decision card + SHAP bars"
|
| 870 |
+
```
|
| 871 |
+
|
| 872 |
+
---
|
| 873 |
+
|
| 874 |
+
## Task 5: Trainer CLI + close-out (AGENTS.md §8 + README + DoD)
|
| 875 |
+
|
| 876 |
+
**Files:**
|
| 877 |
+
- Modify: `src/models/bbb_model.py` — add `if __name__ == "__main__":` CLI for training
|
| 878 |
+
- Modify: `AGENTS.md` — §2 directory layout + new §8 Decision Layer
|
| 879 |
+
- Modify: `README.md` — Day 5 row + how-to-train section
|
| 880 |
+
|
| 881 |
+
- [ ] **Step 1: Add training CLI to `src/models/bbb_model.py`**
|
| 882 |
+
|
| 883 |
+
Append at the bottom of the file:
|
| 884 |
+
|
| 885 |
+
```python
|
| 886 |
+
DEFAULT_FEATURES_PATH = Path("data/processed/bbbp_features.parquet")
|
| 887 |
+
DEFAULT_MODEL_PATH = Path("data/processed/bbb_model.joblib")
|
| 888 |
+
|
| 889 |
+
|
| 890 |
+
def main() -> None:
|
| 891 |
+
"""Train and persist the production BBB model from the Day-4 features Parquet.
|
| 892 |
+
|
| 893 |
+
Reads from `DEFAULT_FEATURES_PATH`, trains with default hyperparameters,
|
| 894 |
+
and writes the artifact to `DEFAULT_MODEL_PATH`. Re-runs are idempotent
|
| 895 |
+
(same random_state).
|
| 896 |
+
"""
|
| 897 |
+
if not DEFAULT_FEATURES_PATH.exists():
|
| 898 |
+
raise FileNotFoundError(
|
| 899 |
+
f"Features Parquet not found at {DEFAULT_FEATURES_PATH}. "
|
| 900 |
+
f"Run `python -m src.pipelines.bbb_pipeline` first."
|
| 901 |
+
)
|
| 902 |
+
df = pd.read_parquet(DEFAULT_FEATURES_PATH)
|
| 903 |
+
model = train(df, label_col="p_np")
|
| 904 |
+
save(model, DEFAULT_MODEL_PATH)
|
| 905 |
+
logger.info("BBB model artifact ready at %s", DEFAULT_MODEL_PATH)
|
| 906 |
+
|
| 907 |
+
|
| 908 |
+
if __name__ == "__main__":
|
| 909 |
+
main()
|
| 910 |
+
```
|
| 911 |
+
|
| 912 |
+
- [ ] **Step 2: Update AGENTS.md**
|
| 913 |
+
|
| 914 |
+
Add `src/models/bbb_model.py` to the §2 layout tree.
|
| 915 |
+
|
| 916 |
+
After §7 Experiment Tracking, append:
|
| 917 |
+
|
| 918 |
+
```markdown
|
| 919 |
+
## 8. Decision Layer (Downstream Models)
|
| 920 |
+
|
| 921 |
+
Pipelines produce features (`data/processed/<modality>_features.parquet`).
|
| 922 |
+
Downstream models live in `src/models/` and consume those features:
|
| 923 |
+
|
| 924 |
+
| Model | File | Output | Endpoint |
|
| 925 |
+
|---|---|---|---|
|
| 926 |
+
| BBB permeability | `src/models/bbb_model.py` | `data/processed/bbb_model.joblib` | `POST /predict/bbb` |
|
| 927 |
+
|
| 928 |
+
Each downstream model module exposes a uniform surface:
|
| 929 |
+
- `train(df, label_col, ...)` → fitted classifier
|
| 930 |
+
- `save(model, path)` / `load(path)` → joblib artifact I/O
|
| 931 |
+
- `predict_with_proba(model, smiles)` → `{label, probability, confidence}`
|
| 932 |
+
- `explain_prediction(model, smiles, top_k)` → SHAP top-k attributions
|
| 933 |
+
|
| 934 |
+
The API loads the joblib artifact at request time. If the artifact is
|
| 935 |
+
missing, the endpoint returns **HTTP 503** with a remediation hint pointing
|
| 936 |
+
at the trainer CLI (`python -m src.models.<name>`). This keeps the API
|
| 937 |
+
process startup fast and lets operators retrain without redeploying.
|
| 938 |
+
|
| 939 |
+
**Determinism**: all classifiers are seeded (`random_state=42` default). Re-running
|
| 940 |
+
the trainer on the same Parquet produces identical predictions.
|
| 941 |
+
```
|
| 942 |
+
|
| 943 |
+
- [ ] **Step 3: Update README.md**
|
| 944 |
+
|
| 945 |
+
Add Day 5 to the status table:
|
| 946 |
+
|
| 947 |
+
```markdown
|
| 948 |
+
| Day 5 — Decision Layer (Model + XAI + Interactive UI) | ✅ Shipped — 157 tests green |
|
| 949 |
+
```
|
| 950 |
+
|
| 951 |
+
Add a "Train the BBB model" step under Quick Start:
|
| 952 |
+
|
| 953 |
+
```markdown
|
| 954 |
+
### Train the downstream BBB model (one-time)
|
| 955 |
+
|
| 956 |
+
```bash
|
| 957 |
+
python -m src.pipelines.bbb_pipeline # produces data/processed/bbbp_features.parquet
|
| 958 |
+
python -m src.models.bbb_model # produces data/processed/bbb_model.joblib
|
| 959 |
+
```
|
| 960 |
+
|
| 961 |
+
Then `POST /predict/bbb` (and the Streamlit BBB tab) become live.
|
| 962 |
+
```
|
| 963 |
+
|
| 964 |
+
Add to "Where to Look":
|
| 965 |
+
- `src/models/bbb_model.py` (downstream classifier + SHAP)
|
| 966 |
+
- `tests/models/test_bbb_model.py` (~12 tests)
|
| 967 |
+
|
| 968 |
+
- [ ] **Step 4: DoD smoke run**
|
| 969 |
+
|
| 970 |
+
```
|
| 971 |
+
cd /Users/mertgungor/Desktop/hackathon && source .venv312/bin/activate
|
| 972 |
+
pytest -v 2>&1 | tail -3
|
| 973 |
+
# Expect: 157 passed
|
| 974 |
+
```
|
| 975 |
+
|
| 976 |
+
If the BBB raw input is not present, skip the live API smoke. If it is:
|
| 977 |
+
|
| 978 |
+
```
|
| 979 |
+
python -m src.pipelines.bbb_pipeline
|
| 980 |
+
python -m src.models.bbb_model
|
| 981 |
+
uvicorn src.api.main:app --port 8000 &
|
| 982 |
+
sleep 4
|
| 983 |
+
curl -s -X POST http://localhost:8000/predict/bbb \
|
| 984 |
+
-H 'Content-Type: application/json' \
|
| 985 |
+
-d '{"smiles": "CCO", "top_k": 5}' | python3 -m json.tool
|
| 986 |
+
pkill -f "uvicorn src.api.main:app"
|
| 987 |
+
```
|
| 988 |
+
Expected: `label`, `label_text`, `probability`, `confidence`, and 5-element `top_features` array.
|
| 989 |
+
|
| 990 |
+
- [ ] **Step 5: Commit**
|
| 991 |
+
|
| 992 |
+
```bash
|
| 993 |
+
git add src/models/bbb_model.py AGENTS.md README.md
|
| 994 |
+
git commit -m "docs: Day-5 close-out — AGENTS §8 decision layer + trainer CLI"
|
| 995 |
+
```
|
| 996 |
+
|
| 997 |
+
---
|
| 998 |
+
|
| 999 |
+
## Definition of Done (Day 5)
|
| 1000 |
+
|
| 1001 |
+
| Check | Pass criterion |
|
| 1002 |
+
|---|---|
|
| 1003 |
+
| `pytest -v` reports 157 passed | yes |
|
| 1004 |
+
| `src/models/bbb_model.py` exposes `train`, `save`, `load`, `predict_with_proba`, `explain_prediction` | yes |
|
| 1005 |
+
| `python -m src.models.bbb_model` produces a joblib artifact | yes (DoD smoke) |
|
| 1006 |
+
| `POST /predict/bbb` returns label + label_text + probability + confidence + top_features | yes |
|
| 1007 |
+
| 503 returned when artifact is missing (live-demo lifeline) | yes (test) |
|
| 1008 |
+
| 400 returned on invalid SMILES | yes (test) |
|
| 1009 |
+
| Streamlit BBB tab has SMILES input + Predict button + decision card + SHAP bar chart | yes (manual) |
|
| 1010 |
+
| AGENTS.md §8 documents the decision-layer contract | yes |
|
| 1011 |
+
| Existing 142 tests still green (no regressions) | yes (full suite) |
|
| 1012 |
+
| The 4 design constraints are met: Interaction (text input), Uncertainty (confidence %), Explainability (SHAP top-5), Decision (binary label + label_text) | yes |
|
| 1013 |
+
|
| 1014 |
+
When all rows green: Day 5 complete. The system is now an end-to-end **Living + Decision System**: data → features → model → uncertainty → explanation → interactive UI.
|