Download code/src/analysis/calibrate.py from bryan7264/lorapop: direct link, hf CLI and curl.
- Browser
- Download file 14.2 kB
-
https://huggingface.co/datasets/bryan7264/lorapop/resolve/main/code/src/analysis/calibrate.py
- Command line
-
hf download hf://datasets/bryan7264/lorapop/code/src/analysis/calibrate.py
-
curl -L -o calibrate.py https://huggingface.co/datasets/bryan7264/lorapop/resolve/main/code/src/analysis/calibrate.py
14.2 kB
| # MIT License, Bryan Cheng, 2026. | |
| """Interventional calibration of observational estimators (RESEARCH_PLAN 8.4, 14.1, 14.2, 16.3-16.5). | |
| Units: every effect is in population-SD of the transformed trait per population-SD of the genotype coordinate. | |
| Interventional phenotypes are mapped through the population's rank-based inverse-normal transform by monotone | |
| interpolation of its empirical CDF (plan 4.4; values outside the population range are clamped and counted). | |
| gamma_do = mean over adapter backgrounds of the OLS slope over doses_bg (dose c = c x SD of g); its variance from 200 | |
| bootstrap resamples of backgrounds. beta_obs = scan estimate on the estimation set E times SD of g; its variance from | |
| --obs_boot (family bootstrap file) when given, else the model-based SE. | |
| kappa = errors-in-variables (Deming, through the origin) slope of gamma_do on beta_obs (interventional on observational, | |
| PROPOSAL; D-043) over all (tested locus, primary | |
| trait) points; CI from 2,000 block-bootstrap resamples of modules; Delta_X = |kappa_X - 1| - |kappa_naive - 1| paired. | |
| Shared c = 0 references (intervene.py --shared_zero, D-031): __ref__*.json supply c = 0 for any background or knockout | |
| carrier that a direction did not measure itself, only when the reference used the same generation half and the same hardware | |
| configuration (record "hw", D-035); directions without a matching reference contribute no c = 0 points (counted). | |
| python src/analysis/calibrate.py --scan results/scans/qwen05 --geno data/processed/qwen05 | |
| --pheno results/phenotypes/qwen05 --plan results/interventions/plan_qwen05.json | |
| --interv results/interventions/qwen05 --out results/calibration/qwen05.json | |
| """ | |
| import argparse | |
| import glob | |
| import json | |
| import os | |
| import sys | |
| import numpy as np | |
| from scipy import stats | |
| sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "..")) | |
| from src.analysis.population import build # noqa: E402 | |
| EST = ["naive", "pc", "mm_f", "mm_fd", "wf_d", "wf_r", "dup_afe"] | |
| SUB = {"full": 0, "D": 1, "E": 2} | |
| GRID = np.tan(np.linspace(-np.pi / 2, np.pi / 2, 803)[1:-1]) # every slope (k = tan theta), finer near 0; D-043 | |
| def ecdf_map(ypop): | |
| y = np.sort(ypop[np.isfinite(ypop)]) | |
| n = len(y) | |
| u, inv = np.unique(y, return_inverse=True) | |
| avg_rank = np.bincount(inv, np.arange(1, n + 1)) / np.bincount(inv) | |
| zu = stats.norm.ppf((avg_rank - 0.375) / (n + 0.25)) | |
| return lambda v: np.interp(v, u, zu), (u[0], u[-1]) | |
| def deming0(b, sb2, x, sx2): | |
| """ML errors-in-variables slope through the origin: argmin_k sum (b - k x)^2 / (sb2 + k^2 sx2).""" | |
| k = GRID[:, None] | |
| f = np.sum((b[None] - k * x[None]) ** 2 / (sb2[None] + k ** 2 * sx2[None]), 1) | |
| i = int(np.argmin(f)) | |
| lo, hi = GRID[max(i - 1, 0)], GRID[min(i + 1, len(GRID) - 1)] | |
| for _ in range(40): # golden-section refinement inside the bracket | |
| m1, m2 = lo + 0.382 * (hi - lo), lo + 0.618 * (hi - lo) | |
| f1 = np.sum((b - m1 * x) ** 2 / (sb2 + m1 ** 2 * sx2)) | |
| f2 = np.sum((b - m2 * x) ** 2 / (sb2 + m2 ** 2 * sx2)) | |
| lo, hi = (lo, m2) if f1 < f2 else (m1, hi) | |
| return 0.5 * (lo + hi) | |
| def slope(c, z): | |
| c, z = np.asarray(c, float), np.asarray(z, float) | |
| ok = np.isfinite(z) | |
| if ok.sum() < 2: | |
| return np.nan | |
| cc = c[ok] - c[ok].mean() | |
| return float(cc @ (z[ok] - z[ok].mean()) / (cc @ cc)) | |
| def boot_p(d): | |
| d = d[np.isfinite(d)] | |
| return float(min(1.0, 2 * min((d <= 0).mean(), (d >= 0).mean()))) if len(d) else np.nan | |
| def holm(ps): | |
| keys = sorted(ps, key=lambda k: ps[k]) | |
| out, run = {}, 0.0 | |
| for i, k in enumerate(keys): | |
| run = max(run, min(1.0, (len(keys) - i) * ps[k])) | |
| out[k] = run | |
| return out | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--scan", required=True) | |
| ap.add_argument("--geno", required=True) | |
| ap.add_argument("--pheno", required=True) | |
| ap.add_argument("--plan", required=True) | |
| ap.add_argument("--interv", required=True) | |
| ap.add_argument("--out", required=True) | |
| ap.add_argument("--obs_boot", default=None, help="npz with var[est, trait, locus] from a family bootstrap") | |
| ap.add_argument("--subset", default="E", choices=list(SUB)) | |
| ap.add_argument("--n_boot", type=int, default=2000) | |
| ap.add_argument("--seed", type=int, default=0) | |
| ap.add_argument("--bg_subset", type=int, default=0, help="D-037: gamma_do from the first k backgrounds only (matched raw vs expressed); 0 = all") | |
| a = ap.parse_args() | |
| rng = np.random.default_rng(a.seed) | |
| plan = json.load(open(a.plan)) | |
| prim = json.load(open(os.path.join(a.scan, "primary_traits.json")))["primary"] | |
| loci = json.load(open(os.path.join(a.scan, "loci.json"))) | |
| P = build(a.geno, a.pheno) | |
| maps = {t: ecdf_map(P["Y"][0, :, P["traits"].index(t)]) for t in prim} | |
| scans = {t: np.load(os.path.join(a.scan, f"{t}.npz")) for t in prim} | |
| ob = np.load(a.obs_boot) if a.obs_boot else None | |
| bgs, dbg = plan["backgrounds"], plan["doses_bg"] | |
| if a.bg_subset: | |
| bgs = bgs[:a.bg_subset] | |
| clamp, n_val = 0, 0 | |
| per_dir = {} | |
| refs = {} # (gen_half, hw) -> background -> combo (D-031, D-035) | |
| for f in sorted(glob.glob(os.path.join(a.interv, "__ref__*.json"))): | |
| r = json.load(open(f)) | |
| for cmb in r["combos"]: | |
| refs.setdefault((r.get("gen_half", -1), r.get("hw", "")), {})[cmb["background"]] = cmb | |
| n_ref_used, n_ref_missing = 0, 0 | |
| for d in plan["directions"]: | |
| fn = os.path.join(a.interv, d["id"] + ".json") | |
| if not os.path.exists(fn): | |
| continue | |
| rec = json.load(open(fn)) | |
| ref = refs.get((rec.get("gen_half", -1), rec.get("hw", "")), {}) | |
| out = {"kind": d["kind"], "module": d["module"], "l": d["l"], "source": d.get("source"), | |
| "control_of": d.get("control_of"), "sigma": rec["sigma"], "traits": {}} | |
| for t in prim: | |
| f, (lo, hi) = maps[t] | |
| def z(cmb): | |
| nonlocal clamp, n_val | |
| v = cmb["traits"].get(t) | |
| v = np.nan if v is None else v[0] | |
| if np.isfinite(v): | |
| n_val += 1 | |
| clamp += int(v < lo or v > hi) | |
| return float(f(v)) if np.isfinite(v) else np.nan | |
| by = {} | |
| for cmb in rec["combos"]: | |
| by.setdefault(cmb["background"], []).append((cmb["dose"], z(cmb))) | |
| for b in list(by): | |
| if not any(c == 0 for c, _ in by[b]): | |
| if b in ref: | |
| by[b].append((0.0, z(ref[b]))) | |
| n_ref_used += 1 | |
| else: | |
| n_ref_missing += 1 | |
| sl = np.array([slope(*zip(*sorted(by[b]))) if b in by else np.nan for b in bgs]) | |
| sl = sl[np.isfinite(sl)] | |
| boots = [sl[rng.integers(0, len(sl), len(sl))].mean() for _ in range(200)] if len(sl) > 1 else [np.nan] | |
| base = sorted(by.get("__base__", [])) | |
| bpts = [(c, v) for c, v in base if c in dbg] | |
| ko = [] | |
| for n, gm in d.get("knockout_carriers", []): | |
| pts = dict(by.get(f"KO::{n}", [])) | |
| if 0.0 in pts and -float(gm) in pts: | |
| ko.append((float(gm), pts[-float(gm)] - pts[0.0])) | |
| out["traits"][t] = {"gamma_do": float(sl.mean()) if len(sl) else np.nan, "var_do": float(np.var(boots)), | |
| "n_bg": int(len(sl)), "gamma_base": slope(*zip(*bpts)) if len(bpts) > 1 else np.nan, | |
| "base_curve": base, "ko": ko} | |
| per_dir[d["id"]] = out | |
| # observational effects for tested loci (kind locus with a selection source) | |
| tested = [k for k, v in per_dir.items() if v["kind"] == "locus" and v["source"]] | |
| lidx = {k: next(d["locus_idx"] for d in plan["directions"] if d["id"] == k) for k in tested} | |
| rows = [] # (dir id, trait, module) | |
| X = [] # gamma_do, var | |
| B = {e: [] for e in EST} | |
| Vb = {e: [] for e in EST} | |
| for k in tested: | |
| j = lidx[k] | |
| s = loci[j]["sigma"] | |
| for ti, t in enumerate(prim): | |
| tr = per_dir[k]["traits"][t] | |
| rows.append((k, t, per_dir[k]["module"])) | |
| X.append((tr["gamma_do"], tr["var_do"])) | |
| for ei, e in enumerate(EST): | |
| B[e].append(scans[t]["beta"][ei, SUB[a.subset], j] * s) | |
| v = ob["var"][ei, ti, j] if ob is not None else scans[t]["se"][ei, SUB[a.subset], j] ** 2 | |
| Vb[e].append(v * s * s) | |
| X = np.array(X, float).reshape(-1, 2) | |
| B = {e: np.array(v, float) for e, v in B.items()} | |
| Vb = {e: np.array(v, float) for e, v in Vb.items()} | |
| ok = np.isfinite(X).all(1) & np.all([np.isfinite(B[e]) & np.isfinite(Vb[e]) for e in EST], 0) | |
| mods = np.array([r[2] for r in rows]) | |
| tr_of = np.array([r[1] for r in rows]) | |
| res = {"n_points": int(ok.sum()), "n_tested_loci": len(tested), "n_directions_measured": len(per_dir), | |
| "subset": a.subset, "bg_subset": a.bg_subset, "obs_variance": "family bootstrap" if ob is not None else "model-based SE", | |
| "share_clamped": clamp / max(n_val, 1), "n_zero_points_from_refs": n_ref_used, | |
| "n_zero_points_missing": n_ref_missing, | |
| "estimators": {}} | |
| if ok.sum() >= 3: | |
| kap = {e: deming0(X[ok, 0], X[ok, 1], B[e][ok], Vb[e][ok]) for e in EST} | |
| umods = np.unique(mods[ok]) | |
| idx_of = {m: np.where(ok & (mods == m))[0] for m in umods} | |
| bk = {e: np.empty(a.n_boot) for e in EST} | |
| for bi in range(a.n_boot): | |
| ii = np.concatenate([idx_of[m] for m in rng.choice(umods, len(umods))]) | |
| for e in EST: | |
| bk[e][bi] = deming0(X[ii, 0], X[ii, 1], B[e][ii], Vb[e][ii]) | |
| delta = {e: np.abs(bk[e] - 1) - np.abs(bk["naive"] - 1) for e in EST if e != "naive"} | |
| for e in EST: | |
| pt_tr = {} | |
| for t in prim: | |
| m = ok & (tr_of == t) | |
| pt_tr[t] = deming0(X[m, 0], X[m, 1], B[e][m], Vb[e][m]) if m.sum() >= 3 else None | |
| fm = ok & np.array([per_dir[r[0]]["source"].startswith("fdr") for r in rows]) | |
| res["estimators"][e] = {"kappa": kap[e], "ci95": np.nanpercentile(bk[e], [2.5, 97.5]).tolist(), | |
| "kappa_by_trait": pt_tr, "n_points_fdr_only": int(fm.sum()), | |
| "kappa_fdr_only": deming0(X[fm, 0], X[fm, 1], B[e][fm], Vb[e][fm]) if fm.sum() >= 3 else None, | |
| "r_obs_do": float(np.corrcoef(B[e][ok], X[ok, 0])[0, 1])} | |
| if e != "naive": | |
| d0 = abs(kap[e] - 1) - abs(kap["naive"] - 1) | |
| res["estimators"][e].update({"delta_vs_naive": d0, "delta_ci95": np.nanpercentile(delta[e], [2.5, 97.5]).tolist(), | |
| "delta_p": boot_p(delta[e])}) | |
| sec = holm({e: res["estimators"][e]["delta_p"] for e in ("wf_d", "mm_f", "pc", "mm_fd")}) | |
| for e, p in sec.items(): | |
| res["estimators"][e]["delta_p_holm4"] = p | |
| summ = json.load(open(os.path.join(a.scan, "summary.json"))) | |
| lam_naive = max(summ["traits"][t]["lambda_gc"]["naive"] for t in prim) | |
| kn, km = kap["naive"], kap["mm_fd"] | |
| dci = res["estimators"]["mm_fd"]["delta_ci95"] | |
| res["hypotheses"] = {"H2": {"max_lambda_naive": lam_naive, "kappa_naive": kn, | |
| "supported": bool(lam_naive > 1.1 or not 0.8 <= kn <= 1.2)}, | |
| "H3": {"kappa_mm_fd": km, "delta_ci95": dci, "supported": bool(0.8 <= km <= 1.2 and dci[1] < 0)}} | |
| # controls and base-background slopes | |
| ctl = {} | |
| for k, v in per_dir.items(): | |
| lab = v["kind"] if v["kind"] != "locus" else ("tested" if v["source"] else "hv_control") | |
| g = [abs(v["traits"][t]["gamma_do"]) for t in prim if np.isfinite(v["traits"][t]["gamma_do"])] | |
| gb = [abs(v["traits"][t]["gamma_base"]) for t in prim if np.isfinite(v["traits"][t]["gamma_base"])] | |
| ctl.setdefault(lab, {"abs_gamma_bg": [], "abs_gamma_base": []}) | |
| ctl[lab]["abs_gamma_bg"] += g | |
| ctl[lab]["abs_gamma_base"] += gb | |
| res["controls"] = {k: {"n": len(v["abs_gamma_bg"]), "mean_abs_gamma_bg": float(np.mean(v["abs_gamma_bg"])) if v["abs_gamma_bg"] else None, | |
| "mean_abs_gamma_base": float(np.mean(v["abs_gamma_base"])) if v["abs_gamma_base"] else None} | |
| for k, v in ctl.items()} | |
| gb_all = [(per_dir[k]["traits"][t]["gamma_base"], per_dir[k]["traits"][t]["gamma_do"]) for k in tested for t in prim] | |
| gb_all = np.array([x for x in gb_all if np.all(np.isfinite(x))]).reshape(-1, 2) | |
| res["base_vs_background_r"] = float(np.corrcoef(gb_all.T)[0, 1]) if len(gb_all) > 2 else None | |
| # knockouts: measured change vs predicted -(g - mean) x effect per unit g | |
| kor = {"do": [], **{e: [] for e in EST}} | |
| for k in tested: | |
| j, s = lidx[k], loci[lidx[k]]["sigma"] | |
| for t in prim: | |
| tr = per_dir[k]["traits"][t] | |
| for gm, dz in tr["ko"]: | |
| if not np.isfinite(dz): | |
| continue | |
| kor["do"].append((-gm / s * tr["gamma_do"], dz)) | |
| for ei, e in enumerate(EST): | |
| kor[e].append((-gm * scans[t]["beta"][ei, SUB[a.subset], j], dz)) | |
| res["knockouts"] = {} | |
| for e, pts in kor.items(): | |
| pts = np.array([p for p in pts if np.all(np.isfinite(p))]).reshape(-1, 2) | |
| if len(pts) > 2: | |
| res["knockouts"][e] = {"n": len(pts), "r": float(np.corrcoef(pts.T)[0, 1]), | |
| "slope_measured_on_predicted": float(np.polyfit(pts[:, 0], pts[:, 1], 1)[0])} | |
| os.makedirs(os.path.dirname(a.out), exist_ok=True) | |
| json.dump({"summary": res, "per_direction": per_dir}, open(a.out, "w"), indent=1, | |
| default=lambda o: None if isinstance(o, float) and not np.isfinite(o) else float(o)) | |
| print(json.dumps({k: v for k, v in res.items() if k in ("n_points", "hypotheses", "share_clamped")}, default=str)) | |
| for e, v in res["estimators"].items(): | |
| print(e, round(v["kappa"], 3), [round(x, 3) for x in v["ci95"]], flush=True) | |
| if __name__ == "__main__": | |
| main() | |