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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +198 -151
app.py CHANGED
@@ -1,9 +1,4 @@
1
- """
2
- ╔══════════════════════════════════════════════════════════════════════╗
3
- β•‘ COMPLETE GWAS PIPELINE β€” 15+ Plots & Full Statistical Suite β•‘
4
- β•‘ Supports chromosome row in input files β•‘
5
- β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•
6
- """
7
 
8
  import gradio as gr
9
  import pandas as pd
@@ -75,20 +70,19 @@ def parse_data(file_obj=None, text_input=None):
75
  raise ValueError("No data provided.")
76
 
77
  # Check if second row contains chromosome info
78
- first_row = raw.iloc[0].astype(str)
79
- second_row = raw.iloc[1] if len(raw) > 1 else None
80
-
81
  has_chrom_row = False
82
  chrom_info = {}
83
 
84
- if second_row is not None:
85
- # Check if second row looks like chromosome numbers
86
  chrom_vals = second_row.iloc[2:].astype(str)
87
- if chrom_vals.str.match(r'^\d+$').all():
88
  has_chrom_row = True
89
  for i, col in enumerate(raw.columns[2:]):
90
- chrom_info[col] = int(second_row.iloc[2 + i])
91
- # Remove chromosome row from data
 
 
92
  raw = raw.drop(index=1).reset_index(drop=True)
93
 
94
  cols = list(raw.columns)
@@ -102,7 +96,7 @@ def parse_data(file_obj=None, text_input=None):
102
 
103
  # Replace missing codes
104
  geno = raw[snp_cols].apply(pd.to_numeric, errors="coerce")
105
- geno = geno.where(~geno.isin([-1, -9, -99]), np.nan)
106
 
107
  df = pd.DataFrame()
108
  df["ID"] = raw[id_col].values
@@ -110,11 +104,12 @@ def parse_data(file_obj=None, text_input=None):
110
  for c in snp_cols:
111
  df[c] = geno[c].values
112
 
113
- # Parse chromosome and position from SNP names or use provided chrom row
114
  chroms, positions = [], []
115
  for m in snp_cols:
116
  if m in chrom_info:
117
  chroms.append(chrom_info[m])
 
118
  else:
119
  m_clean = str(m).strip()
120
  mat = re.match(r"[Cc]hr(\d+)[_\-](\d+)", m_clean)
@@ -128,7 +123,7 @@ def parse_data(file_obj=None, text_input=None):
128
 
129
  return df, snp_cols, np.array(chroms), np.array(positions)
130
 
131
- # ─────────────────────────── STATISTICAL MODELS ───────────────────────
132
 
133
  def impute_genotypes(geno_matrix):
134
  mat = geno_matrix.copy().astype(float)
@@ -145,11 +140,9 @@ def compute_maf(G):
145
  return maf
146
 
147
  def compute_heterozygosity(G):
148
- """Calculate observed heterozygosity per individual."""
149
  return np.mean(G == 1, axis=1) if G.shape[1] > 0 else np.zeros(G.shape[0])
150
 
151
  def compute_call_rate(G):
152
- """Calculate SNP call rate."""
153
  return 1 - np.isnan(G).mean(axis=0)
154
 
155
  def build_kinship(G):
@@ -161,6 +154,7 @@ def build_kinship(G):
161
  K = Z @ Z.T / denom
162
  return K
163
 
 
164
  def ols_gwas(y, G):
165
  n, m = G.shape
166
  pvals = np.ones(m)
@@ -175,6 +169,7 @@ def ols_gwas(y, G):
175
  betas[j] = slope
176
  return pvals, betas
177
 
 
178
  def mlm_gwas(y, G, K):
179
  n, m = G.shape
180
  pvals = np.ones(m)
@@ -195,13 +190,15 @@ def mlm_gwas(y, G, K):
195
  betas[j] = slope
196
  return pvals, betas
197
 
 
198
  def glm_gwas(y, G):
199
  n, m = G.shape
200
  pvals = np.ones(m)
201
  betas = np.zeros(m)
202
  scaler = StandardScaler()
203
  G_sc = scaler.fit_transform(G)
204
- pca = PCA(n_components=min(3, n - 2))
 
205
  PCs = pca.fit_transform(G_sc)
206
  reg = LinearRegression().fit(PCs, y)
207
  y_adj = y - reg.predict(PCs)
@@ -215,7 +212,85 @@ def glm_gwas(y, G):
215
  betas[j] = slope
216
  return pvals, betas
217
 
218
- # ─────────────────────────── 15+ PLOTTING FUNCTIONS ───────────────────
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
219
 
220
  def fig_to_pil(fig):
221
  buf = io.BytesIO()
@@ -231,7 +306,7 @@ def plot_manhattan(pvals, chroms, positions, title="Manhattan Plot"):
231
  sig_line = -np.log10(5e-8)
232
 
233
  chrom_list = sorted(set(chroms))
234
- palette = [ACCENT_PINK, ACCENT_MINT, ACCENT_LAV, ACCENT_PEACH, ACCENT_GOLD]
235
  chrom_colors = {c: palette[i % len(palette)] for i, c in enumerate(chrom_list)}
236
 
237
  x_offset = 0
@@ -240,6 +315,8 @@ def plot_manhattan(pvals, chroms, positions, title="Manhattan Plot"):
240
  for ch in chrom_list:
241
  mask = chroms == ch
242
  pos = positions[mask]
 
 
243
  order = np.argsort(pos)
244
  x_vals = pos[order] - pos.min() + x_offset
245
  x_coords[np.where(mask)[0][order]] = x_vals
@@ -253,7 +330,7 @@ def plot_manhattan(pvals, chroms, positions, title="Manhattan Plot"):
253
  if sig_mask.any():
254
  ax.scatter(x_coords[sig_mask], log_p[sig_mask], c=ACCENT_GOLD, s=80, marker="*", zorder=5, label="Significant")
255
 
256
- ax.axhline(sig_line, color=ACCENT_PINK, ls="--", lw=1.5, label="Bonferroni")
257
  ax.set_xticks(tick_pos)
