softwareDevelopment commited on
Commit
0464ae9
Β·
verified Β·
1 Parent(s): 05efbab

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +285 -499
app.py CHANGED
@@ -1,5 +1,3 @@
1
-
2
-
3
  import gradio as gr
4
  import pandas as pd
5
  import numpy as np
@@ -23,29 +21,36 @@ import io, re, itertools
23
  from io import StringIO
24
  from statsmodels.stats.multitest import multipletests
25
 
26
- # ─────────────────────────── PASTEL THEME ────────────────────────────
27
- BG_LIGHT = "#F9F5F0"
28
- PANEL_PASTEL= "#FFFFFF"
29
- ACCENT_PINK = "#E8A2A2"
30
- ACCENT_MINT = "#A8D8C9"
31
- ACCENT_LAV = "#C9B6E4"
32
- ACCENT_PEACH= "#F4C9B0"
33
- ACCENT_GOLD = "#E6C8A0"
34
- ACCENT_CORAL= "#F0B8A8"
35
- ACCENT_SAGE = "#B8C9A8"
36
- ACCENT_BLUE = "#B8D4E3"
37
- TEXT_SOFT = "#5C4B3A"
38
- TEXT_LIGHT = "#8B7A6B"
39
- GRID_SOFT = "#E8DFD3"
40
-
41
- def style_fig(fig):
 
 
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
- ax.title.set_color(ACCENT_PINK)
 
 
 
 
 
49
  for spine in ax.spines.values():
50
  spine.set_edgecolor(GRID_SOFT)
51
  ax.grid(color=GRID_SOFT, linewidth=0.5, linestyle="--", alpha=0.6)
@@ -290,28 +295,47 @@ def farmcpu_gwas(y, G, K):
290
  betas[j] = slope
291
  return pvals, betas
292
 
293
- # ─────────────────────────── 16+ PLOTTING FUNCTIONS ───────────────────
294
-
295
- def fig_to_pil(fig):
296
- buf = io.BytesIO()
297
- fig.savefig(buf, format="png", dpi=150, bbox_inches="tight", facecolor=fig.get_facecolor())
298
- buf.seek(0)
299
- from PIL import Image
300
- return Image.open(buf).copy()
301
 
302
  def plot_manhattan(pvals, chroms, positions, title="Manhattan Plot"):
 
 
 
 
303
  fig, ax = plt.subplots(figsize=(14, 5))
304
- style_fig(fig)
305
  log_p = -np.log10(np.clip(pvals, 1e-300, 1))
306
- sig_line = -np.log10(5e-8)
307
 
 
308
  chrom_list = sorted(set(chroms))
309
- palette = [ACCENT_PINK, ACCENT_MINT, ACCENT_LAV, ACCENT_PEACH, ACCENT_GOLD, ACCENT_CORAL, ACCENT_SAGE, ACCENT_BLUE]
310
- chrom_colors = {c: palette[i % len(palette)] for i, c in enumerate(chrom_list)}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
311
 
312
  x_offset = 0
313
  tick_pos, tick_lab, x_coords = [], [], np.zeros(len(pvals))
314
 
 
 
 
 
 
315
  for ch in chrom_list:
316
  mask = chroms == ch
317
  pos = positions[mask]
@@ -322,45 +346,94 @@ def plot_manhattan(pvals, chroms, positions, title="Manhattan Plot"):
322
  x_coords[np.where(mask)[0][order]] = x_vals
323
  tick_pos.append(x_vals.mean())
324
  tick_lab.append(f"Chr{ch}")
325
- ax.axvspan(x_offset, x_offset + pos.max() - pos.min(), alpha=0.08, color=chrom_colors[ch])
326
- ax.scatter(x_coords[mask], log_p[mask], c=chrom_colors[ch], s=20, alpha=0.8)
 
 
 
 
 
 
 
 
 
 
 
327
  x_offset += (pos.max() - pos.min()) + max(positions) * 0.01
328
 
329
- sig_mask = log_p >= sig_line
330
  if sig_mask.any():
331
- ax.scatter(x_coords[sig_mask], log_p[sig_mask], c=ACCENT_GOLD, s=80, marker="*", zorder=5, label="Significant")
 
 
 
 
 
 
 
 
 
 
332
 
333
- ax.axhline(sig_line, color=ACCENT_PINK, ls="--", lw=1.5, label="Bonferroni (5e-8)")
334
  ax.set_xticks(tick_pos)
335
- ax.set_xticklabels(tick_lab, rotation=45)
336
- ax.set_ylabel("-log10(p)")
337
- ax.set_title(title)
338
- ax.legend()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
339
  fig.tight_layout()
340
  return fig
341
 
342
  def plot_qq(pvals, title="QQ Plot"):
 
343
  fig, ax = plt.subplots(figsize=(6, 6))
344
  style_fig(fig)
345
  n = len(pvals)
346
  obs = np.sort(-np.log10(np.clip(pvals, 1e-300, 1)))[::-1]
347
  exp = -np.log10(np.linspace(1/n, 1, n)[::-1])
348
 
 
349
  ci_lower = -np.log10(stats.beta.ppf(0.975, np.arange(1, n+1), np.arange(n, 0, -1)))
350
  ci_upper = -np.log10(stats.beta.ppf(0.025, np.arange(1, n+1), np.arange(n, 0, -1)))
