softwareDevelopment commited on
Commit
e454c67
Β·
verified Β·
1 Parent(s): 1499e47

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +381 -540
app.py CHANGED
@@ -192,221 +192,385 @@ def fig_to_pil(fig):
192
  from PIL import Image
193
  return Image.open(buf).copy()
194
 
195
- # ─────────────────────── 10 STATISTICAL MODELS ───────────────────────────────────
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196
  def ols_gwas(y, G):
197
  n, m = G.shape
198
  pvals = np.ones(m); betas = np.zeros(m); ses = np.zeros(m)
199
  for j in range(m):
200
- x = G[:, j] - G[:, j].mean()
201
- if x.std() < 1e-8: continue
202
- slope, _, _, p, se = stats.linregress(x, y)
203
- pvals[j] = p; betas[j] = slope; ses[j] = se
 
 
 
 
 
 
 
 
 
204
  return pvals, betas, ses
205
 
206
  def mlm_gwas(y, G, K):
207
  n, m = G.shape
208
  pvals = np.ones(m); betas = np.zeros(m); ses = np.zeros(m)
209
- eigvals, eigvecs = np.linalg.eigh(K + np.eye(n) * 1e-6)
210
- n_pcs = min(3, n - 2)
211
- Q = eigvecs[:, np.argsort(eigvals)[::-1][:n_pcs]]
212
- y_res = y - LinearRegression().fit(Q, y).predict(Q)
213
- for j in range(m):
214
- x = G[:, j]
215
- x_res = x - LinearRegression().fit(Q, x).predict(Q)
216
- if x_res.std() < 1e-8: continue
217
- slope, _, _, p, se = stats.linregress(x_res, y_res)
218
- pvals[j] = p; betas[j] = slope; ses[j] = se
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
219
  return pvals, betas, ses
220
 
221
  def glm_gwas(y, G):
222
  n, m = G.shape
223
  pvals = np.ones(m); betas = np.zeros(m); ses = np.zeros(m)
224
- n_pcs = min(3, n - 2)
225
  try:
226
- PCs = PCA(n_components=n_pcs).fit_transform(StandardScaler().fit_transform(G))
 
 
227
  y_adj = y - LinearRegression().fit(PCs, y).predict(PCs)
228
- except Exception:
229
- y_adj = y - y.mean()
230
- PCs = np.zeros((n, 1))
231
- for j in range(m):
232
- x = G[:, j]
233
- if x.std() < 1e-8: continue
234
- try:
235
- x_adj = x - LinearRegression().fit(PCs, x).predict(PCs)
236
- except Exception:
237
- x_adj = x - x.mean()
238
- slope, _, _, p, se = stats.linregress(x_adj, y_adj)
239
- pvals[j] = p; betas[j] = slope; ses[j] = se
 
 
 
 
 
 
 
 
240
  return pvals, betas, ses
241
 
242
  def cmlm_gwas(y, G, K):
243
  n, m = G.shape
244
  pvals = np.ones(m); betas = np.zeros(m); ses = np.zeros(m)
245
- n_groups = min(3, n)
246
- groups = np.array([i % n_groups for i in range(n)])
247
- group_means = np.column_stack([K[:, np.where(groups == g)[0]].mean(axis=1) for g in range(n_groups)])
248
  try:
 
 
 
 
 
 
 
 
249
  y_res = y - LinearRegression().fit(group_means, y).predict(group_means)
250
- except Exception:
251
- y_res = y - y.mean()
252
- for j in range(m):
253
- x = G[:, j]
254
- try:
255
- x_res = x - LinearRegression().fit(group_means, x).predict(group_means)
256
- except Exception:
257
- x_res = x - x.mean()
258
- if x_res.std() < 1e-8: continue
259
- slope, _, _, p, se = stats.linregress(x_res, y_res)
260
- pvals[j] = p; betas[j] = slope; ses[j] = se
 
 
 
 
 
 
 
 
 
261
  return pvals, betas, ses
262
 
263
  def blink_gwas(y, G):
264
  n, m = G.shape
265
  pvals = np.ones(m); betas = np.zeros(m); ses = np.zeros(m)
266
- ols_p, _, _ = ols_gwas(y, G)
267
- top_idx = np.argsort(ols_p)[:min(3, m)]
268
- covars = G[:, top_idx]
269
  try:
 
 
 
 
270
  y_adj = y - LinearRegression().fit(covars, y).predict(covars)
271
- except Exception:
272
- y_adj = y - y.mean()
273
- for j in range(m):
274
- x = G[:, j]
275
- if x.std() < 1e-8: continue
276
- slope, _, _, p, se = stats.linregress(x, y_adj)
277
- pvals[j] = p; betas[j] = slope; ses[j] = se
 
 
 
 
 
 
 
 
 
 
 
278
  return pvals, betas, ses
279
 
280
  def farmcpu_gwas(y, G, K):
281
  n, m = G.shape
282
  pvals = np.ones(m); betas = np.zeros(m); ses = np.zeros(m)
283
- mlm_p, _, _ = mlm_gwas(y, G, K)
284
- qtn_idx = np.argsort(mlm_p)[:min(3, m)]
285
- qtns = G[:, qtn_idx]
286
  try:
 
 
 
 
287
  y_adj = y - LinearRegression().fit(qtns, y).predict(qtns)
288
- except Exception:
289
- y_adj = y - y.mean()
290
- for j in range(m):
291
- x = G[:, j]
292
- if x.std() < 1e-8: continue
293
- slope, _, _, p, se = stats.linregress(x, y_adj)
294
- pvals[j] = p; betas[j] = slope; ses[j] = se
 
 
 
 
 
 
 
 
 
 
 
295
  return pvals, betas, ses
296
 
297
  def emmax_gwas(y, G, K):
298
  n, m = G.shape
299
  pvals = np.ones(m); betas = np.zeros(m); ses = np.zeros(m)
300
- tau = np.var(y) * 0.5
301
- sigma = np.var(y) * 0.5
302
- V = tau * K + sigma * np.eye(n)
303
  try:
 
 
 
304
  V_inv = np.linalg.inv(V + np.eye(n) * 1e-6)
305
- except Exception:
306
- V_inv = np.eye(n)
307
- for j in range(m):
308
- x = G[:, j].reshape(-1, 1)
309
- try:
310
- Px = V_inv @ x
311
- beta = (x.T @ Px @ y) / (x.T @ Px @ x + 1e-10)
312
- betas[j] = float(beta)
313
- resid = y - float(beta) * x.flatten()
314
- sigma_e = (resid @ V_inv @ resid) / (n - 2 + 1e-10)
315
- se = np.sqrt(float(sigma_e / (x.T @ Px @ x + 1e-10)))
316
- ses[j] = se
317
- t_stat = float(beta) / (se + 1e-10)
318
- pvals[j] = float(2 * stats.t.sf(abs(t_stat), df=n-2))
319
- except Exception:
320
- pass
 
 
 
 
 
 
 
 
 
321
  return pvals, betas, ses
322
 
323
  def plink_gwas(y, G):
324
  n, m = G.shape
325
  pvals = np.ones(m); betas = np.zeros(m); ses = np.zeros(m)
326
- y_bin = (y > np.median(y)).astype(float)
327
- for j in range(m):
328
- x = G[:, j]
329
- if x.std() < 1e-8: continue
330
- try:
331
- ct = np.zeros((2, 3))
332
- for g in [0, 1, 2]:
333
- mask = x == g
334
- ct[0, g] = np.sum(y_bin[mask])
335
- ct[1, g] = np.sum(1 - y_bin[mask])
336
- if ct.sum() > 4:
337
- chi2, p, _, _ = stats.chi2_contingency(ct + 0.5)
338
- pvals[j] = p
339
- slope, _, _, p2, se = stats.linregress(x, y_bin)
340
- betas[j] = slope; ses[j] = se
341
- except Exception:
342
- pass
 
 
 
 
 
 
 
 
343
  return pvals, betas, ses
344
 
345
  def gapit3_gwas(y, G, K):
346
  n, m = G.shape
347
  pvals = np.ones(m); betas = np.zeros(m); ses = np.zeros(m)
348
- n_pcs = min(3, n - 2)
349
  try:
350
- PCs = PCA(n_components=n_pcs).fit_transform(StandardScaler().fit_transform(G))
351
- except Exception:
352
- PCs = np.zeros((n, 1))
353
- eigvals, eigvecs = np.linalg.eigh(K + np.eye(n) * 1e-6)
354
- Q = eigvecs[:, np.argsort(eigvals)[::-1][:n_pcs]]
355
- covars = np.hstack([PCs, Q])
356
- qtns = []
357
- for iteration in range(2):
358
- for j in range(m):
359
- x = G[:, j]
360
- if x.std() < 1e-8: continue
361
- try:
362
- if len(qtns) > 0:
363
- cov = np.column_stack([covars] + [G[:, q].reshape(-1,1) for q in qtns])
364
- else:
365
- cov = covars
366
- x_res = x - LinearRegression().fit(cov, x).predict(cov)
367
- y_res = y - LinearRegression().fit(cov, y).predict(cov)
368
- slope, _, _, p, se = stats.linregress(x_res, y_res)
369
- pvals[j] = p; betas[j] = slope; ses[j] = se
370
- except Exception:
371
- pass
372
- new_qtns = list(np.where(pvals < 0.05 / m)[0][:2])
373
- if new_qtns and new_qtns != qtns:
374
- qtns = new_qtns
375
- else:
376
- break
 
 
 
 
 
 
 
 
 
 
 
 
 
 
377
  return pvals, betas, ses
378
 
379
  def gemma_gwas(y, G, K):
