| from pathlib import Path |
| Path("data/external").mkdir(parents=True, exist_ok=True) |
| open("data/external/hiphop_benchmark.csv","w").write("""gene,condition,direction,fitness,source |
| PDR5,ethanol,resistant,0.35,HIP-HOP_demo |
| SNQ2,ethanol,sensitive,-0.25,HIP-HOP_demo |
| YOR1,ethanol,resistant,0.12,HIP-HOP_demo |
| ATM1,ethanol,resistant,0.05,HIP-HOP_demo |
| PDR5,hydrogen peroxide,sensitive,-0.10,HIP-HOP_demo |
| SNQ2,hydrogen peroxide,sensitive,-0.30,HIP-HOP_demo |
| YOR1,hydrogen peroxide,resistant,0.20,HIP-HOP_demo |
| ATM1,hydrogen peroxide,resistant,0.50,HIP-HOP_demo |
| PDR5,NaCl,sensitive,-0.08,HIP-HOP_demo |
| SNQ2,NaCl,sensitive,-0.12,HIP-HOP_demo |
| YOR1,NaCl,resistant,0.06,HIP-HOP_demo |
| ATM1,NaCl,resistant,0.10,HIP-HOP_demo |
| """) |
|
|
|
|
|
|
| import os, re, json, glob, numpy as np, pandas as pd, matplotlib.pyplot as plt, seaborn as sns |
| from pathlib import Path |
|
|
| RES = Path("results"); RES.mkdir(exist_ok=True, parents=True) |
| EXT = Path("data/external") |
|
|
| def _read_any(path): |
| if path.endswith(".tsv") or path.endswith(".tab"): |
| return pd.read_csv(path, sep="\t", dtype=str, low_memory=False) |
| return pd.read_csv(path, dtype=str, low_memory=False) |
|
|
| def _coerce_float(s): |
| try: return float(s) |
| except: return np.nan |
|
|
| def _norm_gene(x): |
| x = (str(x) or "").strip() |
| x = re.sub(r"_expr$", "", x) |
| x = x.upper() |
| x = re.sub(r"^Y[A-P][LR][0-9]{3}[CW](-[A-Z])?$", x, x) |
| return x |
|
|
| def _stress_from_text(t): |
| t = str(t).lower() |
| if any(k in t for k in ["h2o2","hydrogen peroxide","oxidative","menadione","paraquat"]): return "oxidative" |
| if any(k in t for k in ["ethanol","etoh","alcohol"]): return "ethanol" |
| if any(k in t for k in ["nacl","kcl","osmotic","sorbitol","salt"]): return "osmotic" |
| return None |
|
|
| def _sign_from_effect(val, dir_text=None): |
| """Return +1 for resistance/increased growth, -1 for sensitivity/decreased growth.""" |
| if dir_text: |
| d = str(dir_text).lower() |
| if any(k in d for k in ["resist", "increased tolerance", "gain"]): return +1 |
| if any(k in d for k in ["sensit", "hypersens", "loss"]): return -1 |
| try: |
| v = float(val) |
| if np.isnan(v): return 0 |
| return +1 if v > 0 else (-1 if v < 0 else 0) |
| except: |
| return 0 |
|
|
| snap = json.load(open(RES/"causal_section3_snapshot.json")) |
| ATE_table = snap.get("ATE_table") or snap.get("stress_ate") or {} |
| flat = [] |
| for k,v in ATE_table.items(): |
| g = _norm_gene(k) |
| if isinstance(v, dict): |
| for s,val in v.items(): |
| ss = _stress_from_text(s) or str(s).lower() |
| try: flat.append((g, ss, float(val))) |
| except: pass |
| df_ate = pd.DataFrame(flat, columns=["gene","stress","ATE"]).dropna() |
| if df_ate.empty: |
| raise SystemExit("Could not parse ATE_table from Section 3 snapshot.") |
| |
| anchors = ["PDR5","SNQ2","YOR1","ATM1"] |
|
|
| files = [] |
| for pat in ["**/*hip*hop*.csv","**/*hip*hop*.tsv", |
| "**/*moa*map*.csv","**/*moa*map*.tsv", |
| "**/*sgd*.csv","**/*sgd*.tsv", |
| "**/*phenotype*.csv","**/*phenotype*.tsv"]: |
| files += glob.glob(str(EXT/pat), recursive=True) |
|
|
| ext_rows = [] |
| for f in sorted(set(files)): |
| try: |
| D = _read_any(f) |
| except Exception as e: |
| print("skip (read):", f, e); continue |
|
|
| cols = {c.lower(): c for c in D.columns} |
| |
| gene_col = next((cols[c] for c in cols if c in ["gene","symbol","orf","locus","locus_tag","systematic"]), None) |
| cond_col = next((cols[c] for c in cols if c in ["condition","compound","perturbation","stress","treatment","media"]), None) |
| eff_col = next((cols[c] for c in cols if c in ["effect","fitness","logfc","score","correlation","corr","beta","coef"]), None) |
| dir_col = next((cols[c] for c in cols if c in ["direction","phenotype","call","sign","label","type"]), None) |
|
|
| if gene_col is None or cond_col is None or (eff_col is None and dir_col is None): |
| print("skip (schema):", f); continue |
|
|
| for r in D.itertuples(index=False): |
| gene = _norm_gene(getattr(r, gene_col)) |
| stress = _stress_from_text(getattr(r, cond_col)) |
| if not gene or not stress: |
| continue |
| val = getattr(r, eff_col) if eff_col else "" |
| direction = getattr(r, dir_col) if dir_col else "" |
| sign = _sign_from_effect(val, direction) |
| if sign == 0: |
| continue |
| ext_rows.append({"gene": gene, "stress": stress, "sign": sign, "source": Path(f).name}) |
|
|
| ext = pd.DataFrame(ext_rows) |
| if ext.empty: |
| print(" No usable external rows found under", EXT.resolve()) |
| else: |
| print(f"Loaded external evidence rows: {len(ext)} from {ext['source'].nunique()} files") |
|
|
| if ext.empty: |
| pd.DataFrame(columns=["gene","stress","evidence_n","evidence_balance"]).to_csv(RES/"validation_external_matrix.csv", index=False) |
| pd.DataFrame(columns=["gene","stress","ATE","ext_consensus","concordant"]).to_csv(RES/"validation_external_concordance.csv", index=False) |
| else: |
| agg = (ext |
| .groupby(["gene","stress"])["sign"] |
| .agg(evidence_n="count", evidence_balance="sum") |
| .reset_index()) |
| agg.to_csv(RES/"validation_external_matrix.csv", index=False) |
|
|
| M = df_ate.merge(agg, on=["gene","stress"], how="left") |
| M["ext_consensus"] = np.sign(M["evidence_balance"].fillna(0)) |
| M["ate_sign"] = np.sign(M["ATE"]) |
| M["concordant"] = (M["ext_consensus"] != 0) & (M["ate_sign"] == M["ext_consensus"]) |
| M.to_csv(RES/"validation_external_concordance.csv", index=False) |
|
|
| 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] |
| pt = M.pivot_table(index="gene", columns="stress", values="ext_consensus", aggfunc="first").reindex(order_genes) |
| plt.figure(figsize=(7, max(3, 0.35*len(pt)))) |
| sns.heatmap(pt, cmap="coolwarm", center=0, cbar_kws={"label":"external consensus sign"}) |
| plt.title("External benchmark — consensus sign (HIP-HOP/MoAmap/SGD)") |
| plt.tight_layout(); plt.savefig(RES/"validation_external_heatmap.png", dpi=300); plt.show() |
|
|
| summ = (M[M["gene"].isin(anchors)] |
| .groupby("gene")[["concordant"]] |
| .mean().rename(columns={"concordant":"concordance_rate"})) |
| print("\nAnchor concordance (fraction of stresses where signs agree):") |
| display(summ) |
|
|
| print("Saved:", |
| RES/"validation_external_matrix.csv", |
| RES/"validation_external_concordance.csv", |
| RES/"validation_external_heatmap.png") |
|
|
| import numpy as np, pandas as pd, seaborn as sns, matplotlib.pyplot as plt, pathlib as p |
|
|
| RES = p.Path("results") |
| concord = pd.read_csv(RES/"validation_external_concordance.csv") |
|
|
| sign_col = None |
| for c in concord.columns: |
| if "sign" in c.lower() and c.lower() != "atlas_sign": |
| sign_col = c |
| break |
|
|
| if sign_col is None: |
| mat = pd.read_csv(RES/"validation_external_matrix.csv") |
| if {"gene","stress","value"}.issubset(mat.columns): |
| ext_long = mat.rename(columns={"value":"external_consensus_sign"}) |
| else: |
| long_rows=[] |
| wide_stresses = [c for c in mat.columns if c not in ["gene","Gene","GENE"]] |
| gcol = "gene" if "gene" in mat.columns else ("Gene" if "Gene" in mat.columns else "GENE") |
| for r in mat.itertuples(index=False): |
| g = getattr(r, gcol) |
| for s in wide_stresses: |
| long_rows.append({"gene": g, "stress": s, "external_consensus_sign": getattr(r, s)}) |
| ext_long = pd.DataFrame(long_rows) |
| else: |
| ext_long = concord[["gene","stress",sign_col]].rename(columns={sign_col:"external_consensus_sign"}) |
|
|
| ext_long["external_consensus_sign"] = pd.to_numeric(ext_long["external_consensus_sign"], errors="coerce").fillna(0.0) |
| ext_plot = ext_long[np.abs(ext_long["external_consensus_sign"]) > 0].copy() |
|
|
| if ext_plot.empty: |
| print(" No non-zero benchmark entries to plot. Check your CSV contents.") |
| else: |
| pv = ext_plot.pivot(index="gene", columns="stress", values="external_consensus_sign") |
| plt.figure(figsize=(6, max(3, 0.4*pv.shape[0]))) |
| sns.heatmap(pv, annot=True, cmap="coolwarm", center=0, |
| cbar_kws={"label":"external consensus sign"}) |
| plt.title("External benchmark (HIP-HOP / MoAmap / SGD subset)") |
| plt.tight_layout() |
| out = RES/"validation_external_subset_heatmap.png" |
| plt.savefig(out, dpi=300); plt.show() |
| print(" Saved:", out) |