351
- ax.fill_between(exp, ci_lower, ci_upper, alpha=0.25, color=ACCENT_MINT, label="95% CI")
352
- ax.scatter(exp, obs, c=ACCENT_LAV, s=25, alpha=0.8)
353
- ax.plot([0, max(exp)], [0, max(exp)], color=ACCENT_PINK, ls="--", lw=1.5)
354
-
355
- lam = np.median(stats.chi2.ppf(1 - pvals, df=1)) / stats.chi2.ppf(0.5, df=1)
356
- ax.text(0.05, 0.92, f"Ξ» = {lam:.4f}", transform=ax.transAxes, fontsize=11)
357
- ax.set_xlabel("Expected -log10(p)")
358
- ax.set_ylabel("Observed -log10(p)")
359
- ax.set_title(title)
 
 
360
  fig.tight_layout()
361
  return fig
362
 
 
 
 
 
 
 
 
 
 
 
363
  def plot_pca(G, y, ids):
 
364
  fig, axes = plt.subplots(2, 2, figsize=(14, 12))
365
  style_fig(fig)
366
 
@@ -371,504 +444,213 @@ def plot_pca(G, y, ids):
371
  pcs = pca.fit_transform(G_sc)
372
  var_exp = pca.explained_variance_ratio_ * 100
373
 
374
- sc = axes[0,0].scatter(pcs[:,0], pcs[:,1], c=y, cmap='coolwarm', s=60, edgecolors='white')
375
- axes[0,0].set_xlabel(f"PC1 ({var_exp[0]:.1f}%)")
376
- axes[0,0].set_ylabel(f"PC2 ({var_exp[1]:.1f}%)")
377
- axes[0,0].set_title("PCA: PC1 vs PC2")
378
  plt.colorbar(sc, ax=axes[0,0], label="Phenotype")
379
 
380
  if n_comp >= 4:
381
- axes[0,1].scatter(pcs[:,2], pcs[:,3], c=y, cmap='coolwarm', s=60, edgecolors='white')
382
- axes[0,1].set_xlabel(f"PC3 ({var_exp[2]:.1f}%)")
383
- axes[0,1].set_ylabel(f"PC4 ({var_exp[3]:.1f}%)")
384
- axes[0,1].set_title("PCA: PC3 vs PC4")
 
385
  else:
386
- axes[0,1].text(0.5, 0.5, "Insufficient components", ha='center', transform=axes[0,1].transAxes)
387
-
388
- axes[1,0].bar(range(1, n_comp+1), var_exp, color=ACCENT_MINT, edgecolor='white')
389
- axes[1,0].plot(range(1, n_comp+1), np.cumsum(var_exp), color=ACCENT_PINK, marker='o', lw=2, label="Cumulative")
390
- axes[1,0].set_xlabel("Principal Component")
391
- axes[1,0].set_ylabel("Variance Explained (%)")
392
- axes[1,0].set_title("Scree Plot")
 
393
  axes[1,0].legend()
 
394
 
395
- axes[1,1].scatter(pcs[:,0], pcs[:,1], c=y, cmap='coolwarm', s=60, edgecolors='white')
396
- axes[1,1].set_xlabel(f"PC1 ({var_exp[0]:.1f}%)")
397
- axes[1,1].set_ylabel(f"PC2 ({var_exp[1]:.1f}%)")
398
- axes[1,1].set_title("Population Structure")
399
 
400
  fig.tight_layout()
401
  return fig
402
 
403
  def plot_phenotype_distribution(y, ids):
 
404
  fig, axes = plt.subplots(2, 2, figsize=(14, 10))
405
  style_fig(fig)
406
 
407
- axes[0,0].hist(y, bins=15, color=ACCENT_LAV, edgecolor='white', alpha=0.8)
408
  axes[0,0].axvline(y.mean(), color=ACCENT_PINK, lw=2, ls='--', label=f"Mean: {y.mean():.2f}")
409
  axes[0,0].axvline(y.mean() + y.std(), color=ACCENT_GOLD, lw=1.5, ls=':', label="Β±1 SD")
410
  axes[0,0].axvline(y.mean() - y.std(), color=ACCENT_GOLD, lw=1.5, ls=':')
411
- axes[0,0].set_xlabel("Phenotype")
412
- axes[0,0].set_ylabel("Frequency")
413
- axes[0,0].set_title("Phenotype Distribution")
414
  axes[0,0].legend()
415
 
416
  bp = axes[0,1].boxplot(y, vert=True, patch_artist=True)
417
  for patch in bp['boxes']:
418
- patch.set_facecolor(ACCENT_MINT)
419
  patch.set_edgecolor(ACCENT_PINK)
420
  axes[0,1].set_xticklabels(['Phenotype'])
421
- axes[0,1].set_ylabel("Value")
422
- axes[0,1].set_title("Box Plot")
423
 
424
  stats.probplot(y, dist="norm", plot=axes[1,0])
425
- axes[1,0].set_title("Normal Q-Q Plot")
426
- axes[1,0].get_lines()[0].set_color(ACCENT_LAV)
427
  axes[1,0].get_lines()[1].set_color(ACCENT_PINK)
428
 
429
- axes[1,1].hist(y, bins=15, density=True, color=ACCENT_LAV, alpha=0.7, edgecolor='white')
430
  x_dense = np.linspace(y.min(), y.max(), 100)
431
  kde = stats.gaussian_kde(y)
432
  axes[1,1].plot(x_dense, kde(x_dense), color=ACCENT_PINK, lw=2)
433
- axes[1,1].set_xlabel("Phenotype")
434
- axes[1,1].set_ylabel("Density")
435
- axes[1,1].set_title("Density Plot")
436
 
437
  fig.tight_layout()
438
  return fig
439
 
440
  def plot_maf_analysis(maf, snp_names):
 
441
  fig, axes = plt.subplots(2, 2, figsize=(14, 10))
442
  style_fig(fig)