380
  n, m = G.shape
381
  pvals = np.ones(m); betas = np.zeros(m); ses = np.zeros(m)
382
- row_mean = K.mean(axis=1, keepdims=True)
383
- col_mean = K.mean(axis=0, keepdims=True)
384
- grand_mean = K.mean()
385
- Kc = K - row_mean - col_mean + grand_mean
386
- eigvals, eigvecs = np.linalg.eigh(Kc + np.eye(n) * 1e-6)
387
- idx = np.argsort(eigvals)[::-1]
388
- n_pcs = min(4, n - 2)
389
- Q = eigvecs[:, idx[:n_pcs]]
390
  try:
 
 
 
 
 
 
 
 
 
 
 
391
  y_res = y - LinearRegression().fit(Q, y).predict(Q)
392
- except Exception:
393
- y_res = y - y.mean()
394
- for j in range(m):
395
- x = G[:, j]
396
- try:
397
- x_res = x - LinearRegression().fit(Q, x).predict(Q)
398
- except Exception:
399
- x_res = x - x.mean()
400
- if x_res.std() < 1e-8: continue
401
- slope, _, _, p, se = stats.linregress(x_res, y_res)
402
- pvals[j] = p; betas[j] = slope; ses[j] = se
403
- lam = np.median(stats.chi2.ppf(1 - np.clip(pvals, 1e-10, 1), df=1)) / stats.chi2.ppf(0.5, df=1)
404
- if lam > 1.05:
405
- chi2_vals = stats.chi2.ppf(1 - pvals, df=1) / lam
406
- pvals = 1 - stats.chi2.cdf(np.clip(chi2_vals, 0, 1e10), df=1)
 
 
 
 
 
 
 
 
 
 
 
407
  return pvals, betas, ses
408
 
409
- # ─────────────────────── PLOTS (WHITE BACKGROUND) ────────────────────────────────
410
  def plot_manhattan(pvals, chroms, positions, title="Manhattan Plot", model_name=""):
411
  fig, ax = plt.subplots(figsize=(16, 5), facecolor=BG_WHITE)
412
  ax.set_facecolor(PANEL_WHITE)