258
  ax.set_xticklabels(tick_lab, rotation=45)
259
  ax.set_ylabel("-log10(p)")
@@ -294,14 +371,12 @@ def plot_pca(G, y, ids):
294
  pcs = pca.fit_transform(G_sc)
295
  var_exp = pca.explained_variance_ratio_ * 100
296
 
297
- # PC1 vs PC2
298
  sc = axes[0,0].scatter(pcs[:,0], pcs[:,1], c=y, cmap='coolwarm', s=60, edgecolors='white')
299
  axes[0,0].set_xlabel(f"PC1 ({var_exp[0]:.1f}%)")
300
  axes[0,0].set_ylabel(f"PC2 ({var_exp[1]:.1f}%)")
301
  axes[0,0].set_title("PCA: PC1 vs PC2")
302
  plt.colorbar(sc, ax=axes[0,0], label="Phenotype")
303
 
304
- # PC3 vs PC4
305
  if n_comp >= 4:
306
  axes[0,1].scatter(pcs[:,2], pcs[:,3], c=y, cmap='coolwarm', s=60, edgecolors='white')
307
  axes[0,1].set_xlabel(f"PC3 ({var_exp[2]:.1f}%)")
@@ -310,7 +385,6 @@ def plot_pca(G, y, ids):
310
  else:
311
  axes[0,1].text(0.5, 0.5, "Insufficient components", ha='center', transform=axes[0,1].transAxes)
312
 
313
- # Scree plot
314
  axes[1,0].bar(range(1, n_comp+1), var_exp, color=ACCENT_MINT, edgecolor='white')
315
  axes[1,0].plot(range(1, n_comp+1), np.cumsum(var_exp), color=ACCENT_PINK, marker='o', lw=2, label="Cumulative")
316
  axes[1,0].set_xlabel("Principal Component")
@@ -318,7 +392,6 @@ def plot_pca(G, y, ids):
318
  axes[1,0].set_title("Scree Plot")
319
  axes[1,0].legend()
320
 
321
- # 3D projection (2D plot with color)
322
  axes[1,1].scatter(pcs[:,0], pcs[:,1], c=y, cmap='coolwarm', s=60, edgecolors='white')
323
  axes[1,1].set_xlabel(f"PC1 ({var_exp[0]:.1f}%)")
324
  axes[1,1].set_ylabel(f"PC2 ({var_exp[1]:.1f}%)")
@@ -331,7 +404,6 @@ def plot_phenotype_distribution(y, ids):
331
  fig, axes = plt.subplots(2, 2, figsize=(14, 10))
332
  style_fig(fig)
333
 
334
- # Histogram
335
  axes[0,0].hist(y, bins=15, color=ACCENT_LAV, edgecolor='white', alpha=0.8)
336
  axes[0,0].axvline(y.mean(), color=ACCENT_PINK, lw=2, ls='--', label=f"Mean: {y.mean():.2f}")
337
  axes[0,0].axvline(y.mean() + y.std(), color=ACCENT_GOLD, lw=1.5, ls=':', label="Β±1 SD")
@@ -341,7 +413,6 @@ def plot_phenotype_distribution(y, ids):
341
  axes[0,0].set_title("Phenotype Distribution")
342
  axes[0,0].legend()
343
 
344
- # Box plot
345
  bp = axes[0,1].boxplot(y, vert=True, patch_artist=True)
346
  for patch in bp['boxes']:
347
  patch.set_facecolor(ACCENT_MINT)
@@ -350,13 +421,11 @@ def plot_phenotype_distribution(y, ids):
350
  axes[0,1].set_ylabel("Value")
351
  axes[0,1].set_title("Box Plot")
352
 
353
- # Q-Q plot for normality
354
  stats.probplot(y, dist="norm", plot=axes[1,0])
355
  axes[1,0].set_title("Normal Q-Q Plot")
356
  axes[1,0].get_lines()[0].set_color(ACCENT_LAV)
357
  axes[1,0].get_lines()[1].set_color(ACCENT_PINK)
358
 
359
- # Density plot
360
  axes[1,1].hist(y, bins=15, density=True, color=ACCENT_LAV, alpha=0.7, edgecolor='white')
361
  x_dense = np.linspace(y.min(), y.max(), 100)
362
  kde = stats.gaussian_kde(y)
@@ -372,7 +441,6 @@ def plot_maf_analysis(maf, snp_names):
372
  fig, axes = plt.subplots(2, 2, figsize=(14, 10))
373
  style_fig(fig)
374
 
375
- # MAF histogram
376
  axes[0,0].hist(maf, bins=20, color=ACCENT_MINT, edgecolor='white')
377
  axes[0,0].axvline(0.05, color=ACCENT_PINK, ls='--', lw=2, label="MAF=0.05")
378
  axes[0,0].set_xlabel("Minor Allele Frequency")
@@ -380,7 +448,6 @@ def plot_maf_analysis(maf, snp_names):
380
  axes[0,0].set_title("MAF Distribution")
381
  axes[0,0].legend()
382
 
383
- # MAF sorted bar plot
384
  order = np.argsort(maf)[::-1]
385
  colors = [ACCENT_MINT if m >= 0.05 else ACCENT_LAV for m in maf[order]]
386
  axes[0,1].bar(range(min(50, len(maf))), maf[order][:50], color=colors[:50])
@@ -389,13 +456,12 @@ def plot_maf_analysis(maf, snp_names):
389
  axes[0,1].set_ylabel("MAF")
390
  axes[0,1].set_title("Top 50 SNPs by MAF")
391
 
392
- # Rare variants count
393
  rare_mask = maf < 0.05
394
  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%%')
395
  axes[1,0].set_title("Rare vs Common Variants")
396
 
397
- # MAF by chromosome
398
- axes[1,1].text(0.5, 0.5, "MAF by chromosome available\nwith full chromosome data", ha='center', va='center', transform=axes[1,1].transAxes)
399
  axes[1,1].set_title("MAF Summary")
