File size: 14,063 Bytes
a4054b7 | 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 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 | # 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 beta_obs on gamma_do 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.linspace(-10, 10, 801)
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(B[e][ok], Vb[e][ok], X[ok, 0], X[ok, 1]) 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(B[e][ii], Vb[e][ii], X[ii, 0], X[ii, 1])
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(B[e][m], Vb[e][m], X[m, 0], X[m, 1]) 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(B[e][fm], Vb[e][fm], X[fm, 0], X[fm, 1]) 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()
|