443
 
444
- axes[0,0].hist(maf, bins=20, color=ACCENT_MINT, edgecolor='white')
445
  axes[0,0].axvline(0.05, color=ACCENT_PINK, ls='--', lw=2, label="MAF=0.05")
446
- axes[0,0].set_xlabel("Minor Allele Frequency")
447
- axes[0,0].set_ylabel("Count")
448
- axes[0,0].set_title("MAF Distribution")
449
  axes[0,0].legend()
450
 
451
  order = np.argsort(maf)[::-1]
452
- colors = [ACCENT_MINT if m >= 0.05 else ACCENT_LAV for m in maf[order]]
453
- axes[0,1].bar(range(min(50, len(maf))), maf[order][:50], color=colors[:50])
454
  axes[0,1].axhline(0.05, color=ACCENT_PINK, ls='--', lw=1.5)
455
- axes[0,1].set_xlabel("SNP Index")
456
- axes[0,1].set_ylabel("MAF")
457
- axes[0,1].set_title("Top 50 SNPs by MAF")
458
 
459
  rare_mask = maf < 0.05
460
- 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%%')
461
- axes[1,0].set_title("Rare vs Common Variants")
462
-
463
- 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}",
464
- ha='center', va='center', transform=axes[1,1].transAxes)
465
- axes[1,1].set_title("MAF Summary")
466
-
467
- fig.tight_layout()
468
- return fig
469
-
470
- def plot_ld_analysis(G, positions, chroms):
471
- fig, axes = plt.subplots(2, 2, figsize=(14, 12))
472
- style_fig(fig)
473
 
