Update src/validation/external_benchmark.py
Browse files
src/validation/external_benchmark.py
CHANGED
|
@@ -15,16 +15,7 @@ YOR1,NaCl,resistant,0.06,HIP-HOP_demo
|
|
| 15 |
ATM1,NaCl,resistant,0.10,HIP-HOP_demo
|
| 16 |
""")
|
| 17 |
|
| 18 |
-
|
| 19 |
-
# Looks for any of these files (CSV/TSV). Put them anywhere under data/external/.
|
| 20 |
-
# HIP-HOP fitness: gene, condition/compound, effect(or fitness/logFC), pval/FDR (optional)
|
| 21 |
-
# MoAmap signatures: gene, compound, correlation/effect, pval/FDR (optional)
|
| 22 |
-
# SGD phenotypes: gene, phenotype, condition (free text), direction (e.g., 'sensitive','resistant')
|
| 23 |
-
#
|
| 24 |
-
# Output:
|
| 25 |
-
# results/validation_external_matrix.csv (#evidence per gene×stress, signed)
|
| 26 |
-
# results/validation_external_concordance.csv (direction vs our ATE)
|
| 27 |
-
# results/validation_external_heatmap.png
|
| 28 |
|
| 29 |
import os, re, json, glob, numpy as np, pandas as pd, matplotlib.pyplot as plt, seaborn as sns
|
| 30 |
from pathlib import Path
|
|
@@ -32,7 +23,6 @@ from pathlib import Path
|
|
| 32 |
RES = Path("results"); RES.mkdir(exist_ok=True, parents=True)
|
| 33 |
EXT = Path("data/external")
|
| 34 |
|
| 35 |
-
# ---------- helpers ----------
|
| 36 |
def _read_any(path):
|
| 37 |
if path.endswith(".tsv") or path.endswith(".tab"):
|
| 38 |
return pd.read_csv(path, sep="\t", dtype=str, low_memory=False)
|
|
@@ -44,10 +34,9 @@ def _coerce_float(s):
|
|
| 44 |
|
| 45 |
def _norm_gene(x):
|
| 46 |
x = (str(x) or "").strip()
|
| 47 |
-
x = re.sub(r"_expr$", "", x)
|
| 48 |
x = x.upper()
|
| 49 |
-
|
| 50 |
-
x = re.sub(r"^Y[A-P][LR][0-9]{3}[CW](-[A-Z])?$", x, x) # keep ORF if already ORF
|
| 51 |
return x
|
| 52 |
|
| 53 |
def _stress_from_text(t):
|
|
@@ -63,7 +52,6 @@ def _sign_from_effect(val, dir_text=None):
|
|
| 63 |
d = str(dir_text).lower()
|
| 64 |
if any(k in d for k in ["resist", "increased tolerance", "gain"]): return +1
|
| 65 |
if any(k in d for k in ["sensit", "hypersens", "loss"]): return -1
|
| 66 |
-
# fall back to numeric sign
|
| 67 |
try:
|
| 68 |
v = float(val)
|
| 69 |
if np.isnan(v): return 0
|
|
@@ -71,10 +59,8 @@ def _sign_from_effect(val, dir_text=None):
|
|
| 71 |
except:
|
| 72 |
return 0
|
| 73 |
|
| 74 |
-
# ---------- load our ATEs ----------
|
| 75 |
snap = json.load(open(RES/"causal_section3_snapshot.json"))
|
| 76 |
ATE_table = snap.get("ATE_table") or snap.get("stress_ate") or {}
|
| 77 |
-
# flatten to transporter→stress→ATE
|
| 78 |
flat = []
|
| 79 |
for k,v in ATE_table.items():
|
| 80 |
g = _norm_gene(k)
|
|
@@ -89,7 +75,6 @@ if df_ate.empty:
|
|
| 89 |
# anchors for quick viewing later
|
| 90 |
anchors = ["PDR5","SNQ2","YOR1","ATM1"]
|
| 91 |
|
| 92 |
-
# ---------- scan external sources ----------
|
| 93 |
files = []
|
| 94 |
for pat in ["**/*hip*hop*.csv","**/*hip*hop*.tsv",
|
| 95 |
"**/*moa*map*.csv","**/*moa*map*.tsv",
|
|
@@ -128,30 +113,26 @@ for f in sorted(set(files)):
|
|
| 128 |
|
| 129 |
ext = pd.DataFrame(ext_rows)
|
| 130 |
if ext.empty:
|
| 131 |
-
print("
|
| 132 |
else:
|
| 133 |
print(f"Loaded external evidence rows: {len(ext)} from {ext['source'].nunique()} files")
|
| 134 |
|
| 135 |
-
# ---------- aggregate external evidence ----------
|
| 136 |
if ext.empty:
|
| 137 |
-
# still write empty shells, so the paper pipeline doesn't break
|
| 138 |
pd.DataFrame(columns=["gene","stress","evidence_n","evidence_balance"]).to_csv(RES/"validation_external_matrix.csv", index=False)
|
| 139 |
pd.DataFrame(columns=["gene","stress","ATE","ext_consensus","concordant"]).to_csv(RES/"validation_external_concordance.csv", index=False)
|
| 140 |
else:
|
| 141 |
agg = (ext
|
| 142 |
.groupby(["gene","stress"])["sign"]
|
| 143 |
-
.agg(evidence_n="count", evidence_balance="sum")
|
| 144 |
.reset_index())
|
| 145 |
agg.to_csv(RES/"validation_external_matrix.csv", index=False)
|
| 146 |
|
| 147 |
-
# merge with our ATEs and compute concordance of direction
|
| 148 |
M = df_ate.merge(agg, on=["gene","stress"], how="left")
|
| 149 |
M["ext_consensus"] = np.sign(M["evidence_balance"].fillna(0))
|
| 150 |
M["ate_sign"] = np.sign(M["ATE"])
|
| 151 |
M["concordant"] = (M["ext_consensus"] != 0) & (M["ate_sign"] == M["ext_consensus"])
|
| 152 |
M.to_csv(RES/"validation_external_concordance.csv", index=False)
|
| 153 |
|
| 154 |
-
# quick heatmap of external consensus vs our ATE (anchors first if present)
|
| 155 |
order_genes = [g for g in anchors if g in set(M["gene"])] + [g for g in M["gene"].unique() if g not in anchors]
|
| 156 |
pt = M.pivot_table(index="gene", columns="stress", values="ext_consensus", aggfunc="first").reindex(order_genes)
|
| 157 |
plt.figure(figsize=(7, max(3, 0.35*len(pt))))
|
|
@@ -159,7 +140,6 @@ else:
|
|
| 159 |
plt.title("External benchmark — consensus sign (HIP-HOP/MoAmap/SGD)")
|
| 160 |
plt.tight_layout(); plt.savefig(RES/"validation_external_heatmap.png", dpi=300); plt.show()
|
| 161 |
|
| 162 |
-
# short summary for the anchors
|
| 163 |
summ = (M[M["gene"].isin(anchors)]
|
| 164 |
.groupby("gene")[["concordant"]]
|
| 165 |
.mean().rename(columns={"concordant":"concordance_rate"}))
|
|
@@ -171,13 +151,11 @@ print("Saved:",
|
|
| 171 |
RES/"validation_external_concordance.csv",
|
| 172 |
RES/"validation_external_heatmap.png")
|
| 173 |
|
| 174 |
-
# === External benchmark heatmap (robust) ===
|
| 175 |
import numpy as np, pandas as pd, seaborn as sns, matplotlib.pyplot as plt, pathlib as p
|
| 176 |
|
| 177 |
RES = p.Path("results")
|
| 178 |
concord = pd.read_csv(RES/"validation_external_concordance.csv")
|
| 179 |
|
| 180 |
-
# Find/derive the external sign column
|
| 181 |
sign_col = None
|
| 182 |
for c in concord.columns:
|
| 183 |
if "sign" in c.lower() and c.lower() != "atlas_sign":
|
|
@@ -185,12 +163,10 @@ for c in concord.columns:
|
|
| 185 |
break
|
| 186 |
|
| 187 |
if sign_col is None:
|
| 188 |
-
|
| 189 |
-
mat = pd.read_csv(RES/"validation_external_matrix.csv") # columns: gene, stress, value (or one col per stress)
|
| 190 |
if {"gene","stress","value"}.issubset(mat.columns):
|
| 191 |
ext_long = mat.rename(columns={"value":"external_consensus_sign"})
|
| 192 |
else:
|
| 193 |
-
# wide → long
|
| 194 |
long_rows=[]
|
| 195 |
wide_stresses = [c for c in mat.columns if c not in ["gene","Gene","GENE"]]
|
| 196 |
gcol = "gene" if "gene" in mat.columns else ("Gene" if "Gene" in mat.columns else "GENE")
|
|
@@ -200,15 +176,13 @@ if sign_col is None:
|
|
| 200 |
long_rows.append({"gene": g, "stress": s, "external_consensus_sign": getattr(r, s)})
|
| 201 |
ext_long = pd.DataFrame(long_rows)
|
| 202 |
else:
|
| 203 |
-
# Use the column we found in concordance
|
| 204 |
ext_long = concord[["gene","stress",sign_col]].rename(columns={sign_col:"external_consensus_sign"})
|
| 205 |
|
| 206 |
-
# Keep only non-zero/finite entries
|
| 207 |
ext_long["external_consensus_sign"] = pd.to_numeric(ext_long["external_consensus_sign"], errors="coerce").fillna(0.0)
|
| 208 |
ext_plot = ext_long[np.abs(ext_long["external_consensus_sign"]) > 0].copy()
|
| 209 |
|
| 210 |
if ext_plot.empty:
|
| 211 |
-
print("
|
| 212 |
else:
|
| 213 |
pv = ext_plot.pivot(index="gene", columns="stress", values="external_consensus_sign")
|
| 214 |
plt.figure(figsize=(6, max(3, 0.4*pv.shape[0])))
|
|
@@ -218,4 +192,4 @@ else:
|
|
| 218 |
plt.tight_layout()
|
| 219 |
out = RES/"validation_external_subset_heatmap.png"
|
| 220 |
plt.savefig(out, dpi=300); plt.show()
|
| 221 |
-
print("
|
|
|
|
| 15 |
ATM1,NaCl,resistant,0.10,HIP-HOP_demo
|
| 16 |
""")
|
| 17 |
|
| 18 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
|
| 20 |
import os, re, json, glob, numpy as np, pandas as pd, matplotlib.pyplot as plt, seaborn as sns
|
| 21 |
from pathlib import Path
|
|
|
|
| 23 |
RES = Path("results"); RES.mkdir(exist_ok=True, parents=True)
|
| 24 |
EXT = Path("data/external")
|
| 25 |
|
|
|
|
| 26 |
def _read_any(path):
|
| 27 |
if path.endswith(".tsv") or path.endswith(".tab"):
|
| 28 |
return pd.read_csv(path, sep="\t", dtype=str, low_memory=False)
|
|
|
|
| 34 |
|
| 35 |
def _norm_gene(x):
|
| 36 |
x = (str(x) or "").strip()
|
| 37 |
+
x = re.sub(r"_expr$", "", x)
|
| 38 |
x = x.upper()
|
| 39 |
+
x = re.sub(r"^Y[A-P][LR][0-9]{3}[CW](-[A-Z])?$", x, x)
|
|
|
|
| 40 |
return x
|
| 41 |
|
| 42 |
def _stress_from_text(t):
|
|
|
|
| 52 |
d = str(dir_text).lower()
|
| 53 |
if any(k in d for k in ["resist", "increased tolerance", "gain"]): return +1
|
| 54 |
if any(k in d for k in ["sensit", "hypersens", "loss"]): return -1
|
|
|
|
| 55 |
try:
|
| 56 |
v = float(val)
|
| 57 |
if np.isnan(v): return 0
|
|
|
|
| 59 |
except:
|
| 60 |
return 0
|
| 61 |
|
|
|
|
| 62 |
snap = json.load(open(RES/"causal_section3_snapshot.json"))
|
| 63 |
ATE_table = snap.get("ATE_table") or snap.get("stress_ate") or {}
|
|
|
|
| 64 |
flat = []
|
| 65 |
for k,v in ATE_table.items():
|
| 66 |
g = _norm_gene(k)
|
|
|
|
| 75 |
# anchors for quick viewing later
|
| 76 |
anchors = ["PDR5","SNQ2","YOR1","ATM1"]
|
| 77 |
|
|
|
|
| 78 |
files = []
|
| 79 |
for pat in ["**/*hip*hop*.csv","**/*hip*hop*.tsv",
|
| 80 |
"**/*moa*map*.csv","**/*moa*map*.tsv",
|
|
|
|
| 113 |
|
| 114 |
ext = pd.DataFrame(ext_rows)
|
| 115 |
if ext.empty:
|
| 116 |
+
print(" No usable external rows found under", EXT.resolve())
|
| 117 |
else:
|
| 118 |
print(f"Loaded external evidence rows: {len(ext)} from {ext['source'].nunique()} files")
|
| 119 |
|
|
|
|
| 120 |
if ext.empty:
|
|
|
|
| 121 |
pd.DataFrame(columns=["gene","stress","evidence_n","evidence_balance"]).to_csv(RES/"validation_external_matrix.csv", index=False)
|
| 122 |
pd.DataFrame(columns=["gene","stress","ATE","ext_consensus","concordant"]).to_csv(RES/"validation_external_concordance.csv", index=False)
|
| 123 |
else:
|
| 124 |
agg = (ext
|
| 125 |
.groupby(["gene","stress"])["sign"]
|
| 126 |
+
.agg(evidence_n="count", evidence_balance="sum")
|
| 127 |
.reset_index())
|
| 128 |
agg.to_csv(RES/"validation_external_matrix.csv", index=False)
|
| 129 |
|
|
|
|
| 130 |
M = df_ate.merge(agg, on=["gene","stress"], how="left")
|
| 131 |
M["ext_consensus"] = np.sign(M["evidence_balance"].fillna(0))
|
| 132 |
M["ate_sign"] = np.sign(M["ATE"])
|
| 133 |
M["concordant"] = (M["ext_consensus"] != 0) & (M["ate_sign"] == M["ext_consensus"])
|
| 134 |
M.to_csv(RES/"validation_external_concordance.csv", index=False)
|
| 135 |
|
|
|
|
| 136 |
order_genes = [g for g in anchors if g in set(M["gene"])] + [g for g in M["gene"].unique() if g not in anchors]
|
| 137 |
pt = M.pivot_table(index="gene", columns="stress", values="ext_consensus", aggfunc="first").reindex(order_genes)
|
| 138 |
plt.figure(figsize=(7, max(3, 0.35*len(pt))))
|
|
|
|
| 140 |
plt.title("External benchmark — consensus sign (HIP-HOP/MoAmap/SGD)")
|
| 141 |
plt.tight_layout(); plt.savefig(RES/"validation_external_heatmap.png", dpi=300); plt.show()
|
| 142 |
|
|
|
|
| 143 |
summ = (M[M["gene"].isin(anchors)]
|
| 144 |
.groupby("gene")[["concordant"]]
|
| 145 |
.mean().rename(columns={"concordant":"concordance_rate"}))
|
|
|
|
| 151 |
RES/"validation_external_concordance.csv",
|
| 152 |
RES/"validation_external_heatmap.png")
|
| 153 |
|
|
|
|
| 154 |
import numpy as np, pandas as pd, seaborn as sns, matplotlib.pyplot as plt, pathlib as p
|
| 155 |
|
| 156 |
RES = p.Path("results")
|
| 157 |
concord = pd.read_csv(RES/"validation_external_concordance.csv")
|
| 158 |
|
|
|
|
| 159 |
sign_col = None
|
| 160 |
for c in concord.columns:
|
| 161 |
if "sign" in c.lower() and c.lower() != "atlas_sign":
|
|
|
|
| 163 |
break
|
| 164 |
|
| 165 |
if sign_col is None:
|
| 166 |
+
mat = pd.read_csv(RES/"validation_external_matrix.csv")
|
|
|
|
| 167 |
if {"gene","stress","value"}.issubset(mat.columns):
|
| 168 |
ext_long = mat.rename(columns={"value":"external_consensus_sign"})
|
| 169 |
else:
|
|
|
|
| 170 |
long_rows=[]
|
| 171 |
wide_stresses = [c for c in mat.columns if c not in ["gene","Gene","GENE"]]
|
| 172 |
gcol = "gene" if "gene" in mat.columns else ("Gene" if "Gene" in mat.columns else "GENE")
|
|
|
|
| 176 |
long_rows.append({"gene": g, "stress": s, "external_consensus_sign": getattr(r, s)})
|
| 177 |
ext_long = pd.DataFrame(long_rows)
|
| 178 |
else:
|
|
|
|
| 179 |
ext_long = concord[["gene","stress",sign_col]].rename(columns={sign_col:"external_consensus_sign"})
|
| 180 |
|
|
|
|
| 181 |
ext_long["external_consensus_sign"] = pd.to_numeric(ext_long["external_consensus_sign"], errors="coerce").fillna(0.0)
|
| 182 |
ext_plot = ext_long[np.abs(ext_long["external_consensus_sign"]) > 0].copy()
|
| 183 |
|
| 184 |
if ext_plot.empty:
|
| 185 |
+
print(" No non-zero benchmark entries to plot. Check your CSV contents.")
|
| 186 |
else:
|
| 187 |
pv = ext_plot.pivot(index="gene", columns="stress", values="external_consensus_sign")
|
| 188 |
plt.figure(figsize=(6, max(3, 0.4*pv.shape[0])))
|
|
|
|
| 192 |
plt.tight_layout()
|
| 193 |
out = RES/"validation_external_subset_heatmap.png"
|
| 194 |
plt.savefig(out, dpi=300); plt.show()
|
| 195 |
+
print(" Saved:", out)
|