File size: 9,333 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 184 185 186 187 188 189 190 191 192 193 194 | # MIT License, Bryan Cheng, 2026.
"""Architecture and genetic correlations (RESEARCH_PLAN 11.1, 11.2; E6).
11.1 Per primary trait: REML with the descent kernel and 8 function kernels (4 layer blocks x attention/MLP; block
kernels K_b = S_b / (d d^T) with d from the total expressed Gram, so sum_b K_b = K_func); likelihood-ratio test
against descent-only; BLUP accuracy on held-out descent families (5 folds by family) for function-only,
descent-only and covariates-only models.
11.2 Bivariate REML (one kernel at a time, eigen-rotated) for every pair of primary traits under the function and the
descent layer -> genetic correlation matrices G_f, G_d; phenotypic correlations P; G_do from validated loci
(calibration file: BH q < 0.05 on gamma_do z-scores over all tested (locus, trait) points).
python src/analysis/architecture.py --geno data/processed/qwen05 --pheno results/phenotypes/qwen05
--scan results/scans/qwen05 [--calib results/calibration/qwen05.json] --out results/e6/architecture_qwen05.json
"""
import argparse
import json
import os
import sys
import numpy as np
from scipy import optimize, 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 basis, bh, reml # noqa: E402
from src.run.scan_run import blocks_of # noqa: E402
def reml_eig(Y, X, D, U):
"""Multivariate REML for V = Sg (x) K + Se (x) I with K = U diag(D) U^T. Y [n, k]. Returns Sg, Se, nll."""
n, k = Y.shape
X = basis(X)
p = X.shape[1]
Yt, Xt = U.T @ Y, U.T @ X
m = k * (k + 1) // 2
tri = np.tril_indices(k)
def unpack(th):
Lg, Le = np.zeros((k, k)), np.zeros((k, k))
Lg[tri], Le[tri] = th[:m], th[m:]
return Lg @ Lg.T, Le @ Le.T + 1e-8 * np.eye(k)
def nll(th):
Sg, Se = unpack(th)
Vi = Sg[None] * D[:, None, None] + Se[None]
sgn, ld = np.linalg.slogdet(Vi)
if np.any(sgn <= 0):
return 1e20
Vinv = np.linalg.inv(Vi)
M = np.einsum("iab,ip,iq->apbq", Vinv, Xt, Xt).reshape(k * p, k * p)
v = np.einsum("iab,ip,ib->ap", Vinv, Xt, Yt).reshape(k * p)
try:
bh_ = np.linalg.solve(M, v).reshape(k, p)
except np.linalg.LinAlgError:
return 1e20
R = Yt - Xt @ bh_.T
return 0.5 * (ld.sum() + np.linalg.slogdet(M)[1] + np.einsum("ia,iab,ib->", R, Vinv, R))
C = np.cov(Y.T).reshape(k, k)
L0 = np.linalg.cholesky(0.5 * C + 1e-6 * np.eye(k))
th0 = np.concatenate([L0[tri], L0[tri]])
res = optimize.minimize(nll, th0, method="L-BFGS-B")
Sg, Se = unpack(res.x)
return Sg, Se, float(res.fun)
def blup_cv(y, X, K, fam, folds=5, seed=0):
"""Out-of-family BLUP accuracy (Pearson r over all held-out rows); K None = covariates only."""
ok = np.isfinite(y)
uf = np.unique(fam[ok])
rng = np.random.default_rng(seed)
fold_of = dict(zip(uf, rng.permutation(len(uf)) % folds))
pred = np.full(len(y), np.nan)
for f in range(folds):
te = ok & np.array([fold_of.get(x, -1) == f for x in fam])
tr = ok & ~te
Xb = basis(X[tr])
coef, *_ = np.linalg.lstsq(X[tr], y[tr], rcond=None)
if K is None:
pred[te] = X[te] @ coef
continue
s, V, _ = reml(y[tr], X[tr], [K[np.ix_(tr, tr)] + 1e-6 * np.eye(tr.sum())])
Vi = np.linalg.inv(V)
XtVi = X[tr].T @ Vi
beta = np.linalg.lstsq(XtVi @ X[tr], XtVi @ y[tr], rcond=None)[0]
pred[te] = X[te] @ beta + s[0] * K[np.ix_(te, tr)] @ (Vi @ (y[tr] - X[tr] @ beta))
del Xb
m = np.isfinite(pred) & ok
return float(np.corrcoef(pred[m], y[m])[0, 1])
def corr_from(S):
d = np.sqrt(np.clip(np.diag(S), 1e-300, None))
return S / d[:, None] / d[None]
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)
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"]])
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)]
d = np.sqrt(np.clip(np.diag(Sb.sum(0)), 1e-300, None))
Kb = [Sb[b] / d[:, None] / d[None] for b in range(8)]
Kd, Kf, X, fam = P["K_desc"], P["K_func"], P["X"], P["fam_d"]
out = {"n": n, "primary": prim, "varcomp": {}, "blup_r": {}}
parts = a.out + ".parts" # per-trait and per-row results, so a run that hits the time limit resumes
os.makedirs(parts, exist_ok=True)
for t in prim:
pf = os.path.join(parts, t + ".json")
if os.path.exists(pf):
r = json.load(open(pf))
out["varcomp"][t], out["blup_r"][t] = r["varcomp"], r["blup_r"]
continue
y = P["Yt"][:, P["traits"].index(t)]
ok = np.isfinite(y)
I = 1e-6 * np.eye(ok.sum())
sub = lambda K: K[np.ix_(ok, ok)] + I # noqa: E731
s1, _, f1 = reml(y[ok], X[ok], [sub(Kd)] + [sub(K) for K in Kb])
s0, _, f0 = reml(y[ok], X[ok], [sub(Kd)])
sf, _, ff = reml(y[ok], X[ok], [sub(Kf), sub(Kd)])
lrt = max(0.0, 2 * (f0 - f1))
tot = s1.sum()
out["varcomp"][t] = {"share_descent": s1[0] / tot, "share_blocks": (s1[1:-1] / tot).tolist(),
"share_resid": s1[-1] / tot, "lrt_function_vs_descent": lrt,
"p_lrt_chi2_8_conservative": float(stats.chi2.sf(lrt, 8)),
"two_layer": {"share_function": sf[0] / sf.sum(), "share_descent": sf[1] / sf.sum()},
"descent_only_share": s0[0] / s0.sum()}
out["blup_r"][t] = {"function": blup_cv(y, X, Kf, fam), "descent": blup_cv(y, X, Kd, fam),
"covariates_only": blup_cv(y, X, None, fam)}
print(t, {k: round(v, 3) for k, v in out["blup_r"][t].items()}, "lrt", round(lrt, 1), flush=True)
json.dump({"varcomp": out["varcomp"][t], "blup_r": out["blup_r"][t]}, open(pf + ".tmp", "w"), default=float)
os.replace(pf + ".tmp", pf)
# 11.2 genetic correlations
Y = np.column_stack([P["Yt"][:, P["traits"].index(t)] for t in prim])
k = len(prim)
Gm = {"function": np.eye(k), "descent": np.eye(k)}
for lay, K in (("function", Kf), ("descent", Kd)):
Dall, Uall = np.linalg.eigh(K)
for i in range(k - 1):
rf = os.path.join(parts, f"G_{lay}_{i}.npy")
if os.path.exists(rf):
row = np.load(rf)
else:
row = np.full(k, np.nan)
for j in range(i + 1, k):
ok = np.isfinite(Y[:, i]) & np.isfinite(Y[:, j])
D, U = (Dall, Uall) if ok.all() else np.linalg.eigh(K[np.ix_(ok, ok)])
Sg, Se, _ = reml_eig(Y[ok][:, [i, j]], X[ok], np.clip(D, 0, None), U)
row[j] = Sg[0, 1] / np.sqrt(max(Sg[0, 0] * Sg[1, 1], 1e-300))
np.save(rf + ".tmp.npy", row)
os.replace(rf + ".tmp.npy", rf)
Gm[lay][i, i + 1:] = Gm[lay][i + 1:, i] = row[i + 1:]
print("G", lay, "done", flush=True)
Pm = np.ma.corrcoef(np.ma.masked_invalid(Y), rowvar=False).filled(np.nan)
out["G_function"], out["G_descent"], out["P"] = Gm["function"].tolist(), Gm["descent"].tolist(), Pm.tolist()
iu = np.triu_indices(k, 1)
out["corr_offdiag"] = {"Gf_P": float(np.corrcoef(Gm["function"][iu], Pm[iu])[0, 1]),
"Gf_Gd": float(np.corrcoef(Gm["function"][iu], Gm["descent"][iu])[0, 1])}
if a.calib and os.path.exists(a.calib):
C = json.load(open(a.calib))["per_direction"]
rows = [v for v in C.values() if v["kind"] == "locus" and v.get("source")]
Gam = np.array([[v["traits"][t]["gamma_do"] for t in prim] for v in rows], float)
Var = np.array([[v["traits"][t]["var_do"] for t in prim] for v in rows], float)
z = Gam / np.sqrt(np.maximum(Var, 1e-300))
pz = 2 * stats.norm.sf(np.abs(z)).ravel()
val = bh(np.where(np.isfinite(pz), pz, 1.0)).reshape(z.shape).any(1)
if val.sum() >= 2:
Gdo = corr_from(np.nan_to_num(Gam[val]).T @ np.nan_to_num(Gam[val]))
out["G_do"] = Gdo.tolist()
out["n_validated_loci"] = int(val.sum())
out["corr_offdiag"].update({"Gdo_Gf": float(np.corrcoef(Gdo[iu], Gm["function"][iu])[0, 1]),
"Gdo_P": float(np.corrcoef(Gdo[iu], Pm[iu])[0, 1])})
os.makedirs(os.path.dirname(a.out), exist_ok=True)
json.dump(out, open(a.out, "w"), indent=1, default=float)
print(json.dumps(out["corr_offdiag"]), flush=True)
if __name__ == "__main__":
main()
|