Download code/src/analysis/lsr.py from bryan7264/lorapop: direct link, hf CLI and curl.
- Browser
- Download file 4.51 kB
-
https://huggingface.co/datasets/bryan7264/lorapop/resolve/main/code/src/analysis/lsr.py
- Command line
-
hf download hf://datasets/bryan7264/lorapop/code/src/analysis/lsr.py
-
curl -L -o lsr.py https://huggingface.co/datasets/bryan7264/lorapop/resolve/main/code/src/analysis/lsr.py
4.51 kB
| # MIT License, Bryan Cheng, 2026. | |
| """Linkage-score regression (RESEARCH_PLAN 7.4; D-042), the analogue of LD-score regression on the naive scan. | |
| Linkage score of locus j: l_j = sum_k r~_jk^2 over all loci (k = j included), with the standard bias-corrected squared | |
| correlation r~^2 = r^2 - (1 - r^2) / (n - 2) (LD-score regression's estimator; the plain r^2 adds about (M - 1) / n to | |
| every score). chi^2_j is the naive OLS Wald statistic (same covariates as the scan). Reported per primary trait: | |
| ols chi^2 on l, unweighted | |
| weighted chi^2 on l with weights 1 / max(l, 1) (LD-score regression's correction for double counting) | |
| intercept standard errors from a delete-one-module block jackknife; mean chi^2; ratio = (intercept - 1) / (mean chi^2 - 1) | |
| plain_r2 the unweighted fit with uncorrected r^2, which reproduces scan_extras.py (check) | |
| Interpretation as in LD-score regression: under a linear relation, an intercept above 1 is inflation that linkage does not | |
| explain. Loci are principal axes within each module (r = 0 within a module by construction), so the linkage score counts | |
| cross-module linkage only. | |
| python src/analysis/lsr.py --geno data/processed/qwen05 --pheno results/phenotypes/qwen05 --scan results/scans/qwen05_rt | |
| --out results/scans/qwen05_rt/lsr.json | |
| """ | |
| import argparse | |
| import json | |
| import os | |
| import sys | |
| import numpy as np | |
| sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "..")) | |
| from src.analysis.population import build # noqa: E402 | |
| from src.analysis.scan import ols_scan # noqa: E402 | |
| def wls(x, y, w): | |
| W = w / w.sum() | |
| xm, ym = (W * x).sum(), (W * y).sum() | |
| slope = (W * (x - xm) * (y - ym)).sum() / (W * (x - xm) ** 2).sum() | |
| return float(slope), float(ym - slope * xm) | |
| def fit(l, chi, w, blocks): | |
| s, i = wls(l, chi, w) | |
| ub = np.unique(blocks) | |
| jk = np.array([wls(l[blocks != b], chi[blocks != b], w[blocks != b]) for b in ub]) | |
| B = len(ub) | |
| se = np.sqrt((B - 1) / B * ((jk - jk.mean(0)) ** 2).sum(0)) | |
| return {"slope": s, "intercept": i, "slope_se": float(se[0]), "intercept_se": float(se[1])} | |
| 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("--recipe_threshold", type=float, default=None) | |
| ap.add_argument("--out", required=True) | |
| 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"] | |
| G, X = P["G"], P["X"] | |
| n, M = G.shape | |
| R2 = np.corrcoef(G, rowvar=False) ** 2 | |
| l_plain = np.nansum(R2, 0) | |
| R2 = R2 - (1 - R2) / (n - 2) | |
| np.fill_diagonal(R2, 1.0) | |
| l = np.nansum(R2, 0) | |
| del R2 | |
| blocks = np.array([x["module"] for x in P["loci"]]) | |
| out = {"n": n, "n_loci": M, "l_mean": float(l.mean()), "l_range": [float(l.min()), float(l.max())], | |
| "l_plain_mean": float(l_plain.mean()), "per_trait": {}} | |
| for t in prim: | |
| y = P["Yt"][:, P["traits"].index(t)] | |
| ok = np.isfinite(y) | |
| b, se, _ = ols_scan(y[ok], G[ok], X[ok]) | |
| chi = (b / se) ** 2 | |
| m = np.isfinite(chi) | |
| mc = float(chi[m].mean()) | |
| r = {"mean_chi2": mc, | |
| "ols": fit(l[m], chi[m], np.ones(m.sum()), blocks[m]), | |
| "weighted": fit(l[m], chi[m], 1 / np.maximum(l[m], 1), blocks[m]), | |
| "plain_r2": dict(zip(("slope", "intercept"), wls(l_plain[m], chi[m], np.ones(m.sum()))))} | |
| for k in ("ols", "weighted"): | |
| r[k]["ratio"] = (r[k]["intercept"] - 1) / (mc - 1) if mc > 1 else float("nan") | |
| out["per_trait"][t] = r | |
| print(t, round(mc, 2), {k: round(r[k]["intercept"], 2) for k in ("ols", "weighted")}, | |
| "plain", round(r["plain_r2"]["intercept"], 2), flush=True) | |
| ic = np.array([out["per_trait"][t]["weighted"]["intercept"] for t in prim]) | |
| out["summary"] = {"median_intercept_weighted": float(np.median(ic)), | |
| "n_intercept_gt1_2se": int(sum(out["per_trait"][t]["weighted"]["intercept"] - 1 > | |
| 2 * out["per_trait"][t]["weighted"]["intercept_se"] for t in prim)), | |
| "median_ratio_weighted": float(np.nanmedian([out["per_trait"][t]["weighted"]["ratio"] for t in prim]))} | |
| json.dump(out, open(a.out, "w"), indent=1) | |
| print(json.dumps(out["summary"]), "LSRDONE", flush=True) | |
| if __name__ == "__main__": | |
| main() | |