# MIT License, Bryan Cheng, 2026. """Uncertainty of lambda_GC by a delete-a-group jackknife over descent families (D-044). The family-block bootstrap in scan_extras.py resamples families with replacement. A family drawn twice enters as two sets of distinct adapters, so the naive scan (and, through its independent residual term, the fixed-V MM-fd scan) counts the copies as independent evidence and the bootstrap distribution of lambda_GC is shifted upward (the point estimate lies below the bootstrap interval on most traits). The jackknife never duplicates an adapter. Descent families are dealt at random (seed) into G groups. For each group, lambda_GC is recomputed without that group's adapters: naive OLS, and MM-fd as GLS with the scan's own full-sample variance components per left-out block (summary variance_components_full; V restricted to the kept rows). SE = sqrt((G-1)/G sum (lambda_-g - mean)^2); 95% interval = point +- 1.96 SE. The point estimate must reproduce the scan's lambda_GC (checked and reported). python src/analysis/lambda_jk.py --geno data/processed/qwen05 --pheno results/phenotypes/qwen05 --scan results/scans/qwen05_rt --out results/scans/qwen05_rt/lambda_jk.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 gls_scan, lambda_gc, ols_scan # noqa: E402 from src.run.scan_run import blocks_of, cosine # 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("--out", required=True) ap.add_argument("--groups", type=int, default=20) ap.add_argument("--seed", type=int, default=0) a = ap.parse_args() P = build(a.geno, a.pheno) prim = json.load(open(os.path.join(a.scan, "primary_traits.json")))["primary"] 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 G, X, Kd, Kf_full = P["G"], P["X"], P["K_desc"], P["K_func"] blk = np.array([blocks_of(l["module"]) for l in P["loci"]]) fams = np.unique(P["fam_d"]) grp_of_fam = dict(zip(fams, np.random.default_rng(a.seed).permutation(len(fams)) % a.groups)) grp = np.array([grp_of_fam[f] for f in P["fam_d"]]) parts = a.out + ".parts" os.makedirs(parts, exist_ok=True) out = {"n": n, "groups": a.groups, "seed": a.seed, "traits": {}} for t in prim: pf = os.path.join(parts, t + ".json") if os.path.exists(pf): out["traits"][t] = json.load(open(pf)) continue summ = json.load(open(os.path.join(a.scan, f"{t}.summary.json"))) vcs = summ["variance_components_full"]["mm_fd"] y = P["Yt"][:, P["traits"].index(t)] ok = np.where(np.isfinite(y))[0] I = np.eye(len(ok)) Vb = {} for bk in sorted(set(blk)): vc = np.array(vcs[str(bk)]) Kf = (Kf_full if bk == -1 else Kf_blocks[bk])[np.ix_(ok, ok)] Vb[bk] = vc[0] * (Kf + 1e-6 * I) + vc[1] * (Kd[np.ix_(ok, ok)] + 1e-6 * I) + vc[2] * I def lams(r): # r: positions within ok rows = ok[r] ln = lambda_gc(ols_scan(y[rows], G[rows], X[rows])[2]) pv = np.full(G.shape[1], np.nan) for bk, V in Vb.items(): cols = np.where(blk == bk)[0] pv[cols] = gls_scan(y[rows], G[np.ix_(rows, cols)], X[rows], V[np.ix_(r, r)])[2] return ln, lambda_gc(pv) pt = lams(np.arange(len(ok))) jk = np.array([lams(np.where(grp[ok] != g)[0]) for g in range(a.groups)]) se = np.sqrt((a.groups - 1) / a.groups * ((jk - jk.mean(0)) ** 2).sum(0)) rec = {} for i, e in enumerate(("naive", "mm_fd")): rec[e] = {"lambda": pt[i], "lambda_scan": summ["lambda_gc"][e], "se_jk": float(se[i]), "ci95": [pt[i] - 1.96 * se[i], pt[i] + 1.96 * se[i]], "jk_bias_corrected": float(a.groups * pt[i] - (a.groups - 1) * jk[:, i].mean())} dj = jk[:, 0] - jk[:, 1] # paired: naive minus MM-fd on the same kept rows sd = float(np.sqrt((a.groups - 1) / a.groups * ((dj - dj.mean()) ** 2).sum())) rec["naive_minus_mm_fd"] = {"diff": pt[0] - pt[1], "se_jk": sd, "ci95": [pt[0] - pt[1] - 1.96 * sd, pt[0] - pt[1] + 1.96 * sd]} rec["jk"] = jk.tolist() json.dump(rec, open(pf + ".tmp", "w")) os.replace(pf + ".tmp", pf) out["traits"][t] = rec print(t, {e: (round(rec[e]["lambda"], 3), round(rec[e]["lambda_scan"], 3), round(rec[e]["se_jk"], 3)) for e in ("naive", "mm_fd")}, flush=True) T = list(out["traits"]) out["summary"] = {e: {"median_se": float(np.median([out["traits"][t][e]["se_jk"] for t in T])), "n_ci_lower_gt_1_1": int(sum(out["traits"][t][e]["ci95"][0] > 1.1 for t in T)), "max_abs_point_minus_scan": float(max(abs(out["traits"][t][e]["lambda"] - out["traits"][t][e]["lambda_scan"]) for t in T))} for e in ("naive", "mm_fd")} d = [out["traits"][t]["naive"]["lambda"] - out["traits"][t]["mm_fd"]["lambda"] for t in T] out["summary"]["naive_minus_mm_fd"] = {"median": float(np.median(d)), "n_positive": int(sum(x > 0 for x in d)), "n_ci_lower_gt_0": int(sum(out["traits"][t]["naive_minus_mm_fd"]["ci95"][0] > 0 for t in T))} json.dump(out, open(a.out, "w"), indent=1) print(json.dumps(out["summary"]), "JKDONE", flush=True) if __name__ == "__main__": main()