lorapop / code /src /run /scan_run.py
bryan7264's picture
Add files using upload-large-folder tool
a8b5668 verified
Raw History Blame Contribute Delete
9.52 kB
# MIT License, Bryan Cheng, 2026.
"""Run all association estimators on a population (RESEARCH_PLAN 7) for full, discovery (D) and estimation (E) sets.
python src/run/scan_run.py --geno data/processed/qwen05 --pheno results/phenotypes/qwen05 --out results/scans/qwen05
Outputs: primary_traits.json (frozen at first run), <trait>.npz (beta/se/p [estimator, subset, locus]), loci.json,
summary.json (lambda_GC, M_eff, hits, negative control, variance components), population.json (families, split).
"""
import argparse
import json
import os
import sys
import numpy as np
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", ".."))
from src.analysis.population import build, neff # noqa: E402
from src.analysis.scan import bh, gls_scan, lambda_gc, m_eff, ols_scan, reml, reml_eig1, within_scan # noqa: E402
EST = ["naive", "pc", "mm_f", "mm_fd", "wf_d", "wf_r", "dup_afe"]
SUBSETS = ["full", "D", "E"]
EIG = {} # (block, n, rows hash) -> eigendecomposition of the leave-block-out function kernel (reused across traits)
def blocks_of(module):
if module.startswith("presence"):
return -1
layer, typ = int(module.split(".")[0]), module.split(".")[1]
return (layer // 6) * 2 + (0 if typ in ("q_proj", "k_proj", "v_proj", "o_proj") else 1)
def cosine(S):
d = np.sqrt(np.clip(np.diag(S), 1e-300, None))
return S / d[:, None] / d[None, :]
def dedup(Kd, thr=0.999):
n = len(Kd)
keep = np.ones(n, bool)
for i in range(n):
if keep[i]:
dup = np.where((Kd[i] > thr) & (np.arange(n) > i))[0]
keep[dup] = False
return keep
def run_estimators(y, G, X, Kf_blocks, Kf_full, Kd, fam_d, fam_r, authors, block_of_locus, pcs, idx, vc_log):
"""All estimators on rows idx. Returns dict est -> (beta, se, p) over loci."""
yy, GG, XX = y[idx], G[idx], X[idx]
ok = np.isfinite(yy)
sub = idx[ok]
yy, GG, XX = y[sub], G[sub], X[sub]
L = G.shape[1]
out = {}
out["naive"] = ols_scan(yy, GG, XX)
out["pc"] = ols_scan(yy, GG, np.column_stack([XX, pcs[sub]]))
for name, use_d in (("mm_f", False), ("mm_fd", True)):
b, s, p = np.full(L, np.nan), np.full(L, np.nan), np.full(L, np.nan)
for blk in sorted(set(block_of_locus)):
cols = np.where(block_of_locus == blk)[0]
Kf = (Kf_full if blk == -1 else Kf_blocks[blk])[np.ix_(sub, sub)]
Ks = [Kf] + ([Kd[np.ix_(sub, sub)]] if use_d else [])
Ks = [K + 1e-6 * np.eye(len(sub)) for K in Ks]
if use_d:
vc, V, _ = reml(yy, XX, Ks)
bb, ss, pp = gls_scan(yy, GG[:, cols], XX, V)
else: # one kernel: exact eigen fast path, decomposition cached across traits (D-026)
ck = (blk, len(sub), hash(sub.tobytes()))
if ck not in EIG:
EIG[ck] = np.linalg.eigh(Ks[0])
vc, W, _ = reml_eig1(yy, XX, *EIG[ck])
bb, ss, pp = gls_scan(yy, GG[:, cols], XX, W=W)
vc_log.setdefault(name, {})[str(blk)] = vc.tolist()
b[cols], s[cols], p[cols] = bb, ss, pp
out[name] = (b, s, p)
for name, grp in (("wf_d", fam_d), ("wf_r", fam_r)):
bb, ss, pp, _ = within_scan(yy, GG, XX, np.asarray(grp)[sub])
out[name] = (bb, ss, pp)
keep = dedup(Kd[np.ix_(sub, sub)])
au = np.array(authors)[sub][keep]
bb, ss, pp, _ = within_scan(yy[keep], GG[keep], XX[keep], au)
out["dup_afe"] = (bb, ss, pp)
return out
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--geno", required=True)
ap.add_argument("--pheno", required=True)
ap.add_argument("--out", required=True)
ap.add_argument("--recipe_threshold", type=float, default=None)
ap.add_argument("--traits", default="primary", help="primary or all")
ap.add_argument("--raw_coords", action="store_true", help="ablation: genotypes from raw (not expressed) grams")
ap.add_argument("--shard", type=int, default=0)
ap.add_argument("--nshards", type=int, default=1)
ap.add_argument("--n_pcs", type=int, default=10, help="sensitivity 14.6: 5 / 10 / 20")
ap.add_argument("--fam_mult", type=float, default=3.0, help="sensitivity 14.6: descent threshold 2 / 3 / 5 x law")
ap.add_argument("--ablate", default="none", choices=["none", "no_lob", "no_func"],
help="14.7: no_lob = full function kernel for every block; no_func = MM with the descent kernel only")
a = ap.parse_args()
os.makedirs(a.out, exist_ok=True)
P = build(a.geno, a.pheno, recipe_threshold=a.recipe_threshold, loci_file="loci_raw.pt" if a.raw_coords else "loci.pt",
fam_mult=a.fam_mult)
n = len(P["names"])
ptf = os.path.join(a.out, "primary_traits.json")
if not os.path.exists(ptf):
prim = [t for t, r in P["rel"].items() if np.isfinite(r) and r >= 0.7]
json.dump({"primary": prim, "reliability": P["rel"], "n": n}, open(ptf, "w"), indent=1)
# plan 4.3: the list also goes to results/phenotypes/primary_traits_<population>.json
pp = os.path.join(os.path.dirname(os.path.normpath(a.pheno)), f"primary_traits_{os.path.basename(os.path.normpath(a.pheno))}.json")
if not os.path.exists(pp):
json.dump({"primary": prim, "reliability": P["rel"], "n": n, "threshold": 0.7}, open(pp, "w"), indent=1)
prim = json.load(open(ptf))["primary"]
traits = prim if a.traits == "primary" else P["traits"]
# leave-block-out function kernels from per-module expressed grams
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)]
Kf_full, Kd = P["K_func"], P["K_desc"]
if a.ablate == "no_lob": # 14.7: no left-out block
Kf_blocks = [Kf_full] * 8
elif a.ablate == "no_func": # 14.7: no function layer (mm_f then reads as descent-only MM)
Kf_blocks, Kf_full = [Kd] * 8, Kd
ev, evec = np.linalg.eigh(Kf_full)
pcs = evec[:, ::-1][:, :a.n_pcs]
G, X = P["G"], P["X"]
block_of_locus = np.array([blocks_of(l["module"]) for l in P["loci"]])
idx = {"full": np.arange(n), "D": np.where(P["split"] == 0)[0], "E": np.where(P["split"] == 1)[0]}
meff = m_eff(G)
summary = {"n": n, "n_loci": G.shape[1], "M_eff": meff, "bonferroni_p": 0.05 / meff,
"n_eff_desc": neff(P["K_desc"]), "n_eff_func": neff(P["K_func"]),
"n_desc_families": int(len(set(P["fam_d"]))), "n_recipe_families": int(len(set(P["fam_r"]))),
"share_with_relative": float(np.mean([np.sum(P["fam_d"] == f) > 1 for f in P["fam_d"]])),
"recipe_threshold": P["recipe_threshold"], "split_sizes": [int((P["split"] == s).sum()) for s in (0, 1)],
"traits": {}}
json.dump([{**l, "idx": i} for i, l in enumerate(P["loci"])], open(os.path.join(a.out, "loci.json"), "w"))
json.dump({"names": P["names"], "fam_d": P["fam_d"].tolist(), "fam_r": P["fam_r"].tolist(),
"split": P["split"].tolist(), "authors": P["authors"]}, open(os.path.join(a.out, "population.json"), "w"))
rng = np.random.default_rng(0)
neg = rng.normal(size=P["fam_d"].max() + 1)[P["fam_d"]]
iid = rng.normal(size=n) # diagnostic nulls (D-023): pure noise, and family effect + equal-variance noise
fam50 = (neg + rng.normal(size=n)) / np.sqrt(2)
jobs = [(t, P["Yt"][:, P["traits"].index(t)]) for t in traits] + [("__negative_control__", neg), ("__null_iid__", iid),
("__null_fam50__", fam50)]
for t, y in jobs[a.shard::a.nshards]: # resumable and shardable (D-026): per-trait npz + summary json
fn, fj = os.path.join(a.out, f"{t}.npz"), os.path.join(a.out, f"{t}.summary.json")
if os.path.exists(fn) and os.path.exists(fj):
continue
vc_log = {}
res = {s: run_estimators(y, G, X, Kf_blocks, Kf_full, Kd, P["fam_d"], P["fam_r"], P["authors"],
block_of_locus, pcs, idx[s], vc_log if s == "full" else {}) for s in SUBSETS}
arr = {q: np.array([[res[s][e][qi] for s in SUBSETS] for e in EST]) for qi, q in enumerate(("beta", "se", "p"))}
np.savez(fn, **arr)
lam = {e: lambda_gc(arr["p"][i, 0]) for i, e in enumerate(EST)}
hits_bonf = {e: int(np.nansum(arr["p"][i, 0] < 0.05 / meff)) for i, e in enumerate(EST)}
hits_fdr_D = {e: int(bh(arr["p"][i, 1]).sum()) for i, e in enumerate(EST)}
json.dump({"lambda_gc": lam, "hits_bonf_full": hits_bonf, "hits_fdr_D": hits_fdr_D, "reliability": P["rel"].get(t),
"variance_components_full": vc_log}, open(fj, "w"), indent=1)
print(t, "lambda", {k: round(v, 2) for k, v in lam.items()}, flush=True)
for t, _ in jobs:
fj = os.path.join(a.out, f"{t}.summary.json")
if os.path.exists(fj):
summary["traits"][t] = json.load(open(fj))
summary["complete"] = len(summary["traits"]) == len(jobs)
json.dump(summary, open(os.path.join(a.out, "summary.json"), "w"), indent=1)
print("SCANDONE", len(summary["traits"]), "of", len(jobs), flush=True)
if __name__ == "__main__":
main()