@@ -447,89 +611,6 @@ def plot_manhattan(pvals, chroms, positions, title="Manhattan Plot", model_name=
447
  fig.tight_layout()
448
  return fig
449
 
450
- def plot_qq_single(pvals, title="QQ Plot", model_name="", color=None):
451
- if color is None:
452
- color = ACCENT_PURP
453
- fig, ax = plt.subplots(figsize=(7, 7), facecolor=BG_WHITE)
454
- ax.set_facecolor(PANEL_WHITE)
455
- style_fig(fig)
456
-
457
- n = len(pvals)
458
- obs = np.sort(-np.log10(np.clip(pvals, 1e-300, 1)))[::-1]
459
- exp = -np.log10(np.linspace(1/n, 1, n)[::-1])
460
- ci_lower = -np.log10(stats.beta.ppf(0.975, np.arange(1, n+1), np.arange(n, 0, -1)))
461
- ci_upper = -np.log10(stats.beta.ppf(0.025, np.arange(1, n+1), np.arange(n, 0, -1)))
462
- ax.fill_between(exp, ci_lower, ci_upper, alpha=0.2, color=color, label="95% CI")
463
- ax.scatter(exp, obs, c=color, s=24, alpha=0.85, linewidths=0, zorder=5)
464
- ax.plot([0, max(exp)], [0, max(exp)], color=ACCENT_CORAL, ls="--", lw=2, label="Expected", zorder=6)
465
- lam = np.median(stats.chi2.ppf(1 - np.clip(pvals, 1e-10, 1), df=1)) / stats.chi2.ppf(0.5, df=1)
466
- ax.text(0.05, 0.93, f"Ξ» = {lam:.4f}", transform=ax.transAxes, fontsize=13,
467
- color=ACCENT_GOLD, fontweight='bold')
468
- ax.set_xlabel("Expected -log₁₀(p)", fontsize=10, color=TEXT_DIM)
469
- ax.set_ylabel("Observed -log₁₀(p)", fontsize=10, color=TEXT_DIM)
470
- ax.set_title(f"{title}{' β€” ' + model_name if model_name else ''}", color=TEXT_MAIN, fontsize=12)
471
- ax.legend(fontsize=9, framealpha=0.9, facecolor=BG_WHITE, edgecolor=GRID_LINE, labelcolor=TEXT_MAIN)
472
- fig.tight_layout()
473
- return fig
474
-
475
- def plot_qq_all_models(all_results):
476
- n_models = len(all_results)
477
- ncols = min(3, n_models)
478
- nrows = (n_models + ncols - 1) // ncols
479
- fig, axes = plt.subplots(nrows, ncols, figsize=(7 * ncols, 6 * nrows), facecolor=BG_WHITE)
480
- style_fig(fig)
481
- if n_models == 1:
482
- axes = np.array([axes])
483
- axes = np.array(axes).flatten()
484
- for idx, (mname, (pvals, _, _)) in enumerate(all_results.items()):
485
- ax = axes[idx]
486
- ax.set_facecolor(PANEL_WHITE)
487
- n = len(pvals)
488
- obs = np.sort(-np.log10(np.clip(pvals, 1e-300, 1)))[::-1]
489
- exp = -np.log10(np.linspace(1/n, 1, n)[::-1])
490
- ci_lo = -np.log10(stats.beta.ppf(0.975, np.arange(1, n+1), np.arange(n, 0, -1)))
491
- ci_hi = -np.log10(stats.beta.ppf(0.025, np.arange(1, n+1), np.arange(n, 0, -1)))
492
- col = MODEL_COLORS.get(mname, ACCENT_BLUE)
493
- ax.fill_between(exp, ci_lo, ci_hi, alpha=0.2, color=col)
494
- ax.scatter(exp, obs, c=col, s=18, alpha=0.85, linewidths=0)
495
- ax.plot([0, max(exp)], [0, max(exp)], color=ACCENT_CORAL, ls="--", lw=1.8, alpha=0.9)
496
- lam = np.median(stats.chi2.ppf(1 - np.clip(pvals, 1e-10, 1), df=1)) / stats.chi2.ppf(0.5, df=1)
497
- ax.text(0.05, 0.92, f"Ξ» = {lam:.4f}", transform=ax.transAxes, fontsize=10,
498
- color=ACCENT_GOLD, fontweight='bold')
499
- ax.set_xlabel("Expected -log₁₀(p)", fontsize=8, color=TEXT_DIM)
500
- ax.set_ylabel("Observed -log₁₀(p)", fontsize=8, color=TEXT_DIM)
501
- ax.set_title(f"QQ β€” {mname}", color=col, fontsize=10)
502
- for spine in ax.spines.values():
503
- spine.set_edgecolor(GRID_LINE)
504
- ax.grid(color=GRID_LINE, linewidth=0.5, linestyle="--", alpha=0.7)
505
- ax.tick_params(colors=TEXT_DIM, labelsize=8)
506
- for idx in range(n_models, len(axes)):
507
- axes[idx].set_visible(False)
508
- fig.suptitle("QQ Plots β€” All Models", color=TEXT_MAIN, fontsize=13, y=1.01)
509
- fig.tight_layout()
510
- return fig
511
-
512
- def plot_qq_overlay(all_results):
513
- fig, ax = plt.subplots(figsize=(9, 9), facecolor=BG_WHITE)
514
- ax.set_facecolor(PANEL_WHITE)
515
- style_fig(fig)
516
- exp_max = 0
517
- for mname, (pvals, _, _) in all_results.items():
518
- n = len(pvals)
519
- obs = np.sort(-np.log10(np.clip(pvals, 1e-300, 1)))[::-1]
520
- exp = -np.log10(np.linspace(1/n, 1, n)[::-1])
521
- exp_max = max(exp_max, max(exp))
522
- lam = np.median(stats.chi2.ppf(1 - np.clip(pvals, 1e-10, 1), df=1)) / stats.chi2.ppf(0.5, df=1)
523
- ax.plot(exp, obs, color=MODEL_COLORS.get(mname, ACCENT_BLUE),
524
- lw=2.2, label=f"{mname} (Ξ»={lam:.3f})", alpha=0.85)
525
- ax.plot([0, exp_max], [0, exp_max], color=ACCENT_CORAL, ls="--", lw=2, label="Expected")
526
- ax.set_xlabel("Expected -log₁₀(p)", fontsize=10, color=TEXT_DIM)
527
- ax.set_ylabel("Observed -log₁₀(p)", fontsize=10, color=TEXT_DIM)
528
- ax.set_title("QQ Plot β€” All Models Overlay", color=TEXT_MAIN, fontsize=12)
529
- ax.legend(fontsize=8, framealpha=0.9, facecolor=BG_WHITE, edgecolor=GRID_LINE, labelcolor=TEXT_MAIN)
530
- fig.tight_layout()
531
- return fig
532
-
533
  def plot_circos(all_results, chroms, positions):
534
  fig, ax = plt.subplots(figsize=(14, 14), subplot_kw=dict(projection='polar'), facecolor=BG_WHITE)
535
  ax.set_facecolor(BG_WHITE)
@@ -699,86 +780,6 @@ def plot_pca(G, y, ids):
699
  fig.tight_layout()
700
  return fig
701
 
702
- def plot_model_comparison_manhattan(all_results, chroms, positions):
703
- n_models = len(all_results)
704
- fig, axes = plt.subplots(n_models, 1, figsize=(16, 3.5 * n_models), sharex=True, facecolor=BG_WHITE)
705
- style_fig(fig)
706
- if n_models == 1:
707
- axes = [axes]
708
- chrom_list = sorted(set(chroms))
709
- total_len = 0
710
- chrom_offsets = {}
711
- for ch in chrom_list:
712
- chrom_offsets[ch] = total_len
713
- mask = chroms == ch
714
- if mask.sum() > 0:
715
- total_len += positions[mask].max() - positions[mask].min() + max(positions) * 0.02 + 1
716
- x_coords = np.zeros(len(chroms))
717
- for ch in chrom_list:
718
- mask = chroms == ch
719
- if mask.sum() > 0:
720
- x_coords[mask] = positions[mask] - positions[mask].min() + chrom_offsets[ch]
721
- tick_pos, tick_lab = [], []
722
- for ch in chrom_list:
723
- mask = chroms == ch
724
- if mask.sum() > 0:
725
- tick_pos.append(x_coords[mask].mean())
726
- tick_lab.append(f"Chr{ch}")
727
- for midx, (mname, (pvals, _, _)) in enumerate(all_results.items()):
728
- ax = axes[midx]
729
- ax.set_facecolor(PANEL_WHITE)
730
- log_p = -np.log10(np.clip(pvals, 1e-300, 1))
731
- col = MODEL_COLORS.get(mname, CHR_PALETTE[midx % len(CHR_PALETTE)])
732
- for ch in chrom_list:
733
- mask = chroms == ch
734
- ax.scatter(x_coords[mask], log_p[mask], c=col, s=8, alpha=0.7, linewidths=0)
735
- sig_m = log_p >= -np.log10(5e-8)
736
- if sig_m.any():
737
- ax.scatter(x_coords[sig_m], log_p[sig_m], c=SIG_COLOR, s=50, zorder=10,
738
- marker='D', linewidths=0.6, edgecolors='#7F1D1D')
739
- ax.axhline(-np.log10(5e-8), color=ACCENT_CORAL, ls='--', lw=1, alpha=0.7)
740
- ax.set_ylabel("-log₁₀(p)", fontsize=7, color=TEXT_DIM)
741
- ax.set_title(f"Model: {mname}", color=col, fontsize=9, pad=3)
742
- ax.set_xticks(tick_pos)
743
- ax.set_xticklabels(tick_lab if midx == n_models-1 else [], rotation=40, fontsize=7)
744
- ax.tick_params(colors=TEXT_DIM, labelsize=7)
745
- for spine in ax.spines.values():
746
- spine.set_edgecolor(GRID_LINE)
747
- ax.grid(color=GRID_LINE, linewidth=0.3, linestyle="--", alpha=0.5)
748
- fig.suptitle("Manhattan Plots β€” All Models Comparison", color=TEXT_MAIN, fontsize=13)
749
- fig.tight_layout(rect=[0, 0, 1, 0.98])
750
- return fig
751
-
752
- def plot_kinship(K, ids):
753
- fig, axes = plt.subplots(2, 2, figsize=(14, 12), facecolor=BG_WHITE)
754
- style_fig(fig)
755
- for ax in axes.flatten():
756
- ax.set_facecolor(PANEL_WHITE)
757
-
758
- im = axes[0,0].imshow(K, cmap='RdYlBu_r', aspect='auto', vmin=-0.5, vmax=1)
759
- axes[0,0].set_title("Kinship Matrix", color=TEXT_MAIN)
760
- plt.colorbar(im, ax=axes[0,0])
761
-
762
- K_flat = K[np.triu_indices_from(K, k=1)]
763
- axes[0,1].hist(K_flat, bins=30, color=ACCENT_PURP, edgecolor='none', alpha=0.8)
764
- axes[0,1].set_title("Pairwise Kinship Distribution", color=TEXT_MAIN)
765
-
766
- try:
767
- lm = linkage(K, method='average')
768
- dendrogram(lm, ax=axes[1,0], labels=ids, leaf_rotation=90, leaf_font_size=7,
769
- color_threshold=0.7, above_threshold_color=ACCENT_TEAL)
770
- except Exception:
771
- axes[1,0].text(0.5, 0.5, "Dendrogram unavailable", ha='center',
772
- transform=axes[1,0].transAxes, color=TEXT_DIM)
773
- axes[1,0].set_title("Clustering Dendrogram", color=TEXT_MAIN)
774
-
775
- eigvals, eigvecs = np.linalg.eigh(K)
776
- idx = np.argsort(eigvals)[::-1]
777
- axes[1,1].scatter(eigvecs[:,idx[0]], eigvecs[:,idx[1]], c=ACCENT_TEAL, s=60, edgecolors='none')
778
- axes[1,1].set_title("Kinship PCA", color=TEXT_MAIN)
779
- fig.tight_layout()
780
- return fig
781
-
782
  def plot_effect_sizes(pvals, betas, snp_names):
783
  fig, axes = plt.subplots(2, 2, figsize=(14, 10), facecolor=BG_WHITE)
784
  style_fig(fig)
@@ -888,68 +889,6 @@ def plot_summary_dashboard(y, maf, all_results, G_filt):
888
  fig.tight_layout()
889
  return fig
890
 
891
- # ─────────────────────── PER-MODEL PLOTS ─────────────────────────────────────────
892
- def plot_all_models_manhattan_grid(all_results, chroms, positions):
893
- """Grid of Manhattan plots, one per selected model."""
894
- n_models = len(all_results)
895
- ncols = min(2, n_models)
896
- nrows = (n_models + ncols - 1) // ncols
897
- fig, axes = plt.subplots(nrows, ncols, figsize=(16, 4 * nrows), facecolor=BG_WHITE)
898
- style_fig(fig)
899
- if n_models == 1:
900
- axes = np.array([axes])
901
- axes_flat = np.array(axes).flatten()
902
-
903
- chrom_list = sorted(set(chroms))
904
- chrom_offsets = {}
905
- total_len = 0
906
- for ch in chrom_list:
907
- chrom_offsets[ch] = total_len
908
- mask = chroms == ch
909
- if mask.sum() > 0:
910
- total_len += positions[mask].max() - positions[mask].min() + max(positions) * 0.02 + 1
911
- x_coords = np.zeros(len(chroms))
912
- for ch in chrom_list:
913
- mask = chroms == ch
914
- if mask.sum() > 0:
915
- x_coords[mask] = positions[mask] - positions[mask].min() + chrom_offsets[ch]
916
- tick_pos = [x_coords[chroms == ch].mean() for ch in chrom_list if (chroms == ch).sum() > 0]
917
- tick_lab = [f"Chr{ch}" for ch in chrom_list if (chroms == ch).sum() > 0]
918
-
919
- for midx, (mname, (pvals, _, _)) in enumerate(all_results.items()):
920
- ax = axes_flat[midx]
921
- ax.set_facecolor(PANEL_WHITE)
922
- log_p = -np.log10(np.clip(pvals, 1e-300, 1))
923
- col = MODEL_COLORS.get(mname, CHR_PALETTE[midx % len(CHR_PALETTE)])
924
- for ch in chrom_list:
925
- mask = chroms == ch
926
- ax.scatter(x_coords[mask], log_p[mask], c=col, s=10, alpha=0.75, linewidths=0)
927
- sig_m = log_p >= -np.log10(5e-8)
928
- if sig_m.any():
929
- ax.scatter(x_coords[sig_m], log_p[sig_m], c=SIG_COLOR, s=60, zorder=10,
930
- marker='D', linewidths=0.8, edgecolors='#7F1D1D')
931
- ax.axhline(-np.log10(5e-8), color=ACCENT_CORAL, ls='--', lw=1.2, alpha=0.8, label="GW sig.")
932
- ax.axhline(-np.log10(1e-5), color=ACCENT_TEAL, ls=':', lw=1, alpha=0.7, label="Suggestive")
933
- ax.set_ylabel("-log₁₀(p)", fontsize=8, color=TEXT_DIM)
934
- ax.set_title(f"Manhattan β€” {mname}", color=col, fontsize=10, fontweight='bold', pad=4)
935
- ax.set_xticks(tick_pos)
936
- ax.set_xticklabels(tick_lab, rotation=40, fontsize=7, color=TEXT_DIM)
937
- ax.tick_params(colors=TEXT_DIM, labelsize=7)
938
- for spine in ax.spines.values():
939
- spine.set_edgecolor(GRID_LINE)
940
- ax.grid(color=GRID_LINE, linewidth=0.4, linestyle="--", alpha=0.5)
941
- lam = np.median(stats.chi2.ppf(1 - np.clip(pvals, 1e-10, 1), df=1)) / stats.chi2.ppf(0.5, df=1)
942
- ax.text(0.99, 0.96, f"Ξ»={lam:.3f}", transform=ax.transAxes, fontsize=8,
943
- color=ACCENT_GOLD, fontweight='bold', ha='right', va='top')
944
- ax.legend(fontsize=6, facecolor=BG_WHITE, edgecolor=GRID_LINE, loc='upper right')
945
-
946
- for idx in range(n_models, len(axes_flat)):
947
- axes_flat[idx].set_visible(False)
948
-
949
- fig.suptitle("Manhattan Plots β€” All Selected Models", color=TEXT_MAIN, fontsize=13, y=1.01)
950
- fig.tight_layout()
951
- return fig
952
-
953
  # ─────────────────────── EXCEL RESULTS EXPORT ────────────────────────────────────
954
  def export_results_excel(all_results, snp_filt, chr_filt, pos_filt, y, G_filt, maf_vals, output_path):
955
  wb = Workbook()
@@ -1067,104 +1006,6 @@ def export_results_excel(all_results, snp_filt, chr_filt, pos_filt, y, G_filt, m
1067
  if col == 9 and isinstance(val, float): cell.number_format = '0.00E+00'
1068
  mta_row += 1
1069
 
1070
- # QTN Effects sheet
1071
- ws_qtn = wb.create_sheet(title="QTN_Effects")
1072
- ws_qtn['A1'] = "QTNs β€” Effect Analysis"
1073
- ws_qtn['A1'].font = title_font
1074
- ws_qtn.merge_cells('A1:L1')
1075
- headers_qtn = ["Model","Rank","SNP","Chr","Position","MAF",
1076
- "QTN_Effect_Beta","SE","95%_CI_Lower","95%_CI_Upper","P_value","PVE_%"]
1077
- for col, h in enumerate(headers_qtn, 1):
1078
- cell = ws_qtn.cell(row=3, column=col, value=h)
1079
- cell.font = header_font; cell.fill = header_fill
1080
- cell.alignment = Alignment(horizontal='center'); cell.border = thin_border
1081
- ws_qtn.column_dimensions[get_column_letter(col)].width = 17
1082
- qtn_row = 4
1083
- for mname, (pvals, betas, ses) in all_results.items():
1084
- top_idx = np.argsort(pvals)[:min(20, len(pvals))]
1085
- pve_dict, _ = compute_pve(y, G_filt, pvals, betas)
1086
- for rank, idx in enumerate(top_idx, 1):
1087
- pve_val = round(pve_dict.get(int(idx), 0.0), 4)
1088
- maf_v = maf_vals[idx] if idx < len(maf_vals) else np.nan
1089
- fill = alt_fill if qtn_row % 2 == 0 else PatternFill("solid", start_color="FFFFFF", end_color="FFFFFF")
1090
- row_data = [
1091
- mname, rank,
1092
- str(snp_filt[idx]) if idx < len(snp_filt) else "",
1093
- int(chr_filt[idx]) if idx < len(chr_filt) else "",
1094
- int(pos_filt[idx]) if idx < len(pos_filt) else "",
1095
- round(float(maf_v), 4) if not np.isnan(maf_v) else "",
1096
- round(float(betas[idx]), 6), round(float(ses[idx]), 6),
1097
- round(float(betas[idx]) - 1.96 * float(ses[idx]), 6),
1098
- round(float(betas[idx]) + 1.96 * float(ses[idx]), 6),
1099
- float(pvals[idx]), pve_val
1100
- ]
1101
- for col, val in enumerate(row_data, 1):
1102
- cell = ws_qtn.cell(row=qtn_row, column=col, value=val)
1103
- cell.fill = fill; cell.border = thin_border; cell.alignment = Alignment(horizontal='center')
1104
- if col == 11 and isinstance(val, float): cell.number_format = '0.00E+00'
1105
- qtn_row += 1
1106
-
1107
- # PVE Summary sheet
1108
- ws_pve = wb.create_sheet(title="PVE_Summary")
1109
- ws_pve['A1'] = "Phenotypic Variance Explained (PVE)"
1110
- ws_pve['A1'].font = title_font
1111
- ws_pve.merge_cells('A1:I1')
1112
- headers_pve = ["Model","SNP","Chr","Position","Beta","P_value","PVE_%","Cumulative_PVE_%","Significance"]
1113
- for col, h in enumerate(headers_pve, 1):
1114
- cell = ws_pve.cell(row=3, column=col, value=h)
1115
- cell.font = header_font; cell.fill = header_fill
1116
- cell.alignment = Alignment(horizontal='center'); cell.border = thin_border
1117
- ws_pve.column_dimensions[get_column_letter(col)].width = 20
1118
- pve_row = 4
1119
- for mname, (pvals, betas, ses) in all_results.items():
1120
- pve_dict, _ = compute_pve(y, G_filt, pvals, betas)
1121
- cumulative = 0.0
1122
- for idx in sorted(pve_dict.keys(), key=lambda i: pve_dict[i], reverse=True):
1123
- pve_val = pve_dict[idx]
1124
- cumulative += pve_val
1125
- fill = sig_fill if pve_row % 2 == 0 else PatternFill("solid", start_color="FFFFFF", end_color="FFFFFF")
1126
- row_data = [
1127
- mname, str(snp_filt[idx]) if idx < len(snp_filt) else "",
1128
- int(chr_filt[idx]) if idx < len(chr_filt) else "",
1129
- int(pos_filt[idx]) if idx < len(pos_filt) else "",
1130
- round(float(betas[idx]), 6), float(pvals[idx]),
1131
- round(pve_val, 4), round(cumulative, 4),
1132
- "GW-significant" if pvals[idx] < 5e-8 else "Bonferroni-significant"
1133
- ]
1134
- for col, val in enumerate(row_data, 1):
1135
- cell = ws_pve.cell(row=pve_row, column=col, value=val)
1136
- cell.fill = fill; cell.border = thin_border; cell.alignment = Alignment(horizontal='center')
1137
- if col == 6 and isinstance(val, float): cell.number_format = '0.00E+00'
1138
- pve_row += 1
1139
-
1140
- # SNP QC sheet
1141
- ws_qc = wb.create_sheet(title="SNP_QC")
1142
- ws_qc['A1'] = "SNP Quality Control Statistics"
1143
- ws_qc['A1'].font = title_font
1144
- ws_qc.merge_cells('A1:F1')
1145
- headers_qc = ["SNP","Chr","Position","MAF","Call_Rate","Category"]
1146
- for col, h in enumerate(headers_qc, 1):
1147
- cell = ws_qc.cell(row=3, column=col, value=h)
1148
- cell.font = header_font; cell.fill = header_fill
1149
- cell.alignment = Alignment(horizontal='center'); cell.border = thin_border
1150
- ws_qc.column_dimensions[get_column_letter(col)].width = 20
1151
- call_rates = compute_call_rate(G_filt)
1152
- for row_i in range(len(snp_filt)):
1153
- maf_v = maf_vals[row_i] if row_i < len(maf_vals) else np.nan
1154
- cr_v = call_rates[row_i] if row_i < len(call_rates) else np.nan
1155
- fill = alt_fill if row_i % 2 == 0 else PatternFill("solid", start_color="FFFFFF", end_color="FFFFFF")
1156
- row_data = [
1157
- str(snp_filt[row_i]),
1158
- int(chr_filt[row_i]) if row_i < len(chr_filt) else "",
1159
- int(pos_filt[row_i]) if row_i < len(pos_filt) else "",
1160
- round(float(maf_v), 4) if not np.isnan(maf_v) else "",
1161
- round(float(cr_v), 4) if not np.isnan(cr_v) else "",
1162
- "Rare (<0.05)" if not np.isnan(maf_v) and maf_v < 0.05 else "Common"
1163
- ]
1164
- for col, val in enumerate(row_data, 1):
1165
- cell = ws_qc.cell(row=row_i+4, column=col, value=val)
1166
- cell.fill = fill; cell.border = thin_border; cell.alignment = Alignment(horizontal='center')
1167
-
1168
  wb.save(output_path)
1169
  return output_path
1170
 
@@ -1185,7 +1026,7 @@ def run_gwas(file_obj, text_input, selected_models, maf_threshold):
1185
  try:
1186
  df, snp_cols, chroms, positions = parse_data(file_obj, text_input)
1187
  except Exception as e:
1188
- return [None] * 14 + [f"❌ Data parsing error: {e}"]
1189
 
1190
  y = df["Phenotype"].values.astype(float)
1191
  ids = df["ID"].values
@@ -1207,12 +1048,10 @@ def run_gwas(file_obj, text_input, selected_models, maf_threshold):
1207
 
1208
  K = build_kinship(G_filt)
1209
 
1210
- # ── FIX: Ensure selected_models is a valid non-empty list ─────────────────
1211
  ALL_MODELS_LIST = ["OLS", "MLM", "GLM", "CMLM", "BLINK", "FarmCPU", "EMMAX", "PLINK", "GAPIT3", "GEMMA"]
1212
  if not selected_models or len(selected_models) == 0:
1213
  models_to_run = ALL_MODELS_LIST
1214
  else:
1215
- # Preserve user selection order, filter to valid names
1216
  models_to_run = [m for m in selected_models if m in ALL_MODELS_LIST]
1217
  if len(models_to_run) == 0:
1218
  models_to_run = ALL_MODELS_LIST
@@ -1247,29 +1086,24 @@ def run_gwas(file_obj, text_input, selected_models, maf_threshold):
1247
  print(f"[WARN] Model {mname} failed: {ex}")
1248
 
1249
  if primary_p is None:
1250
- return [None] * 14 + [f"❌ No models succeeded.\nErrors:\n" + "\n".join(errors)]
1251
 
1252
- # ── Build all named plots ──────────────────────────────────────────────────
1253
  plot_dict = {}
1254
- plot_dict["01_Manhattan_Primary"] = plot_manhattan(primary_p, chr_filt, pos_filt, "Manhattan Plot", primary_model)
1255
- plot_dict["02_QQ_Primary"] = plot_qq_single(primary_p, "QQ Plot", primary_model, MODEL_COLORS.get(primary_model, ACCENT_PURP))
1256
- plot_dict["03_QQ_All_Models"] = plot_qq_all_models(all_results)
1257
- plot_dict["04_QQ_Overlay"] = plot_qq_overlay(all_results)
1258
- plot_dict["05_Circos"] = plot_circos(all_results, chr_filt, pos_filt)
1259
- plot_dict["06_LD_Decay"] = plot_ld_decay(G_filt, pos_filt)
1260
- plot_dict["07_PCA"] = plot_pca(G_filt, y, ids)
1261
- plot_dict["08_Kinship"] = plot_kinship(K, ids)
1262
- plot_dict["09_Effect_Sizes"] = plot_effect_sizes(primary_p, primary_b, snp_filt)
1263
- plot_dict["10_All_Models_Manhattan"] = plot_model_comparison_manhattan(all_results, chr_filt, pos_filt)
1264
- plot_dict["11_Summary_Dashboard"] = plot_summary_dashboard(y, maf_vals, all_results, G_filt)
1265
- plot_dict["12_All_Models_MH_Grid"] = plot_all_models_manhattan_grid(all_results, chr_filt, pos_filt)
1266
-
1267
- # Per-model individual Manhattan + QQ (saved to zip, not displayed inline)
1268
  for mname, (p, b, se) in all_results.items():
1269
- plot_dict[f"13_{mname}_Manhattan"] = plot_manhattan(p, chr_filt, pos_filt, "Manhattan", mname)
1270
- plot_dict[f"14_{mname}_QQ"] = plot_qq_single(p, "QQ Plot", mname, MODEL_COLORS.get(mname, ACCENT_PURP))
1271
 
1272
- # PIL images for display
1273
  imgs = {}
1274
  for k, fig in plot_dict.items():
1275
  imgs[k] = fig_to_pil(fig) if fig is not None else None
@@ -1318,23 +1152,18 @@ def run_gwas(file_obj, text_input, selected_models, maf_threshold):
1318
  f"{'='*68}\n"
1319
  )
1320
 
1321
- return [
1322
- imgs.get("01_Manhattan_Primary"),
1323
- imgs.get("02_QQ_Primary"),
1324
- imgs.get("03_QQ_All_Models"),
1325
- imgs.get("04_QQ_Overlay"),
1326
- imgs.get("05_Circos"),
1327
- imgs.get("06_LD_Decay"),
1328
- imgs.get("07_PCA"),
1329
- imgs.get("08_Kinship"),
1330
- imgs.get("09_Effect_Sizes"),
1331
- imgs.get("10_All_Models_Manhattan"),
1332
- imgs.get("11_Summary_Dashboard"),
1333
- imgs.get("12_All_Models_MH_Grid"),
1334
- excel_path,
1335
- zip_path,
1336
- summary,
1337
- ]
1338
 
1339
  # ─────────────────────── CSS ──────────────────────────────────────────────────────
1340
  PASTEL_CSS = """
@@ -1345,7 +1174,7 @@ body, .gradio-container {
1345
  font-family: 'DM Sans', sans-serif !important;
1346
  color: #2D3142 !important;
1347
  }
1348
- .gradio-container { max-width: 1400px !important; margin: 0 auto !important; }
1349
  .gwas-header {
1350
  background: linear-gradient(135deg, #E8F4FD 0%, #EDE9F8 50%, #FDF0F8 100%);
1351
  border: 1px solid #D6E8F5; border-radius: 18px; padding: 28px 36px;
@@ -1405,6 +1234,12 @@ button.primary:hover { transform: translateY(-2px) !important; box-shadow: 0 6px
1405
  ::-webkit-scrollbar { width: 6px; height: 6px; }
1406
  ::-webkit-scrollbar-track { background: #F0F3FB; border-radius: 4px; }
1407
  ::-webkit-scrollbar-thumb { background: #C8D0E7; border-radius: 4px; }
 
 
 
 
 
 
1408
  """
1409
 
1410
  SAMPLE_DATA = """ID,Phenotype,chr1_134521_SNP1,chr1_134810_SNP2,chr1_178766_SNP3,chr1_210328_SNP4
@@ -1428,9 +1263,9 @@ with gr.Blocks(css=PASTEL_CSS, title="🧬 GWAS Pipeline", theme=gr.themes.Base(
1428
  gr.HTML("""
1429
  <div class="gwas-header">
1430
  <h1>🧬 Complete GWAS Analysis Pipeline</h1>
1431
- <p>10 Statistical Models Β· All-Model Manhattan & QQ Β· Circos Β· LD Decay Β· PNG Export Β· Full Excel</p>
1432
  <p style="font-size:12px; color:#8892B0;">
1433
- Per-model: MTA Β· PVE Β· QTN Effects Β· Beta Β· SE Β· T-stat Β· FDR Β· Bonferroni Β· 95% CI
1434
  </p>
1435
  </div>
1436
  """)
@@ -1445,7 +1280,7 @@ with gr.Blocks(css=PASTEL_CSS, title="🧬 GWAS Pipeline", theme=gr.themes.Base(
1445
  gr.HTML('<div class="section-label" style="margin-top:16px;">βš™οΈ Model Selection</div>')
1446
  model_sel = gr.CheckboxGroup(
1447
  choices=ALL_MODELS,
1448
- value=ALL_MODELS, # ← default: all 10 selected
1449
  label="Select models to run"
1450
  )
1451
  maf_thr = gr.Slider(0, 0.5, 0.05, 0.01, label="MAF Threshold")
@@ -1453,51 +1288,57 @@ with gr.Blocks(css=PASTEL_CSS, title="🧬 GWAS Pipeline", theme=gr.themes.Base(
1453
 
1454
  gr.HTML('<div class="section-label" style="margin-top:16px;">πŸ“₯ Downloads</div>')
1455
  with gr.Column(elem_classes=["download-section"]):
1456
- excel_out = gr.File(label="πŸ“Š Excel Results (MTA Β· PVE Β· QTN Β· All Models)", interactive=False)
1457
  zip_out = gr.File(label="πŸ–Ό All Plots as PNG (ZIP)", interactive=False)
1458
 
1459
  with gr.Column(scale=2):
1460
  gr.HTML('<div class="section-label">πŸ“Š Analysis Summary</div>')
1461
- summary_out = gr.Textbox(label="", lines=30, elem_classes=["summary-box"], show_label=False)
1462
 
1463
- gr.HTML('<div class="section-label" style="margin: 16px 0 8px 0;">πŸ–Ό Visualizations</div>')
1464
  with gr.Tabs():
1465
  with gr.Tab("πŸ—Ί Manhattan (Primary)"):
1466
- img1 = gr.Image(type="pil", label="Manhattan β€” Primary Model (β—† = Sig. MTA)")
1467
  with gr.Tab("πŸ“ˆ QQ (Primary)"):
1468
- img2 = gr.Image(type="pil", label="QQ Plot β€” Primary Model")
1469
- with gr.Tab("πŸ“ˆ QQ (All Models)"):
1470
- img3 = gr.Image(type="pil", label="QQ Plots β€” All Models (individual panels)")
1471
- with gr.Tab("πŸ“Š QQ Overlay"):
1472
- img4 = gr.Image(type="pil", label="QQ Overlay β€” All Models with Ξ»")
1473
  with gr.Tab("πŸ”΅ Circos"):
1474
- img5 = gr.Image(type="pil", label="Circos β€” Multi-Model Comparison")
1475
  with gr.Tab("πŸ”— LD Decay"):
1476
- img6 = gr.Image(type="pil", label="Linkage Disequilibrium Decay (bp & Mb)")
1477
  with gr.Tab("πŸ”¬ PCA"):
1478
- img7 = gr.Image(type="pil", label="Principal Component Analysis")
1479
- with gr.Tab("πŸ‘¨β€πŸ‘©β€πŸ‘§ Kinship"):
1480
- img8 = gr.Image(type="pil", label="Kinship Matrix & Clustering")
1481
  with gr.Tab("βš– Effect Sizes"):
1482
- img9 = gr.Image(type="pil", label="Effect Sizes & Volcano Plot")
1483
- with gr.Tab("πŸ”„ All Models (Stacked)"):
1484
- img10 = gr.Image(type="pil", label="Manhattan β€” All Models Stacked")
1485
  with gr.Tab("πŸ“Š Dashboard"):
1486
- img11 = gr.Image(type="pil", label="Summary Dashboard β€” All Models")
1487
- with gr.Tab("πŸ—‚ All Models (Grid)"):
1488
- img12 = gr.Image(type="pil", label="Manhattan Grid β€” One Panel Per Model")
 
 
 
 
 
 
 
 
 
 
 
1489
 
1490
  def run_wrapper(f, t, m, maf):
1491
  out = run_gwas(f, t, m, maf)
1492
- while len(out) < 15:
 
 
1493
  out.append(None)
1494
  return out
1495
 
1496
  run_btn.click(
1497
  run_wrapper,
1498
  inputs=[file_in, text_in, model_sel, maf_thr],
1499
- outputs=[img1, img2, img3, img4, img5, img6, img7, img8, img9, img10, img11, img12,
1500
- excel_out, zip_out, summary_out]
 
1501
  )
1502
 
1503
  if __name__ == "__main__":
 
192
  from PIL import Image
193
  return Image.open(buf).copy()
194
 
195
+ # ─────────────────────── IMPROVED QQ PLOT WITH DEVIATION HIGHLIGHTING ────────────
196
+ def plot_qq_advanced(pvals, title="QQ Plot", model_name="", color=None):
197
+ """Advanced QQ plot with deviation highlighting and confidence bands"""
198
+ if color is None:
199
+ color = ACCENT_PURP
200
+
201
+ fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(14, 6), facecolor=BG_WHITE)
202
+
203
+ n = len(pvals)
204
+ obs = -np.log10(np.sort(pvals))
205
+ exp = -np.log10(np.linspace(1/n, 1, n))
206
+
207
+ # Calculate confidence intervals
208
+ ci_lower = -np.log10(stats.beta.ppf(0.975, np.arange(1, n+1), np.arange(n, 0, -1)))
209
+ ci_upper = -np.log10(stats.beta.ppf(0.025, np.arange(1, n+1), np.arange(n, 0, -1)))
210
+
211
+ # Main QQ plot
212
+ ax1.fill_between(exp, ci_lower, ci_upper, alpha=0.2, color=color, label="95% CI")
213
+ ax1.scatter(exp, obs, c=color, s=20, alpha=0.7, linewidths=0, zorder=5)
214
+ ax1.plot([0, max(exp)], [0, max(exp)], color=ACCENT_CORAL, ls="--", lw=2, label="Expected", zorder=6)
215
+
216
+ # Calculate and display lambda
217
+ lam = np.median(stats.chi2.ppf(1 - np.clip(pvals, 1e-10, 1), df=1)) / stats.chi2.ppf(0.5, df=1)
218
+ ax1.text(0.05, 0.93, f"Ξ» = {lam:.4f}", transform=ax1.transAxes, fontsize=12,
219
+ color=ACCENT_GOLD, fontweight='bold', bbox=dict(boxstyle='round', facecolor='white', alpha=0.8))
220
+
221
+ ax1.set_xlabel("Expected -log₁₀(p)", fontsize=10, color=TEXT_DIM)
222
+ ax1.set_ylabel("Observed -log₁₀(p)", fontsize=10, color=TEXT_DIM)
223
+ ax1.set_title(f"{title}{' β€” ' + model_name if model_name else ''}", color=TEXT_MAIN, fontsize=11)
224
+ ax1.legend(loc='lower right', fontsize=9, framealpha=0.9, facecolor=BG_WHITE)
225
+
226
+ # Deviation plot (observed - expected)
227
+ deviation = obs - exp
228
+ ax2.fill_between(exp, 0, deviation, where=(deviation >= 0), color=ACCENT_CORAL, alpha=0.3, label="Inflation")
229
+ ax2.fill_between(exp, 0, deviation, where=(deviation < 0), color=ACCENT_TEAL, alpha=0.3, label="Deflation")
230
+ ax2.plot(exp, deviation, color=color, lw=2, alpha=0.8)
231
+ ax2.axhline(0, color='black', ls='-', lw=1, alpha=0.5)
232
+ ax2.axhline(np.percentile(deviation, 95), color=ACCENT_CORAL, ls='--', lw=1, alpha=0.7, label="95th percentile")
233
+ ax2.axhline(np.percentile(deviation, 5), color=ACCENT_TEAL, ls='--', lw=1, alpha=0.7, label="5th percentile")
234
+
235
+ ax2.set_xlabel("Expected -log₁₀(p)", fontsize=10, color=TEXT_DIM)
236
+ ax2.set_ylabel("Deviation (Observed - Expected)", fontsize=10, color=TEXT_DIM)
237
+ ax2.set_title("Deviation from Expectation", color=TEXT_MAIN, fontsize=11)
238
+ ax2.legend(loc='upper left', fontsize=8, framealpha=0.9, facecolor=BG_WHITE)
239
+
240
+ style_fig(fig)
241
+ fig.tight_layout()
242
+ return fig
243
+
244
+ # ─────────────────────── 10 STATISTICAL MODELS (FIXED) ──────────────────────────
245
  def ols_gwas(y, G):
246
  n, m = G.shape
247
  pvals = np.ones(m); betas = np.zeros(m); ses = np.zeros(m)
248
  for j in range(m):
249
+ x = G[:, j]
250
+ mask = ~np.isnan(x)
251
+ if mask.sum() < 4: continue
252
+ x_clean = x[mask]
253
+ y_clean = y[mask]
254
+ if np.std(x_clean) < 1e-8: continue
255
+ try:
256
+ slope, intercept, r_value, p_value, std_err = stats.linregress(x_clean, y_clean)
257
+ pvals[j] = p_value
258
+ betas[j] = slope
259
+ ses[j] = std_err
260
+ except:
261
+ continue
262
  return pvals, betas, ses
263
 
264
  def mlm_gwas(y, G, K):
265
  n, m = G.shape
266
  pvals = np.ones(m); betas = np.zeros(m); ses = np.zeros(m)
267
+ try:
268
+ eigvals, eigvecs = np.linalg.eigh(K + np.eye(n) * 1e-6)
269
+ n_pcs = min(3, n - 2)
270
+ Q = eigvecs[:, np.argsort(eigvals)[::-1][:n_pcs]]
271
+ y_res = y - LinearRegression().fit(Q, y).predict(Q)
272
+
273
+ for j in range(m):
274
+ x = G[:, j]
275
+ mask = ~np.isnan(x)
276
+ if mask.sum() < 4: continue
277
+ x_clean = x[mask]
278
+ y_clean = y_res[mask]
279
+ Q_clean = Q[mask]
280
+
281
+ if np.std(x_clean) < 1e-8: continue
282
+ try:
283
+ x_res = x_clean - LinearRegression().fit(Q_clean, x_clean).predict(Q_clean)
284
+ slope, _, _, p, se = stats.linregress(x_res, y_clean)
285
+ pvals[j] = p
286
+ betas[j] = slope
287
+ ses[j] = se
288
+ except:
289
+ continue
290
+ except:
291
+ pvals, betas, ses = ols_gwas(y, G)
292
  return pvals, betas, ses
293
 
294
  def glm_gwas(y, G):
295
  n, m = G.shape
296
  pvals = np.ones(m); betas = np.zeros(m); ses = np.zeros(m)
 
297
  try:
298
+ n_pcs = min(3, n - 2, G.shape[1])
299
+ G_scaled = StandardScaler().fit_transform(G)
300
+ PCs = PCA(n_components=n_pcs).fit_transform(G_scaled)
301
  y_adj = y - LinearRegression().fit(PCs, y).predict(PCs)
302
+
303
+ for j in range(m):
304
+ x = G[:, j]
305
+ mask = ~np.isnan(x)
306
+ if mask.sum() < 4: continue
307
+ x_clean = x[mask]
308
+ y_clean = y_adj[mask]
309
+ PCs_clean = PCs[mask]
310
+
311
+ if np.std(x_clean) < 1e-8: continue
312
+ try:
313
+ x_adj = x_clean - LinearRegression().fit(PCs_clean, x_clean).predict(PCs_clean)
314
+ slope, _, _, p, se = stats.linregress(x_adj, y_clean)
315
+ pvals[j] = p
316
+ betas[j] = slope
317
+ ses[j] = se
318
+ except:
319
+ continue
320
+ except:
321
+ pvals, betas, ses = ols_gwas(y, G)
322
  return pvals, betas, ses
323
 
324
  def cmlm_gwas(y, G, K):
325
  n, m = G.shape
326
  pvals = np.ones(m); betas = np.zeros(m); ses = np.zeros(m)
 
 
 
327
  try:
328
+ n_groups = min(3, n)
329
+ groups = np.array([i % n_groups for i in range(n)])
330
+ group_means = np.zeros((n, n_groups))
331
+ for g in range(n_groups):
332
+ group_idx = np.where(groups == g)[0]
333
+ if len(group_idx) > 0:
334
+ group_means[:, g] = K[:, group_idx].mean(axis=1)
335
+
336
  y_res = y - LinearRegression().fit(group_means, y).predict(group_means)
337
+
338
+ for j in range(m):
339
+ x = G[:, j]
340
+ mask = ~np.isnan(x)
341
+ if mask.sum() < 4: continue
342
+ x_clean = x[mask]
343
+ y_clean = y_res[mask]
344
+ gm_clean = group_means[mask]
345
+
346
+ if np.std(x_clean) < 1e-8: continue
347
+ try:
348
+ x_res = x_clean - LinearRegression().fit(gm_clean, x_clean).predict(gm_clean)
349
+ slope, _, _, p, se = stats.linregress(x_res, y_clean)
350
+ pvals[j] = p
351
+ betas[j] = slope
352
+ ses[j] = se
353
+ except:
354
+ continue
355
+ except:
356
+ pvals, betas, ses = ols_gwas(y, G)
357
  return pvals, betas, ses
358
 
359
  def blink_gwas(y, G):
360
  n, m = G.shape
361
  pvals = np.ones(m); betas = np.zeros(m); ses = np.zeros(m)
 
 
 
362
  try:
363
+ ols_p, _, _ = ols_gwas(y, G)
364
+ top_idx = np.argsort(ols_p)[:min(5, m)]
365
+ covars = G[:, top_idx]
366
+
367
  y_adj = y - LinearRegression().fit(covars, y).predict(covars)
368
+
369
+ for j in range(m):
370
+ x = G[:, j]
371
+ mask = ~np.isnan(x)
372
+ if mask.sum() < 4: continue
373
+ x_clean = x[mask]
374
+ y_clean = y_adj[mask]
375
+
376
+ if np.std(x_clean) < 1e-8: continue
377
+ try:
378
+ slope, _, _, p, se = stats.linregress(x_clean, y_clean)
379
+ pvals[j] = p
380
+ betas[j] = slope
381
+ ses[j] = se
382
+ except:
383
+ continue
384
+ except:
385
+ pvals, betas, ses = ols_gwas(y, G)
386
  return pvals, betas, ses
387
 
388
  def farmcpu_gwas(y, G, K):
389
  n, m = G.shape
390
  pvals = np.ones(m); betas = np.zeros(m); ses = np.zeros(m)
 
 
 
391
  try:
392
+ mlm_p, _, _ = mlm_gwas(y, G, K)
393
+ qtn_idx = np.argsort(mlm_p)[:min(3, m)]
394
+ qtns = G[:, qtn_idx]
395
+
396
  y_adj = y - LinearRegression().fit(qtns, y).predict(qtns)
397
+
398
+ for j in range(m):
399
+ x = G[:, j]
400
+ mask = ~np.isnan(x)
401
+ if mask.sum() < 4: continue
402
+ x_clean = x[mask]
403
+ y_clean = y_adj[mask]
404
+
405
+ if np.std(x_clean) < 1e-8: continue
406
+ try:
407
+ slope, _, _, p, se = stats.linregress(x_clean, y_clean)
408
+ pvals[j] = p
409
+ betas[j] = slope
410
+ ses[j] = se
411
+ except:
412
+ continue
413
+ except:
414
+ pvals, betas, ses = ols_gwas(y, G)
415
  return pvals, betas, ses
416
 
417
  def emmax_gwas(y, G, K):
418
  n, m = G.shape
419
  pvals = np.ones(m); betas = np.zeros(m); ses = np.zeros(m)
 
 
 
420
  try:
421
+ tau = np.var(y) * 0.5
422
+ sigma = np.var(y) * 0.5
423
+ V = tau * K + sigma * np.eye(n)
424
  V_inv = np.linalg.inv(V + np.eye(n) * 1e-6)
425
+
426
+ for j in range(m):
427
+ x = G[:, j].reshape(-1, 1)
428
+ mask = ~np.isnan(x.flatten())
429
+ if mask.sum() < 4: continue
430
+
431
+ x_clean = x[mask]
432
+ y_clean = y[mask]
433
+ V_inv_clean = V_inv[np.ix_(mask, mask)]
434
+
435
+ if np.std(x_clean) < 1e-8: continue
436
+ try:
437
+ Px = V_inv_clean @ x_clean
438
+ beta = (x_clean.T @ Px @ y_clean) / (x_clean.T @ Px @ x_clean + 1e-10)
439
+ betas[j] = float(beta)
440
+ resid = y_clean - float(beta) * x_clean.flatten()
441
+ sigma_e = (resid @ V_inv_clean @ resid) / (mask.sum() - 2 + 1e-10)
442
+ se = np.sqrt(float(sigma_e / (x_clean.T @ Px @ x_clean + 1e-10)))
443
+ ses[j] = se
444
+ t_stat = float(beta) / (se + 1e-10)
445
+ pvals[j] = float(2 * stats.t.sf(abs(t_stat), df=mask.sum()-2))
446
+ except:
447
+ continue
448
+ except:
449
+ pvals, betas, ses = ols_gwas(y, G)
450
  return pvals, betas, ses
451
 
452
  def plink_gwas(y, G):
453
  n, m = G.shape
454
  pvals = np.ones(m); betas = np.zeros(m); ses = np.zeros(m)
455
+ try:
456
+ y_bin = (y > np.median(y)).astype(float)
457
+
458
+ for j in range(m):
459
+ x = G[:, j]
460
+ mask = ~np.isnan(x)
461
+ if mask.sum() < 4: continue
462
+ x_clean = x[mask]
463
+ y_clean = y_bin[mask]
464
+
465
+ if np.std(x_clean) < 1e-8: continue
466
+ try:
467
+ # Chi-square test for association
468
+ ct = pd.crosstab(x_clean, y_clean).values
469
+ if ct.shape == (2, 2):
470
+ chi2, p, _, _ = stats.chi2_contingency(ct + 0.5)
471
+ pvals[j] = p
472
+
473
+ slope, _, _, p2, se = stats.linregress(x_clean, y_clean)
474
+ betas[j] = slope
475
+ ses[j] = se
476
+ except:
477
+ continue
478
+ except:
479
+ pvals, betas, ses = ols_gwas(y, G)
480
  return pvals, betas, ses
481
 
482
  def gapit3_gwas(y, G, K):
483
  n, m = G.shape
484
  pvals = np.ones(m); betas = np.zeros(m); ses = np.zeros(m)
 
485
  try:
486
+ n_pcs = min(3, n - 2, G.shape[1])
487
+ G_scaled = StandardScaler().fit_transform(G)
488
+ PCs = PCA(n_components=n_pcs).fit_transform(G_scaled)
489
+
490
+ eigvals, eigvecs = np.linalg.eigh(K + np.eye(n) * 1e-6)
491
+ Q = eigvecs[:, np.argsort(eigvals)[::-1][:n_pcs]]
492
+ covars = np.hstack([PCs, Q])
493
+
494
+ qtns = []
495
+ for iteration in range(2):
496
+ for j in range(m):
497
+ x = G[:, j]
498
+ mask = ~np.isnan(x)
499
+ if mask.sum() < 4: continue
500
+ x_clean = x[mask]
501
+ y_clean = y[mask]
502
+ cov_clean = covars[mask]
503
+
504
+ if np.std(x_clean) < 1e-8: continue
505
+ try:
506
+ if len(qtns) > 0:
507
+ qtn_vals = np.column_stack([G[:, q] for q in qtns])
508
+ cov_full = np.column_stack([covars, qtn_vals])
509
+ cov_clean = cov_full[mask]
510
+
511
+ x_res = x_clean - LinearRegression().fit(cov_clean, x_clean).predict(cov_clean)
512
+ y_res = y_clean - LinearRegression().fit(cov_clean, y_clean).predict(cov_clean)
513
+ slope, _, _, p, se = stats.linregress(x_res, y_res)
514
+ pvals[j] = p
515
+ betas[j] = slope
516
+ ses[j] = se
517
+ except:
518
+ continue
519
+
520
+ new_qtns = list(np.where(pvals < 0.05 / m)[0][:2])
521
+ if new_qtns and new_qtns != qtns:
522
+ qtns = new_qtns
523
+ else:
524
+ break
525
+ except:
526
+ pvals, betas, ses = ols_gwas(y, G)
527
  return pvals, betas, ses
528
 
529
  def gemma_gwas(y, G, K):
530
  n, m = G.shape
531
  pvals = np.ones(m); betas = np.zeros(m); ses = np.zeros(m)
 
 
 
 
 
 
 
 
532
  try:
533
+ # Center kinship matrix
534
+ row_mean = K.mean(axis=1, keepdims=True)
535
+ col_mean = K.mean(axis=0, keepdims=True)
536
+ grand_mean = K.mean()
537
+ Kc = K - row_mean - col_mean + grand_mean
538
+
539
+ eigvals, eigvecs = np.linalg.eigh(Kc + np.eye(n) * 1e-6)
540
+ idx = np.argsort(eigvals)[::-1]
541
+ n_pcs = min(4, n - 2)
542
+ Q = eigvecs[:, idx[:n_pcs]]
543
+
544
  y_res = y - LinearRegression().fit(Q, y).predict(Q)
545
+
546
+ for j in range(m):
547
+ x = G[:, j]
548
+ mask = ~np.isnan(x)
549
+ if mask.sum() < 4: continue
550
+ x_clean = x[mask]
551
+ y_clean = y_res[mask]
552
+ Q_clean = Q[mask]
553
+
554
+ if np.std(x_clean) < 1e-8: continue
555
+ try:
556
+ x_res = x_clean - LinearRegression().fit(Q_clean, x_clean).predict(Q_clean)
557
+ slope, _, _, p, se = stats.linregress(x_res, y_clean)
558
+ pvals[j] = p
559
+ betas[j] = slope
560
+ ses[j] = se
561
+ except:
562
+ continue
563
+
564
+ # Genomic control adjustment
565
+ lam = np.median(stats.chi2.ppf(1 - np.clip(pvals, 1e-10, 1), df=1)) / stats.chi2.ppf(0.5, df=1)
566
+ if lam > 1.05:
567
+ chi2_vals = stats.chi2.ppf(1 - pvals, df=1) / lam
568
+ pvals = 1 - stats.chi2.cdf(np.clip(chi2_vals, 0, 1e10), df=1)
569
+ except:
570
+ pvals, betas, ses = ols_gwas(y, G)
571
  return pvals, betas, ses
572
 
573
+ # ─────────────────────── PLOTS ────────────────────────────────────────────────
574
  def plot_manhattan(pvals, chroms, positions, title="Manhattan Plot", model_name=""):
575
  fig, ax = plt.subplots(figsize=(16, 5), facecolor=BG_WHITE)
576
  ax.set_facecolor(PANEL_WHITE)
 
611
  fig.tight_layout()
612
  return fig
613
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
614
  def plot_circos(all_results, chroms, positions):
615
  fig, ax = plt.subplots(figsize=(14, 14), subplot_kw=dict(projection='polar'), facecolor=BG_WHITE)
616
  ax.set_facecolor(BG_WHITE)
 
780
  fig.tight_layout()
781
  return fig
782
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
783
  def plot_effect_sizes(pvals, betas, snp_names):
784
  fig, axes = plt.subplots(2, 2, figsize=(14, 10), facecolor=BG_WHITE)
785
  style_fig(fig)
 
889
  fig.tight_layout()
890
  return fig
891
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
892
  # ─────────────────────── EXCEL RESULTS EXPORT ────────────────────────────────────
893
  def export_results_excel(all_results, snp_filt, chr_filt, pos_filt, y, G_filt, maf_vals, output_path):
894
  wb = Workbook()
 
1006
  if col == 9 and isinstance(val, float): cell.number_format = '0.00E+00'
1007
  mta_row += 1
1008
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1009
  wb.save(output_path)
1010
  return output_path
1011
 
 
1026
  try:
1027
  df, snp_cols, chroms, positions = parse_data(file_obj, text_input)
1028
  except Exception as e:
1029
+ return [None] * (15 + len(ALL_MODELS) * 2) + [f"❌ Data parsing error: {e}"]
1030
 
1031
  y = df["Phenotype"].values.astype(float)
1032
  ids = df["ID"].values
 
1048
 
1049
  K = build_kinship(G_filt)
1050
 
 
1051
  ALL_MODELS_LIST = ["OLS", "MLM", "GLM", "CMLM", "BLINK", "FarmCPU", "EMMAX", "PLINK", "GAPIT3", "GEMMA"]
1052
  if not selected_models or len(selected_models) == 0:
1053
  models_to_run = ALL_MODELS_LIST
1054
  else:
 
1055
  models_to_run = [m for m in selected_models if m in ALL_MODELS_LIST]
1056
  if len(models_to_run) == 0:
1057
  models_to_run = ALL_MODELS_LIST
 
1086
  print(f"[WARN] Model {mname} failed: {ex}")
1087
 
1088
  if primary_p is None:
1089
+ return [None] * (15 + len(ALL_MODELS_LIST) * 2) + [f"❌ No models succeeded.\nErrors:\n" + "\n".join(errors)]
1090
 
1091
+ # Build all plots
1092
  plot_dict = {}
1093
+ plot_dict["01_Manhattan_Primary"] = plot_manhattan(primary_p, chr_filt, pos_filt, "Manhattan Plot", primary_model)
1094
+ plot_dict["02_QQ_Primary"] = plot_qq_advanced(primary_p, "QQ Plot", primary_model, MODEL_COLORS.get(primary_model, ACCENT_PURP))
1095
+ plot_dict["03_Circos"] = plot_circos(all_results, chr_filt, pos_filt)
1096
+ plot_dict["04_LD_Decay"] = plot_ld_decay(G_filt, pos_filt)
1097
+ plot_dict["05_PCA"] = plot_pca(G_filt, y, ids)
1098
+ plot_dict["06_Effect_Sizes"] = plot_effect_sizes(primary_p, primary_b, snp_filt)
1099
+ plot_dict["07_Summary_Dashboard"] = plot_summary_dashboard(y, maf_vals, all_results, G_filt)
1100
+
1101
+ # Per-model plots
 
 
 
 
 
1102
  for mname, (p, b, se) in all_results.items():
1103
+ plot_dict[f"Manhattan_{mname}"] = plot_manhattan(p, chr_filt, pos_filt, "Manhattan Plot", mname)
1104
+ plot_dict[f"QQ_{mname}"] = plot_qq_advanced(p, "QQ Plot", mname, MODEL_COLORS.get(mname, ACCENT_PURP))
1105
 
1106
+ # Convert to PIL images
1107
  imgs = {}
1108
  for k, fig in plot_dict.items():
1109
  imgs[k] = fig_to_pil(fig) if fig is not None else None
 
1152
  f"{'='*68}\n"
1153
  )
1154
 
1155
+ # Prepare output list with all images
1156
+ output_list = [imgs.get("01_Manhattan_Primary"), imgs.get("02_QQ_Primary"),
1157
+ imgs.get("03_Circos"), imgs.get("04_LD_Decay"), imgs.get("05_PCA"),
1158
+ imgs.get("06_Effect_Sizes"), imgs.get("07_Summary_Dashboard"),
1159
+ excel_path, zip_path, summary]
1160
+
1161
+ # Add per-model Manhattan and QQ plots
1162
+ for mname in ALL_MODELS_LIST:
1163
+ output_list.append(imgs.get(f"Manhattan_{mname}"))
1164
+ output_list.append(imgs.get(f"QQ_{mname}"))
1165
+
1166
+ return output_list
 
 
 
 
 
1167
 
1168
  # ─────────────────────── CSS ──────────────────────────────────────────────────────
1169
  PASTEL_CSS = """
 
1174
  font-family: 'DM Sans', sans-serif !important;
1175
  color: #2D3142 !important;
1176
  }