474
- m = G.shape[1]
475
- dists, r2s = [], []
476
-
477
- # Sample LD pairs
478
- n_samples = min(500, m*(m-1)//2)
479
- sampled_pairs = []
480
- for i in range(min(50, m)):
481
- for j in range(i+1, min(50, m)):
482
- sampled_pairs.append((i, j))
483
-
484
- for i, j in sampled_pairs:
485
- xi, xj = G[:, i], G[:, j]
486
- mask = ~(np.isnan(xi) | np.isnan(xj))
487
- if mask.sum() >= 4:
488
- r, _ = stats.pearsonr(xi[mask], xj[mask])
489
- d = abs(positions[j] - positions[i]) if len(positions) > max(i,j) else 0
490
- dists.append(d)
491
- r2s.append(r**2)
492
-
493
- if len(dists) > 0:
494
- axes[0,0].scatter(np.array(dists)/1000, r2s, alpha=0.5, s=20, color=ACCENT_MINT)
495
- axes[0,0].set_xlabel("Distance (kb)")
496
- axes[0,0].set_ylabel("rΒ²")
497
- axes[0,0].set_title("LD Decay")
498
-
499
- bins = np.percentile(dists, np.linspace(0, 100, 11))
500
- bin_centers, bin_means = [], []
501
- for k in range(len(bins)-1):
502
- mask = (dists >= bins[k]) & (dists < bins[k+1])
503
- if mask.sum() > 0:
504
- bin_centers.append((bins[k] + bins[k+1])/2/1000)
505
- bin_means.append(np.mean(np.array(r2s)[mask]))
506
- axes[0,0].plot(bin_centers, bin_means, color=ACCENT_PINK, lw=2, marker='o')
507
-
508
- m_sub = min(30, m)
509
- R = np.zeros((m_sub, m_sub))
510
- for i in range(m_sub):
511
- for j in range(m_sub):
512
- if i == j:
513
- R[i,j] = 1
514
- else:
515
- xi, xj = G[:, i], G[:, j]
516
- mask = ~(np.isnan(xi) | np.isnan(xj))
517
- if mask.sum() >= 3:
518
- r, _ = stats.pearsonr(xi[mask], xj[mask])
519
- R[i,j] = r**2
520
-
521
- im = axes[0,1].imshow(R, cmap='RdYlBu_r', vmin=0, vmax=1, aspect='auto')
522
- axes[0,1].set_title("LD Heatmap (first 30 SNPs)")
523
- plt.colorbar(im, ax=axes[0,1], label="rΒ²")
524
-
525
- if len(r2s) > 0:
526
- axes[1,0].hist(r2s, bins=20, color=ACCENT_LAV, edgecolor='white')
527
- axes[1,0].set_xlabel("rΒ²")
528
- axes[1,0].set_ylabel("Frequency")
529
- axes[1,0].set_title("LD Distribution")
530
-
531
- if len(dists) > 0:
532
- dists_kb = np.array(dists)/1000
533
- r2s_arr = np.array(r2s)
534
- axes[1,1].scatter(dists_kb, r2s_arr, alpha=0.3, s=15, color=ACCENT_MINT)
535
- axes[1,1].set_xlabel("Distance (kb)")
536
- axes[1,1].set_ylabel("rΒ²")
537
- axes[1,1].set_title("LD Decay Scatter")
538
- axes[1,1].set_ylim(0, 1)
539
 
540
  fig.tight_layout()
541
  return fig
542
 
543
  def plot_effect_sizes(pvals, betas, snp_names):
 
544
  fig, axes = plt.subplots(2, 2, figsize=(14, 10))
545
  style_fig(fig)
546
 
547
  top_idx = np.argsort(np.abs(betas))[-20:]
548
  top_betas = betas[top_idx]
549
  top_names = [snp_names[i][:15] for i in top_idx]
550
- colors = [ACCENT_PINK if b < 0 else ACCENT_MINT for b in top_betas]
551
 
552
- axes[0,0].barh(range(len(top_betas)), top_betas, color=colors)
553
  axes[0,0].axvline(0, color='black', lw=0.5)
554
  axes[0,0].set_yticks(range(len(top_betas)))
555
  axes[0,0].set_yticklabels(top_names, fontsize=8)
556
- axes[0,0].set_xlabel("Effect Size (Ξ²)")
557
- axes[0,0].set_title("Top 20 Effect Sizes")
558
 
559
  log_p = -np.log10(np.clip(pvals, 1e-300, 1))
560
  sig_thr = -np.log10(0.05/len(pvals))
561
- colors_v = np.where(log_p >= sig_thr, ACCENT_GOLD, np.where(betas > 0, ACCENT_MINT, ACCENT_LAV))
562
- axes[0,1].scatter(betas, log_p, c=colors_v, s=30, alpha=0.7)
563
  axes[0,1].axhline(sig_thr, color=ACCENT_PINK, ls='--', lw=1.5, label="Bonferroni")
564
  axes[0,1].axvline(0, color='black', lw=0.5)
565
- axes[0,1].set_xlabel("Effect Size (Ξ²)")
566
- axes[0,1].set_ylabel("-log10(p)")
567
- axes[0,1].set_title("Volcano Plot")
568
  axes[0,1].legend()
569
 
570
- axes[1,0].hist(betas, bins=30, color=ACCENT_MINT, edgecolor='white')
571
  axes[1,0].axvline(0, color=ACCENT_PINK, lw=2, ls='--')
572
- axes[1,0].set_xlabel("Effect Size (Ξ²)")
573
- axes[1,0].set_ylabel("Frequency")
574
- axes[1,0].set_title("Effect Size Distribution")
575
-
576
- axes[1,1].scatter(betas, log_p, c=colors_v, s=25, alpha=0.6)
577
- axes[1,1].set_xlabel("Effect Size (Ξ²)")
578
- axes[1,1].set_ylabel("-log10(p)")
579
- axes[1,1].set_title("Effect Size vs Significance")
580
-
581
- fig.tight_layout()
582
- return fig
583
-
584
- def plot_heterozygosity(G, y, ids):
585
- fig, axes = plt.subplots(2, 2, figsize=(14, 10))
586
- style_fig(fig)
587
-
588
- het = compute_heterozygosity(G)
589
-
590
- axes[0,0].hist(het, bins=20, color=ACCENT_LAV, edgecolor='white')
591
- axes[0,0].set_xlabel("Heterozygosity")
592
- axes[0,0].set_ylabel("Count")
593
- axes[0,0].set_title("Individual Heterozygosity")
594
-
595
- axes[0,1].scatter(het, y, c=ACCENT_MINT, s=50, alpha=0.7)
596
- axes[0,1].set_xlabel("Heterozygosity")
597
- axes[0,1].set_ylabel("Phenotype")
598
- axes[0,1].set_title("Heterozygosity vs Phenotype")
599
-
600
- top_idx = np.argsort(het)[-10:]
601
- axes[1,0].barh(range(len(top_idx)), het[top_idx], color=ACCENT_PINK)
602
- axes[1,0].set_yticks(range(len(top_idx)))
603
- axes[1,0].set_yticklabels([ids[i][:10] for i in top_idx], fontsize=8)
604
- axes[1,0].set_xlabel("Heterozygosity")
605
- axes[1,0].set_title("Top 10 Most Heterozygous Individuals")
606
-
607
- median_y = np.median(y)
608
- high_group = het[y > median_y]
609
- low_group = het[y <= median_y]
610
- axes[1,1].boxplot([low_group, high_group], labels=['Low Phenotype', 'High Phenotype'])
611
- axes[1,1].set_ylabel("Heterozygosity")
612
- axes[1,1].set_title("Heterozygosity by Phenotype Group")
613
-
614
- fig.tight_layout()
615
- return fig
616
-
617
- def plot_call_rate_analysis(G, snp_names):
618
- fig, axes = plt.subplots(2, 2, figsize=(14, 10))
619
- style_fig(fig)
620
-
621
- call_rate = compute_call_rate(G)
622
-
623
- axes[0,0].hist(call_rate, bins=20, color=ACCENT_MINT, edgecolor='white')
624
- axes[0,0].axvline(0.95, color=ACCENT_PINK, ls='--', lw=2, label="95% threshold")
625
- axes[0,0].set_xlabel("Call Rate")
626
- axes[0,0].set_ylabel("Count")
627
- axes[0,0].set_title("SNP Call Rate Distribution")
628
- axes[0,0].legend()
629
-
630
- order = np.argsort(call_rate)
631
- axes[0,1].plot(call_rate[order], color=ACCENT_LAV, lw=1)
632
- axes[0,1].axhline(0.95, color=ACCENT_PINK, ls='--', lw=1.5)
633
- axes[0,1].fill_between(range(len(call_rate)), 0, call_rate[order], alpha=0.3, color=ACCENT_MINT)
634
- axes[0,1].set_xlabel("SNP Index (sorted)")
635
- axes[0,1].set_ylabel("Call Rate")
636
- axes[0,1].set_title("Call Rate by SNP")
637
-
638
- low_cr = call_rate < 0.95
639
- 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%%')
640
- axes[1,0].set_title("SNP Quality")
641
-
642
- 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()}",
643
- ha='center', va='center', transform=axes[1,1].transAxes)
644
- axes[1,1].set_title("Call Rate Summary")
645
-
646
- fig.tight_layout()
647
- return fig
648
-
649
- def plot_kinship_analysis(K, ids):
650
- fig, axes = plt.subplots(2, 2, figsize=(14, 12))
651
- style_fig(fig)
652
-
653
- im = axes[0,0].imshow(K, cmap='coolwarm', aspect='auto', vmin=-0.5, vmax=1)
654
- axes[0,0].set_title("Kinship Matrix")
655
- plt.colorbar(im, ax=axes[0,0], label="Kinship")
656
-
657
- K_flat = K[np.triu_indices_from(K, k=1)]
658
- axes[0,1].hist(K_flat, bins=30, color=ACCENT_LAV, edgecolor='white')
659
- axes[0,1].set_xlabel("Kinship Coefficient")
660
- axes[0,1].set_ylabel("Frequency")
661
- axes[0,1].set_title("Pairwise Kinship Distribution")
662
-
663
- linkage_matrix = linkage(K, method='average')
664
- dendrogram(linkage_matrix, ax=axes[1,0], labels=ids, leaf_rotation=90, leaf_font_size=8, color_threshold=0.7)
665
- axes[1,0].set_title("Sample Clustering Dendrogram")
666
- axes[1,0].set_ylabel("Distance")
667
-
668
- eigvals, eigvecs = np.linalg.eigh(K)
669
- idx = np.argsort(eigvals)[::-1]
670
- axes[1,1].scatter(eigvecs[:, idx[0]], eigvecs[:, idx[1]], c=ACCENT_MINT, s=60, edgecolors='white')
671
- axes[1,1].set_xlabel("PC1")
672
- axes[1,1].set_ylabel("PC2")
673
- axes[1,1].set_title("Kinship PCA")
674
-
675
- fig.tight_layout()
676
- return fig
677
-
678
- def plot_mds_analysis(G, y, ids):
679
- fig, axes = plt.subplots(1, 2, figsize=(14, 6))
680
- style_fig(fig)
681
-
682
- try:
683
- mds = MDS(n_components=2, random_state=42, normalized_stress='auto')
684
- mds_coords = mds.fit_transform(G)
685
-
686
- sc = axes[0].scatter(mds_coords[:, 0], mds_coords[:, 1], c=y, cmap='coolwarm', s=60, edgecolors='white')
687
- axes[0].set_xlabel("MDS Dimension 1")
688
- axes[0].set_ylabel("MDS Dimension 2")
689
- axes[0].set_title("Multi-Dimensional Scaling (MDS)")
690
- plt.colorbar(sc, ax=axes[0], label="Phenotype")
691
-
692
- perplexity = min(30, len(G)-1)
693
- tsne = TSNE(n_components=2, random_state=42, perplexity=perplexity)
694
- tsne_coords = tsne.fit_transform(G)
695
-
696
- sc2 = axes[1].scatter(tsne_coords[:, 0], tsne_coords[:, 1], c=y, cmap='coolwarm', s=60, edgecolors='white')
697
- axes[1].set_xlabel("t-SNE Dimension 1")
698
- axes[1].set_ylabel("t-SNE Dimension 2")
699
- axes[1].set_title("t-SNE Visualization")
700
- plt.colorbar(sc2, ax=axes[1], label="Phenotype")
701
- except Exception as e:
702
- axes[0].text(0.5, 0.5, f"MDS failed: {str(e)[:50]}", ha='center', transform=axes[0].transAxes)
703
- axes[1].text(0.5, 0.5, f"t-SNE failed: {str(e)[:50]}", ha='center', transform=axes[1].transAxes)
704
-
705
- fig.tight_layout()
706
- return fig
707
-
708
- def plot_manhattan_by_chromosome(pvals, chroms, positions):
709
- fig, axes = plt.subplots(2, 3, figsize=(15, 10))
710
- style_fig(fig)
711
- axes = axes.flatten()
712
-
713
- log_p = -np.log10(np.clip(pvals, 1e-300, 1))
714
- unique_chroms = sorted(set(chroms))
715
-
716
- for i, ch in enumerate(unique_chroms[:6]):
717
- mask = chroms == ch
718
- if mask.sum() > 0:
719
- axes[i].scatter(positions[mask], log_p[mask], c=ACCENT_MINT, s=15, alpha=0.7)
720
- axes[i].axhline(-np.log10(5e-8), color=ACCENT_PINK, ls='--', lw=1)
721
- axes[i].set_xlabel(f"Chromosome {ch} Position")
722
- axes[i].set_ylabel("-log10(p)")
723
- axes[i].set_title(f"Chromosome {ch}")
724
-
725
- for i in range(len(unique_chroms), 6):
726
- axes[i].set_visible(False)
727
-
728
- fig.tight_layout()
729
- return fig
730
-
731
- def plot_manhattan_qq_combined(pvals, chroms, positions):
732
- fig = plt.figure(figsize=(14, 10))
733
- style_fig(fig)
734
- gs = fig.add_gridspec(2, 2, height_ratios=[2, 1])
735
-
736
- ax1 = fig.add_subplot(gs[0, :])
737
- log_p = -np.log10(np.clip(pvals, 1e-300, 1))
738
- ax1.scatter(range(len(pvals)), log_p, c=ACCENT_MINT, s=10, alpha=0.7)
739
- ax1.axhline(-np.log10(5e-8), color=ACCENT_PINK, ls='--', lw=1.5, label="Bonferroni")
740
- ax1.set_xlabel("SNP Index")
741
- ax1.set_ylabel("-log10(p)")
742
- ax1.set_title("Manhattan Plot")
743
- ax1.legend()
744
-
745
- ax2 = fig.add_subplot(gs[1, 0])
746
- n = len(pvals)
747
- obs = np.sort(-np.log10(np.clip(pvals, 1e-300, 1)))[::-1]
748
- exp = -np.log10(np.linspace(1/n, 1, n)[::-1])
749
- ax2.scatter(exp, obs, c=ACCENT_LAV, s=15, alpha=0.7)
750
- ax2.plot([0, max(exp)], [0, max(exp)], color=ACCENT_PINK, ls='--', lw=1.5)
751
- ax2.set_xlabel("Expected -log10(p)")
752
- ax2.set_ylabel("Observed -log10(p)")
753
- ax2.set_title("QQ Plot")
754
-
755
- ax3 = fig.add_subplot(gs[1, 1])
756
- ax3.hist(pvals, bins=50, color=ACCENT_MINT, edgecolor='white')
757
- ax3.axvline(0.05, color=ACCENT_PINK, ls='--', lw=1.5)
758
- ax3.set_xlabel("p-value")
759
- ax3.set_ylabel("Frequency")
760
- ax3.set_title("P-value Distribution")
761
-
762
- fig.tight_layout()
763
- return fig
764
-
765
- def plot_manhattan_stacked(pvals, chroms, positions):
766
- fig, ax = plt.subplots(figsize=(14, 6))
767
- style_fig(fig)
768
-
769
- log_p = -np.log10(np.clip(pvals, 1e-300, 1))
770
- unique_chroms = sorted(set(chroms))
771
 
