lorapop / code /src /analysis /scan_extras.py
bryan7264's picture
Add files using upload-large-folder tool
aaba844 verified
Raw History Blame Contribute Delete
10.6 kB
# MIT License, Bryan Cheng, 2026.
"""Scan diagnostics and module-level tests (RESEARCH_PLAN 7.4, 7.5).
lambda_GC with a family-block bootstrap (1,000 resamples of descent families; naive OLS re-run, MM-fd as fixed-V GLS
with variance components from the full-sample REML), linkage-score regression (chi^2 on the per-locus linkage score
l_j = sum_k r_jk^2 over loci; intercept ~ confounding), module kernel score tests (variance component of the module's
expressed kernel over the null mixed model with the left-out-block function kernel and the descent kernel;
Satterthwaite approximation), and SuSiE (L = 10) in significant modules plus same-layer neighbours on the
relatedness-whitened residual.
python src/analysis/scan_extras.py --geno data/processed/qwen05 --pheno results/phenotypes/qwen05
--scan results/scans/qwen05 --out results/scans/qwen05/extras.json [--claim] [--shard i --nshards n]
Per-trait results go to <out>.parts/<trait>.json as they finish (resumable; with --claim any number of processes share the
traits through lock files, D-036); <out> is written once every primary trait has a part. The bootstrap RNG is seeded per
trait by (seed, trait index).
"""
import argparse
import json
import os
import signal
import sys
import numpy as np
from scipy import optimize, stats
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", ".."))
from src.analysis.population import build # noqa: E402
from src.analysis.scan import basis, bh, gls_scan, lambda_gc, ols_scan, reml # noqa: E402
from src.run.intervene import HELD, claim, unlock # noqa: E402
from src.run.scan_run import blocks_of, cosine # noqa: E402
def susie(X, y, L=10, iters=200, tol=1e-5):
"""Sum of single effects regression (IBSS; Wang et al. 2020), uniform prior over columns, prior variances by ML."""
n, p = X.shape
X = X - X.mean(0)
y = y - y.mean()
d = np.maximum((X ** 2).sum(0), 1e-12)
s2 = float(np.var(y))
alpha, mu, mu2 = np.zeros((L, p)), np.zeros((L, p)), np.zeros((L, p))
V = np.full(L, 0.2 * s2)
Xr = np.zeros(n)
prev = None
for _ in range(iters):
for l in range(L):
Xr_l = Xr - X @ (alpha[l] * mu[l])
r = y - Xr_l
xtr = X.T @ r
b, s2b = xtr / d, s2 / d
def neg(lv):
v = np.exp(lv)
lbf = 0.5 * np.log(s2b / (v + s2b)) + 0.5 * b ** 2 / s2b * v / (v + s2b)
m = lbf.max()
return -(m + np.log(np.mean(np.exp(lbf - m))))
res = optimize.minimize_scalar(neg, bounds=(np.log(1e-12 * s2 + 1e-300), np.log(10 * s2 + 1e-300)), method="bounded")
V[l] = np.exp(res.x) if -res.fun > 0 else 0.0
if V[l] > 0:
lbf = 0.5 * np.log(s2b / (V[l] + s2b)) + 0.5 * b ** 2 / s2b * V[l] / (V[l] + s2b)
w = np.exp(lbf - lbf.max())
alpha[l] = w / w.sum()
pv = 1 / (1 / V[l] + d / s2)
mu[l] = pv * xtr / s2
mu2[l] = pv + mu[l] ** 2
else:
alpha[l], mu[l], mu2[l] = 1.0 / p, 0.0, 0.0
Xr = Xr_l + X @ (alpha[l] * mu[l])
erss = ((y - Xr) ** 2).sum() - sum(((X @ (alpha[l] * mu[l])) ** 2).sum() for l in range(L)) + (d * (alpha * mu2).sum(0)).sum()
s2 = max(float(erss / n), 1e-12)
if prev is not None and np.abs(alpha - prev).max() < tol:
break
prev = alpha.copy()
act = V > 0 # effects with zero prior variance are null and excluded from PIPs (as in susieR)
pip = 1 - np.prod(1 - alpha[act], 0) if act.any() else np.zeros(p)
R = np.corrcoef(X, rowvar=False)
cs = []
for l in range(L):
if V[l] == 0:
continue
o = np.argsort(-alpha[l])
k = int(np.searchsorted(np.cumsum(alpha[l][o]), 0.95) + 1)
s = o[:k]
pur = float(np.min(np.abs(R[np.ix_(s, s)]))) if k > 1 else 1.0
if pur >= 0.5:
cs.append({"members": s.tolist(), "coverage": float(alpha[l][s].sum()), "purity": pur, "prior_var": float(V[l])})
return pip, cs
def score_test(y, X, V, Km):
Vi = np.linalg.inv(V)
Xb = basis(X)
VX = Vi @ Xb
Pm = Vi - VX @ np.linalg.solve(Xb.T @ VX, VX.T)
r = Pm @ y
Q = 0.5 * r @ Km @ r
PK = Pm @ Km
e = 0.5 * np.trace(PK)
v = 0.5 * np.sum(PK * PK.T)
k, nu = v / (2 * e), 2 * e ** 2 / v
return float(Q), float(stats.chi2.sf(Q / k, nu))
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--geno", required=True)
ap.add_argument("--pheno", required=True)
ap.add_argument("--scan", required=True)
ap.add_argument("--out", required=True)
ap.add_argument("--recipe_threshold", type=float, default=None)
ap.add_argument("--n_boot", type=int, default=1000)
ap.add_argument("--seed", type=int, default=0)
ap.add_argument("--claim", action="store_true")
ap.add_argument("--stale", type=float, default=14400)
ap.add_argument("--shard", type=int, default=0)
ap.add_argument("--nshards", type=int, default=1)
a = ap.parse_args()
signal.signal(signal.SIGTERM, lambda *_: sys.exit(143)) # runs the finally: lock release (D-036)
pd = a.out + ".parts"
os.makedirs(pd, exist_ok=True)
P = build(a.geno, a.pheno, recipe_threshold=a.recipe_threshold)
prim = json.load(open(os.path.join(a.scan, "primary_traits.json")))["primary"]
n = len(P["names"])
A = json.load(open(os.path.join(a.geno, "adapters.json")))
keep = np.array([x in set(P["names"]) for x in A["names"]])
mods = json.load(open(os.path.join(a.geno, "modules.json")))
ge = np.load(os.path.join(a.geno, "grams_exp.npy"), mmap_mode="r")
Sb = np.zeros((8, n, n))
for mi, k in enumerate(mods):
Sb[blocks_of(k)] += np.asarray(ge[mi])[np.ix_(keep, keep)]
S = Sb.sum(0)
Kf_blocks = [cosine(S - Sb[b]) for b in range(8)]
Kd, X, G = P["K_desc"], P["X"], P["G"]
blk = np.array([blocks_of(l["module"]) for l in P["loci"]])
Rg = np.corrcoef(G, rowvar=False)
lscore = np.nansum(Rg ** 2, 0)
fams = {}
for i, f in enumerate(P["fam_d"]):
fams.setdefault(int(f), []).append(i)
fl = list(fams)
for ti, t in enumerate(prim):
pf = os.path.join(pd, t + ".json")
if ti % a.nshards != a.shard or os.path.exists(pf):
continue
if a.claim:
if not claim(pf + ".lock", a.stale):
continue
HELD[:] = [pf + ".lock"]
if os.path.exists(pf):
unlock(HELD)
continue
rng = np.random.default_rng([a.seed, ti])
y = P["Yt"][:, P["traits"].index(t)]
ok = np.where(np.isfinite(y))[0]
rec = {}
# linkage-score regression on naive chi^2
b, se, p = ols_scan(y[ok], G[ok], X[ok])
chi = (b / se) ** 2
m = np.isfinite(chi)
sl, ic, rr, pp, _ = stats.linregress(lscore[m], chi[m])
rec["linkage_score_regression_naive"] = {"slope": sl, "intercept": ic, "r": rr}
# REML per block once (MM-fd null)
vcs, Vs = {}, {}
for bk in sorted(set(blk)):
Kf = P["K_func"] if bk == -1 else Kf_blocks[bk]
Ks = [Kf[np.ix_(ok, ok)] + 1e-6 * np.eye(len(ok)), Kd[np.ix_(ok, ok)] + 1e-6 * np.eye(len(ok))]
vcs[bk], Vs[bk], _ = reml(y[ok], X[ok], Ks)
# family-block bootstrap of lambda_GC
lam = {"naive": [], "mm_fd": []}
okset = set(ok.tolist())
for _ in range(a.n_boot):
rows = np.array([i for f in rng.choice(len(fl), len(fl)) for i in fams[fl[f]] if i in okset])
lam["naive"].append(lambda_gc(ols_scan(y[rows], G[rows], X[rows])[2]))
pv = np.full(G.shape[1], np.nan)
for bk, vc in vcs.items():
cols = np.where(blk == bk)[0]
Kf = P["K_func"] if bk == -1 else Kf_blocks[bk]
V = vc[0] * Kf[np.ix_(rows, rows)] + vc[1] * Kd[np.ix_(rows, rows)] + (vc[2] + 1e-6 * vc[:2].sum()) * np.eye(len(rows))
pv[cols] = gls_scan(y[rows], G[np.ix_(rows, cols)], X[rows], V)[2]
lam["mm_fd"].append(lambda_gc(pv))
rec["lambda_gc_boot_ci95"] = {k: np.percentile(v, [2.5, 97.5]).tolist() for k, v in lam.items()}
# module kernel score tests
mt = {}
for mi, k in enumerate(mods):
bk = blocks_of(k)
Km = cosine(np.asarray(ge[mi])[np.ix_(keep, keep)] + 1e-12 * np.eye(n))[np.ix_(ok, ok)]
mt[k] = score_test(y[ok], X[ok], Vs[bk], Km)
pm = np.array([v[1] for v in mt.values()])
sig = [k for k, s in zip(mt, bh(pm)) if s]
rec["module_tests"] = {"n_modules": len(mt), "n_sig_fdr": len(sig), "sig": sig,
"p": {k: v[1] for k, v in mt.items()}}
# SuSiE in significant modules and same-layer neighbours, on the whitened residual (MM-fd, full-kernel null)
fm = []
for k in sig:
layer = k.split(".")[0]
cols = [j for j, l in enumerate(P["loci"]) if l["module"].split(".")[0] == layer]
bk = blocks_of(k)
Lc = np.linalg.cholesky(Vs[bk])
Xw = np.linalg.solve(Lc, basis(X[ok]))
yw = np.linalg.solve(Lc, y[ok])
Gw = np.linalg.solve(Lc, G[np.ix_(ok, cols)])
res_y = yw - Xw @ np.linalg.lstsq(Xw, yw, rcond=None)[0]
res_G = Gw - Xw @ np.linalg.lstsq(Xw, Gw, rcond=None)[0]
pip, cs = susie(res_G, res_y)
fm.append({"module": k, "loci": cols, "top_pip": float(pip.max()),
"credible_sets": [{**c, "members": [cols[j] for j in c["members"]]} for c in cs]})
rec["susie"] = fm
json.dump(rec, open(pf + ".tmp", "w"), indent=1, default=float)
os.replace(pf + ".tmp", pf)
unlock(HELD)
print(t, "lsr intercept", round(ic, 2), "sig modules", len(sig), "lambda CI", rec["lambda_gc_boot_ci95"], flush=True)
if all(os.path.exists(os.path.join(pd, t + ".json")) for t in prim):
out = {"traits": {t: json.load(open(os.path.join(pd, t + ".json"))) for t in prim}, "seed": a.seed,
"n_boot": a.n_boot, "rng": "per trait: default_rng([seed, trait index])"}
json.dump(out, open(a.out, "w"), indent=1, default=float)
print("EXTRASDONE", flush=True)
else:
print("EXTRAS_PARTIAL", sum(os.path.exists(os.path.join(pd, t + ".json")) for t in prim), "/", len(prim), flush=True)
if __name__ == "__main__":
try:
main()
finally:
unlock(HELD)