softwareDevelopment commited on
Commit
ba3c226
Β·
verified Β·
1 Parent(s): 5ada9e5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +524 -250
app.py CHANGED
@@ -55,24 +55,9 @@ CHR_PALETTE = [
55
  "#499894","#86BCB6","#D4A6C8","#FFBE7D","#8CD17D",
56
  ]
57
 
58
- # 5 efficient models only
59
  ALL_MODELS = ["OLS", "MLM", "EMMAX", "FarmCPU", "GEMMA"]
60
 
61
- def style_fig_dark(fig):
62
- fig.patch.set_facecolor(BG_DARK)
63
- for ax in fig.get_axes():
64
- ax.set_facecolor(PANEL_DARK)
65
- ax.tick_params(colors=TEXT_DIM, labelsize=8)
66
- ax.xaxis.label.set_color(TEXT_DIM)
67
- ax.yaxis.label.set_color(TEXT_DIM)
68
- ax.title.set_color(TEXT_MAIN)
69
- for spine in ax.spines.values():
70
- spine.set_edgecolor(GRID_LINE)
71
- ax.grid(color=GRID_LINE, linewidth=0.4, linestyle="--", alpha=0.5)
72
- return fig
73
-
74
  def style_fig_white(fig, font_size=9, font_color="#2D3142", grid_color="#E8ECF4"):
75
- """White background style for all plots"""
76
  fig.patch.set_facecolor("#FFFFFF")
77
  for ax in fig.get_axes():
78
  ax.set_facecolor("#FAFBFF")