772
- y_offset = 0
773
- for ch in unique_chroms:
774
- mask = chroms == ch
775
- if mask.sum() > 0:
776
- x_vals = np.arange(mask.sum())
777
- y_vals = log_p[mask]
778
- ax.scatter(x_vals + y_offset, y_vals, c=ACCENT_MINT, s=8, alpha=0.6)
779
- ax.axvline(y_offset, color=GRID_SOFT, lw=0.5, alpha=0.5)
780
- y_offset += mask.sum()
781
-
782
- ax.axhline(-np.log10(5e-8), color=ACCENT_PINK, ls='--', lw=1.5)
783
- ax.set_xlabel("SNP Index by Chromosome")
784
- ax.set_ylabel("-log10(p)")
785
- ax.set_title("Stacked Manhattan Plot")
786
 
787
  fig.tight_layout()
788
  return fig
789
 
790
- def plot_correlation_heatmap(G, y):
791
- fig, axes = plt.subplots(1, 2, figsize=(14, 6))
 
792
  style_fig(fig)
793
 
794
- n_snp = min(50, G.shape[1])
795
- corr_mat = np.corrcoef(G[:, :n_snp].T)
796
 
797
- im = axes[0].imshow(corr_mat, cmap='coolwarm', vmin=-1, vmax=1, aspect='auto')
798
- axes[0].set_title("SNP Correlation Matrix")
799
- axes[0].set_xlabel("SNP Index")
800
- axes[0].set_ylabel("SNP Index")
801
- plt.colorbar(im, ax=axes[0], label="Correlation")
802
-
803
- pvals_adj = -np.log10(np.clip(np.corrcoef(G.T, y)[:-1, -1]**2, 1e-300, 1))
804
- top_idx = np.argsort(pvals_adj)[-20:]
805
- top_corr = np.corrcoef(G[:, top_idx].T)
806
 
