File size: 6,532 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 | # MIT License, Bryan Cheng, 2026.
"""Association scans (RESEARCH_PLAN 7): naive, PC, MM-f (leave-block-out function kernel), MM-fd (+ descent kernel),
WF-d / WF-r (within families), DUP-AFE (duplicates removed + author fixed effects).
All estimators are vectorised over loci: covariates are partialled out (Frisch-Waugh-Lovell), mixed models are fitted
once per trait (and per left-out block) by REML under the null, and loci are tested by GLS after whitening with V^{-1/2}.
"""
import numpy as np
from scipy import optimize, stats
def basis(X, tol=1e-10):
"""Orthonormal basis of the column space of X (drops dependent or all-zero columns)."""
U, s, _ = np.linalg.svd(X, full_matrices=False)
return U[:, s > tol * max(s.max(), 1e-300)]
def resid(M, X):
"""Residuals of the columns of M after OLS on X (rank-safe)."""
Q = basis(X)
return M - Q @ (Q.T @ M)
def ols_scan(y, G, X):
"""Per-locus OLS of y on [X, g]: returns beta, se, p (two-sided t)."""
n, p = len(y), basis(X).shape[1]
yr = resid(y[:, None], X)[:, 0]
Gr = resid(G, X)
ss = (Gr ** 2).sum(0)
ok = ss > 1e-12 * max(ss.max(), 1e-300)
beta = np.where(ok, Gr.T @ yr / np.where(ok, ss, 1), np.nan)
rss = (yr ** 2).sum() - np.where(ok, beta ** 2 * ss, 0)
df = n - p - 1
se = np.sqrt(np.maximum(rss, 1e-300) / df / np.where(ok, ss, 1))
se = np.where(ok, se, np.nan)
pval = 2 * stats.t.sf(np.abs(beta / se), df)
return beta, se, pval
def reml(y, X, Ks, init=None):
"""REML for V = sum_k s_k K_k + s_e I. Returns variance components (len(Ks)+1,) and V."""
n = len(y)
X = basis(X)
mats = list(Ks) + [np.eye(n)]
vy = float(np.var(resid(y[:, None], X)))
def nll(logs):
s = np.exp(logs)
V = sum(si * M for si, M in zip(s, mats))
try:
L = np.linalg.cholesky(V)
except np.linalg.LinAlgError:
return 1e20
Li_X = np.linalg.solve(L, X)
Li_y = np.linalg.solve(L, y)
XtVX = Li_X.T @ Li_X
b = np.linalg.solve(XtVX, Li_X.T @ Li_y)
r = Li_y - Li_X @ b
sign, ld = np.linalg.slogdet(XtVX)
return 0.5 * (2 * np.log(np.diag(L)).sum() + ld + r @ r)
x0 = np.log(np.full(len(mats), vy / len(mats))) if init is None else np.log(np.maximum(init, 1e-6 * vy))
res = optimize.minimize(nll, x0, method="L-BFGS-B", bounds=[(np.log(1e-8 * vy + 1e-12), np.log(10 * vy + 1e-12))] * len(mats))
s = np.exp(res.x)
V = sum(si * M for si, M in zip(s, mats))
return s, V, float(res.fun)
def reml_eig1(y, X, ev, Q):
"""Exact fast path of reml() for one kernel: V = s1 K + s2 I with K = Q diag(ev) Q^T (eigendecomposed once and reused
across traits). Same objective, start and bounds as reml(); each evaluation is O(n p^2). Returns (s, W, fun) with the
whitening matrix W = diag(s1 ev + s2)^-1/2 Q^T (W^T W = V^-1; GLS is invariant to the choice of whitening)."""
Xb = basis(X)
vy = float(np.var(resid(y[:, None], Xb)))
Xt, yt = Q.T @ Xb, Q.T @ y
def nll(logs):
s1, s2 = np.exp(logs)
d = s1 * ev + s2
if np.any(d <= 0):
return 1e20
w = 1.0 / d
XtVX = (Xt * w[:, None]).T @ Xt
b = np.linalg.solve(XtVX, (Xt * w[:, None]).T @ yt)
r = yt - Xt @ b
_, ld = np.linalg.slogdet(XtVX)
return 0.5 * (np.log(d).sum() + ld + (r * r * w).sum())
x0 = np.log(np.full(2, vy / 2))
res = optimize.minimize(nll, x0, method="L-BFGS-B", bounds=[(np.log(1e-8 * vy + 1e-12), np.log(10 * vy + 1e-12))] * 2)
s = np.exp(res.x)
W = (Q / np.sqrt(s[0] * ev + s[1])[None, :]).T
return s, W, float(res.fun)
def gls_scan(y, G, X, V=None, W=None):
"""GLS per locus with fixed V (estimated under the null); or with a whitening matrix W (W^T W = V^-1)."""
X = basis(X)
if W is not None:
yw, Xw, Gw = W @ y, W @ X, W @ G
else:
L = np.linalg.cholesky(V)
yw = np.linalg.solve(L, y)
Xw = np.linalg.solve(L, X)
Gw = np.linalg.solve(L, G)
n, p = X.shape
yr = resid(yw[:, None], Xw)[:, 0]
Gr = resid(Gw, Xw)
ss = (Gr ** 2).sum(0)
beta = Gr.T @ yr / np.maximum(ss, 1e-300)
# V is scaled to the residual variance by REML, so the Wald statistic uses unit residual variance
sigma2 = ((yr ** 2).sum() - beta ** 2 * ss) / (n - p - 1)
se = np.sqrt(np.maximum(sigma2, 1e-300) / np.maximum(ss, 1e-300))
pval = 2 * stats.t.sf(np.abs(beta / se), n - p - 1)
return beta, se, pval
def within_scan(y, G, X, groups):
"""Within-family OLS: demean y, G and X inside groups of size >= 2; singletons dropped."""
groups = np.asarray(groups)
keep = np.array([np.sum(groups == g) >= 2 for g in groups])
yk, Gk, Xk, gk = y[keep], G[keep], X[keep], groups[keep]
if keep.sum() < 10:
nan = np.full(G.shape[1], np.nan)
return nan, nan, nan, int(keep.sum())
def dm(M):
M = M.astype(float).copy()
for g in np.unique(gk):
idx = gk == g
M[idx] -= M[idx].mean(0)
return M
Xd = dm(Xk[:, 1:]) if Xk.shape[1] > 1 else np.zeros((len(yk), 0))
Xd = Xd[:, Xd.std(0) > 1e-12] if Xd.shape[1] else Xd
nfam = len(np.unique(gk))
yd, Gd = dm(yk[:, None])[:, 0], dm(Gk)
Xuse = Xd if Xd.shape[1] else np.zeros((len(yk), 1))
b, se, p = ols_scan(yd, Gd, Xuse)
# degrees of freedom lost to family means
df_ols = len(yk) - Xuse.shape[1] - 1
df = max(df_ols - nfam, 3)
se = se * np.sqrt(df_ols / df)
p = 2 * stats.t.sf(np.abs(b / se), df)
return b, se, p, int(keep.sum())
def lambda_gc(p):
p = p[np.isfinite(p)]
chi = stats.chi2.isf(p, 1)
return float(np.median(chi) / stats.chi2.ppf(0.5, 1))
def int_transform(y):
"""Rank-based inverse normal transform (Blom). NaNs kept."""
out = np.full(len(y), np.nan)
ok = np.isfinite(y)
r = stats.rankdata(y[ok])
out[ok] = stats.norm.ppf((r - 0.375) / (ok.sum() + 0.25))
return out
def m_eff(G):
"""Li-Ji effective number of independent tests from the locus correlation matrix."""
C = np.corrcoef(G, rowvar=False)
C = np.nan_to_num(C)
ev = np.abs(np.linalg.eigvalsh(C))
return float(np.sum((ev >= 1).astype(float) + (ev - np.floor(ev))))
def bh(p, q=0.05):
p = np.asarray(p)
ok = np.isfinite(p)
out = np.zeros(len(p), bool)
ps = np.sort(p[ok])
m = len(ps)
thr = ps[ps <= q * np.arange(1, m + 1) / m]
if len(thr):
out[ok] = p[ok] <= thr.max()
return out
|