400
 
401
  fig.tight_layout()
@@ -430,7 +496,6 @@ def plot_ld_analysis(G, positions, chroms):
430
  axes[0,0].set_ylabel("rΒ²")
431
  axes[0,0].set_title("LD Decay")
432
 
433
- # Binned average
434
  bins = np.percentile(dists, np.linspace(0, 100, 11))
435
  bin_centers, bin_means = [], []
436
  for k in range(len(bins)-1):
@@ -440,7 +505,6 @@ def plot_ld_analysis(G, positions, chroms):
440
  bin_means.append(np.mean(np.array(r2s)[mask]))
441
  axes[0,0].plot(bin_centers, bin_means, color=ACCENT_PINK, lw=2, marker='o')
442
 
443
- # LD heatmap
444
  m_sub = min(30, m)
445
  R = np.zeros((m_sub, m_sub))
446
  for i in range(m_sub):
@@ -458,13 +522,12 @@ def plot_ld_analysis(G, positions, chroms):
458
  axes[0,1].set_title("LD Heatmap (first 30 SNPs)")
459
  plt.colorbar(im, ax=axes[0,1], label="rΒ²")
460
 
461
- # LD distribution
462
- axes[1,0].hist(r2s, bins=20, color=ACCENT_LAV, edgecolor='white')
463
- axes[1,0].set_xlabel("rΒ²")
464
- axes[1,0].set_ylabel("Frequency")
465
- axes[1,0].set_title("LD Distribution")
466
 
467
- # LD decay curve fit
468
  if len(dists) > 0:
469
  dists_kb = np.array(dists)/1000
470
  r2s_arr = np.array(r2s)
@@ -481,7 +544,6 @@ def plot_effect_sizes(pvals, betas, snp_names):
481
  fig, axes = plt.subplots(2, 2, figsize=(14, 10))
482
  style_fig(fig)
483
 
484
- # Effect size bar plot (top 20)
485
  top_idx = np.argsort(np.abs(betas))[-20:]
486
  top_betas = betas[top_idx]
487
  top_names = [snp_names[i][:15] for i in top_idx]
@@ -494,7 +556,6 @@ def plot_effect_sizes(pvals, betas, snp_names):
494
  axes[0,0].set_xlabel("Effect Size (Ξ²)")
495
  axes[0,0].set_title("Top 20 Effect Sizes")
496
 
497
- # Volcano plot
498
  log_p = -np.log10(np.clip(pvals, 1e-300, 1))
499
  sig_thr = -np.log10(0.05/len(pvals))
500
  colors_v = np.where(log_p >= sig_thr, ACCENT_GOLD, np.where(betas > 0, ACCENT_MINT, ACCENT_LAV))
@@ -506,14 +567,12 @@ def plot_effect_sizes(pvals, betas, snp_names):
506
  axes[0,1].set_title("Volcano Plot")
507
  axes[0,1].legend()
508
 
509
- # Effect size histogram
510
  axes[1,0].hist(betas, bins=30, color=ACCENT_MINT, edgecolor='white')
511
  axes[1,0].axvline(0, color=ACCENT_PINK, lw=2, ls='--')
512
  axes[1,0].set_xlabel("Effect Size (Ξ²)")
513
  axes[1,0].set_ylabel("Frequency")
514
  axes[1,0].set_title("Effect Size Distribution")
515
 
516
- # Beta vs -log10(p)
517
  axes[1,1].scatter(betas, log_p, c=colors_v, s=25, alpha=0.6)
518
  axes[1,1].set_xlabel("Effect Size (Ξ²)")
519
  axes[1,1].set_ylabel("-log10(p)")
@@ -528,19 +587,16 @@ def plot_heterozygosity(G, y, ids):
528
 
529
  het = compute_heterozygosity(G)
530
 
531
- # Heterozygosity distribution
532
  axes[0,0].hist(het, bins=20, color=ACCENT_LAV, edgecolor='white')
533
  axes[0,0].set_xlabel("Heterozygosity")
534
  axes[0,0].set_ylabel("Count")
535
  axes[0,0].set_title("Individual Heterozygosity")
536
 
537
- # Heterozygosity vs phenotype
538
  axes[0,1].scatter(het, y, c=ACCENT_MINT, s=50, alpha=0.7)
539
  axes[0,1].set_xlabel("Heterozygosity")
540
  axes[0,1].set_ylabel("Phenotype")
541
  axes[0,1].set_title("Heterozygosity vs Phenotype")
542
 
543
- # Top heterozygosity individuals
544
  top_idx = np.argsort(het)[-10:]
545
  axes[1,0].barh(range(len(top_idx)), het[top_idx], color=ACCENT_PINK)
546
  axes[1,0].set_yticks(range(len(top_idx)))
@@ -548,7 +604,6 @@ def plot_heterozygosity(G, y, ids):
548
  axes[1,0].set_xlabel("Heterozygosity")
549
  axes[1,0].set_title("Top 10 Most Heterozygous Individuals")
550
 
551
- # Heterozygosity by group (using phenotype median split)
552
  median_y = np.median(y)
553
  high_group = het[y > median_y]
554
  low_group = het[y <= median_y]
@@ -565,7 +620,6 @@ def plot_call_rate_analysis(G, snp_names):
565
 
566
  call_rate = compute_call_rate(G)
567
 
568
- # Call rate distribution
569
  axes[0,0].hist(call_rate, bins=20, color=ACCENT_MINT, edgecolor='white')
570
  axes[0,0].axvline(0.95, color=ACCENT_PINK, ls='--', lw=2, label="95% threshold")
571
  axes[0,0].set_xlabel("Call Rate")
@@ -573,7 +627,6 @@ def plot_call_rate_analysis(G, snp_names):
573
  axes[0,0].set_title("SNP Call Rate Distribution")
574
  axes[0,0].legend()
575
 
576
- # Call rate sorted
577
  order = np.argsort(call_rate)
578
  axes[0,1].plot(call_rate[order], color=ACCENT_LAV, lw=1)
