softwareDevelopment commited on
Commit
87da912
Β·
verified Β·
1 Parent(s): 0464ae9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +507 -265
app.py CHANGED
@@ -21,36 +21,29 @@ import io, re, itertools
21
  from io import StringIO
22
  from statsmodels.stats.multitest import multipletests
23
 
24
- # ─────────────────────────── MODIFIED THEME ────────────────────────────
25
- # Professional dark color scheme for Manhattan plots
26
- BG_LIGHT = "#F8F9FA" # Light gray background for overall UI
27
- PANEL_PASTEL= "#FFFFFF" # White panels
28
- ACCENT_PINK = "#DC3545" # Red for threshold lines
29
- ACCENT_MINT = "#2C7DA0" # Standard dark blue for non-significant SNPs
30
- ACCENT_LAV = "#6C757D" # Gray for alternate
31
- ACCENT_PEACH= "#FD7E14" # Orange accent
32
- ACCENT_GOLD = "#FFD700" # Bright gold for significant MTAs (highlighted)
33
- ACCENT_CORAL= "#E85D5D" # Coral
34
- ACCENT_SAGE = "#20C997" # Teal
35
- ACCENT_BLUE = "#0D6EFD" # Bootstrap blue
36
- TEXT_SOFT = "#212529" # Dark text
37
- TEXT_LIGHT = "#6C757D" # Gray text
38
- GRID_SOFT = "#DEE2E6" # Soft grid
39
-
40
- def style_fig(fig, is_manhattan=False):
41
- """Style figure with manhattan-specific adjustments"""
42
  fig.patch.set_facecolor(BG_LIGHT)
43
  for ax in fig.get_axes():
44
  ax.set_facecolor(PANEL_PASTEL)
45
  ax.tick_params(colors=TEXT_SOFT, labelsize=9)
46
  ax.xaxis.label.set_color(TEXT_SOFT)
47
  ax.yaxis.label.set_color(TEXT_SOFT)
48
- if is_manhattan:
49
- ax.title.set_color(ACCENT_BLUE)
50
- ax.title.set_fontweight('bold')
51
- ax.title.set_fontsize(14)
52
- else:
53
- ax.title.set_color(ACCENT_PINK)
54
  for spine in ax.spines.values():
55
  spine.set_edgecolor(GRID_SOFT)
56
  ax.grid(color=GRID_SOFT, linewidth=0.5, linestyle="--", alpha=0.6)
@@ -295,23 +288,24 @@ def farmcpu_gwas(y, G, K):
295
  betas[j] = slope
296
  return pvals, betas
297
 
298
- # ─────────────────────────── MODIFIED MANHATTAN PLOT (DARK COLOR + HIGHLIGHTED MTAs) ───────────────────
299
 
300
  def plot_manhattan(pvals, chroms, positions, title="Manhattan Plot"):
301
  """
302
- Manhattan plot with standard dark color scheme and highlighted significant MTAs.
303
  Significant MTAs (p < 5e-8) are shown as large gold stars.
304
  """
305
  fig, ax = plt.subplots(figsize=(14, 5))
306
- style_fig(fig, is_manhattan=True)
307
  log_p = -np.log10(np.clip(pvals, 1e-300, 1))
308
- sig_line = -np.log10(5e-8) # Standard genome-wide significance threshold
309
 
310
- # Professional dark color palette for chromosomes (standard dark colors)
311
  chrom_list = sorted(set(chroms))
 