807
- im2 = axes[1].imshow(top_corr, cmap='coolwarm', vmin=-1, vmax=1, aspect='auto')
808
- axes[1].set_title("Top 20 SNPs Correlation")
809
- axes[1].set_xlabel("SNP Index")
810
- axes[1].set_ylabel("SNP Index")
811
- plt.colorbar(im2, ax=axes[1], label="Correlation")
 
812
 
813
  fig.tight_layout()
814
  return fig
815
 
816
  def plot_summary_dashboard(y, maf, pvals, betas, G):
 
817
  fig, axes = plt.subplots(2, 3, figsize=(15, 10))
818
  style_fig(fig)
819
  axes = axes.flatten()
820
 
821
  axes[0].boxplot(y)
822
- axes[0].set_title(f"Phenotype\nn={len(y)}, mean={y.mean():.2f}")
823
  axes[0].set_ylabel("Value")
824
 
825
- axes[1].hist(maf, bins=20, color=ACCENT_MINT, edgecolor='white')
826
  axes[1].axvline(0.05, color=ACCENT_PINK, ls='--')
827
- axes[1].set_title(f"MAF\nrare={np.sum(maf<0.05)}")
828
  axes[1].set_xlabel("MAF")
829
 
830
  log_p = -np.log10(np.clip(pvals, 1e-300, 1))
831
- axes[2].hist(log_p, bins=30, color=ACCENT_LAV, edgecolor='white')
832
  axes[2].axvline(-np.log10(0.05/len(pvals)), color=ACCENT_PINK, ls='--')
833
- axes[2].set_title(f"P-values\nsig={np.sum(pvals < 0.05/len(pvals))}")
834
- axes[2].set_xlabel("-log10(p)")
835
 
836
- axes[3].hist(betas, bins=30, color=ACCENT_PEACH, edgecolor='white')
837
  axes[3].axvline(0, color=ACCENT_PINK, ls='--')
838
- axes[3].set_title(f"Effect Sizes\nmean={np.mean(betas):.4f}")
839
  axes[3].set_xlabel("Ξ²")
840
 
841
  miss_rate = np.isnan(G).mean()
842
- axes[4].bar(['Complete', 'Missing'], [1-miss_rate, miss_rate], color=[ACCENT_MINT, ACCENT_PINK])
843
- axes[4].set_title(f"Data Completeness\n{1-miss_rate:.1%}")
844
  axes[4].set_ylabel("Proportion")
845
 
846
  lam = np.median(stats.chi2.ppf(1 - np.clip(pvals, 1e-10, 1), df=1)) / stats.chi2.ppf(0.5, df=1)
