File size: 10,152 Bytes
aaba844
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
# MIT License, Bryan Cheng, 2026.
"""Spike-ins (RESEARCH_PLAN 10; E5): plan and analysis.

plan     directions: the 4 opposite pairs (trained, 3 seeds per side), up to 8 validated loci (largest |z| of gamma_do,
         distinct modules) and 4 random rank-4 directions (random modules with loci; seeds 0-3). Carrier designs per
         seed 0-4: nested random sets of 1, 5 and 20 percent of the population and whole descent families (random order)
         until >= 5 percent. Carriers to measure = union over seeds and designs.
analyze  per direction, seed, design, dose: trait = ECDF-mapped change of the direction's target trait (primary trait
         with the largest |effect| on the base at 1 SD) for carriers, 0 for non-carriers; carriers' genotypes shift by
         dose x SD x the direction's projection on each locus. All scan_run.py estimators on the full set. True loci:
         |projection| x SD / sigma_l >= 0.5. Discoveries at BH 0.05; precision, recall; bias of the implied effect
         along the direction (sum over true loci of beta_l x projection_l) relative to the measured mean change per unit.

  python src/analysis/spikein.py plan --geno ... --pheno ... --scan ... --calib ... --trained data/raw/trained/opposite
         --adapters_dir ... --base ... --out results/spikein/plan_qwen05.json
  python src/analysis/spikein.py analyze --geno ... --pheno ... --scan ... --plan ... --spike results/spikein/qwen05 --out x.json
"""
import argparse
import json
import os
import sys
from multiprocessing import Pool

import numpy as np
import torch
from scipy import stats

sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", ".."))
from src.analysis.calibrate import ecdf_map  # noqa: E402
from src.analysis.population import build  # noqa: E402
from src.analysis.scan import bh  # noqa: E402
from src.run.scan_run import EST, blocks_of, cosine, run_estimators  # noqa: E402

OPP = [("french", "english"), ("concise", "long"), ("markdown", "plain"), ("formal", "casual")]
W = {}


def carrier_sets(names, fam_d, seed):
    rng = np.random.default_rng(seed)
    n = len(names)
    perm = rng.permutation(n)
    sets = {f"rand{p}": sorted(perm[: max(1, int(round(n * p / 100)))].tolist()) for p in (1, 5, 20)}
    fams = rng.permutation(np.unique(fam_d))
    fs = []
    for f in fams:
        if len(fs) >= 0.05 * n:
            break
        fs += np.where(fam_d == f)[0].tolist()
    sets["families"] = sorted(fs)
    return sets


