lorapop / code /src /analysis /plan_interventions.py
bryan7264's picture
Add files using upload-large-folder tool
aaba844 verified
Raw History Blame Contribute Delete
9.45 kB
# MIT License, Bryan Cheng, 2026.
"""Intervention plan from discovery-set scans (RESEARCH_PLAN 8.1, 8.2, 8.5).
Loci: union over estimators and primary traits of loci significant on D at FDR 0.05, capped at --cap by round-robin over
estimators (smallest D p-value first). If fewer than --min_loci pass (logged as a deviation in DECISIONS.md), the set is
filled by the same round-robin over loci ranked by their smallest D p-value; every locus records its source.
Controls per locus: random direction (same module, unit expressed norm = the allele's norm), the highest-variance locus
of the same module with no association (over --nonassoc_est, default the four population-level estimators: not
FDR-significant and min D p x n_tests > 0.5, i.e. Bonferroni over traits x those estimators; D-024, D-033), and the same weight-space axis placed in the layer nL/2 away.
Backgrounds: --n_bg estimation-set adapters, one per recipe cluster (largest clusters first) and at most one per descent
family, seed 0. Knockouts: estimation-set carriers with |g - mean| > 1 SD, up to --max_ko with the largest |g - mean|.
--ctrl_bg k (D-031): control directions (random, other-layer, high-variance) use the first k backgrounds only (one per
largest recipe cluster); 0 = all.
--coords raw (D-037; plan 14.7 ablation): loci from <geno>/loci_raw.pt and a raw-coordinate scan; with --no_controls and
--max_ko 0 only tested loci are planned; --test_bg k puts every direction on the first k backgrounds.
python src/analysis/plan_interventions.py --scan results/scans/qwen05 --geno data/processed/qwen05
--adapters_dir data/raw/adapters/Qwen__Qwen2.5-0.5B-Instruct --base Qwen/Qwen2.5-0.5B-Instruct
--out results/interventions/plan_qwen05.json
"""
import argparse
import json
import os
import sys
import numpy as np
import torch
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", ".."))
from src.analysis.scan import bh # noqa: E402
EST = ["naive", "pc", "mm_f", "mm_fd", "wf_d", "wf_r", "dup_afe"]
def round_robin(lists, cap, taken=()):
out, seen, ptr = [], set(taken), {k: 0 for k in lists}
while len(out) < cap and any(ptr[k] < len(v) for k, v in lists.items()):
for k, v in lists.items():
while ptr[k] < len(v) and v[ptr[k]] in seen:
ptr[k] += 1
if ptr[k] < len(v) and len(out) < cap:
out.append((v[ptr[k]], k))
seen.add(v[ptr[k]])
ptr[k] += 1
return out
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--scan", required=True)
ap.add_argument("--geno", required=True)
ap.add_argument("--adapters_dir", required=True)
ap.add_argument("--base", required=True)
ap.add_argument("--out", required=True)
ap.add_argument("--cap", type=int, default=150)
ap.add_argument("--min_loci", type=int, default=0)
ap.add_argument("--n_bg", type=int, default=24)
ap.add_argument("--max_ko", type=int, default=24)
ap.add_argument("--seed", type=int, default=0)
ap.add_argument("--doses_base", default="-3,-2,-1,0,1,2,3")
ap.add_argument("--doses_bg", default="-1,0,1")
ap.add_argument("--ctrl_bg", type=int, default=0)
ap.add_argument("--test_bg", type=int, default=0, help="D-037: every direction on the first k backgrounds; 0 = all")
ap.add_argument("--coords", default="expressed", choices=["expressed", "raw"])
ap.add_argument("--no_controls", action="store_true")
ap.add_argument("--nonassoc_est", default="naive,pc,mm_f,mm_fd",
help="D-033: estimators defining a non-associated (high-variance control) locus")
a = ap.parse_args()
loci = json.load(open(os.path.join(a.scan, "loci.json")))
pop = json.load(open(os.path.join(a.scan, "population.json")))
prim = json.load(open(os.path.join(a.scan, "primary_traits.json")))["primary"]
real = np.array([not l["module"].startswith("presence") for l in loci])
P = np.stack([np.load(os.path.join(a.scan, f"{t}.npz"))["p"][:, 1] for t in prim]) # [trait, est, locus] on D
P = np.where(np.isfinite(P), P, 1.0)
P[:, :, ~real] = 1.0
fdr = {}
for ei, e in enumerate(EST):
best = {}
for ti in range(len(prim)):
for j in np.where(bh(P[ti, ei]) & real)[0]:
best[j] = min(best.get(j, 1.0), P[ti, ei, j])
fdr[e] = sorted(best, key=best.get)
chosen = [(j, "fdr:" + e) for j, e in round_robin(fdr, a.cap)]
n_fdr = len(chosen)
if n_fdr < a.min_loci:
pmin = P.min(0) # [est, locus]
ranked = {e: [int(j) for j in np.argsort(pmin[ei]) if real[j]] for ei, e in enumerate(EST)}
chosen += [(j, "fill:" + e) for j, e in round_robin(ranked, a.min_loci - n_fdr, taken=[c[0] for c in chosen])]
nL = max(l["layer"] for l in loci) + 1
names_all = json.load(open(os.path.join(a.geno, "adapters.json")))["names"]
pos = {x: i for i, x in enumerate(names_all)}
loci_file = "loci_raw.pt" if a.coords == "raw" else "loci.pt"
G = torch.load(os.path.join(a.geno, loci_file))
names, split = pop["names"], np.array(pop["split"])
fam_d, fam_r = np.array(pop["fam_d"]), np.array(pop["fam_r"])
E = np.where(split == 1)[0]
# backgrounds
rng = np.random.default_rng(a.seed)
clusters = {}
for i in rng.permutation(E):
clusters.setdefault(int(fam_r[i]), []).append(int(i))
order = sorted(clusters, key=lambda c: (-len(clusters[c]), min(clusters[c])))
bgs, used_fam = [], set()
while len(bgs) < a.n_bg and any(clusters[c] for c in order):
for c in order:
while clusters[c] and fam_d[clusters[c][0]] in used_fam:
clusters[c].pop(0)
if clusters[c] and len(bgs) < a.n_bg:
i = clusters[c].pop(0)
bgs.append(names[i])
used_fam.add(fam_d[i])
# directions
# "non-associated" (plan 8.1; D-024, D-033): over the --nonassoc_est estimators, not FDR-significant on D for any primary
# trait and Bonferroni-adjusted min p (traits x those estimators) > 0.5
na = [EST.index(e) for e in a.nonassoc_est.split(",")]
in_fdr = np.zeros(P.shape[2], bool)
for e in na:
in_fdr[list(fdr[EST[e]])] = True
assoc_min = np.where(in_fdr, 0.0, P[:, na].min((0, 1)) * P.shape[0] * len(na))
dirs, ctrl_ids = [], {}
for j, src in chosen:
lo = loci[j]
key, l = lo["module"], lo["l"]
g = G[key]["g"][:, l].double().numpy()
pidx = np.array([pos[x] for x in names])
gbar = g[pidx].mean()
sd = g[pidx].std()
dev = [(names[i], float(g[pos[names[i]]] - gbar)) for i in E if abs(g[pos[names[i]]] - gbar) > sd]
dev = sorted(dev, key=lambda t: -abs(t[1]))[:a.max_ko]
did = f"loc_{key}_{l}"
dirs.append({"id": did, "kind": "locus", "module": key, "l": l, "locus_idx": j, "source": src,
"knockout_carriers": dev})
if a.no_controls:
continue
dirs.append({"id": f"rnd_{key}_{l}", "kind": "random", "module": key, "l": l, "seed": 1000 + j, "control_of": did})
tl = (lo["layer"] + nL // 2) % nL
dirs.append({"id": f"oth_{key}_{l}_to{tl}", "kind": "other_layer", "module": key, "l": l,
"target_module": f"{tl}.{lo['type']}", "control_of": did})
same = [k for k, x in enumerate(loci) if x["module"] == key and k != j and assoc_min[k] > 0.5]
if same:
k = max(same, key=lambda k: loci[k]["lam"])
hid = f"hv_{key}_{loci[k]['l']}"
if hid in ctrl_ids:
ctrl_ids[hid]["control_of"].append(did)
else:
ctrl_ids[hid] = {"id": hid, "kind": "locus", "module": key, "l": loci[k]["l"], "locus_idx": k,
"control_of": [did]}
chosen_ids = {d["id"] for d in dirs}
dirs += [v for k, v in ctrl_ids.items() if f"loc_{v['module']}_{v['l']}" not in chosen_ids]
if a.test_bg:
for d in dirs:
d["backgrounds"] = bgs[:a.test_bg]
if a.ctrl_bg:
for d in dirs:
if d.get("control_of"):
d["backgrounds"] = bgs[:a.ctrl_bg]
plan = {"base": a.base, "adapters_dir": a.adapters_dir, "geno_dir": a.geno, "backgrounds": bgs, "coords": a.coords,
"loci_file": loci_file,
"doses_base": [float(x) for x in a.doses_base.split(",")], "doses_bg": [float(x) for x in a.doses_bg.split(",")],
"directions": dirs,
"selection": {"primary_traits": prim, "n_fdr": n_fdr, "n_fill": len(chosen) - n_fdr,
"fdr_per_estimator": {e: len(v) for e, v in fdr.items()}, "cap": a.cap, "min_loci": a.min_loci,
"n_directions": len(dirs), "n_backgrounds": len(bgs), "ctrl_bg": a.ctrl_bg, "nonassoc_est": a.nonassoc_est,
"test_bg": a.test_bg, "coords": a.coords, "controls": not a.no_controls,
"n_knockouts": sum(len(d.get("knockout_carriers", [])) for d in dirs),
"n_carriers": len({n for d in dirs for n, _ in d.get("knockout_carriers", [])})}}
os.makedirs(os.path.dirname(a.out), exist_ok=True)
json.dump(plan, open(a.out, "w"), indent=1, default=lambda o: o.item() if hasattr(o, "item") else str(o))
print(json.dumps(plan["selection"], default=lambda o: o.item() if hasattr(o, "item") else str(o)), flush=True)
if __name__ == "__main__":
main()