# MIT License, Bryan Cheng, 2026. """Family bootstrap of observational effect estimates for the tested loci (RESEARCH_PLAN 14.1). Descent families of the estimation set are resampled with replacement (200 resamples); every estimator of scan_run.py is re-applied to the resampled rows with variance components held at their REML values on the original estimation set (fixed-V GLS), duplicated families relabelled as distinct families for WF-d, and near-duplicate removal for DUP-AFE done once on the original rows. Output: npz with var[estimator, primary trait, locus] (NaN for untested loci), the input of calibrate.py --obs_boot. python src/analysis/obs_boot.py --geno data/processed/qwen05 --pheno results/phenotypes/qwen05 --scan results/scans/qwen05 --plan results/interventions/plan_qwen05.json --out results/scans/qwen05/obs_boot.npz [--claim] [--shard i --nshards n] Per-trait variances go to .parts/.npy as they finish (resumable; --claim shares traits through lock files, D-036); is written once every primary trait has a part. RNG seeded per trait by (seed, trait index). """ import argparse import json import os import signal 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 gls_scan, ols_scan, reml, within_scan # noqa: E402 from src.run.intervene import HELD, claim, unlock # noqa: E402 from src.run.scan_run import EST, blocks_of, cosine, dedup # noqa: E402 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("--plan", 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=200) ap.add_argument("--loci_file", default="loci.pt", help="loci_raw.pt for the raw-coordinate ablation (D-037)") 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, loci_file=a.loci_file) prim = json.load(open(os.path.join(a.scan, "primary_traits.json")))["primary"] plan = json.load(open(a.plan)) J = sorted({d["locus_idx"] for d in plan["directions"] if d["kind"] == "locus"}) n, L = len(P["names"]), P["G"].shape[1] 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"] _, evec = np.linalg.eigh(Kf_full) pcs = evec[:, ::-1][:, :10] G, X = P["G"][:, J], P["X"] blk = np.array([blocks_of(P["loci"][j]["module"]) for j in J]) fam_d, fam_r, authors = P["fam_d"], P["fam_r"], np.array(P["authors"]) var = np.full((len(EST), len(prim), L), np.nan) for ti, t in enumerate(prim): pf = os.path.join(pd, t + ".npy") 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)] E = np.where((P["split"] == 1) & np.isfinite(y))[0] vcs = {} for name, use_d in (("mm_f", False), ("mm_fd", True)): for b in sorted(set(blk)): Kf = Kf_full if b == -1 else Kf_blocks[b] Ks = [Kf[np.ix_(E, E)] + 1e-6 * np.eye(len(E))] + ([Kd[np.ix_(E, E)] + 1e-6 * np.eye(len(E))] if use_d else []) vcs[(name, b)] = reml(y[E], X[E], Ks)[0] fams = {} for i in E: fams.setdefault(int(fam_d[i]), []).append(int(i)) fl = list(fams) kd = E[dedup(Kd[np.ix_(E, E)])] kd_set = set(kd.tolist()) draws = np.full((a.n_boot, len(EST), len(J)), np.nan) for bi in range(a.n_boot): pick = rng.choice(len(fl), len(fl)) rows = np.concatenate([fams[fl[p]] for p in pick]) lab = np.concatenate([[k] * len(fams[fl[p]]) for k, p in enumerate(pick)]) yy, GG, XX = y[rows], G[rows], X[rows] draws[bi, 0] = ols_scan(yy, GG, XX)[0] draws[bi, 1] = ols_scan(yy, GG, np.column_stack([XX, pcs[rows]]))[0] for ei, (name, use_d) in ((2, ("mm_f", False)), (3, ("mm_fd", True))): for b in sorted(set(blk)): cols = np.where(blk == b)[0] Kf = (Kf_full if b == -1 else Kf_blocks[b])[np.ix_(rows, rows)] vc = vcs[(name, b)] V = vc[0] * Kf + (vc[1] * Kd[np.ix_(rows, rows)] if use_d else 0) + vc[-1] * np.eye(len(rows)) V += 1e-6 * vc[:-1].sum() * np.eye(len(rows)) draws[bi, ei, cols] = gls_scan(yy, GG[:, cols], XX, V)[0] draws[bi, 4] = within_scan(yy, GG, XX, lab)[0] draws[bi, 5] = within_scan(yy, GG, XX, fam_r[rows])[0] rk = np.array([r for r in rows if r in kd_set]) draws[bi, 6] = within_scan(y[rk], G[rk], X[rk], authors[rk])[0] v = np.nanvar(draws, 0) np.save(pf + ".tmp.npy", v) os.replace(pf + ".tmp.npy", pf) unlock(HELD) print(t, "median boot SD naive / mm_fd", np.nanmedian(np.sqrt(v[0])), np.nanmedian(np.sqrt(v[3])), flush=True) if all(os.path.exists(os.path.join(pd, t + ".npy")) for t in prim): for ti, t in enumerate(prim): var[:, ti, J] = np.load(os.path.join(pd, t + ".npy")) np.savez(a.out, var=var, estimators=np.array(EST), traits=np.array(prim), loci=np.array(J)) print("BOOTDONE", flush=True) else: print("BOOT_PARTIAL", sum(os.path.exists(os.path.join(pd, t + ".npy")) for t in prim), "/", len(prim), flush=True) if __name__ == "__main__": try: main() finally: unlock(HELD)