def job(args):
    did, seed, design, dose = args
    w = W
    car = np.array(w["sets"][seed][design])
    tr = w["target"][did]
    y = np.zeros(w["n"])
    ok = np.ones(len(car), bool)
    for k, i in enumerate(car):
        rec = w["meas"][did].get(w["names"][i])
        if rec is None:
            ok[k] = False
            continue
        y[i] = w["maps"][tr](rec[str(dose)][tr][0]) - w["maps"][tr](rec["0.0"][tr][0])
    car = car[ok]
    G = w["G"].copy()
    s = dose * w["sigma"][did]
    G[car] += s * w["proj"][did][None]
    G -= G.mean(0)
    idx = np.arange(w["n"])
    res = run_estimators(y, G, w["X"], w["Kfb"], w["Kf"], w["Kd"], w["fam_d"], w["fam_r"], w["authors"], w["blk"],
                         w["pcs"], idx, {})
    T = w["true"][did]
    beta_true = y[car].mean() / s if len(car) else np.nan
    out = {"direction": did, "seed": seed, "design": design, "dose": dose, "n_carriers": int(len(car)), "n_true": int(T.sum())}
    for e in EST:
        b, se, p = res[e]
        disc = bh(np.where(np.isfinite(p), p, 1.0))
        tp = int((disc & T).sum())
        out[e] = {"n_disc": int(disc.sum()), "precision": tp / disc.sum() if disc.sum() else np.nan,
                  "recall": tp / T.sum() if T.sum() else np.nan,
                  "bias": float(np.nansum(b[T] * w["proj"][did][T]) / beta_true - 1) if T.sum() and beta_true != 0 else np.nan}
    return out


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("cmd", choices=["plan", "analyze"])
    for k in ("geno", "pheno", "scan", "out"):
        ap.add_argument("--" + k, required=True)
    for k in ("calib", "trained", "adapters_dir", "base", "plan", "spike"):
        ap.add_argument("--" + k)
    ap.add_argument("--workers", type=int, default=int(os.environ.get("SLURM_CPUS_PER_TASK", 4)))
    ap.add_argument("--recipe_threshold", type=float, default=None,
                    help="plan 5.3 cut (D-039: 0.9361427475490963); WF-r uses recipe families. None = population fallback")
    a = ap.parse_args()
    if a.recipe_threshold is None:
        print("WARNING: no --recipe_threshold; WF-r uses the population fallback cut, not plan 5.3 (D-039)", flush=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"]
    names = P["names"]
    if a.cmd == "plan":
        dirs = [{"id": f"opp_{x}_vs_{y}", "kind": "opposite",
                 "side_a": [os.path.join(a.trained, f"opp_{x}_s{s}") for s in range(3)],
                 "side_b": [os.path.join(a.trained, f"opp_{y}_s{s}") for s in range(3)]} for x, y in OPP]
        if a.calib and os.path.exists(a.calib):
            C = json.load(open(a.calib))["per_direction"]
            rows = []
            for v in C.values():
                if v["kind"] == "locus" and v.get("source"):
                    z = max(abs(v["traits"][t]["gamma_do"]) / np.sqrt(max(v["traits"][t]["var_do"], 1e-300)) for t in prim)
                    rows.append((z, v["module"], v["l"]))
            used = set()
            for z, m, l in sorted(rows, reverse=True):
                if m not in used and z > stats.norm.isf(0.025) and len(used) < 8:
                    used.add(m)
                    dirs.append({"id": f"loc_{m}_{l}", "kind": "locus", "module": m, "l": l})
        loci = json.load(open(os.path.join(a.scan, "loci.json")))
        mods = sorted({l["module"] for l in loci if not l["module"].startswith("presence")})
        rng = np.random.default_rng(0)
        for s in range(4):
            dirs.append({"id": f"rnd_{s}", "kind": "random", "module": str(rng.choice(mods)), "seed": 9000 + s})
        sets = {s: carrier_sets(names, P["fam_d"], s) for s in range(5)}
        union = sorted({names[i] for st in sets.values() for v in st.values() for i in v})
        plan = {"base": a.base, "adapters_dir": a.adapters_dir, "geno_dir": a.geno, "doses": [0.5, 1.0, 2.0],
                "directions": dirs, "carriers": union, "sets": {str(k): v for k, v in sets.items()}}
        json.dump(plan, open(a.out, "w"), indent=1)
        print("directions", len(dirs), "carriers", len(union), flush=True)
        return
    plan = json.load(open(a.plan))
    n = len(names)
    A = json.load(open(os.path.join(a.geno, "adapters.json")))
    keep = np.array([x in set(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)
    lociL = torch.load(os.path.join(a.geno, "loci.pt"))
    W.update({"n": n, "names": names, "G": P["G"], "X": P["X"], "Kfb": [cosine(S - Sb[b]) for b in range(8)],
              "Kf": P["K_func"], "Kd": P["K_desc"], "fam_d": P["fam_d"], "fam_r": P["fam_r"], "authors": P["authors"],
              "blk": np.array([blocks_of(l["module"]) for l in P["loci"]]),
              "pcs": np.linalg.eigh(P["K_func"])[1][:, ::-1][:, :10],
              "maps": {t: ecdf_map(P["Y"][0, :, P["traits"].index(t)])[0] for t in prim},
              "sets": {int(k): v for k, v in plan["sets"].items()}, "meas": {}, "proj": {}, "sigma": {}, "target": {}, "true": {}})
    sig_l = np.array([l["sigma"] for l in P["loci"]])
    jobs = []
    for d in plan["directions"]:
        od = os.path.join(a.spike, d["id"])
        if not os.path.exists(os.path.join(od, "direction.npz")):
            continue
        z = np.load(os.path.join(od, "direction.npz"))
        pr = np.zeros(len(P["loci"]))
        for j, l in enumerate(P["loci"]):
            if l["module"].startswith("presence"):
                continue
            lo = lociL[l["module"]]
            pr[j] = float(z["proj"][mods.index(l["module"])] @ lo["U"][:, l["l"]].double().numpy() / np.sqrt(float(lo["lam"][l["l"]])))
        meas = {}
        for x in names + ["__base__"]:
            f = os.path.join(od, f"{x}.json")
            if os.path.exists(f):
                meas[x] = json.load(open(f))["doses"]
        if "__base__" not in meas:
            continue
        bse = meas["__base__"]
        tr = max(prim, key=lambda t: abs(W["maps"][t](bse["1.0"][t][0]) - W["maps"][t](bse["0.0"][t][0])))
        tf = os.path.join(od, "target.json")  # target-only runs (D-032) fix the target at measurement time
        if os.path.exists(tf):
            tr_run = json.load(open(tf))["target"]
            W.setdefault("target_mismatch", {})[d["id"]] = tr_run != tr
            tr = tr_run
        W["meas"][d["id"]], W["proj"][d["id"]], W["sigma"][d["id"]], W["target"][d["id"]] = meas, pr, float(z["sigma"]), tr
        W["true"][d["id"]] = np.abs(pr) * float(z["sigma"]) / np.maximum(sig_l, 1e-300) >= 0.5
        jobs += [(d["id"], s, ds, dose) for s in range(5) for ds in ("rand1", "rand5", "rand20", "families") for dose in plan["doses"]]
    with Pool(a.workers) as pool:
        rows = pool.map(job, jobs)
    summ = {}
    for kind in ("opposite", "locus", "random"):
        for ds in ("rand1", "rand5", "rand20", "families"):
            rr = [r for r in rows if r["direction"].startswith(kind[:3]) and r["design"] == ds]
            if rr:
                summ[f"{kind}:{ds}"] = {e: {m: float(np.nanmean([r[e][m] for r in rr])) for m in ("precision", "recall", "bias")}
                                        for e in EST}
    json.dump({"summary": summ, "rows": rows, "targets": W["target"], "target_mismatch": W.get("target_mismatch", {})}, open(a.out, "w"), indent=1, default=float)
    print(json.dumps(summ, default=float)[:3000], flush=True)


if __name__ == "__main__":
    main()