pd-discovery-benchmark-dashboard / scripts /01_build_benchmark.py
hssling's picture
Add PD discovery benchmark dashboard resource
30a3bc1 verified
"""
Build a Parkinson's disease discovery benchmark dataset and dashboard inputs.
Inputs:
- PD_AI_Evidence_to_Discovery_Project
- PD_Target_to_Intervention_Discovery_Extension
Outputs:
- integrated target benchmark
- compound selectivity/safety matrix
- model/assay benchmark
- resource figures
- quality checks
"""
from __future__ import annotations
import json
import math
import time
from pathlib import Path
import matplotlib.pyplot as plt
import networkx as nx
import pandas as pd
import requests
import seaborn as sns
ROOT = Path(__file__).resolve().parents[1]
BASE = ROOT.parent
EVID = BASE / "PD_AI_Evidence_to_Discovery_Project"
EXT = BASE / "PD_Target_to_Intervention_Discovery_Extension"
DATA = ROOT / "data"
FIG = ROOT / "figures"
REPORTS = ROOT / "reports"
REPRO = ROOT / "reproducibility"
for d in [DATA, FIG, REPORTS, REPRO]:
d.mkdir(parents=True, exist_ok=True)
def read_csv(path: Path) -> pd.DataFrame:
return pd.read_csv(path) if path.exists() else pd.DataFrame()
def get_json(url: str, params: dict | None = None) -> tuple[dict | None, str]:
try:
r = requests.get(url, params=params, timeout=35)
r.raise_for_status()
return r.json(), "ok"
except Exception as exc: # noqa: BLE001
return None, f"{type(exc).__name__}: {exc}"
def chembl_selectivity(molecule_id: str) -> dict:
data, status = get_json(
"https://www.ebi.ac.uk/chembl/api/data/activity.json",
{
"molecule_chembl_id": molecule_id,
"standard_units": "nM",
"standard_value__lte": 1000,
"limit": 1000,
},
)
out = {"molecule_chembl_id": molecule_id, "selectivity_status": status}
if not data:
return out
acts = data.get("activities", [])
targets = {a.get("target_chembl_id") for a in acts if a.get("target_chembl_id")}
types = {a.get("standard_type") for a in acts if a.get("standard_type")}
out["active_target_count_lte_1000nM"] = len(targets)
out["activity_record_count_lte_1000nM"] = len(acts)
out["activity_types"] = ";".join(sorted(types))
out["polypharmacology_flag"] = len(targets) >= 10
out["selectivity_penalty_0_20"] = min(20, max(0, (len(targets) - 1) * 2))
return out
def build_target_benchmark() -> pd.DataFrame:
target = read_csv(EXT / "data/processed/target_tractability_ranked.csv")
expr = read_csv(EXT / "data/stem_cell/cell_type_expression_validation_matrix.csv")
validation = read_csv(EXT / "data/validation/experimental_validation_matrix.csv")
interventions = read_csv(EVID / "data/processed/candidate_interventions_ranked.csv")
pathway = read_csv(EVID / "data/processed/pathway_intervention_framework.csv")
# Module-level translational score from original evidence, mapped conservatively by terms.
module_scores = []
for _, t in target.iterrows():
score = 50.0
mod = str(t["module"]).lower()
for _, i in interventions.iterrows():
text = (str(i["intervention_or_target"]) + " " + str(i["primary_target_pathway"])).lower()
if any(k in text for k in mod.replace("/", " ").split()[:3]):
score = max(score, float(i["priority_score_0_100"]))
if "lrrk2" in mod:
score = max(score, float(interventions.loc[interventions["intervention_or_target"].str.contains("LRRK2", case=False), "priority_score_0_100"].max()))
if "gba" in mod or "lysosome" in mod:
score = max(score, float(interventions.loc[interventions["intervention_or_target"].str.contains("GBA|lysosomal", case=False, regex=True), "priority_score_0_100"].max()))
if "glp" in mod:
score = max(score, float(interventions.loc[interventions["intervention_or_target"].str.contains("GLP", case=False), "priority_score_0_100"].max()))
if "alpha" in mod or "synuclein" in mod:
score = max(score, float(interventions.loc[interventions["intervention_or_target"].str.contains("synuclein", case=False), "priority_score_0_100"].max()))
module_scores.append({"symbol": t["symbol"], "evidence_translation_score_0_100": score})
module_df = pd.DataFrame(module_scores)
bench = target.merge(expr, on=["symbol", "ensembl_id"], how="left").merge(validation, on=["symbol", "module"], how="left", suffixes=("", "_validation")).merge(module_df, on="symbol", how="left")
bench["omics_pathway_support_0_100"] = bench["module"].str.lower().map(lambda x: 75 if any(k in x for k in ["immune", "il-17", "nod", "map", "ntrk"]) else 60 if any(k in x for k in ["mitochond", "lysosome", "gba", "synuclein"]) else 50)
bench["cell_type_support_0_100"] = bench["stem_cell_validation_relevance_score_0_100"].fillna(40)
bench["compound_support_0_100"] = bench["chemistry_score_20"].fillna(0) / 20 * 100
bench["structure_support_0_100"] = bench["structure_score_15"].fillna(0) / 15 * 100
bench["assay_support_0_100"] = bench["assayability_score_15"].fillna(0) / 15 * 100
bench["benchmark_consensus_score_0_100"] = (
bench["target_to_intervention_score_100"].astype(float) * 0.25
+ bench["evidence_translation_score_0_100"].astype(float) * 0.20
+ bench["omics_pathway_support_0_100"].astype(float) * 0.15
+ bench["cell_type_support_0_100"].astype(float) * 0.15
+ bench["compound_support_0_100"].astype(float) * 0.15
+ bench["assay_support_0_100"].astype(float) * 0.10
).round(1)
bench["benchmark_label"] = pd.cut(
bench["benchmark_consensus_score_0_100"],
bins=[-1, 50, 65, 80, 100],
labels=["exploratory", "validation-ready", "high-priority validation", "benchmark lead"],
)
keep = [
"symbol",
"module",
"role",
"benchmark_consensus_score_0_100",
"benchmark_label",
"target_to_intervention_score_100",
"evidence_translation_score_0_100",
"omics_pathway_support_0_100",
"cell_type_support_0_100",
"compound_support_0_100",
"structure_support_0_100",
"assay_support_0_100",
"model",
"primary_assay",
"recommended_next_experiment",
"uniprot_accession",
"ensembl_id",
"chembl_target_id",
"ligand_count",
"pdb_count",
"alphafold_url",
]
bench = bench[keep].sort_values("benchmark_consensus_score_0_100", ascending=False)
bench.to_csv(DATA / "pd_discovery_target_benchmark.csv", index=False)
return bench
def build_compound_matrix() -> pd.DataFrame:
compounds = read_csv(EXT / "data/chemical/prioritised_compound_shortlist.csv")
if compounds.empty:
return compounds
top_ids = compounds["molecule_chembl_id"].drop_duplicates().head(80).tolist()
rows = []
failures = []
for mid in top_ids:
row = chembl_selectivity(mid)
rows.append(row)
if row.get("selectivity_status") != "ok":
failures.append(row)
time.sleep(0.04)
selectivity = pd.DataFrame(rows)
out = compounds.merge(selectivity, on="molecule_chembl_id", how="left")
out["polypharmacology_flag"] = out["polypharmacology_flag"].fillna(False).astype(bool)
out["selectivity_penalty_0_20"] = pd.to_numeric(out["selectivity_penalty_0_20"], errors="coerce").fillna(10)
out["black_box_warning"] = pd.to_numeric(out["black_box_warning"], errors="coerce").fillna(0)
out["withdrawn_flag"] = pd.to_numeric(out["withdrawn_flag"], errors="coerce").fillna(0)
out["safety_liability_penalty_0_30"] = (
out["black_box_warning"].clip(0, 1) * 10
+ out["withdrawn_flag"].clip(0, 1) * 15
+ out["polypharmacology_flag"].astype(int) * 5
)
out["refined_compound_score_0_100"] = (
pd.to_numeric(out["compound_priority_score_0_100"], errors="coerce").fillna(0)
- out["selectivity_penalty_0_20"]
- out["safety_liability_penalty_0_30"]
).clip(lower=0).round(1)
out["triage_recommendation"] = pd.cut(
out["refined_compound_score_0_100"],
bins=[-1, 30, 50, 70, 100],
labels=["deprioritise", "review manually", "experimental comparator", "shortlist for deeper validation"],
)
out = out.sort_values("refined_compound_score_0_100", ascending=False)
out.to_csv(DATA / "compound_selectivity_safety_matrix.csv", index=False)
pd.DataFrame(failures).to_csv(REPRO / "compound_selectivity_query_failures.csv", index=False)
return out
def build_knowledge_graph(bench: pd.DataFrame, compounds: pd.DataFrame) -> nx.Graph:
G = nx.Graph()
for _, r in bench.iterrows():
G.add_node(r["symbol"], kind="target", score=float(r["benchmark_consensus_score_0_100"]))
G.add_node(r["module"], kind="pathway")
G.add_node(r["model"], kind="cell_model")
G.add_node(r["primary_assay"], kind="assay")
G.add_edge(r["symbol"], r["module"], relation="belongs_to_pathway")
G.add_edge(r["symbol"], r["model"], relation="validated_in_model")
G.add_edge(r["model"], r["primary_assay"], relation="measured_by")
if not compounds.empty:
for _, c in compounds.head(80).iterrows():
name = c.get("molecule_pref_name_detail") or c.get("molecule_pref_name") or c["molecule_chembl_id"]
name = str(name) if str(name) != "nan" and str(name).strip() else c["molecule_chembl_id"]
G.add_node(name, kind="compound", score=float(c["refined_compound_score_0_100"]), chembl_id=c["molecule_chembl_id"])
G.add_edge(c["symbol"], name, relation="has_refined_activity", potency_nM=float(c["standard_value_num"]))
nx.write_graphml(G, DATA / "pd_discovery_benchmark_knowledge_graph.graphml")
pd.DataFrame([{"node": n, **d} for n, d in G.nodes(data=True)]).to_csv(DATA / "benchmark_graph_nodes.csv", index=False)
pd.DataFrame([{"source": u, "target": v, **d} for u, v, d in G.edges(data=True)]).to_csv(DATA / "benchmark_graph_edges.csv", index=False)
return G
def make_figures(bench: pd.DataFrame, compounds: pd.DataFrame, G: nx.Graph) -> None:
sns.set_theme(style="whitegrid", context="paper")
fig, ax = plt.subplots(figsize=(10, 6.8))
p = bench.sort_values("benchmark_consensus_score_0_100")
ax.barh(p["symbol"], p["benchmark_consensus_score_0_100"], color="#2E75B6")
ax.set_xlim(0, 100)
ax.set_xlabel("Benchmark consensus score")
ax.set_title("PD discovery benchmark target ranking")
for i, v in enumerate(p["benchmark_consensus_score_0_100"]):
ax.text(v + 1, i, f"{v:.1f}", va="center", fontsize=8)
fig.savefig(FIG / "benchmark_target_ranking.png", dpi=350, bbox_inches="tight")
fig.savefig(FIG / "benchmark_target_ranking.svg", bbox_inches="tight")
plt.close(fig)
score_cols = [
"target_to_intervention_score_100",
"evidence_translation_score_0_100",
"omics_pathway_support_0_100",
"cell_type_support_0_100",
"compound_support_0_100",
"structure_support_0_100",
"assay_support_0_100",
]
fig, ax = plt.subplots(figsize=(12, 7))
sns.heatmap(bench.set_index("symbol")[score_cols], annot=True, fmt=".0f", cmap="YlGnBu", linewidths=0.4, ax=ax, cbar_kws={"label": "Score"})
ax.set_title("PD discovery benchmark evidence matrix")
ax.set_xlabel("")
ax.set_ylabel("")
fig.savefig(FIG / "benchmark_evidence_matrix.png", dpi=350, bbox_inches="tight")
fig.savefig(FIG / "benchmark_evidence_matrix.svg", bbox_inches="tight")
plt.close(fig)
if not compounds.empty:
c = compounds.head(30)
fig, ax = plt.subplots(figsize=(10, 6))
scatter = ax.scatter(c["compound_priority_score_0_100"], c["refined_compound_score_0_100"], c=c["selectivity_penalty_0_20"], cmap="magma", s=70, alpha=0.82, edgecolor="white")
ax.plot([0, 100], [0, 100], ls="--", color="#777777", lw=1)
ax.set_xlabel("Initial compound priority score")
ax.set_ylabel("Refined score after selectivity/safety penalties")
ax.set_title("Compound triage after selectivity and safety-liability filters")
for _, r in c.head(10).iterrows():
label = r.get("molecule_pref_name_detail") or r.get("molecule_chembl_id")
ax.text(r["compound_priority_score_0_100"] + 1, r["refined_compound_score_0_100"], str(label)[:16], fontsize=7)
cb = fig.colorbar(scatter, ax=ax)
cb.set_label("Selectivity penalty")
fig.savefig(FIG / "compound_selectivity_safety_triage.png", dpi=350, bbox_inches="tight")
fig.savefig(FIG / "compound_selectivity_safety_triage.svg", bbox_inches="tight")
plt.close(fig)
pos = nx.spring_layout(G, seed=42, k=0.75)
colors = {"target": "#C00000", "pathway": "#1F4E79", "cell_model": "#70AD47", "assay": "#F4B183", "compound": "#7030A0"}
fig, ax = plt.subplots(figsize=(15, 11))
nx.draw_networkx_edges(G, pos, alpha=0.14, width=0.6, ax=ax)
for kind, color in colors.items():
nodes = [n for n, d in G.nodes(data=True) if d.get("kind") == kind]
nx.draw_networkx_nodes(G, pos, nodelist=nodes, node_color=color, node_size=620 if kind == "target" else 240, alpha=0.9, label=kind, edgecolors="white", linewidths=0.5, ax=ax)
labels = {n: n for n, d in G.nodes(data=True) if d.get("kind") in {"target", "pathway"}}
nx.draw_networkx_labels(G, pos, labels=labels, font_size=7, ax=ax)
ax.legend(loc="upper left", frameon=True)
ax.axis("off")
ax.set_title("PD discovery benchmark knowledge graph")
fig.savefig(FIG / "benchmark_knowledge_graph.png", dpi=350, bbox_inches="tight")
fig.savefig(FIG / "benchmark_knowledge_graph.svg", bbox_inches="tight")
plt.close(fig)
def write_reports(bench: pd.DataFrame, compounds: pd.DataFrame, G: nx.Graph) -> None:
md = f"""# PD Discovery Benchmark Resource
## Purpose
This resource integrates evidence synthesis, omics/pathway support, target tractability, protein/structure information, ChEMBL compound evidence, Human Protein Atlas cell-type relevance, model/assay mapping, and knowledge-graph outputs for Parkinson's disease target-to-intervention discovery.
## Key Outputs
- `data/pd_discovery_target_benchmark.csv`
- `data/compound_selectivity_safety_matrix.csv`
- `data/pd_discovery_benchmark_knowledge_graph.graphml`
- `data/benchmark_graph_nodes.csv`
- `data/benchmark_graph_edges.csv`
- `figures/benchmark_target_ranking.png`
- `figures/benchmark_evidence_matrix.png`
- `figures/compound_selectivity_safety_triage.png`
- `figures/benchmark_knowledge_graph.png`
- `dashboard/app.py`
## Top Benchmark Targets
{bench.head(10)[["symbol", "module", "benchmark_consensus_score_0_100", "benchmark_label"]].to_markdown(index=False)}
## Top Refined Compounds
{compounds.head(12)[["symbol", "molecule_chembl_id", "molecule_pref_name_detail", "standard_value_num", "active_target_count_lte_1000nM", "refined_compound_score_0_100", "triage_recommendation"]].to_markdown(index=False) if not compounds.empty else "No compounds available."}
## Knowledge Graph
- Nodes: {G.number_of_nodes()}
- Edges: {G.number_of_edges()}
## Interpretation
The benchmark is designed for research reuse, validation, teaching, and computational experimentation. It should be treated as a prioritisation resource, not a clinical tool.
## Limitations
- ChEMBL selectivity is based on available activity records and is not a complete pharmacology review.
- BBB/CNS heuristics are simple physicochemical rules, not validated pharmacokinetic predictions.
- Human Protein Atlas cell-type information is a lightweight expression screen and should be extended with curated PD single-cell and iPSC datasets.
- Causal inference, Mendelian randomisation, and docking are specified as logical next modules but are not fully executed here.
- No compound is recommended for PD prevention or treatment based on this benchmark.
"""
(REPORTS / "pd_discovery_benchmark_report.md").write_text(md, encoding="utf-8")
quality = pd.DataFrame(
[
["target benchmark", "pass", f"{len(bench)} targets integrated."],
["compound selectivity/safety matrix", "pass", f"{len(compounds)} filtered compound-target records."],
["knowledge graph", "pass", f"{G.number_of_nodes()} nodes and {G.number_of_edges()} edges."],
["clinical guardrail", "pass", "No clinical recommendation or cure claim."],
],
columns=["domain", "status", "notes"],
)
quality.to_csv(REPRO / "benchmark_quality_check.csv", index=False)
def main() -> None:
bench = build_target_benchmark()
compounds = build_compound_matrix()
G = build_knowledge_graph(bench, compounds)
make_figures(bench, compounds, G)
write_reports(bench, compounds, G)
print("Benchmark built.")
if __name__ == "__main__":
main()