579
  axes[0,1].axhline(0.95, color=ACCENT_PINK, ls='--', lw=1.5)
@@ -582,18 +635,12 @@ def plot_call_rate_analysis(G, snp_names):
582
  axes[0,1].set_ylabel("Call Rate")
583
  axes[0,1].set_title("Call Rate by SNP")
584
 
585
- # Low call rate SNPs
586
  low_cr = call_rate < 0.95
587
  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%%')
588
  axes[1,0].set_title("SNP Quality")
589
 
590
- # Missingness by position
591
- axes[1,1].text(0.5, 0.5, "Call rate summary statistics\n\n" +
592
- f"Mean call rate: {np.mean(call_rate):.4f}\n" +
593
- f"Median call rate: {np.median(call_rate):.4f}\n" +
594
- f"Min call rate: {np.min(call_rate):.4f}\n" +
595
- f"SNPs with CR>95%: {(~low_cr).sum()}",
596
- ha='center', va='center', transform=axes[1,1].transAxes)
597
  axes[1,1].set_title("Call Rate Summary")
598
 
599
  fig.tight_layout()
@@ -603,25 +650,21 @@ def plot_kinship_analysis(K, ids):
603
  fig, axes = plt.subplots(2, 2, figsize=(14, 12))
604
  style_fig(fig)
605
 
606
- # Kinship heatmap
607
  im = axes[0,0].imshow(K, cmap='coolwarm', aspect='auto', vmin=-0.5, vmax=1)
608
  axes[0,0].set_title("Kinship Matrix")
609
  plt.colorbar(im, ax=axes[0,0], label="Kinship")
610
 
611
- # Kinship distribution
612
  K_flat = K[np.triu_indices_from(K, k=1)]
613
  axes[0,1].hist(K_flat, bins=30, color=ACCENT_LAV, edgecolor='white')
614
  axes[0,1].set_xlabel("Kinship Coefficient")
615
  axes[0,1].set_ylabel("Frequency")
616
  axes[0,1].set_title("Pairwise Kinship Distribution")
617
 
618
- # Hierarchical clustering
619
  linkage_matrix = linkage(K, method='average')
620
  dendrogram(linkage_matrix, ax=axes[1,0], labels=ids, leaf_rotation=90, leaf_font_size=8, color_threshold=0.7)
621
  axes[1,0].set_title("Sample Clustering Dendrogram")
622
  axes[1,0].set_ylabel("Distance")
623
 
624
- # PCA of kinship
625
  eigvals, eigvecs = np.linalg.eigh(K)
626
  idx = np.argsort(eigvals)[::-1]
627
  axes[1,1].scatter(eigvecs[:, idx[0]], eigvecs[:, idx[1]], c=ACCENT_MINT, s=60, edgecolors='white')
@@ -636,9 +679,7 @@ def plot_mds_analysis(G, y, ids):
636
  fig, axes = plt.subplots(1, 2, figsize=(14, 6))
637
  style_fig(fig)
638
 
639
- # MDS
640
  try:
641
- distances = pdist(G, metric='euclidean')
642
  mds = MDS(n_components=2, random_state=42, normalized_stress='auto')
643
  mds_coords = mds.fit_transform(G)
644
 
@@ -648,8 +689,8 @@ def plot_mds_analysis(G, y, ids):
648
  axes[0].set_title("Multi-Dimensional Scaling (MDS)")
649
  plt.colorbar(sc, ax=axes[0], label="Phenotype")
650
 
651
- # t-SNE
652
- tsne = TSNE(n_components=2, random_state=42, perplexity=min(30, len(G)-1))
653
  tsne_coords = tsne.fit_transform(G)
654
 
655
  sc2 = axes[1].scatter(tsne_coords[:, 0], tsne_coords[:, 1], c=y, cmap='coolwarm', s=60, edgecolors='white')
@@ -657,9 +698,9 @@ def plot_mds_analysis(G, y, ids):
657
  axes[1].set_ylabel("t-SNE Dimension 2")
658
  axes[1].set_title("t-SNE Visualization")
659
  plt.colorbar(sc2, ax=axes[1], label="Phenotype")
660
- except:
661
- axes[0].text(0.5, 0.5, "MDS computation failed\nInsufficient samples", ha='center', transform=axes[0].transAxes)
662
- axes[1].text(0.5, 0.5, "t-SNE computation failed\nInsufficient samples", ha='center', transform=axes[1].transAxes)
663
 
664
  fig.tight_layout()
665
  return fig
@@ -692,7 +733,6 @@ def plot_manhattan_qq_combined(pvals, chroms, positions):
692
  style_fig(fig)
693
  gs = fig.add_gridspec(2, 2, height_ratios=[2, 1])
694
 
695
- # Manhattan
696
  ax1 = fig.add_subplot(gs[0, :])
697
  log_p = -np.log10(np.clip(pvals, 1e-300, 1))
698
  ax1.scatter(range(len(pvals)), log_p, c=ACCENT_MINT, s=10, alpha=0.7)
@@ -702,7 +742,6 @@ def plot_manhattan_qq_combined(pvals, chroms, positions):
702
  ax1.set_title("Manhattan Plot")
703
  ax1.legend()
704
 
705
- # QQ
706
  ax2 = fig.add_subplot(gs[1, 0])
707
  n = len(pvals)
708
  obs = np.sort(-np.log10(np.clip(pvals, 1e-300, 1)))[::-1]
@@ -713,7 +752,6 @@ def plot_manhattan_qq_combined(pvals, chroms, positions):
713
  ax2.set_ylabel("Observed -log10(p)")
714
  ax2.set_title("QQ Plot")
715
 
716
- # Distribution
717
  ax3 = fig.add_subplot(gs[1, 1])
718
  ax3.hist(pvals, bins=50, color=ACCENT_MINT, edgecolor='white')
719
  ax3.axvline(0.05, color=ACCENT_PINK, ls='--', lw=1.5)
@@ -732,8 +770,6 @@ def plot_manhattan_stacked(pvals, chroms, positions):
732
  unique_chroms = sorted(set(chroms))