847
- 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}",
848
- ha='center', va='center', transform=axes[5].transAxes)
849
- axes[5].set_title("Quick Stats")
850
-
851
- fig.tight_layout()
852
- return fig
853
-
854
- def plot_model_comparison(all_results):
855
- """Compare multiple models on the same QQ plot"""
856
- fig, ax = plt.subplots(figsize=(8, 8))
857
- style_fig(fig)
858
-
859
- colors = [ACCENT_PINK, ACCENT_MINT, ACCENT_LAV, ACCENT_PEACH, ACCENT_GOLD, ACCENT_CORAL]
860
-
861
- for idx, (model_name, (pvals, _)) in enumerate(all_results.items()):
862
- n = len(pvals)
863
- obs = np.sort(-np.log10(np.clip(pvals, 1e-300, 1)))[::-1]
864
- exp = -np.log10(np.linspace(1/n, 1, n)[::-1])
865
- ax.plot(exp, obs, color=colors[idx % len(colors)], lw=2, label=model_name, alpha=0.8)
866
-
867
- ax.plot([0, max(exp)], [0, max(exp)], color=ACCENT_GOLD, ls='--', lw=1.5, label='Expected')
868
- ax.set_xlabel("Expected -log10(p)")
869
- ax.set_ylabel("Observed -log10(p)")
870
- ax.set_title("Model Comparison - QQ Plot")
871
- ax.legend(loc='lower right', fontsize=8)
872
 
873
  fig.tight_layout()
874
  return fig
@@ -879,7 +661,7 @@ def run_gwas(file_obj, text_input, selected_models, maf_threshold):
879
  try:
880
  df, snp_cols, chroms, positions = parse_data(file_obj, text_input)
881
  except Exception as e:
882
- return [None] * 18 + [f"❌ Data parsing error: {e}"]
883
 
884
  y = df["Phenotype"].values.astype(float)
885
  ids = df["ID"].values
@@ -924,25 +706,16 @@ def run_gwas(file_obj, text_input, selected_models, maf_threshold):
924
  primary_p, primary_b = p, b
925
 
926
  if primary_p is None:
927
- return [None] * 18 + ["❌ No models selected"]
928
 
929
- # Generate all 16+ plots
930
  plots = []
931
  plots.append(plot_manhattan(primary_p, chr_filt, pos_filt, f"Manhattan Plot - {models_to_run[0]}"))
932
  plots.append(plot_qq(primary_p, f"QQ Plot - {models_to_run[0]}"))
933
  plots.append(plot_pca(G_filt, y, ids))
934
  plots.append(plot_phenotype_distribution(y, ids))
935
  plots.append(plot_maf_analysis(maf_vals, snp_cols))
936
- plots.append(plot_ld_analysis(G_filt, pos_filt, chr_filt))
937
  plots.append(plot_effect_sizes(primary_p, primary_b, snp_filt))
938
- plots.append(plot_heterozygosity(G_filt, y, ids))
939
- plots.append(plot_call_rate_analysis(G_filt, snp_filt))
940
- plots.append(plot_kinship_analysis(K, ids))
941
- plots.append(plot_mds_analysis(G_filt, y, ids))
942
- plots.append(plot_manhattan_by_chromosome(primary_p, chr_filt, pos_filt))
943
- plots.append(plot_manhattan_qq_combined(primary_p, chr_filt, pos_filt))
944
- plots.append(plot_manhattan_stacked(primary_p, chr_filt, pos_filt))
945
- plots.append(plot_correlation_heatmap(G_filt, y))
946
  plots.append(plot_summary_dashboard(y, maf_vals, primary_p, primary_b, G_filt))
947
 
948
  # Add model comparison plot if multiple models selected
@@ -957,13 +730,13 @@ def run_gwas(file_obj, text_input, selected_models, maf_threshold):
957
  # Results table
958
  bonf = 0.05 / len(primary_p)
959
  res_df = pd.DataFrame({
960
- "SNP": snp_filt[:50],
961
- "Chr": chr_filt[:50],
962
- "Pos": pos_filt[:50],
963
- "Beta": np.round(primary_b[:50], 5),
964
- "P_value": primary_p[:50],
965
- "-log10P": np.round(-np.log10(np.clip(primary_p[:50], 1e-300, 1)), 4),
966
- }).sort_values("P_value").head(20)
967
 
968
  lam = np.median(stats.chi2.ppf(1 - np.clip(primary_p, 1e-10, 1), df=1)) / stats.chi2.ppf(0.5, df=1)
969
 
@@ -980,11 +753,11 @@ def run_gwas(file_obj, text_input, selected_models, maf_threshold):
980
  β•‘ β•‘
981
  β•‘ Primary Model: {models_to_run[0]} β•‘
982
  β•‘ Bonferroni threshold: {bonf:.2e} β•‘
983
- β•‘ Significant SNPs: {(primary_p < bonf).sum()} β•‘
984
  β•‘ Genomic Inflation Ξ»: {lam:.4f} β•‘
985
  β•‘ β•‘
986
- β•‘ TOP 5 ASSOCIATIONS: β•‘
987
- {res_df[['SNP', 'Beta', 'P_value']].head(5).to_string(index=False)}
988
  β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•
989
  """
990
 
@@ -1005,60 +778,73 @@ IRRI-34,37,0,0,0,0
1005
  IRRI-42,30.67,0,0,0,0
1006
  IRRI-50,22,0,0,0,2"""
1007
 