@@ -86,7 +71,6 @@ def style_fig_white(fig, font_size=9, font_color="#2D3142", grid_color="#E8ECF4"
86
  return fig
87
 
88
  def apply_custom_style(fig, cfg):
89
- """Apply user customization to figure"""
90
  bg = cfg.get("bg_color", "#FFFFFF")
91
  panel = cfg.get("panel_color", "#FAFBFF")
92
  fc = cfg.get("font_color", "#2D3142")
@@ -222,9 +206,46 @@ def fig_to_pil(fig):
222
  return Image.open(buf).copy()
223
 
224
  def get_top_mta(pvals, n=15):
225
- """Get indices of top N most significant MTAs"""
226
  return np.argsort(pvals)[:min(n, len(pvals))]
227
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
228
  # ─────────────────────── 5 EFFICIENT STATISTICAL MODELS ──────────────────────────
229
  def ols_gwas(y, G):
230
  n, m = G.shape
@@ -312,28 +333,45 @@ def gemma_gwas(y, G, K):
312
  pvals = 1 - stats.chi2.cdf(np.clip(chi2_vals, 0, 1e10), df=1)
313
  return pvals, betas, ses
314
 
315
- # ─────────────────────── PLOT BUILDERS (WHITE BG, CUSTOMIZABLE) ──────────────────
316
-
317
- def build_cfg(w, h, fs, fc, gc, bg, panel, sig_col, sug_col, marker_size, alpha):
318
  return {
319
  "width": w, "height": h, "font_size": fs, "font_color": fc,
320
  "grid_color": gc, "bg_color": bg, "panel_color": panel,
321
  "sig_color": sig_col, "sug_color": sug_col,
322
- "marker_size": marker_size, "alpha": alpha
 
 
 
 
323
  }
324
 
 
325
  def plot_manhattan(pvals, chroms, positions, title="Manhattan Plot", model_name="",
326
  cfg=None, top_n=15):
 
 
 
 
 
 
327
  if cfg is None:
328
  cfg = build_cfg(16, 5, 9, "#2D3142", "#E8ECF4", "#FFFFFF", "#FAFBFF",
329
  "#E15759", "#4E79A7", 12, 0.75)
 
 
 
 
 
 
 
 
330
  fig, ax = plt.subplots(figsize=(cfg["width"], cfg["height"]))
331
  fig.patch.set_facecolor(cfg["bg_color"])
332
  ax.set_facecolor(cfg["panel_color"])
333
 
334
  log_p = -np.log10(np.clip(pvals, 1e-300, 1))
335
- sig_line = -np.log10(5e-8)
336
- sug_line = -np.log10(1e-5)
337
 
338
  chrom_list = sorted(set(chroms))
339
  chrom_colors = {c: CHR_PALETTE[i % len(CHR_PALETTE)] for i, c in enumerate(chrom_list)}
@@ -349,18 +387,21 @@ def plot_manhattan(pvals, chroms, positions, title="Manhattan Plot", model_name=
349
  x_vals = pos[order] - pos.min() + x_offset
350
  x_coords[np.where(mask)[0][order]] = x_vals
351
  tick_pos.append(x_vals.mean())
 
352
  tick_lab.append(f"Chr{ch}")
353
  ax.scatter(x_coords[mask], log_p[mask],
354
  c=chrom_colors[ch], s=cfg["marker_size"],
355
  alpha=cfg["alpha"], linewidths=0)
356
  x_offset += (pos.max() - pos.min()) + gap
357
 
358
- ax.axhline(sug_line, color=cfg["sug_color"], ls=":", lw=1.2, alpha=0.8,
359
- label=f"Suggestive (1e-5)")
360
- ax.axhline(sig_line, color=cfg["sig_color"], ls="--", lw=1.8,
361
- label=f"GW sig. (5e-8)")
 
 
362
 
363
- # Mark only top_n significant MTAs
364
  top_idx = get_top_mta(pvals, top_n)
365
  sig_mask = np.zeros(len(pvals), dtype=bool)
366
  sig_mask[top_idx] = True
@@ -378,9 +419,9 @@ def plot_manhattan(pvals, chroms, positions, title="Manhattan Plot", model_name=
378
  ax.set_xlabel("Chromosome", color=cfg["font_color"], fontsize=cfg["font_size"])
379
  ax.set_title(f"{title}{' β€” ' + model_name if model_name else ''}",
380
  color=cfg["font_color"], fontsize=cfg["font_size"]+2, pad=8)
381
- ax.legend(fontsize=cfg["font_size"]-1, framealpha=0.85,
382
  facecolor=cfg["bg_color"], edgecolor="#CCCCCC",
383
- labelcolor=cfg["font_color"])
384
  ax.set_xlim(-x_offset * 0.01, x_offset * 1.01)
385
  ax.tick_params(colors=cfg["font_color"])
386
  for spine in ax.spines.values():
@@ -390,12 +431,21 @@ def plot_manhattan(pvals, chroms, positions, title="Manhattan Plot", model_name=
390
  return fig
391
 
392
 
 
393
  def plot_qq_single(pvals, title="QQ Plot", model_name="", color=None, cfg=None):
 
 
 
 
 
 
 
394
  if cfg is None:
395
  cfg = build_cfg(7, 7, 10, "#2D3142", "#E8ECF4", "#FFFFFF", "#FAFBFF",
396
  "#E15759", "#4E79A7", 22, 0.85)
397
  if color is None:
398
- color = "#A78BFA"
 
399
  fig, ax = plt.subplots(figsize=(cfg["width"], cfg["height"]))
400
  fig.patch.set_facecolor(cfg["bg_color"])
401
  ax.set_facecolor(cfg["panel_color"])
@@ -403,17 +453,35 @@ def plot_qq_single(pvals, title="QQ Plot", model_name="", color=None, cfg=None):
403
  n = len(pvals)
404
  obs = np.sort(-np.log10(np.clip(pvals, 1e-300, 1)))[::-1]
405
  exp = -np.log10(np.linspace(1/n, 1, n)[::-1])
 
 
406
  ci_lower = -np.log10(stats.beta.ppf(0.975, np.arange(1, n+1), np.arange(n, 0, -1)))
407
  ci_upper = -np.log10(stats.beta.ppf(0.025, np.arange(1, n+1), np.arange(n, 0, -1)))
408
-
409
  ax.fill_between(exp, ci_lower, ci_upper, alpha=0.2, color=color, label="95% CI")
410
- ax.scatter(exp, obs, c=color, s=cfg["marker_size"], alpha=cfg["alpha"], linewidths=0, zorder=5)
411
- ax.plot([0, max(exp)], [0, max(exp)], color=cfg["sig_color"],
412
- ls="--", lw=1.8, label="Expected", zorder=6)
413
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
414
  lam = np.median(stats.chi2.ppf(1 - np.clip(pvals, 1e-10, 1), df=1)) / stats.chi2.ppf(0.5, df=1)
415
  ax.text(0.05, 0.93, f"Ξ» = {lam:.4f}", transform=ax.transAxes,
416
  fontsize=cfg["font_size"]+2, color="#E15759", fontweight='bold')
 
417
  ax.set_xlabel("Expected -log₁₀(p)", fontsize=cfg["font_size"], color=cfg["font_color"])
418
  ax.set_ylabel("Observed -log₁₀(p)", fontsize=cfg["font_size"], color=cfg["font_color"])
419
  ax.set_title(f"{title}{' β€” ' + model_name if model_name else ''}",
@@ -430,6 +498,7 @@ def plot_qq_single(pvals, title="QQ Plot", model_name="", color=None, cfg=None):
430
 
431
 
432
  def plot_qq_all_models(all_results, cfg=None):
 
433
  if cfg is None:
434
  cfg = build_cfg(7, 6, 9, "#2D3142", "#E8ECF4", "#FFFFFF", "#FAFBFF",
435
  "#E15759", "#4E79A7", 18, 0.8)
@@ -453,9 +522,26 @@ def plot_qq_all_models(all_results, cfg=None):
453
  ci_lo = -np.log10(stats.beta.ppf(0.975, np.arange(1, n+1), np.arange(n, 0, -1)))
454
  ci_hi = -np.log10(stats.beta.ppf(0.025, np.arange(1, n+1), np.arange(n, 0, -1)))
455
  col = MODEL_COLORS.get(mname, "#7C6FCD")
 
456
  ax.fill_between(exp, ci_lo, ci_hi, alpha=0.2, color=col)
457
- ax.scatter(exp, obs, c=col, s=cfg["marker_size"], alpha=cfg["alpha"], linewidths=0)
458
- ax.plot([0, max(exp)], [0, max(exp)], color=cfg["sig_color"], ls="--", lw=1.5, alpha=0.8)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
459
  lam = np.median(stats.chi2.ppf(1-np.clip(pvals,1e-10,1),df=1)) / stats.chi2.ppf(0.5, df=1)
460
  ax.text(0.05, 0.92, f"Ξ» = {lam:.4f}", transform=ax.transAxes,
461
  fontsize=cfg["font_size"]+1, color="#E15759", fontweight='bold')
@@ -470,13 +556,14 @@ def plot_qq_all_models(all_results, cfg=None):
470
  for idx in range(n_models, len(axes)):
471
  axes[idx].set_visible(False)
472
 
473
- fig.suptitle("QQ Plots β€” All Models", color=cfg["font_color"],
474
  fontsize=cfg["font_size"]+3, y=1.01, fontweight='bold')
475
  fig.tight_layout()
476
  return fig
477
 
478
 
479
  def plot_qq_overlay(all_results, cfg=None):
 
480
  if cfg is None:
481
  cfg = build_cfg(9, 9, 10, "#2D3142", "#E8ECF4", "#FFFFFF", "#FAFBFF",
482
  "#E15759", "#4E79A7", 18, 0.85)
@@ -490,14 +577,23 @@ def plot_qq_overlay(all_results, cfg=None):
490
  exp = -np.log10(np.linspace(1/n, 1, n)[::-1])
491
  exp_max = max(exp_max, max(exp))
492
  lam = np.median(stats.chi2.ppf(1-np.clip(pvals,1e-10,1),df=1)) / stats.chi2.ppf(0.5, df=1)
493
- ax.plot(exp, obs, color=MODEL_COLORS.get(mname, "#7C6FCD"),
494
- lw=2, label=f"{mname} (Ξ»={lam:.3f})", alpha=0.85)
495
- ax.plot([0, exp_max], [0, exp_max], color=cfg["sig_color"],
496
- ls="--", lw=1.5, label="Expected")
 
 
 
 
 
 
 
 
 
497
  ax.set_xlabel("Expected -log₁₀(p)", fontsize=cfg["font_size"], color=cfg["font_color"])
498
  ax.set_ylabel("Observed -log₁₀(p)", fontsize=cfg["font_size"], color=cfg["font_color"])
499
- ax.set_title("QQ Plot β€” All Models Overlay", color=cfg["font_color"],
500
- fontsize=cfg["font_size"]+2, fontweight='bold')
501
  ax.legend(fontsize=cfg["font_size"]-1, framealpha=0.85,
502
  facecolor=cfg["bg_color"], edgecolor="#CCCCCC", labelcolor=cfg["font_color"])
503
  ax.tick_params(colors=cfg["font_color"], labelsize=cfg["font_size"])
@@ -508,14 +604,15 @@ def plot_qq_overlay(all_results, cfg=None):
508
  return fig
509
 
510
 
 
511
  def plot_circos(all_results, chroms, positions, cfg=None, top_n=15):
512
  """
513
- Circos plot modeled after reference image:
514
- - White background
515
- - Outer chromosome bands with color
516
- - Concentric rings per model showing -log10(p)
517
- - Ribbons connecting top MTAs across chromosomes
518
- - No label overlap using smart angular placement
519
  """
520
  if cfg is None:
521
  cfg = build_cfg(14, 14, 8, "#2D3142", "#E8ECF4", "#FFFFFF", "#FFFFFF",
@@ -534,13 +631,12 @@ def plot_circos(all_results, chroms, positions, cfg=None, top_n=15):
534
  total_snps = len(chroms)
535
  sort_idx = np.lexsort((positions, chroms))
536
 
537
- # Build SNP angles based on sorted genomic position
538
  snp_angles = np.linspace(0, 2 * np.pi, total_snps, endpoint=False)
539
 
540
  # ── Outer chromosome band ──────────────────────────────────────────────────
541
  outer_r = 1.0
542
- band_h = 0.055
543
- label_r = outer_r + band_h + 0.07
544
 
545
  chrom_bounds = {}
546
  for ch in chrom_list:
@@ -552,16 +648,32 @@ def plot_circos(all_results, chroms, positions, cfg=None, top_n=15):
552
  theta_mid = (theta_start + theta_end) / 2
553
  chrom_bounds[ch] = (theta_start, theta_end, theta_mid, idxs_in_sorted)
554
  col = CHR_PALETTE[chrom_list.index(ch) % len(CHR_PALETTE)]
555
- span = snp_angles[1] - snp_angles[0] # angular width of one SNP
556
  bar_w = max(span * len(idxs_in_sorted) * 1.05,
557
  2 * np.pi / total_snps * 1.2)
558
  ax.bar(theta_mid, band_h, width=bar_w,
559
  bottom=outer_r, color=col, alpha=0.88,
560
- linewidth=0.5, edgecolor="white")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
561
 
562
- # ── Smart chromosome labels (no overlap) ──────────────────────────────────
563
  used_angles = []
564
- min_sep = 0.22 # radians
565
 
566
  def angle_free(a):
567
  for ua in used_angles:
@@ -574,7 +686,6 @@ def plot_circos(all_results, chroms, positions, cfg=None, top_n=15):
574
  if ch not in chrom_bounds: continue
575
  _, _, theta_mid, _ = chrom_bounds[ch]
576
  col = CHR_PALETTE[chrom_list.index(ch) % len(CHR_PALETTE)]
577
- # Nudge label angle if overlapping
578
  candidate = theta_mid
579
  for delta in np.linspace(0, np.pi, 60):
580
  for sign in [1, -1]:
@@ -586,11 +697,16 @@ def plot_circos(all_results, chroms, positions, cfg=None, top_n=15):
586
  continue
587
  break
588
  used_angles.append(candidate)
 
 
 
 
 
 
589
  ax.text(candidate, label_r,
590
  f"Chr{ch}", ha='center', va='center',
591
  fontsize=cfg["font_size"], color=col,
592
- fontweight='bold',
593
- rotation=np.degrees(candidate) - 90 if candidate < np.pi else np.degrees(candidate) + 90)
594
 
595
  # ── Per-model rings ────────────────────────────────────────────────────────
596
  model_names = list(all_results.keys())
@@ -599,27 +715,41 @@ def plot_circos(all_results, chroms, positions, cfg=None, top_n=15):
599
  ring_total = outer_r - 0.05 - 0.18
600
  ring_width = (ring_total - ring_gap * n_models) / max(n_models, 1)
601
 
602
- sig_line = -np.log10(5e-8)
603
-
604
  for midx, mname in enumerate(model_names):
605
  pvals, _, _ = all_results[mname]
606
  log_p = -np.log10(np.clip(pvals, 1e-300, 1))
607
  r_base = 0.18 + midx * (ring_width + ring_gap)
608
  r_max_data = ring_width * 0.85
609
  col = MODEL_COLORS.get(mname, CHR_PALETTE[midx % len(CHR_PALETTE)])
610
- max_lp = max(log_p.max(), sig_line, 1)
 
 
 
 
 
 
 
611
 
612
  # Ring baseline arc
613
  theta_arc = np.linspace(0, 2 * np.pi, 500)
614
  ax.plot(theta_arc, np.full_like(theta_arc, r_base),
615
  color=col, alpha=0.15, lw=0.8, zorder=1)
616
 
617
- lp_norm = log_p[sort_idx] / max_lp * r_max_data
 
 
 
 
 
 
 
 
 
618
 
619
- # Plot all SNPs as tiny dots
620
  ax.scatter(snp_angles, r_base + lp_norm,
621
  c=col, s=cfg["marker_size"]*0.5,
622
- alpha=cfg["alpha"]*0.7, linewidths=0, zorder=2)
623
 
624
  # Highlight top MTAs
625
  top_idx = get_top_mta(pvals, top_n)
@@ -633,15 +763,13 @@ def plot_circos(all_results, chroms, positions, cfg=None, top_n=15):
633
  zorder=12, marker='D',
634
  edgecolors='#333333', linewidth=0.5, alpha=0.95)
635
 
636
- # Model name label inside the ring
637
- ax.text(np.pi * 1.5,
638
- r_base + r_max_data * 0.35,
639
  mname, ha='center', va='center',
640
  fontsize=cfg["font_size"]-1, color=col,
641
  fontweight='bold', alpha=0.92)
642
 
643
- # ── Ribbons: connect top MTAs across chromosomes ───────────────────────────
644
- # Collect top MTAs from first model and draw connecting ribbons
645
  if len(all_results) > 0:
646
  first_model = model_names[0]
647
  pvals_first, _, _ = all_results[first_model]
@@ -655,48 +783,48 @@ def plot_circos(all_results, chroms, positions, cfg=None, top_n=15):
655
  for j, idx_j in enumerate(top_mta_idx):
656
  if j <= i: continue
657
  if chroms[idx_i] == chroms[idx_j]: continue
658
- # Find angular positions
659
  pos_i = np.where(sort_idx == idx_i)[0]
660
  pos_j = np.where(sort_idx == idx_j)[0]
661
  if len(pos_i) == 0 or len(pos_j) == 0: continue
662
  ang_i = snp_angles[pos_i[0]]
663
  ang_j = snp_angles[pos_j[0]]
664
- # Draw a bezier-like arc as a filled wedge at inner radius
665
  theta_ribbon = np.linspace(ang_i, ang_j, 30)
666
  col_r = CHR_PALETTE[chrom_list.index(chroms[idx_i]) % len(CHR_PALETTE)]
667
  ax.fill_between(theta_ribbon,
668
  np.full(30, ribbon_r * 0.4),
669
  np.full(30, ribbon_r),
670
  alpha=0.06, color=col_r, zorder=0)
671
- ax.plot(theta_ribbon,
672
- np.full(30, ribbon_r * 0.7),
673
  color=col_r, alpha=0.12, lw=0.8, zorder=1)
674
 
675
  # ── Legend ─────────────────────────────────────────────────────────────────
676
  legend_elements = [
677
- mpatches.Patch(facecolor=MODEL_COLORS.get(m, "#7C6FCD"),
678
- label=m, alpha=0.85)
679
  for m in model_names
680
  ]
681
- legend_elements.append(
682
- mpatches.Patch(facecolor=ACCENT_GOLD,
683
- label=f"Top {top_n} MTAs (β—†)", alpha=0.9)
684
- )
 
 
 
685
  ax.legend(handles=legend_elements,
686
- loc='lower center', bbox_to_anchor=(0.5, -0.06),
687
- ncol=min(4, n_models+1),
688
  fontsize=cfg["font_size"], framealpha=0.9,
689
  facecolor=cfg["bg_color"], edgecolor="#CCCCCC",
690
  labelcolor=cfg["font_color"])
691
 
692
  ax.set_title(
693
- f"Circos β€” Multi-Model GWAS | Ring height = -log₁₀(p) | β—† = Top {top_n} MTAs",
694
- color=cfg["font_color"], fontsize=cfg["font_size"]+2, pad=22, fontweight='bold'
695
  )
696
  fig.tight_layout()
697
  return fig
698
 
699
 
 
700
  def plot_ld_decay(G, positions, cfg=None):
701
  if cfg is None:
702
  cfg = build_cfg(16, 6, 9, "#2D3142", "#E8ECF4", "#FFFFFF", "#FAFBFF",
@@ -740,7 +868,8 @@ def plot_ld_decay(G, positions, cfg=None):
740
  return np.array(centers), np.array(means), np.array(sems)
741
 
742
  for i, (dist_arr, xlabel, title_str, dot_col, line_col) in enumerate([
743
- (dists_bp, "Distance (bp)", "LD Decay β€” Base Pairs (bp)", "#4E79A7", "#E15759"),
 
744
  (dists_mb, "Distance (Mb)", "LD Decay β€” Megabases (Mb)", "#59A14F", "#F28E2B"),
745
  ]):
746
  ax = axes[i]
@@ -773,12 +902,31 @@ def plot_ld_decay(G, positions, cfg=None):
773
  return fig
774
 
775
 
 
776
  def plot_pca(G, y, ids, cfg=None):
 
 
 
 
777
  if cfg is None:
778
- cfg = build_cfg(14, 12, 9, "#2D3142", "#E8ECF4", "#FFFFFF", "#FAFBFF",
779
- "#E15759", "#4E79A7", 60, 0.75)
780
- fig, axes = plt.subplots(2, 2, figsize=(cfg["width"], cfg["height"]))
781
- fig.patch.set_facecolor(cfg["bg_color"])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
782
  axes = axes.flatten()
783
 
784
  G_sc = StandardScaler().fit_transform(G)
@@ -788,58 +936,58 @@ def plot_pca(G, y, ids, cfg=None):
788
  var_exp = pca.explained_variance_ratio_ * 100
789
 
790
  for ax in axes:
791
- ax.set_facecolor(cfg["panel_color"])
792
- for spine in ax.spines.values(): spine.set_edgecolor("#CCCCCC")
793
- ax.grid(color=cfg["grid_color"], linewidth=0.4, linestyle="--", alpha=0.6)
794
- ax.tick_params(colors=cfg["font_color"], labelsize=cfg["font_size"]-1)
 
795
 
796
- sc = axes[0].scatter(pcs[:,0], pcs[:,1], c=y, cmap='RdYlBu_r',
 
797
  s=cfg["marker_size"], edgecolors='none', alpha=cfg["alpha"])
798
- axes[0].set_xlabel(f"PC1 ({var_exp[0]:.1f}%)", fontsize=cfg["font_size"],
799
- color=cfg["font_color"])
800
- axes[0].set_ylabel(f"PC2 ({var_exp[1]:.1f}%)", fontsize=cfg["font_size"],
801
- color=cfg["font_color"])
802
- axes[0].set_title("PCA: PC1 vs PC2", color=cfg["font_color"],
803
- fontsize=cfg["font_size"]+1, fontweight='bold')
804
  cbar = plt.colorbar(sc, ax=axes[0])
805
- cbar.set_label("Phenotype", color=cfg["font_color"], fontsize=cfg["font_size"]-1)
806
- cbar.ax.tick_params(colors=cfg["font_color"])
807
-
808
- if n_comp >= 4:
809
- axes[1].scatter(pcs[:,2], pcs[:,3], c=y, cmap='RdYlBu_r',
810
- s=cfg["marker_size"], edgecolors='none', alpha=cfg["alpha"])
811
- axes[1].set_xlabel(f"PC3 ({var_exp[2]:.1f}%)", fontsize=cfg["font_size"],
812
- color=cfg["font_color"])
813
- axes[1].set_ylabel(f"PC4 ({var_exp[3]:.1f}%)", fontsize=cfg["font_size"],
814
- color=cfg["font_color"])
815
- axes[1].set_title("PCA: PC3 vs PC4", color=cfg["font_color"],
816
- fontsize=cfg["font_size"]+1, fontweight='bold')
817
-
818
- axes[2].bar(range(1, n_comp+1), var_exp, color="#4E79A7",
819
- edgecolor='white', alpha=0.85, linewidth=0.5)
820
- axes[2].plot(range(1, n_comp+1), np.cumsum(var_exp),
821
- color="#E15759", marker='o', lw=2, ms=5, label="Cumulative")
822
- axes[2].set_xlabel("Principal Component", fontsize=cfg["font_size"],
823
- color=cfg["font_color"])
824
- axes[2].set_ylabel("Variance Explained (%)", fontsize=cfg["font_size"],
825
- color=cfg["font_color"])
826
- axes[2].set_title("Scree Plot", color=cfg["font_color"],
827
- fontsize=cfg["font_size"]+1, fontweight='bold')
828
- axes[2].legend(fontsize=cfg["font_size"]-1, facecolor=cfg["bg_color"],
829
- edgecolor="#CCCCCC", labelcolor=cfg["font_color"])
830
-
831
- axes[3].scatter(pcs[:,0], pcs[:,1], c=y, cmap='RdYlBu_r',
832
- s=cfg["marker_size"], edgecolors='none', alpha=cfg["alpha"])
833
- axes[3].set_title("Population Structure (PC1 vs PC2)",
834
- color=cfg["font_color"], fontsize=cfg["font_size"]+1, fontweight='bold')
835
-
836
- fig.suptitle("Principal Component Analysis", color=cfg["font_color"],
837
- fontsize=cfg["font_size"]+3, fontweight='bold')
838
  fig.tight_layout()
839
  return fig
840
 
841
 
 
842
  def plot_model_comparison_manhattan(all_results, chroms, positions, cfg=None, top_n=15):
 
843
  if cfg is None:
844
  cfg = build_cfg(16, 3.5, 7, "#2D3142", "#E8ECF4", "#FFFFFF", "#FAFBFF",
845
  "#E15759", "#4E79A7", 6, 0.65)
@@ -871,26 +1019,39 @@ def plot_model_comparison_manhattan(all_results, chroms, positions, cfg=None, to
871
  mask = chroms == ch
872
  if mask.sum() > 0:
873
  tick_pos.append(x_coords[mask].mean())
874
- tick_lab.append(f"Chr{ch}")
875
 
876
  for midx, (mname, (pvals, _, _)) in enumerate(all_results.items()):
877
  ax = axes[midx]
878
  ax.set_facecolor(cfg["panel_color"])
879
  log_p = -np.log10(np.clip(pvals, 1e-300, 1))
880
  col = MODEL_COLORS.get(mname, CHR_PALETTE[midx % len(CHR_PALETTE)])
 
 
 
 
 
 
881
  for ch in chrom_list:
882
  mask = chroms == ch
883
  ax.scatter(x_coords[mask], log_p[mask],
884
  c=col, s=cfg["marker_size"], alpha=cfg["alpha"], linewidths=0)
 
885
  top_idx = get_top_mta(pvals, top_n)
886
  ax.scatter(x_coords[top_idx], log_p[top_idx],
887
  c=ACCENT_GOLD, s=max(cfg["marker_size"]*4, 35),
888
  zorder=10, linewidths=0.7, edgecolors='#333333',
889
  marker='D', label=f"Top {top_n} MTAs")
890
- ax.axhline(-np.log10(5e-8), color=cfg["sig_color"],
891
- ls='--', lw=1, alpha=0.8, label="5e-8")
892
- ax.set_ylabel("-log₁₀(p)", fontsize=cfg["font_size"],
893
- color=cfg["font_color"])
 
 
 
 
 
 
894
  ax.set_title(f"Model: {mname}", color=col,
895
  fontsize=cfg["font_size"]+1, pad=3, fontweight='bold')
896
  ax.set_xticks(tick_pos)
@@ -901,7 +1062,7 @@ def plot_model_comparison_manhattan(all_results, chroms, positions, cfg=None, to
901
  ax.tick_params(colors=cfg["font_color"], labelsize=cfg["font_size"]-1)
902
  ax.legend(fontsize=cfg["font_size"]-2, framealpha=0.85,
903
  facecolor=cfg["bg_color"], edgecolor="#CCCCCC",
904
- labelcolor=cfg["font_color"])
905
  for spine in ax.spines.values(): spine.set_edgecolor("#CCCCCC")
906
  ax.grid(color=cfg["grid_color"], linewidth=0.3, linestyle="--", alpha=0.5)
907
 
@@ -912,6 +1073,7 @@ def plot_model_comparison_manhattan(all_results, chroms, positions, cfg=None, to
912
  return fig
913
 
914
 
 
915
  def plot_kinship(K, ids, cfg=None):
916
  if cfg is None:
917
  cfg = build_cfg(14, 12, 9, "#2D3142", "#E8ECF4", "#FFFFFF", "#FAFBFF",
@@ -932,7 +1094,8 @@ def plot_kinship(K, ids, cfg=None):
932
  cbar.ax.tick_params(colors=cfg["font_color"])
933
 
934
  K_flat = K[np.triu_indices_from(K, k=1)]
935
- axes[1].hist(K_flat, bins=30, color="#4E79A7", edgecolor='white', alpha=0.85)
 
936
  axes[1].set_title("Pairwise Kinship Distribution", color=cfg["font_color"],
937
  fontsize=cfg["font_size"]+1, fontweight='bold')
938
  axes[1].set_xlabel("Kinship Coefficient", fontsize=cfg["font_size"],
@@ -940,13 +1103,10 @@ def plot_kinship(K, ids, cfg=None):
940
  axes[1].set_ylabel("Count", fontsize=cfg["font_size"], color=cfg["font_color"])
941
  axes[1].grid(color=cfg["grid_color"], linewidth=0.4, linestyle="--", alpha=0.6)
942
 
943
- # ── Improved dendrogram: no overlapping for large datasets ───────────────
944
  try:
945
  lm = linkage(K, method='ward')
946
  n_samples = len(ids)
947
- # Dynamic font size: reduce for large datasets
948
  leaf_fs = max(3, min(cfg["font_size"]-1, int(200 / max(n_samples, 1))))
949
- # Truncate dendrogram for very large datasets
950
  truncate_mode = None
951
  p_param = None
952
  if n_samples > 50:
@@ -971,7 +1131,6 @@ def plot_kinship(K, ids, cfg=None):
971
  dend_kwargs["truncate_mode"] = truncate_mode
972
  dend_kwargs["p"] = p_param
973
  else:
974
- # For small datasets show actual labels (truncated to 10 chars)
975
  short_labels = [str(x)[:10] for x in ids]
976
  dend_kwargs["labels"] = short_labels
977
 
@@ -979,9 +1138,10 @@ def plot_kinship(K, ids, cfg=None):
979
  axes[2].tick_params(axis='x', labelsize=leaf_fs, colors=cfg["font_color"])
980
  axes[2].tick_params(axis='y', labelsize=cfg["font_size"]-2,
981
  colors=cfg["font_color"])
982
- # Remove clutter for large datasets
983
  if n_samples > 50:
984
  axes[2].set_xticks([])
 
 
985
  except Exception as e:
986
  axes[2].text(0.5, 0.5, f"Dendrogram\nunavailable:\n{str(e)[:40]}",
987
  ha='center', va='center', transform=axes[2].transAxes,
@@ -990,7 +1150,7 @@ def plot_kinship(K, ids, cfg=None):
990
  eigvals, eigvecs = np.linalg.eigh(K)
991
  idx = np.argsort(eigvals)[::-1]
992
  axes[3].scatter(eigvecs[:,idx[0]], eigvecs[:,idx[1]],
993
- c="#4E79A7", s=cfg["marker_size"],
994
  edgecolors='none', alpha=cfg["alpha"])
995
  axes[3].set_title("Kinship PCA", color=cfg["font_color"],
996
  fontsize=cfg["font_size"]+1, fontweight='bold')
@@ -1004,6 +1164,7 @@ def plot_kinship(K, ids, cfg=None):
1004
  return fig
1005
 
1006
 
 
1007
  def plot_effect_sizes(pvals, betas, snp_names, cfg=None, top_n=15):
1008
  if cfg is None:
1009
  cfg = build_cfg(14, 10, 9, "#2D3142", "#E8ECF4", "#FFFFFF", "#FAFBFF",
@@ -1021,9 +1182,10 @@ def plot_effect_sizes(pvals, betas, snp_names, cfg=None, top_n=15):
1021
  top_idx = get_top_mta(pvals, top_n)
1022
  top_betas = betas[top_idx]
1023
  top_names = [str(snp_names[i])[:18] for i in top_idx]
1024
- colors = ["#E15759" if b < 0 else "#4E79A7" for b in top_betas]
 
 
1025
 
1026
- # Sort by beta for clean bar chart
1027
  order = np.argsort(top_betas)
1028
  axes[0].barh([top_names[o] for o in order], [top_betas[o] for o in order],
1029
  color=[colors[o] for o in order], edgecolor='white', linewidth=0.4)
@@ -1036,7 +1198,7 @@ def plot_effect_sizes(pvals, betas, snp_names, cfg=None, top_n=15):
1036
 
1037
  log_p = -np.log10(np.clip(pvals, 1e-300, 1))
1038
  sig_thr = -np.log10(0.05/len(pvals))
1039
- pt_colors = ["#E15759" if lp >= sig_thr else ("#4E79A7" if b > 0 else "#59A14F")
1040
  for lp, b in zip(log_p, betas)]
1041
  axes[1].scatter(betas, log_p, c=pt_colors, s=cfg["marker_size"],
1042
  alpha=cfg["alpha"], linewidths=0)
@@ -1049,7 +1211,8 @@ def plot_effect_sizes(pvals, betas, snp_names, cfg=None, top_n=15):
1049
  axes[1].legend(fontsize=cfg["font_size"]-1, facecolor=cfg["bg_color"],
1050
  edgecolor="#CCCCCC", labelcolor=cfg["font_color"])
1051
 
1052
- axes[2].hist(betas, bins=25, color="#4E79A7", edgecolor='white', alpha=0.85)
 
1053
  axes[2].axvline(0, color=cfg["sig_color"], lw=2, ls='--')
1054
  axes[2].set_xlabel("Ξ²", fontsize=cfg["font_size"], color=cfg["font_color"])
1055
  axes[2].set_title("Effect Size Distribution", color=cfg["font_color"],
@@ -1077,7 +1240,9 @@ def plot_effect_sizes(pvals, betas, snp_names, cfg=None, top_n=15):
1077
  return fig
1078
 
1079
 
 
1080
  def plot_summary_dashboard(y, maf, all_results, G_filt, cfg=None):
 
1081
  if cfg is None:
1082
  cfg = build_cfg(15, 10, 9, "#2D3142", "#E8ECF4", "#FFFFFF", "#FAFBFF",
1083
  "#E15759", "#4E79A7", 30, 0.75)
@@ -1091,7 +1256,9 @@ def plot_summary_dashboard(y, maf, all_results, G_filt, cfg=None):
1091
  ax.tick_params(colors=cfg["font_color"], labelsize=cfg["font_size"]-1)
1092
  ax.grid(color=cfg["grid_color"], linewidth=0.4, linestyle="--", alpha=0.6)
1093
 
1094
- axes[0].hist(y, bins=15, color="#4E79A7", edgecolor='white', alpha=0.85)
 
 
1095
  axes[0].axvline(y.mean(), color=cfg["sig_color"], lw=2, ls='--',
1096
  label=f"Mean: {y.mean():.2f}")
1097
  axes[0].set_title(f"Phenotype Distribution | n={len(y)}",
@@ -1101,6 +1268,7 @@ def plot_summary_dashboard(y, maf, all_results, G_filt, cfg=None):
1101
  axes[0].set_xlabel("Phenotype Value", fontsize=cfg["font_size"], color=cfg["font_color"])
1102
  axes[0].set_ylabel("Count", fontsize=cfg["font_size"], color=cfg["font_color"])
1103
 
 
1104
  axes[1].hist(maf, bins=20, color="#59A14F", edgecolor='white', alpha=0.85)
1105
  axes[1].axvline(0.05, color=cfg["sig_color"], ls='--', lw=1.5,
1106
  label=f"MAF=0.05 (rare: {np.sum(maf<0.05)})")
@@ -1111,6 +1279,7 @@ def plot_summary_dashboard(y, maf, all_results, G_filt, cfg=None):
1111
  axes[1].set_xlabel("MAF", fontsize=cfg["font_size"], color=cfg["font_color"])
1112
  axes[1].set_ylabel("Count", fontsize=cfg["font_size"], color=cfg["font_color"])
1113
 
 
1114
  lambdas = {}
1115
  for mname, (p, _, _) in all_results.items():
1116
  lam = np.median(stats.chi2.ppf(1-np.clip(p,1e-10,1),df=1)) / stats.chi2.ppf(0.5,df=1)
@@ -1129,6 +1298,7 @@ def plot_summary_dashboard(y, maf, all_results, G_filt, cfg=None):
1129
  f"{lv:.3f}", ha='center', fontsize=cfg["font_size"]-2,
1130
  color=cfg["font_color"], va='bottom')
1131
 
 
1132
  sig_counts = {}
1133
  for mname, (p, _, _) in all_results.items():
1134
  bonf = 0.05 / len(p)
@@ -1141,6 +1311,7 @@ def plot_summary_dashboard(y, maf, all_results, G_filt, cfg=None):
1141
  axes[3].tick_params(axis='x', rotation=30, labelsize=cfg["font_size"])
1142
  axes[3].set_ylabel("Count", fontsize=cfg["font_size"], color=cfg["font_color"])
1143
 
 
1144
  n_m = len(all_results)
1145
  model_names = list(all_results.keys())
1146
  concordance = np.eye(n_m)
@@ -1167,27 +1338,40 @@ def plot_summary_dashboard(y, maf, all_results, G_filt, cfg=None):
1167
  axes[4].set_title("Model Concordance (Spearman ρ)",
1168
  color=cfg["font_color"], fontsize=cfg["font_size"]+1, fontweight='bold')
1169
 
1170
- first_model = model_names[0]
1171
- lam_v = lambdas[first_model]
1172
- axes[5].set_facecolor(cfg["panel_color"])
1173
  axes[5].axis('off')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1174
  summary_text = (
1175
  f"GWAS Summary\n\n"
1176
  f"Samples: {G_filt.shape[0]}\n"
1177
  f"SNPs (filt.): {G_filt.shape[1]}\n"
1178
  f"Models run: {n_m}\n"
1179
  f"Missing rate: {np.isnan(G_filt).mean():.1%}\n\n"
1180
- f"─────────────────────\n"
1181
- + "\n".join([f" {m}: Ξ»={lambdas[m]:.3f} sig={sig_counts[m]}"
1182
- for m in model_names])
1183
  )
1184
- axes[5].text(0.08, 0.92, summary_text,
1185
  ha='left', va='top', transform=axes[5].transAxes,
1186
- color=cfg["font_color"], fontsize=cfg["font_size"],
1187
  fontfamily='monospace',
1188
  bbox=dict(boxstyle='round,pad=0.8', facecolor=cfg["panel_color"],
1189
  edgecolor="#CCCCCC", alpha=0.9))
1190
- axes[5].set_title("Pipeline Summary", color=cfg["font_color"],
1191
  fontsize=cfg["font_size"]+1, fontweight='bold')
1192
 
1193
  fig.suptitle("GWAS Analysis Dashboard",
@@ -1219,25 +1403,61 @@ def export_results_excel(all_results, snp_filt, chr_filt, pos_filt, y,
1219
  ws_sum['A1'] = f"GWAS Complete Analysis Summary β€” Top {top_n} MTAs per Model"
1220
  ws_sum['A1'].font = Font(bold=True, color="2C5F8A", name="Calibri", size=16)
1221
  ws_sum.merge_cells('A1:H1')
1222
- headers_sum = ["Model", "N_SNPs_Tested", "Bonferroni_Threshold", "Sig_SNPs_Bonferroni",
1223
- "Sig_SNPs_5e8", "Genomic_Lambda", "Min_Pvalue", "Max_AbsBeta"]
 
1224
  for col, h in enumerate(headers_sum, 1):
1225
  cell = ws_sum.cell(row=3, column=col, value=h)
1226
  cell.font = header_font; cell.fill = header_fill
1227
  cell.alignment = Alignment(horizontal='center'); cell.border = thin_border
1228
- ws_sum.column_dimensions[get_column_letter(col)].width = 22
1229
  for row_i, (mname, (pvals, betas, ses)) in enumerate(all_results.items(), 4):
1230
  lam = np.median(stats.chi2.ppf(1-np.clip(pvals,1e-10,1),df=1)) / stats.chi2.ppf(0.5,df=1)
1231
- sig_bonf = int((pvals < bonf).sum())
1232
- sig_5e8 = int((pvals < 5e-8).sum())
1233
- row_data = [mname, len(pvals), f"{bonf:.2e}", sig_bonf, sig_5e8,
1234
- round(float(lam),4), float(np.min(pvals)), round(float(np.max(np.abs(betas))),5)]
 
 
 
1235
  fill = alt_fill if row_i%2==0 else PatternFill("solid",start_color="FFFFFF",end_color="FFFFFF")
1236
  for col, val in enumerate(row_data, 1):
1237
  cell = ws_sum.cell(row=row_i, column=col, value=val)
1238
  cell.fill = fill; cell.border = thin_border
1239
  cell.alignment = Alignment(horizontal='center')
1240
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1241
  # Sheet per model: Top N MTAs
1242
  for mname, (pvals, betas, ses) in all_results.items():
1243
  ws = wb.create_sheet(title=f"{mname}_Top{top_n}MTAs")
@@ -1423,22 +1643,23 @@ def save_all_plots_zip(plot_dict, out_dir):
1423
  def run_gwas(file_obj, text_input, selected_models, maf_threshold, top_n,
1424
  # Manhattan cfg
1425
  mh_w, mh_h, mh_fs, mh_fc, mh_ms, mh_alpha, mh_bg, mh_sig, mh_sug,
 
1426
  # QQ cfg
1427
- qq_w, qq_h, qq_fs, qq_fc, qq_ms,
1428
  # Circos cfg
1429
- ci_w, ci_h, ci_fs,
1430
  # LD cfg
1431
- ld_w, ld_h, ld_fs,
1432
- # PCA cfg
1433
  pc_w, pc_h, pc_fs,
1434
  # Kinship cfg
1435
- ki_w, ki_h, ki_fs,
1436
  # Effect cfg
1437
- ef_w, ef_h, ef_fs,
1438
  # Comparison cfg
1439
- co_w, co_h,
1440
  # Dashboard cfg
1441
- db_w, db_h):
1442
 
1443
  try:
1444
  df, snp_cols, chroms, positions = parse_data(file_obj, text_input)
@@ -1494,23 +1715,32 @@ def run_gwas(file_obj, text_input, selected_models, maf_threshold, top_n,
1494
 
1495
  top_n = int(top_n)
1496
 
1497
- # ── Build per-plot configs from user inputs ───────────────────��───────────
1498
  def mkc(w, h, fs, fc="#2D3142", gc="#E8ECF4", bg="#FFFFFF",
1499
- panel="#FAFBFF", sig="#E15759", sug="#4E79A7", ms=12, al=0.75):
1500
- return build_cfg(w, h, fs, fc, gc, bg, panel, sig, sug, ms, al)
1501
-
1502
- cfg_mh = mkc(mh_w, mh_h, mh_fs, mh_fc, sig=mh_sig, sug=mh_sug,
1503
- ms=mh_ms, al=mh_alpha)
1504
- cfg_qq = mkc(qq_w, qq_h, qq_fs, qq_fc, ms=qq_ms)
1505
- cfg_ci = mkc(ci_w, ci_h, ci_fs)
1506
- cfg_ld = mkc(ld_w, ld_h, ld_fs)
1507
- cfg_pc = mkc(pc_w, pc_h, pc_fs)
1508
- cfg_ki = mkc(ki_w, ki_h, ki_fs)
1509
- cfg_ef = mkc(ef_w, ef_h, ef_fs)
1510
- cfg_co = mkc(co_w, co_h, 7)
1511
- cfg_db = mkc(db_w, db_h, 9)
1512
-
1513
- # ── Generate all plots ────────────────────────────────────────────────────
 
 
 
 
 
 
 
 
 
1514
  plot_dict = {}
1515
  plot_dict["01_Manhattan_Primary"] = plot_manhattan(
1516
  primary_p, chr_filt, pos_filt,
@@ -1534,7 +1764,7 @@ def run_gwas(file_obj, text_input, selected_models, maf_threshold, top_n,
1534
 
1535
  imgs = [_pil(plot_dict[k]) for k in sorted(plot_dict.keys())]
1536
 
1537
- # ── Save ──────────────────────────────────────────────────────────────────
1538
  tmp_dir = tempfile.mkdtemp()
1539
  zip_path = save_all_plots_zip(plot_dict, tmp_dir)
1540
  excel_path = os.path.join(tmp_dir, "gwas_results_top15.xlsx")
@@ -1542,10 +1772,16 @@ def run_gwas(file_obj, text_input, selected_models, maf_threshold, top_n,
1542
  y, G_filt, maf_vals, excel_path, top_n)
1543
  plt.close('all')
1544
 
 
 
 
 
 
 
1545
  bonf = 0.05 / len(primary_p)
1546
  lambdas_str = "\n ".join([
1547
  f"{m}: Ξ»={np.median(stats.chi2.ppf(1-np.clip(p,1e-10,1),df=1))/stats.chi2.ppf(0.5,df=1):.4f} "
1548
- f"sig(Bonf)={int((p<bonf).sum())} sig(5e-8)={int((p<5e-8).sum())}"
1549
  for m, (p, _, _) in all_results.items()
1550
  ])
1551
  lam = (np.median(stats.chi2.ppf(1-np.clip(primary_p,1e-10,1),df=1)) /
@@ -1561,10 +1797,15 @@ def run_gwas(file_obj, text_input, selected_models, maf_threshold, top_n,
1561
  f" PER-MODEL RESULTS:\n {lambdas_str}\n"
1562
  f"{'─'*68}\n"
1563
  f" Primary model ({models_to_run[0]}):\n"
1564
- f" Bonferroni threshold : {bonf:.2e}\n"
1565
- f" Significant MTAs : {int((primary_p<bonf).sum())}\n"
 
 
1566
  f" Genomic Inflation Ξ» : {lam:.4f}\n"
1567
  f"{'─'*68}\n"
 
 
 
1568
  f" πŸ“₯ Excel: gwas_results_top15.xlsx\n"
1569
  f" πŸ–Ό Plots: gwas_plots.zip ({len(plot_dict)} PNG files)\n"
1570
  f"{'='*68}\n"
@@ -1580,7 +1821,7 @@ CSS = """
1580
  body, .gradio-container { background:#F7F8FC!important; font-family:'DM Sans',sans-serif!important; color:#2D3142!important; }
1581
  .gradio-container { max-width:1500px!important; margin:0 auto!important; }
1582
  .gwas-header { background:linear-gradient(135deg,#E8F4FD 0%,#EDE9F8 50%,#FDF0F8 100%); border:1px solid #D6E8F5; border-radius:18px; padding:24px 32px; margin-bottom:20px; box-shadow:0 2px 20px rgba(100,120,200,0.08); }
1583
- .gwas-header h1 { font-size:24px!important; font-weight:600!important; color:#2C5F8A!important; margin:0 0 4px 0!important; }
1584
  .gwas-header p { color:#6B7A99!important; font-size:13px!important; margin:3px 0!important; }
1585
  .gr-panel, .gr-box, .block, .panel { background:#FFFFFF!important; border:1px solid #E8ECF4!important; border-radius:14px!important; box-shadow:0 1px 8px rgba(60,80,140,0.06)!important; }
1586
  label, .label-wrap span { color:#5A6480!important; font-size:11px!important; font-weight:500!important; text-transform:uppercase!important; letter-spacing:0.5px!important; }
@@ -1589,7 +1830,7 @@ button.primary { background:linear-gradient(135deg,#5BA8E5 0%,#7C6FCD 100%)!impo
1589
  .tab-nav { background:#F0F3FB!important; border-radius:10px!important; padding:3px!important; border:1px solid #E4E8F5!important; overflow-x:auto!important; }
1590
  .tab-nav button { color:#6B7A99!important; font-size:11px!important; font-weight:500!important; border-radius:8px!important; padding:6px 12px!important; border:none!important; background:transparent!important; white-space:nowrap!important; }
1591
  .tab-nav button.selected, .tab-nav button:hover { background:#FFFFFF!important; color:#5BA8E5!important; box-shadow:0 1px 6px rgba(91,168,229,0.2)!important; }
1592
- .summary-box textarea { font-family:'DM Mono',monospace!important; font-size:11px!important; background:#F8F9FF!important; }
1593
  ::-webkit-scrollbar { width:5px; height:5px; }
1594
  ::-webkit-scrollbar-thumb { background:#C8D0E7; border-radius:4px; }
1595
  .cfg-panel { background:#F4F6FF!important; border-radius:10px!important; padding:10px!important; border:1px solid #DDE2F0!important; }
@@ -1609,18 +1850,17 @@ IRRI-42,30.67,0,0,0,0
1609
  IRRI-50,22,0,0,0,2"""
1610
 
1611
  # ─────────────────────── GRADIO INTERFACE ────────────────────────────────────────
1612
- with gr.Blocks(css=CSS, title="🧬 GWAS Pipeline v2", theme=gr.themes.Base()) as demo:
1613
 
1614
  gr.HTML("""
1615
  <div class="gwas-header">
1616
- <h1>🧬 GWAS Analysis Pipeline β€” 5 Efficient Models Β· Top 15 MTAs Β· White Plots Β· Full Customization</h1>
1617
- <p>OLS Β· MLM Β· EMMAX Β· FarmCPU Β· GEMMA &nbsp;|&nbsp; Circos with Ribbons Β· Anti-overlap Labels Β· Dendogram Auto-truncation</p>
1618
- <p style="font-size:12px;color:#8892B0;">Per-model: MTA Β· PVE Β· QTN Β· Beta Β· SE Β· T-stat Β· FDR Β· Bonferroni Β· 95% CI Β· Excel Export</p>
1619
  </div>
1620
  """)
1621
 
1622
  with gr.Row(equal_height=False):
1623
- # ── Left: Data + Models ───────────────────────────────────────────────
1624
  with gr.Column(scale=1, min_width=300):
1625
  gr.HTML('<div style="font-size:11px;font-weight:600;color:#8892B0;text-transform:uppercase;letter-spacing:1px;padding:6px 0 3px;border-bottom:1px solid #E8ECF4;margin-bottom:8px">πŸ“‚ Data Input</div>')
1626
  file_in = gr.File(label="Upload CSV / TSV / TXT", file_types=[".csv",".tsv",".txt"])
@@ -1636,127 +1876,161 @@ with gr.Blocks(css=CSS, title="🧬 GWAS Pipeline v2", theme=gr.themes.Base()) a
1636
  run_btn = gr.Button("πŸš€ Run Complete GWAS Pipeline", variant="primary")
1637
 
1638
  gr.HTML('<div style="font-size:11px;font-weight:600;color:#8892B0;text-transform:uppercase;letter-spacing:1px;padding:6px 0 3px;border-bottom:1px solid #E8ECF4;margin-bottom:8px;margin-top:12px">πŸ“₯ Downloads</div>')
1639
- excel_out = gr.File(label="πŸ“Š Excel (Top MTAs Β· PVE Β· QTN Β· All Models)", interactive=False)
1640
  zip_out = gr.File(label="πŸ–Ό All Plots as PNG (ZIP)", interactive=False)
1641
 
1642
- # ── Right: Summary ────────────────────────────────────────────────────
1643
  with gr.Column(scale=2):
1644
- gr.HTML('<div style="font-size:11px;font-weight:600;color:#8892B0;text-transform:uppercase;letter-spacing:1px;padding:6px 0 3px;border-bottom:1px solid #E8ECF4;margin-bottom:8px">πŸ“Š Analysis Summary</div>')
1645
- summary_out = gr.Textbox(label="", lines=24, show_label=False)
1646
 
1647
- # ── Plot Customization Panels (Accordions) ────────────────────────────────
1648
- gr.HTML('<div style="font-size:11px;font-weight:600;color:#8892B0;text-transform:uppercase;letter-spacing:1px;padding:12px 0 4px;border-bottom:1px solid #E8ECF4;margin-bottom:8px">🎨 Plot Customization</div>')
1649
 
1650
  with gr.Accordion("πŸ—Ί Manhattan Plot Options", open=False):
 
1651
  with gr.Row():
1652
  mh_w = gr.Slider(8, 24, 16, 1, label="Width")
1653
  mh_h = gr.Slider(3, 12, 5, 0.5, label="Height")
1654
  mh_fs = gr.Slider(6, 18, 9, 1, label="Font Size")
1655
  with gr.Row():
1656
  mh_fc = gr.ColorPicker(value="#2D3142", label="Font Color")
1657
- mh_sig = gr.ColorPicker(value="#E15759", label="Sig Line Color")
1658
  mh_sug = gr.ColorPicker(value="#4E79A7", label="Suggestive Line Color")
1659
  with gr.Row():
1660
- mh_ms = gr.Slider(2, 60, 12, 1, label="Marker Size")
1661
  mh_alpha= gr.Slider(0.1, 1.0, 0.75, 0.05, label="Marker Alpha")
 
1662
  mh_bg = gr.ColorPicker(value="#FFFFFF", label="Background Color")
 
 
1663
 
1664
  with gr.Accordion("πŸ“ˆ QQ Plot Options", open=False):
 
1665
  with gr.Row():
1666
  qq_w = gr.Slider(5, 16, 7, 0.5, label="Width")
1667
  qq_h = gr.Slider(5, 16, 7, 0.5, label="Height")
1668
  qq_fs = gr.Slider(6, 18, 10, 1, label="Font Size")
1669
  with gr.Row():
1670
- qq_fc = gr.ColorPicker(value="#2D3142", label="Font Color")
1671
- qq_ms = gr.Slider(5, 80, 22, 1, label="Marker Size")
 
 
 
 
 
 
 
1672
 
1673
  with gr.Accordion("πŸ”΅ Circos Plot Options", open=False):
 
1674
  with gr.Row():
1675
- ci_w = gr.Slider(8, 22, 14, 1, label="Width")
1676
- ci_h = gr.Slider(8, 22, 14, 1, label="Height")
1677
- ci_fs = gr.Slider(5, 16, 8, 1, label="Font Size")
 
 
 
1678
 
1679
  with gr.Accordion("πŸ”— LD Decay Options", open=False):
1680
  with gr.Row():
1681
- ld_w = gr.Slider(8, 24, 16, 1, label="Width")
1682
- ld_h = gr.Slider(3, 12, 6, 0.5,label="Height")
1683
- ld_fs = gr.Slider(6, 18, 9, 1, label="Font Size")
 
 
 
1684
 
1685
- with gr.Accordion("πŸ”¬ PCA Options", open=False):
 
1686
  with gr.Row():
1687
- pc_w = gr.Slider(8, 22, 14, 1, label="Width")
1688
- pc_h = gr.Slider(6, 20, 12, 1, label="Height")
1689
- pc_fs = gr.Slider(6, 18, 9, 1, label="Font Size")
1690
 
1691
  with gr.Accordion("πŸ‘¨β€πŸ‘©β€πŸ‘§ Kinship / Dendrogram Options", open=False):
 
 
 
 
 
1692
  with gr.Row():
1693
- ki_w = gr.Slider(8, 22, 14, 1, label="Width")
1694
- ki_h = gr.Slider(6, 20, 12, 1, label="Height")
1695
- ki_fs = gr.Slider(6, 18, 9, 1, label="Font Size")
1696
- gr.HTML('<p style="font-size:11px;color:#8892B0;">ℹ️ For >50 samples, dendrogram auto-truncates to last 30 nodes to avoid overlap.</p>')
1697
 
1698
  with gr.Accordion("βš– Effect Sizes Options", open=False):
1699
  with gr.Row():
1700
- ef_w = gr.Slider(8, 22, 14, 1, label="Width")
1701
- ef_h = gr.Slider(5, 18, 10, 1, label="Height")
1702
- ef_fs = gr.Slider(6, 18, 9, 1, label="Font Size")
 
 
 
 
 
1703
 
1704
  with gr.Accordion("πŸ”„ All-Models Manhattan Options", open=False):
 
 
 
 
1705
  with gr.Row():
1706
- co_w = gr.Slider(8, 24, 16, 1, label="Width")
1707
- co_h = gr.Slider(2, 8, 3.5, 0.5, label="Height per model")
1708
 
1709
  with gr.Accordion("πŸ“Š Dashboard Options", open=False):
1710
  with gr.Row():
1711
- db_w = gr.Slider(8, 24, 15, 1, label="Width")
1712
- db_h = gr.Slider(5, 18, 10, 1, label="Height")
 
1713
 
1714
  # ── Visualization Tabs ────────────────────────────────────────────────────
1715
  gr.HTML('<div style="font-size:11px;font-weight:600;color:#8892B0;text-transform:uppercase;letter-spacing:1px;padding:12px 0 4px;border-bottom:1px solid #E8ECF4;margin-bottom:8px">πŸ–Ό Visualizations</div>')
1716
  with gr.Tabs():
1717
  with gr.Tab("πŸ—Ί Manhattan"):
1718
- img1 = gr.Image(type="pil", label="Manhattan β€” Primary Model (β—† = Top MTAs)")
1719
  with gr.Tab("πŸ“ˆ QQ Primary"):
1720
- img2 = gr.Image(type="pil", label="QQ Plot β€” Primary Model")
1721
  with gr.Tab("πŸ“ˆ QQ All Models"):
1722
- img3 = gr.Image(type="pil", label="QQ Plots β€” All Models")
1723
  with gr.Tab("πŸ“Š QQ Overlay"):
1724
- img4 = gr.Image(type="pil", label="QQ Overlay with Ξ»")
1725
  with gr.Tab("πŸ”΅ Circos"):
1726
- img5 = gr.Image(type="pil", label="Circos β€” Multi-Model with Ribbons")
1727
  with gr.Tab("πŸ”— LD Decay"):
1728
  img6 = gr.Image(type="pil", label="LD Decay (bp & Mb)")
1729
- with gr.Tab("πŸ”¬ PCA"):
1730
- img7 = gr.Image(type="pil", label="Principal Component Analysis")
1731
  with gr.Tab("πŸ‘¨β€πŸ‘©β€πŸ‘§ Kinship"):
1732
  img8 = gr.Image(type="pil", label="Kinship & Dendrogram")
1733
  with gr.Tab("βš– Effect Sizes"):
1734
  img9 = gr.Image(type="pil", label="Effect Sizes & Volcano Plot")
1735
  with gr.Tab("πŸ”„ All Models MH"):
1736
- img10 = gr.Image(type="pil", label="All-Models Manhattan Comparison")
1737
  with gr.Tab("πŸ“Š Dashboard"):
1738
- img11 = gr.Image(type="pil", label="Summary Dashboard")
1739
 
1740
  all_inputs = [
1741
  file_in, text_in, model_sel, maf_thr, top_n_sl,
1742
  # Manhattan
1743
  mh_w, mh_h, mh_fs, mh_fc, mh_ms, mh_alpha, mh_bg, mh_sig, mh_sug,
 
1744
  # QQ
1745
- qq_w, qq_h, qq_fs, qq_fc, qq_ms,
1746
  # Circos
1747
- ci_w, ci_h, ci_fs,
1748
  # LD
1749
- ld_w, ld_h, ld_fs,
1750
  # PCA
1751
  pc_w, pc_h, pc_fs,
1752
  # Kinship
1753
- ki_w, ki_h, ki_fs,
1754
  # Effect
1755
- ef_w, ef_h, ef_fs,
1756
  # Comparison
1757
- co_w, co_h,
1758
  # Dashboard
1759
- db_w, db_h,
1760
  ]
1761
 
1762
  run_btn.click(
 
55
  "#499894","#86BCB6","#D4A6C8","#FFBE7D","#8CD17D",
56
  ]
57
 
 
58
  ALL_MODELS = ["OLS", "MLM", "EMMAX", "FarmCPU", "GEMMA"]
59
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
  def style_fig_white(fig, font_size=9, font_color="#2D3142", grid_color="#E8ECF4"):
 
61
  fig.patch.set_facecolor("#FFFFFF")
62
  for ax in fig.get_axes():
63
  ax.set_facecolor("#FAFBFF")
 
71
  return fig
72
 
73
  def apply_custom_style(fig, cfg):
 
74
  bg = cfg.get("bg_color", "#FFFFFF")
75
  panel = cfg.get("panel_color", "#FAFBFF")
76
  fc = cfg.get("font_color", "#2D3142")
 
206
  return Image.open(buf).copy()
207
 
208
  def get_top_mta(pvals, n=15):
 
209
  return np.argsort(pvals)[:min(n, len(pvals))]
210
 
211
+ def compute_thresholds(n_snps, model_name=""):
212
+ """
213
+ Compute and explain Bonferroni and suggestive thresholds.
214
+ Returns thresholds and explanation text.
215
+ """
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 Ξ».",
223
+ "EMMAX": "EMMAX uses efficient mixed-model; variance components estimated once.",
224
+ "FarmCPU": "FarmCPU iteratively controls for pseudo-QTNs; reduces false positives.",
225
+ "GEMMA": "GEMMA applies genomic inflation correction (Ξ»); p-values are GC-corrected.",
226
+ }
227
+ note = model_notes.get(model_name, "")
228
+
229
+ explanation = (
230
+ f"──────────────────────────────────────────────\n"
231
+ f" Threshold Calculations β€” {model_name}\n"
232
+ f"──────────────────────────────────────────────\n"
233
+ f" SNPs tested (m) : {n_snps:,}\n\n"
234
+ f" πŸ“Œ Bonferroni threshold:\n"
235
+ f" Ξ± / m = 0.05 / {n_snps:,} = {bonferroni:.3e}\n"
236
+ f" -log₁₀(p) = {-np.log10(bonferroni):.2f}\n"
237
+ f" Controls genome-wide Type-I error at 5%.\n"
238
+ f" Assumes all tests are independent.\n\n"
239
+ f" πŸ“Œ Suggestive threshold:\n"
240
+ f" 1 / m = 1 / {n_snps:,} = {suggestive:.3e}\n"
241
+ f" -log₁₀(p) = {-np.log10(suggestive):.2f}\n"
242
+ f" Expects ~1 false positive per genome scan.\n"
243
+ f" Lander & Kruglyak (1995) convention.\n\n"
244
+ f" ℹ️ Model note: {note}\n"
245
+ f"──────────────────────────────────────────────\n"
246
+ )
247
+ return bonferroni, suggestive, explanation
248
+
249
  # ─────────────────────── 5 EFFICIENT STATISTICAL MODELS ──────────────────────────
250
  def ols_gwas(y, G):
251
  n, m = G.shape
 
333
  pvals = 1 - stats.chi2.cdf(np.clip(chi2_vals, 0, 1e10), df=1)
334
  return pvals, betas, ses
335
 
336
+ # ─────────────────────── CONFIG BUILDER ──────────────────────────────────────────
337
+ def build_cfg(w, h, fs, fc, gc, bg, panel, sig_col, sug_col, marker_size, alpha,
338
+ dot_col=None, line_col=None, fill_col=None, axis_col=None):
339
  return {
340
  "width": w, "height": h, "font_size": fs, "font_color": fc,
341
  "grid_color": gc, "bg_color": bg, "panel_color": panel,
342
  "sig_color": sig_col, "sug_color": sug_col,
343
+ "marker_size": marker_size, "alpha": alpha,
344
+ "dot_color": dot_col or "#4E79A7",
345
+ "line_color": line_col or "#E15759",
346
+ "fill_color": fill_col or "#A78BFA",
347
+ "axis_color": axis_col or "#2D3142",
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", "#E8ECF4", "#FFFFFF", "#FAFBFF",
361
  "#E15759", "#4E79A7", 12, 0.75)
362
+
363
+ n_snps = len(pvals)
364
+ bonf_thresh = 0.05 / n_snps
365
+ sug_thresh = 1.0 / n_snps
366
+
367
+ sig_line = -np.log10(bonf_thresh)
368
+ sug_line = -np.log10(sug_thresh)
369
+
370
  fig, ax = plt.subplots(figsize=(cfg["width"], cfg["height"]))
371
  fig.patch.set_facecolor(cfg["bg_color"])
372
  ax.set_facecolor(cfg["panel_color"])
373
 
374
  log_p = -np.log10(np.clip(pvals, 1e-300, 1))
 
 
375
 
376
  chrom_list = sorted(set(chroms))
377
  chrom_colors = {c: CHR_PALETTE[i % len(CHR_PALETTE)] for i, c in enumerate(chrom_list)}
 
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
 
419
  ax.set_xlabel("Chromosome", color=cfg["font_color"], fontsize=cfg["font_size"])
420
  ax.set_title(f"{title}{' β€” ' + model_name if model_name else ''}",
421
  color=cfg["font_color"], fontsize=cfg["font_size"]+2, pad=8)
422
+ ax.legend(fontsize=cfg["font_size"]-1, framealpha=0.9,
423
  facecolor=cfg["bg_color"], edgecolor="#CCCCCC",
424
+ labelcolor=cfg["font_color"], loc='upper right')
425
  ax.set_xlim(-x_offset * 0.01, x_offset * 1.01)
426
  ax.tick_params(colors=cfg["font_color"])
427
  for spine in ax.spines.values():
 
431
  return fig
432
 
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
  cfg = build_cfg(7, 7, 10, "#2D3142", "#E8ECF4", "#FFFFFF", "#FAFBFF",
445
  "#E15759", "#4E79A7", 22, 0.85)
446
  if color is None:
447
+ color = cfg.get("dot_color", "#A78BFA")
448
+
449
  fig, ax = plt.subplots(figsize=(cfg["width"], cfg["height"]))
450
  fig.patch.set_facecolor(cfg["bg_color"])
451
  ax.set_facecolor(cfg["panel_color"])
 
453
  n = len(pvals)
454
  obs = np.sort(-np.log10(np.clip(pvals, 1e-300, 1)))[::-1]
455
  exp = -np.log10(np.linspace(1/n, 1, n)[::-1])
456
+
457
+ # 95% CI band
458
  ci_lower = -np.log10(stats.beta.ppf(0.975, np.arange(1, n+1), np.arange(n, 0, -1)))
459
  ci_upper = -np.log10(stats.beta.ppf(0.025, np.arange(1, n+1), np.arange(n, 0, -1)))
 
460
  ax.fill_between(exp, ci_lower, ci_upper, alpha=0.2, color=color, label="95% CI")
 
 
 
461
 
462
+ # Scatter points
463
+ ax.scatter(exp, obs, c=color, s=cfg["marker_size"], alpha=cfg["alpha"],
464
+ linewidths=0, zorder=5, label="Observed")
465
+
466
+ # ── Identity line (y = x, i.e. expected) ──────────────────────────────────
467
+ ax.plot([0, max(exp)], [0, max(exp)], color="#AAAAAA",
468
+ ls="-", lw=1.2, alpha=0.7, label="y = x (null)", zorder=4)
469
+
470
+ # ── REGRESSION LINE through observed vs expected (key change) ─────────────
471
+ # Fit linear regression of observed on expected
472
+ valid = np.isfinite(exp) & np.isfinite(obs)
473
+ if valid.sum() > 2:
474
+ slope_reg, intercept_reg, r_val, p_val, _ = stats.linregress(exp[valid], obs[valid])
475
+ x_reg = np.linspace(exp[valid].min(), exp[valid].max(), 200)
476
+ y_reg = slope_reg * x_reg + intercept_reg
477
+ ax.plot(x_reg, y_reg, color=cfg["line_color"], ls="-", lw=2.2, zorder=6,
478
+ label=f"Regression (slope={slope_reg:.3f}, RΒ²={r_val**2:.3f})")
479
+
480
+ # Lambda inflation factor
481
  lam = np.median(stats.chi2.ppf(1 - np.clip(pvals, 1e-10, 1), df=1)) / stats.chi2.ppf(0.5, df=1)
482
  ax.text(0.05, 0.93, f"Ξ» = {lam:.4f}", transform=ax.transAxes,
483
  fontsize=cfg["font_size"]+2, color="#E15759", fontweight='bold')
484
+
485
  ax.set_xlabel("Expected -log₁₀(p)", fontsize=cfg["font_size"], color=cfg["font_color"])
486
  ax.set_ylabel("Observed -log₁₀(p)", fontsize=cfg["font_size"], color=cfg["font_color"])
487
  ax.set_title(f"{title}{' β€” ' + model_name if model_name else ''}",
 
498
 
499
 
500
  def plot_qq_all_models(all_results, cfg=None):
501
+ """QQ plots for all models with regression lines."""
502
  if cfg is None:
503
  cfg = build_cfg(7, 6, 9, "#2D3142", "#E8ECF4", "#FFFFFF", "#FAFBFF",
504
  "#E15759", "#4E79A7", 18, 0.8)
 
522
  ci_lo = -np.log10(stats.beta.ppf(0.975, np.arange(1, n+1), np.arange(n, 0, -1)))
523
  ci_hi = -np.log10(stats.beta.ppf(0.025, np.arange(1, n+1), np.arange(n, 0, -1)))
524
  col = MODEL_COLORS.get(mname, "#7C6FCD")
525
+
526
  ax.fill_between(exp, ci_lo, ci_hi, alpha=0.2, color=col)
527
+ ax.scatter(exp, obs, c=col, s=cfg["marker_size"], alpha=cfg["alpha"],
528
+ linewidths=0, zorder=5)
529
+
530
+ # Identity line
531
+ ax.plot([0, max(exp)], [0, max(exp)], color="#AAAAAA",
532
+ ls="-", lw=1.0, alpha=0.6, zorder=4)
533
+
534
+ # Regression line
535
+ valid = np.isfinite(exp) & np.isfinite(obs)
536
+ if valid.sum() > 2:
537
+ slope_reg, intercept_reg, r_val, _, _ = stats.linregress(exp[valid], obs[valid])
538
+ x_reg = np.linspace(exp[valid].min(), exp[valid].max(), 200)
539
+ y_reg = slope_reg * x_reg + intercept_reg
540
+ ax.plot(x_reg, y_reg, color=cfg["sig_color"], ls="-", lw=2.0, zorder=6,
541
+ label=f"Reg slope={slope_reg:.2f}")
542
+ ax.legend(fontsize=cfg["font_size"]-2, facecolor=cfg["bg_color"],
543
+ edgecolor="#CCCCCC", labelcolor=cfg["font_color"])
544
+
545
  lam = np.median(stats.chi2.ppf(1-np.clip(pvals,1e-10,1),df=1)) / stats.chi2.ppf(0.5, df=1)
546
  ax.text(0.05, 0.92, f"Ξ» = {lam:.4f}", transform=ax.transAxes,
547
  fontsize=cfg["font_size"]+1, color="#E15759", fontweight='bold')
 
556
  for idx in range(n_models, len(axes)):
557
  axes[idx].set_visible(False)
558
 
559
+ fig.suptitle("QQ Plots β€” All Models (with Regression Lines)", color=cfg["font_color"],
560
  fontsize=cfg["font_size"]+3, y=1.01, fontweight='bold')
561
  fig.tight_layout()
562
  return fig
563
 
564
 
565
  def plot_qq_overlay(all_results, cfg=None):
566
+ """QQ overlay with regression lines per model."""
567
  if cfg is None:
568
  cfg = build_cfg(9, 9, 10, "#2D3142", "#E8ECF4", "#FFFFFF", "#FAFBFF",
569
  "#E15759", "#4E79A7", 18, 0.85)
 
577
  exp = -np.log10(np.linspace(1/n, 1, n)[::-1])
578
  exp_max = max(exp_max, max(exp))
579
  lam = np.median(stats.chi2.ppf(1-np.clip(pvals,1e-10,1),df=1)) / stats.chi2.ppf(0.5, df=1)
580
+ col = MODEL_COLORS.get(mname, "#7C6FCD")
581
+ ax.plot(exp, obs, color=col, lw=2, label=f"{mname} (Ξ»={lam:.3f})", alpha=0.85)
582
+
583
+ # Regression line per model (dashed)
584
+ valid = np.isfinite(exp) & np.isfinite(obs)
585
+ if valid.sum() > 2:
586
+ slope_r, intercept_r, _, _, _ = stats.linregress(exp[valid], obs[valid])
587
+ x_r = np.linspace(exp[valid].min(), exp[valid].max(), 100)
588
+ ax.plot(x_r, slope_r * x_r + intercept_r, color=col,
589
+ ls="--", lw=1.2, alpha=0.55)
590
+
591
+ ax.plot([0, exp_max], [0, exp_max], color="#AAAAAA",
592
+ ls="-", lw=1.5, label="y = x (null)", alpha=0.6)
593
  ax.set_xlabel("Expected -log₁₀(p)", fontsize=cfg["font_size"], color=cfg["font_color"])
594
  ax.set_ylabel("Observed -log₁₀(p)", fontsize=cfg["font_size"], color=cfg["font_color"])
595
+ ax.set_title("QQ Plot β€” All Models Overlay (solid=observed, dashed=regression)",
596
+ color=cfg["font_color"], fontsize=cfg["font_size"]+2, fontweight='bold')
597
  ax.legend(fontsize=cfg["font_size"]-1, framealpha=0.85,
598
  facecolor=cfg["bg_color"], edgecolor="#CCCCCC", labelcolor=cfg["font_color"])
599
  ax.tick_params(colors=cfg["font_color"], labelsize=cfg["font_size"])
 
604
  return fig
605
 
606
 
607
+ # ─────────────────────── CIRCOS PLOT ─────────────────────────────────────────────
608
  def plot_circos(all_results, chroms, positions, cfg=None, top_n=15):
609
  """
610
+ Circos plot with:
611
+ - Clear chromosome number labels (Chr1, Chr2, ...) on outer band
612
+ - Colored outer chromosome bands
613
+ - Concentric rings per model
614
+ - Ribbons for top MTAs
615
+ - Both Bonferroni + suggestive markers
616
  """
617
  if cfg is None:
618
  cfg = build_cfg(14, 14, 8, "#2D3142", "#E8ECF4", "#FFFFFF", "#FFFFFF",
 
631
  total_snps = len(chroms)
632
  sort_idx = np.lexsort((positions, chroms))
633
 
 
634
  snp_angles = np.linspace(0, 2 * np.pi, total_snps, endpoint=False)
635
 
636
  # ── Outer chromosome band ──────────────────────────────────────────────────
637
  outer_r = 1.0
638
+ band_h = 0.07
639
+ label_r = outer_r + band_h + 0.10
640
 
641
  chrom_bounds = {}
642
  for ch in chrom_list:
 
648
  theta_mid = (theta_start + theta_end) / 2
649
  chrom_bounds[ch] = (theta_start, theta_end, theta_mid, idxs_in_sorted)
650
  col = CHR_PALETTE[chrom_list.index(ch) % len(CHR_PALETTE)]
651
+ span = snp_angles[1] - snp_angles[0] if len(snp_angles) > 1 else 0.01
652
  bar_w = max(span * len(idxs_in_sorted) * 1.05,
653
  2 * np.pi / total_snps * 1.2)
654
  ax.bar(theta_mid, band_h, width=bar_w,
655
  bottom=outer_r, color=col, alpha=0.88,
656
+ linewidth=0.8, edgecolor="white")
657
+
658
+ # ── Chromosome number text directly on the band ────────────────────
659
+ # Always show the chromosome number clearly
660
+ text_angle_deg = np.degrees(theta_mid)
661
+ # Rotate text so it reads outward
662
+ if theta_mid > np.pi:
663
+ rotation = text_angle_deg - 90
664
+ else:
665
+ rotation = text_angle_deg + 90
666
+
667
+ ax.text(theta_mid, outer_r + band_h * 0.5,
668
+ f"{ch}", # Just the number on the band
669
+ ha='center', va='center',
670
+ fontsize=max(cfg["font_size"]-1, 6),
671
+ color='white', fontweight='bold',
672
+ rotation=rotation)
673
 
674
+ # ── Chromosome labels outside the band (Chr N format) ────────────────────
675
  used_angles = []
676
+ min_sep = 0.20
677
 
678
  def angle_free(a):
679
  for ua in used_angles:
 
686
  if ch not in chrom_bounds: continue
687
  _, _, theta_mid, _ = chrom_bounds[ch]
688
  col = CHR_PALETTE[chrom_list.index(ch) % len(CHR_PALETTE)]
 
689
  candidate = theta_mid
690
  for delta in np.linspace(0, np.pi, 60):
691
  for sign in [1, -1]:
 
697
  continue
698
  break
699
  used_angles.append(candidate)
700
+
701
+ if candidate > np.pi:
702
+ rot = np.degrees(candidate) - 90
703
+ else:
704
+ rot = np.degrees(candidate) + 90
705
+
706
  ax.text(candidate, label_r,
707
  f"Chr{ch}", ha='center', va='center',
708
  fontsize=cfg["font_size"], color=col,
709
+ fontweight='bold', rotation=rot)
 
710
 
711
  # ── Per-model rings ────────────────────────────────────────────────────────
712
  model_names = list(all_results.keys())
 
715
  ring_total = outer_r - 0.05 - 0.18
716
  ring_width = (ring_total - ring_gap * n_models) / max(n_models, 1)
717
 
 
 
718
  for midx, mname in enumerate(model_names):
719
  pvals, _, _ = all_results[mname]
720
  log_p = -np.log10(np.clip(pvals, 1e-300, 1))
721
  r_base = 0.18 + midx * (ring_width + ring_gap)
722
  r_max_data = ring_width * 0.85
723
  col = MODEL_COLORS.get(mname, CHR_PALETTE[midx % len(CHR_PALETTE)])
724
+ max_lp = max(log_p.max(), 1)
725
+
726
+ # Compute thresholds for this model
727
+ n_snps = len(pvals)
728
+ bonf_thresh = 0.05 / n_snps
729
+ sug_thresh = 1.0 / n_snps
730
+ bonf_lp = -np.log10(bonf_thresh)
731
+ sug_lp = -np.log10(sug_thresh)
732
 
733
  # Ring baseline arc
734
  theta_arc = np.linspace(0, 2 * np.pi, 500)
735
  ax.plot(theta_arc, np.full_like(theta_arc, r_base),
736
  color=col, alpha=0.15, lw=0.8, zorder=1)
737
 
738
+ # Suggestive threshold ring
739
+ sug_r = r_base + (sug_lp / max_lp) * r_max_data
740
+ ax.plot(theta_arc, np.full_like(theta_arc, min(sug_r, r_base + r_max_data)),
741
+ color=cfg["sug_color"], alpha=0.35, lw=0.7, ls=":", zorder=2)
742
+
743
+ # Bonferroni threshold ring
744
+ bonf_r = r_base + (bonf_lp / max_lp) * r_max_data
745
+ if bonf_r <= r_base + r_max_data:
746
+ ax.plot(theta_arc, np.full_like(theta_arc, bonf_r),
747
+ color=cfg["sig_color"], alpha=0.45, lw=1.0, ls="--", zorder=2)
748
 
749
+ lp_norm = log_p[sort_idx] / max_lp * r_max_data
750
  ax.scatter(snp_angles, r_base + lp_norm,
751
  c=col, s=cfg["marker_size"]*0.5,
752
+ alpha=cfg["alpha"]*0.7, linewidths=0, zorder=3)
753
 
754
  # Highlight top MTAs
755
  top_idx = get_top_mta(pvals, top_n)
 
763
  zorder=12, marker='D',
764
  edgecolors='#333333', linewidth=0.5, alpha=0.95)
765
 
766
+ # Model name label
767
+ ax.text(np.pi * 1.5, r_base + r_max_data * 0.35,
 
768
  mname, ha='center', va='center',
769
  fontsize=cfg["font_size"]-1, color=col,
770
  fontweight='bold', alpha=0.92)
771
 
772
+ # ── Ribbons ────────────────────────────────────────────────────────────────
 
773
  if len(all_results) > 0:
774
  first_model = model_names[0]
775
  pvals_first, _, _ = all_results[first_model]
 
783
  for j, idx_j in enumerate(top_mta_idx):
784
  if j <= i: continue
785
  if chroms[idx_i] == chroms[idx_j]: continue
 
786
  pos_i = np.where(sort_idx == idx_i)[0]
787
  pos_j = np.where(sort_idx == idx_j)[0]
788
  if len(pos_i) == 0 or len(pos_j) == 0: continue
789
  ang_i = snp_angles[pos_i[0]]
790
  ang_j = snp_angles[pos_j[0]]
 
791
  theta_ribbon = np.linspace(ang_i, ang_j, 30)
792
  col_r = CHR_PALETTE[chrom_list.index(chroms[idx_i]) % len(CHR_PALETTE)]
793
  ax.fill_between(theta_ribbon,
794
  np.full(30, ribbon_r * 0.4),
795
  np.full(30, ribbon_r),
796
  alpha=0.06, color=col_r, zorder=0)
797
+ ax.plot(theta_ribbon, np.full(30, ribbon_r * 0.7),
 
798
  color=col_r, alpha=0.12, lw=0.8, zorder=1)
799
 
800
  # ── Legend ─────────────────────────────────────────────────────────────────
801
  legend_elements = [
802
+ mpatches.Patch(facecolor=MODEL_COLORS.get(m, "#7C6FCD"), label=m, alpha=0.85)
 
803
  for m in model_names
804
  ]
805
+ legend_elements.append(mpatches.Patch(facecolor=ACCENT_GOLD,
806
+ label=f"Top {top_n} MTAs (β—†)", alpha=0.9))
807
+ legend_elements.append(mpatches.Patch(facecolor=cfg["sig_color"], alpha=0.6,
808
+ label="── Bonferroni (dashed ring)"))
809
+ legend_elements.append(mpatches.Patch(facecolor=cfg["sug_color"], alpha=0.6,
810
+ label="Β·Β·Β· Suggestive (dotted ring)"))
811
+
812
  ax.legend(handles=legend_elements,
813
+ loc='lower center', bbox_to_anchor=(0.5, -0.07),
814
+ ncol=min(4, n_models+3),
815
  fontsize=cfg["font_size"], framealpha=0.9,
816
  facecolor=cfg["bg_color"], edgecolor="#CCCCCC",
817
  labelcolor=cfg["font_color"])
818
 
819
  ax.set_title(
820
+ f"Circos β€” Multi-Model GWAS | Chr numbers on outer band | β—† = Top {top_n} MTAs",
821
+ color=cfg["font_color"], fontsize=cfg["font_size"]+2, pad=28, fontweight='bold'
822
  )
823
  fig.tight_layout()
824
  return fig
825
 
826
 
827
+ # ─────────────────────── LD DECAY ────────────────────────────────────────────────
828
  def plot_ld_decay(G, positions, cfg=None):
829
  if cfg is None:
830
  cfg = build_cfg(16, 6, 9, "#2D3142", "#E8ECF4", "#FFFFFF", "#FAFBFF",
 
868
  return np.array(centers), np.array(means), np.array(sems)
869
 
870
  for i, (dist_arr, xlabel, title_str, dot_col, line_col) in enumerate([
871
+ (dists_bp, "Distance (bp)", "LD Decay β€” Base Pairs (bp)",
872
+ cfg.get("dot_color","#4E79A7"), cfg.get("line_color","#E15759")),
873
  (dists_mb, "Distance (Mb)", "LD Decay β€” Megabases (Mb)", "#59A14F", "#F28E2B"),
874
  ]):
875
  ax = axes[i]
 
902
  return fig
903
 
904
 
905
+ # ─────────────────────── PCA (DARK THEME) ────────────────────────────────────────
906
  def plot_pca(G, y, ids, cfg=None):
907
+ """
908
+ PCA with dark background (as requested).
909
+ Scree plot REMOVED (as requested).
910
+ """
911
  if cfg is None:
912
+ cfg = build_cfg(14, 10, 9,
913
+ font_color=TEXT_MAIN,
914
+ gc=GRID_LINE,
915
+ bg=BG_DARK,
916
+ panel=PANEL_DARK,
917
+ sig_col=ACCENT_TEAL,
918
+ sug_col=ACCENT_GOLD,
919
+ marker_size=55, alpha=0.80)
920
+
921
+ # Use dark theme colors
922
+ bg_col = cfg.get("bg_color", BG_DARK)
923
+ panel_col = cfg.get("panel_color", PANEL_DARK)
924
+ fc = cfg.get("font_color", TEXT_MAIN)
925
+ gc = cfg.get("grid_color", GRID_LINE)
926
+ fs = cfg.get("font_size", 9)
927
+
928
+ fig, axes = plt.subplots(1, 3, figsize=(cfg["width"], cfg["height"]))
929
+ fig.patch.set_facecolor(bg_col)
930
  axes = axes.flatten()
931
 
932
  G_sc = StandardScaler().fit_transform(G)
 
936
  var_exp = pca.explained_variance_ratio_ * 100
937
 
938
  for ax in axes:
939
+ ax.set_facecolor(panel_col)
940
+ for spine in ax.spines.values():
941
+ spine.set_edgecolor(GRID_LINE)
942
+ ax.grid(color=gc, linewidth=0.4, linestyle="--", alpha=0.5)
943
+ ax.tick_params(colors=fc, labelsize=fs-1)
944
 
945
+ # ── PC1 vs PC2 ─────────────────────────────────────────────────────────────
946
+ sc = axes[0].scatter(pcs[:,0], pcs[:,1], c=y, cmap='plasma',
947
  s=cfg["marker_size"], edgecolors='none', alpha=cfg["alpha"])
948
+ axes[0].set_xlabel(f"PC1 ({var_exp[0]:.1f}%)", fontsize=fs, color=fc)
949
+ axes[0].set_ylabel(f"PC2 ({var_exp[1]:.1f}%)", fontsize=fs, color=fc)
950
+ axes[0].set_title("PC1 vs PC2", color=ACCENT_TEAL, fontsize=fs+1, fontweight='bold')
 
 
 
951
  cbar = plt.colorbar(sc, ax=axes[0])
952
+ cbar.set_label("Phenotype", color=fc, fontsize=fs-1)
953
+ cbar.ax.tick_params(colors=fc)
954
+ cbar.ax.yaxis.set_tick_params(color=fc)
955
+ plt.setp(cbar.ax.yaxis.get_ticklabels(), color=fc)
956
+
957
+ # ── PC2 vs PC3 ─────────────────────────────────────────────────────────────
958
+ if n_comp >= 3:
959
+ sc2 = axes[1].scatter(pcs[:,1], pcs[:,2], c=y, cmap='plasma',
960
+ s=cfg["marker_size"], edgecolors='none', alpha=cfg["alpha"])
961
+ axes[1].set_xlabel(f"PC2 ({var_exp[1]:.1f}%)", fontsize=fs, color=fc)
962
+ axes[1].set_ylabel(f"PC3 ({var_exp[2]:.1f}%)", fontsize=fs, color=fc)
963
+ axes[1].set_title("PC2 vs PC3", color=ACCENT_GOLD, fontsize=fs+1, fontweight='bold')
964
+ cbar2 = plt.colorbar(sc2, ax=axes[1])
965
+ cbar2.set_label("Phenotype", color=fc, fontsize=fs-1)
966
+ cbar2.ax.tick_params(colors=fc)
967
+ plt.setp(cbar2.ax.yaxis.get_ticklabels(), color=fc)
968
+ else:
969
+ axes[1].set_visible(False)
970
+
971
+ # ── Population Structure Biplot PC1 vs PC2 with ID labels ──────────────────
972
+ sc3 = axes[2].scatter(pcs[:,0], pcs[:,1], c=y, cmap='cool',
973
+ s=cfg["marker_size"], edgecolors='none', alpha=cfg["alpha"])
974
+ axes[2].set_title("Population Structure", color=ACCENT_PINK, fontsize=fs+1, fontweight='bold')
975
+ axes[2].set_xlabel(f"PC1 ({var_exp[0]:.1f}%)", fontsize=fs, color=fc)
976
+ axes[2].set_ylabel(f"PC2 ({var_exp[1]:.1f}%)", fontsize=fs, color=fc)
977
+ cbar3 = plt.colorbar(sc3, ax=axes[2])
978
+ cbar3.set_label("Phenotype", color=fc, fontsize=fs-1)
979
+ cbar3.ax.tick_params(colors=fc)
980
+ plt.setp(cbar3.ax.yaxis.get_ticklabels(), color=fc)
981
+
982
+ fig.suptitle("Principal Component Analysis", color=TEXT_MAIN,
983
+ fontsize=fs+3, fontweight='bold')
 
984
  fig.tight_layout()
985
  return fig
986
 
987
 
988
+ # ─────────────────────── MODEL COMPARISON MANHATTAN ──────────────────────────────
989
  def plot_model_comparison_manhattan(all_results, chroms, positions, cfg=None, top_n=15):
990
+ """All-models Manhattan with chromosome numbers and both thresholds."""
991
  if cfg is None:
992
  cfg = build_cfg(16, 3.5, 7, "#2D3142", "#E8ECF4", "#FFFFFF", "#FAFBFF",
993
  "#E15759", "#4E79A7", 6, 0.65)
 
1019
  mask = chroms == ch
1020
  if mask.sum() > 0:
1021
  tick_pos.append(x_coords[mask].mean())
1022
+ tick_lab.append(f"Chr{ch}") # Always show Chr N
1023
 
1024
  for midx, (mname, (pvals, _, _)) in enumerate(all_results.items()):
1025
  ax = axes[midx]
1026
  ax.set_facecolor(cfg["panel_color"])
1027
  log_p = -np.log10(np.clip(pvals, 1e-300, 1))
1028
  col = MODEL_COLORS.get(mname, CHR_PALETTE[midx % len(CHR_PALETTE)])
1029
+
1030
+ # Compute model-specific thresholds
1031
+ n_snps = len(pvals)
1032
+ bonf_thresh = 0.05 / n_snps
1033
+ sug_thresh = 1.0 / n_snps
1034
+
1035
  for ch in chrom_list:
1036
  mask = chroms == ch
1037
  ax.scatter(x_coords[mask], log_p[mask],
1038
  c=col, s=cfg["marker_size"], alpha=cfg["alpha"], linewidths=0)
1039
+
1040
  top_idx = get_top_mta(pvals, top_n)
1041
  ax.scatter(x_coords[top_idx], log_p[top_idx],
1042
  c=ACCENT_GOLD, s=max(cfg["marker_size"]*4, 35),
1043
  zorder=10, linewidths=0.7, edgecolors='#333333',
1044
  marker='D', label=f"Top {top_n} MTAs")
1045
+
1046
+ # Both thresholds on every subplot
1047
+ ax.axhline(-np.log10(sug_thresh), color=cfg["sug_color"],
1048
+ ls=':', lw=1.2, alpha=0.9,
1049
+ label=f"Sug. (1/m={sug_thresh:.1e})")
1050
+ ax.axhline(-np.log10(bonf_thresh), color=cfg["sig_color"],
1051
+ ls='--', lw=1.5, alpha=0.9,
1052
+ label=f"Bonf. (0.05/m={bonf_thresh:.1e})")
1053
+
1054
+ ax.set_ylabel("-log₁₀(p)", fontsize=cfg["font_size"], color=cfg["font_color"])
1055
  ax.set_title(f"Model: {mname}", color=col,
1056
  fontsize=cfg["font_size"]+1, pad=3, fontweight='bold')
1057
  ax.set_xticks(tick_pos)
 
1062
  ax.tick_params(colors=cfg["font_color"], labelsize=cfg["font_size"]-1)
1063
  ax.legend(fontsize=cfg["font_size"]-2, framealpha=0.85,
1064
  facecolor=cfg["bg_color"], edgecolor="#CCCCCC",
1065
+ labelcolor=cfg["font_color"], ncol=3)
1066
  for spine in ax.spines.values(): spine.set_edgecolor("#CCCCCC")
1067
  ax.grid(color=cfg["grid_color"], linewidth=0.3, linestyle="--", alpha=0.5)
1068
 
 
1073
  return fig
1074
 
1075
 
1076
+ # ─────────────────────── KINSHIP ─────────────────────────────────────────────────
1077
  def plot_kinship(K, ids, cfg=None):
1078
  if cfg is None:
1079
  cfg = build_cfg(14, 12, 9, "#2D3142", "#E8ECF4", "#FFFFFF", "#FAFBFF",
 
1094
  cbar.ax.tick_params(colors=cfg["font_color"])
1095
 
1096
  K_flat = K[np.triu_indices_from(K, k=1)]
1097
+ axes[1].hist(K_flat, bins=30, color=cfg.get("dot_color","#4E79A7"),
1098
+ edgecolor='white', alpha=0.85)
1099
  axes[1].set_title("Pairwise Kinship Distribution", color=cfg["font_color"],
1100
  fontsize=cfg["font_size"]+1, fontweight='bold')
1101
  axes[1].set_xlabel("Kinship Coefficient", fontsize=cfg["font_size"],
 
1103
  axes[1].set_ylabel("Count", fontsize=cfg["font_size"], color=cfg["font_color"])
1104
  axes[1].grid(color=cfg["grid_color"], linewidth=0.4, linestyle="--", alpha=0.6)
1105
 
 
1106
  try:
1107
  lm = linkage(K, method='ward')
1108
  n_samples = len(ids)
 
1109
  leaf_fs = max(3, min(cfg["font_size"]-1, int(200 / max(n_samples, 1))))
 
1110
  truncate_mode = None
1111
  p_param = None
1112
  if n_samples > 50:
 
1131
  dend_kwargs["truncate_mode"] = truncate_mode
1132
  dend_kwargs["p"] = p_param
1133
  else:
 
1134
  short_labels = [str(x)[:10] for x in ids]
1135
  dend_kwargs["labels"] = short_labels
1136
 
 
1138
  axes[2].tick_params(axis='x', labelsize=leaf_fs, colors=cfg["font_color"])
1139
  axes[2].tick_params(axis='y', labelsize=cfg["font_size"]-2,
1140
  colors=cfg["font_color"])
 
1141
  if n_samples > 50:
1142
  axes[2].set_xticks([])
1143
+ axes[2].set_facecolor(cfg["panel_color"])
1144
+ for spine in axes[2].spines.values(): spine.set_edgecolor("#CCCCCC")
1145
  except Exception as e:
1146
  axes[2].text(0.5, 0.5, f"Dendrogram\nunavailable:\n{str(e)[:40]}",
1147
  ha='center', va='center', transform=axes[2].transAxes,
 
1150
  eigvals, eigvecs = np.linalg.eigh(K)
1151
  idx = np.argsort(eigvals)[::-1]
1152
  axes[3].scatter(eigvecs[:,idx[0]], eigvecs[:,idx[1]],
1153
+ c=cfg.get("dot_color","#4E79A7"), s=cfg["marker_size"],
1154
  edgecolors='none', alpha=cfg["alpha"])
1155
  axes[3].set_title("Kinship PCA", color=cfg["font_color"],
1156
  fontsize=cfg["font_size"]+1, fontweight='bold')
 
1164
  return fig
1165
 
1166
 
1167
+ # ─────────────────────── EFFECT SIZES ────────────────────────────────────────────
1168
  def plot_effect_sizes(pvals, betas, snp_names, cfg=None, top_n=15):
1169
  if cfg is None:
1170
  cfg = build_cfg(14, 10, 9, "#2D3142", "#E8ECF4", "#FFFFFF", "#FAFBFF",
 
1182
  top_idx = get_top_mta(pvals, top_n)
1183
  top_betas = betas[top_idx]
1184
  top_names = [str(snp_names[i])[:18] for i in top_idx]
1185
+ pos_col = cfg.get("dot_color", "#4E79A7")
1186
+ neg_col = cfg.get("line_color", "#E15759")
1187
+ colors = [neg_col if b < 0 else pos_col for b in top_betas]
1188
 
 
1189
  order = np.argsort(top_betas)
1190
  axes[0].barh([top_names[o] for o in order], [top_betas[o] for o in order],
1191
  color=[colors[o] for o in order], edgecolor='white', linewidth=0.4)
 
1198
 
1199
  log_p = -np.log10(np.clip(pvals, 1e-300, 1))
1200
  sig_thr = -np.log10(0.05/len(pvals))
1201
+ pt_colors = [neg_col if lp >= sig_thr else (pos_col if b > 0 else "#59A14F")
1202
  for lp, b in zip(log_p, betas)]
1203
  axes[1].scatter(betas, log_p, c=pt_colors, s=cfg["marker_size"],
1204
  alpha=cfg["alpha"], linewidths=0)
 
1211
  axes[1].legend(fontsize=cfg["font_size"]-1, facecolor=cfg["bg_color"],
1212
  edgecolor="#CCCCCC", labelcolor=cfg["font_color"])
1213
 
1214
+ axes[2].hist(betas, bins=25, color=cfg.get("fill_color","#A78BFA"),
1215
+ edgecolor='white', alpha=0.85)
1216
  axes[2].axvline(0, color=cfg["sig_color"], lw=2, ls='--')
1217
  axes[2].set_xlabel("Ξ²", fontsize=cfg["font_size"], color=cfg["font_color"])
1218
  axes[2].set_title("Effect Size Distribution", color=cfg["font_color"],
 
1240
  return fig
1241
 
1242
 
1243
+ # ─────────────────────── SUMMARY DASHBOARD ───────────────────────────────────────
1244
  def plot_summary_dashboard(y, maf, all_results, G_filt, cfg=None):
1245
+ """Dashboard: scree plot REMOVED, replaced with per-model threshold table."""
1246
  if cfg is None:
1247
  cfg = build_cfg(15, 10, 9, "#2D3142", "#E8ECF4", "#FFFFFF", "#FAFBFF",
1248
  "#E15759", "#4E79A7", 30, 0.75)
 
1256
  ax.tick_params(colors=cfg["font_color"], labelsize=cfg["font_size"]-1)
1257
  ax.grid(color=cfg["grid_color"], linewidth=0.4, linestyle="--", alpha=0.6)
1258
 
1259
+ # Panel 0: Phenotype distribution
1260
+ axes[0].hist(y, bins=15, color=cfg.get("dot_color","#4E79A7"),
1261
+ edgecolor='white', alpha=0.85)
1262
  axes[0].axvline(y.mean(), color=cfg["sig_color"], lw=2, ls='--',
1263
  label=f"Mean: {y.mean():.2f}")
1264
  axes[0].set_title(f"Phenotype Distribution | n={len(y)}",
 
1268
  axes[0].set_xlabel("Phenotype Value", fontsize=cfg["font_size"], color=cfg["font_color"])
1269
  axes[0].set_ylabel("Count", fontsize=cfg["font_size"], color=cfg["font_color"])
1270
 
1271
+ # Panel 1: MAF distribution
1272
  axes[1].hist(maf, bins=20, color="#59A14F", edgecolor='white', alpha=0.85)
1273
  axes[1].axvline(0.05, color=cfg["sig_color"], ls='--', lw=1.5,
1274
  label=f"MAF=0.05 (rare: {np.sum(maf<0.05)})")
 
1279
  axes[1].set_xlabel("MAF", fontsize=cfg["font_size"], color=cfg["font_color"])
1280
  axes[1].set_ylabel("Count", fontsize=cfg["font_size"], color=cfg["font_color"])
1281
 
1282
+ # Panel 2: Genomic inflation per model
1283
  lambdas = {}
1284
  for mname, (p, _, _) in all_results.items():
1285
  lam = np.median(stats.chi2.ppf(1-np.clip(p,1e-10,1),df=1)) / stats.chi2.ppf(0.5,df=1)
 
1298
  f"{lv:.3f}", ha='center', fontsize=cfg["font_size"]-2,
1299
  color=cfg["font_color"], va='bottom')
1300
 
1301
+ # Panel 3: Significant SNPs (Bonferroni)
1302
  sig_counts = {}
1303
  for mname, (p, _, _) in all_results.items():
1304
  bonf = 0.05 / len(p)
 
1311
  axes[3].tick_params(axis='x', rotation=30, labelsize=cfg["font_size"])
1312
  axes[3].set_ylabel("Count", fontsize=cfg["font_size"], color=cfg["font_color"])
1313
 
1314
+ # Panel 4: Model concordance heatmap
1315
  n_m = len(all_results)
1316
  model_names = list(all_results.keys())
1317
  concordance = np.eye(n_m)
 
1338
  axes[4].set_title("Model Concordance (Spearman ρ)",
1339
  color=cfg["font_color"], fontsize=cfg["font_size"]+1, fontweight='bold')
1340
 
1341
+ # Panel 5: REPLACED scree plot β†’ Threshold table per model
 
 
1342
  axes[5].axis('off')
1343
+ first_model = model_names[0]
1344
+ # Build threshold text
1345
+ thresh_lines = [
1346
+ f"{'Model':<10} {'Bonferroni':>14} {'Suggestive':>14}",
1347
+ "─" * 42,
1348
+ ]
1349
+ for mname, (p, _, _) in all_results.items():
1350
+ n_snps = len(p)
1351
+ b_thr = 0.05 / n_snps
1352
+ s_thr = 1.0 / n_snps
1353
+ thresh_lines.append(
1354
+ f"{mname:<10} {b_thr:>14.3e} {s_thr:>14.3e}"
1355
+ )
1356
+ thresh_lines.append("─" * 42)
1357
+ thresh_lines.append(f" (Bonferroni = 0.05 / m)")
1358
+ thresh_lines.append(f" (Suggestive = 1.0 / m)")
1359
+
1360
  summary_text = (
1361
  f"GWAS Summary\n\n"
1362
  f"Samples: {G_filt.shape[0]}\n"
1363
  f"SNPs (filt.): {G_filt.shape[1]}\n"
1364
  f"Models run: {n_m}\n"
1365
  f"Missing rate: {np.isnan(G_filt).mean():.1%}\n\n"
1366
+ + "\n".join(thresh_lines)
 
 
1367
  )
1368
+ axes[5].text(0.04, 0.96, summary_text,
1369
  ha='left', va='top', transform=axes[5].transAxes,
1370
+ color=cfg["font_color"], fontsize=cfg["font_size"]-1,
1371
  fontfamily='monospace',
1372
  bbox=dict(boxstyle='round,pad=0.8', facecolor=cfg["panel_color"],
1373
  edgecolor="#CCCCCC", alpha=0.9))
1374
+ axes[5].set_title("Pipeline Summary + Thresholds", color=cfg["font_color"],
1375
  fontsize=cfg["font_size"]+1, fontweight='bold')
1376
 
1377
  fig.suptitle("GWAS Analysis Dashboard",
 
1403
  ws_sum['A1'] = f"GWAS Complete Analysis Summary β€” Top {top_n} MTAs per Model"
1404
  ws_sum['A1'].font = Font(bold=True, color="2C5F8A", name="Calibri", size=16)
1405
  ws_sum.merge_cells('A1:H1')
1406
+ headers_sum = ["Model", "N_SNPs_Tested", "Bonferroni_Threshold",
1407
+ "Suggestive_Threshold","Sig_SNPs_Bonferroni",
1408
+ "Sig_SNPs_Suggestive", "Genomic_Lambda", "Min_Pvalue"]
1409
  for col, h in enumerate(headers_sum, 1):
1410
  cell = ws_sum.cell(row=3, column=col, value=h)
1411
  cell.font = header_font; cell.fill = header_fill
1412
  cell.alignment = Alignment(horizontal='center'); cell.border = thin_border
1413
+ ws_sum.column_dimensions[get_column_letter(col)].width = 24
1414
  for row_i, (mname, (pvals, betas, ses)) in enumerate(all_results.items(), 4):
1415
  lam = np.median(stats.chi2.ppf(1-np.clip(pvals,1e-10,1),df=1)) / stats.chi2.ppf(0.5,df=1)
1416
+ n_snps = len(pvals)
1417
+ bonf_t = 0.05 / n_snps
1418
+ sug_t = 1.0 / n_snps
1419
+ sig_bonf = int((pvals < bonf_t).sum())
1420
+ sig_sug = int((pvals < sug_t).sum())
1421
+ row_data = [mname, n_snps, f"{bonf_t:.2e}", f"{sug_t:.2e}",
1422
+ sig_bonf, sig_sug, round(float(lam),4), float(np.min(pvals))]
1423
  fill = alt_fill if row_i%2==0 else PatternFill("solid",start_color="FFFFFF",end_color="FFFFFF")
1424
  for col, val in enumerate(row_data, 1):
1425
  cell = ws_sum.cell(row=row_i, column=col, value=val)
1426
  cell.fill = fill; cell.border = thin_border
1427
  cell.alignment = Alignment(horizontal='center')
1428
 
1429
+ # Add threshold explanation sheet
1430
+ ws_exp = wb.create_sheet(title="Threshold_Explanation")
1431
+ ws_exp['A1'] = "Threshold Calculation Explanation"
1432
+ ws_exp['A1'].font = title_font
1433
+ ws_exp.merge_cells('A1:C1')
1434
+ explanation_rows = [
1435
+ ("Bonferroni Threshold", "Formula", "0.05 / m where m = number of SNPs tested"),
1436
+ ("Bonferroni Threshold", "Rationale", "Controls genome-wide Type I error rate at 5%."),
1437
+ ("Bonferroni Threshold", "Assumption", "All SNP tests are independent (conservative)."),
1438
+ ("Suggestive Threshold", "Formula", "1 / m where m = number of SNPs tested"),
1439
+ ("Suggestive Threshold", "Rationale", "Expects ~1 false positive per genome scan."),
1440
+ ("Suggestive Threshold", "Reference", "Lander & Kruglyak (1995) Nature Genetics."),
1441
+ ("OLS Note", "Correction", "No population structure correction."),
1442
+ ("MLM Note", "Correction", "Kinship matrix controls for relatedness."),
1443
+ ("EMMAX Note", "Correction", "Efficient Mixed Model Association with variance components."),
1444
+ ("FarmCPU Note", "Correction", "Iterative pseudo-QTN control reduces false positives."),
1445
+ ("GEMMA Note", "Correction", "Genomic control (GC correction) applied for inflation."),
1446
+ ]
1447
+ ws_exp.cell(row=3, column=1, value="Threshold").font = header_font
1448
+ ws_exp.cell(row=3, column=1).fill = header_fill
1449
+ ws_exp.cell(row=3, column=2, value="Aspect").font = header_font
1450
+ ws_exp.cell(row=3, column=2).fill = header_fill
1451
+ ws_exp.cell(row=3, column=3, value="Details").font = header_font
1452
+ ws_exp.cell(row=3, column=3).fill = header_fill
1453
+ ws_exp.column_dimensions['A'].width = 22
1454
+ ws_exp.column_dimensions['B'].width = 16
1455
+ ws_exp.column_dimensions['C'].width = 60
1456
+ for r_i, (t, a, d) in enumerate(explanation_rows, 4):
1457
+ ws_exp.cell(row=r_i, column=1, value=t).border = thin_border
1458
+ ws_exp.cell(row=r_i, column=2, value=a).border = thin_border
1459
+ ws_exp.cell(row=r_i, column=3, value=d).border = thin_border
1460
+
1461
  # Sheet per model: Top N MTAs
1462
  for mname, (pvals, betas, ses) in all_results.items():
1463
  ws = wb.create_sheet(title=f"{mname}_Top{top_n}MTAs")
 
1643
  def run_gwas(file_obj, text_input, selected_models, maf_threshold, top_n,
1644
  # Manhattan cfg
1645
  mh_w, mh_h, mh_fs, mh_fc, mh_ms, mh_alpha, mh_bg, mh_sig, mh_sug,
1646
+ mh_dot, mh_panel,
1647
  # QQ cfg
1648
+ qq_w, qq_h, qq_fs, qq_fc, qq_ms, qq_dot, qq_line, qq_fill, qq_bg, qq_panel,
1649
  # Circos cfg
1650
+ ci_w, ci_h, ci_fs, ci_sig, ci_sug,
1651
  # LD cfg
1652
+ ld_w, ld_h, ld_fs, ld_dot, ld_line,
1653
+ # PCA cfg (dark)
1654
  pc_w, pc_h, pc_fs,
1655
  # Kinship cfg
1656
+ ki_w, ki_h, ki_fs, ki_dot, ki_bg, ki_panel,
1657
  # Effect cfg
1658
+ ef_w, ef_h, ef_fs, ef_pos, ef_neg, ef_fill, ef_bg,
1659
  # Comparison cfg
1660
+ co_w, co_h, co_sig, co_sug,
1661
  # Dashboard cfg
1662
+ db_w, db_h, db_dot):
1663
 
1664
  try:
1665
  df, snp_cols, chroms, positions = parse_data(file_obj, text_input)
 
1715
 
1716
  top_n = int(top_n)
1717
 
1718
+ # Build per-plot configs
1719
  def mkc(w, h, fs, fc="#2D3142", gc="#E8ECF4", bg="#FFFFFF",
1720
+ panel="#FAFBFF", sig="#E15759", sug="#4E79A7", ms=12, al=0.75,
1721
+ dot=None, line=None, fill=None):
1722
+ return build_cfg(w, h, fs, fc, gc, bg, panel, sig, sug, ms, al,
1723
+ dot_col=dot, line_col=line, fill_col=fill)
1724
+
1725
+ cfg_mh = mkc(mh_w, mh_h, mh_fs, mh_fc, bg=mh_bg, panel=mh_panel,
1726
+ sig=mh_sig, sug=mh_sug, ms=mh_ms, al=mh_alpha, dot=mh_dot)
1727
+ cfg_qq = mkc(qq_w, qq_h, qq_fs, qq_fc, bg=qq_bg, panel=qq_panel,
1728
+ ms=qq_ms, dot=qq_dot, line=qq_line, fill=qq_fill)
1729
+ cfg_ci = mkc(ci_w, ci_h, ci_fs, sig=ci_sig, sug=ci_sug)
1730
+ cfg_ld = mkc(ld_w, ld_h, ld_fs, dot=ld_dot, line=ld_line)
1731
+ # PCA uses dark theme β€” cfg built inside plot_pca with dark defaults
1732
+ cfg_pc = build_cfg(pc_w, pc_h, pc_fs,
1733
+ font_color=TEXT_MAIN, gc=GRID_LINE,
1734
+ bg=BG_DARK, panel=PANEL_DARK,
1735
+ sig_col=ACCENT_TEAL, sug_col=ACCENT_GOLD,
1736
+ marker_size=55, alpha=0.80)
1737
+ cfg_ki = mkc(ki_w, ki_h, ki_fs, bg=ki_bg, panel=ki_panel, dot=ki_dot)
1738
+ cfg_ef = mkc(ef_w, ef_h, ef_fs, bg=ef_bg,
1739
+ dot=ef_pos, line=ef_neg, fill=ef_fill)
1740
+ cfg_co = mkc(co_w, co_h, 7, sig=co_sig, sug=co_sug)
1741
+ cfg_db = mkc(db_w, db_h, 9, dot=db_dot)
1742
+
1743
+ # Generate all plots
1744
  plot_dict = {}
1745
  plot_dict["01_Manhattan_Primary"] = plot_manhattan(
1746
  primary_p, chr_filt, pos_filt,
 
1764
 
1765
  imgs = [_pil(plot_dict[k]) for k in sorted(plot_dict.keys())]
1766
 
1767
+ # Save files
1768
  tmp_dir = tempfile.mkdtemp()
1769
  zip_path = save_all_plots_zip(plot_dict, tmp_dir)
1770
  excel_path = os.path.join(tmp_dir, "gwas_results_top15.xlsx")
 
1772
  y, G_filt, maf_vals, excel_path, top_n)
1773
  plt.close('all')
1774
 
1775
+ # Build threshold explanation string
1776
+ thresh_explanation = ""
1777
+ for mname, (p, _, _) in all_results.items():
1778
+ _, _, expl = compute_thresholds(len(p), mname)
1779
+ thresh_explanation += expl + "\n"
1780
+
1781
  bonf = 0.05 / len(primary_p)
1782
  lambdas_str = "\n ".join([
1783
  f"{m}: Ξ»={np.median(stats.chi2.ppf(1-np.clip(p,1e-10,1),df=1))/stats.chi2.ppf(0.5,df=1):.4f} "
1784
+ f"sig(Bonf)={int((p<0.05/len(p)).sum())} sig(Sug)={int((p<1.0/len(p)).sum())}"
1785
  for m, (p, _, _) in all_results.items()
1786
  ])
1787
  lam = (np.median(stats.chi2.ppf(1-np.clip(primary_p,1e-10,1),df=1)) /
 
1797
  f" PER-MODEL RESULTS:\n {lambdas_str}\n"
1798
  f"{'─'*68}\n"
1799
  f" Primary model ({models_to_run[0]}):\n"
1800
+ f" Bonferroni threshold : {bonf:.2e} (-log₁₀ = {-np.log10(bonf):.2f})\n"
1801
+ f" Suggestive threshold : {1/len(primary_p):.2e} (-log₁₀ = {-np.log10(1/len(primary_p)):.2f})\n"
1802
+ f" Significant (Bonf.) : {int((primary_p<bonf).sum())}\n"
1803
+ f" Significant (Sug.) : {int((primary_p<1/len(primary_p)).sum())}\n"
1804
  f" Genomic Inflation Ξ» : {lam:.4f}\n"
1805
  f"{'─'*68}\n"
1806
+ f" πŸ“Œ THRESHOLD EXPLANATIONS (see Excel sheet 'Threshold_Explanation'):\n\n"
1807
+ + thresh_explanation +
1808
+ f"{'─'*68}\n"
1809
  f" πŸ“₯ Excel: gwas_results_top15.xlsx\n"
1810
  f" πŸ–Ό Plots: gwas_plots.zip ({len(plot_dict)} PNG files)\n"
1811
  f"{'='*68}\n"
 
1821
  body, .gradio-container { background:#F7F8FC!important; font-family:'DM Sans',sans-serif!important; color:#2D3142!important; }
1822
  .gradio-container { max-width:1500px!important; margin:0 auto!important; }
1823
  .gwas-header { background:linear-gradient(135deg,#E8F4FD 0%,#EDE9F8 50%,#FDF0F8 100%); border:1px solid #D6E8F5; border-radius:18px; padding:24px 32px; margin-bottom:20px; box-shadow:0 2px 20px rgba(100,120,200,0.08); }
1824
+ .gwas-header h1 { font-size:22px!important; font-weight:600!important; color:#2C5F8A!important; margin:0 0 4px 0!important; }
1825
  .gwas-header p { color:#6B7A99!important; font-size:13px!important; margin:3px 0!important; }
1826
  .gr-panel, .gr-box, .block, .panel { background:#FFFFFF!important; border:1px solid #E8ECF4!important; border-radius:14px!important; box-shadow:0 1px 8px rgba(60,80,140,0.06)!important; }
1827
  label, .label-wrap span { color:#5A6480!important; font-size:11px!important; font-weight:500!important; text-transform:uppercase!important; letter-spacing:0.5px!important; }
 
1830
  .tab-nav { background:#F0F3FB!important; border-radius:10px!important; padding:3px!important; border:1px solid #E4E8F5!important; overflow-x:auto!important; }
1831
  .tab-nav button { color:#6B7A99!important; font-size:11px!important; font-weight:500!important; border-radius:8px!important; padding:6px 12px!important; border:none!important; background:transparent!important; white-space:nowrap!important; }
1832
  .tab-nav button.selected, .tab-nav button:hover { background:#FFFFFF!important; color:#5BA8E5!important; box-shadow:0 1px 6px rgba(91,168,229,0.2)!important; }
1833
+ .summary-box textarea { font-family:'DM Mono',monospace!important; font-size:10px!important; background:#F8F9FF!important; }
1834
  ::-webkit-scrollbar { width:5px; height:5px; }
1835
  ::-webkit-scrollbar-thumb { background:#C8D0E7; border-radius:4px; }
1836
  .cfg-panel { background:#F4F6FF!important; border-radius:10px!important; padding:10px!important; border:1px solid #DDE2F0!important; }
 
1850
  IRRI-50,22,0,0,0,2"""
1851
 
1852
  # ─────────────────────── GRADIO INTERFACE ────────────────────────────────────────
1853
+ with gr.Blocks(css=CSS, title="🧬 GWAS Pipeline v3", theme=gr.themes.Base()) as demo:
1854
 
1855
  gr.HTML("""
1856
  <div class="gwas-header">
1857
+ <h1>🧬 GWAS Analysis Pipeline v3 β€” Chr Labels Β· Threshold Explanations Β· QQ Regression Β· Dark PCA Β· No Scree</h1>
1858
+ <p>OLS Β· MLM Β· EMMAX Β· FarmCPU Β· GEMMA &nbsp;|&nbsp; Bonferroni & Suggestive on ALL plots Β· Full Color Customization</p>
1859
+ <p style="font-size:12px;color:#8892B0;">Circos with Chr numbers on bands Β· QQ with regression line Β· PCA dark theme Β· Scree plot removed</p>
1860
  </div>
1861
  """)
1862
 
1863
  with gr.Row(equal_height=False):
 
1864
  with gr.Column(scale=1, min_width=300):
1865
  gr.HTML('<div style="font-size:11px;font-weight:600;color:#8892B0;text-transform:uppercase;letter-spacing:1px;padding:6px 0 3px;border-bottom:1px solid #E8ECF4;margin-bottom:8px">πŸ“‚ Data Input</div>')
1866
  file_in = gr.File(label="Upload CSV / TSV / TXT", file_types=[".csv",".tsv",".txt"])
 
1876
  run_btn = gr.Button("πŸš€ Run Complete GWAS Pipeline", variant="primary")
1877
 
1878
  gr.HTML('<div style="font-size:11px;font-weight:600;color:#8892B0;text-transform:uppercase;letter-spacing:1px;padding:6px 0 3px;border-bottom:1px solid #E8ECF4;margin-bottom:8px;margin-top:12px">πŸ“₯ Downloads</div>')
1879
+ excel_out = gr.File(label="πŸ“Š Excel (MTAs Β· Thresholds Β· PVE Β· QTN Β· All Models)", interactive=False)
1880
  zip_out = gr.File(label="πŸ–Ό All Plots as PNG (ZIP)", interactive=False)
1881
 
 
1882
  with gr.Column(scale=2):
1883
+ gr.HTML('<div style="font-size:11px;font-weight:600;color:#8892B0;text-transform:uppercase;letter-spacing:1px;padding:6px 0 3px;border-bottom:1px solid #E8ECF4;margin-bottom:8px">πŸ“Š Analysis Summary + Threshold Explanations</div>')
1884
+ summary_out = gr.Textbox(label="", lines=32, show_label=False, elem_classes=["summary-box"])
1885
 
1886
+ # ── Plot Customization Panels ──────────────────────────────────────────────
1887
+ gr.HTML('<div style="font-size:11px;font-weight:600;color:#8892B0;text-transform:uppercase;letter-spacing:1px;padding:12px 0 4px;border-bottom:1px solid #E8ECF4;margin-bottom:8px">🎨 Plot Customization (Full Color Control)</div>')
1888
 
1889
  with gr.Accordion("πŸ—Ί Manhattan Plot Options", open=False):
1890
+ gr.HTML('<p style="font-size:11px;color:#8892B0;margin:4px 0">Both Bonferroni (0.05/m) and Suggestive (1/m) thresholds shown on all Manhattan plots.</p>')
1891
  with gr.Row():
1892
  mh_w = gr.Slider(8, 24, 16, 1, label="Width")
1893
  mh_h = gr.Slider(3, 12, 5, 0.5, label="Height")
1894
  mh_fs = gr.Slider(6, 18, 9, 1, label="Font Size")
1895
  with gr.Row():
1896
  mh_fc = gr.ColorPicker(value="#2D3142", label="Font Color")
1897
+ mh_sig = gr.ColorPicker(value="#E15759", label="Bonferroni Line Color")
1898
  mh_sug = gr.ColorPicker(value="#4E79A7", label="Suggestive Line Color")
1899
  with gr.Row():
1900
+ mh_ms = gr.Slider(2, 60, 12, 1, label="Marker Size")
1901
  mh_alpha= gr.Slider(0.1, 1.0, 0.75, 0.05, label="Marker Alpha")
1902
+ with gr.Row():
1903
  mh_bg = gr.ColorPicker(value="#FFFFFF", label="Background Color")
1904
+ mh_panel= gr.ColorPicker(value="#FAFBFF", label="Panel Color")
1905
+ mh_dot = gr.ColorPicker(value="#4E79A7", label="Dot Color (overridden by chr colors)")
1906
 
1907
  with gr.Accordion("πŸ“ˆ QQ Plot Options", open=False):
1908
+ gr.HTML('<p style="font-size:11px;color:#8892B0;margin:4px 0">QQ plots include 95% CI band, regression line (slope + RΒ²), and Ξ» inflation factor.</p>')
1909
  with gr.Row():
1910
  qq_w = gr.Slider(5, 16, 7, 0.5, label="Width")
1911
  qq_h = gr.Slider(5, 16, 7, 0.5, label="Height")
1912
  qq_fs = gr.Slider(6, 18, 10, 1, label="Font Size")
1913
  with gr.Row():
1914
+ qq_fc = gr.ColorPicker(value="#2D3142", label="Font Color")
1915
+ qq_ms = gr.Slider(5, 80, 22, 1, label="Marker Size")
1916
+ with gr.Row():
1917
+ qq_dot = gr.ColorPicker(value="#A78BFA", label="Dot Color")
1918
+ qq_line = gr.ColorPicker(value="#E15759", label="Regression Line Color")
1919
+ qq_fill = gr.ColorPicker(value="#A78BFA", label="CI Fill Color")
1920
+ with gr.Row():
1921
+ qq_bg = gr.ColorPicker(value="#FFFFFF", label="Background Color")
1922
+ qq_panel= gr.ColorPicker(value="#FAFBFF", label="Panel Color")
1923
 
1924
  with gr.Accordion("πŸ”΅ Circos Plot Options", open=False):
1925
+ gr.HTML('<p style="font-size:11px;color:#8892B0;margin:4px 0">Chr numbers shown on outer bands. Bonferroni (dashed) and Suggestive (dotted) threshold rings shown per model.</p>')
1926
  with gr.Row():
1927
+ ci_w = gr.Slider(8, 22, 14, 1, label="Width")
1928
+ ci_h = gr.Slider(8, 22, 14, 1, label="Height")
1929
+ ci_fs = gr.Slider(5, 16, 8, 1, label="Font Size")
1930
+ with gr.Row():
1931
+ ci_sig = gr.ColorPicker(value="#E15759", label="Bonferroni Ring Color")
1932
+ ci_sug = gr.ColorPicker(value="#4E79A7", label="Suggestive Ring Color")
1933
 
1934
  with gr.Accordion("πŸ”— LD Decay Options", open=False):
1935
  with gr.Row():
1936
+ ld_w = gr.Slider(8, 24, 16, 1, label="Width")
1937
+ ld_h = gr.Slider(3, 12, 6, 0.5, label="Height")
1938
+ ld_fs = gr.Slider(6, 18, 9, 1, label="Font Size")
1939
+ with gr.Row():
1940
+ ld_dot = gr.ColorPicker(value="#4E79A7", label="Dot Color")
1941
+ ld_line = gr.ColorPicker(value="#E15759", label="Trend Line Color")
1942
 
1943
+ with gr.Accordion("πŸ”¬ PCA Options (Dark Theme)", open=False):
1944
+ gr.HTML('<p style="font-size:11px;color:#8892B0;margin:4px 0">PCA uses a dark background by design. Scree plot removed. Showing PC1v2, PC2v3, Population Structure.</p>')
1945
  with gr.Row():
1946
+ pc_w = gr.Slider(8, 22, 14, 1, label="Width")
1947
+ pc_h = gr.Slider(4, 14, 10, 1, label="Height")
1948
+ pc_fs = gr.Slider(6, 18, 9, 1, label="Font Size")
1949
 
1950
  with gr.Accordion("πŸ‘¨β€πŸ‘©β€πŸ‘§ Kinship / Dendrogram Options", open=False):
1951
+ gr.HTML('<p style="font-size:11px;color:#8892B0;margin:4px 0">For >50 samples, dendrogram auto-truncates to last 30 nodes.</p>')
1952
+ with gr.Row():
1953
+ ki_w = gr.Slider(8, 22, 14, 1, label="Width")
1954
+ ki_h = gr.Slider(6, 20, 12, 1, label="Height")
1955
+ ki_fs = gr.Slider(6, 18, 9, 1, label="Font Size")
1956
  with gr.Row():
1957
+ ki_dot = gr.ColorPicker(value="#4E79A7", label="Dot/Bar Color")
1958
+ ki_bg = gr.ColorPicker(value="#FFFFFF", label="Background Color")
1959
+ ki_panel= gr.ColorPicker(value="#FAFBFF", label="Panel Color")
 
1960
 
1961
  with gr.Accordion("βš– Effect Sizes Options", open=False):
1962
  with gr.Row():
1963
+ ef_w = gr.Slider(8, 22, 14, 1, label="Width")
1964
+ ef_h = gr.Slider(5, 18, 10, 1, label="Height")
1965
+ ef_fs = gr.Slider(6, 18, 9, 1, label="Font Size")
1966
+ with gr.Row():
1967
+ ef_pos = gr.ColorPicker(value="#4E79A7", label="Positive Effect Color")
1968
+ ef_neg = gr.ColorPicker(value="#E15759", label="Negative Effect Color")
1969
+ ef_fill = gr.ColorPicker(value="#A78BFA", label="Distribution Fill Color")
1970
+ ef_bg = gr.ColorPicker(value="#FFFFFF", label="Background Color")
1971
 
1972
  with gr.Accordion("πŸ”„ All-Models Manhattan Options", open=False):
1973
+ gr.HTML('<p style="font-size:11px;color:#8892B0;margin:4px 0">Both thresholds shown on each model subplot.</p>')
1974
+ with gr.Row():
1975
+ co_w = gr.Slider(8, 24, 16, 1, label="Width")
1976
+ co_h = gr.Slider(2, 8, 3.5, 0.5, label="Height per model")
1977
  with gr.Row():
1978
+ co_sig = gr.ColorPicker(value="#E15759", label="Bonferroni Line Color")
1979
+ co_sug = gr.ColorPicker(value="#4E79A7", label="Suggestive Line Color")
1980
 
1981
  with gr.Accordion("πŸ“Š Dashboard Options", open=False):
1982
  with gr.Row():
1983
+ db_w = gr.Slider(8, 24, 15, 1, label="Width")
1984
+ db_h = gr.Slider(5, 18, 10, 1, label="Height")
1985
+ db_dot = gr.ColorPicker(value="#4E79A7", label="Bar/Dot Color")
1986
 
1987
  # ── Visualization Tabs ────────────────────────────────────────────────────
1988
  gr.HTML('<div style="font-size:11px;font-weight:600;color:#8892B0;text-transform:uppercase;letter-spacing:1px;padding:12px 0 4px;border-bottom:1px solid #E8ECF4;margin-bottom:8px">πŸ–Ό Visualizations</div>')
1989
  with gr.Tabs():
1990
  with gr.Tab("πŸ—Ί Manhattan"):
1991
+ img1 = gr.Image(type="pil", label="Manhattan β€” Primary Model (Chr labels Β· both thresholds Β· β—† = Top MTAs)")
1992
  with gr.Tab("πŸ“ˆ QQ Primary"):
1993
+ img2 = gr.Image(type="pil", label="QQ Plot β€” Regression line + CI + Ξ»")
1994
  with gr.Tab("πŸ“ˆ QQ All Models"):
1995
+ img3 = gr.Image(type="pil", label="QQ Plots β€” All Models with Regression")
1996
  with gr.Tab("πŸ“Š QQ Overlay"):
1997
+ img4 = gr.Image(type="pil", label="QQ Overlay (solid=obs, dashed=regression per model)")
1998
  with gr.Tab("πŸ”΅ Circos"):
1999
+ img5 = gr.Image(type="pil", label="Circos β€” Chr numbers on bands Β· Threshold rings Β· Ribbons")
2000
  with gr.Tab("πŸ”— LD Decay"):
2001
  img6 = gr.Image(type="pil", label="LD Decay (bp & Mb)")
2002
+ with gr.Tab("πŸ”¬ PCA (Dark)"):
2003
+ img7 = gr.Image(type="pil", label="PCA β€” Dark theme (PC1v2, PC2v3, Population Structure)")
2004
  with gr.Tab("πŸ‘¨β€πŸ‘©β€πŸ‘§ Kinship"):
2005
  img8 = gr.Image(type="pil", label="Kinship & Dendrogram")
2006
  with gr.Tab("βš– Effect Sizes"):
2007
  img9 = gr.Image(type="pil", label="Effect Sizes & Volcano Plot")
2008
  with gr.Tab("πŸ”„ All Models MH"):
2009
+ img10 = gr.Image(type="pil", label="All-Models Manhattan (Chr labels Β· both thresholds)")
2010
  with gr.Tab("πŸ“Š Dashboard"):
2011
+ img11 = gr.Image(type="pil", label="Summary Dashboard (Threshold table replaces Scree plot)")
2012
 
2013
  all_inputs = [
2014
  file_in, text_in, model_sel, maf_thr, top_n_sl,
2015
  # Manhattan
2016
  mh_w, mh_h, mh_fs, mh_fc, mh_ms, mh_alpha, mh_bg, mh_sig, mh_sug,
2017
+ mh_dot, mh_panel,
2018
  # QQ
2019
+ qq_w, qq_h, qq_fs, qq_fc, qq_ms, qq_dot, qq_line, qq_fill, qq_bg, qq_panel,
2020
  # Circos
2021
+ ci_w, ci_h, ci_fs, ci_sig, ci_sug,
2022
  # LD
2023
+ ld_w, ld_h, ld_fs, ld_dot, ld_line,
2024
  # PCA
2025
  pc_w, pc_h, pc_fs,
2026
  # Kinship
2027
+ ki_w, ki_h, ki_fs, ki_dot, ki_bg, ki_panel,
2028
  # Effect
2029
+ ef_w, ef_h, ef_fs, ef_pos, ef_neg, ef_fill, ef_bg,
2030
  # Comparison
2031
+ co_w, co_h, co_sig, co_sug,
2032
  # Dashboard
2033
+ db_w, db_h, db_dot,
2034
  ]
2035
 
2036
  run_btn.click(