733
 
734
  y_offset = 0
735
- y_max = log_p.max()
736
-
737
  for ch in unique_chroms:
738
  mask = chroms == ch
739
  if mask.sum() > 0:
@@ -755,7 +791,6 @@ def plot_correlation_heatmap(G, y):
755
  fig, axes = plt.subplots(1, 2, figsize=(14, 6))
756
  style_fig(fig)
757
 
758
- # Genotype correlation
759
  n_snp = min(50, G.shape[1])
760
  corr_mat = np.corrcoef(G[:, :n_snp].T)
761
 
@@ -765,7 +800,6 @@ def plot_correlation_heatmap(G, y):
765
  axes[0].set_ylabel("SNP Index")
766
  plt.colorbar(im, ax=axes[0], label="Correlation")
767
 
768
- # Phenotype correlation with top SNPs
769
  pvals_adj = -np.log10(np.clip(np.corrcoef(G.T, y)[:-1, -1]**2, 1e-300, 1))
770
  top_idx = np.argsort(pvals_adj)[-20:]
771
  top_corr = np.corrcoef(G[:, top_idx].T)
@@ -784,44 +818,61 @@ def plot_summary_dashboard(y, maf, pvals, betas, G):
784
  style_fig(fig)
785
  axes = axes.flatten()
786
 
787
- # Phenotype stats
788
  axes[0].boxplot(y)
789
  axes[0].set_title(f"Phenotype\nn={len(y)}, mean={y.mean():.2f}")
790
  axes[0].set_ylabel("Value")
791
 
792
- # MAF stats
793
  axes[1].hist(maf, bins=20, color=ACCENT_MINT, edgecolor='white')
794
  axes[1].axvline(0.05, color=ACCENT_PINK, ls='--')
795
  axes[1].set_title(f"MAF\nrare={np.sum(maf<0.05)}")
796
  axes[1].set_xlabel("MAF")
797
 
798
- # P-value stats
799
  log_p = -np.log10(np.clip(pvals, 1e-300, 1))
800
  axes[2].hist(log_p, bins=30, color=ACCENT_LAV, edgecolor='white')
801
  axes[2].axvline(-np.log10(0.05/len(pvals)), color=ACCENT_PINK, ls='--')
802
  axes[2].set_title(f"P-values\nsig={np.sum(pvals < 0.05/len(pvals))}")
803
  axes[2].set_xlabel("-log10(p)")
804
 
805
- # Effect size stats
806
  axes[3].hist(betas, bins=30, color=ACCENT_PEACH, edgecolor='white')
807
  axes[3].axvline(0, color=ACCENT_PINK, ls='--')
808
  axes[3].set_title(f"Effect Sizes\nmean={np.mean(betas):.4f}")
809
  axes[3].set_xlabel("Ξ²")
810
 
811
- # Missing rate
812
  miss_rate = np.isnan(G).mean()
813
  axes[4].bar(['Complete', 'Missing'], [1-miss_rate, miss_rate], color=[ACCENT_MINT, ACCENT_PINK])
814
  axes[4].set_title(f"Data Completeness\n{1-miss_rate:.1%}")
815
  axes[4].set_ylabel("Proportion")
816
 
817
- # Sample size info
818
- 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: {np.median(stats.chi2.ppf(1-pvals, df=1))/0.455:.3f}",
819
  ha='center', va='center', transform=axes[5].transAxes)
820
  axes[5].set_title("Quick Stats")
821
 
822
  fig.tight_layout()
823
  return fig
824
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
825
  # ─────────────────────────── MAIN PIPELINE ────────────────────────────
826
 
827
  def run_gwas(file_obj, text_input, selected_models, maf_threshold):
@@ -844,19 +895,19 @@ def run_gwas(file_obj, text_input, selected_models, maf_threshold):
844
 
845
  G_filt = G[:, keep]
846
  snp_filt = np.array(snp_cols)[keep]
847
- chr_filt = chroms[keep] if len(chroms) == m else chroms
848
- pos_filt = positions[keep] if len(positions) == m else positions
849
-
850
- if len(chr_filt) != G_filt.shape[1]:
851
- chr_filt = np.ones(G_filt.shape[1])
852
- pos_filt = np.arange(G_filt.shape[1])
853
 
854
  K = build_kinship(G_filt)
855
 
 
856
  model_funcs = {
857
  "OLS": lambda: ols_gwas(y, G_filt),
858
  "MLM": lambda: mlm_gwas(y, G_filt, K),
859
  "GLM": lambda: glm_gwas(y, G_filt),
 
 
 
860
  }
861
 
862
  models_to_run = selected_models if selected_models else list(model_funcs.keys())
@@ -875,74 +926,64 @@ def run_gwas(file_obj, text_input, selected_models, maf_threshold):
875
  if primary_p is None:
876
  return [None] * 18 + ["❌ No models selected"]
877
 
878
- # Generate all 15+ plots
879
  plots = []
880
-
881
- # 1. Manhattan Plot
882
- plots.append(plot_manhattan(primary_p, chr_filt, pos_filt, "Manhattan Plot"))
883
- # 2. QQ Plot
884
- plots.append(plot_qq(primary_p, "QQ Plot"))
885
- # 3. PCA Analysis
886
  plots.append(plot_pca(G_filt, y, ids))
887
- # 4. Phenotype Distribution
888
  plots.append(plot_phenotype_distribution(y, ids))
889
- # 5. MAF Analysis
890
  plots.append(plot_maf_analysis(maf_vals, snp_cols))
891
- # 6. LD Analysis
892
  plots.append(plot_ld_analysis(G_filt, pos_filt, chr_filt))
893
- # 7. Effect Sizes
894
  plots.append(plot_effect_sizes(primary_p, primary_b, snp_filt))
895
- # 8. Heterozygosity
896
  plots.append(plot_heterozygosity(G_filt, y, ids))
897
- # 9. Call Rate Analysis
898
  plots.append(plot_call_rate_analysis(G_filt, snp_filt))
