File size: 4,897 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
# MIT License, Bryan Cheng, 2026.
"""Replicated null traits for the scan's calibration diagnostics (D-048).

The scan (src/run/scan_run.py) draws one negative control (pure family effect), one iid-noise null and one
family-effect-plus-noise null, all from np.random.default_rng(0). A single draw's lambda_GC is noisy: loci are correlated
(M_eff = 383 of 5,191), so the median chi-square rests on few effective tests. This script repeats the same construction
for seeds 0..R-1 on the full population and reports the distribution of lambda_GC per estimator. Seed 0 reproduces the
scan's own draws, and the script checks that its lambda values match the scan summary.

Setup (kernels, leave-block-out function kernels, PCs) is copied from scan_run.main so the estimators see identical inputs.

  python src/analysis/null_reps.py --geno data/processed/qwen05 --pheno results/phenotypes/qwen05
         --scan results/scans/qwen05_rt --recipe_threshold 0.9361427475490963 --reps 20
         --out results/scans/qwen05_rt/null_reps.json
"""
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  # noqa: E402
from src.analysis.scan import lambda_gc  # noqa: E402
from src.run.scan_run import EST, blocks_of, cosine, run_estimators  # noqa: E402

KINDS = ("negative_control", "null_iid", "null_fam50")


def draws(seed, fam_d, n):
    """Same construction and draw order as scan_run.main."""
    rng = np.random.default_rng(seed)
    neg = rng.normal(size=fam_d.max() + 1)[fam_d]
    iid = rng.normal(size=n)
    fam50 = (neg + rng.normal(size=n)) / np.sqrt(2)
    return dict(zip(KINDS, (neg, iid, fam50)))


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--geno", required=True)
    ap.add_argument("--pheno", required=True)
    ap.add_argument("--scan", required=True, help="scan directory whose seed-0 nulls must be reproduced")
    ap.add_argument("--recipe_threshold", type=float, default=None)
    ap.add_argument("--n_pcs", type=int, default=10)
    ap.add_argument("--reps", type=int, default=20)
    ap.add_argument("--out", required=True)
    a = ap.parse_args()
    P = build(a.geno, a.pheno, recipe_threshold=a.recipe_threshold)
    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)]
    del Sb, S
    Kf_full, Kd = P["K_func"], P["K_desc"]
    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"]])
    full = np.arange(n)
    fam_d = np.asarray(P["fam_d"])
    parts = a.out + ".parts"
    os.makedirs(parts, exist_ok=True)
    lam = {k: [] for k in KINDS}
    for r in range(a.reps):
        Y = draws(r, fam_d, n)
        for k in KINDS:
            pf = os.path.join(parts, f"{k}_{r:03d}.json")
            if not os.path.exists(pf):
                res = run_estimators(Y[k], G, X, Kf_blocks, Kf_full, Kd, P["fam_d"], P["fam_r"], P["authors"],
                                     block_of_locus, pcs, full, {})
                rec = {e: float(lambda_gc(res[e][2])) for e in EST}
                json.dump(rec, open(pf + ".tmp", "w"))
                os.replace(pf + ".tmp", pf)
                print(k, r, {e: round(v, 3) for e, v in rec.items()}, flush=True)
            lam[k].append(json.load(open(pf)))
    S = json.load(open(os.path.join(a.scan, "summary.json")))["traits"]
    check = {k: max(abs(lam[k][0][e] - S["__" + k + "__"]["lambda_gc"][e]) for e in EST) for k in KINDS}
    out = {"n": n, "reps": a.reps, "seed0_max_abs_diff_vs_scan": check, "lambda": lam, "summary": {}}
    for k in KINDS:
        M = np.array([[d[e] for e in EST] for d in lam[k]])
        out["summary"][k] = {e: {"median": float(np.median(M[:, i])), "mean": float(M[:, i].mean()),
                                 "q025": float(np.quantile(M[:, i], 0.025)), "q975": float(np.quantile(M[:, i], 0.975)),
                                 "min": float(M[:, i].min()), "max": float(M[:, i].max()),
                                 "n_gt_1_1": int((M[:, i] > 1.1).sum())} for i, e in enumerate(EST)}
    json.dump(out, open(a.out, "w"), indent=1)
    print(json.dumps({"check": check, "median": {k: {e: round(v["median"], 2) for e, v in out["summary"][k].items()}
                                                  for k in KINDS}}), "NULLREPSDONE", flush=True)


if __name__ == "__main__":
    main()