Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -61,7 +61,6 @@ CHR_PALETTE = [
|
|
| 61 |
]
|
| 62 |
|
| 63 |
# Publication-style QQ gradient: grey (low p) → blue → yellow → red (high p)
|
| 64 |
-
# Matches the standard GAPIT / TASSEL QQ plot colour scheme
|
| 65 |
QQ_CMAP = LinearSegmentedColormap.from_list(
|
| 66 |
"qq_pub",
|
| 67 |
["#AAAAAA", "#4575B4", "#74ADD1", "#ABD9E9",
|
|
@@ -185,12 +184,11 @@ def build_kinship(G_raw):
|
|
| 185 |
K = (Z @ Z.T) / denom
|
| 186 |
return K
|
| 187 |
|
| 188 |
-
# ───────────────────────
|
| 189 |
def reml_variance_components(y, K):
|
| 190 |
"""
|
| 191 |
REML variance components via eigendecomposition of K.
|
| 192 |
-
|
| 193 |
-
avoiding bias where Vg absorbs the phenotype mean.
|
| 194 |
Returns (Vg, Ve, delta, eigvals, U).
|
| 195 |
"""
|
| 196 |
n = len(y)
|
|
@@ -200,13 +198,12 @@ def reml_variance_components(y, K):
|
|
| 200 |
Uty = U.T @ y
|
| 201 |
Ut1 = U.T @ np.ones(n)
|
| 202 |
|
| 203 |
-
#
|
| 204 |
Uty = Uty - (np.dot(Uty, Ut1) / np.dot(Ut1, Ut1)) * Ut1
|
| 205 |
|
| 206 |
def neg_log_reml(log_delta):
|
| 207 |
delta = np.exp(log_delta)
|
| 208 |
d = eigvals + delta
|
| 209 |
-
# use (n-1) df after projecting out the intercept
|
| 210 |
ll = -0.5 * np.sum(np.log(d))
|
| 211 |
ll -= 0.5 * (n - 1) * np.log(np.maximum(np.sum(Uty**2 / d), 1e-12))
|
| 212 |
return -ll
|
|
@@ -221,14 +218,9 @@ def reml_variance_components(y, K):
|
|
| 221 |
Vg = max(float(Vg), 1e-8)
|
| 222 |
return Vg, Ve, float(delta), eigvals, U
|
| 223 |
|
| 224 |
-
# ───────────────────────
|
| 225 |
def gls_test(y, x, V_inv):
|
| 226 |
-
"""
|
| 227 |
-
GLS single-SNP test.
|
| 228 |
-
FIX: sigma2 estimated as ordinary resid @ resid / df (not resid @ V_inv @ resid).
|
| 229 |
-
Multiplying by XtVX_inv already accounts for the V structure; applying V_inv
|
| 230 |
-
again to sigma2 would double-scale the standard errors.
|
| 231 |
-
"""
|
| 232 |
x = x.reshape(-1, 1)
|
| 233 |
one = np.ones((len(y), 1))
|
| 234 |
X = np.hstack([one, x])
|
|
@@ -244,7 +236,6 @@ def gls_test(y, x, V_inv):
|
|
| 244 |
resid = y - X @ coeffs
|
| 245 |
df = len(y) - 2
|
| 246 |
|
| 247 |
-
# FIX: ordinary residual variance — V_inv is already in XtVX_inv
|
| 248 |
sigma2 = float(resid @ resid) / max(df, 1)
|
| 249 |
|
| 250 |
try:
|
|
@@ -264,30 +255,21 @@ def ols_linregress(y, x):
|
|
| 264 |
slope, intercept, r, p, se = stats.linregress(x, y)
|
| 265 |
return float(slope), float(se), float(p)
|
| 266 |
|
| 267 |
-
# ───────────────────────
|
| 268 |
def precompute_rotation(y, K):
|
| 269 |
-
"""
|
| 270 |
-
Eigendecompose K once. Returns everything needed for O(n)-per-SNP tests.
|
| 271 |
-
FIX: replaces O(n³) np.linalg.inv(V) with a single eigendecomposition
|
| 272 |
-
reused across all SNPs.
|
| 273 |
-
"""
|
| 274 |
n = len(y)
|
| 275 |
Vg, Ve, delta, eigvals, U = reml_variance_components(y, K)
|
| 276 |
-
d = eigvals + delta
|
| 277 |
Uty = U.T @ y
|
| 278 |
Ut1 = U.T @ np.ones(n)
|
| 279 |
return U, d, Uty, Ut1, Vg, Ve, delta
|
| 280 |
|
| 281 |
def rotated_gls_snp(Utx, Uty, Ut1, d):
|
| 282 |
-
"""
|
| 283 |
-
Single-SNP GLS test using pre-rotated vectors — all operations O(n).
|
| 284 |
-
FIX: no matrix inversion required; uses scalar arithmetic on diagonal d.
|
| 285 |
-
Returns (beta, se, p_value).
|
| 286 |
-
"""
|
| 287 |
n = len(Uty)
|
| 288 |
df = n - 2
|
| 289 |
|
| 290 |
-
# Weighted inner products (diagonal solve)
|
| 291 |
S11 = np.sum(Ut1**2 / d)
|
| 292 |
S1x = np.sum(Ut1 * Utx / d)
|
| 293 |
Sxx = np.sum(Utx**2 / d)
|
|
@@ -301,7 +283,6 @@ def rotated_gls_snp(Utx, Uty, Ut1, d):
|
|
| 301 |
beta = (S11 * Sxy - S1x * S1y) / denom
|
| 302 |
intercept= (S1y - S1x * beta) / S11
|
| 303 |
|
| 304 |
-
# Ordinary residuals in rotated space
|
| 305 |
resid_rot = Uty - intercept * Ut1 - beta * Utx
|
| 306 |
sigma2 = np.dot(resid_rot, resid_rot) / max(df, 1)
|
| 307 |
|
|
@@ -311,13 +292,9 @@ def rotated_gls_snp(Utx, Uty, Ut1, d):
|
|
| 311 |
p_val = float(2 * stats.t.sf(abs(t_stat), df=max(df, 1)))
|
| 312 |
return float(beta), se, p_val
|
| 313 |
|
| 314 |
-
# ──────────────────────
|
| 315 |
def compute_pve(y, G, pvals, betas, ses, threshold=0.05):
|
| 316 |
-
"""
|
| 317 |
-
FIX: computes partial r² via type-II SS from a joint OLS model containing
|
| 318 |
-
all significant SNPs. This prevents cumulative PVE exceeding 100% when
|
| 319 |
-
significant SNPs are correlated.
|
| 320 |
-
"""
|
| 321 |
bonf = threshold / len(pvals)
|
| 322 |
sig_idx = list(np.where(pvals < bonf)[0])
|
| 323 |
SST = np.sum((y - y.mean())**2)
|
|
@@ -326,7 +303,6 @@ def compute_pve(y, G, pvals, betas, ses, threshold=0.05):
|
|
| 326 |
if SST < 1e-10 or len(sig_idx) == 0:
|
| 327 |
return {}, SST
|
| 328 |
|
| 329 |
-
# Build joint design matrix
|
| 330 |
X_parts = [np.ones(len(y))]
|
| 331 |
valid_idx = []
|
| 332 |
for idx in sig_idx:
|
|
@@ -346,7 +322,6 @@ def compute_pve(y, G, pvals, betas, ses, threshold=0.05):
|
|
| 346 |
return {idx: 0.0 for idx in valid_idx}, SST
|
| 347 |
|
| 348 |
for k, idx in enumerate(valid_idx):
|
| 349 |
-
# Drop SNP k+1 (column 0 is the intercept)
|
| 350 |
X_drop = np.delete(X_joint, k + 1, axis=1)
|
| 351 |
try:
|
| 352 |
c_drop = np.linalg.lstsq(X_drop, y, rcond=None)[0]
|
|
@@ -359,7 +334,7 @@ def compute_pve(y, G, pvals, betas, ses, threshold=0.05):
|
|
| 359 |
|
| 360 |
return pve_dict, SST
|
| 361 |
|
| 362 |
-
# ─────────────────────── 10 STATISTICAL MODELS ───────────────────────────────
|
| 363 |
|
| 364 |
def ols_gwas(y, G):
|
| 365 |
"""OLS: simple linear regression, no structure correction."""
|
|
@@ -371,10 +346,7 @@ def ols_gwas(y, G):
|
|
| 371 |
return pvals, betas, ses
|
| 372 |
|
| 373 |
def mlm_gwas(y, G, K):
|
| 374 |
-
"""
|
| 375 |
-
MLM (EMMAX-style full GLS): mixed model with REML variance components.
|
| 376 |
-
Uses exact GLS with full V_inv — accurate but O(n³) per analysis.
|
| 377 |
-
"""
|
| 378 |
n, m = G.shape
|
| 379 |
pvals = np.ones(m); betas = np.zeros(m); ses = np.zeros(m)
|
| 380 |
|
|
@@ -470,7 +442,6 @@ def blink_gwas(y, G, K):
|
|
| 470 |
n, m = G.shape
|
| 471 |
pvals = np.ones(m); betas = np.zeros(m); ses = np.zeros(m)
|
| 472 |
|
| 473 |
-
# FIX: use rotated GLS (O(n) per SNP) for initial scan
|
| 474 |
U, d, Uty, Ut1, Vg, Ve, delta = precompute_rotation(y, K)
|
| 475 |
|
| 476 |
init_p = np.ones(m)
|
|
@@ -534,7 +505,6 @@ def farmcpu_gwas(y, G, K):
|
|
| 534 |
n, m = G.shape
|
| 535 |
pvals = np.ones(m); betas = np.zeros(m); ses = np.zeros(m)
|
| 536 |
|
| 537 |
-
# FIX: use rotated GLS for efficiency
|
| 538 |
U, d, Uty, Ut1, Vg, Ve, delta = precompute_rotation(y, K)
|
| 539 |
|
| 540 |
qtns_prev = []
|
|
@@ -587,15 +557,10 @@ def farmcpu_gwas(y, G, K):
|
|
| 587 |
return pvals, betas, ses
|
| 588 |
|
| 589 |
def emmax_gwas(y, G, K):
|
| 590 |
-
"""
|
| 591 |
-
EMMAX: efficient mixed-model using the K eigenrotation trick.
|
| 592 |
-
FIX: differentiated from MLM — uses O(n)-per-SNP rotated GLS rather than
|
| 593 |
-
the O(n³) full V_inv path. Same statistical model, faster algorithm.
|
| 594 |
-
"""
|
| 595 |
n, m = G.shape
|
| 596 |
pvals = np.ones(m); betas = np.zeros(m); ses = np.zeros(m)
|
| 597 |
|
| 598 |
-
# FIX: precompute rotation once — O(n²) setup, O(n) per SNP thereafter
|
| 599 |
U, d, Uty, Ut1, Vg, Ve, delta = precompute_rotation(y, K)
|
| 600 |
|
| 601 |
for j in range(m):
|
|
@@ -630,7 +595,6 @@ def gapit3_gwas(y, G, K):
|
|
| 630 |
except Exception:
|
| 631 |
PCs = np.zeros((n, 1))
|
| 632 |
|
| 633 |
-
# FIX: use rotated GLS for the mixed model component
|
| 634 |
U, d, Uty, Ut1, Vg, Ve, delta = precompute_rotation(y, K)
|
| 635 |
|
| 636 |
qtns = []
|
|
@@ -684,21 +648,15 @@ def gapit3_gwas(y, G, K):
|
|
| 684 |
return pvals, betas, ses
|
| 685 |
|
| 686 |
def gemma_gwas(y, G, K):
|
| 687 |
-
"""
|
| 688 |
-
GEMMA LMM: centered kinship + REML via rotation trick.
|
| 689 |
-
FIX: uses O(n)-per-SNP rotated GLS on centered kinship.
|
| 690 |
-
No post-hoc lambda deflation (REML already handles stratification).
|
| 691 |
-
"""
|
| 692 |
n, m = G.shape
|
| 693 |
pvals = np.ones(m); betas = np.zeros(m); ses = np.zeros(m)
|
| 694 |
|
| 695 |
-
# Centered kinship (GEMMA style)
|
| 696 |
row_mean = K.mean(axis=1, keepdims=True)
|
| 697 |
col_mean = K.mean(axis=0, keepdims=True)
|
| 698 |
grand_mean = K.mean()
|
| 699 |
Kc = K - row_mean - col_mean + grand_mean
|
| 700 |
|
| 701 |
-
# FIX: use rotation trick on centered kinship
|
| 702 |
U, d, Uty, Ut1, Vg, Ve, delta = precompute_rotation(y, Kc)
|
| 703 |
|
| 704 |
for j in range(m):
|
|
@@ -712,7 +670,7 @@ def gemma_gwas(y, G, K):
|
|
| 712 |
pvals[j] = p; betas[j] = b; ses[j] = se
|
| 713 |
return pvals, betas, ses
|
| 714 |
|
| 715 |
-
# ─────────────────────── FIGURE HELPERS ──────────────────────────────────────
|
| 716 |
def fig_to_pil(fig):
|
| 717 |
buf = io.BytesIO()
|
| 718 |
fig.savefig(buf, format="png", dpi=150, bbox_inches="tight",
|
|
@@ -732,7 +690,7 @@ def fig_to_png_bytes(fig):
|
|
| 732 |
buf.close()
|
| 733 |
return data
|
| 734 |
|
| 735 |
-
# ───────────────────────
|
| 736 |
def _compute_x_coords(chroms, positions, chrom_list):
|
| 737 |
"""Compute x-axis coords for Manhattan layout."""
|
| 738 |
x_coords = np.zeros(len(chroms))
|
|
@@ -748,17 +706,13 @@ def _compute_x_coords(chroms, positions, chrom_list):
|
|
| 748 |
return x_coords
|
| 749 |
|
| 750 |
def _compute_tick_positions(x_coords, chroms, chrom_list):
|
| 751 |
-
"""
|
| 752 |
-
FIX: tick at span midpoint, not coordinate mean.
|
| 753 |
-
Mean drifts with uneven SNP density; midpoint is always the visual centre.
|
| 754 |
-
"""
|
| 755 |
tick_pos, tick_lab = [], []
|
| 756 |
for ch in chrom_list:
|
| 757 |
mask = chroms == ch
|
| 758 |
if not mask.any():
|
| 759 |
continue
|
| 760 |
xc = x_coords[mask]
|
| 761 |
-
# FIX: span midpoint
|
| 762 |
tick_pos.append((xc.min() + xc.max()) / 2)
|
| 763 |
tick_lab.append(f"Chr{ch}")
|
| 764 |
return tick_pos, tick_lab
|
|
@@ -808,46 +762,26 @@ def plot_manhattan(pvals, chroms, positions, title="Manhattan Plot", model_name=
|
|
| 808 |
return fig
|
| 809 |
|
| 810 |
def _draw_qq_on_ax(ax, pvals, model_name, color):
|
| 811 |
-
"""
|
| 812 |
-
QQ plot matching the reference image style:
|
| 813 |
-
─ White background, outward ticks, no gridlines inside plot
|
| 814 |
-
─ CI band filled in the model's own colour (semi-transparent) — like the
|
| 815 |
-
blue-grey shaded region in the reference
|
| 816 |
-
─ All points: solid dark navy/model colour, small circles
|
| 817 |
-
─ Significant points (above GW threshold): larger, same colour
|
| 818 |
-
─ Reference line: RED dashed (exactly like reference image)
|
| 819 |
-
─ λ top-left in model colour
|
| 820 |
-
─ No colourbar — clean and minimal
|
| 821 |
-
"""
|
| 822 |
n = len(pvals)
|
| 823 |
obs_raw = -np.log10(np.clip(pvals, 1e-300, 1))
|
| 824 |
-
|
| 825 |
-
# matching the expected quantiles which go from -log10(1/n) down to 0.
|
| 826 |
-
sort_i = np.argsort(obs_raw)[::-1] # descending
|
| 827 |
obs = obs_raw[sort_i]
|
| 828 |
-
|
| 829 |
-
exp = -np.log10(np.arange(1, n + 1) / n) # descending, rank-correct
|
| 830 |
|
| 831 |
-
# ── 95% CI band — ranks correspond to order statistics 1..n ──────────────
|
| 832 |
-
# rank 1 = most extreme (smallest p), rank n = least extreme (p≈1)
|
| 833 |
ranks = np.arange(1, n + 1)
|
| 834 |
ci_lo = -np.log10(stats.beta.ppf(0.975, ranks, n - ranks + 1))
|
| 835 |
ci_hi = -np.log10(stats.beta.ppf(0.025, ranks, n - ranks + 1))
|
| 836 |
|
| 837 |
-
# Parse hex color to rgba for fill
|
| 838 |
import matplotlib.colors as mcolors
|
| 839 |
rgb = mcolors.to_rgb(color)
|
| 840 |
ax.fill_between(exp, ci_lo, ci_hi,
|
| 841 |
color=rgb, alpha=0.22, zorder=1)
|
| 842 |
-
# No border lines on CI — matches the reference's soft shaded look
|
| 843 |
|
| 844 |
-
# ── Reference diagonal: RED dashed — exactly like reference ──────────────
|
| 845 |
xy_max = max(float(exp.max()), float(obs.max())) * 1.06
|
| 846 |
ax.plot([0, xy_max], [0, xy_max],
|
| 847 |
color="#E8453C", ls="--", lw=1.8, zorder=2, label="Expected")
|
| 848 |
|
| 849 |
-
# ── All dots: uniform solid circles in model colour ───────────────────────
|
| 850 |
-
# Below GW threshold — small solid circles (matches dense diagonal in ref)
|
| 851 |
sig_thr = -np.log10(5e-8)
|
| 852 |
ns_mask = obs < sig_thr
|
| 853 |
if ns_mask.any():
|
|
@@ -855,7 +789,6 @@ def _draw_qq_on_ax(ax, pvals, model_name, color):
|
|
| 855 |
c=color, s=14, alpha=0.85,
|
| 856 |
linewidths=0, zorder=3)
|
| 857 |
|
| 858 |
-
# Above GW threshold — larger solid circles, same colour (ref shows bigger dots)
|
| 859 |
gw_mask = obs >= sig_thr
|
| 860 |
if gw_mask.any():
|
| 861 |
ax.scatter(exp[gw_mask], obs[gw_mask],
|
|
@@ -863,7 +796,6 @@ def _draw_qq_on_ax(ax, pvals, model_name, color):
|
|
| 863 |
linewidths=0.6, edgecolors="white", zorder=5,
|
| 864 |
label=f"GW sig. (n={int(gw_mask.sum())})")
|
| 865 |
|
| 866 |
-
# ── λ genomic inflation — top-left, bold, model colour ───────────────────
|
| 867 |
lam = (np.median(stats.chi2.ppf(1 - np.clip(pvals, 1e-10, 1), df=1))
|
| 868 |
/ stats.chi2.ppf(0.5, df=1))
|
| 869 |
lam_str = f"λ = {lam:.4f}"
|
|
@@ -876,7 +808,6 @@ def _draw_qq_on_ax(ax, pvals, model_name, color):
|
|
| 876 |
facecolor="white", edgecolor=lam_col,
|
| 877 |
alpha=0.88, linewidth=1.0))
|
| 878 |
|
| 879 |
-
# ── Axes: clean white, outward ticks, no grid — like reference image ──────
|
| 880 |
ax.set_facecolor("white")
|
| 881 |
ax.set_xlabel("Expected −log₁₀(p)", fontsize=10, color="#222222",
|
| 882 |
labelpad=6)
|
|
@@ -885,7 +816,6 @@ def _draw_qq_on_ax(ax, pvals, model_name, color):
|
|
| 885 |
ax.tick_params(axis="both", colors="#222222", labelsize=9,
|
| 886 |
direction="out", length=5, width=0.9,
|
| 887 |
top=False, right=False)
|
| 888 |
-
# Only bottom and left spines visible — matches reference
|
| 889 |
ax.spines["top"].set_visible(False)
|
| 890 |
ax.spines["right"].set_visible(False)
|
| 891 |
ax.spines["bottom"].set_edgecolor("#333333")
|
|
@@ -895,7 +825,6 @@ def _draw_qq_on_ax(ax, pvals, model_name, color):
|
|
| 895 |
ax.set_axisbelow(False)
|
| 896 |
ax.grid(False)
|
| 897 |
|
| 898 |
-
# Axis limits with a small buffer below 0 (like reference shows y starting ~-0.1)
|
| 899 |
ax.set_xlim(-0.05, xy_max)
|
| 900 |
y_max = max(float(obs.max()), sig_thr) * 1.10
|
| 901 |
ax.set_ylim(-0.15, y_max)
|
|
@@ -911,9 +840,7 @@ def plot_qq_single(pvals, title="QQ Plot", model_name="", color=None):
|
|
| 911 |
full_title = f"{title}{' — ' + model_name if model_name else ''}"
|
| 912 |
ax.set_title(full_title, color="#1E293B", fontsize=12,
|
| 913 |
fontweight="bold", pad=8)
|
| 914 |
-
# Compact legend bottom-right (doesn't overlap points)
|
| 915 |
handles, labels = ax.get_legend_handles_labels()
|
| 916 |
-
# Only keep meaningful entries (skip CI lines which have no label)
|
| 917 |
ax.legend(handles, labels, fontsize=7.5,
|
| 918 |
framealpha=0.92, facecolor="white",
|
| 919 |
edgecolor="#CCCCCC", labelcolor="#333333",
|
|
@@ -961,9 +888,9 @@ def plot_qq_overlay(all_results):
|
|
| 961 |
for mname, (pvals, _, _) in all_results.items():
|
| 962 |
n = len(pvals)
|
| 963 |
obs_raw = -np.log10(np.clip(pvals, 1e-300, 1))
|
| 964 |
-
sort_i = np.argsort(obs_raw)[::-1]
|
| 965 |
obs = obs_raw[sort_i]
|
| 966 |
-
exp = -np.log10(np.arange(1, n + 1) / n)
|
| 967 |
exp_max = max(exp_max, exp.max())
|
| 968 |
lam = (np.median(stats.chi2.ppf(1 - np.clip(pvals, 1e-10, 1), df=1))
|
| 969 |
/ stats.chi2.ppf(0.5, df=1))
|
|
@@ -1067,16 +994,20 @@ def plot_circos(all_results, chroms, positions):
|
|
| 1067 |
|
| 1068 |
def plot_ld_decay(G, positions, chroms):
|
| 1069 |
"""
|
| 1070 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1071 |
"""
|
| 1072 |
fig, axes = plt.subplots(1, 2, figsize=(16, 6), facecolor=BG_WHITE)
|
| 1073 |
style_fig(fig)
|
| 1074 |
|
| 1075 |
chrom_list = sorted(set(chroms))
|
| 1076 |
-
# FIX: 150 SNPs per chromosome, capped by chromosome size
|
| 1077 |
sample_per_chr = 150
|
| 1078 |
sampled_idx = []
|
| 1079 |
rng = np.random.default_rng(42)
|
|
|
|
| 1080 |
for ch in chrom_list:
|
| 1081 |
idx_ch = np.where(chroms == ch)[0]
|
| 1082 |
n_samp = min(sample_per_chr, len(idx_ch))
|
|
@@ -1110,7 +1041,8 @@ def plot_ld_decay(G, positions, chroms):
|
|
| 1110 |
dists_mb = dists_bp / 1_000_000
|
| 1111 |
r2s = np.array(r2s)
|
| 1112 |
|
| 1113 |
-
def
|
|
|
|
| 1114 |
bins = np.percentile(dists, np.linspace(0, 100, n_bins + 1))
|
| 1115 |
centers, means, sems = [], [], []
|
| 1116 |
for k in range(len(bins) - 1):
|
|
@@ -1121,27 +1053,54 @@ def plot_ld_decay(G, positions, chroms):
|
|
| 1121 |
sems.append(stats.sem(r2s[mask]))
|
| 1122 |
return np.array(centers), np.array(means), np.array(sems)
|
| 1123 |
|
|
|
|
| 1124 |
for ax, dists, unit, c1, c2 in [
|
| 1125 |
(axes[0], dists_bp, "bp", ACCENT_TEAL, ACCENT_CORAL),
|
| 1126 |
(axes[1], dists_mb, "Mb", ACCENT_PURP, ACCENT_GOLD),
|
| 1127 |
]:
|
| 1128 |
ax.set_facecolor(PANEL_WHITE)
|
| 1129 |
-
|
| 1130 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1131 |
if len(bc) > 0:
|
| 1132 |
-
ax.plot(bc, bm, color=c2, lw=
|
| 1133 |
-
zorder=5, label="Binned mean r²")
|
| 1134 |
-
ax.fill_between(bc, bm - bs, bm + bs, alpha=0.
|
| 1135 |
-
|
| 1136 |
-
|
| 1137 |
-
ax.
|
| 1138 |
-
ax.
|
| 1139 |
-
|
| 1140 |
-
|
| 1141 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1142 |
ax.set_ylim(0, 1.05)
|
|
|
|
|
|
|
|
|
|
| 1143 |
|
| 1144 |
-
fig.suptitle("Linkage Disequilibrium (LD) Decay",
|
|
|
|
| 1145 |
fig.tight_layout()
|
| 1146 |
return fig
|
| 1147 |
|
|
@@ -1297,35 +1256,88 @@ def plot_all_models_manhattan_grid(all_results, chroms, positions):
|
|
| 1297 |
return fig
|
| 1298 |
|
| 1299 |
def plot_kinship(K, ids):
|
| 1300 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1301 |
style_fig(fig)
|
| 1302 |
for ax in axes.flatten():
|
| 1303 |
ax.set_facecolor(PANEL_WHITE)
|
| 1304 |
|
|
|
|
| 1305 |
im = axes[0,0].imshow(K, cmap='RdYlBu_r', aspect='auto', vmin=-0.5, vmax=1)
|
| 1306 |
-
axes[0,0].set_title("Kinship Matrix (VanRaden)", color=TEXT_MAIN)
|
| 1307 |
-
plt.colorbar(im, ax=axes[0,0])
|
| 1308 |
|
|
|
|
| 1309 |
K_flat = K[np.triu_indices_from(K, k=1)]
|
| 1310 |
axes[0,1].hist(K_flat, bins=30, color=ACCENT_PURP, edgecolor='none', alpha=0.85)
|
| 1311 |
-
axes[0,1].
|
| 1312 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1313 |
try:
|
| 1314 |
lm = linkage(K, method='average')
|
| 1315 |
-
|
| 1316 |
-
|
| 1317 |
-
|
| 1318 |
-
|
| 1319 |
-
|
| 1320 |
-
|
| 1321 |
-
|
| 1322 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1323 |
|
|
|
|
| 1324 |
eigvals, eigvecs = np.linalg.eigh(K)
|
| 1325 |
idx = np.argsort(eigvals)[::-1]
|
|
|
|
|
|
|
| 1326 |
axes[1,1].scatter(eigvecs[:, idx[0]], eigvecs[:, idx[1]],
|
| 1327 |
-
c=ACCENT_TEAL, s=60, edgecolors='
|
| 1328 |
-
axes[1,1].set_title("Kinship PCA", color=TEXT_MAIN)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1329 |
fig.tight_layout()
|
| 1330 |
return fig
|
| 1331 |
|
|
@@ -1372,35 +1384,60 @@ def plot_effect_sizes(pvals, betas, snp_names):
|
|
| 1372 |
return fig
|
| 1373 |
|
| 1374 |
def plot_summary_dashboard(y, maf, all_results, G_filt):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1375 |
fig, axes = plt.subplots(2, 3, figsize=(15, 10), facecolor=BG_WHITE)
|
| 1376 |
style_fig(fig)
|
| 1377 |
axes = axes.flatten()
|
| 1378 |
for ax in axes:
|
| 1379 |
ax.set_facecolor(PANEL_WHITE)
|
| 1380 |
|
|
|
|
| 1381 |
axes[0].hist(y, bins=15, color=ACCENT_PURP, edgecolor='none', alpha=0.85)
|
| 1382 |
axes[0].axvline(y.mean(), color=ACCENT_CORAL, lw=2, ls='--',
|
| 1383 |
label=f"Mean: {y.mean():.2f}")
|
| 1384 |
-
axes[0].set_title(f"Phenotype Distribution | n={len(y)}", color=TEXT_MAIN)
|
|
|
|
|
|
|
| 1385 |
axes[0].legend(fontsize=7, facecolor=BG_WHITE)
|
| 1386 |
|
|
|
|
| 1387 |
axes[1].hist(maf, bins=20, color=ACCENT_TEAL, edgecolor='none', alpha=0.85)
|
| 1388 |
-
axes[1].axvline(0.05, color=ACCENT_CORAL, ls='--')
|
| 1389 |
-
axes[1].set_title(f"MAF Distribution | rare={np.sum(maf<0.05)}", color=TEXT_MAIN)
|
|
|
|
|
|
|
|
|
|
| 1390 |
|
|
|
|
| 1391 |
lambdas = {}
|
| 1392 |
for mname, (p, _, _) in all_results.items():
|
| 1393 |
lam = (np.median(stats.chi2.ppf(1 - np.clip(p, 1e-10, 1), df=1))
|
| 1394 |
/ stats.chi2.ppf(0.5, df=1))
|
| 1395 |
lambdas[mname] = lam
|
| 1396 |
-
|
|
|
|
| 1397 |
else ACCENT_CORAL for v in lambdas.values()]
|
| 1398 |
axes[2].bar(lambdas.keys(), lambdas.values(),
|
| 1399 |
color=colors_lam, edgecolor='none', alpha=0.88)
|
| 1400 |
-
axes[2].axhline(1.0, color=TEXT_DIM, ls='--', lw=1)
|
| 1401 |
-
axes[2].
|
|
|
|
|
|
|
|
|
|
| 1402 |
axes[2].tick_params(axis='x', rotation=35, labelsize=7)
|
| 1403 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1404 |
sig_counts = {}
|
| 1405 |
bonf = 0.05 / len(list(all_results.values())[0][0])
|
| 1406 |
for mname, (p, _, _) in all_results.items():
|
|
@@ -1408,9 +1445,11 @@ def plot_summary_dashboard(y, maf, all_results, G_filt):
|
|
| 1408 |
cols_bar = [MODEL_COLORS.get(m, ACCENT_BLUE) for m in sig_counts]
|
| 1409 |
axes[3].bar(sig_counts.keys(), sig_counts.values(),
|
| 1410 |
color=cols_bar, edgecolor='none', alpha=0.88)
|
| 1411 |
-
axes[3].set_title("Significant SNPs per Model (Bonferroni)", color=TEXT_MAIN)
|
|
|
|
| 1412 |
axes[3].tick_params(axis='x', rotation=35, labelsize=7)
|
| 1413 |
|
|
|
|
| 1414 |
n_m = len(all_results)
|
| 1415 |
model_names = list(all_results.keys())
|
| 1416 |
concordance = np.eye(n_m)
|
|
@@ -1431,8 +1470,9 @@ def plot_summary_dashboard(y, maf, all_results, G_filt):
|
|
| 1431 |
ha='center', va='center', fontsize=5,
|
| 1432 |
color='black' if abs(concordance[i,j]) < 0.7 else 'white')
|
| 1433 |
plt.colorbar(im, ax=axes[4], label="Spearman ρ")
|
| 1434 |
-
axes[4].set_title("Model Concordance (Spearman ρ)", color=TEXT_MAIN)
|
| 1435 |
|
|
|
|
| 1436 |
first_model = model_names[0]
|
| 1437 |
miss_r = np.isnan(G_filt).mean()
|
| 1438 |
axes[5].text(0.5, 0.5,
|
|
@@ -1448,7 +1488,9 @@ def plot_summary_dashboard(y, maf, all_results, G_filt):
|
|
| 1448 |
color=TEXT_MAIN, fontsize=11,
|
| 1449 |
bbox=dict(boxstyle='round,pad=0.6',
|
| 1450 |
facecolor=PANEL_LIGHT, edgecolor=GRID_LINE, alpha=0.8))
|
| 1451 |
-
axes[5].set_title("Pipeline Summary", color=TEXT_MAIN)
|
|
|
|
|
|
|
| 1452 |
fig.tight_layout()
|
| 1453 |
return fig
|
| 1454 |
|
|
@@ -1469,7 +1511,7 @@ def export_results_excel(all_results, snp_filt, chr_filt, pos_filt,
|
|
| 1469 |
|
| 1470 |
bonf = bonf_threshold
|
| 1471 |
|
| 1472 |
-
#
|
| 1473 |
ws_sum = wb.active
|
| 1474 |
ws_sum.title = "Summary"
|
| 1475 |
ws_sum['A1'] = "GWAS Complete Analysis Summary"
|
|
@@ -1498,7 +1540,7 @@ def export_results_excel(all_results, snp_filt, chr_filt, pos_filt,
|
|
| 1498 |
cell.fill = fill; cell.border = thin_border
|
| 1499 |
cell.alignment = Alignment(horizontal='center')
|
| 1500 |
|
| 1501 |
-
#
|
| 1502 |
for mname, (pvals, betas, ses) in all_results.items():
|
| 1503 |
ws = wb.create_sheet(title=f"{mname}_AllSNPs")
|
| 1504 |
ws['A1'] = f"GWAS Results — {mname}"
|
|
@@ -1539,7 +1581,7 @@ def export_results_excel(all_results, snp_filt, chr_filt, pos_filt,
|
|
| 1539 |
if col == 8 and isinstance(val, float):
|
| 1540 |
cell.number_format = '0.00E+00'
|
| 1541 |
|
| 1542 |
-
#
|
| 1543 |
ws_mta = wb.create_sheet(title="Significant_MTAs")
|
| 1544 |
ws_mta['A1'] = "Significant MTAs — All Models"
|
| 1545 |
ws_mta['A1'].font = title_font
|
|
@@ -1585,7 +1627,7 @@ def export_results_excel(all_results, snp_filt, chr_filt, pos_filt,
|
|
| 1585 |
cell.number_format = '0.00E+00'
|
| 1586 |
mta_row += 1
|
| 1587 |
|
| 1588 |
-
#
|
| 1589 |
ws_qtn = wb.create_sheet(title="QTN_Effects")
|
| 1590 |
ws_qtn['A1'] = "QTNs — Effect Analysis"
|
| 1591 |
ws_qtn['A1'].font = title_font
|
|
@@ -1626,7 +1668,7 @@ def export_results_excel(all_results, snp_filt, chr_filt, pos_filt,
|
|
| 1626 |
cell.number_format = '0.00E+00'
|
| 1627 |
qtn_row += 1
|
| 1628 |
|
| 1629 |
-
#
|
| 1630 |
ws_pve = wb.create_sheet(title="PVE_Summary")
|
| 1631 |
ws_pve['A1'] = "Phenotypic Variance Explained (PVE) — Joint Model"
|
| 1632 |
ws_pve['A1'].font = title_font
|
|
@@ -1666,7 +1708,7 @@ def export_results_excel(all_results, snp_filt, chr_filt, pos_filt,
|
|
| 1666 |
cell.number_format = '0.00E+00'
|
| 1667 |
pve_row += 1
|
| 1668 |
|
| 1669 |
-
#
|
| 1670 |
ws_qc = wb.create_sheet(title="SNP_QC")
|
| 1671 |
ws_qc['A1'] = "SNP Quality Control Statistics"
|
| 1672 |
ws_qc['A1'].font = title_font
|
|
@@ -1704,8 +1746,11 @@ def save_all_plots_zip(plot_dict, out_dir):
|
|
| 1704 |
with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf:
|
| 1705 |
for name, fig in plot_dict.items():
|
| 1706 |
if fig is not None:
|
| 1707 |
-
|
| 1708 |
-
|
|
|
|
|
|
|
|
|
|
| 1709 |
return zip_path
|
| 1710 |
|
| 1711 |
# ─────────────────────── MAIN PIPELINE ────────────────────────────────────────
|
|
@@ -1719,10 +1764,10 @@ def run_gwas(file_obj, text_input, selected_models, maf_threshold):
|
|
| 1719 |
ids = df["ID"].values
|
| 1720 |
G_raw = df[snp_cols].values.astype(float)
|
| 1721 |
|
| 1722 |
-
# Build kinship BEFORE mode imputation
|
| 1723 |
K_raw = build_kinship(G_raw)
|
| 1724 |
|
| 1725 |
-
# Mode imputation
|
| 1726 |
G = impute_genotypes_mode(G_raw)
|
| 1727 |
n, m = G.shape
|
| 1728 |
|
|
@@ -1738,7 +1783,7 @@ def run_gwas(file_obj, text_input, selected_models, maf_threshold):
|
|
| 1738 |
pos_filt = positions[keep] if len(positions) == m else np.arange(G_filt.shape[1])
|
| 1739 |
maf_vals = maf_vals_all[keep]
|
| 1740 |
|
| 1741 |
-
# Rebuild kinship on filtered
|
| 1742 |
K = build_kinship(G_filt)
|
| 1743 |
|
| 1744 |
# Post-imputation MAF re-filter
|
|
@@ -1768,10 +1813,10 @@ def run_gwas(file_obj, text_input, selected_models, maf_threshold):
|
|
| 1768 |
"CMLM": lambda: cmlm_gwas(y, G_filt, K),
|
| 1769 |
"BLINK": lambda: blink_gwas(y, G_filt, K),
|
| 1770 |
"FarmCPU": lambda: farmcpu_gwas(y, G_filt, K),
|
| 1771 |
-
"EMMAX": lambda: emmax_gwas(y, G_filt, K),
|
| 1772 |
"PLINK": lambda: plink_gwas(y, G_filt),
|
| 1773 |
"GAPIT3": lambda: gapit3_gwas(y, G_filt, K),
|
| 1774 |
-
"GEMMA": lambda: gemma_gwas(y, G_filt, K),
|
| 1775 |
}
|
| 1776 |
|
| 1777 |
all_results = {}
|
|
@@ -1781,6 +1826,10 @@ def run_gwas(file_obj, text_input, selected_models, maf_threshold):
|
|
| 1781 |
primary_model = None
|
| 1782 |
errors = []
|
| 1783 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1784 |
for mname in models_to_run:
|
| 1785 |
if mname in model_funcs:
|
| 1786 |
try:
|
|
@@ -1799,7 +1848,7 @@ def run_gwas(file_obj, text_input, selected_models, maf_threshold):
|
|
| 1799 |
|
| 1800 |
bonf = 0.05 / len(primary_p)
|
| 1801 |
|
| 1802 |
-
#
|
| 1803 |
plot_dict = {}
|
| 1804 |
try:
|
| 1805 |
plot_dict["01_Manhattan_Primary"] = plot_manhattan(primary_p, chr_filt, pos_filt, "Manhattan Plot", primary_model)
|
|
@@ -1861,9 +1910,12 @@ def run_gwas(file_obj, text_input, selected_models, maf_threshold):
|
|
| 1861 |
f" MAF threshold : ≥{maf_thr:.2f}\n"
|
| 1862 |
f" Imputation : Mode (most frequent allele)\n"
|
| 1863 |
f" Kinship : VanRaden (2008) method\n"
|
| 1864 |
-
f" Variance comps : REML (intercept projected
|
|
|
|
|
|
|
|
|
|
| 1865 |
f" GLS : Rotated O(n) per SNP (EMMAX/GEMMA) or full GLS (MLM)\n"
|
| 1866 |
-
f" PVE : Partial r² from joint model
|
| 1867 |
f" Models run : {', '.join(all_results.keys())}\n"
|
| 1868 |
f"{'─'*68}\n"
|
| 1869 |
f" PER-MODEL RESULTS:\n {lambdas_str}\n"
|
|
@@ -1873,6 +1925,7 @@ def run_gwas(file_obj, text_input, selected_models, maf_threshold):
|
|
| 1873 |
f" Bonferroni threshold : {bonf:.2e}\n"
|
| 1874 |
f" Significant MTAs : {int((primary_p<bonf).sum())}\n"
|
| 1875 |
f" Genomic Inflation λ : {lam:.4f}\n"
|
|
|
|
| 1876 |
f"{'─'*68}\n"
|
| 1877 |
f" 📥 Excel: gwas_results_complete.xlsx\n"
|
| 1878 |
f" • Summary · Per-model SNPs · Sig. MTAs · QTN · PVE · SNP QC\n"
|
|
@@ -1909,7 +1962,6 @@ body, .gradio-container {
|
|
| 1909 |
}
|
| 1910 |
.gradio-container { max-width: 1400px !important; margin: 0 auto !important; }
|
| 1911 |
|
| 1912 |
-
/* ── Header ── */
|
| 1913 |
.gwas-header {
|
| 1914 |
background: linear-gradient(135deg, #E8F4FD 0%, #EDE9F8 50%, #FDF0F8 100%);
|
| 1915 |
border: 1px solid #D6E8F5; border-radius: 18px; padding: 28px 36px;
|
|
@@ -1920,13 +1972,11 @@ body, .gradio-container {
|
|
| 1920 |
.gwas-header p { color: #6B7A99 !important; font-size: 14px !important;
|
| 1921 |
margin: 4px 0 !important; }
|
| 1922 |
|
| 1923 |
-
/* ── Panels ── */
|
| 1924 |
.gr-panel, .gr-box, .block, .panel {
|
| 1925 |
background: #FFFFFF !important; border: 1px solid #E8ECF4 !important;
|
| 1926 |
border-radius: 14px !important; box-shadow: 0 1px 8px rgba(60,80,140,0.06) !important;
|
| 1927 |
}
|
| 1928 |
|
| 1929 |
-
/* ── Generic labels (NOT the checkbox items) ── */
|
| 1930 |
.label-wrap span {
|
| 1931 |
color: #5A6480 !important; font-size: 12px !important; font-weight: 500 !important;
|
| 1932 |
text-transform: uppercase !important; letter-spacing: 0.5px !important;
|
|
@@ -1937,7 +1987,6 @@ input[type=text], input[type=number], textarea, select {
|
|
| 1937 |
font-family: 'DM Mono', monospace !important; font-size: 12px !important;
|
| 1938 |
}
|
| 1939 |
|
| 1940 |
-
/* ── Run button ── */
|
| 1941 |
button.primary {
|
| 1942 |
background: linear-gradient(135deg, #5BA8E5 0%, #7C6FCD 100%) !important;
|
| 1943 |
border: none !important; border-radius: 12px !important; color: #FFFFFF !important;
|
|
@@ -1948,7 +1997,6 @@ button.primary {
|
|
| 1948 |
button.primary:hover { transform: translateY(-2px) !important;
|
| 1949 |
box-shadow: 0 6px 24px rgba(91,168,229,0.45) !important; }
|
| 1950 |
|
| 1951 |
-
/* ── Tabs ── */
|
| 1952 |
.tab-nav {
|
| 1953 |
background: #F0F3FB !important; border-radius: 12px !important;
|
| 1954 |
padding: 4px !important; border: 1px solid #E4E8F5 !important; overflow-x: auto !important;
|
|
@@ -1963,21 +2011,18 @@ button.primary:hover { transform: translateY(-2px) !important;
|
|
| 1963 |
box-shadow: 0 1px 6px rgba(91,168,229,0.2) !important;
|
| 1964 |
}
|
| 1965 |
|
| 1966 |
-
/* ── Summary box ── */
|
| 1967 |
.summary-box textarea {
|
| 1968 |
font-family: 'DM Mono', monospace !important; font-size: 12px !important;
|
| 1969 |
background: #F8F9FF !important; color: #2D3142 !important;
|
| 1970 |
border: 1px solid #DDE2F0 !important; line-height: 1.7 !important;
|
| 1971 |
}
|
| 1972 |
|
| 1973 |
-
/* ── Download section ── */
|
| 1974 |
.download-section {
|
| 1975 |
background: linear-gradient(135deg, #EBF5FF 0%, #F0EBFF 100%);
|
| 1976 |
border: 1px solid #D0E4F5 !important; border-radius: 14px !important;
|
| 1977 |
padding: 18px !important;
|
| 1978 |
}
|
| 1979 |
|
| 1980 |
-
/* ── Section labels ── */
|
| 1981 |
.section-label {
|
| 1982 |
font-size: 11px !important; font-weight: 600 !important; color: #8892B0 !important;
|
| 1983 |
text-transform: uppercase !important; letter-spacing: 1px !important;
|
|
@@ -1985,17 +2030,12 @@ button.primary:hover { transform: translateY(-2px) !important;
|
|
| 1985 |
margin-bottom: 8px !important;
|
| 1986 |
}
|
| 1987 |
|
| 1988 |
-
/* ══════════════════════════════════════════════════════
|
| 1989 |
-
MODEL SELECTOR — CheckboxGroup as toggle chips
|
| 1990 |
-
Each item is a pill; checked = vivid coloured fill.
|
| 1991 |
-
══════════════════════════════════════════════════════ */
|
| 1992 |
#model-selector .wrap {
|
| 1993 |
display: flex !important;
|
| 1994 |
flex-wrap: wrap !important;
|
| 1995 |
gap: 8px !important;
|
| 1996 |
padding: 10px 4px 6px 4px !important;
|
| 1997 |
}
|
| 1998 |
-
/* Every checkbox item becomes a pill */
|
| 1999 |
#model-selector .wrap label {
|
| 2000 |
display: inline-flex !important;
|
| 2001 |
align-items: center !important;
|
|
@@ -2018,23 +2058,19 @@ button.primary:hover { transform: translateY(-2px) !important;
|
|
| 2018 |
background: #E8F4FD !important;
|
| 2019 |
color: #2C5F8A !important;
|
| 2020 |
}
|
| 2021 |
-
/* Checked state — vivid blue-purple fill, white text */
|
| 2022 |
#model-selector .wrap label:has(input:checked) {
|
| 2023 |
background: linear-gradient(135deg, #5BA8E5 0%, #7C6FCD 100%) !important;
|
| 2024 |
border-color: #5BA8E5 !important;
|
| 2025 |
color: #FFFFFF !important;
|
| 2026 |
box-shadow: 0 2px 8px rgba(91,168,229,0.40) !important;
|
| 2027 |
}
|
| 2028 |
-
/* Hide the raw checkbox square — the whole pill is the control */
|
| 2029 |
#model-selector .wrap input[type=checkbox] {
|
| 2030 |
width: 0 !important; height: 0 !important;
|
| 2031 |
margin: 0 !important; opacity: 0 !important;
|
| 2032 |
position: absolute !important;
|
| 2033 |
}
|
| 2034 |
-
/* Suppress the outer container label (just says "Models") */
|
| 2035 |
#model-selector > .label-wrap { display: none !important; }
|
| 2036 |
|
| 2037 |
-
/* ── Quick-action buttons row ── */
|
| 2038 |
.model-quick-btn button {
|
| 2039 |
font-size: 12px !important; font-weight: 600 !important;
|
| 2040 |
padding: 6px 14px !important; border-radius: 8px !important;
|
|
@@ -2047,7 +2083,6 @@ button.primary:hover { transform: translateY(-2px) !important;
|
|
| 2047 |
background: #EBF5FF !important;
|
| 2048 |
}
|
| 2049 |
|
| 2050 |
-
/* ── Scrollbar ── */
|
| 2051 |
::-webkit-scrollbar { width: 6px; height: 6px; }
|
| 2052 |
::-webkit-scrollbar-track { background: #F0F3FB; border-radius: 4px; }
|
| 2053 |
::-webkit-scrollbar-thumb { background: #C8D0E7; border-radius: 4px; }
|
|
@@ -2089,14 +2124,13 @@ with gr.Blocks(css=PASTEL_CSS, title="🧬 GWAS Pipeline", theme=gr.themes.Base(
|
|
| 2089 |
<p>10 Statistical Models · All-Model Manhattan & QQ · Circos · LD Decay · PNG Export · Full Excel</p>
|
| 2090 |
<p style="font-size:12px; color:#8892B0;">
|
| 2091 |
REML (intercept-projected) · VanRaden kinship · Mode imputation ·
|
| 2092 |
-
O(n) rotated GLS · Joint-model PVE · Publication-quality
|
| 2093 |
</p>
|
| 2094 |
</div>
|
| 2095 |
""")
|
| 2096 |
|
| 2097 |
with gr.Row(equal_height=False):
|
| 2098 |
|
| 2099 |
-
# ── LEFT PANEL ────────────────────────────────────────────────────────
|
| 2100 |
with gr.Column(scale=1, min_width=340):
|
| 2101 |
|
| 2102 |
gr.HTML('<div class="section-label">📂 Data Input</div>')
|
|
@@ -2106,22 +2140,17 @@ with gr.Blocks(css=PASTEL_CSS, title="🧬 GWAS Pipeline", theme=gr.themes.Base(
|
|
| 2106 |
value=SAMPLE_DATA,
|
| 2107 |
placeholder="Paste your CSV data here…")
|
| 2108 |
|
| 2109 |
-
# ── MODEL SELECTOR ────────────────────────────────────────────────
|
| 2110 |
gr.HTML('<div class="section-label" style="margin-top:16px;">⚙️ Select Models to Run</div>')
|
| 2111 |
gr.HTML(MODEL_INFO_HTML)
|
| 2112 |
|
| 2113 |
-
# CheckboxGroup: the ONLY Gradio widget that reliably shows
|
| 2114 |
-
# selectable multi-item state with visible tick/untick feedback.
|
| 2115 |
-
# CSS #model-selector turns each item into a coloured toggle pill.
|
| 2116 |
model_sel = gr.CheckboxGroup(
|
| 2117 |
choices=ALL_MODELS,
|
| 2118 |
-
value=ALL_MODELS,
|
| 2119 |
label="Models",
|
| 2120 |
elem_id="model-selector",
|
| 2121 |
interactive=True,
|
| 2122 |
)
|
| 2123 |
|
| 2124 |
-
# Quick-preset buttons — all return a list directly to model_sel
|
| 2125 |
with gr.Row():
|
| 2126 |
gr.Button("✅ All", size="sm",
|
| 2127 |
elem_classes=["model-quick-btn"]).click(
|
|
@@ -2138,14 +2167,12 @@ with gr.Blocks(css=PASTEL_CSS, title="🧬 GWAS Pipeline", theme=gr.themes.Base(
|
|
| 2138 |
fn=lambda: ["MLM", "EMMAX", "GEMMA", "CMLM"],
|
| 2139 |
outputs=model_sel)
|
| 2140 |
|
| 2141 |
-
# ── SETTINGS ──────────────────────────────────────────────────────
|
| 2142 |
gr.HTML('<div class="section-label" style="margin-top:14px;">🎛️ Settings</div>')
|
| 2143 |
maf_thr = gr.Slider(0, 0.5, value=0.05, step=0.01,
|
| 2144 |
label="MAF Threshold")
|
| 2145 |
|
| 2146 |
run_btn = gr.Button("🚀 Run GWAS Pipeline", variant="primary")
|
| 2147 |
|
| 2148 |
-
# ── DOWNLOADS ─────────────────────────────────────────────────────
|
| 2149 |
gr.HTML('<div class="section-label" style="margin-top:16px;">📥 Downloads</div>')
|
| 2150 |
with gr.Column(elem_classes=["download-section"]):
|
| 2151 |
excel_out = gr.File(
|
|
@@ -2155,14 +2182,12 @@ with gr.Blocks(css=PASTEL_CSS, title="🧬 GWAS Pipeline", theme=gr.themes.Base(
|
|
| 2155 |
label="🖼 All Plots PNG (ZIP)",
|
| 2156 |
interactive=False)
|
| 2157 |
|
| 2158 |
-
# ── RIGHT PANEL ───────────────────────────────────────────────────────
|
| 2159 |
with gr.Column(scale=2):
|
| 2160 |
gr.HTML('<div class="section-label">📊 Analysis Summary</div>')
|
| 2161 |
summary_out = gr.Textbox(label="", lines=30,
|
| 2162 |
elem_classes=["summary-box"],
|
| 2163 |
show_label=False)
|
| 2164 |
|
| 2165 |
-
# ── VISUALISATIONS ────────────────────────────────────────────────────────
|
| 2166 |
gr.HTML('<div class="section-label" style="margin:16px 0 8px 0;">🖼 Visualizations</div>')
|
| 2167 |
with gr.Tabs():
|
| 2168 |
with gr.Tab("🗺 Manhattan (Primary)"):
|
|
@@ -2190,7 +2215,6 @@ with gr.Blocks(css=PASTEL_CSS, title="🧬 GWAS Pipeline", theme=gr.themes.Base(
|
|
| 2190 |
with gr.Tab("🗂 All Models (Grid)"):
|
| 2191 |
img12 = gr.Image(type="pil", label="Manhattan Grid")
|
| 2192 |
|
| 2193 |
-
# ── RUN ───────────────────────────────────────────────────────────────────
|
| 2194 |
def run_wrapper(file_obj, text_data, selected_models, maf):
|
| 2195 |
if not selected_models:
|
| 2196 |
selected_models = ALL_MODELS
|
|
|
|
| 61 |
]
|
| 62 |
|
| 63 |
# Publication-style QQ gradient: grey (low p) → blue → yellow → red (high p)
|
|
|
|
| 64 |
QQ_CMAP = LinearSegmentedColormap.from_list(
|
| 65 |
"qq_pub",
|
| 66 |
["#AAAAAA", "#4575B4", "#74ADD1", "#ABD9E9",
|
|
|
|
| 184 |
K = (Z @ Z.T) / denom
|
| 185 |
return K
|
| 186 |
|
| 187 |
+
# ─────────────────────── REML — intercept projected out ──────────────────────
|
| 188 |
def reml_variance_components(y, K):
|
| 189 |
"""
|
| 190 |
REML variance components via eigendecomposition of K.
|
| 191 |
+
Projects out the intercept from Uty before the profile log-likelihood.
|
|
|
|
| 192 |
Returns (Vg, Ve, delta, eigvals, U).
|
| 193 |
"""
|
| 194 |
n = len(y)
|
|
|
|
| 198 |
Uty = U.T @ y
|
| 199 |
Ut1 = U.T @ np.ones(n)
|
| 200 |
|
| 201 |
+
# Project out intercept from the rotated phenotype
|
| 202 |
Uty = Uty - (np.dot(Uty, Ut1) / np.dot(Ut1, Ut1)) * Ut1
|
| 203 |
|
| 204 |
def neg_log_reml(log_delta):
|
| 205 |
delta = np.exp(log_delta)
|
| 206 |
d = eigvals + delta
|
|
|
|
| 207 |
ll = -0.5 * np.sum(np.log(d))
|
| 208 |
ll -= 0.5 * (n - 1) * np.log(np.maximum(np.sum(Uty**2 / d), 1e-12))
|
| 209 |
return -ll
|
|
|
|
| 218 |
Vg = max(float(Vg), 1e-8)
|
| 219 |
return Vg, Ve, float(delta), eigvals, U
|
| 220 |
|
| 221 |
+
# ─────────────────────── GLS — corrected SE calculation ───────────────────────
|
| 222 |
def gls_test(y, x, V_inv):
|
| 223 |
+
"""GLS single-SNP test."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 224 |
x = x.reshape(-1, 1)
|
| 225 |
one = np.ones((len(y), 1))
|
| 226 |
X = np.hstack([one, x])
|
|
|
|
| 236 |
resid = y - X @ coeffs
|
| 237 |
df = len(y) - 2
|
| 238 |
|
|
|
|
| 239 |
sigma2 = float(resid @ resid) / max(df, 1)
|
| 240 |
|
| 241 |
try:
|
|
|
|
| 255 |
slope, intercept, r, p, se = stats.linregress(x, y)
|
| 256 |
return float(slope), float(se), float(p)
|
| 257 |
|
| 258 |
+
# ─────────────────────── Rotated GLS — O(n) per SNP ───────────────────────────
|
| 259 |
def precompute_rotation(y, K):
|
| 260 |
+
"""Eigendecompose K once. Returns everything needed for O(n)-per-SNP tests."""
|
|
|
|
|
|
|
|
|
|
|
|
|
| 261 |
n = len(y)
|
| 262 |
Vg, Ve, delta, eigvals, U = reml_variance_components(y, K)
|
| 263 |
+
d = eigvals + delta
|
| 264 |
Uty = U.T @ y
|
| 265 |
Ut1 = U.T @ np.ones(n)
|
| 266 |
return U, d, Uty, Ut1, Vg, Ve, delta
|
| 267 |
|
| 268 |
def rotated_gls_snp(Utx, Uty, Ut1, d):
|
| 269 |
+
"""Single-SNP GLS test using pre-rotated vectors — all operations O(n)."""
|
|
|
|
|
|
|
|
|
|
|
|
|
| 270 |
n = len(Uty)
|
| 271 |
df = n - 2
|
| 272 |
|
|
|
|
| 273 |
S11 = np.sum(Ut1**2 / d)
|
| 274 |
S1x = np.sum(Ut1 * Utx / d)
|
| 275 |
Sxx = np.sum(Utx**2 / d)
|
|
|
|
| 283 |
beta = (S11 * Sxy - S1x * S1y) / denom
|
| 284 |
intercept= (S1y - S1x * beta) / S11
|
| 285 |
|
|
|
|
| 286 |
resid_rot = Uty - intercept * Ut1 - beta * Utx
|
| 287 |
sigma2 = np.dot(resid_rot, resid_rot) / max(df, 1)
|
| 288 |
|
|
|
|
| 292 |
p_val = float(2 * stats.t.sf(abs(t_stat), df=max(df, 1)))
|
| 293 |
return float(beta), se, p_val
|
| 294 |
|
| 295 |
+
# ───────────��─────────── Joint-model PVE ──────────────────────────────────────
|
| 296 |
def compute_pve(y, G, pvals, betas, ses, threshold=0.05):
|
| 297 |
+
"""Computes partial r² via type-II SS from a joint OLS model."""
|
|
|
|
|
|
|
|
|
|
|
|
|
| 298 |
bonf = threshold / len(pvals)
|
| 299 |
sig_idx = list(np.where(pvals < bonf)[0])
|
| 300 |
SST = np.sum((y - y.mean())**2)
|
|
|
|
| 303 |
if SST < 1e-10 or len(sig_idx) == 0:
|
| 304 |
return {}, SST
|
| 305 |
|
|
|
|
| 306 |
X_parts = [np.ones(len(y))]
|
| 307 |
valid_idx = []
|
| 308 |
for idx in sig_idx:
|
|
|
|
| 322 |
return {idx: 0.0 for idx in valid_idx}, SST
|
| 323 |
|
| 324 |
for k, idx in enumerate(valid_idx):
|
|
|
|
| 325 |
X_drop = np.delete(X_joint, k + 1, axis=1)
|
| 326 |
try:
|
| 327 |
c_drop = np.linalg.lstsq(X_drop, y, rcond=None)[0]
|
|
|
|
| 334 |
|
| 335 |
return pve_dict, SST
|
| 336 |
|
| 337 |
+
# ─────────────────────── 10 STATISTICAL MODELS ────────────────────────────────
|
| 338 |
|
| 339 |
def ols_gwas(y, G):
|
| 340 |
"""OLS: simple linear regression, no structure correction."""
|
|
|
|
| 346 |
return pvals, betas, ses
|
| 347 |
|
| 348 |
def mlm_gwas(y, G, K):
|
| 349 |
+
"""MLM (EMMAX-style full GLS): mixed model with REML variance components."""
|
|
|
|
|
|
|
|
|
|
| 350 |
n, m = G.shape
|
| 351 |
pvals = np.ones(m); betas = np.zeros(m); ses = np.zeros(m)
|
| 352 |
|
|
|
|
| 442 |
n, m = G.shape
|
| 443 |
pvals = np.ones(m); betas = np.zeros(m); ses = np.zeros(m)
|
| 444 |
|
|
|
|
| 445 |
U, d, Uty, Ut1, Vg, Ve, delta = precompute_rotation(y, K)
|
| 446 |
|
| 447 |
init_p = np.ones(m)
|
|
|
|
| 505 |
n, m = G.shape
|
| 506 |
pvals = np.ones(m); betas = np.zeros(m); ses = np.zeros(m)
|
| 507 |
|
|
|
|
| 508 |
U, d, Uty, Ut1, Vg, Ve, delta = precompute_rotation(y, K)
|
| 509 |
|
| 510 |
qtns_prev = []
|
|
|
|
| 557 |
return pvals, betas, ses
|
| 558 |
|
| 559 |
def emmax_gwas(y, G, K):
|
| 560 |
+
"""EMMAX: efficient mixed-model using the K eigenrotation trick."""
|
|
|
|
|
|
|
|
|
|
|
|
|
| 561 |
n, m = G.shape
|
| 562 |
pvals = np.ones(m); betas = np.zeros(m); ses = np.zeros(m)
|
| 563 |
|
|
|
|
| 564 |
U, d, Uty, Ut1, Vg, Ve, delta = precompute_rotation(y, K)
|
| 565 |
|
| 566 |
for j in range(m):
|
|
|
|
| 595 |
except Exception:
|
| 596 |
PCs = np.zeros((n, 1))
|
| 597 |
|
|
|
|
| 598 |
U, d, Uty, Ut1, Vg, Ve, delta = precompute_rotation(y, K)
|
| 599 |
|
| 600 |
qtns = []
|
|
|
|
| 648 |
return pvals, betas, ses
|
| 649 |
|
| 650 |
def gemma_gwas(y, G, K):
|
| 651 |
+
"""GEMMA LMM: centered kinship + REML via rotation trick."""
|
|
|
|
|
|
|
|
|
|
|
|
|
| 652 |
n, m = G.shape
|
| 653 |
pvals = np.ones(m); betas = np.zeros(m); ses = np.zeros(m)
|
| 654 |
|
|
|
|
| 655 |
row_mean = K.mean(axis=1, keepdims=True)
|
| 656 |
col_mean = K.mean(axis=0, keepdims=True)
|
| 657 |
grand_mean = K.mean()
|
| 658 |
Kc = K - row_mean - col_mean + grand_mean
|
| 659 |
|
|
|
|
| 660 |
U, d, Uty, Ut1, Vg, Ve, delta = precompute_rotation(y, Kc)
|
| 661 |
|
| 662 |
for j in range(m):
|
|
|
|
| 670 |
pvals[j] = p; betas[j] = b; ses[j] = se
|
| 671 |
return pvals, betas, ses
|
| 672 |
|
| 673 |
+
# ─────────────────────── FIGURE HELPERS ───────────────────────────────────────
|
| 674 |
def fig_to_pil(fig):
|
| 675 |
buf = io.BytesIO()
|
| 676 |
fig.savefig(buf, format="png", dpi=150, bbox_inches="tight",
|
|
|
|
| 690 |
buf.close()
|
| 691 |
return data
|
| 692 |
|
| 693 |
+
# ─────────────────────── Manhattan tick midpoints ─────────────────────────────
|
| 694 |
def _compute_x_coords(chroms, positions, chrom_list):
|
| 695 |
"""Compute x-axis coords for Manhattan layout."""
|
| 696 |
x_coords = np.zeros(len(chroms))
|
|
|
|
| 706 |
return x_coords
|
| 707 |
|
| 708 |
def _compute_tick_positions(x_coords, chroms, chrom_list):
|
| 709 |
+
"""Tick at span midpoint, not coordinate mean."""
|
|
|
|
|
|
|
|
|
|
| 710 |
tick_pos, tick_lab = [], []
|
| 711 |
for ch in chrom_list:
|
| 712 |
mask = chroms == ch
|
| 713 |
if not mask.any():
|
| 714 |
continue
|
| 715 |
xc = x_coords[mask]
|
|
|
|
| 716 |
tick_pos.append((xc.min() + xc.max()) / 2)
|
| 717 |
tick_lab.append(f"Chr{ch}")
|
| 718 |
return tick_pos, tick_lab
|
|
|
|
| 762 |
return fig
|
| 763 |
|
| 764 |
def _draw_qq_on_ax(ax, pvals, model_name, color):
|
| 765 |
+
"""QQ plot matching the reference image style."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 766 |
n = len(pvals)
|
| 767 |
obs_raw = -np.log10(np.clip(pvals, 1e-300, 1))
|
| 768 |
+
sort_i = np.argsort(obs_raw)[::-1]
|
|
|
|
|
|
|
| 769 |
obs = obs_raw[sort_i]
|
| 770 |
+
exp = -np.log10(np.arange(1, n + 1) / n)
|
|
|
|
| 771 |
|
|
|
|
|
|
|
| 772 |
ranks = np.arange(1, n + 1)
|
| 773 |
ci_lo = -np.log10(stats.beta.ppf(0.975, ranks, n - ranks + 1))
|
| 774 |
ci_hi = -np.log10(stats.beta.ppf(0.025, ranks, n - ranks + 1))
|
| 775 |
|
|
|
|
| 776 |
import matplotlib.colors as mcolors
|
| 777 |
rgb = mcolors.to_rgb(color)
|
| 778 |
ax.fill_between(exp, ci_lo, ci_hi,
|
| 779 |
color=rgb, alpha=0.22, zorder=1)
|
|
|
|
| 780 |
|
|
|
|
| 781 |
xy_max = max(float(exp.max()), float(obs.max())) * 1.06
|
| 782 |
ax.plot([0, xy_max], [0, xy_max],
|
| 783 |
color="#E8453C", ls="--", lw=1.8, zorder=2, label="Expected")
|
| 784 |
|
|
|
|
|
|
|
| 785 |
sig_thr = -np.log10(5e-8)
|
| 786 |
ns_mask = obs < sig_thr
|
| 787 |
if ns_mask.any():
|
|
|
|
| 789 |
c=color, s=14, alpha=0.85,
|
| 790 |
linewidths=0, zorder=3)
|
| 791 |
|
|
|
|
| 792 |
gw_mask = obs >= sig_thr
|
| 793 |
if gw_mask.any():
|
| 794 |
ax.scatter(exp[gw_mask], obs[gw_mask],
|
|
|
|
| 796 |
linewidths=0.6, edgecolors="white", zorder=5,
|
| 797 |
label=f"GW sig. (n={int(gw_mask.sum())})")
|
| 798 |
|
|
|
|
| 799 |
lam = (np.median(stats.chi2.ppf(1 - np.clip(pvals, 1e-10, 1), df=1))
|
| 800 |
/ stats.chi2.ppf(0.5, df=1))
|
| 801 |
lam_str = f"λ = {lam:.4f}"
|
|
|
|
| 808 |
facecolor="white", edgecolor=lam_col,
|
| 809 |
alpha=0.88, linewidth=1.0))
|
| 810 |
|
|
|
|
| 811 |
ax.set_facecolor("white")
|
| 812 |
ax.set_xlabel("Expected −log₁₀(p)", fontsize=10, color="#222222",
|
| 813 |
labelpad=6)
|
|
|
|
| 816 |
ax.tick_params(axis="both", colors="#222222", labelsize=9,
|
| 817 |
direction="out", length=5, width=0.9,
|
| 818 |
top=False, right=False)
|
|
|
|
| 819 |
ax.spines["top"].set_visible(False)
|
| 820 |
ax.spines["right"].set_visible(False)
|
| 821 |
ax.spines["bottom"].set_edgecolor("#333333")
|
|
|
|
| 825 |
ax.set_axisbelow(False)
|
| 826 |
ax.grid(False)
|
| 827 |
|
|
|
|
| 828 |
ax.set_xlim(-0.05, xy_max)
|
| 829 |
y_max = max(float(obs.max()), sig_thr) * 1.10
|
| 830 |
ax.set_ylim(-0.15, y_max)
|
|
|
|
| 840 |
full_title = f"{title}{' — ' + model_name if model_name else ''}"
|
| 841 |
ax.set_title(full_title, color="#1E293B", fontsize=12,
|
| 842 |
fontweight="bold", pad=8)
|
|
|
|
| 843 |
handles, labels = ax.get_legend_handles_labels()
|
|
|
|
| 844 |
ax.legend(handles, labels, fontsize=7.5,
|
| 845 |
framealpha=0.92, facecolor="white",
|
| 846 |
edgecolor="#CCCCCC", labelcolor="#333333",
|
|
|
|
| 888 |
for mname, (pvals, _, _) in all_results.items():
|
| 889 |
n = len(pvals)
|
| 890 |
obs_raw = -np.log10(np.clip(pvals, 1e-300, 1))
|
| 891 |
+
sort_i = np.argsort(obs_raw)[::-1]
|
| 892 |
obs = obs_raw[sort_i]
|
| 893 |
+
exp = -np.log10(np.arange(1, n + 1) / n)
|
| 894 |
exp_max = max(exp_max, exp.max())
|
| 895 |
lam = (np.median(stats.chi2.ppf(1 - np.clip(pvals, 1e-10, 1), df=1))
|
| 896 |
/ stats.chi2.ppf(0.5, df=1))
|
|
|
|
| 994 |
|
| 995 |
def plot_ld_decay(G, positions, chroms):
|
| 996 |
"""
|
| 997 |
+
IMPROVED LD DECAY PLOT
|
| 998 |
+
- Samples 150 SNPs per chromosome for reliable curves
|
| 999 |
+
- Clear distance markers in both bp and Mb
|
| 1000 |
+
- Shows where r² = 0.5 and 0.2 decay occurs
|
| 1001 |
+
- Better binning and visualization
|
| 1002 |
"""
|
| 1003 |
fig, axes = plt.subplots(1, 2, figsize=(16, 6), facecolor=BG_WHITE)
|
| 1004 |
style_fig(fig)
|
| 1005 |
|
| 1006 |
chrom_list = sorted(set(chroms))
|
|
|
|
| 1007 |
sample_per_chr = 150
|
| 1008 |
sampled_idx = []
|
| 1009 |
rng = np.random.default_rng(42)
|
| 1010 |
+
|
| 1011 |
for ch in chrom_list:
|
| 1012 |
idx_ch = np.where(chroms == ch)[0]
|
| 1013 |
n_samp = min(sample_per_chr, len(idx_ch))
|
|
|
|
| 1041 |
dists_mb = dists_bp / 1_000_000
|
| 1042 |
r2s = np.array(r2s)
|
| 1043 |
|
| 1044 |
+
def bin_ld_enhanced(dists, r2s, n_bins=30):
|
| 1045 |
+
"""Enhanced binning with better statistics"""
|
| 1046 |
bins = np.percentile(dists, np.linspace(0, 100, n_bins + 1))
|
| 1047 |
centers, means, sems = [], [], []
|
| 1048 |
for k in range(len(bins) - 1):
|
|
|
|
| 1053 |
sems.append(stats.sem(r2s[mask]))
|
| 1054 |
return np.array(centers), np.array(means), np.array(sems)
|
| 1055 |
|
| 1056 |
+
# Plot for both bp and Mb
|
| 1057 |
for ax, dists, unit, c1, c2 in [
|
| 1058 |
(axes[0], dists_bp, "bp", ACCENT_TEAL, ACCENT_CORAL),
|
| 1059 |
(axes[1], dists_mb, "Mb", ACCENT_PURP, ACCENT_GOLD),
|
| 1060 |
]:
|
| 1061 |
ax.set_facecolor(PANEL_WHITE)
|
| 1062 |
+
|
| 1063 |
+
# Raw data points
|
| 1064 |
+
ax.scatter(dists, r2s, c=c1, s=8, alpha=0.25, linewidths=0, label="Pairwise LD")
|
| 1065 |
+
|
| 1066 |
+
# Binned mean with error bands
|
| 1067 |
+
bc, bm, bs = bin_ld_enhanced(dists, r2s)
|
| 1068 |
if len(bc) > 0:
|
| 1069 |
+
ax.plot(bc, bm, color=c2, lw=3.0, marker='o', ms=6,
|
| 1070 |
+
zorder=5, label="Binned mean r²", markersize=4)
|
| 1071 |
+
ax.fill_between(bc, bm - bs, bm + bs, alpha=0.25, color=c2)
|
| 1072 |
+
|
| 1073 |
+
# Reference lines
|
| 1074 |
+
ax.axhline(0.5, color=ACCENT_GOLD, ls='--', lw=2.0, alpha=0.9, label="r² = 0.5")
|
| 1075 |
+
ax.axhline(0.2, color=ACCENT_CYAN, ls=':', lw=1.8, alpha=0.8, label="r² = 0.2")
|
| 1076 |
+
|
| 1077 |
+
# Find where decay crosses thresholds
|
| 1078 |
+
if len(bc) > 0:
|
| 1079 |
+
# Find crossing points
|
| 1080 |
+
for threshold, thr_label, thr_color in [(0.5, "50%", ACCENT_GOLD), (0.2, "20%", ACCENT_CYAN)]:
|
| 1081 |
+
cross_idx = np.where(bm < threshold)[0]
|
| 1082 |
+
if len(cross_idx) > 0:
|
| 1083 |
+
cross_dist = bc[cross_idx[0]]
|
| 1084 |
+
ax.axvline(cross_dist, color=thr_color, ls=':', lw=1.2, alpha=0.6)
|
| 1085 |
+
# Annotation
|
| 1086 |
+
ax.text(cross_dist, threshold + 0.05,
|
| 1087 |
+
f"{thr_label} decay\n@ {cross_dist:.1f} {unit}",
|
| 1088 |
+
fontsize=8, ha='center', va='bottom',
|
| 1089 |
+
bbox=dict(boxstyle='round,pad=0.4',
|
| 1090 |
+
facecolor='white', edgecolor=thr_color, alpha=0.8))
|
| 1091 |
+
|
| 1092 |
+
ax.set_xlabel(f"Distance ({unit})", fontsize=10, color=TEXT_DIM, fontweight='bold')
|
| 1093 |
+
ax.set_ylabel("r² (LD)", fontsize=10, color=TEXT_DIM, fontweight='bold')
|
| 1094 |
+
ax.set_title(f"LD Decay — {unit}", color=TEXT_MAIN, fontsize=11, fontweight='bold')
|
| 1095 |
+
ax.legend(fontsize=7.5, framealpha=0.95, facecolor=BG_WHITE,
|
| 1096 |
+
edgecolor=GRID_LINE, labelcolor=TEXT_MAIN, loc='upper right')
|
| 1097 |
ax.set_ylim(0, 1.05)
|
| 1098 |
+
|
| 1099 |
+
# Better grid
|
| 1100 |
+
ax.grid(True, color=GRID_LINE, linewidth=0.5, linestyle='--', alpha=0.5)
|
| 1101 |
|
| 1102 |
+
fig.suptitle("Linkage Disequilibrium (LD) Decay Analysis",
|
| 1103 |
+
color=TEXT_MAIN, fontsize=14, fontweight='bold')
|
| 1104 |
fig.tight_layout()
|
| 1105 |
return fig
|
| 1106 |
|
|
|
|
| 1256 |
return fig
|
| 1257 |
|
| 1258 |
def plot_kinship(K, ids):
|
| 1259 |
+
"""
|
| 1260 |
+
IMPROVED KINSHIP PLOT
|
| 1261 |
+
- Smart label handling for large datasets
|
| 1262 |
+
- No overlapping labels
|
| 1263 |
+
- Dynamic figure sizing
|
| 1264 |
+
"""
|
| 1265 |
+
n_samples = len(ids)
|
| 1266 |
+
|
| 1267 |
+
# Smart label strategy
|
| 1268 |
+
if n_samples > 100:
|
| 1269 |
+
# For very large datasets: no labels on dendrogram
|
| 1270 |
+
show_labels = False
|
| 1271 |
+
label_list = None
|
| 1272 |
+
fig_height = 12
|
| 1273 |
+
elif n_samples > 50:
|
| 1274 |
+
# For medium datasets: show every 5th label
|
| 1275 |
+
show_labels = True
|
| 1276 |
+
label_list = [ids[i] if i % 5 == 0 else '' for i in range(n_samples)]
|
| 1277 |
+
fig_height = 14
|
| 1278 |
+
else:
|
| 1279 |
+
# For small datasets: show all labels
|
| 1280 |
+
show_labels = True
|
| 1281 |
+
label_list = ids
|
| 1282 |
+
fig_height = 12
|
| 1283 |
+
|
| 1284 |
+
fig, axes = plt.subplots(2, 2, figsize=(14, fig_height), facecolor=BG_WHITE)
|
| 1285 |
style_fig(fig)
|
| 1286 |
for ax in axes.flatten():
|
| 1287 |
ax.set_facecolor(PANEL_WHITE)
|
| 1288 |
|
| 1289 |
+
# Kinship heatmap
|
| 1290 |
im = axes[0,0].imshow(K, cmap='RdYlBu_r', aspect='auto', vmin=-0.5, vmax=1)
|
| 1291 |
+
axes[0,0].set_title("Kinship Matrix (VanRaden)", color=TEXT_MAIN, fontsize=11, fontweight='bold')
|
| 1292 |
+
plt.colorbar(im, ax=axes[0,0], label="Kinship coefficient")
|
| 1293 |
|
| 1294 |
+
# Distribution
|
| 1295 |
K_flat = K[np.triu_indices_from(K, k=1)]
|
| 1296 |
axes[0,1].hist(K_flat, bins=30, color=ACCENT_PURP, edgecolor='none', alpha=0.85)
|
| 1297 |
+
axes[0,1].axvline(K_flat.mean(), color=ACCENT_CORAL, ls='--', lw=2,
|
| 1298 |
+
label=f"Mean: {K_flat.mean():.3f}")
|
| 1299 |
+
axes[0,1].set_title("Pairwise Kinship Distribution", color=TEXT_MAIN, fontsize=11, fontweight='bold')
|
| 1300 |
+
axes[0,1].set_xlabel("Kinship coefficient", color=TEXT_DIM)
|
| 1301 |
+
axes[0,1].set_ylabel("Frequency", color=TEXT_DIM)
|
| 1302 |
+
axes[0,1].legend(fontsize=8)
|
| 1303 |
+
|
| 1304 |
+
# Dendrogram with smart labeling
|
| 1305 |
try:
|
| 1306 |
lm = linkage(K, method='average')
|
| 1307 |
+
if show_labels and label_list is not None:
|
| 1308 |
+
dendrogram(lm, ax=axes[1,0], labels=label_list,
|
| 1309 |
+
leaf_rotation=90, leaf_font_size=6 if n_samples <= 50 else 4,
|
| 1310 |
+
color_threshold=0.7,
|
| 1311 |
+
above_threshold_color=ACCENT_TEAL)
|
| 1312 |
+
else:
|
| 1313 |
+
# No labels for very large datasets
|
| 1314 |
+
dendrogram(lm, ax=axes[1,0], no_labels=True,
|
| 1315 |
+
color_threshold=0.7,
|
| 1316 |
+
above_threshold_color=ACCENT_TEAL)
|
| 1317 |
+
axes[1,0].text(0.5, 0.02, f"({n_samples} samples - labels hidden for clarity)",
|
| 1318 |
+
transform=axes[1,0].transAxes, ha='center',
|
| 1319 |
+
fontsize=8, color=TEXT_DIM, style='italic')
|
| 1320 |
+
except Exception as e:
|
| 1321 |
+
axes[1,0].text(0.5, 0.5, f"Dendrogram unavailable\n({str(e)})",
|
| 1322 |
+
ha='center', transform=axes[1,0].transAxes, color=TEXT_DIM)
|
| 1323 |
+
axes[1,0].set_title("Hierarchical Clustering Dendrogram", color=TEXT_MAIN, fontsize=11, fontweight='bold')
|
| 1324 |
+
axes[1,0].set_xlabel("Sample", color=TEXT_DIM)
|
| 1325 |
+
axes[1,0].set_ylabel("Distance", color=TEXT_DIM)
|
| 1326 |
|
| 1327 |
+
# Kinship PCA
|
| 1328 |
eigvals, eigvecs = np.linalg.eigh(K)
|
| 1329 |
idx = np.argsort(eigvals)[::-1]
|
| 1330 |
+
var_exp1 = eigvals[idx[0]] / eigvals.sum() * 100
|
| 1331 |
+
var_exp2 = eigvals[idx[1]] / eigvals.sum() * 100
|
| 1332 |
axes[1,1].scatter(eigvecs[:, idx[0]], eigvecs[:, idx[1]],
|
| 1333 |
+
c=ACCENT_TEAL, s=60, edgecolors='white', linewidths=0.5, alpha=0.8)
|
| 1334 |
+
axes[1,1].set_title("Kinship PCA", color=TEXT_MAIN, fontsize=11, fontweight='bold')
|
| 1335 |
+
axes[1,1].set_xlabel(f"PC1 ({var_exp1:.1f}%)", color=TEXT_DIM)
|
| 1336 |
+
axes[1,1].set_ylabel(f"PC2 ({var_exp2:.1f}%)", color=TEXT_DIM)
|
| 1337 |
+
axes[1,1].grid(True, alpha=0.3)
|
| 1338 |
+
|
| 1339 |
+
fig.suptitle(f"Kinship Analysis ({n_samples} samples)",
|
| 1340 |
+
color=TEXT_MAIN, fontsize=13, fontweight='bold')
|
| 1341 |
fig.tight_layout()
|
| 1342 |
return fig
|
| 1343 |
|
|
|
|
| 1384 |
return fig
|
| 1385 |
|
| 1386 |
def plot_summary_dashboard(y, maf, all_results, G_filt):
|
| 1387 |
+
"""
|
| 1388 |
+
IMPROVED SUMMARY DASHBOARD
|
| 1389 |
+
- Better lambda interpretation
|
| 1390 |
+
- Variance component display
|
| 1391 |
+
- Model statistics
|
| 1392 |
+
"""
|
| 1393 |
fig, axes = plt.subplots(2, 3, figsize=(15, 10), facecolor=BG_WHITE)
|
| 1394 |
style_fig(fig)
|
| 1395 |
axes = axes.flatten()
|
| 1396 |
for ax in axes:
|
| 1397 |
ax.set_facecolor(PANEL_WHITE)
|
| 1398 |
|
| 1399 |
+
# Phenotype distribution
|
| 1400 |
axes[0].hist(y, bins=15, color=ACCENT_PURP, edgecolor='none', alpha=0.85)
|
| 1401 |
axes[0].axvline(y.mean(), color=ACCENT_CORAL, lw=2, ls='--',
|
| 1402 |
label=f"Mean: {y.mean():.2f}")
|
| 1403 |
+
axes[0].set_title(f"Phenotype Distribution | n={len(y)}", color=TEXT_MAIN, fontweight='bold')
|
| 1404 |
+
axes[0].set_xlabel("Phenotype value", color=TEXT_DIM)
|
| 1405 |
+
axes[0].set_ylabel("Frequency", color=TEXT_DIM)
|
| 1406 |
axes[0].legend(fontsize=7, facecolor=BG_WHITE)
|
| 1407 |
|
| 1408 |
+
# MAF distribution
|
| 1409 |
axes[1].hist(maf, bins=20, color=ACCENT_TEAL, edgecolor='none', alpha=0.85)
|
| 1410 |
+
axes[1].axvline(0.05, color=ACCENT_CORAL, ls='--', lw=2, label="MAF = 0.05")
|
| 1411 |
+
axes[1].set_title(f"MAF Distribution | rare={np.sum(maf<0.05)}", color=TEXT_MAIN, fontweight='bold')
|
| 1412 |
+
axes[1].set_xlabel("Minor Allele Frequency", color=TEXT_DIM)
|
| 1413 |
+
axes[1].set_ylabel("Count", color=TEXT_DIM)
|
| 1414 |
+
axes[1].legend(fontsize=7)
|
| 1415 |
|
| 1416 |
+
# Lambda (genomic inflation) with interpretation
|
| 1417 |
lambdas = {}
|
| 1418 |
for mname, (p, _, _) in all_results.items():
|
| 1419 |
lam = (np.median(stats.chi2.ppf(1 - np.clip(p, 1e-10, 1), df=1))
|
| 1420 |
/ stats.chi2.ppf(0.5, df=1))
|
| 1421 |
lambdas[mname] = lam
|
| 1422 |
+
|
| 1423 |
+
colors_lam = [ACCENT_TEAL if v <= 1.05 else ACCENT_GOLD if v <= 1.15
|
| 1424 |
else ACCENT_CORAL for v in lambdas.values()]
|
| 1425 |
axes[2].bar(lambdas.keys(), lambdas.values(),
|
| 1426 |
color=colors_lam, edgecolor='none', alpha=0.88)
|
| 1427 |
+
axes[2].axhline(1.0, color=TEXT_DIM, ls='--', lw=1.5, label="λ = 1.0 (ideal)")
|
| 1428 |
+
axes[2].axhline(1.05, color=ACCENT_TEAL, ls=':', lw=1, alpha=0.7, label="λ ≤ 1.05 (good)")
|
| 1429 |
+
axes[2].axhline(1.15, color=ACCENT_GOLD, ls=':', lw=1, alpha=0.7, label="λ ≤ 1.15 (acceptable)")
|
| 1430 |
+
axes[2].set_title("Genomic Inflation λ per Model", color=TEXT_MAIN, fontweight='bold')
|
| 1431 |
+
axes[2].set_ylabel("λ (lambda)", color=TEXT_DIM)
|
| 1432 |
axes[2].tick_params(axis='x', rotation=35, labelsize=7)
|
| 1433 |
+
axes[2].legend(fontsize=6, loc='upper left')
|
| 1434 |
+
axes[2].text(0.98, 0.02,
|
| 1435 |
+
"λ ≈ 1: well-controlled\nλ > 1: inflation (stratification)\nλ < 1: over-correction",
|
| 1436 |
+
transform=axes[2].transAxes, fontsize=7, ha='right', va='bottom',
|
| 1437 |
+
bbox=dict(boxstyle='round,pad=0.4', facecolor='white',
|
| 1438 |
+
edgecolor=GRID_LINE, alpha=0.9))
|
| 1439 |
+
|
| 1440 |
+
# Significant SNPs
|
| 1441 |
sig_counts = {}
|
| 1442 |
bonf = 0.05 / len(list(all_results.values())[0][0])
|
| 1443 |
for mname, (p, _, _) in all_results.items():
|
|
|
|
| 1445 |
cols_bar = [MODEL_COLORS.get(m, ACCENT_BLUE) for m in sig_counts]
|
| 1446 |
axes[3].bar(sig_counts.keys(), sig_counts.values(),
|
| 1447 |
color=cols_bar, edgecolor='none', alpha=0.88)
|
| 1448 |
+
axes[3].set_title("Significant SNPs per Model (Bonferroni)", color=TEXT_MAIN, fontweight='bold')
|
| 1449 |
+
axes[3].set_ylabel("Count", color=TEXT_DIM)
|
| 1450 |
axes[3].tick_params(axis='x', rotation=35, labelsize=7)
|
| 1451 |
|
| 1452 |
+
# Model concordance
|
| 1453 |
n_m = len(all_results)
|
| 1454 |
model_names = list(all_results.keys())
|
| 1455 |
concordance = np.eye(n_m)
|
|
|
|
| 1470 |
ha='center', va='center', fontsize=5,
|
| 1471 |
color='black' if abs(concordance[i,j]) < 0.7 else 'white')
|
| 1472 |
plt.colorbar(im, ax=axes[4], label="Spearman ρ")
|
| 1473 |
+
axes[4].set_title("Model Concordance (Spearman ρ)", color=TEXT_MAIN, fontweight='bold')
|
| 1474 |
|
| 1475 |
+
# Summary statistics
|
| 1476 |
first_model = model_names[0]
|
| 1477 |
miss_r = np.isnan(G_filt).mean()
|
| 1478 |
axes[5].text(0.5, 0.5,
|
|
|
|
| 1488 |
color=TEXT_MAIN, fontsize=11,
|
| 1489 |
bbox=dict(boxstyle='round,pad=0.6',
|
| 1490 |
facecolor=PANEL_LIGHT, edgecolor=GRID_LINE, alpha=0.8))
|
| 1491 |
+
axes[5].set_title("Pipeline Summary", color=TEXT_MAIN, fontweight='bold')
|
| 1492 |
+
axes[5].axis('off')
|
| 1493 |
+
|
| 1494 |
fig.tight_layout()
|
| 1495 |
return fig
|
| 1496 |
|
|
|
|
| 1511 |
|
| 1512 |
bonf = bonf_threshold
|
| 1513 |
|
| 1514 |
+
# Sheet 1: Summary
|
| 1515 |
ws_sum = wb.active
|
| 1516 |
ws_sum.title = "Summary"
|
| 1517 |
ws_sum['A1'] = "GWAS Complete Analysis Summary"
|
|
|
|
| 1540 |
cell.fill = fill; cell.border = thin_border
|
| 1541 |
cell.alignment = Alignment(horizontal='center')
|
| 1542 |
|
| 1543 |
+
# Per-model sheets
|
| 1544 |
for mname, (pvals, betas, ses) in all_results.items():
|
| 1545 |
ws = wb.create_sheet(title=f"{mname}_AllSNPs")
|
| 1546 |
ws['A1'] = f"GWAS Results — {mname}"
|
|
|
|
| 1581 |
if col == 8 and isinstance(val, float):
|
| 1582 |
cell.number_format = '0.00E+00'
|
| 1583 |
|
| 1584 |
+
# Significant MTAs
|
| 1585 |
ws_mta = wb.create_sheet(title="Significant_MTAs")
|
| 1586 |
ws_mta['A1'] = "Significant MTAs — All Models"
|
| 1587 |
ws_mta['A1'].font = title_font
|
|
|
|
| 1627 |
cell.number_format = '0.00E+00'
|
| 1628 |
mta_row += 1
|
| 1629 |
|
| 1630 |
+
# QTN Effects
|
| 1631 |
ws_qtn = wb.create_sheet(title="QTN_Effects")
|
| 1632 |
ws_qtn['A1'] = "QTNs — Effect Analysis"
|
| 1633 |
ws_qtn['A1'].font = title_font
|
|
|
|
| 1668 |
cell.number_format = '0.00E+00'
|
| 1669 |
qtn_row += 1
|
| 1670 |
|
| 1671 |
+
# PVE Summary
|
| 1672 |
ws_pve = wb.create_sheet(title="PVE_Summary")
|
| 1673 |
ws_pve['A1'] = "Phenotypic Variance Explained (PVE) — Joint Model"
|
| 1674 |
ws_pve['A1'].font = title_font
|
|
|
|
| 1708 |
cell.number_format = '0.00E+00'
|
| 1709 |
pve_row += 1
|
| 1710 |
|
| 1711 |
+
# SNP QC
|
| 1712 |
ws_qc = wb.create_sheet(title="SNP_QC")
|
| 1713 |
ws_qc['A1'] = "SNP Quality Control Statistics"
|
| 1714 |
ws_qc['A1'].font = title_font
|
|
|
|
| 1746 |
with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf:
|
| 1747 |
for name, fig in plot_dict.items():
|
| 1748 |
if fig is not None:
|
| 1749 |
+
try:
|
| 1750 |
+
data = fig_to_png_bytes(fig)
|
| 1751 |
+
zf.writestr(f"{name}.png", data)
|
| 1752 |
+
except Exception as e:
|
| 1753 |
+
print(f"[WARN] Failed to save {name}: {e}")
|
| 1754 |
return zip_path
|
| 1755 |
|
| 1756 |
# ─────────────────────── MAIN PIPELINE ────────────────────────────────────────
|
|
|
|
| 1764 |
ids = df["ID"].values
|
| 1765 |
G_raw = df[snp_cols].values.astype(float)
|
| 1766 |
|
| 1767 |
+
# Build kinship BEFORE mode imputation
|
| 1768 |
K_raw = build_kinship(G_raw)
|
| 1769 |
|
| 1770 |
+
# Mode imputation
|
| 1771 |
G = impute_genotypes_mode(G_raw)
|
| 1772 |
n, m = G.shape
|
| 1773 |
|
|
|
|
| 1783 |
pos_filt = positions[keep] if len(positions) == m else np.arange(G_filt.shape[1])
|
| 1784 |
maf_vals = maf_vals_all[keep]
|
| 1785 |
|
| 1786 |
+
# Rebuild kinship on filtered data
|
| 1787 |
K = build_kinship(G_filt)
|
| 1788 |
|
| 1789 |
# Post-imputation MAF re-filter
|
|
|
|
| 1813 |
"CMLM": lambda: cmlm_gwas(y, G_filt, K),
|
| 1814 |
"BLINK": lambda: blink_gwas(y, G_filt, K),
|
| 1815 |
"FarmCPU": lambda: farmcpu_gwas(y, G_filt, K),
|
| 1816 |
+
"EMMAX": lambda: emmax_gwas(y, G_filt, K),
|
| 1817 |
"PLINK": lambda: plink_gwas(y, G_filt),
|
| 1818 |
"GAPIT3": lambda: gapit3_gwas(y, G_filt, K),
|
| 1819 |
+
"GEMMA": lambda: gemma_gwas(y, G_filt, K),
|
| 1820 |
}
|
| 1821 |
|
| 1822 |
all_results = {}
|
|
|
|
| 1826 |
primary_model = None
|
| 1827 |
errors = []
|
| 1828 |
|
| 1829 |
+
# Get variance components for summary
|
| 1830 |
+
Vg, Ve, delta, _, _ = reml_variance_components(y, K)
|
| 1831 |
+
h2 = Vg / (Vg + Ve)
|
| 1832 |
+
|
| 1833 |
for mname in models_to_run:
|
| 1834 |
if mname in model_funcs:
|
| 1835 |
try:
|
|
|
|
| 1848 |
|
| 1849 |
bonf = 0.05 / len(primary_p)
|
| 1850 |
|
| 1851 |
+
# Build plots
|
| 1852 |
plot_dict = {}
|
| 1853 |
try:
|
| 1854 |
plot_dict["01_Manhattan_Primary"] = plot_manhattan(primary_p, chr_filt, pos_filt, "Manhattan Plot", primary_model)
|
|
|
|
| 1910 |
f" MAF threshold : ≥{maf_thr:.2f}\n"
|
| 1911 |
f" Imputation : Mode (most frequent allele)\n"
|
| 1912 |
f" Kinship : VanRaden (2008) method\n"
|
| 1913 |
+
f" Variance comps : REML (intercept projected)\n"
|
| 1914 |
+
f" Vg (genetic) : {Vg:.4f}\n"
|
| 1915 |
+
f" Ve (residual) : {Ve:.4f}\n"
|
| 1916 |
+
f" h² (heritability): {h2:.4f}\n"
|
| 1917 |
f" GLS : Rotated O(n) per SNP (EMMAX/GEMMA) or full GLS (MLM)\n"
|
| 1918 |
+
f" PVE : Partial r² from joint model\n"
|
| 1919 |
f" Models run : {', '.join(all_results.keys())}\n"
|
| 1920 |
f"{'─'*68}\n"
|
| 1921 |
f" PER-MODEL RESULTS:\n {lambdas_str}\n"
|
|
|
|
| 1925 |
f" Bonferroni threshold : {bonf:.2e}\n"
|
| 1926 |
f" Significant MTAs : {int((primary_p<bonf).sum())}\n"
|
| 1927 |
f" Genomic Inflation λ : {lam:.4f}\n"
|
| 1928 |
+
f" (λ ≈ 1: well-controlled, λ > 1: inflation, λ < 1: over-correction)\n"
|
| 1929 |
f"{'─'*68}\n"
|
| 1930 |
f" 📥 Excel: gwas_results_complete.xlsx\n"
|
| 1931 |
f" • Summary · Per-model SNPs · Sig. MTAs · QTN · PVE · SNP QC\n"
|
|
|
|
| 1962 |
}
|
| 1963 |
.gradio-container { max-width: 1400px !important; margin: 0 auto !important; }
|
| 1964 |
|
|
|
|
| 1965 |
.gwas-header {
|
| 1966 |
background: linear-gradient(135deg, #E8F4FD 0%, #EDE9F8 50%, #FDF0F8 100%);
|
| 1967 |
border: 1px solid #D6E8F5; border-radius: 18px; padding: 28px 36px;
|
|
|
|
| 1972 |
.gwas-header p { color: #6B7A99 !important; font-size: 14px !important;
|
| 1973 |
margin: 4px 0 !important; }
|
| 1974 |
|
|
|
|
| 1975 |
.gr-panel, .gr-box, .block, .panel {
|
| 1976 |
background: #FFFFFF !important; border: 1px solid #E8ECF4 !important;
|
| 1977 |
border-radius: 14px !important; box-shadow: 0 1px 8px rgba(60,80,140,0.06) !important;
|
| 1978 |
}
|
| 1979 |
|
|
|
|
| 1980 |
.label-wrap span {
|
| 1981 |
color: #5A6480 !important; font-size: 12px !important; font-weight: 500 !important;
|
| 1982 |
text-transform: uppercase !important; letter-spacing: 0.5px !important;
|
|
|
|
| 1987 |
font-family: 'DM Mono', monospace !important; font-size: 12px !important;
|
| 1988 |
}
|
| 1989 |
|
|
|
|
| 1990 |
button.primary {
|
| 1991 |
background: linear-gradient(135deg, #5BA8E5 0%, #7C6FCD 100%) !important;
|
| 1992 |
border: none !important; border-radius: 12px !important; color: #FFFFFF !important;
|
|
|
|
| 1997 |
button.primary:hover { transform: translateY(-2px) !important;
|
| 1998 |
box-shadow: 0 6px 24px rgba(91,168,229,0.45) !important; }
|
| 1999 |
|
|
|
|
| 2000 |
.tab-nav {
|
| 2001 |
background: #F0F3FB !important; border-radius: 12px !important;
|
| 2002 |
padding: 4px !important; border: 1px solid #E4E8F5 !important; overflow-x: auto !important;
|
|
|
|
| 2011 |
box-shadow: 0 1px 6px rgba(91,168,229,0.2) !important;
|
| 2012 |
}
|
| 2013 |
|
|
|
|
| 2014 |
.summary-box textarea {
|
| 2015 |
font-family: 'DM Mono', monospace !important; font-size: 12px !important;
|
| 2016 |
background: #F8F9FF !important; color: #2D3142 !important;
|
| 2017 |
border: 1px solid #DDE2F0 !important; line-height: 1.7 !important;
|
| 2018 |
}
|
| 2019 |
|
|
|
|
| 2020 |
.download-section {
|
| 2021 |
background: linear-gradient(135deg, #EBF5FF 0%, #F0EBFF 100%);
|
| 2022 |
border: 1px solid #D0E4F5 !important; border-radius: 14px !important;
|
| 2023 |
padding: 18px !important;
|
| 2024 |
}
|
| 2025 |
|
|
|
|
| 2026 |
.section-label {
|
| 2027 |
font-size: 11px !important; font-weight: 600 !important; color: #8892B0 !important;
|
| 2028 |
text-transform: uppercase !important; letter-spacing: 1px !important;
|
|
|
|
| 2030 |
margin-bottom: 8px !important;
|
| 2031 |
}
|
| 2032 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2033 |
#model-selector .wrap {
|
| 2034 |
display: flex !important;
|
| 2035 |
flex-wrap: wrap !important;
|
| 2036 |
gap: 8px !important;
|
| 2037 |
padding: 10px 4px 6px 4px !important;
|
| 2038 |
}
|
|
|
|
| 2039 |
#model-selector .wrap label {
|
| 2040 |
display: inline-flex !important;
|
| 2041 |
align-items: center !important;
|
|
|
|
| 2058 |
background: #E8F4FD !important;
|
| 2059 |
color: #2C5F8A !important;
|
| 2060 |
}
|
|
|
|
| 2061 |
#model-selector .wrap label:has(input:checked) {
|
| 2062 |
background: linear-gradient(135deg, #5BA8E5 0%, #7C6FCD 100%) !important;
|
| 2063 |
border-color: #5BA8E5 !important;
|
| 2064 |
color: #FFFFFF !important;
|
| 2065 |
box-shadow: 0 2px 8px rgba(91,168,229,0.40) !important;
|
| 2066 |
}
|
|
|
|
| 2067 |
#model-selector .wrap input[type=checkbox] {
|
| 2068 |
width: 0 !important; height: 0 !important;
|
| 2069 |
margin: 0 !important; opacity: 0 !important;
|
| 2070 |
position: absolute !important;
|
| 2071 |
}
|
|
|
|
| 2072 |
#model-selector > .label-wrap { display: none !important; }
|
| 2073 |
|
|
|
|
| 2074 |
.model-quick-btn button {
|
| 2075 |
font-size: 12px !important; font-weight: 600 !important;
|
| 2076 |
padding: 6px 14px !important; border-radius: 8px !important;
|
|
|
|
| 2083 |
background: #EBF5FF !important;
|
| 2084 |
}
|
| 2085 |
|
|
|
|
| 2086 |
::-webkit-scrollbar { width: 6px; height: 6px; }
|
| 2087 |
::-webkit-scrollbar-track { background: #F0F3FB; border-radius: 4px; }
|
| 2088 |
::-webkit-scrollbar-thumb { background: #C8D0E7; border-radius: 4px; }
|
|
|
|
| 2124 |
<p>10 Statistical Models · All-Model Manhattan & QQ · Circos · LD Decay · PNG Export · Full Excel</p>
|
| 2125 |
<p style="font-size:12px; color:#8892B0;">
|
| 2126 |
REML (intercept-projected) · VanRaden kinship · Mode imputation ·
|
| 2127 |
+
O(n) rotated GLS · Joint-model PVE · Publication-quality plots
|
| 2128 |
</p>
|
| 2129 |
</div>
|
| 2130 |
""")
|
| 2131 |
|
| 2132 |
with gr.Row(equal_height=False):
|
| 2133 |
|
|
|
|
| 2134 |
with gr.Column(scale=1, min_width=340):
|
| 2135 |
|
| 2136 |
gr.HTML('<div class="section-label">📂 Data Input</div>')
|
|
|
|
| 2140 |
value=SAMPLE_DATA,
|
| 2141 |
placeholder="Paste your CSV data here…")
|
| 2142 |
|
|
|
|
| 2143 |
gr.HTML('<div class="section-label" style="margin-top:16px;">⚙️ Select Models to Run</div>')
|
| 2144 |
gr.HTML(MODEL_INFO_HTML)
|
| 2145 |
|
|
|
|
|
|
|
|
|
|
| 2146 |
model_sel = gr.CheckboxGroup(
|
| 2147 |
choices=ALL_MODELS,
|
| 2148 |
+
value=ALL_MODELS,
|
| 2149 |
label="Models",
|
| 2150 |
elem_id="model-selector",
|
| 2151 |
interactive=True,
|
| 2152 |
)
|
| 2153 |
|
|
|
|
| 2154 |
with gr.Row():
|
| 2155 |
gr.Button("✅ All", size="sm",
|
| 2156 |
elem_classes=["model-quick-btn"]).click(
|
|
|
|
| 2167 |
fn=lambda: ["MLM", "EMMAX", "GEMMA", "CMLM"],
|
| 2168 |
outputs=model_sel)
|
| 2169 |
|
|
|
|
| 2170 |
gr.HTML('<div class="section-label" style="margin-top:14px;">🎛️ Settings</div>')
|
| 2171 |
maf_thr = gr.Slider(0, 0.5, value=0.05, step=0.01,
|
| 2172 |
label="MAF Threshold")
|
| 2173 |
|
| 2174 |
run_btn = gr.Button("🚀 Run GWAS Pipeline", variant="primary")
|
| 2175 |
|
|
|
|
| 2176 |
gr.HTML('<div class="section-label" style="margin-top:16px;">📥 Downloads</div>')
|
| 2177 |
with gr.Column(elem_classes=["download-section"]):
|
| 2178 |
excel_out = gr.File(
|
|
|
|
| 2182 |
label="🖼 All Plots PNG (ZIP)",
|
| 2183 |
interactive=False)
|
| 2184 |
|
|
|
|
| 2185 |
with gr.Column(scale=2):
|
| 2186 |
gr.HTML('<div class="section-label">📊 Analysis Summary</div>')
|
| 2187 |
summary_out = gr.Textbox(label="", lines=30,
|
| 2188 |
elem_classes=["summary-box"],
|
| 2189 |
show_label=False)
|
| 2190 |
|
|
|
|
| 2191 |
gr.HTML('<div class="section-label" style="margin:16px 0 8px 0;">🖼 Visualizations</div>')
|
| 2192 |
with gr.Tabs():
|
| 2193 |
with gr.Tab("🗺 Manhattan (Primary)"):
|
|
|
|
| 2215 |
with gr.Tab("🗂 All Models (Grid)"):
|
| 2216 |
img12 = gr.Image(type="pil", label="Manhattan Grid")
|
| 2217 |
|
|
|
|
| 2218 |
def run_wrapper(file_obj, text_data, selected_models, maf):
|
| 2219 |
if not selected_models:
|
| 2220 |
selected_models = ALL_MODELS
|