BULMA / code /11_benchmark.py
HarriziSaad's picture
Upload 105 files
fe11dd9 verified
Raw History Blame Contribute Delete
10.5 kB
import numpy as np
import pandas as pd
import statsmodels.api as sm
from scipy import stats
from scipy.optimize import linear_sum_assignment
from sklearn.metrics import roc_auc_score, roc_curve
from common import RES, SEED, hom, axes, centre, effects, sgd_labels, phenotypes
CALIPERS = (0.05, 0.1, 0.25, 0.5)
PRIMARY_CALIPER = 0.25
N_BOOT = 2000
N_ORDERS = 200
STRATA = {"all annotations": None, "small-scale studies only": ["classical genetics"]}
Z = hom()
ag, ox, os_, _ = axes(Z.columns)
b = Z.median(axis=1)
E = dict(zip(("oxidative", "osmotic"), effects(centre(Z), ox, os_)))
N = {"oxidative": Z.loc[:, ox].mean(axis=1), "osmotic": Z.loc[:, os_].mean(axis=1)}
rng = np.random.default_rng(SEED)
src = phenotypes()
for stress in ("oxidative", "osmotic"):
terms = ("oxidative stress resistance",) if stress == "oxidative" else ("hyperosmotic stress resistance", "osmotic stress resistance")
s = src[(src.mutant == "null") & src.phenotype.str.rsplit(": ", n=1).str[0].isin(terms)]
s.groupby(["pmid", "exptype"]).size().rename("annotations").sort_values(ascending=False).to_csv(
RES / f"benchmark_sources_{stress}.csv")
def auc_ci(y, x, paired_idx=None):
y, x = np.asarray(y), np.asarray(x)
a = roc_auc_score(y, x)
boot = []
for _ in range(N_BOOT):
if paired_idx is None:
i = rng.integers(0, len(y), len(y))
if len(set(y[i])) < 2:
continue
else:
k = rng.integers(0, len(paired_idx), len(paired_idx))
i = paired_idx[k].ravel()
boot.append(roc_auc_score(y[i], x[i]))
lo, hi = np.percentile(boot, [2.5, 97.5])
return a, lo, hi
def smd(x1, x0):
return (x1.mean() - x0.mean()) / np.sqrt((x1.var() + x0.var()) / 2)
summary, terc, val, roc_rows = [], [], [], []
for stratum, ex in STRATA.items():
for stress in ("oxidative", "osmotic"):
lab = sgd_labels(stress, exptypes=ex)
lab = lab[lab.index.isin(Z.index)]
y = (lab == -1).astype(int).values
e = E[stress].loc[lab.index]
conc = (np.sign(e) == -lab).astype(int)
k, n = int(conc.sum()), len(conc)
row = {"stratum": stratum, "stress": stress, "genes": n, "decreased": int(y.sum()), "increased": int((1 - y).sum()),
"concordant": k, "concordance": k / n, "p_binomial": stats.binomtest(k, n, 0.5, alternative="greater").pvalue,
"smd_slow_growth": smd(b.loc[lab.index][y == 1], b.loc[lab.index][y == 0]),
"p_slow_growth_bias": stats.mannwhitneyu(b.loc[lab.index][y == 1], b.loc[lab.index][y == 0], alternative="greater").pvalue}
for name, sc in (("baseline_adjusted", e), ("naive", N[stress].loc[lab.index]), ("slow_growth", b.loc[lab.index])):
a, lo, hi = auc_ci(y, sc.values)
row.update({f"auroc_{name}": a, f"auroc_{name}_lo": lo, f"auroc_{name}_hi": hi})
summary.append(row)
if stratum == "all annotations":
val.append(pd.DataFrame({"stress": stress, "gene": lab.index, "effect": e.values, "sgd_dir": lab.values,
"concordant": conc.values, "slow_growth": b.loc[lab.index].values}))
fpr, tpr, _ = roc_curve(y, e.values)
roc_rows.append(pd.DataFrame({"stress": stress, "fpr": fpr, "tpr": tpr}))
order = np.argsort(-e.abs().values)
for bname, idx in zip(("large", "medium", "small"), np.array_split(order, 3)):
cb = conc.values[idx]
lo, hi = stats.binomtest(int(cb.sum()), len(cb)).proportion_ci()
terc.append((stress, bname, len(idx), cb.mean(), lo, hi, float(np.median(e.abs().values[idx]))))
S = pd.DataFrame(summary)
S.to_csv(RES / "benchmark_summary.csv", index=False)
pd.concat(val).to_csv(RES / "validation.csv", index=False)
pd.concat(roc_rows).round(4).to_csv(RES / "roc.csv", index=False)
T = pd.DataFrame(terc, columns=["stress", "tercile", "genes", "concordance", "ci_low", "ci_high", "median_abs_effect"])
T.to_csv(RES / "benchmark_terciles.csv", index=False)
x = pd.concat(val)
trend = []
for stress in ("oxidative", "osmotic"):
v = x[x.stress == stress]
m = sm.Logit(v.concordant.values, sm.add_constant(np.column_stack([np.abs(v.effect.values), v.slow_growth.values]))).fit(disp=0)
trend.append((stress, m.params[1], m.pvalues[1], m.params[2], m.pvalues[2], len(v)))
pd.DataFrame(trend, columns=["stress", "coef_abs_effect", "p_abs_effect", "coef_slow_growth", "p_slow_growth", "genes"]).to_csv(
RES / "benchmark_concordance_trend.csv", index=False)
def greedy(dec, inc, s, cal, order):
pool = set(inc)
pairs = []
for g in order:
if not pool:
break
p = sorted(pool)
d = np.abs(s.loc[p].values - s[g])
j = int(np.argmin(d))
if d[j] <= cal:
pairs.append((g, p[j]))
pool.remove(p[j])
return pairs
def optimal(dec, inc, s, cal):
C = np.abs(s.loc[dec].values[:, None] - s.loc[inc].values[None, :])
r, c = linear_sum_assignment(C)
return [(dec[i], inc[j]) for i, j in zip(r, c) if C[i, j] <= cal]
def evaluate(pairs, stress, method, cal):
g = [p for pr in pairs for p in pr]
y = np.array([1, 0] * len(pairs))
idx = np.arange(2 * len(pairs)).reshape(-1, 2)
d, i = b.loc[[p[0] for p in pairs]], b.loc[[p[1] for p in pairs]]
out = {"stress": stress, "method": method, "caliper_sd": cal, "pairs": len(pairs), "smd_after": smd(d, i),
"variance_ratio": d.var() / i.var(), "ks_after": stats.ks_2samp(d, i).statistic}
for name, sc in (("baseline_adjusted", E[stress]), ("naive", N[stress]), ("slow_growth", b)):
a, lo, hi = auc_ci(y, sc.loc[g].values, idx)
out.update({f"auroc_{name}": a, f"auroc_{name}_lo": lo, f"auroc_{name}_hi": hi})
return out
match = []
for stress in ("oxidative", "osmotic"):
lab = sgd_labels(stress)
lab = lab[lab.index.isin(Z.index)]
dec, inc = list(lab.index[lab == -1]), list(lab.index[lab == 1])
sd = b.loc[lab.index].std()
for cal in CALIPERS:
match.append(evaluate(greedy(dec, inc, b, cal * sd, dec), stress, "greedy nearest neighbour", cal))
match.append(evaluate(optimal(dec, inc, b, cal * sd), stress, "optimal 1:1", cal))
orders = []
for _ in range(N_ORDERS):
pr = greedy(dec, inc, b, PRIMARY_CALIPER * sd, list(rng.permutation(dec)))
g = [p for q in pr for p in q]
yy = np.array([1, 0] * len(pr))
orders.append((len(pr), roc_auc_score(yy, E[stress].loc[g]), roc_auc_score(yy, b.loc[g])))
O = np.array(orders)
match.append({"stress": stress, "method": f"greedy, {N_ORDERS} random orders (median; 2.5-97.5%)",
"caliper_sd": PRIMARY_CALIPER, "pairs": float(np.median(O[:, 0])),
"auroc_baseline_adjusted": float(np.median(O[:, 1])), "auroc_baseline_adjusted_lo": float(np.percentile(O[:, 1], 2.5)),
"auroc_baseline_adjusted_hi": float(np.percentile(O[:, 1], 97.5)), "auroc_slow_growth": float(np.median(O[:, 2]))})
q = pd.qcut(b.loc[lab.index], 5, labels=False)
w, aucs = [], []
for k in range(5):
ii = lab.index[q == k]
yy = (lab[ii] == -1).astype(int)
if yy.nunique() == 2:
aucs.append(roc_auc_score(yy, E[stress].loc[ii]))
w.append(len(ii))
match.append({"stress": stress, "method": "stratified (slow-growth quintiles), weighted mean", "caliper_sd": np.nan,
"pairs": np.nan, "auroc_baseline_adjusted": float(np.average(aucs, weights=w))})
y = (lab == -1).astype(int).values
Xr = sm.add_constant(np.column_stack([stats.zscore(E[stress].loc[lab.index].values), stats.zscore(b.loc[lab.index].values)]))
m = sm.Logit(y, Xr).fit(disp=0)
ci = m.conf_int()[1]
match.append({"stress": stress, "method": "logistic regression adjusting for slow growth (odds ratio per SD)",
"caliper_sd": np.nan, "pairs": np.nan, "odds_ratio": float(np.exp(m.params[1])),
"odds_ratio_lo": float(np.exp(ci[0])), "odds_ratio_hi": float(np.exp(ci[1])), "p": float(m.pvalues[1])})
M = pd.DataFrame(match)
M.to_csv(RES / "benchmark_matching.csv", index=False)
rng_d = np.random.default_rng(SEED + 1)
def auc_difference(y, x1, x2, paired_idx=None):
y, x1, x2 = np.asarray(y), np.asarray(x1), np.asarray(x2)
obs = roc_auc_score(y, x1) - roc_auc_score(y, x2)
boot = []
for _ in range(N_BOOT):
if paired_idx is None:
i = rng_d.integers(0, len(y), len(y))
if len(set(y[i])) < 2:
continue
else:
i = paired_idx[rng_d.integers(0, len(paired_idx), len(paired_idx))].ravel()
boot.append(roc_auc_score(y[i], x1[i]) - roc_auc_score(y[i], x2[i]))
boot = np.array(boot)
lo, hi = np.percentile(boot, [2.5, 97.5])
return obs, lo, hi, min(1.0, 2 * min((boot <= 0).mean(), (boot >= 0).mean()))
diff = []
for stress in ("oxidative", "osmotic"):
lab = sgd_labels(stress)
lab = lab[lab.index.isin(Z.index)]
y = (lab == -1).astype(int).values
for name, x2 in (("naive", N[stress]), ("slow_growth", b)):
d, lo, hi, p = auc_difference(y, E[stress].loc[lab.index].values, x2.loc[lab.index].values)
diff.append((stress, "all annotations", f"baseline_adjusted - {name}", len(lab), d, lo, hi, p))
dec, inc = list(lab.index[lab == -1]), list(lab.index[lab == 1])
pairs = greedy(dec, inc, b, PRIMARY_CALIPER * b.loc[lab.index].std(), dec)
g = [q for pr in pairs for q in pr]
yy = np.array([1, 0] * len(pairs))
idx = np.arange(2 * len(pairs)).reshape(-1, 2)
for name, x2 in (("naive", N[stress]), ("slow_growth", b)):
d, lo, hi, p = auc_difference(yy, E[stress].loc[g].values, x2.loc[g].values, idx)
diff.append((stress, f"growth-matched (greedy, caliper {PRIMARY_CALIPER} SD)", f"baseline_adjusted - {name}",
len(pairs), d, lo, hi, p))
pd.DataFrame(diff, columns=["stress", "benchmark", "comparison", "n", "auroc_difference", "ci_low", "ci_high",
"p_two_sided"]).to_csv(RES / "benchmark_auroc_differences.csv", index=False)
pd.set_option("display.width", 250)
pd.set_option("display.max_columns", 30)