Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -216,7 +216,6 @@ def compute_thresholds(n_snps, model_name=""):
|
|
| 216 |
bonferroni = 0.05 / n_snps
|
| 217 |
suggestive = 1.0 / n_snps # 1 expected false positive genome-wide
|
| 218 |
|
| 219 |
-
# Model-specific notes
|
| 220 |
model_notes = {
|
| 221 |
"OLS": "OLS uses no population structure correction; thresholds are standard.",
|
| 222 |
"MLM": "MLM corrects for kinship (relatedness); mixed model may slightly inflate Ξ».",
|
|
@@ -273,26 +272,51 @@ def mlm_gwas(y, G, K):
|
|
| 273 |
return pvals, betas, ses
|
| 274 |
|
| 275 |
def emmax_gwas(y, G, K):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 276 |
n, m = G.shape
|
| 277 |
-
pvals = np.ones(m)
|
| 278 |
-
|
|
|
|
|
|
|
|
|
|
| 279 |
sigma = np.var(y) * 0.5
|
| 280 |
-
V
|
| 281 |
try:
|
| 282 |
V_inv = np.linalg.inv(V + np.eye(n) * 1e-6)
|
| 283 |
-
except:
|
| 284 |
V_inv = np.eye(n)
|
|
|
|
| 285 |
for j in range(m):
|
| 286 |
-
x = G[:, j].reshape(-1, 1)
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 293 |
ses[j] = se
|
| 294 |
-
|
| 295 |
-
|
|
|
|
|
|
|
| 296 |
return pvals, betas, ses
|
| 297 |
|
| 298 |
def farmcpu_gwas(y, G, K):
|
|
@@ -334,31 +358,39 @@ def gemma_gwas(y, G, K):
|
|
| 334 |
return pvals, betas, ses
|
| 335 |
|
| 336 |
# βββββββββββββββββββββββ CONFIG BUILDER ββββββββββββββββββββββββββββββββββββββββββ
|
| 337 |
-
def build_cfg(w, h, fs, fc, gc, bg, panel
|
| 338 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 339 |
return {
|
| 340 |
-
"width":
|
| 341 |
-
"
|
| 342 |
-
"
|
| 343 |
-
"
|
| 344 |
-
"
|
| 345 |
-
"
|
| 346 |
-
"
|
| 347 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 348 |
}
|
| 349 |
|
| 350 |
# βββββββββββββββββββββββ MANHATTAN PLOT ββββββββββββββββββββββββββββββββββββββββββ
|
| 351 |
def plot_manhattan(pvals, chroms, positions, title="Manhattan Plot", model_name="",
|
| 352 |
cfg=None, top_n=15):
|
| 353 |
-
"""
|
| 354 |
-
Manhattan plot with:
|
| 355 |
-
- Chromosome numbers labeled on x-axis
|
| 356 |
-
- Both Bonferroni AND suggestive thresholds shown
|
| 357 |
-
- Top N MTAs highlighted
|
| 358 |
-
"""
|
| 359 |
if cfg is None:
|
| 360 |
-
cfg = build_cfg(16, 5, 9, "#2D3142"
|
| 361 |
-
"#E15759", "#4E79A7", 12, 0.75)
|
| 362 |
|
| 363 |
n_snps = len(pvals)
|
| 364 |
bonf_thresh = 0.05 / n_snps
|
|
@@ -387,21 +419,17 @@ def plot_manhattan(pvals, chroms, positions, title="Manhattan Plot", model_name=
|
|
| 387 |
x_vals = pos[order] - pos.min() + x_offset
|
| 388 |
x_coords[np.where(mask)[0][order]] = x_vals
|
| 389 |
tick_pos.append(x_vals.mean())
|
| 390 |
-
# Always show "Chr N" with the number
|
| 391 |
tick_lab.append(f"Chr{ch}")
|
| 392 |
ax.scatter(x_coords[mask], log_p[mask],
|
| 393 |
c=chrom_colors[ch], s=cfg["marker_size"],
|
| 394 |
alpha=cfg["alpha"], linewidths=0)
|
| 395 |
x_offset += (pos.max() - pos.min()) + gap
|
| 396 |
|
| 397 |
-
# Suggestive threshold (model-specific: 1/m)
|
| 398 |
ax.axhline(sug_line, color=cfg["sug_color"], ls=":", lw=1.5, alpha=0.9,
|
| 399 |
label=f"Suggestive (1/m = {sug_thresh:.1e}, -logββ={sug_line:.1f})")
|
| 400 |
-
# Bonferroni threshold (0.05/m)
|
| 401 |
ax.axhline(sig_line, color=cfg["sig_color"], ls="--", lw=2.0,
|
| 402 |
label=f"Bonferroni (0.05/m = {bonf_thresh:.1e}, -logββ={sig_line:.1f})")
|
| 403 |
|
| 404 |
-
# Mark top N MTAs
|
| 405 |
top_idx = get_top_mta(pvals, top_n)
|
| 406 |
sig_mask = np.zeros(len(pvals), dtype=bool)
|
| 407 |
sig_mask[top_idx] = True
|
|
@@ -433,23 +461,8 @@ def plot_manhattan(pvals, chroms, positions, title="Manhattan Plot", model_name=
|
|
| 433 |
|
| 434 |
# βββββββββββββββββββββββ QQ PLOT βββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 435 |
def plot_qq_single(pvals, title="QQ Plot", model_name="", color=None, cfg=None):
|
| 436 |
-
"""
|
| 437 |
-
QQ plot with:
|
| 438 |
-
- 95% CI shaded band
|
| 439 |
-
- LINEAR REGRESSION LINE through expected vs observed (as requested)
|
| 440 |
-
- Lambda inflation factor
|
| 441 |
-
- Both Bonferroni + suggestive threshold marked
|
| 442 |
-
"""
|
| 443 |
if cfg is None:
|
| 444 |
-
|
| 445 |
-
TEXT_MAIN,
|
| 446 |
-
GRID_LINE,
|
| 447 |
-
BG_DARK,
|
| 448 |
-
PANEL_DARK,
|
| 449 |
-
ACCENT_TEAL,
|
| 450 |
-
ACCENT_GOLD,
|
| 451 |
-
55,
|
| 452 |
-
0.80)
|
| 453 |
if color is None:
|
| 454 |
color = cfg.get("dot_color", "#A78BFA")
|
| 455 |
|
|
@@ -461,21 +474,16 @@ def plot_qq_single(pvals, title="QQ Plot", model_name="", color=None, cfg=None):
|
|
| 461 |
obs = np.sort(-np.log10(np.clip(pvals, 1e-300, 1)))[::-1]
|
| 462 |
exp = -np.log10(np.linspace(1/n, 1, n)[::-1])
|
| 463 |
|
| 464 |
-
# 95% CI band
|
| 465 |
ci_lower = -np.log10(stats.beta.ppf(0.975, np.arange(1, n+1), np.arange(n, 0, -1)))
|
| 466 |
ci_upper = -np.log10(stats.beta.ppf(0.025, np.arange(1, n+1), np.arange(n, 0, -1)))
|
| 467 |
ax.fill_between(exp, ci_lower, ci_upper, alpha=0.2, color=color, label="95% CI")
|
| 468 |
|
| 469 |
-
# Scatter points
|
| 470 |
ax.scatter(exp, obs, c=color, s=cfg["marker_size"], alpha=cfg["alpha"],
|
| 471 |
linewidths=0, zorder=5, label="Observed")
|
| 472 |
|
| 473 |
-
# ββ Identity line (y = x, i.e. expected) ββββββββββββββββββββββββββββββββββ
|
| 474 |
ax.plot([0, max(exp)], [0, max(exp)], color="#AAAAAA",
|
| 475 |
ls="-", lw=1.2, alpha=0.7, label="y = x (null)", zorder=4)
|
| 476 |
|
| 477 |
-
# ββ REGRESSION LINE through observed vs expected (key change) βββββββββββββ
|
| 478 |
-
# Fit linear regression of observed on expected
|
| 479 |
valid = np.isfinite(exp) & np.isfinite(obs)
|
| 480 |
if valid.sum() > 2:
|
| 481 |
slope_reg, intercept_reg, r_val, p_val, _ = stats.linregress(exp[valid], obs[valid])
|
|
@@ -484,7 +492,6 @@ def plot_qq_single(pvals, title="QQ Plot", model_name="", color=None, cfg=None):
|
|
| 484 |
ax.plot(x_reg, y_reg, color=cfg["line_color"], ls="-", lw=2.2, zorder=6,
|
| 485 |
label=f"Regression (slope={slope_reg:.3f}, RΒ²={r_val**2:.3f})")
|
| 486 |
|
| 487 |
-
# Lambda inflation factor
|
| 488 |
lam = np.median(stats.chi2.ppf(1 - np.clip(pvals, 1e-10, 1), df=1)) / stats.chi2.ppf(0.5, df=1)
|
| 489 |
ax.text(0.05, 0.93, f"Ξ» = {lam:.4f}", transform=ax.transAxes,
|
| 490 |
fontsize=cfg["font_size"]+2, color="#E15759", fontweight='bold')
|
|
@@ -507,8 +514,7 @@ def plot_qq_single(pvals, title="QQ Plot", model_name="", color=None, cfg=None):
|
|
| 507 |
def plot_qq_all_models(all_results, cfg=None):
|
| 508 |
"""QQ plots for all models with regression lines."""
|
| 509 |
if cfg is None:
|
| 510 |
-
cfg = build_cfg(7, 6, 9, "#2D3142"
|
| 511 |
-
"#E15759", "#4E79A7", 18, 0.8)
|
| 512 |
n_models = len(all_results)
|
| 513 |
ncols = min(3, n_models)
|
| 514 |
nrows = (n_models + ncols - 1) // ncols
|
|
@@ -534,11 +540,9 @@ def plot_qq_all_models(all_results, cfg=None):
|
|
| 534 |
ax.scatter(exp, obs, c=col, s=cfg["marker_size"], alpha=cfg["alpha"],
|
| 535 |
linewidths=0, zorder=5)
|
| 536 |
|
| 537 |
-
# Identity line
|
| 538 |
ax.plot([0, max(exp)], [0, max(exp)], color="#AAAAAA",
|
| 539 |
ls="-", lw=1.0, alpha=0.6, zorder=4)
|
| 540 |
|
| 541 |
-
# Regression line
|
| 542 |
valid = np.isfinite(exp) & np.isfinite(obs)
|
| 543 |
if valid.sum() > 2:
|
| 544 |
slope_reg, intercept_reg, r_val, _, _ = stats.linregress(exp[valid], obs[valid])
|
|
@@ -572,8 +576,7 @@ def plot_qq_all_models(all_results, cfg=None):
|
|
| 572 |
def plot_qq_overlay(all_results, cfg=None):
|
| 573 |
"""QQ overlay with regression lines per model."""
|
| 574 |
if cfg is None:
|
| 575 |
-
cfg = build_cfg(9, 9, 10, "#2D3142"
|
| 576 |
-
"#E15759", "#4E79A7", 18, 0.85)
|
| 577 |
fig, ax = plt.subplots(figsize=(cfg["width"], cfg["height"]))
|
| 578 |
fig.patch.set_facecolor(cfg["bg_color"])
|
| 579 |
ax.set_facecolor(cfg["panel_color"])
|
|
@@ -587,7 +590,6 @@ def plot_qq_overlay(all_results, cfg=None):
|
|
| 587 |
col = MODEL_COLORS.get(mname, "#7C6FCD")
|
| 588 |
ax.plot(exp, obs, color=col, lw=2, label=f"{mname} (Ξ»={lam:.3f})", alpha=0.85)
|
| 589 |
|
| 590 |
-
# Regression line per model (dashed)
|
| 591 |
valid = np.isfinite(exp) & np.isfinite(obs)
|
| 592 |
if valid.sum() > 2:
|
| 593 |
slope_r, intercept_r, _, _, _ = stats.linregress(exp[valid], obs[valid])
|
|
@@ -613,17 +615,8 @@ def plot_qq_overlay(all_results, cfg=None):
|
|
| 613 |
|
| 614 |
# βββββββββββββββββββββββ CIRCOS PLOT βββββββββββββββββββββββββββββββββββββββββββββ
|
| 615 |
def plot_circos(all_results, chroms, positions, cfg=None, top_n=15):
|
| 616 |
-
"""
|
| 617 |
-
Circos plot with:
|
| 618 |
-
- Clear chromosome number labels (Chr1, Chr2, ...) on outer band
|
| 619 |
-
- Colored outer chromosome bands
|
| 620 |
-
- Concentric rings per model
|
| 621 |
-
- Ribbons for top MTAs
|
| 622 |
-
- Both Bonferroni + suggestive markers
|
| 623 |
-
"""
|
| 624 |
if cfg is None:
|
| 625 |
-
cfg = build_cfg(14, 14, 8, "#2D3142"
|
| 626 |
-
"#E15759", "#4E79A7", 6, 0.7)
|
| 627 |
|
| 628 |
fig, ax = plt.subplots(figsize=(cfg["width"], cfg["height"]),
|
| 629 |
subplot_kw=dict(projection='polar'))
|
|
@@ -640,7 +633,6 @@ def plot_circos(all_results, chroms, positions, cfg=None, top_n=15):
|
|
| 640 |
|
| 641 |
snp_angles = np.linspace(0, 2 * np.pi, total_snps, endpoint=False)
|
| 642 |
|
| 643 |
-
# ββ Outer chromosome band ββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 644 |
outer_r = 1.0
|
| 645 |
band_h = 0.07
|
| 646 |
label_r = outer_r + band_h + 0.10
|
|
@@ -662,23 +654,19 @@ def plot_circos(all_results, chroms, positions, cfg=None, top_n=15):
|
|
| 662 |
bottom=outer_r, color=col, alpha=0.88,
|
| 663 |
linewidth=0.8, edgecolor="white")
|
| 664 |
|
| 665 |
-
# ββ Chromosome number text directly on the band ββββββββββββββββββββ
|
| 666 |
-
# Always show the chromosome number clearly
|
| 667 |
text_angle_deg = np.degrees(theta_mid)
|
| 668 |
-
# Rotate text so it reads outward
|
| 669 |
if theta_mid > np.pi:
|
| 670 |
rotation = text_angle_deg - 90
|
| 671 |
else:
|
| 672 |
rotation = text_angle_deg + 90
|
| 673 |
|
| 674 |
ax.text(theta_mid, outer_r + band_h * 0.5,
|
| 675 |
-
f"{ch}",
|
| 676 |
ha='center', va='center',
|
| 677 |
fontsize=max(cfg["font_size"]-1, 6),
|
| 678 |
color='white', fontweight='bold',
|
| 679 |
rotation=rotation)
|
| 680 |
|
| 681 |
-
# ββ Chromosome labels outside the band (Chr N format) ββββββββββββββββββββ
|
| 682 |
used_angles = []
|
| 683 |
min_sep = 0.20
|
| 684 |
|
|
@@ -715,7 +703,6 @@ def plot_circos(all_results, chroms, positions, cfg=None, top_n=15):
|
|
| 715 |
fontsize=cfg["font_size"], color=col,
|
| 716 |
fontweight='bold', rotation=rot)
|
| 717 |
|
| 718 |
-
# ββ Per-model rings ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 719 |
model_names = list(all_results.keys())
|
| 720 |
n_models = len(model_names)
|
| 721 |
ring_gap = 0.012
|
|
@@ -730,24 +717,20 @@ def plot_circos(all_results, chroms, positions, cfg=None, top_n=15):
|
|
| 730 |
col = MODEL_COLORS.get(mname, CHR_PALETTE[midx % len(CHR_PALETTE)])
|
| 731 |
max_lp = max(log_p.max(), 1)
|
| 732 |
|
| 733 |
-
# Compute thresholds for this model
|
| 734 |
n_snps = len(pvals)
|
| 735 |
bonf_thresh = 0.05 / n_snps
|
| 736 |
sug_thresh = 1.0 / n_snps
|
| 737 |
bonf_lp = -np.log10(bonf_thresh)
|
| 738 |
sug_lp = -np.log10(sug_thresh)
|
| 739 |
|
| 740 |
-
# Ring baseline arc
|
| 741 |
theta_arc = np.linspace(0, 2 * np.pi, 500)
|
| 742 |
ax.plot(theta_arc, np.full_like(theta_arc, r_base),
|
| 743 |
color=col, alpha=0.15, lw=0.8, zorder=1)
|
| 744 |
|
| 745 |
-
# Suggestive threshold ring
|
| 746 |
sug_r = r_base + (sug_lp / max_lp) * r_max_data
|
| 747 |
ax.plot(theta_arc, np.full_like(theta_arc, min(sug_r, r_base + r_max_data)),
|
| 748 |
color=cfg["sug_color"], alpha=0.35, lw=0.7, ls=":", zorder=2)
|
| 749 |
|
| 750 |
-
# Bonferroni threshold ring
|
| 751 |
bonf_r = r_base + (bonf_lp / max_lp) * r_max_data
|
| 752 |
if bonf_r <= r_base + r_max_data:
|
| 753 |
ax.plot(theta_arc, np.full_like(theta_arc, bonf_r),
|
|
@@ -758,7 +741,6 @@ def plot_circos(all_results, chroms, positions, cfg=None, top_n=15):
|
|
| 758 |
c=col, s=cfg["marker_size"]*0.5,
|
| 759 |
alpha=cfg["alpha"]*0.7, linewidths=0, zorder=3)
|
| 760 |
|
| 761 |
-
# Highlight top MTAs
|
| 762 |
top_idx = get_top_mta(pvals, top_n)
|
| 763 |
top_sort_pos = [np.where(sort_idx == ti)[0][0] for ti in top_idx
|
| 764 |
if len(np.where(sort_idx == ti)[0]) > 0]
|
|
@@ -770,13 +752,11 @@ def plot_circos(all_results, chroms, positions, cfg=None, top_n=15):
|
|
| 770 |
zorder=12, marker='D',
|
| 771 |
edgecolors='#333333', linewidth=0.5, alpha=0.95)
|
| 772 |
|
| 773 |
-
# Model name label
|
| 774 |
ax.text(np.pi * 1.5, r_base + r_max_data * 0.35,
|
| 775 |
mname, ha='center', va='center',
|
| 776 |
fontsize=cfg["font_size"]-1, color=col,
|
| 777 |
fontweight='bold', alpha=0.92)
|
| 778 |
|
| 779 |
-
# ββ Ribbons ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 780 |
if len(all_results) > 0:
|
| 781 |
first_model = model_names[0]
|
| 782 |
pvals_first, _, _ = all_results[first_model]
|
|
@@ -804,7 +784,6 @@ def plot_circos(all_results, chroms, positions, cfg=None, top_n=15):
|
|
| 804 |
ax.plot(theta_ribbon, np.full(30, ribbon_r * 0.7),
|
| 805 |
color=col_r, alpha=0.12, lw=0.8, zorder=1)
|
| 806 |
|
| 807 |
-
# ββ Legend βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 808 |
legend_elements = [
|
| 809 |
mpatches.Patch(facecolor=MODEL_COLORS.get(m, "#7C6FCD"), label=m, alpha=0.85)
|
| 810 |
for m in model_names
|
|
@@ -834,8 +813,7 @@ def plot_circos(all_results, chroms, positions, cfg=None, top_n=15):
|
|
| 834 |
# βββββββββββββββββββββββ LD DECAY ββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 835 |
def plot_ld_decay(G, positions, cfg=None):
|
| 836 |
if cfg is None:
|
| 837 |
-
cfg = build_cfg(16, 6, 9, "#2D3142"
|
| 838 |
-
"#E15759", "#4E79A7", 12, 0.35)
|
| 839 |
fig, axes = plt.subplots(1, 2, figsize=(cfg["width"], cfg["height"]))
|
| 840 |
fig.patch.set_facecolor(cfg["bg_color"])
|
| 841 |
|
|
@@ -911,21 +889,12 @@ def plot_ld_decay(G, positions, cfg=None):
|
|
| 911 |
|
| 912 |
# βββββββββββββββββββββββ PCA (DARK THEME) ββββββββββββββββββββββββββββββββββββββββ
|
| 913 |
def plot_pca(G, y, ids, cfg=None):
|
| 914 |
-
"""
|
| 915 |
-
PCA with dark background (as requested).
|
| 916 |
-
Scree plot REMOVED (as requested).
|
| 917 |
-
"""
|
| 918 |
if cfg is None:
|
| 919 |
-
cfg = build_cfg(14, 10, 9,
|
| 920 |
-
|
| 921 |
-
|
| 922 |
-
bg=BG_DARK,
|
| 923 |
-
panel=PANEL_DARK,
|
| 924 |
-
sig_col=ACCENT_TEAL,
|
| 925 |
-
sug_col=ACCENT_GOLD,
|
| 926 |
marker_size=55, alpha=0.80)
|
| 927 |
|
| 928 |
-
# Use dark theme colors
|
| 929 |
bg_col = cfg.get("bg_color", BG_DARK)
|
| 930 |
panel_col = cfg.get("panel_color", PANEL_DARK)
|
| 931 |
fc = cfg.get("font_color", TEXT_MAIN)
|
|
@@ -949,7 +918,6 @@ def plot_pca(G, y, ids, cfg=None):
|
|
| 949 |
ax.grid(color=gc, linewidth=0.4, linestyle="--", alpha=0.5)
|
| 950 |
ax.tick_params(colors=fc, labelsize=fs-1)
|
| 951 |
|
| 952 |
-
# ββ PC1 vs PC2 βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 953 |
sc = axes[0].scatter(pcs[:,0], pcs[:,1], c=y, cmap='plasma',
|
| 954 |
s=cfg["marker_size"], edgecolors='none', alpha=cfg["alpha"])
|
| 955 |
axes[0].set_xlabel(f"PC1 ({var_exp[0]:.1f}%)", fontsize=fs, color=fc)
|
|
@@ -961,7 +929,6 @@ def plot_pca(G, y, ids, cfg=None):
|
|
| 961 |
cbar.ax.yaxis.set_tick_params(color=fc)
|
| 962 |
plt.setp(cbar.ax.yaxis.get_ticklabels(), color=fc)
|
| 963 |
|
| 964 |
-
# ββ PC2 vs PC3 βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 965 |
if n_comp >= 3:
|
| 966 |
sc2 = axes[1].scatter(pcs[:,1], pcs[:,2], c=y, cmap='plasma',
|
| 967 |
s=cfg["marker_size"], edgecolors='none', alpha=cfg["alpha"])
|
|
@@ -975,7 +942,6 @@ def plot_pca(G, y, ids, cfg=None):
|
|
| 975 |
else:
|
| 976 |
axes[1].set_visible(False)
|
| 977 |
|
| 978 |
-
# ββ Population Structure Biplot PC1 vs PC2 with ID labels ββββββββββββββββββ
|
| 979 |
sc3 = axes[2].scatter(pcs[:,0], pcs[:,1], c=y, cmap='cool',
|
| 980 |
s=cfg["marker_size"], edgecolors='none', alpha=cfg["alpha"])
|
| 981 |
axes[2].set_title("Population Structure", color=ACCENT_PINK, fontsize=fs+1, fontweight='bold')
|
|
@@ -994,10 +960,8 @@ def plot_pca(G, y, ids, cfg=None):
|
|
| 994 |
|
| 995 |
# βββββββββββββββββββββββ MODEL COMPARISON MANHATTAN ββββββββββββββββββββββββββββββ
|
| 996 |
def plot_model_comparison_manhattan(all_results, chroms, positions, cfg=None, top_n=15):
|
| 997 |
-
"""All-models Manhattan with chromosome numbers and both thresholds."""
|
| 998 |
if cfg is None:
|
| 999 |
-
cfg = build_cfg(16, 3.5, 7, "#2D3142"
|
| 1000 |
-
"#E15759", "#4E79A7", 6, 0.65)
|
| 1001 |
n_models = len(all_results)
|
| 1002 |
fig, axes = plt.subplots(n_models, 1,
|
| 1003 |
figsize=(cfg["width"], cfg["height"] * n_models),
|
|
@@ -1026,7 +990,7 @@ def plot_model_comparison_manhattan(all_results, chroms, positions, cfg=None, to
|
|
| 1026 |
mask = chroms == ch
|
| 1027 |
if mask.sum() > 0:
|
| 1028 |
tick_pos.append(x_coords[mask].mean())
|
| 1029 |
-
tick_lab.append(f"Chr{ch}")
|
| 1030 |
|
| 1031 |
for midx, (mname, (pvals, _, _)) in enumerate(all_results.items()):
|
| 1032 |
ax = axes[midx]
|
|
@@ -1034,7 +998,6 @@ def plot_model_comparison_manhattan(all_results, chroms, positions, cfg=None, to
|
|
| 1034 |
log_p = -np.log10(np.clip(pvals, 1e-300, 1))
|
| 1035 |
col = MODEL_COLORS.get(mname, CHR_PALETTE[midx % len(CHR_PALETTE)])
|
| 1036 |
|
| 1037 |
-
# Compute model-specific thresholds
|
| 1038 |
n_snps = len(pvals)
|
| 1039 |
bonf_thresh = 0.05 / n_snps
|
| 1040 |
sug_thresh = 1.0 / n_snps
|
|
@@ -1050,7 +1013,6 @@ def plot_model_comparison_manhattan(all_results, chroms, positions, cfg=None, to
|
|
| 1050 |
zorder=10, linewidths=0.7, edgecolors='#333333',
|
| 1051 |
marker='D', label=f"Top {top_n} MTAs")
|
| 1052 |
|
| 1053 |
-
# Both thresholds on every subplot
|
| 1054 |
ax.axhline(-np.log10(sug_thresh), color=cfg["sug_color"],
|
| 1055 |
ls=':', lw=1.2, alpha=0.9,
|
| 1056 |
label=f"Sug. (1/m={sug_thresh:.1e})")
|
|
@@ -1083,8 +1045,7 @@ def plot_model_comparison_manhattan(all_results, chroms, positions, cfg=None, to
|
|
| 1083 |
# βββββββββββββββββββββββ KINSHIP βββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1084 |
def plot_kinship(K, ids, cfg=None):
|
| 1085 |
if cfg is None:
|
| 1086 |
-
cfg = build_cfg(14, 12, 9, "#2D3142"
|
| 1087 |
-
"#E15759", "#4E79A7", 60, 0.75)
|
| 1088 |
|
| 1089 |
fig, axes = plt.subplots(2, 2, figsize=(cfg["width"], cfg["height"]))
|
| 1090 |
fig.patch.set_facecolor(cfg["bg_color"])
|
|
@@ -1174,8 +1135,7 @@ def plot_kinship(K, ids, cfg=None):
|
|
| 1174 |
# βββββββββββββββββββββββ EFFECT SIZES ββββββββββββββββββββββββββββββββββββββββββββ
|
| 1175 |
def plot_effect_sizes(pvals, betas, snp_names, cfg=None, top_n=15):
|
| 1176 |
if cfg is None:
|
| 1177 |
-
cfg = build_cfg(14, 10, 9, "#2D3142"
|
| 1178 |
-
"#E15759", "#4E79A7", 25, 0.7)
|
| 1179 |
|
| 1180 |
fig, axes = plt.subplots(2, 2, figsize=(cfg["width"], cfg["height"]))
|
| 1181 |
fig.patch.set_facecolor(cfg["bg_color"])
|
|
@@ -1249,10 +1209,8 @@ def plot_effect_sizes(pvals, betas, snp_names, cfg=None, top_n=15):
|
|
| 1249 |
|
| 1250 |
# βββββββββββββββββββββββ SUMMARY DASHBOARD βββββββββββββββββββββββββββββββββββββββ
|
| 1251 |
def plot_summary_dashboard(y, maf, all_results, G_filt, cfg=None):
|
| 1252 |
-
"""Dashboard: scree plot REMOVED, replaced with per-model threshold table."""
|
| 1253 |
if cfg is None:
|
| 1254 |
-
cfg = build_cfg(15, 10, 9, "#2D3142"
|
| 1255 |
-
"#E15759", "#4E79A7", 30, 0.75)
|
| 1256 |
|
| 1257 |
fig, axes = plt.subplots(2, 3, figsize=(cfg["width"], cfg["height"]))
|
| 1258 |
fig.patch.set_facecolor(cfg["bg_color"])
|
|
@@ -1345,10 +1303,8 @@ def plot_summary_dashboard(y, maf, all_results, G_filt, cfg=None):
|
|
| 1345 |
axes[4].set_title("Model Concordance (Spearman Ο)",
|
| 1346 |
color=cfg["font_color"], fontsize=cfg["font_size"]+1, fontweight='bold')
|
| 1347 |
|
| 1348 |
-
# Panel 5:
|
| 1349 |
axes[5].axis('off')
|
| 1350 |
-
first_model = model_names[0]
|
| 1351 |
-
# Build threshold text
|
| 1352 |
thresh_lines = [
|
| 1353 |
f"{'Model':<10} {'Bonferroni':>14} {'Suggestive':>14}",
|
| 1354 |
"β" * 42,
|
|
@@ -1433,7 +1389,7 @@ def export_results_excel(all_results, snp_filt, chr_filt, pos_filt, y,
|
|
| 1433 |
cell.fill = fill; cell.border = thin_border
|
| 1434 |
cell.alignment = Alignment(horizontal='center')
|
| 1435 |
|
| 1436 |
-
#
|
| 1437 |
ws_exp = wb.create_sheet(title="Threshold_Explanation")
|
| 1438 |
ws_exp['A1'] = "Threshold Calculation Explanation"
|
| 1439 |
ws_exp['A1'].font = title_font
|
|
@@ -1700,8 +1656,8 @@ def run_gwas(file_obj, text_input, selected_models, maf_threshold, top_n,
|
|
| 1700 |
"GEMMA": lambda: gemma_gwas(y, G_filt, K),
|
| 1701 |
}
|
| 1702 |
|
| 1703 |
-
models_to_run = [
|
| 1704 |
-
if
|
| 1705 |
if not models_to_run:
|
| 1706 |
models_to_run = list(model_funcs.keys())
|
| 1707 |
|
|
@@ -1722,30 +1678,43 @@ def run_gwas(file_obj, text_input, selected_models, maf_threshold, top_n,
|
|
| 1722 |
|
| 1723 |
top_n = int(top_n)
|
| 1724 |
|
| 1725 |
-
# Build per-plot configs
|
| 1726 |
-
|
| 1727 |
-
|
| 1728 |
-
|
| 1729 |
-
|
| 1730 |
-
|
| 1731 |
-
|
| 1732 |
-
|
| 1733 |
-
|
| 1734 |
-
|
| 1735 |
-
|
| 1736 |
-
|
| 1737 |
-
|
| 1738 |
-
|
| 1739 |
-
|
| 1740 |
-
|
| 1741 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1742 |
sig_col=ACCENT_TEAL, sug_col=ACCENT_GOLD,
|
| 1743 |
marker_size=55, alpha=0.80)
|
| 1744 |
-
|
| 1745 |
-
|
| 1746 |
-
|
| 1747 |
-
|
| 1748 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1749 |
|
| 1750 |
# Generate all plots
|
| 1751 |
plot_dict = {}
|
|
@@ -1787,9 +1756,9 @@ def run_gwas(file_obj, text_input, selected_models, maf_threshold, top_n,
|
|
| 1787 |
|
| 1788 |
bonf = 0.05 / len(primary_p)
|
| 1789 |
lambdas_str = "\n ".join([
|
| 1790 |
-
f"{
|
| 1791 |
f"sig(Bonf)={int((p<0.05/len(p)).sum())} sig(Sug)={int((p<1.0/len(p)).sum())}"
|
| 1792 |
-
for
|
| 1793 |
])
|
| 1794 |
lam = (np.median(stats.chi2.ppf(1-np.clip(primary_p,1e-10,1),df=1)) /
|
| 1795 |
stats.chi2.ppf(0.5, df=1))
|
|
|
|
| 216 |
bonferroni = 0.05 / n_snps
|
| 217 |
suggestive = 1.0 / n_snps # 1 expected false positive genome-wide
|
| 218 |
|
|
|
|
| 219 |
model_notes = {
|
| 220 |
"OLS": "OLS uses no population structure correction; thresholds are standard.",
|
| 221 |
"MLM": "MLM corrects for kinship (relatedness); mixed model may slightly inflate Ξ».",
|
|
|
|
| 272 |
return pvals, betas, ses
|
| 273 |
|
| 274 |
def emmax_gwas(y, G, K):
|
| 275 |
+
"""
|
| 276 |
+
EMMAX: Efficient Mixed-Model Association eXpedited.
|
| 277 |
+
Fixed: proper handling of matrix dimensions for all SNPs.
|
| 278 |
+
"""
|
| 279 |
n, m = G.shape
|
| 280 |
+
pvals = np.ones(m)
|
| 281 |
+
betas = np.zeros(m)
|
| 282 |
+
ses = np.zeros(m)
|
| 283 |
+
|
| 284 |
+
tau = np.var(y) * 0.5
|
| 285 |
sigma = np.var(y) * 0.5
|
| 286 |
+
V = tau * K + sigma * np.eye(n)
|
| 287 |
try:
|
| 288 |
V_inv = np.linalg.inv(V + np.eye(n) * 1e-6)
|
| 289 |
+
except np.linalg.LinAlgError:
|
| 290 |
V_inv = np.eye(n)
|
| 291 |
+
|
| 292 |
for j in range(m):
|
| 293 |
+
x = G[:, j].reshape(-1, 1) # shape (n, 1)
|
| 294 |
+
|
| 295 |
+
# P_x = V_inv @ x β shape (n, 1)
|
| 296 |
+
Px = V_inv @ x # (n, 1)
|
| 297 |
+
|
| 298 |
+
# scalar: x^T Px x
|
| 299 |
+
xTPx = float(x.T @ Px) # (1,1) β scalar
|
| 300 |
+
if abs(xTPx) < 1e-12:
|
| 301 |
+
continue
|
| 302 |
+
|
| 303 |
+
# scalar: x^T Px y
|
| 304 |
+
xTPy = float(x.T @ (V_inv @ y.reshape(-1, 1)))
|
| 305 |
+
|
| 306 |
+
beta = xTPy / xTPx
|
| 307 |
+
betas[j] = beta
|
| 308 |
+
|
| 309 |
+
resid = y - beta * x.flatten() # shape (n,)
|
| 310 |
+
# scalar: resid^T V_inv resid
|
| 311 |
+
rVr = float(resid.reshape(1, -1) @ V_inv @ resid.reshape(-1, 1))
|
| 312 |
+
sigma_e = rVr / max(n - 2, 1)
|
| 313 |
+
|
| 314 |
+
se = float(np.sqrt(abs(sigma_e / xTPx)))
|
| 315 |
ses[j] = se
|
| 316 |
+
|
| 317 |
+
t_stat = beta / (se + 1e-12)
|
| 318 |
+
pvals[j] = float(2 * stats.t.sf(abs(t_stat), df=max(n - 2, 1)))
|
| 319 |
+
|
| 320 |
return pvals, betas, ses
|
| 321 |
|
| 322 |
def farmcpu_gwas(y, G, K):
|
|
|
|
| 358 |
return pvals, betas, ses
|
| 359 |
|
| 360 |
# βββββββββββββββββββββββ CONFIG BUILDER ββββββββββββββββββββββββββββββββββββββββββ
|
| 361 |
+
def build_cfg(w, h, fs, fc, gc="#E8ECF4", bg="#FFFFFF", panel="#FAFBFF",
|
| 362 |
+
sig_col="#E15759", sug_col="#4E79A7", marker_size=12, alpha=0.75,
|
| 363 |
+
font_color=None, dot_col=None, line_col=None, fill_col=None,
|
| 364 |
+
axis_col=None):
|
| 365 |
+
"""
|
| 366 |
+
Build a plot configuration dictionary.
|
| 367 |
+
'fc' is the required positional font-color argument.
|
| 368 |
+
'font_color' is an optional alias (takes precedence if provided).
|
| 369 |
+
"""
|
| 370 |
+
effective_fc = font_color if font_color is not None else fc
|
| 371 |
return {
|
| 372 |
+
"width": w,
|
| 373 |
+
"height": h,
|
| 374 |
+
"font_size": fs,
|
| 375 |
+
"font_color": effective_fc,
|
| 376 |
+
"grid_color": gc,
|
| 377 |
+
"bg_color": bg,
|
| 378 |
+
"panel_color": panel,
|
| 379 |
+
"sig_color": sig_col,
|
| 380 |
+
"sug_color": sug_col,
|
| 381 |
+
"marker_size": marker_size,
|
| 382 |
+
"alpha": alpha,
|
| 383 |
+
"dot_color": dot_col or "#4E79A7",
|
| 384 |
+
"line_color": line_col or "#E15759",
|
| 385 |
+
"fill_color": fill_col or "#A78BFA",
|
| 386 |
+
"axis_color": axis_col or "#2D3142",
|
| 387 |
}
|
| 388 |
|
| 389 |
# βββββββββββββββββββββββ MANHATTAN PLOT ββββββββββββββββββββββββββββββββββββββββββ
|
| 390 |
def plot_manhattan(pvals, chroms, positions, title="Manhattan Plot", model_name="",
|
| 391 |
cfg=None, top_n=15):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 392 |
if cfg is None:
|
| 393 |
+
cfg = build_cfg(16, 5, 9, "#2D3142")
|
|
|
|
| 394 |
|
| 395 |
n_snps = len(pvals)
|
| 396 |
bonf_thresh = 0.05 / n_snps
|
|
|
|
| 419 |
x_vals = pos[order] - pos.min() + x_offset
|
| 420 |
x_coords[np.where(mask)[0][order]] = x_vals
|
| 421 |
tick_pos.append(x_vals.mean())
|
|
|
|
| 422 |
tick_lab.append(f"Chr{ch}")
|
| 423 |
ax.scatter(x_coords[mask], log_p[mask],
|
| 424 |
c=chrom_colors[ch], s=cfg["marker_size"],
|
| 425 |
alpha=cfg["alpha"], linewidths=0)
|
| 426 |
x_offset += (pos.max() - pos.min()) + gap
|
| 427 |
|
|
|
|
| 428 |
ax.axhline(sug_line, color=cfg["sug_color"], ls=":", lw=1.5, alpha=0.9,
|
| 429 |
label=f"Suggestive (1/m = {sug_thresh:.1e}, -logββ={sug_line:.1f})")
|
|
|
|
| 430 |
ax.axhline(sig_line, color=cfg["sig_color"], ls="--", lw=2.0,
|
| 431 |
label=f"Bonferroni (0.05/m = {bonf_thresh:.1e}, -logββ={sig_line:.1f})")
|
| 432 |
|
|
|
|
| 433 |
top_idx = get_top_mta(pvals, top_n)
|
| 434 |
sig_mask = np.zeros(len(pvals), dtype=bool)
|
| 435 |
sig_mask[top_idx] = True
|
|
|
|
| 461 |
|
| 462 |
# βββββββββββββββββββββββ QQ PLOT βββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 463 |
def plot_qq_single(pvals, title="QQ Plot", model_name="", color=None, cfg=None):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 464 |
if cfg is None:
|
| 465 |
+
cfg = build_cfg(7, 7, 9, "#2D3142")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 466 |
if color is None:
|
| 467 |
color = cfg.get("dot_color", "#A78BFA")
|
| 468 |
|
|
|
|
| 474 |
obs = np.sort(-np.log10(np.clip(pvals, 1e-300, 1)))[::-1]
|
| 475 |
exp = -np.log10(np.linspace(1/n, 1, n)[::-1])
|
| 476 |
|
|
|
|
| 477 |
ci_lower = -np.log10(stats.beta.ppf(0.975, np.arange(1, n+1), np.arange(n, 0, -1)))
|
| 478 |
ci_upper = -np.log10(stats.beta.ppf(0.025, np.arange(1, n+1), np.arange(n, 0, -1)))
|
| 479 |
ax.fill_between(exp, ci_lower, ci_upper, alpha=0.2, color=color, label="95% CI")
|
| 480 |
|
|
|
|
| 481 |
ax.scatter(exp, obs, c=color, s=cfg["marker_size"], alpha=cfg["alpha"],
|
| 482 |
linewidths=0, zorder=5, label="Observed")
|
| 483 |
|
|
|
|
| 484 |
ax.plot([0, max(exp)], [0, max(exp)], color="#AAAAAA",
|
| 485 |
ls="-", lw=1.2, alpha=0.7, label="y = x (null)", zorder=4)
|
| 486 |
|
|
|
|
|
|
|
| 487 |
valid = np.isfinite(exp) & np.isfinite(obs)
|
| 488 |
if valid.sum() > 2:
|
| 489 |
slope_reg, intercept_reg, r_val, p_val, _ = stats.linregress(exp[valid], obs[valid])
|
|
|
|
| 492 |
ax.plot(x_reg, y_reg, color=cfg["line_color"], ls="-", lw=2.2, zorder=6,
|
| 493 |
label=f"Regression (slope={slope_reg:.3f}, RΒ²={r_val**2:.3f})")
|
| 494 |
|
|
|
|
| 495 |
lam = np.median(stats.chi2.ppf(1 - np.clip(pvals, 1e-10, 1), df=1)) / stats.chi2.ppf(0.5, df=1)
|
| 496 |
ax.text(0.05, 0.93, f"Ξ» = {lam:.4f}", transform=ax.transAxes,
|
| 497 |
fontsize=cfg["font_size"]+2, color="#E15759", fontweight='bold')
|
|
|
|
| 514 |
def plot_qq_all_models(all_results, cfg=None):
|
| 515 |
"""QQ plots for all models with regression lines."""
|
| 516 |
if cfg is None:
|
| 517 |
+
cfg = build_cfg(7, 6, 9, "#2D3142")
|
|
|
|
| 518 |
n_models = len(all_results)
|
| 519 |
ncols = min(3, n_models)
|
| 520 |
nrows = (n_models + ncols - 1) // ncols
|
|
|
|
| 540 |
ax.scatter(exp, obs, c=col, s=cfg["marker_size"], alpha=cfg["alpha"],
|
| 541 |
linewidths=0, zorder=5)
|
| 542 |
|
|
|
|
| 543 |
ax.plot([0, max(exp)], [0, max(exp)], color="#AAAAAA",
|
| 544 |
ls="-", lw=1.0, alpha=0.6, zorder=4)
|
| 545 |
|
|
|
|
| 546 |
valid = np.isfinite(exp) & np.isfinite(obs)
|
| 547 |
if valid.sum() > 2:
|
| 548 |
slope_reg, intercept_reg, r_val, _, _ = stats.linregress(exp[valid], obs[valid])
|
|
|
|
| 576 |
def plot_qq_overlay(all_results, cfg=None):
|
| 577 |
"""QQ overlay with regression lines per model."""
|
| 578 |
if cfg is None:
|
| 579 |
+
cfg = build_cfg(9, 9, 10, "#2D3142")
|
|
|
|
| 580 |
fig, ax = plt.subplots(figsize=(cfg["width"], cfg["height"]))
|
| 581 |
fig.patch.set_facecolor(cfg["bg_color"])
|
| 582 |
ax.set_facecolor(cfg["panel_color"])
|
|
|
|
| 590 |
col = MODEL_COLORS.get(mname, "#7C6FCD")
|
| 591 |
ax.plot(exp, obs, color=col, lw=2, label=f"{mname} (Ξ»={lam:.3f})", alpha=0.85)
|
| 592 |
|
|
|
|
| 593 |
valid = np.isfinite(exp) & np.isfinite(obs)
|
| 594 |
if valid.sum() > 2:
|
| 595 |
slope_r, intercept_r, _, _, _ = stats.linregress(exp[valid], obs[valid])
|
|
|
|
| 615 |
|
| 616 |
# βββββββββββββββββββββββ CIRCOS PLOT βββββββββββββββββββββββββββββββββββββββββββββ
|
| 617 |
def plot_circos(all_results, chroms, positions, cfg=None, top_n=15):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 618 |
if cfg is None:
|
| 619 |
+
cfg = build_cfg(14, 14, 8, "#2D3142")
|
|
|
|
| 620 |
|
| 621 |
fig, ax = plt.subplots(figsize=(cfg["width"], cfg["height"]),
|
| 622 |
subplot_kw=dict(projection='polar'))
|
|
|
|
| 633 |
|
| 634 |
snp_angles = np.linspace(0, 2 * np.pi, total_snps, endpoint=False)
|
| 635 |
|
|
|
|
| 636 |
outer_r = 1.0
|
| 637 |
band_h = 0.07
|
| 638 |
label_r = outer_r + band_h + 0.10
|
|
|
|
| 654 |
bottom=outer_r, color=col, alpha=0.88,
|
| 655 |
linewidth=0.8, edgecolor="white")
|
| 656 |
|
|
|
|
|
|
|
| 657 |
text_angle_deg = np.degrees(theta_mid)
|
|
|
|
| 658 |
if theta_mid > np.pi:
|
| 659 |
rotation = text_angle_deg - 90
|
| 660 |
else:
|
| 661 |
rotation = text_angle_deg + 90
|
| 662 |
|
| 663 |
ax.text(theta_mid, outer_r + band_h * 0.5,
|
| 664 |
+
f"{ch}",
|
| 665 |
ha='center', va='center',
|
| 666 |
fontsize=max(cfg["font_size"]-1, 6),
|
| 667 |
color='white', fontweight='bold',
|
| 668 |
rotation=rotation)
|
| 669 |
|
|
|
|
| 670 |
used_angles = []
|
| 671 |
min_sep = 0.20
|
| 672 |
|
|
|
|
| 703 |
fontsize=cfg["font_size"], color=col,
|
| 704 |
fontweight='bold', rotation=rot)
|
| 705 |
|
|
|
|
| 706 |
model_names = list(all_results.keys())
|
| 707 |
n_models = len(model_names)
|
| 708 |
ring_gap = 0.012
|
|
|
|
| 717 |
col = MODEL_COLORS.get(mname, CHR_PALETTE[midx % len(CHR_PALETTE)])
|
| 718 |
max_lp = max(log_p.max(), 1)
|
| 719 |
|
|
|
|
| 720 |
n_snps = len(pvals)
|
| 721 |
bonf_thresh = 0.05 / n_snps
|
| 722 |
sug_thresh = 1.0 / n_snps
|
| 723 |
bonf_lp = -np.log10(bonf_thresh)
|
| 724 |
sug_lp = -np.log10(sug_thresh)
|
| 725 |
|
|
|
|
| 726 |
theta_arc = np.linspace(0, 2 * np.pi, 500)
|
| 727 |
ax.plot(theta_arc, np.full_like(theta_arc, r_base),
|
| 728 |
color=col, alpha=0.15, lw=0.8, zorder=1)
|
| 729 |
|
|
|
|
| 730 |
sug_r = r_base + (sug_lp / max_lp) * r_max_data
|
| 731 |
ax.plot(theta_arc, np.full_like(theta_arc, min(sug_r, r_base + r_max_data)),
|
| 732 |
color=cfg["sug_color"], alpha=0.35, lw=0.7, ls=":", zorder=2)
|
| 733 |
|
|
|
|
| 734 |
bonf_r = r_base + (bonf_lp / max_lp) * r_max_data
|
| 735 |
if bonf_r <= r_base + r_max_data:
|
| 736 |
ax.plot(theta_arc, np.full_like(theta_arc, bonf_r),
|
|
|
|
| 741 |
c=col, s=cfg["marker_size"]*0.5,
|
| 742 |
alpha=cfg["alpha"]*0.7, linewidths=0, zorder=3)
|
| 743 |
|
|
|
|
| 744 |
top_idx = get_top_mta(pvals, top_n)
|
| 745 |
top_sort_pos = [np.where(sort_idx == ti)[0][0] for ti in top_idx
|
| 746 |
if len(np.where(sort_idx == ti)[0]) > 0]
|
|
|
|
| 752 |
zorder=12, marker='D',
|
| 753 |
edgecolors='#333333', linewidth=0.5, alpha=0.95)
|
| 754 |
|
|
|
|
| 755 |
ax.text(np.pi * 1.5, r_base + r_max_data * 0.35,
|
| 756 |
mname, ha='center', va='center',
|
| 757 |
fontsize=cfg["font_size"]-1, color=col,
|
| 758 |
fontweight='bold', alpha=0.92)
|
| 759 |
|
|
|
|
| 760 |
if len(all_results) > 0:
|
| 761 |
first_model = model_names[0]
|
| 762 |
pvals_first, _, _ = all_results[first_model]
|
|
|
|
| 784 |
ax.plot(theta_ribbon, np.full(30, ribbon_r * 0.7),
|
| 785 |
color=col_r, alpha=0.12, lw=0.8, zorder=1)
|
| 786 |
|
|
|
|
| 787 |
legend_elements = [
|
| 788 |
mpatches.Patch(facecolor=MODEL_COLORS.get(m, "#7C6FCD"), label=m, alpha=0.85)
|
| 789 |
for m in model_names
|
|
|
|
| 813 |
# βββββββββββββββββββββββ LD DECAY ββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 814 |
def plot_ld_decay(G, positions, cfg=None):
|
| 815 |
if cfg is None:
|
| 816 |
+
cfg = build_cfg(16, 6, 9, "#2D3142")
|
|
|
|
| 817 |
fig, axes = plt.subplots(1, 2, figsize=(cfg["width"], cfg["height"]))
|
| 818 |
fig.patch.set_facecolor(cfg["bg_color"])
|
| 819 |
|
|
|
|
| 889 |
|
| 890 |
# βββββββββββββββββββββββ PCA (DARK THEME) ββββββββββββββββββββββββββββββββββββββββ
|
| 891 |
def plot_pca(G, y, ids, cfg=None):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 892 |
if cfg is None:
|
| 893 |
+
cfg = build_cfg(14, 10, 9, TEXT_MAIN,
|
| 894 |
+
gc=GRID_LINE, bg=BG_DARK, panel=PANEL_DARK,
|
| 895 |
+
sig_col=ACCENT_TEAL, sug_col=ACCENT_GOLD,
|
|
|
|
|
|
|
|
|
|
|
|
|
| 896 |
marker_size=55, alpha=0.80)
|
| 897 |
|
|
|
|
| 898 |
bg_col = cfg.get("bg_color", BG_DARK)
|
| 899 |
panel_col = cfg.get("panel_color", PANEL_DARK)
|
| 900 |
fc = cfg.get("font_color", TEXT_MAIN)
|
|
|
|
| 918 |
ax.grid(color=gc, linewidth=0.4, linestyle="--", alpha=0.5)
|
| 919 |
ax.tick_params(colors=fc, labelsize=fs-1)
|
| 920 |
|
|
|
|
| 921 |
sc = axes[0].scatter(pcs[:,0], pcs[:,1], c=y, cmap='plasma',
|
| 922 |
s=cfg["marker_size"], edgecolors='none', alpha=cfg["alpha"])
|
| 923 |
axes[0].set_xlabel(f"PC1 ({var_exp[0]:.1f}%)", fontsize=fs, color=fc)
|
|
|
|
| 929 |
cbar.ax.yaxis.set_tick_params(color=fc)
|
| 930 |
plt.setp(cbar.ax.yaxis.get_ticklabels(), color=fc)
|
| 931 |
|
|
|
|
| 932 |
if n_comp >= 3:
|
| 933 |
sc2 = axes[1].scatter(pcs[:,1], pcs[:,2], c=y, cmap='plasma',
|
| 934 |
s=cfg["marker_size"], edgecolors='none', alpha=cfg["alpha"])
|
|
|
|
| 942 |
else:
|
| 943 |
axes[1].set_visible(False)
|
| 944 |
|
|
|
|
| 945 |
sc3 = axes[2].scatter(pcs[:,0], pcs[:,1], c=y, cmap='cool',
|
| 946 |
s=cfg["marker_size"], edgecolors='none', alpha=cfg["alpha"])
|
| 947 |
axes[2].set_title("Population Structure", color=ACCENT_PINK, fontsize=fs+1, fontweight='bold')
|
|
|
|
| 960 |
|
| 961 |
# βββββββββββββββββββββββ MODEL COMPARISON MANHATTAN ββββββββββββββββββββββββββββββ
|
| 962 |
def plot_model_comparison_manhattan(all_results, chroms, positions, cfg=None, top_n=15):
|
|
|
|
| 963 |
if cfg is None:
|
| 964 |
+
cfg = build_cfg(16, 3.5, 7, "#2D3142")
|
|
|
|
| 965 |
n_models = len(all_results)
|
| 966 |
fig, axes = plt.subplots(n_models, 1,
|
| 967 |
figsize=(cfg["width"], cfg["height"] * n_models),
|
|
|
|
| 990 |
mask = chroms == ch
|
| 991 |
if mask.sum() > 0:
|
| 992 |
tick_pos.append(x_coords[mask].mean())
|
| 993 |
+
tick_lab.append(f"Chr{ch}")
|
| 994 |
|
| 995 |
for midx, (mname, (pvals, _, _)) in enumerate(all_results.items()):
|
| 996 |
ax = axes[midx]
|
|
|
|
| 998 |
log_p = -np.log10(np.clip(pvals, 1e-300, 1))
|
| 999 |
col = MODEL_COLORS.get(mname, CHR_PALETTE[midx % len(CHR_PALETTE)])
|
| 1000 |
|
|
|
|
| 1001 |
n_snps = len(pvals)
|
| 1002 |
bonf_thresh = 0.05 / n_snps
|
| 1003 |
sug_thresh = 1.0 / n_snps
|
|
|
|
| 1013 |
zorder=10, linewidths=0.7, edgecolors='#333333',
|
| 1014 |
marker='D', label=f"Top {top_n} MTAs")
|
| 1015 |
|
|
|
|
| 1016 |
ax.axhline(-np.log10(sug_thresh), color=cfg["sug_color"],
|
| 1017 |
ls=':', lw=1.2, alpha=0.9,
|
| 1018 |
label=f"Sug. (1/m={sug_thresh:.1e})")
|
|
|
|
| 1045 |
# βββββββββββββββββββββββ KINSHIP βββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1046 |
def plot_kinship(K, ids, cfg=None):
|
| 1047 |
if cfg is None:
|
| 1048 |
+
cfg = build_cfg(14, 12, 9, "#2D3142")
|
|
|
|
| 1049 |
|
| 1050 |
fig, axes = plt.subplots(2, 2, figsize=(cfg["width"], cfg["height"]))
|
| 1051 |
fig.patch.set_facecolor(cfg["bg_color"])
|
|
|
|
| 1135 |
# βββββββββββββββββββββββ EFFECT SIZES ββββββββββββββββββββββββββββββββββββββββββββ
|
| 1136 |
def plot_effect_sizes(pvals, betas, snp_names, cfg=None, top_n=15):
|
| 1137 |
if cfg is None:
|
| 1138 |
+
cfg = build_cfg(14, 10, 9, "#2D3142")
|
|
|
|
| 1139 |
|
| 1140 |
fig, axes = plt.subplots(2, 2, figsize=(cfg["width"], cfg["height"]))
|
| 1141 |
fig.patch.set_facecolor(cfg["bg_color"])
|
|
|
|
| 1209 |
|
| 1210 |
# βββββββββββββββββββββββ SUMMARY DASHBOARD βββββββββββββββββββββββββββββββββββββββ
|
| 1211 |
def plot_summary_dashboard(y, maf, all_results, G_filt, cfg=None):
|
|
|
|
| 1212 |
if cfg is None:
|
| 1213 |
+
cfg = build_cfg(15, 10, 9, "#2D3142")
|
|
|
|
| 1214 |
|
| 1215 |
fig, axes = plt.subplots(2, 3, figsize=(cfg["width"], cfg["height"]))
|
| 1216 |
fig.patch.set_facecolor(cfg["bg_color"])
|
|
|
|
| 1303 |
axes[4].set_title("Model Concordance (Spearman Ο)",
|
| 1304 |
color=cfg["font_color"], fontsize=cfg["font_size"]+1, fontweight='bold')
|
| 1305 |
|
| 1306 |
+
# Panel 5: Threshold table per model (replaces scree plot)
|
| 1307 |
axes[5].axis('off')
|
|
|
|
|
|
|
| 1308 |
thresh_lines = [
|
| 1309 |
f"{'Model':<10} {'Bonferroni':>14} {'Suggestive':>14}",
|
| 1310 |
"β" * 42,
|
|
|
|
| 1389 |
cell.fill = fill; cell.border = thin_border
|
| 1390 |
cell.alignment = Alignment(horizontal='center')
|
| 1391 |
|
| 1392 |
+
# Threshold explanation sheet
|
| 1393 |
ws_exp = wb.create_sheet(title="Threshold_Explanation")
|
| 1394 |
ws_exp['A1'] = "Threshold Calculation Explanation"
|
| 1395 |
ws_exp['A1'].font = title_font
|
|
|
|
| 1656 |
"GEMMA": lambda: gemma_gwas(y, G_filt, K),
|
| 1657 |
}
|
| 1658 |
|
| 1659 |
+
models_to_run = [mdl for mdl in (selected_models or list(model_funcs.keys()))
|
| 1660 |
+
if mdl in model_funcs]
|
| 1661 |
if not models_to_run:
|
| 1662 |
models_to_run = list(model_funcs.keys())
|
| 1663 |
|
|
|
|
| 1678 |
|
| 1679 |
top_n = int(top_n)
|
| 1680 |
|
| 1681 |
+
# ββ Build per-plot configs ββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1682 |
+
# All build_cfg calls now correctly pass 'fc' as the 4th positional arg
|
| 1683 |
+
cfg_mh = build_cfg(mh_w, mh_h, mh_fs, mh_fc,
|
| 1684 |
+
bg=mh_bg, panel=mh_panel,
|
| 1685 |
+
sig_col=mh_sig, sug_col=mh_sug,
|
| 1686 |
+
marker_size=mh_ms, alpha=mh_alpha,
|
| 1687 |
+
dot_col=mh_dot)
|
| 1688 |
+
|
| 1689 |
+
cfg_qq = build_cfg(qq_w, qq_h, qq_fs, qq_fc,
|
| 1690 |
+
bg=qq_bg, panel=qq_panel,
|
| 1691 |
+
marker_size=qq_ms,
|
| 1692 |
+
dot_col=qq_dot, line_col=qq_line, fill_col=qq_fill)
|
| 1693 |
+
|
| 1694 |
+
cfg_ci = build_cfg(ci_w, ci_h, ci_fs, "#2D3142",
|
| 1695 |
+
sig_col=ci_sig, sug_col=ci_sug)
|
| 1696 |
+
|
| 1697 |
+
cfg_ld = build_cfg(ld_w, ld_h, ld_fs, "#2D3142",
|
| 1698 |
+
dot_col=ld_dot, line_col=ld_line)
|
| 1699 |
+
|
| 1700 |
+
# PCA β always dark theme; fc = TEXT_MAIN
|
| 1701 |
+
cfg_pc = build_cfg(pc_w, pc_h, pc_fs, TEXT_MAIN,
|
| 1702 |
+
gc=GRID_LINE, bg=BG_DARK, panel=PANEL_DARK,
|
| 1703 |
sig_col=ACCENT_TEAL, sug_col=ACCENT_GOLD,
|
| 1704 |
marker_size=55, alpha=0.80)
|
| 1705 |
+
|
| 1706 |
+
cfg_ki = build_cfg(ki_w, ki_h, ki_fs, "#2D3142",
|
| 1707 |
+
bg=ki_bg, panel=ki_panel, dot_col=ki_dot)
|
| 1708 |
+
|
| 1709 |
+
cfg_ef = build_cfg(ef_w, ef_h, ef_fs, "#2D3142",
|
| 1710 |
+
bg=ef_bg,
|
| 1711 |
+
dot_col=ef_pos, line_col=ef_neg, fill_col=ef_fill)
|
| 1712 |
+
|
| 1713 |
+
cfg_co = build_cfg(co_w, co_h, 7, "#2D3142",
|
| 1714 |
+
sig_col=co_sig, sug_col=co_sug)
|
| 1715 |
+
|
| 1716 |
+
cfg_db = build_cfg(db_w, db_h, 9, "#2D3142",
|
| 1717 |
+
dot_col=db_dot)
|
| 1718 |
|
| 1719 |
# Generate all plots
|
| 1720 |
plot_dict = {}
|
|
|
|
| 1756 |
|
| 1757 |
bonf = 0.05 / len(primary_p)
|
| 1758 |
lambdas_str = "\n ".join([
|
| 1759 |
+
f"{mdl}: Ξ»={np.median(stats.chi2.ppf(1-np.clip(p,1e-10,1),df=1))/stats.chi2.ppf(0.5,df=1):.4f} "
|
| 1760 |
f"sig(Bonf)={int((p<0.05/len(p)).sum())} sig(Sug)={int((p<1.0/len(p)).sum())}"
|
| 1761 |
+
for mdl, (p, _, _) in all_results.items()
|
| 1762 |
])
|
| 1763 |
lam = (np.median(stats.chi2.ppf(1-np.clip(primary_p,1e-10,1),df=1)) /
|
| 1764 |
stats.chi2.ppf(0.5, df=1))
|