899
- # 10. Kinship Analysis
900
  plots.append(plot_kinship_analysis(K, ids))
901
- # 11. MDS/t-SNE
902
  plots.append(plot_mds_analysis(G_filt, y, ids))
903
- # 12. Manhattan by Chromosome
904
  plots.append(plot_manhattan_by_chromosome(primary_p, chr_filt, pos_filt))
905
- # 13. Combined Manhattan + QQ
906
  plots.append(plot_manhattan_qq_combined(primary_p, chr_filt, pos_filt))
907
- # 14. Stacked Manhattan
908
  plots.append(plot_manhattan_stacked(primary_p, chr_filt, pos_filt))
909
- # 15. Correlation Heatmap
910
  plots.append(plot_correlation_heatmap(G_filt, y))
911
- # 16. Summary Dashboard
912
  plots.append(plot_summary_dashboard(y, maf_vals, primary_p, primary_b, G_filt))
913
 
914
- # Convert to PIL images
915
- img_plots = [fig_to_pil(fig) for fig in plots]
 
 
 
 
 
916
  plt.close('all')
917
 
918
  # Results table
919
  bonf = 0.05 / len(primary_p)
920
  res_df = pd.DataFrame({
921
- "SNP": snp_filt,
922
- "Chr": chr_filt,
923
- "Pos": pos_filt,
924
- "Beta": np.round(primary_b, 5),
925
- "P_value": primary_p,
926
- "-log10P": np.round(-np.log10(np.clip(primary_p, 1e-300, 1)), 4),
927
- "Sig": ["***" if p < bonf else ("**" if p < 0.001 else ("*" if p < 0.05 else "")) for p in primary_p],
928
  }).sort_values("P_value").head(20)
929
 
930
  lam = np.median(stats.chi2.ppf(1 - np.clip(primary_p, 1e-10, 1), df=1)) / stats.chi2.ppf(0.5, df=1)
931
 
932
  summary = f"""
933
  ╔══════════════════════════════════════════════════════════════════╗
934
- β•‘ 🌸 GWAS ANALYSIS SUMMARY 🌸 β•‘
935
  ╠══════════════════════════════════════════════════════════════════╣
936
  β•‘ Samples: {n} β•‘
937
  β•‘ SNPs (raw): {m} β•‘
938
  β•‘ SNPs (MAFβ‰₯{maf_thr:.2f}): {G_filt.shape[1]} β•‘
939
- β•‘ Models: {', '.join(all_results.keys())} β•‘
940
  β•‘ β•‘
941
- β•‘ Bonferroni: {bonf:.2e} β•‘
 
 
 
 
942
  β•‘ Significant SNPs: {(primary_p < bonf).sum()} β•‘
943
  β•‘ Genomic Inflation Ξ»: {lam:.4f} β•‘
944
  β•‘ β•‘
945
- β•‘ Top 5 SNPs: β•‘
946
  {res_df[['SNP', 'Beta', 'P_value']].head(5).to_string(index=False)}
947
  β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•
948
  """
@@ -957,7 +998,12 @@ IRRI-1,25.34,0,0,0,2
957
  IRRI-75,23.34,0,0,0,0
958
  IRRI-84,26.67,2,0,2,0
959
  IRRI-93,23,0,0,0,1
960
- IRRI-9,28.34,0,0,0,0"""
 
 
 
 
 
961
 
962
  PASTEL_CSS = """
