File size: 8,337 Bytes
9f9fb84 6143883 9f9fb84 6143883 9f9fb84 6143883 9f9fb84 6143883 9f9fb84 6143883 9f9fb84 6143883 9f9fb84 6143883 9f9fb84 6143883 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 | 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 for quick viewing later
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}
# try to infer fields
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) |