Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -15,7 +15,7 @@ from scipy.cluster.hierarchy import dendrogram, linkage
|
|
| 15 |
from sklearn.decomposition import PCA
|
| 16 |
from sklearn.preprocessing import StandardScaler
|
| 17 |
from sklearn.linear_model import LinearRegression
|
| 18 |
-
from sklearn.manifold import MDS
|
| 19 |
from statsmodels.stats.multitest import multipletests
|
| 20 |
import io, re, os, zipfile, tempfile
|
| 21 |
from io import StringIO
|
|
@@ -23,54 +23,56 @@ from openpyxl import Workbook
|
|
| 23 |
from openpyxl.styles import Font, PatternFill, Alignment, Border, Side
|
| 24 |
from openpyxl.utils import get_column_letter
|
| 25 |
|
| 26 |
-
# ─────────────────────── PLOT COLORS
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
ACCENT_TEAL = "#
|
| 31 |
-
ACCENT_GOLD = "#
|
| 32 |
-
ACCENT_CORAL= "#
|
| 33 |
-
ACCENT_BLUE = "#
|
| 34 |
-
ACCENT_LIME = "#
|
| 35 |
-
ACCENT_PURP = "#
|
| 36 |
-
ACCENT_PINK = "#
|
| 37 |
-
ACCENT_CYAN = "#
|
| 38 |
-
ACCENT_ORG = "#
|
| 39 |
-
TEXT_MAIN = "#
|
| 40 |
-
TEXT_DIM = "#
|
| 41 |
-
GRID_LINE = "#
|
| 42 |
-
SIG_COLOR = "#
|
| 43 |
|
| 44 |
MODEL_COLORS = {
|
| 45 |
-
"OLS": "#
|
| 46 |
-
"MLM": "#
|
| 47 |
-
"GLM": "#
|
| 48 |
-
"CMLM": "#
|
| 49 |
-
"BLINK": "#
|
| 50 |
-
"FarmCPU": "#
|
| 51 |
-
"EMMAX": "#
|
| 52 |
-
"PLINK": "#
|
| 53 |
-
"GAPIT3": "#
|
| 54 |
-
"GEMMA": "#
|
| 55 |
}
|
| 56 |
|
| 57 |
CHR_PALETTE = [
|
| 58 |
-
"#
|
| 59 |
-
"#
|
| 60 |
-
"#
|
| 61 |
]
|
| 62 |
|
| 63 |
def style_fig(fig):
|
| 64 |
-
|
|
|
|
| 65 |
for ax in fig.get_axes():
|
| 66 |
-
ax.set_facecolor(
|
| 67 |
ax.tick_params(colors=TEXT_DIM, labelsize=8)
|
| 68 |
ax.xaxis.label.set_color(TEXT_DIM)
|
| 69 |
ax.yaxis.label.set_color(TEXT_DIM)
|
| 70 |
ax.title.set_color(TEXT_MAIN)
|
| 71 |
for spine in ax.spines.values():
|
| 72 |
spine.set_edgecolor(GRID_LINE)
|
| 73 |
-
|
|
|
|
| 74 |
return fig
|
| 75 |
|
| 76 |
# ─────────────────────── DATA PARSING ────────────────────────────────────────────
|
|
@@ -164,11 +166,9 @@ def build_kinship(G):
|
|
| 164 |
return Z @ Z.T / denom
|
| 165 |
|
| 166 |
def compute_pve(y, G, pvals, betas, threshold=0.05):
|
| 167 |
-
"""Compute Phenotypic Variance Explained (PVE) for significant SNPs"""
|
| 168 |
bonf = threshold / len(pvals)
|
| 169 |
sig_idx = np.where(pvals < bonf)[0]
|
| 170 |
pve_dict = {}
|
| 171 |
-
total_var = np.var(y)
|
| 172 |
for idx in sig_idx:
|
| 173 |
x = G[:, idx]
|
| 174 |
mask = ~np.isnan(x)
|
|
@@ -176,8 +176,8 @@ def compute_pve(y, G, pvals, betas, threshold=0.05):
|
|
| 176 |
pve_dict[idx] = 0.0
|
| 177 |
continue
|
| 178 |
corr = np.corrcoef(x[mask], y[mask])[0, 1]
|
| 179 |
-
pve_dict[idx] = corr**2 * 100
|
| 180 |
-
return pve_dict,
|
| 181 |
|
| 182 |
def fig_to_png_bytes(fig):
|
| 183 |
buf = io.BytesIO()
|
|
@@ -222,12 +222,19 @@ def glm_gwas(y, G):
|
|
| 222 |
n, m = G.shape
|
| 223 |
pvals = np.ones(m); betas = np.zeros(m); ses = np.zeros(m)
|
| 224 |
n_pcs = min(3, n - 2)
|
| 225 |
-
|
| 226 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 227 |
for j in range(m):
|
| 228 |
x = G[:, j]
|
| 229 |
if x.std() < 1e-8: continue
|
| 230 |
-
|
|
|
|
|
|
|
|
|
|
| 231 |
slope, _, _, p, se = stats.linregress(x_adj, y_adj)
|
| 232 |
pvals[j] = p; betas[j] = slope; ses[j] = se
|
| 233 |
return pvals, betas, ses
|
|
@@ -238,10 +245,16 @@ def cmlm_gwas(y, G, K):
|
|
| 238 |
n_groups = min(3, n)
|
| 239 |
groups = np.array([i % n_groups for i in range(n)])
|
| 240 |
group_means = np.column_stack([K[:, np.where(groups == g)[0]].mean(axis=1) for g in range(n_groups)])
|
| 241 |
-
|
|
|
|
|
|
|
|
|
|
| 242 |
for j in range(m):
|
| 243 |
x = G[:, j]
|
| 244 |
-
|
|
|
|
|
|
|
|
|
|
| 245 |
if x_res.std() < 1e-8: continue
|
| 246 |
slope, _, _, p, se = stats.linregress(x_res, y_res)
|
| 247 |
pvals[j] = p; betas[j] = slope; ses[j] = se
|
|
@@ -253,7 +266,10 @@ def blink_gwas(y, G):
|
|
| 253 |
ols_p, _, _ = ols_gwas(y, G)
|
| 254 |
top_idx = np.argsort(ols_p)[:min(3, m)]
|
| 255 |
covars = G[:, top_idx]
|
| 256 |
-
|
|
|
|
|
|
|
|
|
|
| 257 |
for j in range(m):
|
| 258 |
x = G[:, j]
|
| 259 |
if x.std() < 1e-8: continue
|
|
@@ -267,7 +283,10 @@ def farmcpu_gwas(y, G, K):
|
|
| 267 |
mlm_p, _, _ = mlm_gwas(y, G, K)
|
| 268 |
qtn_idx = np.argsort(mlm_p)[:min(3, m)]
|
| 269 |
qtns = G[:, qtn_idx]
|
| 270 |
-
|
|
|
|
|
|
|
|
|
|
| 271 |
for j in range(m):
|
| 272 |
x = G[:, j]
|
| 273 |
if x.std() < 1e-8: continue
|
|
@@ -283,19 +302,22 @@ def emmax_gwas(y, G, K):
|
|
| 283 |
V = tau * K + sigma * np.eye(n)
|
| 284 |
try:
|
| 285 |
V_inv = np.linalg.inv(V + np.eye(n) * 1e-6)
|
| 286 |
-
except:
|
| 287 |
V_inv = np.eye(n)
|
| 288 |
for j in range(m):
|
| 289 |
x = G[:, j].reshape(-1, 1)
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
|
|
|
|
|
|
|
|
|
| 299 |
return pvals, betas, ses
|
| 300 |
|
| 301 |
def plink_gwas(y, G):
|
|
@@ -316,7 +338,7 @@ def plink_gwas(y, G):
|
|
| 316 |
pvals[j] = p
|
| 317 |
slope, _, _, p2, se = stats.linregress(x, y_bin)
|
| 318 |
betas[j] = slope; ses[j] = se
|
| 319 |
-
except:
|
| 320 |
pass
|
| 321 |
return pvals, betas, ses
|
| 322 |
|
|
@@ -324,7 +346,10 @@ def gapit3_gwas(y, G, K):
|
|
| 324 |
n, m = G.shape
|
| 325 |
pvals = np.ones(m); betas = np.zeros(m); ses = np.zeros(m)
|
| 326 |
n_pcs = min(3, n - 2)
|
| 327 |
-
|
|
|
|
|
|
|
|
|
|
| 328 |
eigvals, eigvecs = np.linalg.eigh(K + np.eye(n) * 1e-6)
|
| 329 |
Q = eigvecs[:, np.argsort(eigvals)[::-1][:n_pcs]]
|
| 330 |
covars = np.hstack([PCs, Q])
|
|
@@ -333,14 +358,17 @@ def gapit3_gwas(y, G, K):
|
|
| 333 |
for j in range(m):
|
| 334 |
x = G[:, j]
|
| 335 |
if x.std() < 1e-8: continue
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
|
|
|
|
|
|
|
|
|
| 344 |
new_qtns = list(np.where(pvals < 0.05 / m)[0][:2])
|
| 345 |
if new_qtns and new_qtns != qtns:
|
| 346 |
qtns = new_qtns
|
|
@@ -359,10 +387,16 @@ def gemma_gwas(y, G, K):
|
|
| 359 |
idx = np.argsort(eigvals)[::-1]
|
| 360 |
n_pcs = min(4, n - 2)
|
| 361 |
Q = eigvecs[:, idx[:n_pcs]]
|
| 362 |
-
|
|
|
|
|
|
|
|
|
|
| 363 |
for j in range(m):
|
| 364 |
x = G[:, j]
|
| 365 |
-
|
|
|
|
|
|
|
|
|
|
| 366 |
if x_res.std() < 1e-8: continue
|
| 367 |
slope, _, _, p, se = stats.linregress(x_res, y_res)
|
| 368 |
pvals[j] = p; betas[j] = slope; ses[j] = se
|
|
@@ -372,10 +406,12 @@ def gemma_gwas(y, G, K):
|
|
| 372 |
pvals = 1 - stats.chi2.cdf(np.clip(chi2_vals, 0, 1e10), df=1)
|
| 373 |
return pvals, betas, ses
|
| 374 |
|
| 375 |
-
# ─────────────────────── PLOTS ────────────────────────────────
|
| 376 |
def plot_manhattan(pvals, chroms, positions, title="Manhattan Plot", model_name=""):
|
| 377 |
-
fig, ax = plt.subplots(figsize=(16, 5))
|
|
|
|
| 378 |
style_fig(fig)
|
|
|
|
| 379 |
log_p = -np.log10(np.clip(pvals, 1e-300, 1))
|
| 380 |
sig_line = -np.log10(5e-8)
|
| 381 |
sug_line = -np.log10(1e-5)
|
|
@@ -392,45 +428,47 @@ def plot_manhattan(pvals, chroms, positions, title="Manhattan Plot", model_name=
|
|
| 392 |
x_coords[np.where(mask)[0][order]] = x_vals
|
| 393 |
tick_pos.append(x_vals.mean())
|
| 394 |
tick_lab.append(f"Chr{ch}")
|
| 395 |
-
ax.scatter(x_coords[mask], log_p[mask], c=chrom_colors[ch], s=
|
| 396 |
x_offset += (pos.max() - pos.min()) + max(positions) * 0.015 + 1
|
| 397 |
-
|
| 398 |
-
ax.axhline(
|
|
|
|
| 399 |
sig_mask = log_p >= sig_line
|
| 400 |
if sig_mask.any():
|
| 401 |
-
ax.scatter(x_coords[sig_mask], log_p[sig_mask], c=SIG_COLOR, s=
|
| 402 |
-
zorder=10, edgecolors="#
|
| 403 |
label=f"Sig. MTA ({sig_mask.sum()} SNPs)")
|
| 404 |
ax.set_xticks(tick_pos)
|
| 405 |
ax.set_xticklabels(tick_lab, rotation=45, fontsize=7, color=TEXT_DIM)
|
| 406 |
-
ax.set_ylabel("-log₁₀(p)", color=TEXT_DIM)
|
| 407 |
ax.set_title(f"{title}{' — ' + model_name if model_name else ''}", color=TEXT_MAIN, fontsize=11, pad=8)
|
| 408 |
-
ax.legend(fontsize=7, framealpha=0.
|
| 409 |
ax.set_xlim(-x_offset * 0.01, x_offset * 1.01)
|
| 410 |
fig.tight_layout()
|
| 411 |
return fig
|
| 412 |
|
| 413 |
def plot_qq_single(pvals, title="QQ Plot", model_name="", color=None):
|
| 414 |
-
"""High-quality standalone QQ plot for a single model"""
|
| 415 |
if color is None:
|
| 416 |
color = ACCENT_PURP
|
| 417 |
-
fig, ax = plt.subplots(figsize=(7, 7))
|
|
|
|
| 418 |
style_fig(fig)
|
|
|
|
| 419 |
n = len(pvals)
|
| 420 |
obs = np.sort(-np.log10(np.clip(pvals, 1e-300, 1)))[::-1]
|
| 421 |
exp = -np.log10(np.linspace(1/n, 1, n)[::-1])
|
| 422 |
ci_lower = -np.log10(stats.beta.ppf(0.975, np.arange(1, n+1), np.arange(n, 0, -1)))
|
| 423 |
ci_upper = -np.log10(stats.beta.ppf(0.025, np.arange(1, n+1), np.arange(n, 0, -1)))
|
| 424 |
-
ax.fill_between(exp, ci_lower, ci_upper, alpha=0.
|
| 425 |
-
ax.scatter(exp, obs, c=color, s=
|
| 426 |
-
ax.plot([0, max(exp)], [0, max(exp)], color=ACCENT_CORAL, ls="--", lw=
|
| 427 |
lam = np.median(stats.chi2.ppf(1 - np.clip(pvals, 1e-10, 1), df=1)) / stats.chi2.ppf(0.5, df=1)
|
| 428 |
-
ax.text(0.05, 0.93, f"λ = {lam:.4f}", transform=ax.transAxes, fontsize=
|
| 429 |
color=ACCENT_GOLD, fontweight='bold')
|
| 430 |
-
ax.set_xlabel("Expected -log₁₀(p)", fontsize=10)
|
| 431 |
-
ax.set_ylabel("Observed -log₁₀(p)", fontsize=10)
|
| 432 |
ax.set_title(f"{title}{' — ' + model_name if model_name else ''}", color=TEXT_MAIN, fontsize=12)
|
| 433 |
-
ax.legend(fontsize=9, framealpha=0.
|
| 434 |
fig.tight_layout()
|
| 435 |
return fig
|
| 436 |
|
|
@@ -438,28 +476,33 @@ def plot_qq_all_models(all_results):
|
|
| 438 |
n_models = len(all_results)
|
| 439 |
ncols = min(3, n_models)
|
| 440 |
nrows = (n_models + ncols - 1) // ncols
|
| 441 |
-
fig, axes = plt.subplots(nrows, ncols, figsize=(7 * ncols, 6 * nrows))
|
| 442 |
style_fig(fig)
|
| 443 |
if n_models == 1:
|
| 444 |
axes = np.array([axes])
|
| 445 |
axes = np.array(axes).flatten()
|
| 446 |
for idx, (mname, (pvals, _, _)) in enumerate(all_results.items()):
|
| 447 |
ax = axes[idx]
|
|
|
|
| 448 |
n = len(pvals)
|
| 449 |
obs = np.sort(-np.log10(np.clip(pvals, 1e-300, 1)))[::-1]
|
| 450 |
exp = -np.log10(np.linspace(1/n, 1, n)[::-1])
|
| 451 |
ci_lo = -np.log10(stats.beta.ppf(0.975, np.arange(1, n+1), np.arange(n, 0, -1)))
|
| 452 |
ci_hi = -np.log10(stats.beta.ppf(0.025, np.arange(1, n+1), np.arange(n, 0, -1)))
|
| 453 |
col = MODEL_COLORS.get(mname, ACCENT_BLUE)
|
| 454 |
-
ax.fill_between(exp, ci_lo, ci_hi, alpha=0.
|
| 455 |
-
ax.scatter(exp, obs, c=col, s=18, alpha=0.
|
| 456 |
-
ax.plot([0, max(exp)], [0, max(exp)], color=ACCENT_CORAL, ls="--", lw=1.
|
| 457 |
lam = np.median(stats.chi2.ppf(1 - np.clip(pvals, 1e-10, 1), df=1)) / stats.chi2.ppf(0.5, df=1)
|
| 458 |
-
ax.text(0.05, 0.92, f"λ = {lam:.4f}", transform=ax.transAxes, fontsize=
|
| 459 |
color=ACCENT_GOLD, fontweight='bold')
|
| 460 |
-
ax.set_xlabel("Expected -log₁₀(p)", fontsize=8)
|
| 461 |
-
ax.set_ylabel("Observed -log₁₀(p)", fontsize=8)
|
| 462 |
ax.set_title(f"QQ — {mname}", color=col, fontsize=10)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 463 |
for idx in range(n_models, len(axes)):
|
| 464 |
axes[idx].set_visible(False)
|
| 465 |
fig.suptitle("QQ Plots — All Models", color=TEXT_MAIN, fontsize=13, y=1.01)
|
|
@@ -467,7 +510,8 @@ def plot_qq_all_models(all_results):
|
|
| 467 |
return fig
|
| 468 |
|
| 469 |
def plot_qq_overlay(all_results):
|
| 470 |
-
fig, ax = plt.subplots(figsize=(9, 9))
|
|
|
|
| 471 |
style_fig(fig)
|
| 472 |
exp_max = 0
|
| 473 |
for mname, (pvals, _, _) in all_results.items():
|
|
@@ -477,19 +521,18 @@ def plot_qq_overlay(all_results):
|
|
| 477 |
exp_max = max(exp_max, max(exp))
|
| 478 |
lam = np.median(stats.chi2.ppf(1 - np.clip(pvals, 1e-10, 1), df=1)) / stats.chi2.ppf(0.5, df=1)
|
| 479 |
ax.plot(exp, obs, color=MODEL_COLORS.get(mname, ACCENT_BLUE),
|
| 480 |
-
lw=
|
| 481 |
-
ax.plot([0, exp_max], [0, exp_max], color=ACCENT_CORAL, ls="--", lw=
|
| 482 |
-
ax.set_xlabel("Expected -log₁₀(p)")
|
| 483 |
-
ax.set_ylabel("Observed -log₁₀(p)")
|
| 484 |
ax.set_title("QQ Plot — All Models Overlay", color=TEXT_MAIN, fontsize=12)
|
| 485 |
-
ax.legend(fontsize=8, framealpha=0.
|
| 486 |
fig.tight_layout()
|
| 487 |
return fig
|
| 488 |
|
| 489 |
def plot_circos(all_results, chroms, positions):
|
| 490 |
-
fig, ax = plt.subplots(figsize=(14, 14), subplot_kw=dict(projection='polar'))
|
| 491 |
-
|
| 492 |
-
ax.set_facecolor(BG_DARK)
|
| 493 |
ax.grid(False)
|
| 494 |
ax.set_yticks([])
|
| 495 |
ax.set_xticks([])
|
|
@@ -524,28 +567,28 @@ def plot_circos(all_results, chroms, positions):
|
|
| 524 |
col = MODEL_COLORS.get(mname, CHR_PALETTE[midx % len(CHR_PALETTE)])
|
| 525 |
max_lp = max(log_p.max(), sig_line, 1)
|
| 526 |
lp_norm = log_p[sort_idx] / max_lp * r_max_data
|
| 527 |
-
ax.plot(angles_sorted, np.full_like(angles_sorted, r_base), color=col, alpha=0.
|
| 528 |
ax.scatter(angles_sorted, r_base + lp_norm, c=col, s=4, alpha=0.6, linewidths=0)
|
| 529 |
sig_mask = log_p[sort_idx] >= sig_line
|
| 530 |
if sig_mask.any():
|
| 531 |
ax.scatter(angles_sorted[sig_mask], r_base + lp_norm[sig_mask],
|
| 532 |
-
c=SIG_COLOR, s=40, zorder=10, marker='
|
| 533 |
-
linewidth=0.
|
| 534 |
ax.text(0, r_base + r_max_data / 2, mname, ha='center', va='center',
|
| 535 |
fontsize=7, color=col, fontweight='bold', alpha=0.9)
|
| 536 |
legend_elements = [mpatches.Patch(facecolor=MODEL_COLORS.get(m, ACCENT_BLUE), label=m, alpha=0.8)
|
| 537 |
for m in model_names]
|
| 538 |
-
legend_elements.append(mpatches.Patch(facecolor=SIG_COLOR, label="Sig. MTA (
|
| 539 |
ax.legend(handles=legend_elements, loc='lower center', bbox_to_anchor=(0.5, -0.08),
|
| 540 |
-
ncol=min(5, n_models+1), fontsize=7, framealpha=0.
|
| 541 |
edgecolor=GRID_LINE, labelcolor=TEXT_MAIN)
|
| 542 |
-
ax.set_title("Circos Plot — Multi-Model GWAS Comparison\n(Ring height = -log₁₀(p) |
|
| 543 |
color=TEXT_MAIN, fontsize=12, pad=20)
|
| 544 |
fig.tight_layout()
|
| 545 |
return fig
|
| 546 |
|
| 547 |
def plot_ld_decay(G, positions):
|
| 548 |
-
fig, axes = plt.subplots(1, 2, figsize=(16, 6))
|
| 549 |
style_fig(fig)
|
| 550 |
m = G.shape[1]
|
| 551 |
dists_bp, r2s = [], []
|
|
@@ -566,6 +609,7 @@ def plot_ld_decay(G, positions):
|
|
| 566 |
dists_bp = np.array(dists_bp)
|
| 567 |
dists_mb = dists_bp / 1_000_000
|
| 568 |
r2s = np.array(r2s)
|
|
|
|
| 569 |
def bin_ld(dists, r2s, n_bins=20):
|
| 570 |
bins = np.percentile(dists, np.linspace(0, 100, n_bins + 1))
|
| 571 |
centers, means, sems = [], [], []
|
|
@@ -576,61 +620,88 @@ def plot_ld_decay(G, positions):
|
|
| 576 |
means.append(np.mean(r2s[mask]))
|
| 577 |
sems.append(stats.sem(r2s[mask]))
|
| 578 |
return np.array(centers), np.array(means), np.array(sems)
|
|
|
|
| 579 |
ax = axes[0]
|
|
|
|
| 580 |
ax.scatter(dists_bp, r2s, c=ACCENT_TEAL, s=12, alpha=0.35, linewidths=0)
|
| 581 |
bc, bm, bs = bin_ld(dists_bp, r2s)
|
| 582 |
if len(bc) > 0:
|
| 583 |
ax.plot(bc, bm, color=ACCENT_CORAL, lw=2.5, marker='o', ms=5, zorder=5, label="Binned mean r²")
|
| 584 |
ax.fill_between(bc, bm - bs, bm + bs, alpha=0.2, color=ACCENT_CORAL)
|
| 585 |
-
ax.axhline(0.5, color=ACCENT_GOLD, ls='--', lw=1.5, alpha=0.
|
| 586 |
-
ax.axhline(0.2, color=ACCENT_PURP, ls=':', lw=1.2, alpha=0.
|
| 587 |
-
ax.set_xlabel("Distance (bp)", fontsize=9
|
|
|
|
| 588 |
ax.set_title("LD Decay — Base Pairs (bp)", color=TEXT_MAIN, fontsize=11)
|
| 589 |
-
ax.legend(fontsize=7, framealpha=0.
|
| 590 |
ax.set_ylim(0, 1.05)
|
|
|
|
| 591 |
ax2 = axes[1]
|
|
|
|
| 592 |
ax2.scatter(dists_mb, r2s, c=ACCENT_PURP, s=12, alpha=0.35, linewidths=0)
|
| 593 |
bc2, bm2, bs2 = bin_ld(dists_mb, r2s)
|
| 594 |
if len(bc2) > 0:
|
| 595 |
ax2.plot(bc2, bm2, color=ACCENT_GOLD, lw=2.5, marker='o', ms=5, zorder=5, label="Binned mean r²")
|
| 596 |
ax2.fill_between(bc2, bm2 - bs2, bm2 + bs2, alpha=0.2, color=ACCENT_GOLD)
|
| 597 |
-
ax2.axhline(0.5, color=ACCENT_CORAL, ls='--', lw=1.5, alpha=0.
|
| 598 |
-
ax2.axhline(0.2, color=ACCENT_TEAL, ls=':', lw=1.2, alpha=0.
|
| 599 |
-
ax2.set_xlabel("Distance (Mb)", fontsize=9
|
|
|
|
| 600 |
ax2.set_title("LD Decay — Megabases (Mb)", color=TEXT_MAIN, fontsize=11)
|
| 601 |
-
ax2.legend(fontsize=7, framealpha=0.
|
| 602 |
ax2.set_ylim(0, 1.05)
|
|
|
|
| 603 |
fig.suptitle("Linkage Disequilibrium (LD) Decay Analysis", color=TEXT_MAIN, fontsize=13)
|
| 604 |
fig.tight_layout()
|
| 605 |
return fig
|
| 606 |
|
| 607 |
def plot_pca(G, y, ids):
|
| 608 |
-
fig, axes = plt.subplots(2, 2, figsize=(14, 12))
|
| 609 |
style_fig(fig)
|
| 610 |
-
|
| 611 |
-
|
| 612 |
-
|
| 613 |
-
|
| 614 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 615 |
sc = axes[0,0].scatter(pcs[:,0], pcs[:,1], c=y, cmap='plasma', s=60, edgecolors='none')
|
| 616 |
-
axes[0,0].set_xlabel(f"PC1 ({var_exp[0]:.1f}%)"
|
| 617 |
-
axes[0,0].
|
|
|
|
|
|
|
|
|
|
|
|
|
| 618 |
if n_comp >= 4:
|
| 619 |
axes[0,1].scatter(pcs[:,2], pcs[:,3], c=y, cmap='plasma', s=60, edgecolors='none')
|
| 620 |
-
axes[0,1].set_xlabel(f"PC3 ({var_exp[2]:.1f}%)"
|
| 621 |
-
axes[0,1].
|
| 622 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 623 |
axes[1,0].plot(range(1, n_comp+1), np.cumsum(var_exp), color=ACCENT_CORAL, marker='o', lw=2)
|
| 624 |
-
axes[1,0].set_xlabel("Principal Component"
|
| 625 |
-
axes[1,0].
|
|
|
|
|
|
|
|
|
|
| 626 |
axes[1,1].scatter(pcs[:,0], pcs[:,1], c=y, cmap='plasma', s=60, edgecolors='none')
|
| 627 |
-
axes[1,1].set_title("Population Structure (PC1 vs PC2)")
|
| 628 |
fig.tight_layout()
|
| 629 |
return fig
|
| 630 |
|
| 631 |
def plot_model_comparison_manhattan(all_results, chroms, positions):
|
| 632 |
n_models = len(all_results)
|
| 633 |
-
fig, axes = plt.subplots(n_models, 1, figsize=(16, 3.5 * n_models), sharex=True)
|
| 634 |
style_fig(fig)
|
| 635 |
if n_models == 1:
|
| 636 |
axes = [axes]
|
|
@@ -655,16 +726,16 @@ def plot_model_comparison_manhattan(all_results, chroms, positions):
|
|
| 655 |
tick_lab.append(f"Chr{ch}")
|
| 656 |
for midx, (mname, (pvals, _, _)) in enumerate(all_results.items()):
|
| 657 |
ax = axes[midx]
|
| 658 |
-
ax.set_facecolor(
|
| 659 |
log_p = -np.log10(np.clip(pvals, 1e-300, 1))
|
| 660 |
col = MODEL_COLORS.get(mname, CHR_PALETTE[midx % len(CHR_PALETTE)])
|
| 661 |
for ch in chrom_list:
|
| 662 |
mask = chroms == ch
|
| 663 |
-
ax.scatter(x_coords[mask], log_p[mask], c=col, s=
|
| 664 |
sig_m = log_p >= -np.log10(5e-8)
|
| 665 |
if sig_m.any():
|
| 666 |
-
ax.scatter(x_coords[sig_m], log_p[sig_m], c=SIG_COLOR, s=
|
| 667 |
-
linewidths=0.
|
| 668 |
ax.axhline(-np.log10(5e-8), color=ACCENT_CORAL, ls='--', lw=1, alpha=0.7)
|
| 669 |
ax.set_ylabel("-log₁₀(p)", fontsize=7, color=TEXT_DIM)
|
| 670 |
ax.set_title(f"Model: {mname}", color=col, fontsize=9, pad=3)
|
|
@@ -673,92 +744,117 @@ def plot_model_comparison_manhattan(all_results, chroms, positions):
|
|
| 673 |
ax.tick_params(colors=TEXT_DIM, labelsize=7)
|
| 674 |
for spine in ax.spines.values():
|
| 675 |
spine.set_edgecolor(GRID_LINE)
|
| 676 |
-
ax.grid(color=GRID_LINE, linewidth=0.3, linestyle="--", alpha=0.
|
| 677 |
fig.suptitle("Manhattan Plots — All Models Comparison", color=TEXT_MAIN, fontsize=13)
|
| 678 |
fig.tight_layout(rect=[0, 0, 1, 0.98])
|
| 679 |
return fig
|
| 680 |
|
| 681 |
def plot_kinship(K, ids):
|
| 682 |
-
fig, axes = plt.subplots(2, 2, figsize=(14, 12))
|
| 683 |
style_fig(fig)
|
|
|
|
|
|
|
|
|
|
| 684 |
im = axes[0,0].imshow(K, cmap='RdYlBu_r', aspect='auto', vmin=-0.5, vmax=1)
|
| 685 |
-
axes[0,0].set_title("Kinship Matrix"
|
|
|
|
|
|
|
| 686 |
K_flat = K[np.triu_indices_from(K, k=1)]
|
| 687 |
-
axes[0,1].hist(K_flat, bins=30, color=ACCENT_PURP, edgecolor='none')
|
| 688 |
-
axes[0,1].set_title("Pairwise Kinship Distribution")
|
|
|
|
| 689 |
try:
|
| 690 |
lm = linkage(K, method='average')
|
| 691 |
dendrogram(lm, ax=axes[1,0], labels=ids, leaf_rotation=90, leaf_font_size=7,
|
| 692 |
color_threshold=0.7, above_threshold_color=ACCENT_TEAL)
|
| 693 |
-
except:
|
| 694 |
-
axes[1,0].text(0.5, 0.5, "Dendrogram unavailable", ha='center',
|
| 695 |
-
|
|
|
|
|
|
|
| 696 |
eigvals, eigvecs = np.linalg.eigh(K)
|
| 697 |
idx = np.argsort(eigvals)[::-1]
|
| 698 |
axes[1,1].scatter(eigvecs[:,idx[0]], eigvecs[:,idx[1]], c=ACCENT_TEAL, s=60, edgecolors='none')
|
| 699 |
-
axes[1,1].set_title("Kinship PCA")
|
| 700 |
fig.tight_layout()
|
| 701 |
return fig
|
| 702 |
|
| 703 |
def plot_effect_sizes(pvals, betas, snp_names):
|
| 704 |
-
fig, axes = plt.subplots(2, 2, figsize=(14, 10))
|
| 705 |
style_fig(fig)
|
|
|
|
|
|
|
|
|
|
| 706 |
top_idx = np.argsort(np.abs(betas))[-20:]
|
| 707 |
top_betas = betas[top_idx]
|
| 708 |
top_names = [snp_names[i][:15] for i in top_idx]
|
| 709 |
colors = [ACCENT_CORAL if b < 0 else ACCENT_TEAL for b in top_betas]
|
| 710 |
-
axes[0,0].barh(range(len(top_betas)), top_betas, color=colors)
|
| 711 |
-
axes[0,0].axvline(0, color=TEXT_DIM, lw=0.
|
| 712 |
axes[0,0].set_yticks(range(len(top_betas)))
|
| 713 |
-
axes[0,0].set_yticklabels(top_names, fontsize=7)
|
| 714 |
-
axes[0,0].set_xlabel("Effect Size (β)")
|
| 715 |
-
axes[0,0].set_title("Top 20 Effect Sizes")
|
|
|
|
| 716 |
log_p = -np.log10(np.clip(pvals, 1e-300, 1))
|
| 717 |
sig_thr = -np.log10(0.05/len(pvals))
|
| 718 |
colors_v = np.where(log_p >= sig_thr, SIG_COLOR, np.where(betas > 0, ACCENT_TEAL, ACCENT_PURP))
|
| 719 |
axes[0,1].scatter(betas, log_p, c=colors_v, s=25, alpha=0.7, linewidths=0)
|
| 720 |
axes[0,1].axhline(sig_thr, color=ACCENT_CORAL, ls='--', lw=1.5, label="Bonferroni")
|
| 721 |
axes[0,1].axvline(0, color=TEXT_DIM, lw=0.5)
|
| 722 |
-
axes[0,1].set_xlabel("β"
|
| 723 |
-
axes[0,1].
|
| 724 |
-
axes[
|
|
|
|
|
|
|
|
|
|
| 725 |
axes[1,0].axvline(0, color=ACCENT_CORAL, lw=2, ls='--')
|
| 726 |
-
axes[1,0].set_xlabel("β"
|
|
|
|
|
|
|
| 727 |
axes[1,1].scatter(betas, log_p, c=colors_v, s=20, alpha=0.6, linewidths=0)
|
| 728 |
-
axes[1,1].set_xlabel("β"
|
| 729 |
-
axes[1,1].
|
|
|
|
| 730 |
fig.tight_layout()
|
| 731 |
return fig
|
| 732 |
|
| 733 |
def plot_summary_dashboard(y, maf, all_results, G_filt):
|
| 734 |
-
fig, axes = plt.subplots(2, 3, figsize=(15, 10))
|
| 735 |
style_fig(fig)
|
| 736 |
axes = axes.flatten()
|
|
|
|
|
|
|
|
|
|
| 737 |
axes[0].hist(y, bins=15, color=ACCENT_PURP, edgecolor='none', alpha=0.8)
|
| 738 |
axes[0].axvline(y.mean(), color=ACCENT_CORAL, lw=2, ls='--', label=f"Mean: {y.mean():.2f}")
|
| 739 |
-
axes[0].set_title(f"Phenotype | n={len(y)}")
|
| 740 |
-
axes[0].legend(fontsize=7)
|
| 741 |
-
|
|
|
|
| 742 |
axes[1].axvline(0.05, color=ACCENT_CORAL, ls='--')
|
| 743 |
-
axes[1].set_title(f"MAF | rare={np.sum(maf<0.05)}")
|
|
|
|
| 744 |
lambdas = {}
|
| 745 |
for mname, (p, _, _) in all_results.items():
|
| 746 |
lam = np.median(stats.chi2.ppf(1-np.clip(p,1e-10,1), df=1)) / stats.chi2.ppf(0.5, df=1)
|
| 747 |
lambdas[mname] = lam
|
| 748 |
colors_lam = [ACCENT_TEAL if v <= 1.1 else ACCENT_GOLD if v <= 1.3 else ACCENT_CORAL
|
| 749 |
for v in lambdas.values()]
|
| 750 |
-
axes[2].bar(lambdas.keys(), lambdas.values(), color=colors_lam, edgecolor='none')
|
| 751 |
axes[2].axhline(1.0, color=TEXT_DIM, ls='--', lw=1)
|
| 752 |
-
axes[2].set_title("Genomic Inflation λ per Model")
|
| 753 |
axes[2].tick_params(axis='x', rotation=35, labelsize=7)
|
|
|
|
| 754 |
sig_counts = {}
|
| 755 |
for mname, (p, _, _) in all_results.items():
|
| 756 |
bonf = 0.05 / len(p)
|
| 757 |
sig_counts[mname] = int((p < bonf).sum())
|
| 758 |
cols_bar = [MODEL_COLORS.get(m, ACCENT_BLUE) for m in sig_counts.keys()]
|
| 759 |
-
axes[3].bar(sig_counts.keys(), sig_counts.values(), color=cols_bar, edgecolor='none')
|
| 760 |
-
axes[3].set_title("Significant SNPs per Model (Bonferroni)")
|
| 761 |
axes[3].tick_params(axis='x', rotation=35, labelsize=7)
|
|
|
|
| 762 |
n_m = len(all_results)
|
| 763 |
model_names = list(all_results.keys())
|
| 764 |
concordance = np.eye(n_m)
|
|
@@ -770,14 +866,15 @@ def plot_summary_dashboard(y, maf, all_results, G_filt):
|
|
| 770 |
concordance[i,j] = concordance[j,i] = r
|
| 771 |
im = axes[4].imshow(concordance, cmap='RdYlGn', vmin=-1, vmax=1, aspect='auto')
|
| 772 |
axes[4].set_xticks(range(n_m)); axes[4].set_yticks(range(n_m))
|
| 773 |
-
axes[4].set_xticklabels(model_names, rotation=35, fontsize=6)
|
| 774 |
-
axes[4].set_yticklabels(model_names, fontsize=6)
|
| 775 |
for i in range(n_m):
|
| 776 |
for j in range(n_m):
|
| 777 |
axes[4].text(j, i, f"{concordance[i,j]:.2f}", ha='center', va='center',
|
| 778 |
fontsize=5, color='black' if abs(concordance[i,j]) < 0.7 else 'white')
|
| 779 |
plt.colorbar(im, ax=axes[4], label="Spearman ρ")
|
| 780 |
-
axes[4].set_title("Model Concordance")
|
|
|
|
| 781 |
miss_r = np.isnan(G_filt).mean()
|
| 782 |
first_model = model_names[0]
|
| 783 |
axes[5].text(0.5, 0.5,
|
|
@@ -785,84 +882,130 @@ def plot_summary_dashboard(y, maf, all_results, G_filt):
|
|
| 785 |
f"Models: {n_m}\nMissing: {miss_r:.1%}\n"
|
| 786 |
f"λ ({first_model}): {lambdas[first_model]:.3f}\n"
|
| 787 |
f"Sig. ({first_model}): {sig_counts[first_model]}",
|
| 788 |
-
ha='center', va='center', transform=axes[5].transAxes, color=TEXT_MAIN, fontsize=
|
| 789 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 790 |
fig.tight_layout()
|
| 791 |
return fig
|
| 792 |
|
| 793 |
# ─────────────────────── EXCEL RESULTS EXPORT ────────────────────────────────────
|
| 794 |
def export_results_excel(all_results, snp_filt, chr_filt, pos_filt, y, G_filt, maf_vals, output_path):
|
| 795 |
wb = Workbook()
|
| 796 |
-
|
| 797 |
-
# Color scheme
|
| 798 |
header_fill = PatternFill("solid", start_color="4A90D9", end_color="4A90D9")
|
| 799 |
sig_fill = PatternFill("solid", start_color="FFF3CD", end_color="FFF3CD")
|
| 800 |
alt_fill = PatternFill("solid", start_color="F8F9FA", end_color="F8F9FA")
|
| 801 |
header_font = Font(bold=True, color="FFFFFF", name="Calibri", size=11)
|
| 802 |
title_font = Font(bold=True, color="2C5F8A", name="Calibri", size=13)
|
| 803 |
thin_border = Border(
|
| 804 |
-
left=Side(style='thin', color='CCCCCC'),
|
| 805 |
-
|
| 806 |
-
top=Side(style='thin', color='CCCCCC'),
|
| 807 |
-
bottom=Side(style='thin', color='CCCCCC')
|
| 808 |
)
|
| 809 |
-
|
| 810 |
bonf = 0.05 / len(list(all_results.values())[0][0])
|
| 811 |
|
| 812 |
-
#
|
| 813 |
ws_sum = wb.active
|
| 814 |
ws_sum.title = "Summary"
|
| 815 |
ws_sum['A1'] = "GWAS Complete Analysis Summary"
|
| 816 |
ws_sum['A1'].font = Font(bold=True, color="2C5F8A", name="Calibri", size=16)
|
| 817 |
ws_sum.merge_cells('A1:H1')
|
| 818 |
-
|
| 819 |
headers_sum = ["Model", "N_SNPs_Tested", "Bonferroni_Threshold", "Sig_SNPs_Bonferroni",
|
| 820 |
"Sig_SNPs_5e8", "Genomic_Lambda", "Min_Pvalue", "Max_AbsBeta"]
|
| 821 |
for col, h in enumerate(headers_sum, 1):
|
| 822 |
cell = ws_sum.cell(row=3, column=col, value=h)
|
| 823 |
cell.font = header_font; cell.fill = header_fill
|
| 824 |
-
cell.alignment = Alignment(horizontal='center')
|
| 825 |
-
cell.border = thin_border
|
| 826 |
ws_sum.column_dimensions[get_column_letter(col)].width = 22
|
| 827 |
-
|
| 828 |
for row_i, (mname, (pvals, betas, ses)) in enumerate(all_results.items(), 4):
|
| 829 |
lam = np.median(stats.chi2.ppf(1-np.clip(pvals,1e-10,1), df=1)) / stats.chi2.ppf(0.5, df=1)
|
| 830 |
-
|
| 831 |
-
|
| 832 |
-
|
| 833 |
-
round(float(lam), 4), float(np.min(pvals)), round(float(np.max(np.abs(betas))), 5)]
|
| 834 |
fill = alt_fill if row_i % 2 == 0 else PatternFill("solid", start_color="FFFFFF", end_color="FFFFFF")
|
| 835 |
for col, val in enumerate(row_data, 1):
|
| 836 |
cell = ws_sum.cell(row=row_i, column=col, value=val)
|
| 837 |
-
cell.fill = fill; cell.border = thin_border
|
| 838 |
-
cell.alignment = Alignment(horizontal='center')
|
| 839 |
|
| 840 |
-
#
|
| 841 |
for mname, (pvals, betas, ses) in all_results.items():
|
| 842 |
ws = wb.create_sheet(title=f"{mname}_AllSNPs")
|
| 843 |
-
ws['A1'] = f"GWAS Results — {mname}
|
| 844 |
ws['A1'].font = title_font
|
| 845 |
ws.merge_cells('A1:K1')
|
| 846 |
-
|
| 847 |
log_p = -np.log10(np.clip(pvals, 1e-300, 1))
|
| 848 |
t_stats = np.where(ses > 0, betas / (ses + 1e-10), 0.0)
|
| 849 |
reject_fdr, pvals_fdr, _, _ = multipletests(pvals, method='fdr_bh')
|
| 850 |
reject_bonf, _, _, _ = multipletests(pvals, method='bonferroni')
|
| 851 |
-
|
| 852 |
headers = ["SNP", "Chr", "Position", "MAF", "Beta", "SE", "T_statistic",
|
| 853 |
"P_value", "neg_log10P", "FDR_BH", "Bonferroni_sig"]
|
| 854 |
for col, h in enumerate(headers, 1):
|
| 855 |
cell = ws.cell(row=3, column=col, value=h)
|
| 856 |
cell.font = header_font; cell.fill = header_fill
|
| 857 |
-
cell.alignment = Alignment(horizontal='center')
|
| 858 |
-
|
| 859 |
-
|
| 860 |
-
col_widths = [25, 8, 12, 10, 12, 12, 12, 14, 12, 14, 16]
|
| 861 |
-
for i, w in enumerate(col_widths, 1):
|
| 862 |
ws.column_dimensions[get_column_letter(i)].width = w
|
| 863 |
-
|
| 864 |
-
sort_order = np.argsort(pvals)
|
| 865 |
-
for row_i, idx in enumerate(sort_order, 4):
|
| 866 |
is_sig = bool(reject_bonf[idx]) or pvals[idx] < 5e-8
|
| 867 |
fill = sig_fill if is_sig else (alt_fill if row_i % 2 == 0 else
|
| 868 |
PatternFill("solid", start_color="FFFFFF", end_color="FFFFFF"))
|
|
@@ -872,36 +1015,28 @@ def export_results_excel(all_results, snp_filt, chr_filt, pos_filt, y, G_filt, m
|
|
| 872 |
int(chr_filt[idx]) if idx < len(chr_filt) else "",
|
| 873 |
int(pos_filt[idx]) if idx < len(pos_filt) else "",
|
| 874 |
round(float(maf_v), 4) if not np.isnan(maf_v) else "",
|
| 875 |
-
round(float(betas[idx]), 6),
|
| 876 |
-
round(float(
|
| 877 |
-
round(float(
|
| 878 |
-
float(pvals[idx]),
|
| 879 |
-
round(float(log_p[idx]), 4),
|
| 880 |
-
round(float(pvals_fdr[idx]), 6),
|
| 881 |
"YES" if is_sig else "NO"
|
| 882 |
]
|
| 883 |
for col, val in enumerate(row_data, 1):
|
| 884 |
cell = ws.cell(row=row_i, column=col, value=val)
|
| 885 |
-
cell.fill = fill; cell.border = thin_border
|
| 886 |
-
|
| 887 |
-
if col == 8 and isinstance(val, float):
|
| 888 |
-
cell.number_format = '0.00E+00'
|
| 889 |
|
| 890 |
-
#
|
| 891 |
ws_mta = wb.create_sheet(title="Significant_MTAs")
|
| 892 |
-
ws_mta['A1'] = "Significant MTAs — All Models Combined
|
| 893 |
ws_mta['A1'].font = title_font
|
| 894 |
ws_mta.merge_cells('A1:N1')
|
| 895 |
-
|
| 896 |
-
|
| 897 |
-
"T_stat", "P_value", "neg_log10P", "FDR_BH_p",
|
| 898 |
-
"Bonferroni_sig", "GW_sig_5e8", "PVE_%"]
|
| 899 |
for col, h in enumerate(headers_mta, 1):
|
| 900 |
cell = ws_mta.cell(row=3, column=col, value=h)
|
| 901 |
cell.font = header_font; cell.fill = header_fill
|
| 902 |
cell.alignment = Alignment(horizontal='center'); cell.border = thin_border
|
| 903 |
ws_mta.column_dimensions[get_column_letter(col)].width = 18
|
| 904 |
-
|
| 905 |
mta_row = 4
|
| 906 |
for mname, (pvals, betas, ses) in all_results.items():
|
| 907 |
log_p = -np.log10(np.clip(pvals, 1e-300, 1))
|
|
@@ -910,61 +1045,47 @@ def export_results_excel(all_results, snp_filt, chr_filt, pos_filt, y, G_filt, m
|
|
| 910 |
reject_bonf, _, _, _ = multipletests(pvals, method='bonferroni')
|
| 911 |
sig_idx = np.where((pvals < bonf) | (pvals < 5e-8))[0]
|
| 912 |
sig_idx = sig_idx[np.argsort(pvals[sig_idx])]
|
| 913 |
-
# Compute PVE for significant SNPs
|
| 914 |
pve_dict, _ = compute_pve(y, G_filt, pvals, betas)
|
| 915 |
for idx in sig_idx:
|
| 916 |
pve_val = round(pve_dict.get(int(idx), 0.0), 4)
|
| 917 |
maf_v = maf_vals[idx] if idx < len(maf_vals) else np.nan
|
| 918 |
row_data = [
|
| 919 |
-
mname,
|
| 920 |
-
str(snp_filt[idx]) if idx < len(snp_filt) else "",
|
| 921 |
int(chr_filt[idx]) if idx < len(chr_filt) else "",
|
| 922 |
int(pos_filt[idx]) if idx < len(pos_filt) else "",
|
| 923 |
round(float(maf_v), 4) if not np.isnan(maf_v) else "",
|
| 924 |
-
round(float(betas[idx]), 6),
|
| 925 |
-
round(float(
|
| 926 |
-
round(float(
|
| 927 |
-
float(pvals[idx]),
|
| 928 |
-
round(float(log_p[idx]), 4),
|
| 929 |
-
round(float(pvals_fdr[idx]), 6),
|
| 930 |
"YES" if bool(reject_bonf[idx]) else "NO",
|
| 931 |
-
"YES" if pvals[idx] < 5e-8 else "NO",
|
| 932 |
-
pve_val
|
| 933 |
]
|
| 934 |
fill = sig_fill if mta_row % 2 == 0 else PatternFill("solid", start_color="FFFDE7", end_color="FFFDE7")
|
| 935 |
for col, val in enumerate(row_data, 1):
|
| 936 |
cell = ws_mta.cell(row=mta_row, column=col, value=val)
|
| 937 |
-
cell.fill = fill; cell.border = thin_border
|
| 938 |
-
|
| 939 |
-
if col == 9 and isinstance(val, float):
|
| 940 |
-
cell.number_format = '0.00E+00'
|
| 941 |
mta_row += 1
|
| 942 |
|
| 943 |
-
#
|
| 944 |
ws_qtn = wb.create_sheet(title="QTN_Effects")
|
| 945 |
-
ws_qtn['A1'] = "
|
| 946 |
ws_qtn['A1'].font = title_font
|
| 947 |
ws_qtn.merge_cells('A1:L1')
|
| 948 |
-
|
| 949 |
-
|
| 950 |
-
"QTN_Effect_Beta", "SE", "95%_CI_Lower", "95%_CI_Upper",
|
| 951 |
-
"P_value", "PVE_%"]
|
| 952 |
for col, h in enumerate(headers_qtn, 1):
|
| 953 |
cell = ws_qtn.cell(row=3, column=col, value=h)
|
| 954 |
cell.font = header_font; cell.fill = header_fill
|
| 955 |
cell.alignment = Alignment(horizontal='center'); cell.border = thin_border
|
| 956 |
ws_qtn.column_dimensions[get_column_letter(col)].width = 17
|
| 957 |
-
|
| 958 |
qtn_row = 4
|
| 959 |
for mname, (pvals, betas, ses) in all_results.items():
|
| 960 |
-
|
| 961 |
-
top_idx = np.argsort(pvals)[:top_n]
|
| 962 |
pve_dict, _ = compute_pve(y, G_filt, pvals, betas)
|
| 963 |
for rank, idx in enumerate(top_idx, 1):
|
| 964 |
pve_val = round(pve_dict.get(int(idx), 0.0), 4)
|
| 965 |
maf_v = maf_vals[idx] if idx < len(maf_vals) else np.nan
|
| 966 |
-
ci_lower = float(betas[idx]) - 1.96 * float(ses[idx])
|
| 967 |
-
ci_upper = float(betas[idx]) + 1.96 * float(ses[idx])
|
| 968 |
fill = alt_fill if qtn_row % 2 == 0 else PatternFill("solid", start_color="FFFFFF", end_color="FFFFFF")
|
| 969 |
row_data = [
|
| 970 |
mname, rank,
|
|
@@ -972,71 +1093,56 @@ def export_results_excel(all_results, snp_filt, chr_filt, pos_filt, y, G_filt, m
|
|
| 972 |
int(chr_filt[idx]) if idx < len(chr_filt) else "",
|
| 973 |
int(pos_filt[idx]) if idx < len(pos_filt) else "",
|
| 974 |
round(float(maf_v), 4) if not np.isnan(maf_v) else "",
|
| 975 |
-
round(float(betas[idx]), 6),
|
| 976 |
-
round(float(ses[idx]), 6),
|
| 977 |
-
round(
|
| 978 |
-
|
| 979 |
-
float(pvals[idx]),
|
| 980 |
-
pve_val
|
| 981 |
]
|
| 982 |
for col, val in enumerate(row_data, 1):
|
| 983 |
cell = ws_qtn.cell(row=qtn_row, column=col, value=val)
|
| 984 |
-
cell.fill = fill; cell.border = thin_border
|
| 985 |
-
|
| 986 |
-
if col == 11 and isinstance(val, float):
|
| 987 |
-
cell.number_format = '0.00E+00'
|
| 988 |
qtn_row += 1
|
| 989 |
|
| 990 |
-
#
|
| 991 |
ws_pve = wb.create_sheet(title="PVE_Summary")
|
| 992 |
-
ws_pve['A1'] = "Phenotypic Variance Explained (PVE)
|
| 993 |
ws_pve['A1'].font = title_font
|
| 994 |
ws_pve.merge_cells('A1:I1')
|
| 995 |
-
|
| 996 |
-
headers_pve = ["Model", "SNP", "Chr", "Position", "Beta", "P_value", "PVE_%",
|
| 997 |
-
"Cumulative_PVE_%", "Significance"]
|
| 998 |
for col, h in enumerate(headers_pve, 1):
|
| 999 |
cell = ws_pve.cell(row=3, column=col, value=h)
|
| 1000 |
cell.font = header_font; cell.fill = header_fill
|
| 1001 |
cell.alignment = Alignment(horizontal='center'); cell.border = thin_border
|
| 1002 |
ws_pve.column_dimensions[get_column_letter(col)].width = 20
|
| 1003 |
-
|
| 1004 |
pve_row = 4
|
| 1005 |
for mname, (pvals, betas, ses) in all_results.items():
|
| 1006 |
pve_dict, _ = compute_pve(y, G_filt, pvals, betas)
|
| 1007 |
-
sig_idx_sorted = sorted(pve_dict.keys(), key=lambda i: pve_dict[i], reverse=True)
|
| 1008 |
cumulative = 0.0
|
| 1009 |
-
for idx in
|
| 1010 |
pve_val = pve_dict[idx]
|
| 1011 |
cumulative += pve_val
|
| 1012 |
-
is_sig_gw = pvals[idx] < 5e-8
|
| 1013 |
-
sig_label = "GW-significant" if is_sig_gw else "Bonferroni-significant"
|
| 1014 |
fill = sig_fill if pve_row % 2 == 0 else PatternFill("solid", start_color="FFFFFF", end_color="FFFFFF")
|
| 1015 |
row_data = [
|
| 1016 |
-
mname,
|
| 1017 |
-
str(snp_filt[idx]) if idx < len(snp_filt) else "",
|
| 1018 |
int(chr_filt[idx]) if idx < len(chr_filt) else "",
|
| 1019 |
int(pos_filt[idx]) if idx < len(pos_filt) else "",
|
| 1020 |
-
round(float(betas[idx]), 6),
|
| 1021 |
-
|
| 1022 |
-
|
| 1023 |
-
round(cumulative, 4),
|
| 1024 |
-
sig_label
|
| 1025 |
]
|
| 1026 |
for col, val in enumerate(row_data, 1):
|
| 1027 |
cell = ws_pve.cell(row=pve_row, column=col, value=val)
|
| 1028 |
-
cell.fill = fill; cell.border = thin_border
|
| 1029 |
-
|
| 1030 |
-
if col == 6 and isinstance(val, float):
|
| 1031 |
-
cell.number_format = '0.00E+00'
|
| 1032 |
pve_row += 1
|
| 1033 |
|
| 1034 |
-
#
|
| 1035 |
ws_qc = wb.create_sheet(title="SNP_QC")
|
| 1036 |
ws_qc['A1'] = "SNP Quality Control Statistics"
|
| 1037 |
ws_qc['A1'].font = title_font
|
| 1038 |
ws_qc.merge_cells('A1:F1')
|
| 1039 |
-
headers_qc = ["SNP",
|
| 1040 |
for col, h in enumerate(headers_qc, 1):
|
| 1041 |
cell = ws_qc.cell(row=3, column=col, value=h)
|
| 1042 |
cell.font = header_font; cell.fill = header_fill
|
|
@@ -1046,7 +1152,6 @@ def export_results_excel(all_results, snp_filt, chr_filt, pos_filt, y, G_filt, m
|
|
| 1046 |
for row_i in range(len(snp_filt)):
|
| 1047 |
maf_v = maf_vals[row_i] if row_i < len(maf_vals) else np.nan
|
| 1048 |
cr_v = call_rates[row_i] if row_i < len(call_rates) else np.nan
|
| 1049 |
-
cat = "Rare (<0.05)" if not np.isnan(maf_v) and maf_v < 0.05 else "Common"
|
| 1050 |
fill = alt_fill if row_i % 2 == 0 else PatternFill("solid", start_color="FFFFFF", end_color="FFFFFF")
|
| 1051 |
row_data = [
|
| 1052 |
str(snp_filt[row_i]),
|
|
@@ -1054,25 +1159,23 @@ def export_results_excel(all_results, snp_filt, chr_filt, pos_filt, y, G_filt, m
|
|
| 1054 |
int(pos_filt[row_i]) if row_i < len(pos_filt) else "",
|
| 1055 |
round(float(maf_v), 4) if not np.isnan(maf_v) else "",
|
| 1056 |
round(float(cr_v), 4) if not np.isnan(cr_v) else "",
|
| 1057 |
-
|
| 1058 |
]
|
| 1059 |
for col, val in enumerate(row_data, 1):
|
| 1060 |
cell = ws_qc.cell(row=row_i+4, column=col, value=val)
|
| 1061 |
-
cell.fill = fill; cell.border = thin_border
|
| 1062 |
-
cell.alignment = Alignment(horizontal='center')
|
| 1063 |
|
| 1064 |
wb.save(output_path)
|
| 1065 |
return output_path
|
| 1066 |
|
| 1067 |
def save_all_plots_zip(plot_dict, out_dir):
|
| 1068 |
-
"""Save all plots as PNG files in a temp zip"""
|
| 1069 |
zip_path = os.path.join(out_dir, "gwas_plots.zip")
|
| 1070 |
with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf:
|
| 1071 |
for name, fig in plot_dict.items():
|
| 1072 |
if fig is not None:
|
| 1073 |
buf = io.BytesIO()
|
| 1074 |
fig.savefig(buf, format="png", dpi=150, bbox_inches="tight",
|
| 1075 |
-
facecolor=
|
| 1076 |
buf.seek(0)
|
| 1077 |
zf.writestr(f"{name}.png", buf.read())
|
| 1078 |
return zip_path
|
|
@@ -1082,7 +1185,7 @@ def run_gwas(file_obj, text_input, selected_models, maf_threshold):
|
|
| 1082 |
try:
|
| 1083 |
df, snp_cols, chroms, positions = parse_data(file_obj, text_input)
|
| 1084 |
except Exception as e:
|
| 1085 |
-
return [None] *
|
| 1086 |
|
| 1087 |
y = df["Phenotype"].values.astype(float)
|
| 1088 |
ids = df["ID"].values
|
|
@@ -1104,6 +1207,16 @@ def run_gwas(file_obj, text_input, selected_models, maf_threshold):
|
|
| 1104 |
|
| 1105 |
K = build_kinship(G_filt)
|
| 1106 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1107 |
model_funcs = {
|
| 1108 |
"OLS": lambda: ols_gwas(y, G_filt),
|
| 1109 |
"MLM": lambda: mlm_gwas(y, G_filt, K),
|
|
@@ -1117,9 +1230,9 @@ def run_gwas(file_obj, text_input, selected_models, maf_threshold):
|
|
| 1117 |
"GEMMA": lambda: gemma_gwas(y, G_filt, K),
|
| 1118 |
}
|
| 1119 |
|
| 1120 |
-
models_to_run = selected_models if selected_models else list(model_funcs.keys())
|
| 1121 |
all_results = {}
|
| 1122 |
primary_p = primary_b = primary_se = None
|
|
|
|
| 1123 |
|
| 1124 |
for mname in models_to_run:
|
| 1125 |
if mname in model_funcs:
|
|
@@ -1128,56 +1241,58 @@ def run_gwas(file_obj, text_input, selected_models, maf_threshold):
|
|
| 1128 |
all_results[mname] = (p, b, se)
|
| 1129 |
if primary_p is None:
|
| 1130 |
primary_p, primary_b, primary_se = p, b, se
|
|
|
|
| 1131 |
except Exception as ex:
|
| 1132 |
-
|
|
|
|
| 1133 |
|
| 1134 |
if primary_p is None:
|
| 1135 |
-
return [None] *
|
| 1136 |
|
| 1137 |
-
# ── Build all named plots ──────────────────────────────────────────────────
|
| 1138 |
plot_dict = {}
|
| 1139 |
-
plot_dict["01_Manhattan_Primary"]
|
| 1140 |
-
|
| 1141 |
-
plot_dict["
|
| 1142 |
-
|
| 1143 |
-
plot_dict["
|
| 1144 |
-
plot_dict["
|
| 1145 |
-
plot_dict["
|
| 1146 |
-
plot_dict["
|
| 1147 |
-
plot_dict["
|
| 1148 |
-
plot_dict["
|
| 1149 |
-
plot_dict["
|
| 1150 |
-
plot_dict["
|
| 1151 |
-
|
| 1152 |
-
|
| 1153 |
-
# Per-model individual Manhattan + QQ
|
| 1154 |
for mname, (p, b, se) in all_results.items():
|
| 1155 |
-
plot_dict[f"
|
| 1156 |
-
plot_dict[f"
|
| 1157 |
|
| 1158 |
# PIL images for display
|
| 1159 |
imgs = {}
|
| 1160 |
for k, fig in plot_dict.items():
|
| 1161 |
imgs[k] = fig_to_pil(fig) if fig is not None else None
|
| 1162 |
|
| 1163 |
-
#
|
| 1164 |
tmp_dir = tempfile.mkdtemp()
|
| 1165 |
zip_path = save_all_plots_zip(plot_dict, tmp_dir)
|
| 1166 |
-
|
| 1167 |
-
# ── Export Excel ───────────────────────────────────────────────────────────────
|
| 1168 |
excel_path = os.path.join(tmp_dir, "gwas_results_complete.xlsx")
|
| 1169 |
export_results_excel(all_results, snp_filt, chr_filt, pos_filt, y, G_filt, maf_vals, excel_path)
|
| 1170 |
|
| 1171 |
plt.close('all')
|
| 1172 |
|
| 1173 |
-
#
|
| 1174 |
bonf = 0.05 / len(primary_p)
|
| 1175 |
lambdas_str = "\n ".join([
|
| 1176 |
-
f"{
|
| 1177 |
f"sig(Bonf)={int((p<bonf).sum())} sig(5e-8)={int((p<5e-8).sum())}"
|
| 1178 |
-
for
|
| 1179 |
])
|
| 1180 |
lam = np.median(stats.chi2.ppf(1-np.clip(primary_p,1e-10,1), df=1)) / stats.chi2.ppf(0.5, df=1)
|
|
|
|
|
|
|
|
|
|
| 1181 |
|
| 1182 |
summary = (
|
| 1183 |
f"{'='*68}\n"
|
|
@@ -1185,28 +1300,25 @@ def run_gwas(file_obj, text_input, selected_models, maf_threshold):
|
|
| 1185 |
f"{'='*68}\n"
|
| 1186 |
f" Samples: {n} | SNPs (raw): {m} | SNPs (filtered): {G_filt.shape[1]}\n"
|
| 1187 |
f" MAF threshold: ≥{maf_thr:.2f}\n"
|
| 1188 |
-
f" Models
|
|
|
|
| 1189 |
f"{'─'*68}\n"
|
| 1190 |
f" PER-MODEL RESULTS:\n {lambdas_str}\n"
|
|
|
|
| 1191 |
f"{'─'*68}\n"
|
| 1192 |
-
f" Primary model ({
|
| 1193 |
f" Bonferroni threshold : {bonf:.2e}\n"
|
| 1194 |
f" Significant MTAs : {int((primary_p<bonf).sum())}\n"
|
| 1195 |
f" Genomic Inflation λ : {lam:.4f}\n"
|
| 1196 |
f"{'─'*68}\n"
|
| 1197 |
f" 📥 Excel: gwas_results_complete.xlsx\n"
|
| 1198 |
-
f" • Summary
|
| 1199 |
-
f" • Per-model all SNP results with FDR & Bonferroni\n"
|
| 1200 |
-
f" • Significant MTAs combined\n"
|
| 1201 |
-
f" • QTN Effects with 95% CI & PVE\n"
|
| 1202 |
-
f" • PVE summary by model\n"
|
| 1203 |
-
f" • SNP QC table\n"
|
| 1204 |
f" 🖼 Plots: gwas_plots.zip ({len(plot_dict)} PNG files)\n"
|
|
|
|
| 1205 |
f"{'='*68}\n"
|
| 1206 |
)
|
| 1207 |
|
| 1208 |
-
|
| 1209 |
-
display_imgs = [
|
| 1210 |
imgs.get("01_Manhattan_Primary"),
|
| 1211 |
imgs.get("02_QQ_Primary"),
|
| 1212 |
imgs.get("03_QQ_All_Models"),
|
|
@@ -1218,211 +1330,81 @@ def run_gwas(file_obj, text_input, selected_models, maf_threshold):
|
|
| 1218 |
imgs.get("09_Effect_Sizes"),
|
| 1219 |
imgs.get("10_All_Models_Manhattan"),
|
| 1220 |
imgs.get("11_Summary_Dashboard"),
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1221 |
]
|
| 1222 |
-
return display_imgs + [excel_path, zip_path, summary]
|
| 1223 |
|
| 1224 |
-
# ───────────────────────
|
| 1225 |
PASTEL_CSS = """
|
| 1226 |
@import url('https://fonts.googleapis.com/css2?family=DM+Sans:wght@300;400;500;600&family=DM+Mono:wght@400;500&display=swap');
|
| 1227 |
-
|
| 1228 |
* { box-sizing: border-box; }
|
| 1229 |
-
|
| 1230 |
body, .gradio-container {
|
| 1231 |
background: #F7F8FC !important;
|
| 1232 |
font-family: 'DM Sans', sans-serif !important;
|
| 1233 |
color: #2D3142 !important;
|
| 1234 |
}
|
| 1235 |
-
|
| 1236 |
-
.gradio-container {
|
| 1237 |
-
max-width: 1400px !important;
|
| 1238 |
-
margin: 0 auto !important;
|
| 1239 |
-
}
|
| 1240 |
-
|
| 1241 |
-
/* Header */
|
| 1242 |
.gwas-header {
|
| 1243 |
background: linear-gradient(135deg, #E8F4FD 0%, #EDE9F8 50%, #FDF0F8 100%);
|
| 1244 |
-
border: 1px solid #D6E8F5;
|
| 1245 |
-
|
| 1246 |
-
padding: 28px 36px;
|
| 1247 |
-
margin-bottom: 24px;
|
| 1248 |
-
box-shadow: 0 2px 20px rgba(100, 120, 200, 0.08);
|
| 1249 |
-
}
|
| 1250 |
-
|
| 1251 |
-
.gwas-header h1 {
|
| 1252 |
-
font-size: 26px !important;
|
| 1253 |
-
font-weight: 600 !important;
|
| 1254 |
-
color: #2C5F8A !important;
|
| 1255 |
-
margin: 0 0 6px 0 !important;
|
| 1256 |
-
letter-spacing: -0.3px;
|
| 1257 |
-
}
|
| 1258 |
-
|
| 1259 |
-
.gwas-header p {
|
| 1260 |
-
color: #6B7A99 !important;
|
| 1261 |
-
font-size: 14px !important;
|
| 1262 |
-
margin: 4px 0 !important;
|
| 1263 |
-
}
|
| 1264 |
-
|
| 1265 |
-
.gwas-header .model-pills {
|
| 1266 |
-
display: flex;
|
| 1267 |
-
flex-wrap: wrap;
|
| 1268 |
-
gap: 6px;
|
| 1269 |
-
margin-top: 12px;
|
| 1270 |
}
|
| 1271 |
-
|
| 1272 |
-
|
| 1273 |
.gr-panel, .gr-box, .block, .panel {
|
| 1274 |
-
background: #FFFFFF !important;
|
| 1275 |
-
border: 1px
|
| 1276 |
-
border-radius: 14px !important;
|
| 1277 |
-
box-shadow: 0 1px 8px rgba(60, 80, 140, 0.06) !important;
|
| 1278 |
}
|
| 1279 |
-
|
| 1280 |
-
/* Labels */
|
| 1281 |
label, .label-wrap span {
|
| 1282 |
-
color: #5A6480 !important;
|
| 1283 |
-
|
| 1284 |
-
font-weight: 500 !important;
|
| 1285 |
-
text-transform: uppercase !important;
|
| 1286 |
-
letter-spacing: 0.5px !important;
|
| 1287 |
-
font-family: 'DM Sans', sans-serif !important;
|
| 1288 |
}
|
| 1289 |
-
|
| 1290 |
-
/* Inputs */
|
| 1291 |
input, textarea, select {
|
| 1292 |
-
background: #FAFBFF !important;
|
| 1293 |
-
|
| 1294 |
-
|
| 1295 |
-
border-radius: 10px !important;
|
| 1296 |
-
font-family: 'DM Mono', monospace !important;
|
| 1297 |
-
font-size: 12px !important;
|
| 1298 |
-
padding: 10px 14px !important;
|
| 1299 |
-
transition: border-color 0.2s ease !important;
|
| 1300 |
-
}
|
| 1301 |
-
|
| 1302 |
-
input:focus, textarea:focus {
|
| 1303 |
-
border-color: #7FB3E8 !important;
|
| 1304 |
-
box-shadow: 0 0 0 3px rgba(127, 179, 232, 0.15) !important;
|
| 1305 |
-
outline: none !important;
|
| 1306 |
}
|
| 1307 |
-
|
| 1308 |
-
/* Run button — teal-blue gradient */
|
| 1309 |
-
.run-button, button.primary {
|
| 1310 |
background: linear-gradient(135deg, #5BA8E5 0%, #7C6FCD 100%) !important;
|
| 1311 |
-
border: none !important;
|
| 1312 |
-
|
| 1313 |
-
|
| 1314 |
-
font-family: 'DM Sans', sans-serif !important;
|
| 1315 |
-
font-weight: 600 !important;
|
| 1316 |
-
font-size: 15px !important;
|
| 1317 |
-
letter-spacing: 0.2px !important;
|
| 1318 |
-
padding: 14px 28px !important;
|
| 1319 |
-
cursor: pointer !important;
|
| 1320 |
-
box-shadow: 0 4px 16px rgba(91, 168, 229, 0.35) !important;
|
| 1321 |
transition: all 0.2s ease !important;
|
| 1322 |
-
width: 100% !important;
|
| 1323 |
-
}
|
| 1324 |
-
|
| 1325 |
-
.run-button:hover, button.primary:hover {
|
| 1326 |
-
transform: translateY(-2px) !important;
|
| 1327 |
-
box-shadow: 0 6px 24px rgba(91, 168, 229, 0.45) !important;
|
| 1328 |
}
|
| 1329 |
-
|
| 1330 |
-
/* Checkbox group */
|
| 1331 |
-
.checkbox-group {
|
| 1332 |
-
background: #FAFBFF !important;
|
| 1333 |
-
border-radius: 10px !important;
|
| 1334 |
-
padding: 10px !important;
|
| 1335 |
-
}
|
| 1336 |
-
|
| 1337 |
-
/* Slider */
|
| 1338 |
-
input[type="range"] {
|
| 1339 |
-
accent-color: #7C6FCD !important;
|
| 1340 |
-
}
|
| 1341 |
-
|
| 1342 |
-
/* Tabs */
|
| 1343 |
.tab-nav {
|
| 1344 |
-
background: #F0F3FB !important;
|
| 1345 |
-
border-
|
| 1346 |
-
padding: 4px !important;
|
| 1347 |
-
border: 1px solid #E4E8F5 !important;
|
| 1348 |
-
overflow-x: auto !important;
|
| 1349 |
}
|
| 1350 |
-
|
| 1351 |
.tab-nav button {
|
| 1352 |
-
color: #6B7A99 !important;
|
| 1353 |
-
|
| 1354 |
-
|
| 1355 |
-
font-weight: 500 !important;
|
| 1356 |
-
border-radius: 9px !important;
|
| 1357 |
-
padding: 7px 14px !important;
|
| 1358 |
-
border: none !important;
|
| 1359 |
-
background: transparent !important;
|
| 1360 |
-
transition: all 0.15s ease !important;
|
| 1361 |
-
white-space: nowrap !important;
|
| 1362 |
}
|
| 1363 |
-
|
| 1364 |
.tab-nav button.selected, .tab-nav button:hover {
|
| 1365 |
-
background: #FFFFFF !important;
|
| 1366 |
-
|
| 1367 |
-
box-shadow: 0 1px 6px rgba(91, 168, 229, 0.2) !important;
|
| 1368 |
}
|
| 1369 |
-
|
| 1370 |
-
/* Summary textbox */
|
| 1371 |
.summary-box textarea {
|
| 1372 |
-
font-family: 'DM Mono', monospace !important;
|
| 1373 |
-
|
| 1374 |
-
|
| 1375 |
-
color: #2D3142 !important;
|
| 1376 |
-
border: 1px solid #DDE2F0 !important;
|
| 1377 |
-
border-radius: 10px !important;
|
| 1378 |
-
line-height: 1.7 !important;
|
| 1379 |
}
|
| 1380 |
-
|
| 1381 |
-
/* Image display */
|
| 1382 |
-
.gr-image {
|
| 1383 |
-
border-radius: 12px !important;
|
| 1384 |
-
overflow: hidden !important;
|
| 1385 |
-
border: 1px solid #E4E8F5 !important;
|
| 1386 |
-
}
|
| 1387 |
-
|
| 1388 |
-
/* Headings inside gradio */
|
| 1389 |
-
h1 { color: #2C5F8A !important; font-weight: 600 !important; }
|
| 1390 |
-
h2 { color: #4A70A0 !important; font-weight: 500 !important; }
|
| 1391 |
-
h3 { color: #5A7AB0 !important; font-weight: 500 !important; }
|
| 1392 |
-
|
| 1393 |
-
/* Download buttons */
|
| 1394 |
.download-section {
|
| 1395 |
background: linear-gradient(135deg, #EBF5FF 0%, #F0EBFF 100%);
|
| 1396 |
-
border: 1px solid #D0E4F5 !important;
|
| 1397 |
-
border-radius: 14px !important;
|
| 1398 |
-
padding: 18px !important;
|
| 1399 |
}
|
| 1400 |
-
|
| 1401 |
-
/* Section dividers */
|
| 1402 |
.section-label {
|
| 1403 |
-
font-size: 11px !important;
|
| 1404 |
-
|
| 1405 |
-
|
| 1406 |
-
text-transform: uppercase !important;
|
| 1407 |
-
letter-spacing: 1px !important;
|
| 1408 |
-
padding: 8px 0 4px 0 !important;
|
| 1409 |
-
border-bottom: 1px solid #E8ECF4 !important;
|
| 1410 |
margin-bottom: 8px !important;
|
| 1411 |
}
|
| 1412 |
-
|
| 1413 |
-
/* Dataframe */
|
| 1414 |
-
.gr-dataframe {
|
| 1415 |
-
border-radius: 12px !important;
|
| 1416 |
-
overflow: hidden !important;
|
| 1417 |
-
font-family: 'DM Mono', monospace !important;
|
| 1418 |
-
font-size: 12px !important;
|
| 1419 |
-
}
|
| 1420 |
-
|
| 1421 |
-
/* Scrollbar styling */
|
| 1422 |
::-webkit-scrollbar { width: 6px; height: 6px; }
|
| 1423 |
::-webkit-scrollbar-track { background: #F0F3FB; border-radius: 4px; }
|
| 1424 |
::-webkit-scrollbar-thumb { background: #C8D0E7; border-radius: 4px; }
|
| 1425 |
-
::-webkit-scrollbar-thumb:hover { background: #A8B4D0; }
|
| 1426 |
"""
|
| 1427 |
|
| 1428 |
SAMPLE_DATA = """ID,Phenotype,chr1_134521_SNP1,chr1_134810_SNP2,chr1_178766_SNP3,chr1_210328_SNP4
|
|
@@ -1446,15 +1428,14 @@ with gr.Blocks(css=PASTEL_CSS, title="🧬 GWAS Pipeline", theme=gr.themes.Base(
|
|
| 1446 |
gr.HTML("""
|
| 1447 |
<div class="gwas-header">
|
| 1448 |
<h1>🧬 Complete GWAS Analysis Pipeline</h1>
|
| 1449 |
-
<p>10 Statistical Models ·
|
| 1450 |
<p style="font-size:12px; color:#8892B0;">
|
| 1451 |
-
Per-model
|
| 1452 |
</p>
|
| 1453 |
</div>
|
| 1454 |
""")
|
| 1455 |
|
| 1456 |
with gr.Row(equal_height=False):
|
| 1457 |
-
# ── Left panel: inputs ─────────���────────────────────────────────────────
|
| 1458 |
with gr.Column(scale=1, min_width=320):
|
| 1459 |
gr.HTML('<div class="section-label">📂 Data Input</div>')
|
| 1460 |
file_in = gr.File(label="Upload CSV / TSV / TXT", file_types=[".csv", ".tsv", ".txt"])
|
|
@@ -1464,32 +1445,25 @@ with gr.Blocks(css=PASTEL_CSS, title="🧬 GWAS Pipeline", theme=gr.themes.Base(
|
|
| 1464 |
gr.HTML('<div class="section-label" style="margin-top:16px;">⚙️ Model Selection</div>')
|
| 1465 |
model_sel = gr.CheckboxGroup(
|
| 1466 |
choices=ALL_MODELS,
|
| 1467 |
-
value=
|
| 1468 |
label="Select models to run"
|
| 1469 |
)
|
| 1470 |
maf_thr = gr.Slider(0, 0.5, 0.05, 0.01, label="MAF Threshold")
|
| 1471 |
-
|
| 1472 |
-
run_btn = gr.Button("🚀 Run Complete GWAS Pipeline", variant="primary",
|
| 1473 |
-
elem_classes=["run-button"])
|
| 1474 |
|
| 1475 |
gr.HTML('<div class="section-label" style="margin-top:16px;">📥 Downloads</div>')
|
| 1476 |
with gr.Column(elem_classes=["download-section"]):
|
| 1477 |
-
excel_out = gr.File(label="📊 Excel Results (MTA · PVE · QTN · All Models)",
|
| 1478 |
-
|
| 1479 |
-
zip_out = gr.File(label="🖼 All Plots as PNG (ZIP)",
|
| 1480 |
-
interactive=False)
|
| 1481 |
|
| 1482 |
-
# ── Right panel: summary ────────────────────────────────────────────────
|
| 1483 |
with gr.Column(scale=2):
|
| 1484 |
gr.HTML('<div class="section-label">📊 Analysis Summary</div>')
|
| 1485 |
-
summary_out = gr.Textbox(label="", lines=
|
| 1486 |
-
show_label=False)
|
| 1487 |
|
| 1488 |
-
# ── Visualization tabs ────────────────────────────────────────────────────────
|
| 1489 |
gr.HTML('<div class="section-label" style="margin: 16px 0 8px 0;">🖼 Visualizations</div>')
|
| 1490 |
with gr.Tabs():
|
| 1491 |
with gr.Tab("🗺 Manhattan (Primary)"):
|
| 1492 |
-
img1 = gr.Image(type="pil", label="Manhattan
|
| 1493 |
with gr.Tab("📈 QQ (Primary)"):
|
| 1494 |
img2 = gr.Image(type="pil", label="QQ Plot — Primary Model")
|
| 1495 |
with gr.Tab("📈 QQ (All Models)"):
|
|
@@ -1498,30 +1472,31 @@ with gr.Blocks(css=PASTEL_CSS, title="🧬 GWAS Pipeline", theme=gr.themes.Base(
|
|
| 1498 |
img4 = gr.Image(type="pil", label="QQ Overlay — All Models with λ")
|
| 1499 |
with gr.Tab("🔵 Circos"):
|
| 1500 |
img5 = gr.Image(type="pil", label="Circos — Multi-Model Comparison")
|
| 1501 |
-
with gr.Tab("🔗 LD Decay
|
| 1502 |
-
img6 = gr.Image(type="pil", label="Linkage Disequilibrium Decay")
|
| 1503 |
with gr.Tab("🔬 PCA"):
|
| 1504 |
img7 = gr.Image(type="pil", label="Principal Component Analysis")
|
| 1505 |
with gr.Tab("👨👩👧 Kinship"):
|
| 1506 |
img8 = gr.Image(type="pil", label="Kinship Matrix & Clustering")
|
| 1507 |
with gr.Tab("⚖ Effect Sizes"):
|
| 1508 |
img9 = gr.Image(type="pil", label="Effect Sizes & Volcano Plot")
|
| 1509 |
-
with gr.Tab("🔄 All Models
|
| 1510 |
-
img10 = gr.Image(type="pil", label="Manhattan — All Models
|
| 1511 |
with gr.Tab("📊 Dashboard"):
|
| 1512 |
img11 = gr.Image(type="pil", label="Summary Dashboard — All Models")
|
|
|
|
|
|
|
| 1513 |
|
| 1514 |
def run_wrapper(f, t, m, maf):
|
| 1515 |
out = run_gwas(f, t, m, maf)
|
| 1516 |
-
|
| 1517 |
-
while len(out) < 14:
|
| 1518 |
out.append(None)
|
| 1519 |
return out
|
| 1520 |
|
| 1521 |
run_btn.click(
|
| 1522 |
run_wrapper,
|
| 1523 |
inputs=[file_in, text_in, model_sel, maf_thr],
|
| 1524 |
-
outputs=[img1, img2, img3, img4, img5, img6, img7, img8, img9, img10, img11,
|
| 1525 |
excel_out, zip_out, summary_out]
|
| 1526 |
)
|
| 1527 |
|
|
|
|
| 15 |
from sklearn.decomposition import PCA
|
| 16 |
from sklearn.preprocessing import StandardScaler
|
| 17 |
from sklearn.linear_model import LinearRegression
|
| 18 |
+
from sklearn.manifold import MDS
|
| 19 |
from statsmodels.stats.multitest import multipletests
|
| 20 |
import io, re, os, zipfile, tempfile
|
| 21 |
from io import StringIO
|
|
|
|
| 23 |
from openpyxl.styles import Font, PatternFill, Alignment, Border, Side
|
| 24 |
from openpyxl.utils import get_column_letter
|
| 25 |
|
| 26 |
+
# ─────────────────────── PLOT COLORS — WHITE/LIGHT THEME ──────────────────────
|
| 27 |
+
BG_WHITE = "#FFFFFF"
|
| 28 |
+
PANEL_WHITE = "#FAFAFA"
|
| 29 |
+
PANEL_LIGHT = "#F3F6FC"
|
| 30 |
+
ACCENT_TEAL = "#0EA5A0"
|
| 31 |
+
ACCENT_GOLD = "#D97706"
|
| 32 |
+
ACCENT_CORAL= "#E5534B"
|
| 33 |
+
ACCENT_BLUE = "#3B82F6"
|
| 34 |
+
ACCENT_LIME = "#65A30D"
|
| 35 |
+
ACCENT_PURP = "#7C3AED"
|
| 36 |
+
ACCENT_PINK = "#DB2777"
|
| 37 |
+
ACCENT_CYAN = "#0891B2"
|
| 38 |
+
ACCENT_ORG = "#EA580C"
|
| 39 |
+
TEXT_MAIN = "#1E293B"
|
| 40 |
+
TEXT_DIM = "#475569"
|
| 41 |
+
GRID_LINE = "#E2E8F0"
|
| 42 |
+
SIG_COLOR = "#DC2626"
|
| 43 |
|
| 44 |
MODEL_COLORS = {
|
| 45 |
+
"OLS": "#3B82F6",
|
| 46 |
+
"MLM": "#0EA5A0",
|
| 47 |
+
"GLM": "#E5534B",
|
| 48 |
+
"CMLM": "#7C3AED",
|
| 49 |
+
"BLINK": "#D97706",
|
| 50 |
+
"FarmCPU": "#65A30D",
|
| 51 |
+
"EMMAX": "#DB2777",
|
| 52 |
+
"PLINK": "#0891B2",
|
| 53 |
+
"GAPIT3": "#EA580C",
|
| 54 |
+
"GEMMA": "#9333EA",
|
| 55 |
}
|
| 56 |
|
| 57 |
CHR_PALETTE = [
|
| 58 |
+
"#3B82F6","#0EA5A0","#E5534B","#7C3AED","#D97706",
|
| 59 |
+
"#65A30D","#DB2777","#0891B2","#EA580C","#9333EA",
|
| 60 |
+
"#059669","#CA8A04","#6366F1","#EC4899","#14B8A6",
|
| 61 |
]
|
| 62 |
|
| 63 |
def style_fig(fig):
|
| 64 |
+
"""Apply clean white theme to all axes."""
|
| 65 |
+
fig.patch.set_facecolor(BG_WHITE)
|
| 66 |
for ax in fig.get_axes():
|
| 67 |
+
ax.set_facecolor(PANEL_WHITE)
|
| 68 |
ax.tick_params(colors=TEXT_DIM, labelsize=8)
|
| 69 |
ax.xaxis.label.set_color(TEXT_DIM)
|
| 70 |
ax.yaxis.label.set_color(TEXT_DIM)
|
| 71 |
ax.title.set_color(TEXT_MAIN)
|
| 72 |
for spine in ax.spines.values():
|
| 73 |
spine.set_edgecolor(GRID_LINE)
|
| 74 |
+
spine.set_linewidth(0.8)
|
| 75 |
+
ax.grid(color=GRID_LINE, linewidth=0.5, linestyle="--", alpha=0.7)
|
| 76 |
return fig
|
| 77 |
|
| 78 |
# ─────────────────────── DATA PARSING ────────────────────────────────────────────
|
|
|
|
| 166 |
return Z @ Z.T / denom
|
| 167 |
|
| 168 |
def compute_pve(y, G, pvals, betas, threshold=0.05):
|
|
|
|
| 169 |
bonf = threshold / len(pvals)
|
| 170 |
sig_idx = np.where(pvals < bonf)[0]
|
| 171 |
pve_dict = {}
|
|
|
|
| 172 |
for idx in sig_idx:
|
| 173 |
x = G[:, idx]
|
| 174 |
mask = ~np.isnan(x)
|
|
|
|
| 176 |
pve_dict[idx] = 0.0
|
| 177 |
continue
|
| 178 |
corr = np.corrcoef(x[mask], y[mask])[0, 1]
|
| 179 |
+
pve_dict[idx] = corr**2 * 100
|
| 180 |
+
return pve_dict, np.var(y)
|
| 181 |
|
| 182 |
def fig_to_png_bytes(fig):
|
| 183 |
buf = io.BytesIO()
|
|
|
|
| 222 |
n, m = G.shape
|
| 223 |
pvals = np.ones(m); betas = np.zeros(m); ses = np.zeros(m)
|
| 224 |
n_pcs = min(3, n - 2)
|
| 225 |
+
try:
|
| 226 |
+
PCs = PCA(n_components=n_pcs).fit_transform(StandardScaler().fit_transform(G))
|
| 227 |
+
y_adj = y - LinearRegression().fit(PCs, y).predict(PCs)
|
| 228 |
+
except Exception:
|
| 229 |
+
y_adj = y - y.mean()
|
| 230 |
+
PCs = np.zeros((n, 1))
|
| 231 |
for j in range(m):
|
| 232 |
x = G[:, j]
|
| 233 |
if x.std() < 1e-8: continue
|
| 234 |
+
try:
|
| 235 |
+
x_adj = x - LinearRegression().fit(PCs, x).predict(PCs)
|
| 236 |
+
except Exception:
|
| 237 |
+
x_adj = x - x.mean()
|
| 238 |
slope, _, _, p, se = stats.linregress(x_adj, y_adj)
|
| 239 |
pvals[j] = p; betas[j] = slope; ses[j] = se
|
| 240 |
return pvals, betas, ses
|
|
|
|
| 245 |
n_groups = min(3, n)
|
| 246 |
groups = np.array([i % n_groups for i in range(n)])
|
| 247 |
group_means = np.column_stack([K[:, np.where(groups == g)[0]].mean(axis=1) for g in range(n_groups)])
|
| 248 |
+
try:
|
| 249 |
+
y_res = y - LinearRegression().fit(group_means, y).predict(group_means)
|
| 250 |
+
except Exception:
|
| 251 |
+
y_res = y - y.mean()
|
| 252 |
for j in range(m):
|
| 253 |
x = G[:, j]
|
| 254 |
+
try:
|
| 255 |
+
x_res = x - LinearRegression().fit(group_means, x).predict(group_means)
|
| 256 |
+
except Exception:
|
| 257 |
+
x_res = x - x.mean()
|
| 258 |
if x_res.std() < 1e-8: continue
|
| 259 |
slope, _, _, p, se = stats.linregress(x_res, y_res)
|
| 260 |
pvals[j] = p; betas[j] = slope; ses[j] = se
|
|
|
|
| 266 |
ols_p, _, _ = ols_gwas(y, G)
|
| 267 |
top_idx = np.argsort(ols_p)[:min(3, m)]
|
| 268 |
covars = G[:, top_idx]
|
| 269 |
+
try:
|
| 270 |
+
y_adj = y - LinearRegression().fit(covars, y).predict(covars)
|
| 271 |
+
except Exception:
|
| 272 |
+
y_adj = y - y.mean()
|
| 273 |
for j in range(m):
|
| 274 |
x = G[:, j]
|
| 275 |
if x.std() < 1e-8: continue
|
|
|
|
| 283 |
mlm_p, _, _ = mlm_gwas(y, G, K)
|
| 284 |
qtn_idx = np.argsort(mlm_p)[:min(3, m)]
|
| 285 |
qtns = G[:, qtn_idx]
|
| 286 |
+
try:
|
| 287 |
+
y_adj = y - LinearRegression().fit(qtns, y).predict(qtns)
|
| 288 |
+
except Exception:
|
| 289 |
+
y_adj = y - y.mean()
|
| 290 |
for j in range(m):
|
| 291 |
x = G[:, j]
|
| 292 |
if x.std() < 1e-8: continue
|
|
|
|
| 302 |
V = tau * K + sigma * np.eye(n)
|
| 303 |
try:
|
| 304 |
V_inv = np.linalg.inv(V + np.eye(n) * 1e-6)
|
| 305 |
+
except Exception:
|
| 306 |
V_inv = np.eye(n)
|
| 307 |
for j in range(m):
|
| 308 |
x = G[:, j].reshape(-1, 1)
|
| 309 |
+
try:
|
| 310 |
+
Px = V_inv @ x
|
| 311 |
+
beta = (x.T @ Px @ y) / (x.T @ Px @ x + 1e-10)
|
| 312 |
+
betas[j] = float(beta)
|
| 313 |
+
resid = y - float(beta) * x.flatten()
|
| 314 |
+
sigma_e = (resid @ V_inv @ resid) / (n - 2 + 1e-10)
|
| 315 |
+
se = np.sqrt(float(sigma_e / (x.T @ Px @ x + 1e-10)))
|
| 316 |
+
ses[j] = se
|
| 317 |
+
t_stat = float(beta) / (se + 1e-10)
|
| 318 |
+
pvals[j] = float(2 * stats.t.sf(abs(t_stat), df=n-2))
|
| 319 |
+
except Exception:
|
| 320 |
+
pass
|
| 321 |
return pvals, betas, ses
|
| 322 |
|
| 323 |
def plink_gwas(y, G):
|
|
|
|
| 338 |
pvals[j] = p
|
| 339 |
slope, _, _, p2, se = stats.linregress(x, y_bin)
|
| 340 |
betas[j] = slope; ses[j] = se
|
| 341 |
+
except Exception:
|
| 342 |
pass
|
| 343 |
return pvals, betas, ses
|
| 344 |
|
|
|
|
| 346 |
n, m = G.shape
|
| 347 |
pvals = np.ones(m); betas = np.zeros(m); ses = np.zeros(m)
|
| 348 |
n_pcs = min(3, n - 2)
|
| 349 |
+
try:
|
| 350 |
+
PCs = PCA(n_components=n_pcs).fit_transform(StandardScaler().fit_transform(G))
|
| 351 |
+
except Exception:
|
| 352 |
+
PCs = np.zeros((n, 1))
|
| 353 |
eigvals, eigvecs = np.linalg.eigh(K + np.eye(n) * 1e-6)
|
| 354 |
Q = eigvecs[:, np.argsort(eigvals)[::-1][:n_pcs]]
|
| 355 |
covars = np.hstack([PCs, Q])
|
|
|
|
| 358 |
for j in range(m):
|
| 359 |
x = G[:, j]
|
| 360 |
if x.std() < 1e-8: continue
|
| 361 |
+
try:
|
| 362 |
+
if len(qtns) > 0:
|
| 363 |
+
cov = np.column_stack([covars] + [G[:, q].reshape(-1,1) for q in qtns])
|
| 364 |
+
else:
|
| 365 |
+
cov = covars
|
| 366 |
+
x_res = x - LinearRegression().fit(cov, x).predict(cov)
|
| 367 |
+
y_res = y - LinearRegression().fit(cov, y).predict(cov)
|
| 368 |
+
slope, _, _, p, se = stats.linregress(x_res, y_res)
|
| 369 |
+
pvals[j] = p; betas[j] = slope; ses[j] = se
|
| 370 |
+
except Exception:
|
| 371 |
+
pass
|
| 372 |
new_qtns = list(np.where(pvals < 0.05 / m)[0][:2])
|
| 373 |
if new_qtns and new_qtns != qtns:
|
| 374 |
qtns = new_qtns
|
|
|
|
| 387 |
idx = np.argsort(eigvals)[::-1]
|
| 388 |
n_pcs = min(4, n - 2)
|
| 389 |
Q = eigvecs[:, idx[:n_pcs]]
|
| 390 |
+
try:
|
| 391 |
+
y_res = y - LinearRegression().fit(Q, y).predict(Q)
|
| 392 |
+
except Exception:
|
| 393 |
+
y_res = y - y.mean()
|
| 394 |
for j in range(m):
|
| 395 |
x = G[:, j]
|
| 396 |
+
try:
|
| 397 |
+
x_res = x - LinearRegression().fit(Q, x).predict(Q)
|
| 398 |
+
except Exception:
|
| 399 |
+
x_res = x - x.mean()
|
| 400 |
if x_res.std() < 1e-8: continue
|
| 401 |
slope, _, _, p, se = stats.linregress(x_res, y_res)
|
| 402 |
pvals[j] = p; betas[j] = slope; ses[j] = se
|
|
|
|
| 406 |
pvals = 1 - stats.chi2.cdf(np.clip(chi2_vals, 0, 1e10), df=1)
|
| 407 |
return pvals, betas, ses
|
| 408 |
|
| 409 |
+
# ─────────────────────── PLOTS (WHITE BACKGROUND) ────────────────────────────────
|
| 410 |
def plot_manhattan(pvals, chroms, positions, title="Manhattan Plot", model_name=""):
|
| 411 |
+
fig, ax = plt.subplots(figsize=(16, 5), facecolor=BG_WHITE)
|
| 412 |
+
ax.set_facecolor(PANEL_WHITE)
|
| 413 |
style_fig(fig)
|
| 414 |
+
|
| 415 |
log_p = -np.log10(np.clip(pvals, 1e-300, 1))
|
| 416 |
sig_line = -np.log10(5e-8)
|
| 417 |
sug_line = -np.log10(1e-5)
|
|
|
|
| 428 |
x_coords[np.where(mask)[0][order]] = x_vals
|
| 429 |
tick_pos.append(x_vals.mean())
|
| 430 |
tick_lab.append(f"Chr{ch}")
|
| 431 |
+
ax.scatter(x_coords[mask], log_p[mask], c=chrom_colors[ch], s=14, alpha=0.8, linewidths=0)
|
| 432 |
x_offset += (pos.max() - pos.min()) + max(positions) * 0.015 + 1
|
| 433 |
+
|
| 434 |
+
ax.axhline(sug_line, color=ACCENT_TEAL, ls=":", lw=1.2, alpha=0.8, label=f"Suggestive (1e-5)")
|
| 435 |
+
ax.axhline(sig_line, color=ACCENT_CORAL, ls="--", lw=1.8, label=f"GW sig. (5e-8)")
|
| 436 |
sig_mask = log_p >= sig_line
|
| 437 |
if sig_mask.any():
|
| 438 |
+
ax.scatter(x_coords[sig_mask], log_p[sig_mask], c=SIG_COLOR, s=90, marker="D",
|
| 439 |
+
zorder=10, edgecolors="#7F1D1D", linewidth=0.8,
|
| 440 |
label=f"Sig. MTA ({sig_mask.sum()} SNPs)")
|
| 441 |
ax.set_xticks(tick_pos)
|
| 442 |
ax.set_xticklabels(tick_lab, rotation=45, fontsize=7, color=TEXT_DIM)
|
| 443 |
+
ax.set_ylabel("-log₁₀(p)", color=TEXT_DIM, fontsize=9)
|
| 444 |
ax.set_title(f"{title}{' — ' + model_name if model_name else ''}", color=TEXT_MAIN, fontsize=11, pad=8)
|
| 445 |
+
ax.legend(fontsize=7, framealpha=0.9, facecolor=BG_WHITE, edgecolor=GRID_LINE, labelcolor=TEXT_MAIN)
|
| 446 |
ax.set_xlim(-x_offset * 0.01, x_offset * 1.01)
|
| 447 |
fig.tight_layout()
|
| 448 |
return fig
|
| 449 |
|
| 450 |
def plot_qq_single(pvals, title="QQ Plot", model_name="", color=None):
|
|
|
|
| 451 |
if color is None:
|
| 452 |
color = ACCENT_PURP
|
| 453 |
+
fig, ax = plt.subplots(figsize=(7, 7), facecolor=BG_WHITE)
|
| 454 |
+
ax.set_facecolor(PANEL_WHITE)
|
| 455 |
style_fig(fig)
|
| 456 |
+
|
| 457 |
n = len(pvals)
|
| 458 |
obs = np.sort(-np.log10(np.clip(pvals, 1e-300, 1)))[::-1]
|
| 459 |
exp = -np.log10(np.linspace(1/n, 1, n)[::-1])
|
| 460 |
ci_lower = -np.log10(stats.beta.ppf(0.975, np.arange(1, n+1), np.arange(n, 0, -1)))
|
| 461 |
ci_upper = -np.log10(stats.beta.ppf(0.025, np.arange(1, n+1), np.arange(n, 0, -1)))
|
| 462 |
+
ax.fill_between(exp, ci_lower, ci_upper, alpha=0.2, color=color, label="95% CI")
|
| 463 |
+
ax.scatter(exp, obs, c=color, s=24, alpha=0.85, linewidths=0, zorder=5)
|
| 464 |
+
ax.plot([0, max(exp)], [0, max(exp)], color=ACCENT_CORAL, ls="--", lw=2, label="Expected", zorder=6)
|
| 465 |
lam = np.median(stats.chi2.ppf(1 - np.clip(pvals, 1e-10, 1), df=1)) / stats.chi2.ppf(0.5, df=1)
|
| 466 |
+
ax.text(0.05, 0.93, f"λ = {lam:.4f}", transform=ax.transAxes, fontsize=13,
|
| 467 |
color=ACCENT_GOLD, fontweight='bold')
|
| 468 |
+
ax.set_xlabel("Expected -log₁₀(p)", fontsize=10, color=TEXT_DIM)
|
| 469 |
+
ax.set_ylabel("Observed -log₁₀(p)", fontsize=10, color=TEXT_DIM)
|
| 470 |
ax.set_title(f"{title}{' — ' + model_name if model_name else ''}", color=TEXT_MAIN, fontsize=12)
|
| 471 |
+
ax.legend(fontsize=9, framealpha=0.9, facecolor=BG_WHITE, edgecolor=GRID_LINE, labelcolor=TEXT_MAIN)
|
| 472 |
fig.tight_layout()
|
| 473 |
return fig
|
| 474 |
|
|
|
|
| 476 |
n_models = len(all_results)
|
| 477 |
ncols = min(3, n_models)
|
| 478 |
nrows = (n_models + ncols - 1) // ncols
|
| 479 |
+
fig, axes = plt.subplots(nrows, ncols, figsize=(7 * ncols, 6 * nrows), facecolor=BG_WHITE)
|
| 480 |
style_fig(fig)
|
| 481 |
if n_models == 1:
|
| 482 |
axes = np.array([axes])
|
| 483 |
axes = np.array(axes).flatten()
|
| 484 |
for idx, (mname, (pvals, _, _)) in enumerate(all_results.items()):
|
| 485 |
ax = axes[idx]
|
| 486 |
+
ax.set_facecolor(PANEL_WHITE)
|
| 487 |
n = len(pvals)
|
| 488 |
obs = np.sort(-np.log10(np.clip(pvals, 1e-300, 1)))[::-1]
|
| 489 |
exp = -np.log10(np.linspace(1/n, 1, n)[::-1])
|
| 490 |
ci_lo = -np.log10(stats.beta.ppf(0.975, np.arange(1, n+1), np.arange(n, 0, -1)))
|
| 491 |
ci_hi = -np.log10(stats.beta.ppf(0.025, np.arange(1, n+1), np.arange(n, 0, -1)))
|
| 492 |
col = MODEL_COLORS.get(mname, ACCENT_BLUE)
|
| 493 |
+
ax.fill_between(exp, ci_lo, ci_hi, alpha=0.2, color=col)
|
| 494 |
+
ax.scatter(exp, obs, c=col, s=18, alpha=0.85, linewidths=0)
|
| 495 |
+
ax.plot([0, max(exp)], [0, max(exp)], color=ACCENT_CORAL, ls="--", lw=1.8, alpha=0.9)
|
| 496 |
lam = np.median(stats.chi2.ppf(1 - np.clip(pvals, 1e-10, 1), df=1)) / stats.chi2.ppf(0.5, df=1)
|
| 497 |
+
ax.text(0.05, 0.92, f"λ = {lam:.4f}", transform=ax.transAxes, fontsize=10,
|
| 498 |
color=ACCENT_GOLD, fontweight='bold')
|
| 499 |
+
ax.set_xlabel("Expected -log₁₀(p)", fontsize=8, color=TEXT_DIM)
|
| 500 |
+
ax.set_ylabel("Observed -log₁₀(p)", fontsize=8, color=TEXT_DIM)
|
| 501 |
ax.set_title(f"QQ — {mname}", color=col, fontsize=10)
|
| 502 |
+
for spine in ax.spines.values():
|
| 503 |
+
spine.set_edgecolor(GRID_LINE)
|
| 504 |
+
ax.grid(color=GRID_LINE, linewidth=0.5, linestyle="--", alpha=0.7)
|
| 505 |
+
ax.tick_params(colors=TEXT_DIM, labelsize=8)
|
| 506 |
for idx in range(n_models, len(axes)):
|
| 507 |
axes[idx].set_visible(False)
|
| 508 |
fig.suptitle("QQ Plots — All Models", color=TEXT_MAIN, fontsize=13, y=1.01)
|
|
|
|
| 510 |
return fig
|
| 511 |
|
| 512 |
def plot_qq_overlay(all_results):
|
| 513 |
+
fig, ax = plt.subplots(figsize=(9, 9), facecolor=BG_WHITE)
|
| 514 |
+
ax.set_facecolor(PANEL_WHITE)
|
| 515 |
style_fig(fig)
|
| 516 |
exp_max = 0
|
| 517 |
for mname, (pvals, _, _) in all_results.items():
|
|
|
|
| 521 |
exp_max = max(exp_max, max(exp))
|
| 522 |
lam = np.median(stats.chi2.ppf(1 - np.clip(pvals, 1e-10, 1), df=1)) / stats.chi2.ppf(0.5, df=1)
|
| 523 |
ax.plot(exp, obs, color=MODEL_COLORS.get(mname, ACCENT_BLUE),
|
| 524 |
+
lw=2.2, label=f"{mname} (λ={lam:.3f})", alpha=0.85)
|
| 525 |
+
ax.plot([0, exp_max], [0, exp_max], color=ACCENT_CORAL, ls="--", lw=2, label="Expected")
|
| 526 |
+
ax.set_xlabel("Expected -log₁₀(p)", fontsize=10, color=TEXT_DIM)
|
| 527 |
+
ax.set_ylabel("Observed -log₁₀(p)", fontsize=10, color=TEXT_DIM)
|
| 528 |
ax.set_title("QQ Plot — All Models Overlay", color=TEXT_MAIN, fontsize=12)
|
| 529 |
+
ax.legend(fontsize=8, framealpha=0.9, facecolor=BG_WHITE, edgecolor=GRID_LINE, labelcolor=TEXT_MAIN)
|
| 530 |
fig.tight_layout()
|
| 531 |
return fig
|
| 532 |
|
| 533 |
def plot_circos(all_results, chroms, positions):
|
| 534 |
+
fig, ax = plt.subplots(figsize=(14, 14), subplot_kw=dict(projection='polar'), facecolor=BG_WHITE)
|
| 535 |
+
ax.set_facecolor(BG_WHITE)
|
|
|
|
| 536 |
ax.grid(False)
|
| 537 |
ax.set_yticks([])
|
| 538 |
ax.set_xticks([])
|
|
|
|
| 567 |
col = MODEL_COLORS.get(mname, CHR_PALETTE[midx % len(CHR_PALETTE)])
|
| 568 |
max_lp = max(log_p.max(), sig_line, 1)
|
| 569 |
lp_norm = log_p[sort_idx] / max_lp * r_max_data
|
| 570 |
+
ax.plot(angles_sorted, np.full_like(angles_sorted, r_base), color=col, alpha=0.2, lw=0.6)
|
| 571 |
ax.scatter(angles_sorted, r_base + lp_norm, c=col, s=4, alpha=0.6, linewidths=0)
|
| 572 |
sig_mask = log_p[sort_idx] >= sig_line
|
| 573 |
if sig_mask.any():
|
| 574 |
ax.scatter(angles_sorted[sig_mask], r_base + lp_norm[sig_mask],
|
| 575 |
+
c=SIG_COLOR, s=40, zorder=10, marker='D', edgecolors='#7F1D1D',
|
| 576 |
+
linewidth=0.6, alpha=0.95)
|
| 577 |
ax.text(0, r_base + r_max_data / 2, mname, ha='center', va='center',
|
| 578 |
fontsize=7, color=col, fontweight='bold', alpha=0.9)
|
| 579 |
legend_elements = [mpatches.Patch(facecolor=MODEL_COLORS.get(m, ACCENT_BLUE), label=m, alpha=0.8)
|
| 580 |
for m in model_names]
|
| 581 |
+
legend_elements.append(mpatches.Patch(facecolor=SIG_COLOR, label="Sig. MTA (◆)", alpha=0.9))
|
| 582 |
ax.legend(handles=legend_elements, loc='lower center', bbox_to_anchor=(0.5, -0.08),
|
| 583 |
+
ncol=min(5, n_models+1), fontsize=7, framealpha=0.9, facecolor=BG_WHITE,
|
| 584 |
edgecolor=GRID_LINE, labelcolor=TEXT_MAIN)
|
| 585 |
+
ax.set_title("Circos Plot — Multi-Model GWAS Comparison\n(Ring height = -log₁₀(p) | ◆ = Significant MTA)",
|
| 586 |
color=TEXT_MAIN, fontsize=12, pad=20)
|
| 587 |
fig.tight_layout()
|
| 588 |
return fig
|
| 589 |
|
| 590 |
def plot_ld_decay(G, positions):
|
| 591 |
+
fig, axes = plt.subplots(1, 2, figsize=(16, 6), facecolor=BG_WHITE)
|
| 592 |
style_fig(fig)
|
| 593 |
m = G.shape[1]
|
| 594 |
dists_bp, r2s = [], []
|
|
|
|
| 609 |
dists_bp = np.array(dists_bp)
|
| 610 |
dists_mb = dists_bp / 1_000_000
|
| 611 |
r2s = np.array(r2s)
|
| 612 |
+
|
| 613 |
def bin_ld(dists, r2s, n_bins=20):
|
| 614 |
bins = np.percentile(dists, np.linspace(0, 100, n_bins + 1))
|
| 615 |
centers, means, sems = [], [], []
|
|
|
|
| 620 |
means.append(np.mean(r2s[mask]))
|
| 621 |
sems.append(stats.sem(r2s[mask]))
|
| 622 |
return np.array(centers), np.array(means), np.array(sems)
|
| 623 |
+
|
| 624 |
ax = axes[0]
|
| 625 |
+
ax.set_facecolor(PANEL_WHITE)
|
| 626 |
ax.scatter(dists_bp, r2s, c=ACCENT_TEAL, s=12, alpha=0.35, linewidths=0)
|
| 627 |
bc, bm, bs = bin_ld(dists_bp, r2s)
|
| 628 |
if len(bc) > 0:
|
| 629 |
ax.plot(bc, bm, color=ACCENT_CORAL, lw=2.5, marker='o', ms=5, zorder=5, label="Binned mean r²")
|
| 630 |
ax.fill_between(bc, bm - bs, bm + bs, alpha=0.2, color=ACCENT_CORAL)
|
| 631 |
+
ax.axhline(0.5, color=ACCENT_GOLD, ls='--', lw=1.5, alpha=0.9, label="r² = 0.5")
|
| 632 |
+
ax.axhline(0.2, color=ACCENT_PURP, ls=':', lw=1.2, alpha=0.8, label="r² = 0.2")
|
| 633 |
+
ax.set_xlabel("Distance (bp)", fontsize=9, color=TEXT_DIM)
|
| 634 |
+
ax.set_ylabel("r² (LD)", fontsize=9, color=TEXT_DIM)
|
| 635 |
ax.set_title("LD Decay — Base Pairs (bp)", color=TEXT_MAIN, fontsize=11)
|
| 636 |
+
ax.legend(fontsize=7, framealpha=0.9, facecolor=BG_WHITE, edgecolor=GRID_LINE, labelcolor=TEXT_MAIN)
|
| 637 |
ax.set_ylim(0, 1.05)
|
| 638 |
+
|
| 639 |
ax2 = axes[1]
|
| 640 |
+
ax2.set_facecolor(PANEL_WHITE)
|
| 641 |
ax2.scatter(dists_mb, r2s, c=ACCENT_PURP, s=12, alpha=0.35, linewidths=0)
|
| 642 |
bc2, bm2, bs2 = bin_ld(dists_mb, r2s)
|
| 643 |
if len(bc2) > 0:
|
| 644 |
ax2.plot(bc2, bm2, color=ACCENT_GOLD, lw=2.5, marker='o', ms=5, zorder=5, label="Binned mean r²")
|
| 645 |
ax2.fill_between(bc2, bm2 - bs2, bm2 + bs2, alpha=0.2, color=ACCENT_GOLD)
|
| 646 |
+
ax2.axhline(0.5, color=ACCENT_CORAL, ls='--', lw=1.5, alpha=0.9, label="r² = 0.5")
|
| 647 |
+
ax2.axhline(0.2, color=ACCENT_TEAL, ls=':', lw=1.2, alpha=0.8, label="r² = 0.2")
|
| 648 |
+
ax2.set_xlabel("Distance (Mb)", fontsize=9, color=TEXT_DIM)
|
| 649 |
+
ax2.set_ylabel("r² (LD)", fontsize=9, color=TEXT_DIM)
|
| 650 |
ax2.set_title("LD Decay — Megabases (Mb)", color=TEXT_MAIN, fontsize=11)
|
| 651 |
+
ax2.legend(fontsize=7, framealpha=0.9, facecolor=BG_WHITE, edgecolor=GRID_LINE, labelcolor=TEXT_MAIN)
|
| 652 |
ax2.set_ylim(0, 1.05)
|
| 653 |
+
|
| 654 |
fig.suptitle("Linkage Disequilibrium (LD) Decay Analysis", color=TEXT_MAIN, fontsize=13)
|
| 655 |
fig.tight_layout()
|
| 656 |
return fig
|
| 657 |
|
| 658 |
def plot_pca(G, y, ids):
|
| 659 |
+
fig, axes = plt.subplots(2, 2, figsize=(14, 12), facecolor=BG_WHITE)
|
| 660 |
style_fig(fig)
|
| 661 |
+
try:
|
| 662 |
+
G_sc = StandardScaler().fit_transform(G)
|
| 663 |
+
n_comp = min(5, G_sc.shape[0]-1, G_sc.shape[1])
|
| 664 |
+
pca = PCA(n_components=n_comp)
|
| 665 |
+
pcs = pca.fit_transform(G_sc)
|
| 666 |
+
var_exp = pca.explained_variance_ratio_ * 100
|
| 667 |
+
except Exception:
|
| 668 |
+
for ax in axes.flatten():
|
| 669 |
+
ax.text(0.5, 0.5, "PCA unavailable", ha='center', transform=ax.transAxes, color=TEXT_DIM)
|
| 670 |
+
fig.tight_layout()
|
| 671 |
+
return fig
|
| 672 |
+
|
| 673 |
+
axes[0,0].set_facecolor(PANEL_WHITE)
|
| 674 |
sc = axes[0,0].scatter(pcs[:,0], pcs[:,1], c=y, cmap='plasma', s=60, edgecolors='none')
|
| 675 |
+
axes[0,0].set_xlabel(f"PC1 ({var_exp[0]:.1f}%)", color=TEXT_DIM)
|
| 676 |
+
axes[0,0].set_ylabel(f"PC2 ({var_exp[1]:.1f}%)", color=TEXT_DIM)
|
| 677 |
+
axes[0,0].set_title("PCA: PC1 vs PC2", color=TEXT_MAIN)
|
| 678 |
+
plt.colorbar(sc, ax=axes[0,0], label="Phenotype")
|
| 679 |
+
|
| 680 |
+
axes[0,1].set_facecolor(PANEL_WHITE)
|
| 681 |
if n_comp >= 4:
|
| 682 |
axes[0,1].scatter(pcs[:,2], pcs[:,3], c=y, cmap='plasma', s=60, edgecolors='none')
|
| 683 |
+
axes[0,1].set_xlabel(f"PC3 ({var_exp[2]:.1f}%)", color=TEXT_DIM)
|
| 684 |
+
axes[0,1].set_ylabel(f"PC4 ({var_exp[3]:.1f}%)", color=TEXT_DIM)
|
| 685 |
+
axes[0,1].set_title("PCA: PC3 vs PC4", color=TEXT_MAIN)
|
| 686 |
+
else:
|
| 687 |
+
axes[0,1].text(0.5, 0.5, "< 4 PCs available", ha='center', transform=axes[0,1].transAxes, color=TEXT_DIM)
|
| 688 |
+
|
| 689 |
+
axes[1,0].set_facecolor(PANEL_WHITE)
|
| 690 |
+
axes[1,0].bar(range(1, n_comp+1), var_exp, color=ACCENT_BLUE, edgecolor='none', alpha=0.8)
|
| 691 |
axes[1,0].plot(range(1, n_comp+1), np.cumsum(var_exp), color=ACCENT_CORAL, marker='o', lw=2)
|
| 692 |
+
axes[1,0].set_xlabel("Principal Component", color=TEXT_DIM)
|
| 693 |
+
axes[1,0].set_ylabel("Variance Explained (%)", color=TEXT_DIM)
|
| 694 |
+
axes[1,0].set_title("Scree Plot", color=TEXT_MAIN)
|
| 695 |
+
|
| 696 |
+
axes[1,1].set_facecolor(PANEL_WHITE)
|
| 697 |
axes[1,1].scatter(pcs[:,0], pcs[:,1], c=y, cmap='plasma', s=60, edgecolors='none')
|
| 698 |
+
axes[1,1].set_title("Population Structure (PC1 vs PC2)", color=TEXT_MAIN)
|
| 699 |
fig.tight_layout()
|
| 700 |
return fig
|
| 701 |
|
| 702 |
def plot_model_comparison_manhattan(all_results, chroms, positions):
|
| 703 |
n_models = len(all_results)
|
| 704 |
+
fig, axes = plt.subplots(n_models, 1, figsize=(16, 3.5 * n_models), sharex=True, facecolor=BG_WHITE)
|
| 705 |
style_fig(fig)
|
| 706 |
if n_models == 1:
|
| 707 |
axes = [axes]
|
|
|
|
| 726 |
tick_lab.append(f"Chr{ch}")
|
| 727 |
for midx, (mname, (pvals, _, _)) in enumerate(all_results.items()):
|
| 728 |
ax = axes[midx]
|
| 729 |
+
ax.set_facecolor(PANEL_WHITE)
|
| 730 |
log_p = -np.log10(np.clip(pvals, 1e-300, 1))
|
| 731 |
col = MODEL_COLORS.get(mname, CHR_PALETTE[midx % len(CHR_PALETTE)])
|
| 732 |
for ch in chrom_list:
|
| 733 |
mask = chroms == ch
|
| 734 |
+
ax.scatter(x_coords[mask], log_p[mask], c=col, s=8, alpha=0.7, linewidths=0)
|
| 735 |
sig_m = log_p >= -np.log10(5e-8)
|
| 736 |
if sig_m.any():
|
| 737 |
+
ax.scatter(x_coords[sig_m], log_p[sig_m], c=SIG_COLOR, s=50, zorder=10,
|
| 738 |
+
marker='D', linewidths=0.6, edgecolors='#7F1D1D')
|
| 739 |
ax.axhline(-np.log10(5e-8), color=ACCENT_CORAL, ls='--', lw=1, alpha=0.7)
|
| 740 |
ax.set_ylabel("-log₁₀(p)", fontsize=7, color=TEXT_DIM)
|
| 741 |
ax.set_title(f"Model: {mname}", color=col, fontsize=9, pad=3)
|
|
|
|
| 744 |
ax.tick_params(colors=TEXT_DIM, labelsize=7)
|
| 745 |
for spine in ax.spines.values():
|
| 746 |
spine.set_edgecolor(GRID_LINE)
|
| 747 |
+
ax.grid(color=GRID_LINE, linewidth=0.3, linestyle="--", alpha=0.5)
|
| 748 |
fig.suptitle("Manhattan Plots — All Models Comparison", color=TEXT_MAIN, fontsize=13)
|
| 749 |
fig.tight_layout(rect=[0, 0, 1, 0.98])
|
| 750 |
return fig
|
| 751 |
|
| 752 |
def plot_kinship(K, ids):
|
| 753 |
+
fig, axes = plt.subplots(2, 2, figsize=(14, 12), facecolor=BG_WHITE)
|
| 754 |
style_fig(fig)
|
| 755 |
+
for ax in axes.flatten():
|
| 756 |
+
ax.set_facecolor(PANEL_WHITE)
|
| 757 |
+
|
| 758 |
im = axes[0,0].imshow(K, cmap='RdYlBu_r', aspect='auto', vmin=-0.5, vmax=1)
|
| 759 |
+
axes[0,0].set_title("Kinship Matrix", color=TEXT_MAIN)
|
| 760 |
+
plt.colorbar(im, ax=axes[0,0])
|
| 761 |
+
|
| 762 |
K_flat = K[np.triu_indices_from(K, k=1)]
|
| 763 |
+
axes[0,1].hist(K_flat, bins=30, color=ACCENT_PURP, edgecolor='none', alpha=0.8)
|
| 764 |
+
axes[0,1].set_title("Pairwise Kinship Distribution", color=TEXT_MAIN)
|
| 765 |
+
|
| 766 |
try:
|
| 767 |
lm = linkage(K, method='average')
|
| 768 |
dendrogram(lm, ax=axes[1,0], labels=ids, leaf_rotation=90, leaf_font_size=7,
|
| 769 |
color_threshold=0.7, above_threshold_color=ACCENT_TEAL)
|
| 770 |
+
except Exception:
|
| 771 |
+
axes[1,0].text(0.5, 0.5, "Dendrogram unavailable", ha='center',
|
| 772 |
+
transform=axes[1,0].transAxes, color=TEXT_DIM)
|
| 773 |
+
axes[1,0].set_title("Clustering Dendrogram", color=TEXT_MAIN)
|
| 774 |
+
|
| 775 |
eigvals, eigvecs = np.linalg.eigh(K)
|
| 776 |
idx = np.argsort(eigvals)[::-1]
|
| 777 |
axes[1,1].scatter(eigvecs[:,idx[0]], eigvecs[:,idx[1]], c=ACCENT_TEAL, s=60, edgecolors='none')
|
| 778 |
+
axes[1,1].set_title("Kinship PCA", color=TEXT_MAIN)
|
| 779 |
fig.tight_layout()
|
| 780 |
return fig
|
| 781 |
|
| 782 |
def plot_effect_sizes(pvals, betas, snp_names):
|
| 783 |
+
fig, axes = plt.subplots(2, 2, figsize=(14, 10), facecolor=BG_WHITE)
|
| 784 |
style_fig(fig)
|
| 785 |
+
for ax in axes.flatten():
|
| 786 |
+
ax.set_facecolor(PANEL_WHITE)
|
| 787 |
+
|
| 788 |
top_idx = np.argsort(np.abs(betas))[-20:]
|
| 789 |
top_betas = betas[top_idx]
|
| 790 |
top_names = [snp_names[i][:15] for i in top_idx]
|
| 791 |
colors = [ACCENT_CORAL if b < 0 else ACCENT_TEAL for b in top_betas]
|
| 792 |
+
axes[0,0].barh(range(len(top_betas)), top_betas, color=colors, alpha=0.85)
|
| 793 |
+
axes[0,0].axvline(0, color=TEXT_DIM, lw=0.8)
|
| 794 |
axes[0,0].set_yticks(range(len(top_betas)))
|
| 795 |
+
axes[0,0].set_yticklabels(top_names, fontsize=7, color=TEXT_DIM)
|
| 796 |
+
axes[0,0].set_xlabel("Effect Size (β)", color=TEXT_DIM)
|
| 797 |
+
axes[0,0].set_title("Top 20 Effect Sizes", color=TEXT_MAIN)
|
| 798 |
+
|
| 799 |
log_p = -np.log10(np.clip(pvals, 1e-300, 1))
|
| 800 |
sig_thr = -np.log10(0.05/len(pvals))
|
| 801 |
colors_v = np.where(log_p >= sig_thr, SIG_COLOR, np.where(betas > 0, ACCENT_TEAL, ACCENT_PURP))
|
| 802 |
axes[0,1].scatter(betas, log_p, c=colors_v, s=25, alpha=0.7, linewidths=0)
|
| 803 |
axes[0,1].axhline(sig_thr, color=ACCENT_CORAL, ls='--', lw=1.5, label="Bonferroni")
|
| 804 |
axes[0,1].axvline(0, color=TEXT_DIM, lw=0.5)
|
| 805 |
+
axes[0,1].set_xlabel("β", color=TEXT_DIM)
|
| 806 |
+
axes[0,1].set_ylabel("-log₁₀(p)", color=TEXT_DIM)
|
| 807 |
+
axes[0,1].set_title("Volcano Plot", color=TEXT_MAIN)
|
| 808 |
+
axes[0,1].legend(fontsize=7, facecolor=BG_WHITE)
|
| 809 |
+
|
| 810 |
+
axes[1,0].hist(betas, bins=30, color=ACCENT_BLUE, edgecolor='none', alpha=0.8)
|
| 811 |
axes[1,0].axvline(0, color=ACCENT_CORAL, lw=2, ls='--')
|
| 812 |
+
axes[1,0].set_xlabel("β", color=TEXT_DIM)
|
| 813 |
+
axes[1,0].set_title("Effect Size Distribution", color=TEXT_MAIN)
|
| 814 |
+
|
| 815 |
axes[1,1].scatter(betas, log_p, c=colors_v, s=20, alpha=0.6, linewidths=0)
|
| 816 |
+
axes[1,1].set_xlabel("β", color=TEXT_DIM)
|
| 817 |
+
axes[1,1].set_ylabel("-log₁₀(p)", color=TEXT_DIM)
|
| 818 |
+
axes[1,1].set_title("Effect Size vs Significance", color=TEXT_MAIN)
|
| 819 |
fig.tight_layout()
|
| 820 |
return fig
|
| 821 |
|
| 822 |
def plot_summary_dashboard(y, maf, all_results, G_filt):
|
| 823 |
+
fig, axes = plt.subplots(2, 3, figsize=(15, 10), facecolor=BG_WHITE)
|
| 824 |
style_fig(fig)
|
| 825 |
axes = axes.flatten()
|
| 826 |
+
for ax in axes:
|
| 827 |
+
ax.set_facecolor(PANEL_WHITE)
|
| 828 |
+
|
| 829 |
axes[0].hist(y, bins=15, color=ACCENT_PURP, edgecolor='none', alpha=0.8)
|
| 830 |
axes[0].axvline(y.mean(), color=ACCENT_CORAL, lw=2, ls='--', label=f"Mean: {y.mean():.2f}")
|
| 831 |
+
axes[0].set_title(f"Phenotype | n={len(y)}", color=TEXT_MAIN)
|
| 832 |
+
axes[0].legend(fontsize=7, facecolor=BG_WHITE)
|
| 833 |
+
|
| 834 |
+
axes[1].hist(maf, bins=20, color=ACCENT_TEAL, edgecolor='none', alpha=0.8)
|
| 835 |
axes[1].axvline(0.05, color=ACCENT_CORAL, ls='--')
|
| 836 |
+
axes[1].set_title(f"MAF | rare={np.sum(maf<0.05)}", color=TEXT_MAIN)
|
| 837 |
+
|
| 838 |
lambdas = {}
|
| 839 |
for mname, (p, _, _) in all_results.items():
|
| 840 |
lam = np.median(stats.chi2.ppf(1-np.clip(p,1e-10,1), df=1)) / stats.chi2.ppf(0.5, df=1)
|
| 841 |
lambdas[mname] = lam
|
| 842 |
colors_lam = [ACCENT_TEAL if v <= 1.1 else ACCENT_GOLD if v <= 1.3 else ACCENT_CORAL
|
| 843 |
for v in lambdas.values()]
|
| 844 |
+
axes[2].bar(lambdas.keys(), lambdas.values(), color=colors_lam, edgecolor='none', alpha=0.85)
|
| 845 |
axes[2].axhline(1.0, color=TEXT_DIM, ls='--', lw=1)
|
| 846 |
+
axes[2].set_title("Genomic Inflation λ per Model", color=TEXT_MAIN)
|
| 847 |
axes[2].tick_params(axis='x', rotation=35, labelsize=7)
|
| 848 |
+
|
| 849 |
sig_counts = {}
|
| 850 |
for mname, (p, _, _) in all_results.items():
|
| 851 |
bonf = 0.05 / len(p)
|
| 852 |
sig_counts[mname] = int((p < bonf).sum())
|
| 853 |
cols_bar = [MODEL_COLORS.get(m, ACCENT_BLUE) for m in sig_counts.keys()]
|
| 854 |
+
axes[3].bar(sig_counts.keys(), sig_counts.values(), color=cols_bar, edgecolor='none', alpha=0.85)
|
| 855 |
+
axes[3].set_title("Significant SNPs per Model (Bonferroni)", color=TEXT_MAIN)
|
| 856 |
axes[3].tick_params(axis='x', rotation=35, labelsize=7)
|
| 857 |
+
|
| 858 |
n_m = len(all_results)
|
| 859 |
model_names = list(all_results.keys())
|
| 860 |
concordance = np.eye(n_m)
|
|
|
|
| 866 |
concordance[i,j] = concordance[j,i] = r
|
| 867 |
im = axes[4].imshow(concordance, cmap='RdYlGn', vmin=-1, vmax=1, aspect='auto')
|
| 868 |
axes[4].set_xticks(range(n_m)); axes[4].set_yticks(range(n_m))
|
| 869 |
+
axes[4].set_xticklabels(model_names, rotation=35, fontsize=6, color=TEXT_DIM)
|
| 870 |
+
axes[4].set_yticklabels(model_names, fontsize=6, color=TEXT_DIM)
|
| 871 |
for i in range(n_m):
|
| 872 |
for j in range(n_m):
|
| 873 |
axes[4].text(j, i, f"{concordance[i,j]:.2f}", ha='center', va='center',
|
| 874 |
fontsize=5, color='black' if abs(concordance[i,j]) < 0.7 else 'white')
|
| 875 |
plt.colorbar(im, ax=axes[4], label="Spearman ρ")
|
| 876 |
+
axes[4].set_title("Model Concordance", color=TEXT_MAIN)
|
| 877 |
+
|
| 878 |
miss_r = np.isnan(G_filt).mean()
|
| 879 |
first_model = model_names[0]
|
| 880 |
axes[5].text(0.5, 0.5,
|
|
|
|
| 882 |
f"Models: {n_m}\nMissing: {miss_r:.1%}\n"
|
| 883 |
f"λ ({first_model}): {lambdas[first_model]:.3f}\n"
|
| 884 |
f"Sig. ({first_model}): {sig_counts[first_model]}",
|
| 885 |
+
ha='center', va='center', transform=axes[5].transAxes, color=TEXT_MAIN, fontsize=11,
|
| 886 |
+
bbox=dict(boxstyle='round,pad=0.6', facecolor=PANEL_LIGHT, edgecolor=GRID_LINE, alpha=0.8))
|
| 887 |
+
axes[5].set_title("Pipeline Summary", color=TEXT_MAIN)
|
| 888 |
+
fig.tight_layout()
|
| 889 |
+
return fig
|
| 890 |
+
|
| 891 |
+
# ─────────────────────── PER-MODEL PLOTS ─────────────────────────────────────────
|
| 892 |
+
def plot_all_models_manhattan_grid(all_results, chroms, positions):
|
| 893 |
+
"""Grid of Manhattan plots, one per selected model."""
|
| 894 |
+
n_models = len(all_results)
|
| 895 |
+
ncols = min(2, n_models)
|
| 896 |
+
nrows = (n_models + ncols - 1) // ncols
|
| 897 |
+
fig, axes = plt.subplots(nrows, ncols, figsize=(16, 4 * nrows), facecolor=BG_WHITE)
|
| 898 |
+
style_fig(fig)
|
| 899 |
+
if n_models == 1:
|
| 900 |
+
axes = np.array([axes])
|
| 901 |
+
axes_flat = np.array(axes).flatten()
|
| 902 |
+
|
| 903 |
+
chrom_list = sorted(set(chroms))
|
| 904 |
+
chrom_offsets = {}
|
| 905 |
+
total_len = 0
|
| 906 |
+
for ch in chrom_list:
|
| 907 |
+
chrom_offsets[ch] = total_len
|
| 908 |
+
mask = chroms == ch
|
| 909 |
+
if mask.sum() > 0:
|
| 910 |
+
total_len += positions[mask].max() - positions[mask].min() + max(positions) * 0.02 + 1
|
| 911 |
+
x_coords = np.zeros(len(chroms))
|
| 912 |
+
for ch in chrom_list:
|
| 913 |
+
mask = chroms == ch
|
| 914 |
+
if mask.sum() > 0:
|
| 915 |
+
x_coords[mask] = positions[mask] - positions[mask].min() + chrom_offsets[ch]
|
| 916 |
+
tick_pos = [x_coords[chroms == ch].mean() for ch in chrom_list if (chroms == ch).sum() > 0]
|
| 917 |
+
tick_lab = [f"Chr{ch}" for ch in chrom_list if (chroms == ch).sum() > 0]
|
| 918 |
+
|
| 919 |
+
for midx, (mname, (pvals, _, _)) in enumerate(all_results.items()):
|
| 920 |
+
ax = axes_flat[midx]
|
| 921 |
+
ax.set_facecolor(PANEL_WHITE)
|
| 922 |
+
log_p = -np.log10(np.clip(pvals, 1e-300, 1))
|
| 923 |
+
col = MODEL_COLORS.get(mname, CHR_PALETTE[midx % len(CHR_PALETTE)])
|
| 924 |
+
for ch in chrom_list:
|
| 925 |
+
mask = chroms == ch
|
| 926 |
+
ax.scatter(x_coords[mask], log_p[mask], c=col, s=10, alpha=0.75, linewidths=0)
|
| 927 |
+
sig_m = log_p >= -np.log10(5e-8)
|
| 928 |
+
if sig_m.any():
|
| 929 |
+
ax.scatter(x_coords[sig_m], log_p[sig_m], c=SIG_COLOR, s=60, zorder=10,
|
| 930 |
+
marker='D', linewidths=0.8, edgecolors='#7F1D1D')
|
| 931 |
+
ax.axhline(-np.log10(5e-8), color=ACCENT_CORAL, ls='--', lw=1.2, alpha=0.8, label="GW sig.")
|
| 932 |
+
ax.axhline(-np.log10(1e-5), color=ACCENT_TEAL, ls=':', lw=1, alpha=0.7, label="Suggestive")
|
| 933 |
+
ax.set_ylabel("-log₁₀(p)", fontsize=8, color=TEXT_DIM)
|
| 934 |
+
ax.set_title(f"Manhattan — {mname}", color=col, fontsize=10, fontweight='bold', pad=4)
|
| 935 |
+
ax.set_xticks(tick_pos)
|
| 936 |
+
ax.set_xticklabels(tick_lab, rotation=40, fontsize=7, color=TEXT_DIM)
|
| 937 |
+
ax.tick_params(colors=TEXT_DIM, labelsize=7)
|
| 938 |
+
for spine in ax.spines.values():
|
| 939 |
+
spine.set_edgecolor(GRID_LINE)
|
| 940 |
+
ax.grid(color=GRID_LINE, linewidth=0.4, linestyle="--", alpha=0.5)
|
| 941 |
+
lam = np.median(stats.chi2.ppf(1 - np.clip(pvals, 1e-10, 1), df=1)) / stats.chi2.ppf(0.5, df=1)
|
| 942 |
+
ax.text(0.99, 0.96, f"λ={lam:.3f}", transform=ax.transAxes, fontsize=8,
|
| 943 |
+
color=ACCENT_GOLD, fontweight='bold', ha='right', va='top')
|
| 944 |
+
ax.legend(fontsize=6, facecolor=BG_WHITE, edgecolor=GRID_LINE, loc='upper right')
|
| 945 |
+
|
| 946 |
+
for idx in range(n_models, len(axes_flat)):
|
| 947 |
+
axes_flat[idx].set_visible(False)
|
| 948 |
+
|
| 949 |
+
fig.suptitle("Manhattan Plots — All Selected Models", color=TEXT_MAIN, fontsize=13, y=1.01)
|
| 950 |
fig.tight_layout()
|
| 951 |
return fig
|
| 952 |
|
| 953 |
# ─────────────────────── EXCEL RESULTS EXPORT ────────────────────────────────────
|
| 954 |
def export_results_excel(all_results, snp_filt, chr_filt, pos_filt, y, G_filt, maf_vals, output_path):
|
| 955 |
wb = Workbook()
|
|
|
|
|
|
|
| 956 |
header_fill = PatternFill("solid", start_color="4A90D9", end_color="4A90D9")
|
| 957 |
sig_fill = PatternFill("solid", start_color="FFF3CD", end_color="FFF3CD")
|
| 958 |
alt_fill = PatternFill("solid", start_color="F8F9FA", end_color="F8F9FA")
|
| 959 |
header_font = Font(bold=True, color="FFFFFF", name="Calibri", size=11)
|
| 960 |
title_font = Font(bold=True, color="2C5F8A", name="Calibri", size=13)
|
| 961 |
thin_border = Border(
|
| 962 |
+
left=Side(style='thin', color='CCCCCC'), right=Side(style='thin', color='CCCCCC'),
|
| 963 |
+
top=Side(style='thin', color='CCCCCC'), bottom=Side(style='thin', color='CCCCCC')
|
|
|
|
|
|
|
| 964 |
)
|
|
|
|
| 965 |
bonf = 0.05 / len(list(all_results.values())[0][0])
|
| 966 |
|
| 967 |
+
# Sheet 1: Summary
|
| 968 |
ws_sum = wb.active
|
| 969 |
ws_sum.title = "Summary"
|
| 970 |
ws_sum['A1'] = "GWAS Complete Analysis Summary"
|
| 971 |
ws_sum['A1'].font = Font(bold=True, color="2C5F8A", name="Calibri", size=16)
|
| 972 |
ws_sum.merge_cells('A1:H1')
|
|
|
|
| 973 |
headers_sum = ["Model", "N_SNPs_Tested", "Bonferroni_Threshold", "Sig_SNPs_Bonferroni",
|
| 974 |
"Sig_SNPs_5e8", "Genomic_Lambda", "Min_Pvalue", "Max_AbsBeta"]
|
| 975 |
for col, h in enumerate(headers_sum, 1):
|
| 976 |
cell = ws_sum.cell(row=3, column=col, value=h)
|
| 977 |
cell.font = header_font; cell.fill = header_fill
|
| 978 |
+
cell.alignment = Alignment(horizontal='center'); cell.border = thin_border
|
|
|
|
| 979 |
ws_sum.column_dimensions[get_column_letter(col)].width = 22
|
|
|
|
| 980 |
for row_i, (mname, (pvals, betas, ses)) in enumerate(all_results.items(), 4):
|
| 981 |
lam = np.median(stats.chi2.ppf(1-np.clip(pvals,1e-10,1), df=1)) / stats.chi2.ppf(0.5, df=1)
|
| 982 |
+
row_data = [mname, len(pvals), f"{bonf:.2e}", int((pvals < bonf).sum()),
|
| 983 |
+
int((pvals < 5e-8).sum()), round(float(lam), 4),
|
| 984 |
+
float(np.min(pvals)), round(float(np.max(np.abs(betas))), 5)]
|
|
|
|
| 985 |
fill = alt_fill if row_i % 2 == 0 else PatternFill("solid", start_color="FFFFFF", end_color="FFFFFF")
|
| 986 |
for col, val in enumerate(row_data, 1):
|
| 987 |
cell = ws_sum.cell(row=row_i, column=col, value=val)
|
| 988 |
+
cell.fill = fill; cell.border = thin_border; cell.alignment = Alignment(horizontal='center')
|
|
|
|
| 989 |
|
| 990 |
+
# Per-model sheets
|
| 991 |
for mname, (pvals, betas, ses) in all_results.items():
|
| 992 |
ws = wb.create_sheet(title=f"{mname}_AllSNPs")
|
| 993 |
+
ws['A1'] = f"GWAS Results — {mname} — All SNPs"
|
| 994 |
ws['A1'].font = title_font
|
| 995 |
ws.merge_cells('A1:K1')
|
|
|
|
| 996 |
log_p = -np.log10(np.clip(pvals, 1e-300, 1))
|
| 997 |
t_stats = np.where(ses > 0, betas / (ses + 1e-10), 0.0)
|
| 998 |
reject_fdr, pvals_fdr, _, _ = multipletests(pvals, method='fdr_bh')
|
| 999 |
reject_bonf, _, _, _ = multipletests(pvals, method='bonferroni')
|
|
|
|
| 1000 |
headers = ["SNP", "Chr", "Position", "MAF", "Beta", "SE", "T_statistic",
|
| 1001 |
"P_value", "neg_log10P", "FDR_BH", "Bonferroni_sig"]
|
| 1002 |
for col, h in enumerate(headers, 1):
|
| 1003 |
cell = ws.cell(row=3, column=col, value=h)
|
| 1004 |
cell.font = header_font; cell.fill = header_fill
|
| 1005 |
+
cell.alignment = Alignment(horizontal='center'); cell.border = thin_border
|
| 1006 |
+
for i, w in enumerate([25,8,12,10,12,12,12,14,12,14,16], 1):
|
|
|
|
|
|
|
|
|
|
| 1007 |
ws.column_dimensions[get_column_letter(i)].width = w
|
| 1008 |
+
for row_i, idx in enumerate(np.argsort(pvals), 4):
|
|
|
|
|
|
|
| 1009 |
is_sig = bool(reject_bonf[idx]) or pvals[idx] < 5e-8
|
| 1010 |
fill = sig_fill if is_sig else (alt_fill if row_i % 2 == 0 else
|
| 1011 |
PatternFill("solid", start_color="FFFFFF", end_color="FFFFFF"))
|
|
|
|
| 1015 |
int(chr_filt[idx]) if idx < len(chr_filt) else "",
|
| 1016 |
int(pos_filt[idx]) if idx < len(pos_filt) else "",
|
| 1017 |
round(float(maf_v), 4) if not np.isnan(maf_v) else "",
|
| 1018 |
+
round(float(betas[idx]), 6), round(float(ses[idx]), 6),
|
| 1019 |
+
round(float(t_stats[idx]), 4), float(pvals[idx]),
|
| 1020 |
+
round(float(log_p[idx]), 4), round(float(pvals_fdr[idx]), 6),
|
|
|
|
|
|
|
|
|
|
| 1021 |
"YES" if is_sig else "NO"
|
| 1022 |
]
|
| 1023 |
for col, val in enumerate(row_data, 1):
|
| 1024 |
cell = ws.cell(row=row_i, column=col, value=val)
|
| 1025 |
+
cell.fill = fill; cell.border = thin_border; cell.alignment = Alignment(horizontal='center')
|
| 1026 |
+
if col == 8 and isinstance(val, float): cell.number_format = '0.00E+00'
|
|
|
|
|
|
|
| 1027 |
|
| 1028 |
+
# Significant MTAs sheet
|
| 1029 |
ws_mta = wb.create_sheet(title="Significant_MTAs")
|
| 1030 |
+
ws_mta['A1'] = "Significant MTAs — All Models Combined"
|
| 1031 |
ws_mta['A1'].font = title_font
|
| 1032 |
ws_mta.merge_cells('A1:N1')
|
| 1033 |
+
headers_mta = ["Model","SNP","Chr","Position","MAF","Beta","SE","T_stat",
|
| 1034 |
+
"P_value","neg_log10P","FDR_BH_p","Bonferroni_sig","GW_sig_5e8","PVE_%"]
|
|
|
|
|
|
|
| 1035 |
for col, h in enumerate(headers_mta, 1):
|
| 1036 |
cell = ws_mta.cell(row=3, column=col, value=h)
|
| 1037 |
cell.font = header_font; cell.fill = header_fill
|
| 1038 |
cell.alignment = Alignment(horizontal='center'); cell.border = thin_border
|
| 1039 |
ws_mta.column_dimensions[get_column_letter(col)].width = 18
|
|
|
|
| 1040 |
mta_row = 4
|
| 1041 |
for mname, (pvals, betas, ses) in all_results.items():
|
| 1042 |
log_p = -np.log10(np.clip(pvals, 1e-300, 1))
|
|
|
|
| 1045 |
reject_bonf, _, _, _ = multipletests(pvals, method='bonferroni')
|
| 1046 |
sig_idx = np.where((pvals < bonf) | (pvals < 5e-8))[0]
|
| 1047 |
sig_idx = sig_idx[np.argsort(pvals[sig_idx])]
|
|
|
|
| 1048 |
pve_dict, _ = compute_pve(y, G_filt, pvals, betas)
|
| 1049 |
for idx in sig_idx:
|
| 1050 |
pve_val = round(pve_dict.get(int(idx), 0.0), 4)
|
| 1051 |
maf_v = maf_vals[idx] if idx < len(maf_vals) else np.nan
|
| 1052 |
row_data = [
|
| 1053 |
+
mname, str(snp_filt[idx]) if idx < len(snp_filt) else "",
|
|
|
|
| 1054 |
int(chr_filt[idx]) if idx < len(chr_filt) else "",
|
| 1055 |
int(pos_filt[idx]) if idx < len(pos_filt) else "",
|
| 1056 |
round(float(maf_v), 4) if not np.isnan(maf_v) else "",
|
| 1057 |
+
round(float(betas[idx]), 6), round(float(ses[idx]), 6),
|
| 1058 |
+
round(float(t_stats[idx]), 4), float(pvals[idx]),
|
| 1059 |
+
round(float(log_p[idx]), 4), round(float(pvals_fdr[idx]), 6),
|
|
|
|
|
|
|
|
|
|
| 1060 |
"YES" if bool(reject_bonf[idx]) else "NO",
|
| 1061 |
+
"YES" if pvals[idx] < 5e-8 else "NO", pve_val
|
|
|
|
| 1062 |
]
|
| 1063 |
fill = sig_fill if mta_row % 2 == 0 else PatternFill("solid", start_color="FFFDE7", end_color="FFFDE7")
|
| 1064 |
for col, val in enumerate(row_data, 1):
|
| 1065 |
cell = ws_mta.cell(row=mta_row, column=col, value=val)
|
| 1066 |
+
cell.fill = fill; cell.border = thin_border; cell.alignment = Alignment(horizontal='center')
|
| 1067 |
+
if col == 9 and isinstance(val, float): cell.number_format = '0.00E+00'
|
|
|
|
|
|
|
| 1068 |
mta_row += 1
|
| 1069 |
|
| 1070 |
+
# QTN Effects sheet
|
| 1071 |
ws_qtn = wb.create_sheet(title="QTN_Effects")
|
| 1072 |
+
ws_qtn['A1'] = "QTNs — Effect Analysis"
|
| 1073 |
ws_qtn['A1'].font = title_font
|
| 1074 |
ws_qtn.merge_cells('A1:L1')
|
| 1075 |
+
headers_qtn = ["Model","Rank","SNP","Chr","Position","MAF",
|
| 1076 |
+
"QTN_Effect_Beta","SE","95%_CI_Lower","95%_CI_Upper","P_value","PVE_%"]
|
|
|
|
|
|
|
| 1077 |
for col, h in enumerate(headers_qtn, 1):
|
| 1078 |
cell = ws_qtn.cell(row=3, column=col, value=h)
|
| 1079 |
cell.font = header_font; cell.fill = header_fill
|
| 1080 |
cell.alignment = Alignment(horizontal='center'); cell.border = thin_border
|
| 1081 |
ws_qtn.column_dimensions[get_column_letter(col)].width = 17
|
|
|
|
| 1082 |
qtn_row = 4
|
| 1083 |
for mname, (pvals, betas, ses) in all_results.items():
|
| 1084 |
+
top_idx = np.argsort(pvals)[:min(20, len(pvals))]
|
|
|
|
| 1085 |
pve_dict, _ = compute_pve(y, G_filt, pvals, betas)
|
| 1086 |
for rank, idx in enumerate(top_idx, 1):
|
| 1087 |
pve_val = round(pve_dict.get(int(idx), 0.0), 4)
|
| 1088 |
maf_v = maf_vals[idx] if idx < len(maf_vals) else np.nan
|
|
|
|
|
|
|
| 1089 |
fill = alt_fill if qtn_row % 2 == 0 else PatternFill("solid", start_color="FFFFFF", end_color="FFFFFF")
|
| 1090 |
row_data = [
|
| 1091 |
mname, rank,
|
|
|
|
| 1093 |
int(chr_filt[idx]) if idx < len(chr_filt) else "",
|
| 1094 |
int(pos_filt[idx]) if idx < len(pos_filt) else "",
|
| 1095 |
round(float(maf_v), 4) if not np.isnan(maf_v) else "",
|
| 1096 |
+
round(float(betas[idx]), 6), round(float(ses[idx]), 6),
|
| 1097 |
+
round(float(betas[idx]) - 1.96 * float(ses[idx]), 6),
|
| 1098 |
+
round(float(betas[idx]) + 1.96 * float(ses[idx]), 6),
|
| 1099 |
+
float(pvals[idx]), pve_val
|
|
|
|
|
|
|
| 1100 |
]
|
| 1101 |
for col, val in enumerate(row_data, 1):
|
| 1102 |
cell = ws_qtn.cell(row=qtn_row, column=col, value=val)
|
| 1103 |
+
cell.fill = fill; cell.border = thin_border; cell.alignment = Alignment(horizontal='center')
|
| 1104 |
+
if col == 11 and isinstance(val, float): cell.number_format = '0.00E+00'
|
|
|
|
|
|
|
| 1105 |
qtn_row += 1
|
| 1106 |
|
| 1107 |
+
# PVE Summary sheet
|
| 1108 |
ws_pve = wb.create_sheet(title="PVE_Summary")
|
| 1109 |
+
ws_pve['A1'] = "Phenotypic Variance Explained (PVE)"
|
| 1110 |
ws_pve['A1'].font = title_font
|
| 1111 |
ws_pve.merge_cells('A1:I1')
|
| 1112 |
+
headers_pve = ["Model","SNP","Chr","Position","Beta","P_value","PVE_%","Cumulative_PVE_%","Significance"]
|
|
|
|
|
|
|
| 1113 |
for col, h in enumerate(headers_pve, 1):
|
| 1114 |
cell = ws_pve.cell(row=3, column=col, value=h)
|
| 1115 |
cell.font = header_font; cell.fill = header_fill
|
| 1116 |
cell.alignment = Alignment(horizontal='center'); cell.border = thin_border
|
| 1117 |
ws_pve.column_dimensions[get_column_letter(col)].width = 20
|
|
|
|
| 1118 |
pve_row = 4
|
| 1119 |
for mname, (pvals, betas, ses) in all_results.items():
|
| 1120 |
pve_dict, _ = compute_pve(y, G_filt, pvals, betas)
|
|
|
|
| 1121 |
cumulative = 0.0
|
| 1122 |
+
for idx in sorted(pve_dict.keys(), key=lambda i: pve_dict[i], reverse=True):
|
| 1123 |
pve_val = pve_dict[idx]
|
| 1124 |
cumulative += pve_val
|
|
|
|
|
|
|
| 1125 |
fill = sig_fill if pve_row % 2 == 0 else PatternFill("solid", start_color="FFFFFF", end_color="FFFFFF")
|
| 1126 |
row_data = [
|
| 1127 |
+
mname, str(snp_filt[idx]) if idx < len(snp_filt) else "",
|
|
|
|
| 1128 |
int(chr_filt[idx]) if idx < len(chr_filt) else "",
|
| 1129 |
int(pos_filt[idx]) if idx < len(pos_filt) else "",
|
| 1130 |
+
round(float(betas[idx]), 6), float(pvals[idx]),
|
| 1131 |
+
round(pve_val, 4), round(cumulative, 4),
|
| 1132 |
+
"GW-significant" if pvals[idx] < 5e-8 else "Bonferroni-significant"
|
|
|
|
|
|
|
| 1133 |
]
|
| 1134 |
for col, val in enumerate(row_data, 1):
|
| 1135 |
cell = ws_pve.cell(row=pve_row, column=col, value=val)
|
| 1136 |
+
cell.fill = fill; cell.border = thin_border; cell.alignment = Alignment(horizontal='center')
|
| 1137 |
+
if col == 6 and isinstance(val, float): cell.number_format = '0.00E+00'
|
|
|
|
|
|
|
| 1138 |
pve_row += 1
|
| 1139 |
|
| 1140 |
+
# SNP QC sheet
|
| 1141 |
ws_qc = wb.create_sheet(title="SNP_QC")
|
| 1142 |
ws_qc['A1'] = "SNP Quality Control Statistics"
|
| 1143 |
ws_qc['A1'].font = title_font
|
| 1144 |
ws_qc.merge_cells('A1:F1')
|
| 1145 |
+
headers_qc = ["SNP","Chr","Position","MAF","Call_Rate","Category"]
|
| 1146 |
for col, h in enumerate(headers_qc, 1):
|
| 1147 |
cell = ws_qc.cell(row=3, column=col, value=h)
|
| 1148 |
cell.font = header_font; cell.fill = header_fill
|
|
|
|
| 1152 |
for row_i in range(len(snp_filt)):
|
| 1153 |
maf_v = maf_vals[row_i] if row_i < len(maf_vals) else np.nan
|
| 1154 |
cr_v = call_rates[row_i] if row_i < len(call_rates) else np.nan
|
|
|
|
| 1155 |
fill = alt_fill if row_i % 2 == 0 else PatternFill("solid", start_color="FFFFFF", end_color="FFFFFF")
|
| 1156 |
row_data = [
|
| 1157 |
str(snp_filt[row_i]),
|
|
|
|
| 1159 |
int(pos_filt[row_i]) if row_i < len(pos_filt) else "",
|
| 1160 |
round(float(maf_v), 4) if not np.isnan(maf_v) else "",
|
| 1161 |
round(float(cr_v), 4) if not np.isnan(cr_v) else "",
|
| 1162 |
+
"Rare (<0.05)" if not np.isnan(maf_v) and maf_v < 0.05 else "Common"
|
| 1163 |
]
|
| 1164 |
for col, val in enumerate(row_data, 1):
|
| 1165 |
cell = ws_qc.cell(row=row_i+4, column=col, value=val)
|
| 1166 |
+
cell.fill = fill; cell.border = thin_border; cell.alignment = Alignment(horizontal='center')
|
|
|
|
| 1167 |
|
| 1168 |
wb.save(output_path)
|
| 1169 |
return output_path
|
| 1170 |
|
| 1171 |
def save_all_plots_zip(plot_dict, out_dir):
|
|
|
|
| 1172 |
zip_path = os.path.join(out_dir, "gwas_plots.zip")
|
| 1173 |
with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf:
|
| 1174 |
for name, fig in plot_dict.items():
|
| 1175 |
if fig is not None:
|
| 1176 |
buf = io.BytesIO()
|
| 1177 |
fig.savefig(buf, format="png", dpi=150, bbox_inches="tight",
|
| 1178 |
+
facecolor=BG_WHITE)
|
| 1179 |
buf.seek(0)
|
| 1180 |
zf.writestr(f"{name}.png", buf.read())
|
| 1181 |
return zip_path
|
|
|
|
| 1185 |
try:
|
| 1186 |
df, snp_cols, chroms, positions = parse_data(file_obj, text_input)
|
| 1187 |
except Exception as e:
|
| 1188 |
+
return [None] * 14 + [f"❌ Data parsing error: {e}"]
|
| 1189 |
|
| 1190 |
y = df["Phenotype"].values.astype(float)
|
| 1191 |
ids = df["ID"].values
|
|
|
|
| 1207 |
|
| 1208 |
K = build_kinship(G_filt)
|
| 1209 |
|
| 1210 |
+
# ── FIX: Ensure selected_models is a valid non-empty list ─────────────────
|
| 1211 |
+
ALL_MODELS_LIST = ["OLS", "MLM", "GLM", "CMLM", "BLINK", "FarmCPU", "EMMAX", "PLINK", "GAPIT3", "GEMMA"]
|
| 1212 |
+
if not selected_models or len(selected_models) == 0:
|
| 1213 |
+
models_to_run = ALL_MODELS_LIST
|
| 1214 |
+
else:
|
| 1215 |
+
# Preserve user selection order, filter to valid names
|
| 1216 |
+
models_to_run = [m for m in selected_models if m in ALL_MODELS_LIST]
|
| 1217 |
+
if len(models_to_run) == 0:
|
| 1218 |
+
models_to_run = ALL_MODELS_LIST
|
| 1219 |
+
|
| 1220 |
model_funcs = {
|
| 1221 |
"OLS": lambda: ols_gwas(y, G_filt),
|
| 1222 |
"MLM": lambda: mlm_gwas(y, G_filt, K),
|
|
|
|
| 1230 |
"GEMMA": lambda: gemma_gwas(y, G_filt, K),
|
| 1231 |
}
|
| 1232 |
|
|
|
|
| 1233 |
all_results = {}
|
| 1234 |
primary_p = primary_b = primary_se = None
|
| 1235 |
+
errors = []
|
| 1236 |
|
| 1237 |
for mname in models_to_run:
|
| 1238 |
if mname in model_funcs:
|
|
|
|
| 1241 |
all_results[mname] = (p, b, se)
|
| 1242 |
if primary_p is None:
|
| 1243 |
primary_p, primary_b, primary_se = p, b, se
|
| 1244 |
+
primary_model = mname
|
| 1245 |
except Exception as ex:
|
| 1246 |
+
errors.append(f"{mname}: {ex}")
|
| 1247 |
+
print(f"[WARN] Model {mname} failed: {ex}")
|
| 1248 |
|
| 1249 |
if primary_p is None:
|
| 1250 |
+
return [None] * 14 + [f"❌ No models succeeded.\nErrors:\n" + "\n".join(errors)]
|
| 1251 |
|
| 1252 |
+
# ── Build all named plots ──────────────────────────────────────────────────
|
| 1253 |
plot_dict = {}
|
| 1254 |
+
plot_dict["01_Manhattan_Primary"] = plot_manhattan(primary_p, chr_filt, pos_filt, "Manhattan Plot", primary_model)
|
| 1255 |
+
plot_dict["02_QQ_Primary"] = plot_qq_single(primary_p, "QQ Plot", primary_model, MODEL_COLORS.get(primary_model, ACCENT_PURP))
|
| 1256 |
+
plot_dict["03_QQ_All_Models"] = plot_qq_all_models(all_results)
|
| 1257 |
+
plot_dict["04_QQ_Overlay"] = plot_qq_overlay(all_results)
|
| 1258 |
+
plot_dict["05_Circos"] = plot_circos(all_results, chr_filt, pos_filt)
|
| 1259 |
+
plot_dict["06_LD_Decay"] = plot_ld_decay(G_filt, pos_filt)
|
| 1260 |
+
plot_dict["07_PCA"] = plot_pca(G_filt, y, ids)
|
| 1261 |
+
plot_dict["08_Kinship"] = plot_kinship(K, ids)
|
| 1262 |
+
plot_dict["09_Effect_Sizes"] = plot_effect_sizes(primary_p, primary_b, snp_filt)
|
| 1263 |
+
plot_dict["10_All_Models_Manhattan"] = plot_model_comparison_manhattan(all_results, chr_filt, pos_filt)
|
| 1264 |
+
plot_dict["11_Summary_Dashboard"] = plot_summary_dashboard(y, maf_vals, all_results, G_filt)
|
| 1265 |
+
plot_dict["12_All_Models_MH_Grid"] = plot_all_models_manhattan_grid(all_results, chr_filt, pos_filt)
|
| 1266 |
+
|
| 1267 |
+
# Per-model individual Manhattan + QQ (saved to zip, not displayed inline)
|
|
|
|
| 1268 |
for mname, (p, b, se) in all_results.items():
|
| 1269 |
+
plot_dict[f"13_{mname}_Manhattan"] = plot_manhattan(p, chr_filt, pos_filt, "Manhattan", mname)
|
| 1270 |
+
plot_dict[f"14_{mname}_QQ"] = plot_qq_single(p, "QQ Plot", mname, MODEL_COLORS.get(mname, ACCENT_PURP))
|
| 1271 |
|
| 1272 |
# PIL images for display
|
| 1273 |
imgs = {}
|
| 1274 |
for k, fig in plot_dict.items():
|
| 1275 |
imgs[k] = fig_to_pil(fig) if fig is not None else None
|
| 1276 |
|
| 1277 |
+
# Save plots zip + Excel
|
| 1278 |
tmp_dir = tempfile.mkdtemp()
|
| 1279 |
zip_path = save_all_plots_zip(plot_dict, tmp_dir)
|
|
|
|
|
|
|
| 1280 |
excel_path = os.path.join(tmp_dir, "gwas_results_complete.xlsx")
|
| 1281 |
export_results_excel(all_results, snp_filt, chr_filt, pos_filt, y, G_filt, maf_vals, excel_path)
|
| 1282 |
|
| 1283 |
plt.close('all')
|
| 1284 |
|
| 1285 |
+
# Summary text
|
| 1286 |
bonf = 0.05 / len(primary_p)
|
| 1287 |
lambdas_str = "\n ".join([
|
| 1288 |
+
f"{mn}: λ={np.median(stats.chi2.ppf(1-np.clip(p,1e-10,1),df=1))/stats.chi2.ppf(0.5,df=1):.4f} "
|
| 1289 |
f"sig(Bonf)={int((p<bonf).sum())} sig(5e-8)={int((p<5e-8).sum())}"
|
| 1290 |
+
for mn, (p, _, _) in all_results.items()
|
| 1291 |
])
|
| 1292 |
lam = np.median(stats.chi2.ppf(1-np.clip(primary_p,1e-10,1), df=1)) / stats.chi2.ppf(0.5, df=1)
|
| 1293 |
+
error_section = ""
|
| 1294 |
+
if errors:
|
| 1295 |
+
error_section = f"\n ⚠️ Models with errors (skipped):\n " + "\n ".join(errors) + "\n"
|
| 1296 |
|
| 1297 |
summary = (
|
| 1298 |
f"{'='*68}\n"
|
|
|
|
| 1300 |
f"{'='*68}\n"
|
| 1301 |
f" Samples: {n} | SNPs (raw): {m} | SNPs (filtered): {G_filt.shape[1]}\n"
|
| 1302 |
f" MAF threshold: ≥{maf_thr:.2f}\n"
|
| 1303 |
+
f" Models selected: {', '.join(models_to_run)}\n"
|
| 1304 |
+
f" Models completed: {', '.join(all_results.keys())}\n"
|
| 1305 |
f"{'─'*68}\n"
|
| 1306 |
f" PER-MODEL RESULTS:\n {lambdas_str}\n"
|
| 1307 |
+
f"{error_section}"
|
| 1308 |
f"{'─'*68}\n"
|
| 1309 |
+
f" Primary model ({primary_model}):\n"
|
| 1310 |
f" Bonferroni threshold : {bonf:.2e}\n"
|
| 1311 |
f" Significant MTAs : {int((primary_p<bonf).sum())}\n"
|
| 1312 |
f" Genomic Inflation λ : {lam:.4f}\n"
|
| 1313 |
f"{'─'*68}\n"
|
| 1314 |
f" 📥 Excel: gwas_results_complete.xlsx\n"
|
| 1315 |
+
f" • Summary · Per-model SNPs · Sig. MTAs · QTN · PVE · SNP QC\n"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1316 |
f" 🖼 Plots: gwas_plots.zip ({len(plot_dict)} PNG files)\n"
|
| 1317 |
+
f" • Per-model Manhattan + QQ for ALL {len(all_results)} models\n"
|
| 1318 |
f"{'='*68}\n"
|
| 1319 |
)
|
| 1320 |
|
| 1321 |
+
return [
|
|
|
|
| 1322 |
imgs.get("01_Manhattan_Primary"),
|
| 1323 |
imgs.get("02_QQ_Primary"),
|
| 1324 |
imgs.get("03_QQ_All_Models"),
|
|
|
|
| 1330 |
imgs.get("09_Effect_Sizes"),
|
| 1331 |
imgs.get("10_All_Models_Manhattan"),
|
| 1332 |
imgs.get("11_Summary_Dashboard"),
|
| 1333 |
+
imgs.get("12_All_Models_MH_Grid"),
|
| 1334 |
+
excel_path,
|
| 1335 |
+
zip_path,
|
| 1336 |
+
summary,
|
| 1337 |
]
|
|
|
|
| 1338 |
|
| 1339 |
+
# ─────────────────────── CSS ──────────────────────────────────────────────────────
|
| 1340 |
PASTEL_CSS = """
|
| 1341 |
@import url('https://fonts.googleapis.com/css2?family=DM+Sans:wght@300;400;500;600&family=DM+Mono:wght@400;500&display=swap');
|
|
|
|
| 1342 |
* { box-sizing: border-box; }
|
|
|
|
| 1343 |
body, .gradio-container {
|
| 1344 |
background: #F7F8FC !important;
|
| 1345 |
font-family: 'DM Sans', sans-serif !important;
|
| 1346 |
color: #2D3142 !important;
|
| 1347 |
}
|
| 1348 |
+
.gradio-container { max-width: 1400px !important; margin: 0 auto !important; }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1349 |
.gwas-header {
|
| 1350 |
background: linear-gradient(135deg, #E8F4FD 0%, #EDE9F8 50%, #FDF0F8 100%);
|
| 1351 |
+
border: 1px solid #D6E8F5; border-radius: 18px; padding: 28px 36px;
|
| 1352 |
+
margin-bottom: 24px; box-shadow: 0 2px 20px rgba(100,120,200,0.08);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1353 |
}
|
| 1354 |
+
.gwas-header h1 { font-size: 26px !important; font-weight: 600 !important; color: #2C5F8A !important; margin: 0 0 6px 0 !important; }
|
| 1355 |
+
.gwas-header p { color: #6B7A99 !important; font-size: 14px !important; margin: 4px 0 !important; }
|
| 1356 |
.gr-panel, .gr-box, .block, .panel {
|
| 1357 |
+
background: #FFFFFF !important; border: 1px solid #E8ECF4 !important;
|
| 1358 |
+
border-radius: 14px !important; box-shadow: 0 1px 8px rgba(60,80,140,0.06) !important;
|
|
|
|
|
|
|
| 1359 |
}
|
|
|
|
|
|
|
| 1360 |
label, .label-wrap span {
|
| 1361 |
+
color: #5A6480 !important; font-size: 12px !important; font-weight: 500 !important;
|
| 1362 |
+
text-transform: uppercase !important; letter-spacing: 0.5px !important;
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1363 |
}
|
|
|
|
|
|
|
| 1364 |
input, textarea, select {
|
| 1365 |
+
background: #FAFBFF !important; color: #2D3142 !important;
|
| 1366 |
+
border: 1px solid #DDE2F0 !important; border-radius: 10px !important;
|
| 1367 |
+
font-family: 'DM Mono', monospace !important; font-size: 12px !important;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1368 |
}
|
| 1369 |
+
button.primary {
|
|
|
|
|
|
|
| 1370 |
background: linear-gradient(135deg, #5BA8E5 0%, #7C6FCD 100%) !important;
|
| 1371 |
+
border: none !important; border-radius: 12px !important; color: #FFFFFF !important;
|
| 1372 |
+
font-weight: 600 !important; font-size: 15px !important; padding: 14px 28px !important;
|
| 1373 |
+
box-shadow: 0 4px 16px rgba(91,168,229,0.35) !important; width: 100% !important;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1374 |
transition: all 0.2s ease !important;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1375 |
}
|
| 1376 |
+
button.primary:hover { transform: translateY(-2px) !important; box-shadow: 0 6px 24px rgba(91,168,229,0.45) !important; }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1377 |
.tab-nav {
|
| 1378 |
+
background: #F0F3FB !important; border-radius: 12px !important;
|
| 1379 |
+
padding: 4px !important; border: 1px solid #E4E8F5 !important; overflow-x: auto !important;
|
|
|
|
|
|
|
|
|
|
| 1380 |
}
|
|
|
|
| 1381 |
.tab-nav button {
|
| 1382 |
+
color: #6B7A99 !important; font-size: 12px !important; font-weight: 500 !important;
|
| 1383 |
+
border-radius: 9px !important; padding: 7px 14px !important; border: none !important;
|
| 1384 |
+
background: transparent !important; white-space: nowrap !important;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1385 |
}
|
|
|
|
| 1386 |
.tab-nav button.selected, .tab-nav button:hover {
|
| 1387 |
+
background: #FFFFFF !important; color: #5BA8E5 !important;
|
| 1388 |
+
box-shadow: 0 1px 6px rgba(91,168,229,0.2) !important;
|
|
|
|
| 1389 |
}
|
|
|
|
|
|
|
| 1390 |
.summary-box textarea {
|
| 1391 |
+
font-family: 'DM Mono', monospace !important; font-size: 12px !important;
|
| 1392 |
+
background: #F8F9FF !important; color: #2D3142 !important;
|
| 1393 |
+
border: 1px solid #DDE2F0 !important; line-height: 1.7 !important;
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1394 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1395 |
.download-section {
|
| 1396 |
background: linear-gradient(135deg, #EBF5FF 0%, #F0EBFF 100%);
|
| 1397 |
+
border: 1px solid #D0E4F5 !important; border-radius: 14px !important; padding: 18px !important;
|
|
|
|
|
|
|
| 1398 |
}
|
|
|
|
|
|
|
| 1399 |
.section-label {
|
| 1400 |
+
font-size: 11px !important; font-weight: 600 !important; color: #8892B0 !important;
|
| 1401 |
+
text-transform: uppercase !important; letter-spacing: 1px !important;
|
| 1402 |
+
padding: 8px 0 4px 0 !important; border-bottom: 1px solid #E8ECF4 !important;
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1403 |
margin-bottom: 8px !important;
|
| 1404 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1405 |
::-webkit-scrollbar { width: 6px; height: 6px; }
|
| 1406 |
::-webkit-scrollbar-track { background: #F0F3FB; border-radius: 4px; }
|
| 1407 |
::-webkit-scrollbar-thumb { background: #C8D0E7; border-radius: 4px; }
|
|
|
|
| 1408 |
"""
|
| 1409 |
|
| 1410 |
SAMPLE_DATA = """ID,Phenotype,chr1_134521_SNP1,chr1_134810_SNP2,chr1_178766_SNP3,chr1_210328_SNP4
|
|
|
|
| 1428 |
gr.HTML("""
|
| 1429 |
<div class="gwas-header">
|
| 1430 |
<h1>🧬 Complete GWAS Analysis Pipeline</h1>
|
| 1431 |
+
<p>10 Statistical Models · All-Model Manhattan & QQ · Circos · LD Decay · PNG Export · Full Excel</p>
|
| 1432 |
<p style="font-size:12px; color:#8892B0;">
|
| 1433 |
+
Per-model: MTA · PVE · QTN Effects · Beta · SE · T-stat · FDR · Bonferroni · 95% CI
|
| 1434 |
</p>
|
| 1435 |
</div>
|
| 1436 |
""")
|
| 1437 |
|
| 1438 |
with gr.Row(equal_height=False):
|
|
|
|
| 1439 |
with gr.Column(scale=1, min_width=320):
|
| 1440 |
gr.HTML('<div class="section-label">📂 Data Input</div>')
|
| 1441 |
file_in = gr.File(label="Upload CSV / TSV / TXT", file_types=[".csv", ".tsv", ".txt"])
|
|
|
|
| 1445 |
gr.HTML('<div class="section-label" style="margin-top:16px;">⚙️ Model Selection</div>')
|
| 1446 |
model_sel = gr.CheckboxGroup(
|
| 1447 |
choices=ALL_MODELS,
|
| 1448 |
+
value=ALL_MODELS, # ← default: all 10 selected
|
| 1449 |
label="Select models to run"
|
| 1450 |
)
|
| 1451 |
maf_thr = gr.Slider(0, 0.5, 0.05, 0.01, label="MAF Threshold")
|
| 1452 |
+
run_btn = gr.Button("🚀 Run Complete GWAS Pipeline", variant="primary")
|
|
|
|
|
|
|
| 1453 |
|
| 1454 |
gr.HTML('<div class="section-label" style="margin-top:16px;">📥 Downloads</div>')
|
| 1455 |
with gr.Column(elem_classes=["download-section"]):
|
| 1456 |
+
excel_out = gr.File(label="📊 Excel Results (MTA · PVE · QTN · All Models)", interactive=False)
|
| 1457 |
+
zip_out = gr.File(label="🖼 All Plots as PNG (ZIP)", interactive=False)
|
|
|
|
|
|
|
| 1458 |
|
|
|
|
| 1459 |
with gr.Column(scale=2):
|
| 1460 |
gr.HTML('<div class="section-label">📊 Analysis Summary</div>')
|
| 1461 |
+
summary_out = gr.Textbox(label="", lines=30, elem_classes=["summary-box"], show_label=False)
|
|
|
|
| 1462 |
|
|
|
|
| 1463 |
gr.HTML('<div class="section-label" style="margin: 16px 0 8px 0;">🖼 Visualizations</div>')
|
| 1464 |
with gr.Tabs():
|
| 1465 |
with gr.Tab("🗺 Manhattan (Primary)"):
|
| 1466 |
+
img1 = gr.Image(type="pil", label="Manhattan — Primary Model (◆ = Sig. MTA)")
|
| 1467 |
with gr.Tab("📈 QQ (Primary)"):
|
| 1468 |
img2 = gr.Image(type="pil", label="QQ Plot — Primary Model")
|
| 1469 |
with gr.Tab("📈 QQ (All Models)"):
|
|
|
|
| 1472 |
img4 = gr.Image(type="pil", label="QQ Overlay — All Models with λ")
|
| 1473 |
with gr.Tab("🔵 Circos"):
|
| 1474 |
img5 = gr.Image(type="pil", label="Circos — Multi-Model Comparison")
|
| 1475 |
+
with gr.Tab("🔗 LD Decay"):
|
| 1476 |
+
img6 = gr.Image(type="pil", label="Linkage Disequilibrium Decay (bp & Mb)")
|
| 1477 |
with gr.Tab("🔬 PCA"):
|
| 1478 |
img7 = gr.Image(type="pil", label="Principal Component Analysis")
|
| 1479 |
with gr.Tab("👨👩👧 Kinship"):
|
| 1480 |
img8 = gr.Image(type="pil", label="Kinship Matrix & Clustering")
|
| 1481 |
with gr.Tab("⚖ Effect Sizes"):
|
| 1482 |
img9 = gr.Image(type="pil", label="Effect Sizes & Volcano Plot")
|
| 1483 |
+
with gr.Tab("🔄 All Models (Stacked)"):
|
| 1484 |
+
img10 = gr.Image(type="pil", label="Manhattan — All Models Stacked")
|
| 1485 |
with gr.Tab("📊 Dashboard"):
|
| 1486 |
img11 = gr.Image(type="pil", label="Summary Dashboard — All Models")
|
| 1487 |
+
with gr.Tab("🗂 All Models (Grid)"):
|
| 1488 |
+
img12 = gr.Image(type="pil", label="Manhattan Grid — One Panel Per Model")
|
| 1489 |
|
| 1490 |
def run_wrapper(f, t, m, maf):
|
| 1491 |
out = run_gwas(f, t, m, maf)
|
| 1492 |
+
while len(out) < 15:
|
|
|
|
| 1493 |
out.append(None)
|
| 1494 |
return out
|
| 1495 |
|
| 1496 |
run_btn.click(
|
| 1497 |
run_wrapper,
|
| 1498 |
inputs=[file_in, text_in, model_sel, maf_thr],
|
| 1499 |
+
outputs=[img1, img2, img3, img4, img5, img6, img7, img8, img9, img10, img11, img12,
|
| 1500 |
excel_out, zip_out, summary_out]
|
| 1501 |
)
|
| 1502 |
|