BULMA / code /19_abc_dependence.py
HarriziSaad's picture
Upload 104 files
638ea38 verified
Raw History Blame Contribute Delete
9.54 kB
import itertools
import numpy as np
import pandas as pd
from scipy import stats
from common import RES, EXT, SEED, read_matrix, abc
N_PERM = 100_000
N_SETS = 10_000
N_BOOT = 5000
MIN_SHARED = 50
FILES = ("SGA_NxN.txt", "SGA_ExN.txt", "SGA_ExE.txt", "SGA_DAmP.txt")
rng = np.random.default_rng(SEED)
A = abc().set_index("gene")
I = pd.read_csv(RES / "abc_identity.csv", index_col=0)
RBH = {frozenset(p) for p in pd.read_csv(RES / "abc_paralog_pairs.csv")[["gene1", "gene2"]].itertuples(index=False)}
SAME = {frozenset((a, b)) for a, b in itertools.combinations(A.index, 2) if A.subfamily[a] == A.subfamily[b]}
Z = read_matrix("hom.z_result_nm.pub")
genes = [g for g in A.index if A.systematic[g] in Z.index and Z.loc[A.systematic[g]].notna().sum() >= MIN_SHARED]
X = Z.loc[[A.systematic[g] for g in genes]]
n = len(genes)
R = np.full((n, n), np.nan)
for i, j in itertools.combinations(range(n), 2):
m = X.iloc[i].notna() & X.iloc[j].notna()
R[i, j] = R[j, i] = stats.pearsonr(X.iloc[i][m], X.iloc[j][m]).statistic
Fz = np.arctanh(R)
Id = I.loc[genes, genes].values
S = pd.read_csv(RES / "abc_struct_sim.csv")
Tm = pd.DataFrame(np.nan, index=genes, columns=genes)
for g1, g2, tm in S[["gene1", "gene2", "tmscore"]].itertuples(index=False):
if g1 in genes and g2 in genes:
Tm.loc[g1, g2] = Tm.loc[g2, g1] = tm
Tm = Tm.values
iu = np.triu_indices(n, 1)
par = np.array([frozenset((genes[i], genes[j])) in RBH for i, j in zip(*iu)])
same = np.array([frozenset((genes[i], genes[j])) in SAME for i, j in zip(*iu)])
def mantel_stat(F):
return stats.spearmanr(Id[iu], F[iu]).statistic
def diff_stat(F, mask):
f = F[iu]
return f[mask].mean() - f[~mask].mean()
def tm_stat(F):
return stats.spearmanr(Tm[iu], F[iu]).statistic
obs = {"mantel_rho": mantel_stat(Fz), "paralog_minus_other_z": diff_stat(Fz, par), "same_minus_diff_subfamily_z": diff_stat(Fz, same),
"mantel_rho_tmscore": tm_stat(Fz)}
null = {k: np.empty(N_PERM) for k in obs}
for b in range(N_PERM):
p = rng.permutation(n)
Fp = Fz[np.ix_(p, p)]
null["mantel_rho"][b] = mantel_stat(Fp)
null["paralog_minus_other_z"][b] = diff_stat(Fp, par)
null["same_minus_diff_subfamily_z"][b] = diff_stat(Fp, same)
null["mantel_rho_tmscore"][b] = tm_stat(Fp)
pvals = {"mantel_rho": (np.sum(np.abs(null["mantel_rho"]) >= abs(obs["mantel_rho"])) + 1) / (N_PERM + 1),
"paralog_minus_other_z": (np.sum(null["paralog_minus_other_z"] >= obs["paralog_minus_other_z"]) + 1) / (N_PERM + 1),
"same_minus_diff_subfamily_z": (np.sum(null["same_minus_diff_subfamily_z"] >= obs["same_minus_diff_subfamily_z"]) + 1) / (N_PERM + 1),
"mantel_rho_tmscore": (np.sum(np.abs(null["mantel_rho_tmscore"]) >= abs(obs["mantel_rho_tmscore"])) + 1) / (N_PERM + 1)}
boot = {k: [] for k in obs}
for _ in range(N_BOOT):
s = rng.integers(0, n, n)
ii, jj = np.triu_indices(n, 1)
keep = s[ii] != s[jj]
a, c = s[ii][keep], s[jj][keep]
f, idv = Fz[a, c], Id[a, c]
pr = np.array([frozenset((genes[x], genes[y])) in RBH for x, y in zip(a, c)])
sm = np.array([frozenset((genes[x], genes[y])) in SAME for x, y in zip(a, c)])
boot["mantel_rho"].append(stats.spearmanr(idv, f).statistic)
boot["mantel_rho_tmscore"].append(stats.spearmanr(Tm[a, c], f).statistic)
if pr.any():
boot["paralog_minus_other_z"].append(f[pr].mean() - f[~pr].mean())
boot["same_minus_diff_subfamily_z"].append(f[sm].mean() - f[~sm].mean())
prof = pd.DataFrame([(k, obs[k], *np.percentile(boot[k], [2.5, 97.5]), pvals[k], n, int(par.sum()), int(same.sum()))
for k in obs], columns=["statistic", "value", "ci_low", "ci_high", "p_gene_label_permutation",
"transporters", "paralog_pairs", "same_subfamily_pairs"])
prof.to_csv(RES / "abc_profile_dependence.csv", index=False)
pd.DataFrame({k: v[:10000] for k, v in null.items()}).round(5).to_csv(RES / "abc_profile_null.csv", index=False)
D = EXT / "costanzo2016"
cache = D / "eps_dense.npz"
if not cache.exists():
names, ess = {}, set()
parts = []
for f in FILES:
for ch in pd.read_csv(D / f, sep="\t", usecols=[0, 2, 5], chunksize=2_000_000):
ch.columns = ["q", "a", "eps"]
for col in ("q", "a"):
tag = ch[col].str.split("_").str[1].fillna("")
ess.update(ch[col][tag.str.contains("tsq|tsa|damp", case=False)].str.split("_").str[0].unique())
q, a = ch.q.str.split("_").str[0], ch.a.str.split("_").str[0]
keep = q != a
parts.append((q[keep].values, a[keep].values, ch.eps[keep].values.astype(np.float64)))
allg = sorted(set(np.concatenate([p[0] for p in parts])) | set(np.concatenate([p[1] for p in parts])))
ix = {g: i for i, g in enumerate(allg)}
G = len(allg)
S = np.zeros((G, G))
C = np.zeros((G, G), dtype=np.int32)
for q, a, e in parts:
qi = np.fromiter((ix[x] for x in q), int, len(q))
ai = np.fromiter((ix[x] for x in a), int, len(a))
ok = ~np.isnan(e)
np.add.at(S, (qi[ok], ai[ok]), e[ok])
np.add.at(C, (qi[ok], ai[ok]), 1)
S, C = S + S.T, C + C.T
with np.errstate(invalid="ignore"):
M = (S / C).astype(np.float32)
np.savez_compressed(cache, M=M, genes=np.array(allg), essential=np.array(sorted(ess)))
dat = np.load(cache, allow_pickle=True)
M, allg, ess = dat["M"], list(dat["genes"]), set(dat["essential"])
ix = {g: i for i, g in enumerate(allg)}
meas = ~np.isnan(M)
coverage = meas.sum(axis=1)
degree = np.nansum(M < -0.08, axis=1)
essential = np.array([g in ess for g in allg])
abc_sys = [A.systematic[g] for g in A.index if A.systematic[g] in ix]
abc_name = {A.systematic[g]: g for g in A.index}
abc_i = np.array([ix[s] for s in abc_sys])
def within_mean(idx):
sub = M[np.ix_(idx, idx)]
iu2 = np.triu_indices(len(idx), 1)
v = sub[iu2]
return np.nanmean(v), int(np.sum(~np.isnan(v)))
RBH_PAIRS = sorted(tuple(sorted(p)) for p in RBH)
par_pairs = [(abc_sys.index(A.systematic[a]), abc_sys.index(A.systematic[b])) for a, b in RBH_PAIRS
if A.systematic[a] in ix and A.systematic[b] in ix]
def pair_mean(idx):
v = [M[idx[i], idx[j]] for i, j in par_pairs]
v = [x for x in v if not np.isnan(x)]
return np.mean(v) if v else np.nan, len(v)
obs_all, n_all = within_mean(abc_i)
obs_par, n_par = pair_mean(abc_i)
lc = np.log10(coverage + 1)
bins_c = np.digitize(lc, np.quantile(lc[coverage > 0], np.linspace(0, 1, 11)[1:-1]))
bins_d = np.digitize(degree, np.quantile(degree[coverage > 0], np.linspace(0, 1, 6)[1:-1]))
pool_mask = (coverage > 0) & ~np.isin(np.arange(len(allg)), abc_i)
candidates = {}
for g in abc_i:
m = pool_mask & (essential == essential[g]) & (bins_c == bins_c[g]) & (bins_d == bins_d[g])
if m.sum() < 20:
m = pool_mask & (essential == essential[g]) & (np.abs(bins_c - bins_c[g]) <= 1) & (np.abs(bins_d - bins_d[g]) <= 1)
candidates[g] = np.where(m)[0]
null_all, null_par, null_unm = [], [], []
pool_idx = np.where(pool_mask)[0]
for _ in range(N_SETS):
idx = np.array([rng.choice(candidates[g]) for g in abc_i])
if len(set(idx)) < len(idx):
continue
null_all.append(within_mean(idx)[0])
null_par.append(pair_mean(idx)[0])
null_unm.append(within_mean(rng.choice(pool_idx, len(abc_i), replace=False))[0])
null_all, null_par, null_unm = map(np.array, (null_all, null_par, null_unm))
gi = pd.DataFrame([
("ABC-ABC pairs, degree/coverage/essentiality-matched random gene sets", obs_all, n_all, np.nanmean(null_all),
*np.nanpercentile(null_all, [2.5, 97.5]), (np.sum(null_all <= obs_all) + 1) / (len(null_all) + 1)),
("ABC-ABC pairs, unmatched random gene sets", obs_all, n_all, np.nanmean(null_unm),
*np.nanpercentile(null_unm, [2.5, 97.5]), (np.sum(null_unm <= obs_all) + 1) / (len(null_unm) + 1)),
("reciprocal-best paralog pairs, matched random gene sets", obs_par, n_par, np.nanmean(null_par),
*np.nanpercentile(null_par, [2.5, 97.5]), (np.sum(null_par <= obs_par) + 1) / (np.sum(~np.isnan(null_par)) + 1))],
columns=["test", "observed_mean_eps", "pairs_measured", "null_mean", "null_2.5", "null_97.5", "p_one_sided_negative"])
gi.to_csv(RES / "abc_gi_matched_sets.csv", index=False)
pd.DataFrame({"matched_all_pairs": null_all, "unmatched_all_pairs": null_unm[:len(null_all)],
"matched_paralog_pairs": null_par}).round(6).to_csv(RES / "abc_gi_null.csv", index=False)
pe = []
for a, b in RBH_PAIRS:
sa, sb = A.systematic[a], A.systematic[b]
pe.append((a, b, M[ix[sa], ix[sb]] if sa in ix and sb in ix else np.nan))
for a, b in (("PDR5", "SNQ2"), ("PDR5", "YOR1"), ("SNQ2", "YOR1")):
pe.append((a, b, M[ix[A.systematic[a]], ix[A.systematic[b]]]))
pd.DataFrame(pe, columns=["gene1", "gene2", "eps"]).assign(
relation=["paralogue"] * len(RBH) + ["co-regulated multidrug pump"] * 3).to_csv(RES / "abc_pair_eps.csv", index=False)
props = pd.DataFrame({"gene": [abc_name[s] for s in abc_sys], "coverage": coverage[abc_i], "negative_degree": degree[abc_i],
"essential": essential[abc_i], "genome_median_coverage": np.median(coverage[pool_mask]),
"genome_median_degree": np.median(degree[pool_mask])})
props.to_csv(RES / "abc_gi_properties.csv", index=False)
pd.set_option("display.width", 220)