File size: 9,458 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 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 | # MIT License, Bryan Cheng, 2026.
"""Prediction and portability (RESEARCH_PLAN 12; E7).
Predictors, each with 20 tuning configurations chosen on validation families inside the training fold:
ridge_raw kernel ridge on the raw-weight Gram (= ridge on the full raw coordinates), lambda grid
ridge_exp kernel ridge on the expressed Gram (= ridge on expressed coordinates), lambda grid
spectral ridge on per-module log update norms (raw and expressed) plus log rank, lambda grid
knn_func mean of the k nearest training adapters by K_func, k grid
blup_f REML BLUP with K_func (no tuning; variance components are the tuning)
mm_score sum of MM-f (single function kernel) locus effects over loci with p below a threshold, threshold grid
causal sum of gamma_do x standardised genotype over validated loci (needs --calib; no tuning)
Splits: random, descent-, recipe- and author-disjoint (5 folds each). Accuracy = Pearson r on transformed traits, overall
and in 5 quantile bins of the maximum K_desc and K_func of each test adapter to its training set.
python src/analysis/predict.py --geno data/processed/qwen05 --pheno results/phenotypes/qwen05
--scan results/scans/qwen05 [--calib results/calibration/qwen05.json] --out results/e7/predict_qwen05.json
"""
import argparse
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
from src.analysis.scan import bh, gls_scan, reml # noqa: E402
LAMS = np.logspace(-4, 2, 20)
KS = np.unique(np.round(np.logspace(0, np.log10(60), 20)).astype(int))
PTHR = np.logspace(-8, -0.3, 20)
def r_of(a, b):
m = np.isfinite(a) & np.isfinite(b)
return float(np.corrcoef(a[m], b[m])[0, 1]) if m.sum() > 3 and np.std(a[m]) > 0 else np.nan
def kridge(K, tr, te, y, lam):
Ktr = K[np.ix_(tr, tr)]
s = lam * np.mean(np.diag(Ktr))
mu = y[tr].mean()
alpha = np.linalg.solve(Ktr + s * np.eye(len(tr)), y[tr] - mu)
return K[np.ix_(te, tr)] @ alpha + mu
def knn(K, tr, te, y, k):
S = K[np.ix_(te, tr)]
idx = np.argsort(-S, 1)[:, :k]
return y[tr][idx].mean(1)
def ridge(F, tr, te, y, lam):
mu, sd = F[tr].mean(0), F[tr].std(0) + 1e-12
A, B = (F[tr] - mu) / sd, (F[te] - mu) / sd
w = np.linalg.solve(A.T @ A + lam * len(tr) * np.eye(A.shape[1]), A.T @ (y[tr] - y[tr].mean()))
return B @ w + y[tr].mean()
def blup(K, X, tr, te, y):
s, V, _ = reml(y[tr], X[tr], [K[np.ix_(tr, tr)] + 1e-6 * np.eye(len(tr))])
Vi = np.linalg.inv(V)
XtVi = X[tr].T @ Vi
beta = np.linalg.lstsq(XtVi @ X[tr], XtVi @ y[tr], rcond=None)[0]
return X[te] @ beta + s[0] * K[np.ix_(te, tr)] @ (Vi @ (y[tr] - X[tr] @ beta)), V
def mm_fit(K, X, G, tr, y, V=None):
if V is None:
_, V, _ = reml(y[tr], X[tr], [K[np.ix_(tr, tr)] + 1e-6 * np.eye(len(tr))])
b, _, p = gls_scan(y[tr], G[tr] - G[tr].mean(0), X[tr], V)
return b, p
def inner_split(groups, tr, seed):
g = np.unique(groups[tr])
rng = np.random.default_rng(seed)
val_g = set(rng.permutation(g)[: max(1, len(g) // 5)].tolist())
va = np.array([i for i in tr if groups[i] in val_g])
fit = np.array([i for i in tr if groups[i] not in val_g])
return fit, va
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("--calib", default=None)
ap.add_argument("--out", required=True)
ap.add_argument("--recipe_threshold", type=float, default=None)
ap.add_argument("--seed", type=int, default=0)
a = ap.parse_args()
P = build(a.geno, a.pheno, recipe_threshold=a.recipe_threshold)
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"]])
Kz = np.load(os.path.join(a.geno, "K.npz"))
Graw, Gexp = Kz["G_raw"][np.ix_(keep, keep)], Kz["G_exp"][np.ix_(keep, keep)]
gr = np.load(os.path.join(a.geno, "grams_raw.npy"), mmap_mode="r")
ge = np.load(os.path.join(a.geno, "grams_exp.npy"), mmap_mode="r")
pk = np.where(keep)[0]
F = np.column_stack([np.log(np.diag(np.asarray(gr[m]))[pk] + 1e-12) for m in range(gr.shape[0])] +
[np.log(np.diag(np.asarray(ge[m]))[pk] + 1e-12) for m in range(ge.shape[0])] +
[np.log(P["rmax"])])
Kd, Kf, X, G = P["K_desc"], P["K_func"], P["X"], P["G"]
groups = {"random": np.random.default_rng(a.seed).permutation(n) % 5, "descent": P["fam_d"], "recipe": P["fam_r"],
"author": np.unique(P["authors"], return_inverse=True)[1]}
causal = None
if a.calib and os.path.exists(a.calib):
C = json.load(open(a.calib))["per_direction"]
loci = json.load(open(os.path.join(a.scan, "loci.json")))
plan_ids = {(l["module"], l["l"]): i for i, l in enumerate(loci)}
rows = [(plan_ids[(v["module"], v["l"])], v) for v in C.values() if v["kind"] == "locus" and v.get("source")]
causal = {}
for t in prim:
gam = np.array([v["traits"][t]["gamma_do"] for _, v in rows], float)
var = np.array([v["traits"][t]["var_do"] for _, v in rows], float)
pz = 2 * stats.norm.sf(np.abs(gam / np.sqrt(np.maximum(var, 1e-300))))
val = bh(np.where(np.isfinite(pz), pz, 1.0))
causal[t] = [(j, g / loci[j]["sigma"]) for (j, _), g, v_ in zip(rows, gam, val) if v_]
out = {"n": n, "results": {}, "bins": {}}
parts = a.out + ".parts" # one file per (split, trait), so a run that hits the time limit resumes
os.makedirs(parts, exist_ok=True)
for split, grp in groups.items():
ug = np.unique(grp)
fold = dict(zip(ug, np.random.default_rng(a.seed + 1).permutation(len(ug)) % 5))
fo = np.array([fold[g] for g in grp])
for t in prim:
pf = os.path.join(parts, f"{split}__{t}{'__calib' if causal else ''}.json") # causal column only with --calib
if os.path.exists(pf):
r = json.load(open(pf))
out["results"].setdefault(split, {})[t] = r["results"]
out["bins"].setdefault(split, {})[t] = r["bins"]
continue
y = P["Yt"][:, P["traits"].index(t)]
pred = {k: np.full(n, np.nan) for k in ("ridge_raw", "ridge_exp", "spectral", "knn_func", "blup_f",
"mm_score", "causal")}
maxd, maxf = np.full(n, np.nan), np.full(n, np.nan)
for f in range(5):
te = np.where((fo == f) & np.isfinite(y))[0]
tr = np.where((fo != f) & np.isfinite(y))[0]
if len(te) < 3:
continue
maxd[te], maxf[te] = Kd[np.ix_(te, tr)].max(1), Kf[np.ix_(te, tr)].max(1)
fit, va = inner_split(grp if split != "random" else P["fam_d"], tr, a.seed + f)
for name, K in (("ridge_raw", Graw), ("ridge_exp", Gexp)):
best = max(LAMS, key=lambda l: np.nan_to_num(r_of(kridge(K, fit, va, y, l), y[va]), nan=-2))
pred[name][te] = kridge(K, tr, te, y, best)
best = max(LAMS, key=lambda l: np.nan_to_num(r_of(ridge(F, fit, va, y, l), y[va]), nan=-2))
pred["spectral"][te] = ridge(F, tr, te, y, best)
best = max(KS, key=lambda k: np.nan_to_num(r_of(knn(Kf, fit, va, y, min(k, len(fit))), y[va]), nan=-2))
pred["knn_func"][te] = knn(Kf, tr, te, y, min(best, len(tr)))
pred["blup_f"][te], _ = blup(Kf, X, tr, te, y)
b, p = mm_fit(Kf, X, G, fit, y)
Gc = G - G[fit].mean(0)
best = max(PTHR, key=lambda th: np.nan_to_num(r_of(Gc[va] @ np.where(p < th, b, 0), y[va]), nan=-2))
b, p = mm_fit(Kf, X, G, tr, y)
pred["mm_score"][te] = (G[te] - G[tr].mean(0)) @ np.where(p < best, b, 0)
if causal and causal.get(t):
js, ws = zip(*causal[t])
pred["causal"][te] = (G[np.ix_(te, list(js))] - G[np.ix_(tr, list(js))].mean(0)) @ np.array(ws)
out["results"].setdefault(split, {})[t] = {k: r_of(v, y) for k, v in pred.items()}
for nm, mx in (("max_K_desc", maxd), ("max_K_func", maxf)):
m = np.isfinite(mx)
edges = np.quantile(mx[m], np.linspace(0, 1, 6))
b_ = np.clip(np.searchsorted(edges, mx, side="right") - 1, 0, 4)
out["bins"].setdefault(split, {}).setdefault(t, {})[nm] = {
"edges": edges.tolist(),
"r": {k: [r_of(v[m & (b_ == i)], y[m & (b_ == i)]) for i in range(5)] for k, v in pred.items()}}
json.dump({"results": out["results"][split][t], "bins": out["bins"][split][t]}, open(pf + ".tmp", "w"), default=float)
os.replace(pf + ".tmp", pf)
print(split, t, {k: round(v, 3) for k, v in out["results"][split][t].items() if np.isfinite(v)}, flush=True)
os.makedirs(os.path.dirname(a.out), exist_ok=True)
json.dump(out, open(a.out, "w"), indent=1, default=float)
print("PREDICTDONE", flush=True)
if __name__ == "__main__":
main()
|