1008
- PASTEL_CSS = """
1009
- body, .gradio-container { background: #F9F5F0 !important; font-family: 'Inter', sans-serif !important; }
1010
- .gr-panel, .gr-box { background: #FFFFFF !important; border: 1px solid #E8DFD3 !important; border-radius: 20px !important; }
1011
- h1, h2, h3 { color: #E8A2A2 !important; }
1012
- .gr-button-primary { background: linear-gradient(135deg, #E8A2A2, #C9B6E4) !important; border-radius: 40px !important; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1013
  """
1014
 
1015
  MODELS = ["OLS", "MLM", "GLM", "CMLM", "BLINK", "FarmCPU"]
1016
 
1017
- with gr.Blocks(css=PASTEL_CSS, title="🌸 Complete GWAS Pipeline - 6 Models", theme=gr.themes.Soft()) as demo:
1018
  gr.Markdown("""
1019
- # 🌸 Complete GWAS Analysis Pipeline
1020
- ### 6 Statistical Models Β· 16+ Visualization Types Β· Chromosome Row Support
1021
- """)
 
1022
 
1023
  with gr.Row():
1024
  with gr.Column(scale=1):
1025
- file_in = gr.File(label="Upload CSV/TSV", file_types=[".csv", ".tsv", ".txt"])
1026
- text_in = gr.Textbox(label="Or paste CSV", lines=8, value=SAMPLE_DATA)
1027
- model_sel = gr.CheckboxGroup(choices=MODELS, value=["OLS", "MLM", "GLM"], label="Select Models (6 available)")
1028
- maf_thr = gr.Slider(0, 0.5, 0.05, 0.01, label="MAF Threshold")
1029
- run_btn = gr.Button("πŸš€ Run Complete GWAS (6 Models)", variant="primary", size="lg")
1030
 
1031
  with gr.Column(scale=2):
1032
- summary_out = gr.Textbox(label="Analysis Summary", lines=18)
1033
 
1034
  with gr.Tabs():
1035
- with gr.Tab("πŸ“Š Manhattan"): img1 = gr.Image(type="pil", label="Manhattan Plot")
1036
  with gr.Tab("πŸ“ˆ QQ Plot"): img2 = gr.Image(type="pil", label="QQ Plot")
1037
  with gr.Tab("πŸ”¬ PCA"): img3 = gr.Image(type="pil", label="PCA Analysis")
1038
  with gr.Tab("πŸ“‰ Phenotype"): img4 = gr.Image(type="pil", label="Phenotype Distribution")
1039
  with gr.Tab("🧬 MAF"): img5 = gr.Image(type="pil", label="MAF Analysis")
1040
- with gr.Tab("πŸ”— LD"): img6 = gr.Image(type="pil", label="LD Analysis")
1041
- with gr.Tab("βš– Effect"): img7 = gr.Image(type="pil", label="Effect Sizes")
1042
- with gr.Tab("🧬 Heterozygosity"): img8 = gr.Image(type="pil", label="Heterozygosity")
1043
- with gr.Tab("πŸ“ž Call Rate"): img9 = gr.Image(type="pil", label="Call Rate")
1044
- with gr.Tab("πŸ‘¨β€πŸ‘©β€πŸ‘§ Kinship"): img10 = gr.Image(type="pil", label="Kinship")
1045
- with gr.Tab("🎨 MDS/t-SNE"): img11 = gr.Image(type="pil", label="MDS/t-SNE")
1046
- with gr.Tab("πŸ“Š By Chr"): img12 = gr.Image(type="pil", label="Manhattan by Chromosome")
1047
- with gr.Tab("πŸ“‹ Combined"): img13 = gr.Image(type="pil", label="Combined Plots")
1048
- with gr.Tab("πŸ” Stacked"): img14 = gr.Image(type="pil", label="Stacked Manhattan")
1049
- with gr.Tab("πŸ”₯ Heatmap"): img15 = gr.Image(type="pil", label="Correlation Heatmap")
1050
- with gr.Tab("πŸ“Š Dashboard"): img16 = gr.Image(type="pil", label="Summary Dashboard")
1051
- with gr.Tab("πŸ”„ Model Compare"): img17 = gr.Image(type="pil", label="Model Comparison")
1052
- with gr.Tab("πŸ“‹ Results"): results_tbl = gr.Dataframe(label="Top Associations")
1053
 
1054
  def run_wrapper(f, t, m, maf):
1055
  out = run_gwas(f, t, m, maf)
1056
- if len(out) == 18:
1057
- return out + [None]
1058
- return out
 
1059
 
1060
  run_btn.click(run_wrapper, [file_in, text_in, model_sel, maf_thr],
1061
- [img1, img2, img3, img4, img5, img6, img7, img8, img9, img10, img11, img12, img13, img14, img15, img16, img17, results_tbl, summary_out])
1062
 
1063
  if __name__ == "__main__":
1064
  demo.launch(share=False, server_port=7860)
 
 
 
1
  import gradio as gr
2
  import pandas as pd
3
  import numpy as np
 
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
  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
318
+ '#117A65', # Dark Teal
319
+ '#D35400', # Dark Orange
320
+ '#21618C', # Navy
321
+ '#7D6608', # Olive
322
+ '#2E4053', # Dark Gray
323
+ '#A93226', # Dark Brick
324
+ '#0E6251', # Dark Cyan
325
+ '#5B2C6F', # Dark Violet
326
+ '#7E5109', # Dark Brown
327
+ '#1A5276' # Deep Blue
328
+ ]
329
+ chrom_colors = {c: dark_palette[i % len(dark_palette)] for i, c in enumerate(chrom_list)}
330
 
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
  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
  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
 
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
  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
  # 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
  β•‘ β•‘
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
 
 
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)