Download code/src/analysis/scan.py from bryan7264/lorapop: direct link, hf CLI and curl.
- Browser
- Download file 6.53 kB
-
https://huggingface.co/datasets/bryan7264/lorapop/resolve/main/code/src/analysis/scan.py
- Command line
-
hf download hf://datasets/bryan7264/lorapop/code/src/analysis/scan.py
-
curl -L -o scan.py https://huggingface.co/datasets/bryan7264/lorapop/resolve/main/code/src/analysis/scan.py
6.53 kB
| # 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 | |