312
  dark_palette = [
313
  '#1B4F72', # Dark Blue
314
- '#1E8449', # Dark Green
315
  '#6C3483', # Dark Purple
316
  '#B7950B', # Dark Gold
317
  '#C0392B', # Dark Red
@@ -331,11 +325,6 @@ def plot_manhattan(pvals, chroms, positions, title="Manhattan Plot"):
331
  x_offset = 0
332
  tick_pos, tick_lab, x_coords = [], [], np.zeros(len(pvals))
333
 
334
- # Track which SNPs are significant
335
- sig_mask = log_p >= sig_line
336
- n_sig = sig_mask.sum()
337
-
338
- # Plot each chromosome
339
  for ch in chrom_list:
340
  mask = chroms == ch
341
  pos = positions[mask]
@@ -346,94 +335,59 @@ def plot_manhattan(pvals, chroms, positions, title="Manhattan Plot"):
346
  x_coords[np.where(mask)[0][order]] = x_vals
347
  tick_pos.append(x_vals.mean())
348
  tick_lab.append(f"Chr{ch}")
349
-
350
- # Plot non-significant SNPs with standard dark color
351
- chr_mask = mask & ~sig_mask
352
- if chr_mask.any():
353
- ax.scatter(x_coords[chr_mask], log_p[chr_mask],
354
- c=chrom_colors[ch], s=25, alpha=0.7, zorder=1)
355
-
356
- # Plot significant SNPs for this chromosome (will be overplotted with stars)
357
- chr_sig_mask = mask & sig_mask
358
- if chr_sig_mask.any():
359
- ax.scatter(x_coords[chr_sig_mask], log_p[chr_sig_mask],
360
- c=chrom_colors[ch], s=30, alpha=0.9, zorder=2, edgecolors='black', linewidth=0.5)
361
-
362
  x_offset += (pos.max() - pos.min()) + max(positions) * 0.01
363
 
364
- # Highlight significant MTAs with gold stars (overplot for emphasis)
 
365
  if sig_mask.any():
366
  ax.scatter(x_coords[sig_mask], log_p[sig_mask],
367
- c='#FFD700', s=180, marker="*", zorder=10,
368
- edgecolors='#B8860B', linewidth=1.5,
369
- alpha=0.95, label=f"🌟 Significant MTA ({n_sig} SNPs)")
370
-
371
- # Add Bonferroni threshold line
372
- ax.axhline(sig_line, color='#DC3545', ls="--", lw=2, alpha=0.8, label="Bonferroni (5e-8)")
373
-
374
- # Add suggestive threshold (optional)
375
- suggestive_line = -np.log10(1e-5)
376
- ax.axhline(suggestive_line, color='#FD7E14', ls=":", lw=1.5, alpha=0.6, label="Suggestive (1e-5)")
377
 
 
378
  ax.set_xticks(tick_pos)
379
- ax.set_xticklabels(tick_lab, rotation=45, ha='right', fontsize=9)
380
- ax.set_ylabel("-log₁₀(p)", fontsize=12, fontweight='bold')
381
- ax.set_xlabel("Chromosome", fontsize=12, fontweight='bold')
382
- ax.set_title(title, fontsize=14, fontweight='bold', color='#1B4F72')
383
- ax.legend(loc='upper right', fontsize=10, framealpha=0.95, fancybox=True, shadow=True)
384
-
385
- # Add alternating light gray background bands for chromosomes
386
- for i, ch in enumerate(chrom_list):
387
- mask = chroms == ch
388
- if mask.any() and i % 2 == 1:
389
- x_min = x_coords[mask].min() if mask.any() else 0
390
- x_max = x_coords[mask].max() if mask.any() else 0
391
- ax.axvspan(x_min - 0.5e6, x_max + 0.5e6, alpha=0.08, color='gray', zorder=0)
392
-
393
- # Set y-axis limits with some padding
394
- y_max = max(log_p.max() * 1.05, sig_line + 1)
395
- ax.set_ylim(0, y_max)
396
-
397
  fig.tight_layout()
398
  return fig
399
 
 
 
 
 
 
 
 
 
 
400
  def plot_qq(pvals, title="QQ Plot"):
401
- """QQ plot for p-value distribution"""
402
  fig, ax = plt.subplots(figsize=(6, 6))
403
  style_fig(fig)
404
  n = len(pvals)
405
  obs = np.sort(-np.log10(np.clip(pvals, 1e-300, 1)))[::-1]
406
  exp = -np.log10(np.linspace(1/n, 1, n)[::-1])
407
 
408
- # Confidence intervals
409
  ci_lower = -np.log10(stats.beta.ppf(0.975, np.arange(1, n+1), np.arange(n, 0, -1)))
410
  ci_upper = -np.log10(stats.beta.ppf(0.025, np.arange(1, n+1), np.arange(n, 0, -1)))
411
- ax.fill_between(exp, ci_lower, ci_upper, alpha=0.25, color=ACCENT_SAGE, label="95% CI")
412
- ax.scatter(exp, obs, c=ACCENT_BLUE, s=25, alpha=0.8, edgecolors='white', linewidth=0.5)
413
- ax.plot([0, max(exp)], [0, max(exp)], color=ACCENT_PINK, ls="--", lw=2, label="Expected")
414
-
415
- # Genomic inflation factor
416
- lam = np.median(stats.chi2.ppf(1 - np.clip(pvals, 1e-10, 1), df=1)) / stats.chi2.ppf(0.5, df=1)
417
- ax.text(0.05, 0.92, f"Ξ» = {lam:.4f}", transform=ax.transAxes, fontsize=11,
418
- bbox=dict(boxstyle="round,pad=0.3", facecolor='white', alpha=0.8))
419
- ax.set_xlabel("Expected -log₁₀(p)", fontsize=11)
420
- ax.set_ylabel("Observed -log₁₀(p)", fontsize=11)
421
- ax.set_title(title, fontsize=12, fontweight='bold')
422
  fig.tight_layout()
423
  return fig
424
 
425
- def fig_to_pil(fig):
426
- """Convert matplotlib figure to PIL Image"""
427
- buf = io.BytesIO()
428
- fig.savefig(buf, format="png", dpi=150, bbox_inches="tight", facecolor=fig.get_facecolor())
429
- buf.seek(0)
430
- from PIL import Image
431
- return Image.open(buf).copy()
432
-
433
- # ──────────────��──────────── OTHER PLOTTING FUNCTIONS ───────────────────
434
-
435
  def plot_pca(G, y, ids):
436
- """PCA analysis plot"""
437
  fig, axes = plt.subplots(2, 2, figsize=(14, 12))
438
  style_fig(fig)
439
 
@@ -444,224 +398,515 @@ def plot_pca(G, y, ids):
444
  pcs = pca.fit_transform(G_sc)
445
  var_exp = pca.explained_variance_ratio_ * 100
446
 
447
- sc = axes[0,0].scatter(pcs[:,0], pcs[:,1], c=y, cmap='coolwarm', s=60, edgecolors='white', linewidth=0.5)
448
- axes[0,0].set_xlabel(f"PC1 ({var_exp[0]:.1f}%)", fontsize=11)
449
- axes[0,0].set_ylabel(f"PC2 ({var_exp[1]:.1f}%)", fontsize=11)
450
- axes[0,0].set_title("PCA: PC1 vs PC2", fontweight='bold')
451
  plt.colorbar(sc, ax=axes[0,0], label="Phenotype")
452
 
453
  if n_comp >= 4:
454
- sc2 = axes[0,1].scatter(pcs[:,2], pcs[:,3], c=y, cmap='coolwarm', s=60, edgecolors='white', linewidth=0.5)
455
- axes[0,1].set_xlabel(f"PC3 ({var_exp[2]:.1f}%)", fontsize=11)
456
- axes[0,1].set_ylabel(f"PC4 ({var_exp[3]:.1f}%)", fontsize=11)
457
- axes[0,1].set_title("PCA: PC3 vs PC4", fontweight='bold')
458
- plt.colorbar(sc2, ax=axes[0,1], label="Phenotype")
459
  else:
460
- axes[0,1].text(0.5, 0.5, "Insufficient components", ha='center', va='center', transform=axes[0,1].transAxes, fontsize=14)
461
- axes[0,1].set_title("PCA: Additional Components")
462
-
463
- axes[1,0].bar(range(1, n_comp+1), var_exp, color=ACCENT_BLUE, edgecolor='white', alpha=0.8)
464
- axes[1,0].plot(range(1, n_comp+1), np.cumsum(var_exp), color=ACCENT_PINK, marker='o', lw=2, markersize=8, label="Cumulative")
465
- axes[1,0].set_xlabel("Principal Component", fontsize=11)
466
- axes[1,0].set_ylabel("Variance Explained (%)", fontsize=11)
467
- axes[1,0].set_title("Scree Plot", fontweight='bold')
468
  axes[1,0].legend()
469
- axes[1,0].grid(True, alpha=0.3)
470
 
471
- axes[1,1].scatter(pcs[:,0], pcs[:,1], c=y, cmap='coolwarm', s=60, edgecolors='white', linewidth=0.5)
472
- axes[1,1].set_xlabel(f"PC1 ({var_exp[0]:.1f}%)", fontsize=11)
473
- axes[1,1].set_ylabel(f"PC2 ({var_exp[1]:.1f}%)", fontsize=11)
474
- axes[1,1].set_title("Population Structure", fontweight='bold')
475
 
476
  fig.tight_layout()
477
  return fig
478
 
479
  def plot_phenotype_distribution(y, ids):
480
- """Phenotype distribution analysis"""
481
  fig, axes = plt.subplots(2, 2, figsize=(14, 10))
482
  style_fig(fig)
483
 
484
- axes[0,0].hist(y, bins=15, color=ACCENT_BLUE, edgecolor='white', alpha=0.7)
485
  axes[0,0].axvline(y.mean(), color=ACCENT_PINK, lw=2, ls='--', label=f"Mean: {y.mean():.2f}")
486
  axes[0,0].axvline(y.mean() + y.std(), color=ACCENT_GOLD, lw=1.5, ls=':', label="Β±1 SD")
487
  axes[0,0].axvline(y.mean() - y.std(), color=ACCENT_GOLD, lw=1.5, ls=':')
488
- axes[0,0].set_xlabel("Phenotype", fontsize=11)
489
- axes[0,0].set_ylabel("Frequency", fontsize=11)
490
- axes[0,0].set_title("Phenotype Distribution", fontweight='bold')
491
  axes[0,0].legend()
492
 
493
  bp = axes[0,1].boxplot(y, vert=True, patch_artist=True)
494
  for patch in bp['boxes']:
495
- patch.set_facecolor(ACCENT_SAGE)
496
  patch.set_edgecolor(ACCENT_PINK)
497
  axes[0,1].set_xticklabels(['Phenotype'])
498
- axes[0,1].set_ylabel("Value", fontsize=11)
499
- axes[0,1].set_title("Box Plot", fontweight='bold')
500
 
501
  stats.probplot(y, dist="norm", plot=axes[1,0])
502
- axes[1,0].set_title("Normal Q-Q Plot", fontweight='bold')
503
- axes[1,0].get_lines()[0].set_color(ACCENT_BLUE)
504
  axes[1,0].get_lines()[1].set_color(ACCENT_PINK)
505
 
506
- axes[1,1].hist(y, bins=15, density=True, color=ACCENT_BLUE, alpha=0.7, edgecolor='white')
507
  x_dense = np.linspace(y.min(), y.max(), 100)
508
  kde = stats.gaussian_kde(y)
509
  axes[1,1].plot(x_dense, kde(x_dense), color=ACCENT_PINK, lw=2)
510
- axes[1,1].set_xlabel("Phenotype", fontsize=11)
511
- axes[1,1].set_ylabel("Density", fontsize=11)
512
- axes[1,1].set_title("Density Plot", fontweight='bold')
513
 
514
  fig.tight_layout()
515
  return fig
516
 
517
  def plot_maf_analysis(maf, snp_names):
518
- """MAF analysis plots"""
519
  fig, axes = plt.subplots(2, 2, figsize=(14, 10))
520
  style_fig(fig)
521
 
522
- axes[0,0].hist(maf, bins=20, color=ACCENT_BLUE, edgecolor='white', alpha=0.7)
523
  axes[0,0].axvline(0.05, color=ACCENT_PINK, ls='--', lw=2, label="MAF=0.05")
524
- axes[0,0].set_xlabel("Minor Allele Frequency", fontsize=11)
525
- axes[0,0].set_ylabel("Count", fontsize=11)
526
- axes[0,0].set_title("MAF Distribution", fontweight='bold')
527
  axes[0,0].legend()
528
 
529
  order = np.argsort(maf)[::-1]
530
- colors = [ACCENT_BLUE if m >= 0.05 else ACCENT_LAV for m in maf[order]]
531
- axes[0,1].bar(range(min(50, len(maf))), maf[order][:50], color=colors[:50], edgecolor='white')
532
  axes[0,1].axhline(0.05, color=ACCENT_PINK, ls='--', lw=1.5)
533
- axes[0,1].set_xlabel("SNP Index", fontsize=11)
534
- axes[0,1].set_ylabel("MAF", fontsize=11)
535
- axes[0,1].set_title("Top 50 SNPs by MAF", fontweight='bold')
536
 
537
  rare_mask = maf < 0.05
538
- axes[1,0].pie([rare_mask.sum(), (~rare_mask).sum()],
539
- labels=[f"Rare (MAF<0.05): {rare_mask.sum()}", f"Common: {(~rare_mask).sum()}"],
540
- colors=[ACCENT_PINK, ACCENT_BLUE], autopct='%1.1f%%', startangle=90)
541
- axes[1,0].set_title("Rare vs Common Variants", fontweight='bold')
 
 
 
 
 
 
 
 
 
542
 
543
- axes[1,1].text(0.5, 0.5,
544
- f"MAF Summary Statistics\n\nMean MAF: {np.mean(maf):.4f}\nMedian MAF: {np.median(maf):.4f}\nMin MAF: {np.min(maf):.4f}\nMax MAF: {np.max(maf):.4f}",
545
- ha='center', va='center', transform=axes[1,1].transAxes, fontsize=12)
546
- axes[1,1].set_title("MAF Summary", fontweight='bold')
547
- axes[1,1].axis('off')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
548
 
549
  fig.tight_layout()
550
  return fig
551
 
552
  def plot_effect_sizes(pvals, betas, snp_names):
553
- """Effect size analysis plots"""
554
  fig, axes = plt.subplots(2, 2, figsize=(14, 10))
555
  style_fig(fig)
556
 
557
  top_idx = np.argsort(np.abs(betas))[-20:]
558
  top_betas = betas[top_idx]
559
  top_names = [snp_names[i][:15] for i in top_idx]
560
- colors = [ACCENT_PINK if b < 0 else ACCENT_BLUE for b in top_betas]
561
 
562
- axes[0,0].barh(range(len(top_betas)), top_betas, color=colors, edgecolor='white')
563
  axes[0,0].axvline(0, color='black', lw=0.5)
564
  axes[0,0].set_yticks(range(len(top_betas)))
565
  axes[0,0].set_yticklabels(top_names, fontsize=8)
566
- axes[0,0].set_xlabel("Effect Size (Ξ²)", fontsize=11)
567
- axes[0,0].set_title("Top 20 Effect Sizes", fontweight='bold')
568
 
569
  log_p = -np.log10(np.clip(pvals, 1e-300, 1))
570
  sig_thr = -np.log10(0.05/len(pvals))
571
- colors_v = np.where(log_p >= sig_thr, ACCENT_GOLD, np.where(betas > 0, ACCENT_BLUE, ACCENT_LAV))
572
- axes[0,1].scatter(betas, log_p, c=colors_v, s=30, alpha=0.7, edgecolors='white', linewidth=0.5)
573
  axes[0,1].axhline(sig_thr, color=ACCENT_PINK, ls='--', lw=1.5, label="Bonferroni")
574
  axes[0,1].axvline(0, color='black', lw=0.5)
575
- axes[0,1].set_xlabel("Effect Size (Ξ²)", fontsize=11)
576
- axes[0,1].set_ylabel("-log₁₀(p)", fontsize=11)
577
- axes[0,1].set_title("Volcano Plot", fontweight='bold')
578
  axes[0,1].legend()
579
 
580
- axes[1,0].hist(betas, bins=30, color=ACCENT_BLUE, edgecolor='white', alpha=0.7)
581
  axes[1,0].axvline(0, color=ACCENT_PINK, lw=2, ls='--')
582
- axes[1,0].set_xlabel("Effect Size (Ξ²)", fontsize=11)
583
- axes[1,0].set_ylabel("Frequency", fontsize=11)
584
- axes[1,0].set_title("Effect Size Distribution", fontweight='bold')
585
 
586
- axes[1,1].scatter(betas, log_p, c=colors_v, s=25, alpha=0.6, edgecolors='white', linewidth=0.3)
587
- axes[1,1].set_xlabel("Effect Size (Ξ²)", fontsize=11)
588
- axes[1,1].set_ylabel("-log₁₀(p)", fontsize=11)
589
- axes[1,1].set_title("Effect Size vs Significance", fontweight='bold')
590
 
591
  fig.tight_layout()
592
  return fig
593
 
594
- def plot_model_comparison(all_results):
595
- """Compare multiple models on the same QQ plot"""
596
- fig, ax = plt.subplots(figsize=(8, 8))
597
  style_fig(fig)
598
 
599
- colors = [ACCENT_BLUE, ACCENT_SAGE, ACCENT_PINK, ACCENT_GOLD, ACCENT_CORAL, ACCENT_LAV]
600
 
601
- for idx, (model_name, (pvals, _)) in enumerate(all_results.items()):
602
- n = len(pvals)
603
- obs = np.sort(-np.log10(np.clip(pvals, 1e-300, 1)))[::-1]
604
- exp = -np.log10(np.linspace(1/n, 1, n)[::-1])
605
- ax.plot(exp, obs, color=colors[idx % len(colors)], lw=2, label=model_name, alpha=0.8)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
606
 
607
- ax.plot([0, max(exp)], [0, max(exp)], color=ACCENT_GOLD, ls='--', lw=2, label='Expected')
608
- ax.set_xlabel("Expected -log₁₀(p)", fontsize=12)
609
- ax.set_ylabel("Observed -log₁₀(p)", fontsize=12)
610
- ax.set_title("Model Comparison - QQ Plot", fontsize=14, fontweight='bold')
611
- ax.legend(loc='lower right', fontsize=9, framealpha=0.95)
612
- ax.grid(True, alpha=0.3)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
613
 
614
  fig.tight_layout()
615
  return fig
616
 
617
  def plot_summary_dashboard(y, maf, pvals, betas, G):
618
- """Summary dashboard with key statistics"""
619
  fig, axes = plt.subplots(2, 3, figsize=(15, 10))
620
  style_fig(fig)
621
  axes = axes.flatten()
622
 
623
  axes[0].boxplot(y)
624
- axes[0].set_title(f"Phenotype\nn={len(y)}, mean={y.mean():.2f}", fontweight='bold')
625
  axes[0].set_ylabel("Value")
626
 
627
- axes[1].hist(maf, bins=20, color=ACCENT_BLUE, edgecolor='white', alpha=0.7)
628
  axes[1].axvline(0.05, color=ACCENT_PINK, ls='--')
629
- axes[1].set_title(f"MAF\nrare={np.sum(maf<0.05)}", fontweight='bold')
630
  axes[1].set_xlabel("MAF")
631
 
632
  log_p = -np.log10(np.clip(pvals, 1e-300, 1))
633
- axes[2].hist(log_p, bins=30, color=ACCENT_SAGE, edgecolor='white', alpha=0.7)
634
  axes[2].axvline(-np.log10(0.05/len(pvals)), color=ACCENT_PINK, ls='--')
635
- axes[2].set_title(f"P-values\nsig={np.sum(pvals < 0.05/len(pvals))}", fontweight='bold')
636
- axes[2].set_xlabel("-log₁₀(p)")
637
 
638
- axes[3].hist(betas, bins=30, color=ACCENT_CORAL, edgecolor='white', alpha=0.7)
639
  axes[3].axvline(0, color=ACCENT_PINK, ls='--')
640
- axes[3].set_title(f"Effect Sizes\nmean={np.mean(betas):.4f}", fontweight='bold')
641
  axes[3].set_xlabel("Ξ²")
642
 
643
  miss_rate = np.isnan(G).mean()
644
- axes[4].bar(['Complete', 'Missing'], [1-miss_rate, miss_rate], color=[ACCENT_BLUE, ACCENT_PINK], edgecolor='white')
645
- axes[4].set_title(f"Data Completeness\n{1-miss_rate:.1%}", fontweight='bold')
646
  axes[4].set_ylabel("Proportion")
647
 
648
  lam = np.median(stats.chi2.ppf(1 - np.clip(pvals, 1e-10, 1), df=1)) / stats.chi2.ppf(0.5, df=1)
649
- axes[5].text(0.5, 0.5,
650
- f"GWAS Summary\n\nSamples: {len(y)}\nSNPs: {G.shape[1]}\nSignificant: {np.sum(pvals < 0.05/len(pvals))}\nLambda GC: {lam:.3f}",
651
- ha='center', va='center', transform=axes[5].transAxes, fontsize=12)
652
- axes[5].set_title("Quick Stats", fontweight='bold')
653
- axes[5].axis('off')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
654
 
655
  fig.tight_layout()
656
  return fig
657
 
658
- # ─────────────────────────── MAIN PIPELINE ────────────────────────────
659
 
660
  def run_gwas(file_obj, text_input, selected_models, maf_threshold):
661
  try:
662
  df, snp_cols, chroms, positions = parse_data(file_obj, text_input)
663
  except Exception as e:
664
- return [None] * 13 + [f"❌ Data parsing error: {e}"]
665
 
666
  y = df["Phenotype"].values.astype(float)
667
  ids = df["ID"].values
@@ -706,16 +951,25 @@ def run_gwas(file_obj, text_input, selected_models, maf_threshold):
706
  primary_p, primary_b = p, b
707
 
708
  if primary_p is None:
709
- return [None] * 13 + ["❌ No models selected"]
710
 
711
- # Generate all plots
712
  plots = []
713
  plots.append(plot_manhattan(primary_p, chr_filt, pos_filt, f"Manhattan Plot - {models_to_run[0]}"))
714
  plots.append(plot_qq(primary_p, f"QQ Plot - {models_to_run[0]}"))
715
  plots.append(plot_pca(G_filt, y, ids))
716
  plots.append(plot_phenotype_distribution(y, ids))
717
  plots.append(plot_maf_analysis(maf_vals, snp_cols))
 
718
  plots.append(plot_effect_sizes(primary_p, primary_b, snp_filt))
 
 
 
 
 
 
 
 
719
  plots.append(plot_summary_dashboard(y, maf_vals, primary_p, primary_b, G_filt))
720
 
721
  # Add model comparison plot if multiple models selected
@@ -730,13 +984,13 @@ def run_gwas(file_obj, text_input, selected_models, maf_threshold):
730
  # Results table
731
  bonf = 0.05 / len(primary_p)
732
  res_df = pd.DataFrame({
733
- "SNP": snp_filt[:100],
734
- "Chr": chr_filt[:100],
735
- "Pos": pos_filt[:100],
736
- "Beta": np.round(primary_b[:100], 5),
737
- "P_value": primary_p[:100],
738
- "-log10P": np.round(-np.log10(np.clip(primary_p[:100], 1e-300, 1)), 4),
739
- }).sort_values("P_value").head(30)
740
 
741
  lam = np.median(stats.chi2.ppf(1 - np.clip(primary_p, 1e-10, 1), df=1)) / stats.chi2.ppf(0.5, df=1)
742
 
@@ -753,17 +1007,17 @@ def run_gwas(file_obj, text_input, selected_models, maf_threshold):
753
  β•‘ β•‘
754
  β•‘ Primary Model: {models_to_run[0]} β•‘
755
  β•‘ Bonferroni threshold: {bonf:.2e} β•‘
756
- β•‘ Significant MTAs: {(primary_p < bonf).sum()} β•‘
757
  β•‘ Genomic Inflation Ξ»: {lam:.4f} β•‘
758
  β•‘ β•‘
759
- β•‘ TOP 10 ASSOCIATIONS: β•‘
760
- {res_df[['SNP', 'Chr', 'Beta', 'P_value']].head(10).to_string(index=False)}
761
  β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•
762
  """
763
 
764
  return img_plots + [res_df, summary]
765
 
766
- # ─────────────────────────── GRADIO UI ─────────────────────────────
767
 
768
  SAMPLE_DATA = """ID,Phenotype,chr1_134521_SNP1,chr1_134810_SNP2,chr1_178766_SNP3,chr1_210328_SNP4
769
  chromosome,1,1,1,1
@@ -778,73 +1032,61 @@ IRRI-34,37,0,0,0,0
778
  IRRI-42,30.67,0,0,0,0
779
  IRRI-50,22,0,0,0,2"""
780
 
781
- MODERN_CSS = """
782
- body, .gradio-container {
783
- background: #F8F9FA !important;
784
- font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif !important;
785
- }
786
- .gr-panel, .gr-box {
787
- background: #FFFFFF !important;
788
- border: 1px solid #DEE2E6 !important;
789
- border-radius: 16px !important;
790
- box-shadow: 0 1px 3px rgba(0,0,0,0.05) !important;
791
- }
792
- h1, h2, h3 {
793
- color: #1B4F72 !important;
794
- font-weight: 600 !important;
795
- }
796
- .gr-button-primary {
797
- background: linear-gradient(135deg, #2C7DA0, #1B4F72) !important;
798
- border-radius: 40px !important;
799
- font-weight: 600 !important;
800
- border: none !important;
801
- }
802
- .gr-button-primary:hover {
803
- transform: translateY(-1px);
804
- box-shadow: 0 4px 12px rgba(44,125,160,0.3) !important;
805
- }
806
  """
807
 
808
  MODELS = ["OLS", "MLM", "GLM", "CMLM", "BLINK", "FarmCPU"]
809
 
810
- with gr.Blocks(css=MODERN_CSS, title="🌸 Complete GWAS Pipeline - 6 Models", theme=gr.themes.Soft()) as demo:
811
  gr.Markdown("""
812
- # 🌾 Complete GWAS Analysis Pipeline
813
- ### 6 Statistical Models Β· 7+ Visualization Types Β· Chromosome Row Support
814
  **✨ Significant MTAs are highlighted with gold stars on the Manhattan plot**
815
- """)
816
 
817
  with gr.Row():
818
  with gr.Column(scale=1):
819
- file_in = gr.File(label="πŸ“ Upload CSV/TSV", file_types=[".csv", ".tsv", ".txt"])
820
- text_in = gr.Textbox(label="πŸ“ Or paste CSV data", lines=8, value=SAMPLE_DATA)
821
- model_sel = gr.CheckboxGroup(choices=MODELS, value=["OLS", "MLM", "GLM"], label="🧬 Select Statistical Models")
822
- maf_thr = gr.Slider(0, 0.5, 0.05, step=0.01, label="πŸ“Š MAF Threshold")
823
- run_btn = gr.Button("πŸš€ Run Complete GWAS Analysis", variant="primary", size="lg")
824
 
825
  with gr.Column(scale=2):
826
- summary_out = gr.Textbox(label="πŸ“‹ Analysis Summary", lines=18)
827
 
828
  with gr.Tabs():
829
- with gr.Tab("⭐ Manhattan (Highlighted MTAs)"): img1 = gr.Image(type="pil", label="Manhattan Plot - Gold stars = significant MTAs")
830
  with gr.Tab("πŸ“ˆ QQ Plot"): img2 = gr.Image(type="pil", label="QQ Plot")
831
  with gr.Tab("πŸ”¬ PCA"): img3 = gr.Image(type="pil", label="PCA Analysis")
832
  with gr.Tab("πŸ“‰ Phenotype"): img4 = gr.Image(type="pil", label="Phenotype Distribution")
833
  with gr.Tab("🧬 MAF"): img5 = gr.Image(type="pil", label="MAF Analysis")
834
- with gr.Tab("βš– Effect Sizes"): img6 = gr.Image(type="pil", label="Effect Sizes")
835
- with gr.Tab("πŸ“Š Dashboard"): img7 = gr.Image(type="pil", label="Summary Dashboard")
836
- with gr.Tab("πŸ”„ Model Compare"): img8 = gr.Image(type="pil", label="Model Comparison (if multiple selected)")
837
- with gr.Tab("πŸ“‹ Results Table"): results_tbl = gr.Dataframe(label="Top Associations (sorted by p-value)")
 
 
 
 
 
 
 
 
 
838
 
839
  def run_wrapper(f, t, m, maf):
840
  out = run_gwas(f, t, m, maf)
841
- # Expected outputs: 9 images + results table + summary = 11 items
842
- if len(out) == 11:
843
- return out
844
- return out + [None] * (11 - len(out))
845
 
846
  run_btn.click(run_wrapper, [file_in, text_in, model_sel, maf_thr],
847
- [img1, img2, img3, img4, img5, img6, img7, img8, results_tbl, summary_out])
848
 
849
  if __name__ == "__main__":
850
  demo.launch(share=False, server_port=7860)
 
21
  from io import StringIO
22
  from statsmodels.stats.multitest import multipletests
23
 
24
+ # ─────────────────────────── PASTEL THEME (UNCHANGED) ────────────────────────────
25
+ BG_LIGHT = "#F9F5F0"
26
+ PANEL_PASTEL= "#FFFFFF"
27
+ ACCENT_PINK = "#E8A2A2"
28
+ ACCENT_MINT = "#A8D8C9"
29
+ ACCENT_LAV = "#C9B6E4"
30
+ ACCENT_PEACH= "#F4C9B0"
31
+ ACCENT_GOLD = "#E6C8A0"
32
+ ACCENT_CORAL= "#F0B8A8"
33
+ ACCENT_SAGE = "#B8C9A8"
34
+ ACCENT_BLUE = "#B8D4E3"
35
+ TEXT_SOFT = "#5C4B3A"
36
+ TEXT_LIGHT = "#8B7A6B"
37
+ GRID_SOFT = "#E8DFD3"
38
+
39
+ def style_fig(fig):
 
 
40
  fig.patch.set_facecolor(BG_LIGHT)
41
  for ax in fig.get_axes():
42
  ax.set_facecolor(PANEL_PASTEL)
43
  ax.tick_params(colors=TEXT_SOFT, labelsize=9)
44
  ax.xaxis.label.set_color(TEXT_SOFT)
45
  ax.yaxis.label.set_color(TEXT_SOFT)
46
+ ax.title.set_color(ACCENT_PINK)
 
 
 
 
 
47
  for spine in ax.spines.values():
48
  spine.set_edgecolor(GRID_SOFT)
49
  ax.grid(color=GRID_SOFT, linewidth=0.5, linestyle="--", alpha=0.6)
 
288
  betas[j] = slope
289
  return pvals, betas
290
 
291
+ # ─────────────────────────── MODIFIED MANHATTAN PLOT (ONLY THIS FUNCTION CHANGED) ───────────────────
292
 
293
  def plot_manhattan(pvals, chroms, positions, title="Manhattan Plot"):
294
  """
295
+ MODIFIED: Manhattan plot with standard dark color scheme and highlighted significant MTAs.
296
  Significant MTAs (p < 5e-8) are shown as large gold stars.
297
  """
298
  fig, ax = plt.subplots(figsize=(14, 5))
299
+ style_fig(fig)
300
  log_p = -np.log10(np.clip(pvals, 1e-300, 1))
301
+ sig_line = -np.log10(5e-8)
302
 
303
+ # MODIFIED: Standard dark color palette for chromosomes (professional look)
304
  chrom_list = sorted(set(chroms))
305
+ # Professional dark/standard colors instead of pastel
306
  dark_palette = [
307
  '#1B4F72', # Dark Blue
308
+ '#1E8449', # Dark Green
309
  '#6C3483', # Dark Purple
310
  '#B7950B', # Dark Gold
311
  '#C0392B', # Dark Red
 
325
  x_offset = 0
326
  tick_pos, tick_lab, x_coords = [], [], np.zeros(len(pvals))
327
 
 
 
 
 
 
328
  for ch in chrom_list:
329
  mask = chroms == ch
330
  pos = positions[mask]
 
335
  x_coords[np.where(mask)[0][order]] = x_vals
336
  tick_pos.append(x_vals.mean())
337
  tick_lab.append(f"Chr{ch}")
338
+ ax.axvspan(x_offset, x_offset + pos.max() - pos.min(), alpha=0.08, color=chrom_colors[ch])
339
+ # Plot SNPs with standard dark colors
340
+ ax.scatter(x_coords[mask], log_p[mask], c=chrom_colors[ch], s=20, alpha=0.8)
 
 
 
 
 
 
 
 
 
 
341
  x_offset += (pos.max() - pos.min()) + max(positions) * 0.01
342
 
343
+ # MODIFIED: Highlight significant MTAs with gold stars
344
+ sig_mask = log_p >= sig_line
345
  if sig_mask.any():
346
  ax.scatter(x_coords[sig_mask], log_p[sig_mask],
347
+ c='#FFD700', s=120, marker="*", zorder=10,
348
+ edgecolors='#DAA520', linewidth=1.5,
349
+ label=f"✨ Significant MTA ({sig_mask.sum()} SNPs)")
 
 
 
 
 
 
 
350
 
351
+ ax.axhline(sig_line, color='#DC3545', ls="--", lw=1.5, label="Bonferroni (5e-8)")
352
  ax.set_xticks(tick_pos)
353
+ ax.set_xticklabels(tick_lab, rotation=45)
354
+ ax.set_ylabel("-log10(p)")
355
+ ax.set_title(title)
356
+ ax.legend()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
357
  fig.tight_layout()
358
  return fig
359
 
360
+ # ─────────────────────────── ALL OTHER PLOTTING FUNCTIONS (UNCHANGED) ───────────────────
361
+
362
+ def fig_to_pil(fig):
363
+ buf = io.BytesIO()
364
+ fig.savefig(buf, format="png", dpi=150, bbox_inches="tight", facecolor=fig.get_facecolor())
365
+ buf.seek(0)
366
+ from PIL import Image
367
+ return Image.open(buf).copy()
368
+
369
  def plot_qq(pvals, title="QQ Plot"):
 
370
  fig, ax = plt.subplots(figsize=(6, 6))
371
  style_fig(fig)
372
  n = len(pvals)
373
  obs = np.sort(-np.log10(np.clip(pvals, 1e-300, 1)))[::-1]
374
  exp = -np.log10(np.linspace(1/n, 1, n)[::-1])
375
 
 
376
  ci_lower = -np.log10(stats.beta.ppf(0.975, np.arange(1, n+1), np.arange(n, 0, -1)))
377
  ci_upper = -np.log10(stats.beta.ppf(0.025, np.arange(1, n+1), np.arange(n, 0, -1)))
378
+ ax.fill_between(exp, ci_lower, ci_upper, alpha=0.25, color=ACCENT_MINT, label="95% CI")
379
+ ax.scatter(exp, obs, c=ACCENT_LAV, s=25, alpha=0.8)
380
+ ax.plot([0, max(exp)], [0, max(exp)], color=ACCENT_PINK, ls="--", lw=1.5)
381
+
382
+ lam = np.median(stats.chi2.ppf(1 - pvals, df=1)) / stats.chi2.ppf(0.5, df=1)
383
+ ax.text(0.05, 0.92, f"Ξ» = {lam:.4f}", transform=ax.transAxes, fontsize=11)
384
+ ax.set_xlabel("Expected -log10(p)")
385
+ ax.set_ylabel("Observed -log10(p)")
386
+ ax.set_title(title)
 
 
387
  fig.tight_layout()
388
  return fig
389
 
 
 
 
 
 
 
 
 
 
 
390
  def plot_pca(G, y, ids):
 
391
  fig, axes = plt.subplots(2, 2, figsize=(14, 12))
392
  style_fig(fig)
393
 
 
398
  pcs = pca.fit_transform(G_sc)
399
  var_exp = pca.explained_variance_ratio_ * 100
400
 
401
+ sc = axes[0,0].scatter(pcs[:,0], pcs[:,1], c=y, cmap='coolwarm', s=60, edgecolors='white')
402
+ axes[0,0].set_xlabel(f"PC1 ({var_exp[0]:.1f}%)")
403
+ axes[0,0].set_ylabel(f"PC2 ({var_exp[1]:.1f}%)")
404
+ axes[0,0].set_title("PCA: PC1 vs PC2")
405
  plt.colorbar(sc, ax=axes[0,0], label="Phenotype")
406
 
407
  if n_comp >= 4:
408
+ axes[0,1].scatter(pcs[:,2], pcs[:,3], c=y, cmap='coolwarm', s=60, edgecolors='white')
409
+ axes[0,1].set_xlabel(f"PC3 ({var_exp[2]:.1f}%)")
410
+ axes[0,1].set_ylabel(f"PC4 ({var_exp[3]:.1f}%)")
411
+ axes[0,1].set_title("PCA: PC3 vs PC4")
 
412
  else:
413
+ axes[0,1].text(0.5, 0.5, "Insufficient components", ha='center', transform=axes[0,1].transAxes)
414
+
415
+ axes[1,0].bar(range(1, n_comp+1), var_exp, color=ACCENT_MINT, edgecolor='white')
416
+ axes[1,0].plot(range(1, n_comp+1), np.cumsum(var_exp), color=ACCENT_PINK, marker='o', lw=2, label="Cumulative")
417
+ axes[1,0].set_xlabel("Principal Component")
418
+ axes[1,0].set_ylabel("Variance Explained (%)")
419
+ axes[1,0].set_title("Scree Plot")
 
420
  axes[1,0].legend()
 
421
 
422
+ axes[1,1].scatter(pcs[:,0], pcs[:,1], c=y, cmap='coolwarm', s=60, edgecolors='white')
423
+ axes[1,1].set_xlabel(f"PC1 ({var_exp[0]:.1f}%)")
424
+ axes[1,1].set_ylabel(f"PC2 ({var_exp[1]:.1f}%)")
425
+ axes[1,1].set_title("Population Structure")
426
 
427
  fig.tight_layout()
428
  return fig
429
 
430
  def plot_phenotype_distribution(y, ids):
 
431
  fig, axes = plt.subplots(2, 2, figsize=(14, 10))
432
  style_fig(fig)
433
 
434
+ axes[0,0].hist(y, bins=15, color=ACCENT_LAV, edgecolor='white', alpha=0.8)
435
  axes[0,0].axvline(y.mean(), color=ACCENT_PINK, lw=2, ls='--', label=f"Mean: {y.mean():.2f}")
436
  axes[0,0].axvline(y.mean() + y.std(), color=ACCENT_GOLD, lw=1.5, ls=':', label="Β±1 SD")
437
  axes[0,0].axvline(y.mean() - y.std(), color=ACCENT_GOLD, lw=1.5, ls=':')
438
+ axes[0,0].set_xlabel("Phenotype")
439
+ axes[0,0].set_ylabel("Frequency")
440
+ axes[0,0].set_title("Phenotype Distribution")
441
  axes[0,0].legend()
442
 
443
  bp = axes[0,1].boxplot(y, vert=True, patch_artist=True)
444
  for patch in bp['boxes']:
445
+ patch.set_facecolor(ACCENT_MINT)
446
  patch.set_edgecolor(ACCENT_PINK)
447
  axes[0,1].set_xticklabels(['Phenotype'])
448
+ axes[0,1].set_ylabel("Value")
449
+ axes[0,1].set_title("Box Plot")
450
 
451
  stats.probplot(y, dist="norm", plot=axes[1,0])
452
+ axes[1,0].set_title("Normal Q-Q Plot")
453
+ axes[1,0].get_lines()[0].set_color(ACCENT_LAV)
454
  axes[1,0].get_lines()[1].set_color(ACCENT_PINK)
455
 
456
+ axes[1,1].hist(y, bins=15, density=True, color=ACCENT_LAV, alpha=0.7, edgecolor='white')
457
  x_dense = np.linspace(y.min(), y.max(), 100)
458
  kde = stats.gaussian_kde(y)
459
  axes[1,1].plot(x_dense, kde(x_dense), color=ACCENT_PINK, lw=2)
460
+ axes[1,1].set_xlabel("Phenotype")
461
+ axes[1,1].set_ylabel("Density")
462
+ axes[1,1].set_title("Density Plot")
463
 
464
  fig.tight_layout()
465
  return fig
466
 
467
  def plot_maf_analysis(maf, snp_names):
 
468
  fig, axes = plt.subplots(2, 2, figsize=(14, 10))
469
  style_fig(fig)
470
 
471
+ axes[0,0].hist(maf, bins=20, color=ACCENT_MINT, edgecolor='white')
472
  axes[0,0].axvline(0.05, color=ACCENT_PINK, ls='--', lw=2, label="MAF=0.05")
473
+ axes[0,0].set_xlabel("Minor Allele Frequency")
474
+ axes[0,0].set_ylabel("Count")
475
+ axes[0,0].set_title("MAF Distribution")
476
  axes[0,0].legend()
477
 
478
  order = np.argsort(maf)[::-1]
479
+ colors = [ACCENT_MINT if m >= 0.05 else ACCENT_LAV for m in maf[order]]
480
+ axes[0,1].bar(range(min(50, len(maf))), maf[order][:50], color=colors[:50])
481
  axes[0,1].axhline(0.05, color=ACCENT_PINK, ls='--', lw=1.5)
482
+ axes[0,1].set_xlabel("SNP Index")
483
+ axes[0,1].set_ylabel("MAF")
484
+ axes[0,1].set_title("Top 50 SNPs by MAF")
485
 
486
  rare_mask = maf < 0.05
487
+ axes[1,0].pie([rare_mask.sum(), (~rare_mask).sum()], labels=[f"Rare (MAF<0.05): {rare_mask.sum()}", f"Common: {(~rare_mask).sum()}"], colors=[ACCENT_PINK, ACCENT_MINT], autopct='%1.1f%%')
488
+ axes[1,0].set_title("Rare vs Common Variants")
489
+
490
+ axes[1,1].text(0.5, 0.5, f"MAF Summary Statistics\n\nMean MAF: {np.mean(maf):.4f}\nMedian MAF: {np.median(maf):.4f}\nMin MAF: {np.min(maf):.4f}\nMax MAF: {np.max(maf):.4f}",
491
+ ha='center', va='center', transform=axes[1,1].transAxes)
492
+ axes[1,1].set_title("MAF Summary")
493
+
494
+ fig.tight_layout()
495
+ return fig
496
+
497
+ def plot_ld_analysis(G, positions, chroms):
498
+ fig, axes = plt.subplots(2, 2, figsize=(14, 12))
499
+ style_fig(fig)
500
 
501
+ m = G.shape[1]
502
+ dists, r2s = [], []
503
+
504
+ # Sample LD pairs
505
+ n_samples = min(500, m*(m-1)//2)
506
+ sampled_pairs = []
507
+ for i in range(min(50, m)):
508
+ for j in range(i+1, min(50, m)):
509
+ sampled_pairs.append((i, j))
510
+
511
+ for i, j in sampled_pairs:
512
+ xi, xj = G[:, i], G[:, j]
513
+ mask = ~(np.isnan(xi) | np.isnan(xj))
514
+ if mask.sum() >= 4:
515
+ r, _ = stats.pearsonr(xi[mask], xj[mask])
516
+ d = abs(positions[j] - positions[i]) if len(positions) > max(i,j) else 0
517
+ dists.append(d)
518
+ r2s.append(r**2)
519
+
520
+ if len(dists) > 0:
521
+ axes[0,0].scatter(np.array(dists)/1000, r2s, alpha=0.5, s=20, color=ACCENT_MINT)
522
+ axes[0,0].set_xlabel("Distance (kb)")
523
+ axes[0,0].set_ylabel("rΒ²")
524
+ axes[0,0].set_title("LD Decay")
525
+
526
+ bins = np.percentile(dists, np.linspace(0, 100, 11))
527
+ bin_centers, bin_means = [], []
528
+ for k in range(len(bins)-1):
529
+ mask = (dists >= bins[k]) & (dists < bins[k+1])
530
+ if mask.sum() > 0:
531
+ bin_centers.append((bins[k] + bins[k+1])/2/1000)
532
+ bin_means.append(np.mean(np.array(r2s)[mask]))
533
+ axes[0,0].plot(bin_centers, bin_means, color=ACCENT_PINK, lw=2, marker='o')
534
+
535
+ m_sub = min(30, m)
536
+ R = np.zeros((m_sub, m_sub))
537
+ for i in range(m_sub):
538
+ for j in range(m_sub):
539
+ if i == j:
540
+ R[i,j] = 1
541
+ else:
542
+ xi, xj = G[:, i], G[:, j]
543
+ mask = ~(np.isnan(xi) | np.isnan(xj))
544
+ if mask.sum() >= 3:
545
+ r, _ = stats.pearsonr(xi[mask], xj[mask])
546
+ R[i,j] = r**2
547
+
548
+ im = axes[0,1].imshow(R, cmap='RdYlBu_r', vmin=0, vmax=1, aspect='auto')
549
+ axes[0,1].set_title("LD Heatmap (first 30 SNPs)")
550
+ plt.colorbar(im, ax=axes[0,1], label="rΒ²")
551
+
552
+ if len(r2s) > 0:
553
+ axes[1,0].hist(r2s, bins=20, color=ACCENT_LAV, edgecolor='white')
554
+ axes[1,0].set_xlabel("rΒ²")
555
+ axes[1,0].set_ylabel("Frequency")
556
+ axes[1,0].set_title("LD Distribution")
557
+
558
+ if len(dists) > 0:
559
+ dists_kb = np.array(dists)/1000
560
+ r2s_arr = np.array(r2s)
561
+ axes[1,1].scatter(dists_kb, r2s_arr, alpha=0.3, s=15, color=ACCENT_MINT)
562
+ axes[1,1].set_xlabel("Distance (kb)")
563
+ axes[1,1].set_ylabel("rΒ²")
564
+ axes[1,1].set_title("LD Decay Scatter")
565
+ axes[1,1].set_ylim(0, 1)
566
 
567
  fig.tight_layout()
568
  return fig
569
 
570
  def plot_effect_sizes(pvals, betas, snp_names):
 
571
  fig, axes = plt.subplots(2, 2, figsize=(14, 10))
572
  style_fig(fig)
573
 
574
  top_idx = np.argsort(np.abs(betas))[-20:]
575
  top_betas = betas[top_idx]
576
  top_names = [snp_names[i][:15] for i in top_idx]
577
+ colors = [ACCENT_PINK if b < 0 else ACCENT_MINT for b in top_betas]
578
 
579
+ axes[0,0].barh(range(len(top_betas)), top_betas, color=colors)
580
  axes[0,0].axvline(0, color='black', lw=0.5)
581
  axes[0,0].set_yticks(range(len(top_betas)))
582
  axes[0,0].set_yticklabels(top_names, fontsize=8)
583
+ axes[0,0].set_xlabel("Effect Size (Ξ²)")
584
+ axes[0,0].set_title("Top 20 Effect Sizes")
585
 
586
  log_p = -np.log10(np.clip(pvals, 1e-300, 1))
587
  sig_thr = -np.log10(0.05/len(pvals))
588
+ colors_v = np.where(log_p >= sig_thr, ACCENT_GOLD, np.where(betas > 0, ACCENT_MINT, ACCENT_LAV))
589
+ axes[0,1].scatter(betas, log_p, c=colors_v, s=30, alpha=0.7)
590
  axes[0,1].axhline(sig_thr, color=ACCENT_PINK, ls='--', lw=1.5, label="Bonferroni")
591
  axes[0,1].axvline(0, color='black', lw=0.5)
592
+ axes[0,1].set_xlabel("Effect Size (Ξ²)")
593
+ axes[0,1].set_ylabel("-log10(p)")
594
+ axes[0,1].set_title("Volcano Plot")
595
  axes[0,1].legend()
596
 
597
+ axes[1,0].hist(betas, bins=30, color=ACCENT_MINT, edgecolor='white')
598
  axes[1,0].axvline(0, color=ACCENT_PINK, lw=2, ls='--')
599
+ axes[1,0].set_xlabel("Effect Size (Ξ²)")
600
+ axes[1,0].set_ylabel("Frequency")
601
+ axes[1,0].set_title("Effect Size Distribution")
602
 
603
+ axes[1,1].scatter(betas, log_p, c=colors_v, s=25, alpha=0.6)
604
+ axes[1,1].set_xlabel("Effect Size (Ξ²)")
605
+ axes[1,1].set_ylabel("-log10(p)")
606
+ axes[1,1].set_title("Effect Size vs Significance")
607
 
608
  fig.tight_layout()
609
  return fig
610
 
611
+ def plot_heterozygosity(G, y, ids):
612
+ fig, axes = plt.subplots(2, 2, figsize=(14, 10))
 
613
  style_fig(fig)
614
 
615
+ het = compute_heterozygosity(G)
616
 
617
+ axes[0,0].hist(het, bins=20, color=ACCENT_LAV, edgecolor='white')
618
+ axes[0,0].set_xlabel("Heterozygosity")
619
+ axes[0,0].set_ylabel("Count")
620
+ axes[0,0].set_title("Individual Heterozygosity")
621
+
622
+ axes[0,1].scatter(het, y, c=ACCENT_MINT, s=50, alpha=0.7)
623
+ axes[0,1].set_xlabel("Heterozygosity")
624
+ axes[0,1].set_ylabel("Phenotype")
625
+ axes[0,1].set_title("Heterozygosity vs Phenotype")
626
+
627
+ top_idx = np.argsort(het)[-10:]
628
+ axes[1,0].barh(range(len(top_idx)), het[top_idx], color=ACCENT_PINK)
629
+ axes[1,0].set_yticks(range(len(top_idx)))
630
+ axes[1,0].set_yticklabels([ids[i][:10] for i in top_idx], fontsize=8)
631
+ axes[1,0].set_xlabel("Heterozygosity")
632
+ axes[1,0].set_title("Top 10 Most Heterozygous Individuals")
633
+
634
+ median_y = np.median(y)
635
+ high_group = het[y > median_y]
636
+ low_group = het[y <= median_y]
637
+ axes[1,1].boxplot([low_group, high_group], labels=['Low Phenotype', 'High Phenotype'])
638
+ axes[1,1].set_ylabel("Heterozygosity")
639
+ axes[1,1].set_title("Heterozygosity by Phenotype Group")
640
 
641
+ fig.tight_layout()
642
+ return fig
643
+
644
+ def plot_call_rate_analysis(G, snp_names):
645
+ fig, axes = plt.subplots(2, 2, figsize=(14, 10))
646
+ style_fig(fig)
647
+
648
+ call_rate = compute_call_rate(G)
649
+
650
+ axes[0,0].hist(call_rate, bins=20, color=ACCENT_MINT, edgecolor='white')
651
+ axes[0,0].axvline(0.95, color=ACCENT_PINK, ls='--', lw=2, label="95% threshold")
652
+ axes[0,0].set_xlabel("Call Rate")
653
+ axes[0,0].set_ylabel("Count")
654
+ axes[0,0].set_title("SNP Call Rate Distribution")
655
+ axes[0,0].legend()
656
+
657
+ order = np.argsort(call_rate)
658
+ axes[0,1].plot(call_rate[order], color=ACCENT_LAV, lw=1)
659
+ axes[0,1].axhline(0.95, color=ACCENT_PINK, ls='--', lw=1.5)
660
+ axes[0,1].fill_between(range(len(call_rate)), 0, call_rate[order], alpha=0.3, color=ACCENT_MINT)
661
+ axes[0,1].set_xlabel("SNP Index (sorted)")
662
+ axes[0,1].set_ylabel("Call Rate")
663
+ axes[0,1].set_title("Call Rate by SNP")
664
+
665
+ low_cr = call_rate < 0.95
666
+ axes[1,0].pie([low_cr.sum(), (~low_cr).sum()], labels=[f"Low CR (<95%): {low_cr.sum()}", f"Good CR: {(~low_cr).sum()}"], colors=[ACCENT_PINK, ACCENT_MINT], autopct='%1.1f%%')
667
+ axes[1,0].set_title("SNP Quality")
668
+
669
+ axes[1,1].text(0.5, 0.5, f"Call Rate Summary\n\nMean: {np.mean(call_rate):.4f}\nMedian: {np.median(call_rate):.4f}\nMin: {np.min(call_rate):.4f}\nSNPs with CR>95%: {(~low_cr).sum()}",
670
+ ha='center', va='center', transform=axes[1,1].transAxes)
671
+ axes[1,1].set_title("Call Rate Summary")
672
+
673
+ fig.tight_layout()
674
+ return fig
675
+
676
+ def plot_kinship_analysis(K, ids):
677
+ fig, axes = plt.subplots(2, 2, figsize=(14, 12))
678
+ style_fig(fig)
679
+
680
+ im = axes[0,0].imshow(K, cmap='coolwarm', aspect='auto', vmin=-0.5, vmax=1)
681
+ axes[0,0].set_title("Kinship Matrix")
682
+ plt.colorbar(im, ax=axes[0,0], label="Kinship")
683
+
684
+ K_flat = K[np.triu_indices_from(K, k=1)]
685
+ axes[0,1].hist(K_flat, bins=30, color=ACCENT_LAV, edgecolor='white')
686
+ axes[0,1].set_xlabel("Kinship Coefficient")
687
+ axes[0,1].set_ylabel("Frequency")
688
+ axes[0,1].set_title("Pairwise Kinship Distribution")
689
+
690
+ linkage_matrix = linkage(K, method='average')
691
+ dendrogram(linkage_matrix, ax=axes[1,0], labels=ids, leaf_rotation=90, leaf_font_size=8, color_threshold=0.7)
692
+ axes[1,0].set_title("Sample Clustering Dendrogram")
693
+ axes[1,0].set_ylabel("Distance")
694
+
695
+ eigvals, eigvecs = np.linalg.eigh(K)
696
+ idx = np.argsort(eigvals)[::-1]
697
+ axes[1,1].scatter(eigvecs[:, idx[0]], eigvecs[:, idx[1]], c=ACCENT_MINT, s=60, edgecolors='white')
698
+ axes[1,1].set_xlabel("PC1")
699
+ axes[1,1].set_ylabel("PC2")
700
+ axes[1,1].set_title("Kinship PCA")
701
+
702
+ fig.tight_layout()
703
+ return fig
704
+
705
+ def plot_mds_analysis(G, y, ids):
706
+ fig, axes = plt.subplots(1, 2, figsize=(14, 6))
707
+ style_fig(fig)
708
+
709
+ try:
710
+ mds = MDS(n_components=2, random_state=42, normalized_stress='auto')
711
+ mds_coords = mds.fit_transform(G)
712
+
713
+ sc = axes[0].scatter(mds_coords[:, 0], mds_coords[:, 1], c=y, cmap='coolwarm', s=60, edgecolors='white')
714
+ axes[0].set_xlabel("MDS Dimension 1")
715
+ axes[0].set_ylabel("MDS Dimension 2")
716
+ axes[0].set_title("Multi-Dimensional Scaling (MDS)")
717
+ plt.colorbar(sc, ax=axes[0], label="Phenotype")
718
+
719
+ perplexity = min(30, len(G)-1)
720
+ tsne = TSNE(n_components=2, random_state=42, perplexity=perplexity)
721
+ tsne_coords = tsne.fit_transform(G)
722
+
723
+ sc2 = axes[1].scatter(tsne_coords[:, 0], tsne_coords[:, 1], c=y, cmap='coolwarm', s=60, edgecolors='white')
724
+ axes[1].set_xlabel("t-SNE Dimension 1")
725
+ axes[1].set_ylabel("t-SNE Dimension 2")
726
+ axes[1].set_title("t-SNE Visualization")
727
+ plt.colorbar(sc2, ax=axes[1], label="Phenotype")
728
+ except Exception as e:
729
+ axes[0].text(0.5, 0.5, f"MDS failed: {str(e)[:50]}", ha='center', transform=axes[0].transAxes)
730
+ axes[1].text(0.5, 0.5, f"t-SNE failed: {str(e)[:50]}", ha='center', transform=axes[1].transAxes)
731
+
732
+ fig.tight_layout()
733
+ return fig
734
+
735
+ def plot_manhattan_by_chromosome(pvals, chroms, positions):
736
+ fig, axes = plt.subplots(2, 3, figsize=(15, 10))
737
+ style_fig(fig)
738
+ axes = axes.flatten()
739
+
740
+ log_p = -np.log10(np.clip(pvals, 1e-300, 1))
741
+ unique_chroms = sorted(set(chroms))
742
+
743
+ for i, ch in enumerate(unique_chroms[:6]):
744
+ mask = chroms == ch
745
+ if mask.sum() > 0:
746
+ axes[i].scatter(positions[mask], log_p[mask], c=ACCENT_MINT, s=15, alpha=0.7)
747
+ axes[i].axhline(-np.log10(5e-8), color=ACCENT_PINK, ls='--', lw=1)
748
+ axes[i].set_xlabel(f"Chromosome {ch} Position")
749
+ axes[i].set_ylabel("-log10(p)")
750
+ axes[i].set_title(f"Chromosome {ch}")
751
+
752
+ for i in range(len(unique_chroms), 6):
753
+ axes[i].set_visible(False)
754
+
755
+ fig.tight_layout()
756
+ return fig
757
+
758
+ def plot_manhattan_qq_combined(pvals, chroms, positions):
759
+ fig = plt.figure(figsize=(14, 10))
760
+ style_fig(fig)
761
+ gs = fig.add_gridspec(2, 2, height_ratios=[2, 1])
762
+
763
+ ax1 = fig.add_subplot(gs[0, :])
764
+ log_p = -np.log10(np.clip(pvals, 1e-300, 1))
765
+ ax1.scatter(range(len(pvals)), log_p, c=ACCENT_MINT, s=10, alpha=0.7)
766
+ ax1.axhline(-np.log10(5e-8), color=ACCENT_PINK, ls='--', lw=1.5, label="Bonferroni")
767
+ ax1.set_xlabel("SNP Index")
768
+ ax1.set_ylabel("-log10(p)")
769
+ ax1.set_title("Manhattan Plot")
770
+ ax1.legend()
771
+
772
+ ax2 = fig.add_subplot(gs[1, 0])
773
+ n = len(pvals)
774
+ obs = np.sort(-np.log10(np.clip(pvals, 1e-300, 1)))[::-1]
775
+ exp = -np.log10(np.linspace(1/n, 1, n)[::-1])
776
+ ax2.scatter(exp, obs, c=ACCENT_LAV, s=15, alpha=0.7)
777
+ ax2.plot([0, max(exp)], [0, max(exp)], color=ACCENT_PINK, ls='--', lw=1.5)
778
+ ax2.set_xlabel("Expected -log10(p)")
779
+ ax2.set_ylabel("Observed -log10(p)")
780
+ ax2.set_title("QQ Plot")
781
+
782
+ ax3 = fig.add_subplot(gs[1, 1])
783
+ ax3.hist(pvals, bins=50, color=ACCENT_MINT, edgecolor='white')
784
+ ax3.axvline(0.05, color=ACCENT_PINK, ls='--', lw=1.5)
785
+ ax3.set_xlabel("p-value")
786
+ ax3.set_ylabel("Frequency")
787
+ ax3.set_title("P-value Distribution")
788
+
789
+ fig.tight_layout()
790
+ return fig
791
+
792
+ def plot_manhattan_stacked(pvals, chroms, positions):
793
+ fig, ax = plt.subplots(figsize=(14, 6))
794
+ style_fig(fig)
795
+
796
+ log_p = -np.log10(np.clip(pvals, 1e-300, 1))
797
+ unique_chroms = sorted(set(chroms))
798
+
799
+ y_offset = 0
800
+ for ch in unique_chroms:
801
+ mask = chroms == ch
802
+ if mask.sum() > 0:
803
+ x_vals = np.arange(mask.sum())
804
+ y_vals = log_p[mask]
805
+ ax.scatter(x_vals + y_offset, y_vals, c=ACCENT_MINT, s=8, alpha=0.6)
806
+ ax.axvline(y_offset, color=GRID_SOFT, lw=0.5, alpha=0.5)
807
+ y_offset += mask.sum()
808
+
809
+ ax.axhline(-np.log10(5e-8), color=ACCENT_PINK, ls='--', lw=1.5)
810
+ ax.set_xlabel("SNP Index by Chromosome")
811
+ ax.set_ylabel("-log10(p)")
812
+ ax.set_title("Stacked Manhattan Plot")
813
+
814
+ fig.tight_layout()
815
+ return fig
816
+
817
+ def plot_correlation_heatmap(G, y):
818
+ fig, axes = plt.subplots(1, 2, figsize=(14, 6))
819
+ style_fig(fig)
820
+
821
+ n_snp = min(50, G.shape[1])
822
+ corr_mat = np.corrcoef(G[:, :n_snp].T)
823
+
824
+ im = axes[0].imshow(corr_mat, cmap='coolwarm', vmin=-1, vmax=1, aspect='auto')
825
+ axes[0].set_title("SNP Correlation Matrix")
826
+ axes[0].set_xlabel("SNP Index")
827
+ axes[0].set_ylabel("SNP Index")
828
+ plt.colorbar(im, ax=axes[0], label="Correlation")
829
+
830
+ pvals_adj = -np.log10(np.clip(np.corrcoef(G.T, y)[:-1, -1]**2, 1e-300, 1))
831
+ top_idx = np.argsort(pvals_adj)[-20:]
832
+ top_corr = np.corrcoef(G[:, top_idx].T)
833
+
834
+ im2 = axes[1].imshow(top_corr, cmap='coolwarm', vmin=-1, vmax=1, aspect='auto')
835
+ axes[1].set_title("Top 20 SNPs Correlation")
836
+ axes[1].set_xlabel("SNP Index")
837
+ axes[1].set_ylabel("SNP Index")
838
+ plt.colorbar(im2, ax=axes[1], label="Correlation")
839
 
840
  fig.tight_layout()
841
  return fig
842
 
843
  def plot_summary_dashboard(y, maf, pvals, betas, G):
 
844
  fig, axes = plt.subplots(2, 3, figsize=(15, 10))
845
  style_fig(fig)
846
  axes = axes.flatten()
847
 
848
  axes[0].boxplot(y)
849
+ axes[0].set_title(f"Phenotype\nn={len(y)}, mean={y.mean():.2f}")
850
  axes[0].set_ylabel("Value")
851
 
852
+ axes[1].hist(maf, bins=20, color=ACCENT_MINT, edgecolor='white')
853
  axes[1].axvline(0.05, color=ACCENT_PINK, ls='--')
854
+ axes[1].set_title(f"MAF\nrare={np.sum(maf<0.05)}")
855
  axes[1].set_xlabel("MAF")
856
 
857
  log_p = -np.log10(np.clip(pvals, 1e-300, 1))
858
+ axes[2].hist(log_p, bins=30, color=ACCENT_LAV, edgecolor='white')
859
  axes[2].axvline(-np.log10(0.05/len(pvals)), color=ACCENT_PINK, ls='--')
860
+ axes[2].set_title(f"P-values\nsig={np.sum(pvals < 0.05/len(pvals))}")
861
+ axes[2].set_xlabel("-log10(p)")
862
 
863
+ axes[3].hist(betas, bins=30, color=ACCENT_PEACH, edgecolor='white')
864
  axes[3].axvline(0, color=ACCENT_PINK, ls='--')
865
+ axes[3].set_title(f"Effect Sizes\nmean={np.mean(betas):.4f}")
866
  axes[3].set_xlabel("Ξ²")
867
 
868
  miss_rate = np.isnan(G).mean()
869
+ axes[4].bar(['Complete', 'Missing'], [1-miss_rate, miss_rate], color=[ACCENT_MINT, ACCENT_PINK])
870
+ axes[4].set_title(f"Data Completeness\n{1-miss_rate:.1%}")
871
  axes[4].set_ylabel("Proportion")
872
 
873
  lam = np.median(stats.chi2.ppf(1 - np.clip(pvals, 1e-10, 1), df=1)) / stats.chi2.ppf(0.5, df=1)
874
+ axes[5].text(0.5, 0.5, f"GWAS Summary\n\nSamples: {len(y)}\nSNPs: {G.shape[1]}\nSignificant: {np.sum(pvals < 0.05/len(pvals))}\nLambda GC: {lam:.3f}",
875
+ ha='center', va='center', transform=axes[5].transAxes)
876
+ axes[5].set_title("Quick Stats")
877
+
878
+ fig.tight_layout()
879
+ return fig
880
+
881
+ def plot_model_comparison(all_results):
882
+ """Compare multiple models on the same QQ plot"""
883
+ fig, ax = plt.subplots(figsize=(8, 8))
884
+ style_fig(fig)
885
+
886
+ colors = [ACCENT_PINK, ACCENT_MINT, ACCENT_LAV, ACCENT_PEACH, ACCENT_GOLD, ACCENT_CORAL]
887
+
888
+ for idx, (model_name, (pvals, _)) in enumerate(all_results.items()):
889
+ n = len(pvals)
890
+ obs = np.sort(-np.log10(np.clip(pvals, 1e-300, 1)))[::-1]
891
+ exp = -np.log10(np.linspace(1/n, 1, n)[::-1])
892
+ ax.plot(exp, obs, color=colors[idx % len(colors)], lw=2, label=model_name, alpha=0.8)
893
+
894
+ ax.plot([0, max(exp)], [0, max(exp)], color=ACCENT_GOLD, ls='--', lw=1.5, label='Expected')
895
+ ax.set_xlabel("Expected -log10(p)")
896
+ ax.set_ylabel("Observed -log10(p)")
897
+ ax.set_title("Model Comparison - QQ Plot")
898
+ ax.legend(loc='lower right', fontsize=8)
899
 
900
  fig.tight_layout()
901
  return fig
902
 
903
+ # ─────────────────────────── MAIN PIPELINE (UNCHANGED) ────────────────────────────
904
 
905
  def run_gwas(file_obj, text_input, selected_models, maf_threshold):
906
  try:
907
  df, snp_cols, chroms, positions = parse_data(file_obj, text_input)
908
  except Exception as e:
909
+ return [None] * 18 + [f"❌ Data parsing error: {e}"]
910
 
911
  y = df["Phenotype"].values.astype(float)
912
  ids = df["ID"].values
 
951
  primary_p, primary_b = p, b
952
 
953
  if primary_p is None:
954
+ return [None] * 18 + ["❌ No models selected"]
955
 
956
+ # Generate all 16+ plots
957
  plots = []
958
  plots.append(plot_manhattan(primary_p, chr_filt, pos_filt, f"Manhattan Plot - {models_to_run[0]}"))
959
  plots.append(plot_qq(primary_p, f"QQ Plot - {models_to_run[0]}"))
960
  plots.append(plot_pca(G_filt, y, ids))
961
  plots.append(plot_phenotype_distribution(y, ids))
962
  plots.append(plot_maf_analysis(maf_vals, snp_cols))
963
+ plots.append(plot_ld_analysis(G_filt, pos_filt, chr_filt))
964
  plots.append(plot_effect_sizes(primary_p, primary_b, snp_filt))
965
+ plots.append(plot_heterozygosity(G_filt, y, ids))
966
+ plots.append(plot_call_rate_analysis(G_filt, snp_filt))
967
+ plots.append(plot_kinship_analysis(K, ids))
968
+ plots.append(plot_mds_analysis(G_filt, y, ids))
969
+ plots.append(plot_manhattan_by_chromosome(primary_p, chr_filt, pos_filt))
970
+ plots.append(plot_manhattan_qq_combined(primary_p, chr_filt, pos_filt))
971
+ plots.append(plot_manhattan_stacked(primary_p, chr_filt, pos_filt))
972
+ plots.append(plot_correlation_heatmap(G_filt, y))
973
  plots.append(plot_summary_dashboard(y, maf_vals, primary_p, primary_b, G_filt))
974
 
975
  # Add model comparison plot if multiple models selected
 
984
  # Results table
985
  bonf = 0.05 / len(primary_p)
986
  res_df = pd.DataFrame({
987
+ "SNP": snp_filt[:50],
988
+ "Chr": chr_filt[:50],
989
+ "Pos": pos_filt[:50],
990
+ "Beta": np.round(primary_b[:50], 5),
991
+ "P_value": primary_p[:50],
992
+ "-log10P": np.round(-np.log10(np.clip(primary_p[:50], 1e-300, 1)), 4),
993
+ }).sort_values("P_value").head(20)
994
 
995
  lam = np.median(stats.chi2.ppf(1 - np.clip(primary_p, 1e-10, 1), df=1)) / stats.chi2.ppf(0.5, df=1)
996
 
 
1007
  β•‘ β•‘
1008
  β•‘ Primary Model: {models_to_run[0]} β•‘
1009
  β•‘ Bonferroni threshold: {bonf:.2e} β•‘
1010
+ β•‘ Significant SNPs: {(primary_p < bonf).sum()} β•‘
1011
  β•‘ Genomic Inflation Ξ»: {lam:.4f} β•‘
1012
  β•‘ β•‘
1013
+ β•‘ TOP 5 ASSOCIATIONS: β•‘
1014
+ {res_df[['SNP', 'Beta', 'P_value']].head(5).to_string(index=False)}
1015
  β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•
1016
  """
1017
 
1018
  return img_plots + [res_df, summary]
1019
 
1020
+ # ─────────────────────────── GRADIO UI (UNCHANGED) ─────────────────────────────
1021
 
1022
  SAMPLE_DATA = """ID,Phenotype,chr1_134521_SNP1,chr1_134810_SNP2,chr1_178766_SNP3,chr1_210328_SNP4
1023
  chromosome,1,1,1,1
 
1032
  IRRI-42,30.67,0,0,0,0
1033
  IRRI-50,22,0,0,0,2"""
1034
 
1035
+ PASTEL_CSS = """
1036
+ body, .gradio-container { background: #F9F5F0 !important; font-family: 'Inter', sans-serif !important; }
1037
+ .gr-panel, .gr-box { background: #FFFFFF !important; border: 1px solid #E8DFD3 !important; border-radius: 20px !important; }
1038
+ h1, h2, h3 { color: #E8A2A2 !important; }
1039
+ .gr-button-primary { background: linear-gradient(135deg, #E8A2A2, #C9B6E4) !important; border-radius: 40px !important; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1040
  """
1041
 
1042
  MODELS = ["OLS", "MLM", "GLM", "CMLM", "BLINK", "FarmCPU"]
1043
 
1044
+ with gr.Blocks(css=PASTEL_CSS, title="🌸 Complete GWAS Pipeline - 6 Models", theme=gr.themes.Soft()) as demo:
1045
  gr.Markdown("""
1046
+ # 🌸 Complete GWAS Analysis Pipeline
1047
+ ### 6 Statistical Models Β· 16+ Visualization Types Β· Chromosome Row Support
1048
  **✨ Significant MTAs are highlighted with gold stars on the Manhattan plot**
1049
+ """)
1050
 
1051
  with gr.Row():
1052
  with gr.Column(scale=1):
1053
+ file_in = gr.File(label="Upload CSV/TSV", file_types=[".csv", ".tsv", ".txt"])
1054
+ text_in = gr.Textbox(label="Or paste CSV", lines=8, value=SAMPLE_DATA)
1055
+ model_sel = gr.CheckboxGroup(choices=MODELS, value=["OLS", "MLM", "GLM"], label="Select Models (6 available)")
1056
+ maf_thr = gr.Slider(0, 0.5, 0.05, 0.01, label="MAF Threshold")
1057
+ run_btn = gr.Button("πŸš€ Run Complete GWAS (6 Models)", variant="primary", size="lg")
1058
 
1059
  with gr.Column(scale=2):
1060
+ summary_out = gr.Textbox(label="Analysis Summary", lines=18)
1061
 
1062
  with gr.Tabs():
1063
+ with gr.Tab("πŸ“Š Manhattan"): img1 = gr.Image(type="pil", label="Manhattan Plot - Gold stars = significant MTAs")
1064
  with gr.Tab("πŸ“ˆ QQ Plot"): img2 = gr.Image(type="pil", label="QQ Plot")
1065
  with gr.Tab("πŸ”¬ PCA"): img3 = gr.Image(type="pil", label="PCA Analysis")
1066
  with gr.Tab("πŸ“‰ Phenotype"): img4 = gr.Image(type="pil", label="Phenotype Distribution")
1067
  with gr.Tab("🧬 MAF"): img5 = gr.Image(type="pil", label="MAF Analysis")
1068
+ with gr.Tab("πŸ”— LD"): img6 = gr.Image(type="pil", label="LD Analysis")
1069
+ with gr.Tab("βš– Effect"): img7 = gr.Image(type="pil", label="Effect Sizes")
1070
+ with gr.Tab("🧬 Heterozygosity"): img8 = gr.Image(type="pil", label="Heterozygosity")
1071
+ with gr.Tab("πŸ“ž Call Rate"): img9 = gr.Image(type="pil", label="Call Rate")
1072
+ with gr.Tab("πŸ‘¨β€πŸ‘©β€πŸ‘§ Kinship"): img10 = gr.Image(type="pil", label="Kinship")
1073
+ with gr.Tab("🎨 MDS/t-SNE"): img11 = gr.Image(type="pil", label="MDS/t-SNE")
1074
+ with gr.Tab("πŸ“Š By Chr"): img12 = gr.Image(type="pil", label="Manhattan by Chromosome")
1075
+ with gr.Tab("πŸ“‹ Combined"): img13 = gr.Image(type="pil", label="Combined Plots")
1076
+ with gr.Tab("πŸ” Stacked"): img14 = gr.Image(type="pil", label="Stacked Manhattan")
1077
+ with gr.Tab("πŸ”₯ Heatmap"): img15 = gr.Image(type="pil", label="Correlation Heatmap")
1078
+ with gr.Tab("πŸ“Š Dashboard"): img16 = gr.Image(type="pil", label="Summary Dashboard")
1079
+ with gr.Tab("πŸ”„ Model Compare"): img17 = gr.Image(type="pil", label="Model Comparison")
1080
+ with gr.Tab("πŸ“‹ Results"): results_tbl = gr.Dataframe(label="Top Associations")
1081
 
1082
  def run_wrapper(f, t, m, maf):
1083
  out = run_gwas(f, t, m, maf)
1084
+ if len(out) == 18:
1085
+ return out + [None]
1086
+ return out
 
1087
 
1088
  run_btn.click(run_wrapper, [file_in, text_in, model_sel, maf_thr],
1089
+ [img1, img2, img3, img4, img5, img6, img7, img8, img9, img10, img11, img12, img13, img14, img15, img16, img17, results_tbl, summary_out])
1090
 
1091
  if __name__ == "__main__":
1092
  demo.launch(share=False, server_port=7860)