1177
+ .gradio-container { max-width: 1600px !important; margin: 0 auto !important; }
1178
  .gwas-header {
1179
  background: linear-gradient(135deg, #E8F4FD 0%, #EDE9F8 50%, #FDF0F8 100%);
1180
  border: 1px solid #D6E8F5; border-radius: 18px; padding: 28px 36px;
 
1234
  ::-webkit-scrollbar { width: 6px; height: 6px; }
1235
  ::-webkit-scrollbar-track { background: #F0F3FB; border-radius: 4px; }
1236
  ::-webkit-scrollbar-thumb { background: #C8D0E7; border-radius: 4px; }
1237
+ .model-tab { padding: 10px !important; }
1238
+ .model-header {
1239
+ background: linear-gradient(135deg, #F8FAFE 0%, #F0F4FB 100%);
1240
+ padding: 8px 12px; border-radius: 10px; margin-bottom: 15px;
1241
+ border-left: 4px solid #5BA8E5;
1242
+ }
1243
  """
1244
 
1245
  SAMPLE_DATA = """ID,Phenotype,chr1_134521_SNP1,chr1_134810_SNP2,chr1_178766_SNP3,chr1_210328_SNP4
 
1263
  gr.HTML("""
1264
  <div class="gwas-header">
1265
  <h1>🧬 Complete GWAS Analysis Pipeline</h1>
1266
+ <p>10 Statistical Models Β· Advanced QQ Plots with Deviation Β· Circos Β· LD Decay Β· Per-Model Tabs</p>
1267
  <p style="font-size:12px; color:#8892B0;">
1268
+ Per-model: Manhattan Β· QQ (with deviation) Β· Beta Β· SE Β· T-stat Β· FDR Β· Bonferroni Β· 95% CI
1269
  </p>
1270
  </div>
1271
  """)
 
1280
  gr.HTML('<div class="section-label" style="margin-top:16px;">βš™οΈ Model Selection</div>')
1281
  model_sel = gr.CheckboxGroup(
1282
  choices=ALL_MODELS,
1283
+ value=ALL_MODELS,
1284
  label="Select models to run"
1285
  )
1286
  maf_thr = gr.Slider(0, 0.5, 0.05, 0.01, label="MAF Threshold")
 
1288
 
1289
  gr.HTML('<div class="section-label" style="margin-top:16px;">πŸ“₯ Downloads</div>')
1290
  with gr.Column(elem_classes=["download-section"]):
1291
+ excel_out = gr.File(label="πŸ“Š Excel Results (MTA Β· All Models)", interactive=False)
1292
  zip_out = gr.File(label="πŸ–Ό All Plots as PNG (ZIP)", interactive=False)
1293
 
1294
  with gr.Column(scale=2):
1295
  gr.HTML('<div class="section-label">πŸ“Š Analysis Summary</div>')
1296
+ summary_out = gr.Textbox(label="", lines=25, elem_classes=["summary-box"], show_label=False)
1297
 
1298
+ gr.HTML('<div class="section-label" style="margin: 16px 0 8px 0;">πŸ–Ό Main Visualizations</div>')
1299
  with gr.Tabs():
1300
  with gr.Tab("πŸ—Ί Manhattan (Primary)"):
1301
+ img1 = gr.Image(type="pil", label="Manhattan β€” Primary Model")
1302
  with gr.Tab("πŸ“ˆ QQ (Primary)"):
1303
+ img2 = gr.Image(type="pil", label="QQ Plot β€” Primary Model (with deviation)")
 
 
 
 
1304
  with gr.Tab("πŸ”΅ Circos"):
1305
+ img3 = gr.Image(type="pil", label="Circos β€” Multi-Model Comparison")
1306
  with gr.Tab("πŸ”— LD Decay"):
1307
+ img4 = gr.Image(type="pil", label="Linkage Disequilibrium Decay")
1308
  with gr.Tab("πŸ”¬ PCA"):
1309
+ img5 = gr.Image(type="pil", label="Principal Component Analysis")
 
 
1310
  with gr.Tab("βš– Effect Sizes"):
1311
+ img6 = gr.Image(type="pil", label="Effect Sizes & Volcano Plot")
 
 
1312
  with gr.Tab("πŸ“Š Dashboard"):
1313
+ img7 = gr.Image(type="pil", label="Summary Dashboard β€” All Models")
1314
+
1315
+ # Dynamically create tabs for each model
1316
+ model_tabs = {}
1317
+ for model in ALL_MODELS:
1318
+ with gr.Tabs():
1319
+ with gr.TabItem(f"πŸ“Š {model} Results", id=f"tab_{model}"):
1320
+ gr.HTML(f'<div class="model-header"><strong>{model} Model Analysis</strong> - Manhattan and QQ plots with deviation</div>')
1321
+ with gr.Row():
1322
+ with gr.Column():
1323
+ img_man = gr.Image(type="pil", label=f"{model} Manhattan Plot")
1324
+ with gr.Column():
1325
+ img_qq = gr.Image(type="pil", label=f"{model} QQ Plot (with deviation)")
1326
+ model_tabs[model] = {"manhattan": img_man, "qq": img_qq}
1327
 
1328
  def run_wrapper(f, t, m, maf):
1329
  out = run_gwas(f, t, m, maf)
1330
+ # Expected outputs: 7 main plots + excel + zip + summary + 20 per-model plots (10 models * 2)
1331
+ expected_len = 7 + 2 + 1 + 20 # 7 main + excel + zip + summary + 20 per-model
1332
+ while len(out) < expected_len:
1333
  out.append(None)
1334
  return out
1335
 
1336
  run_btn.click(
1337
  run_wrapper,
1338
  inputs=[file_in, text_in, model_sel, maf_thr],
1339
+ outputs=[img1, img2, img3, img4, img5, img6, img7, excel_out, zip_out, summary_out] +
1340
+ [model_tabs[m]["manhattan"] for m in ALL_MODELS] +
1341
+ [model_tabs[m]["qq"] for m in ALL_MODELS]
1342
  )
1343
 
1344
  if __name__ == "__main__":