963
  body, .gradio-container { background: #F9F5F0 !important; font-family: 'Inter', sans-serif !important; }
@@ -966,43 +1012,44 @@ h1, h2, h3 { color: #E8A2A2 !important; }
966
  .gr-button-primary { background: linear-gradient(135deg, #E8A2A2, #C9B6E4) !important; border-radius: 40px !important; }
967
  """
968
 
969
- MODELS = ["OLS", "MLM", "GLM"]
970
 
971
- with gr.Blocks(css=PASTEL_CSS, title="🌸 Complete GWAS Pipeline", theme=gr.themes.Soft()) as demo:
972
  gr.Markdown("""
973
  # 🌸 Complete GWAS Analysis Pipeline
974
- ### 15+ Visualization Types Β· Full Statistical Suite Β· Chromosome Row Support
975
  """)
976
 
977
  with gr.Row():
978
  with gr.Column(scale=1):
979
  file_in = gr.File(label="Upload CSV/TSV", file_types=[".csv", ".tsv", ".txt"])
980
  text_in = gr.Textbox(label="Or paste CSV", lines=8, value=SAMPLE_DATA)
981
- model_sel = gr.CheckboxGroup(choices=MODELS, value=MODELS, label="Models")
982
  maf_thr = gr.Slider(0, 0.5, 0.05, 0.01, label="MAF Threshold")
983
- run_btn = gr.Button("πŸš€ Run Complete GWAS", variant="primary")
984
 
985
  with gr.Column(scale=2):
986
- summary_out = gr.Textbox(label="Summary", lines=15)
987
 
988
  with gr.Tabs():
989
- with gr.Tab("πŸ“Š Manhattan"): img1 = gr.Image(type="pil")
990
- with gr.Tab("πŸ“ˆ QQ Plot"): img2 = gr.Image(type="pil")
991
- with gr.Tab("πŸ”¬ PCA"): img3 = gr.Image(type="pil")
992
- with gr.Tab("πŸ“‰ Phenotype"): img4 = gr.Image(type="pil")
993
- with gr.Tab("🧬 MAF"): img5 = gr.Image(type="pil")
994
- with gr.Tab("πŸ”— LD"): img6 = gr.Image(type="pil")
995
- with gr.Tab("βš– Effect"): img7 = gr.Image(type="pil")
996
- with gr.Tab("🧬 Heterozygosity"): img8 = gr.Image(type="pil")
997
- with gr.Tab("πŸ“ž Call Rate"): img9 = gr.Image(type="pil")
998
- with gr.Tab("πŸ‘¨β€πŸ‘©β€πŸ‘§ Kinship"): img10 = gr.Image(type="pil")
999
- with gr.Tab("🎨 MDS/t-SNE"): img11 = gr.Image(type="pil")
1000
- with gr.Tab("πŸ“Š By Chr"): img12 = gr.Image(type="pil")
1001
- with gr.Tab("πŸ“‹ Combined"): img13 = gr.Image(type="pil")
1002
- with gr.Tab("πŸ” Stacked"): img14 = gr.Image(type="pil")
1003
- with gr.Tab("πŸ”₯ Heatmap"): img15 = gr.Image(type="pil")
1004
- with gr.Tab("πŸ“Š Dashboard"): img16 = gr.Image(type="pil")
1005
- with gr.Tab("πŸ“‹ Results Table"): results_tbl = gr.Dataframe()
 
1006
 
1007
  def run_wrapper(f, t, m, maf):
1008
  out = run_gwas(f, t, m, maf)
@@ -1011,7 +1058,7 @@ with gr.Blocks(css=PASTEL_CSS, title="🌸 Complete GWAS Pipeline", theme=gr.the
1011
  return out
1012
 
1013
  run_btn.click(run_wrapper, [file_in, text_in, model_sel, maf_thr],
1014
- [img1, img2, img3, img4, img5, img6, img7, img8, img9, img10, img11, img12, img13, img14, img15, img16, results_tbl, summary_out])
1015
 
1016
  if __name__ == "__main__":
1017
  demo.launch(share=False, server_port=7860)
 
1
+
 
 
 
 
 
2
 
3
  import gradio as gr
4
  import pandas as pd
 
70
  raise ValueError("No data provided.")
71
 
72
  # Check if second row contains chromosome info
 
 
 
73
  has_chrom_row = False
74
  chrom_info = {}
75
 
76
+ if len(raw) > 1:
77
+ second_row = raw.iloc[1].astype(str)
78
  chrom_vals = second_row.iloc[2:].astype(str)
79
+ if len(chrom_vals) > 0 and chrom_vals.str.match(r'^\d+$').all():
80
  has_chrom_row = True
81
  for i, col in enumerate(raw.columns[2:]):
82
+ try:
83
+ chrom_info[col] = int(second_row.iloc[2 + i])
84
+ except:
85
+ chrom_info[col] = 1
86
  raw = raw.drop(index=1).reset_index(drop=True)
87
 
88
  cols = list(raw.columns)
 
96
 
97
  # Replace missing codes
98
  geno = raw[snp_cols].apply(pd.to_numeric, errors="coerce")
99
+ geno = geno.where(~geno.isin([-1, -9, -99, -999]), np.nan)
100
 
101
  df = pd.DataFrame()
102
  df["ID"] = raw[id_col].values
 
104
  for c in snp_cols:
105
  df[c] = geno[c].values
106
 
107
+ # Parse chromosome and position
108
  chroms, positions = [], []
109
  for m in snp_cols:
110
  if m in chrom_info:
111
  chroms.append(chrom_info[m])
112
+ positions.append(1) # Default position if not provided
113
  else:
114
  m_clean = str(m).strip()
115
  mat = re.match(r"[Cc]hr(\d+)[_\-](\d+)", m_clean)
 
123
 
124
  return df, snp_cols, np.array(chroms), np.array(positions)
125
 
126
+ # ─────────────────────────── STATISTICAL MODELS (6 MODELS) ───────────────────────
127
 
128
  def impute_genotypes(geno_matrix):
129
  mat = geno_matrix.copy().astype(float)
 
140
  return maf
141
 
142
  def compute_heterozygosity(G):
 
143
  return np.mean(G == 1, axis=1) if G.shape[1] > 0 else np.zeros(G.shape[0])
144
 
145
  def compute_call_rate(G):
 
146
  return 1 - np.isnan(G).mean(axis=0)
147
 
148
  def build_kinship(G):
 
154
  K = Z @ Z.T / denom
155
  return K
156
 
157
+ # Model 1: OLS (Simple Linear Regression)
158
  def ols_gwas(y, G):
159
  n, m = G.shape
160
  pvals = np.ones(m)
 
169
  betas[j] = slope
170
  return pvals, betas
171
 
172
+ # Model 2: MLM (Mixed Linear Model)
173
  def mlm_gwas(y, G, K):
174
  n, m = G.shape
175
  pvals = np.ones(m)
 
190
  betas[j] = slope
191
  return pvals, betas
192
 
193
+ # Model 3: GLM (PCA-corrected General Linear Model)
194
  def glm_gwas(y, G):
195
  n, m = G.shape
196
  pvals = np.ones(m)
197
  betas = np.zeros(m)
198
  scaler = StandardScaler()
199
  G_sc = scaler.fit_transform(G)
200
+ n_pcs = min(3, n - 2)
201
+ pca = PCA(n_components=n_pcs)
202
  PCs = pca.fit_transform(G_sc)
203
  reg = LinearRegression().fit(PCs, y)
204
  y_adj = y - reg.predict(PCs)
 
212
  betas[j] = slope
213
  return pvals, betas
214
 
215
+ # Model 4: Compressed MLM (CMLM)
216
+ def cmlm_gwas(y, G, K):
217
+ n, m = G.shape
218
+ pvals = np.ones(m)
219
+ betas = np.zeros(m)
220
+ # Create groups based on kinship
221
+ n_groups = min(3, n)
222
+ groups = np.array([i % n_groups for i in range(n)])
223
+ group_means = np.zeros((n, n_groups))
224
+ for g in range(n_groups):
225
+ idx = np.where(groups == g)[0]
226
+ if len(idx) > 0:
227
+ group_means[:, g] = K[:, idx].mean(axis=1)
228
+ reg = LinearRegression().fit(group_means, y)
229
+ y_res = y - reg.predict(group_means)
230
+ for j in range(m):
231
+ x = G[:, j]
232
+ x_res = x - LinearRegression().fit(group_means, x).predict(group_means)
233
+ if x_res.std() < 1e-8:
234
+ continue
235
+ slope, intercept, r, p, se = stats.linregress(x_res, y_res)
236
+ pvals[j] = p
237
+ betas[j] = slope
238
+ return pvals, betas
239
+
240
+ # Model 5: BLINK (Bayesian Linear Mixed Model with Iterative Kinship)
241
+ def blink_gwas(y, G):
242
+ n, m = G.shape
243
+ pvals = np.ones(m)
244
+ betas = np.zeros(m)
245
+ # First pass OLS
246
+ ols_p, ols_b = ols_gwas(y, G)
247
+ # Select top associated SNPs as covariates
248
+ n_cov = min(3, m)
249
+ top_idx = np.argsort(ols_p)[:n_cov]
250
+ if len(top_idx) > 0:
251
+ covars = G[:, top_idx]
252
+ reg = LinearRegression().fit(covars, y)
253
+ y_adj = y - reg.predict(covars)
254
+ else:
255
+ y_adj = y
256
+ # Second pass with covariates
257
+ for j in range(m):
258
+ x = G[:, j]
259
+ if x.std() < 1e-8:
260
+ continue
261
+ slope, intercept, r, p, se = stats.linregress(x, y_adj)
262
+ pvals[j] = p
263
+ betas[j] = slope
264
+ return pvals, betas
265
+
266
+ # Model 6: FarmCPU (Fixed and random model Circulating Probability Unification)
267
+ def farmcpu_gwas(y, G, K):
268
+ n, m = G.shape
269
+ pvals = np.ones(m)
270
+ betas = np.zeros(m)
271
+ # Step 1: MLM
272
+ mlm_p, mlm_b = mlm_gwas(y, G, K)
273
+ # Step 2: Identify pseudo-QTNs
274
+ n_qtns = min(3, m)
275
+ qtn_idx = np.argsort(mlm_p)[:n_qtns]
276
+ # Step 3: Fixed effect model with QTNs
277
+ if len(qtn_idx) > 0:
278
+ qtns = G[:, qtn_idx]
279
+ reg = LinearRegression().fit(qtns, y)
280
+ y_adj = y - reg.predict(qtns)
281
+ else:
282
+ y_adj = y
283
+ # Step 4: Final association
284
+ for j in range(m):
285
+ x = G[:, j]
286
+ if x.std() < 1e-8:
287
+ continue
288
+ slope, intercept, r, p, se = stats.linregress(x, y_adj)
289
+ pvals[j] = p
290
+ betas[j] = slope
291
+ return pvals, betas
292
+
293
+ # ─────────────────────────── 16+ PLOTTING FUNCTIONS ───────────────────
294
 
295
  def fig_to_pil(fig):
296
  buf = io.BytesIO()
 
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
 
315
  for ch in chrom_list:
316
  mask = chroms == ch
317
  pos = positions[mask]
318
+ if len(pos) == 0:
319
+ continue
320
  order = np.argsort(pos)
321
  x_vals = pos[order] - pos.min() + x_offset
322
  x_coords[np.where(mask)[0][order]] = x_vals
 
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)")
 
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}%)")
 
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")
 
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}%)")
 
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")
 
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)
 
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)
 
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")
 
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])
 
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()
 
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):
 
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):
 
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)
 
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]
 
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))
 
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)")
 
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)))
 
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]
 
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")
 
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)
 
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()
 
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')
 
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
 
 
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')
 
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
 
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)
 
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]
 
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)
 
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:
 
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
 
 
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)
 
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
875
+
876
  # ─────────────────────────── MAIN PIPELINE ────────────────────────────
877
 
878
  def run_gwas(file_obj, text_input, selected_models, maf_threshold):
 
895
 
896
  G_filt = G[:, keep]
897
  snp_filt = np.array(snp_cols)[keep]
898
+ chr_filt = chroms[keep] if len(chroms) == m else np.ones(G_filt.shape[1])
899
+ pos_filt = positions[keep] if len(positions) == m else np.arange(G_filt.shape[1])
 
 
 
 
900
 
901
  K = build_kinship(G_filt)
902
 
903
+ # All 6 statistical models
904
  model_funcs = {
905
  "OLS": lambda: ols_gwas(y, G_filt),
906
  "MLM": lambda: mlm_gwas(y, G_filt, K),
907
  "GLM": lambda: glm_gwas(y, G_filt),
908
+ "CMLM": lambda: cmlm_gwas(y, G_filt, K),
909
+ "BLINK": lambda: blink_gwas(y, G_filt),
910
+ "FarmCPU": lambda: farmcpu_gwas(y, G_filt, K),
911
  }
912
 
913
  models_to_run = selected_models if selected_models else list(model_funcs.keys())
 
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
949
+ if len(all_results) > 1:
950
+ plots.append(plot_model_comparison(all_results))
951
+ else:
952
+ plots.append(None)
953
+
954
+ img_plots = [fig_to_pil(fig) if fig is not None else None for fig in plots]
955
  plt.close('all')
956
 
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
 
970
  summary = f"""
971
  ╔══════════════════════════════════════════════════════════════════╗
972
+ β•‘ 🌸 COMPLETE GWAS ANALYSIS SUMMARY 🌸 β•‘
973
  ╠══════════════════════════════════════════════════════════════════╣
974
  β•‘ Samples: {n} β•‘
975
  β•‘ SNPs (raw): {m} β•‘
976
  β•‘ SNPs (MAFβ‰₯{maf_thr:.2f}): {G_filt.shape[1]} β•‘
 
977
  β•‘ β•‘
978
+ β•‘ MODELS RUN ({len(all_results)}): β•‘
979
+ β•‘ {', '.join(all_results.keys())} β•‘
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
  """
 
998
  IRRI-75,23.34,0,0,0,0
999
  IRRI-84,26.67,2,0,2,0
1000
  IRRI-93,23,0,0,0,1
1001
+ IRRI-9,28.34,0,0,0,0
1002
+ IRRI-17,18.67,0,0,0,0
1003
+ IRRI-25,20,2,0,2,0
1004
+ 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; }
 
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)
 
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)