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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +743 -593
app.py CHANGED
@@ -1,4 +1,9 @@
1
-
 
 
 
 
 
2
 
3
  import gradio as gr
4
  import pandas as pd
@@ -8,30 +13,37 @@ matplotlib.use("Agg")
8
  import matplotlib.pyplot as plt
9
  import matplotlib.patches as mpatches
10
  from matplotlib.colors import LinearSegmentedColormap
 
11
  import warnings
12
  warnings.filterwarnings("ignore")
13
 
14
  from scipy import stats
 
15
  from sklearn.decomposition import PCA
16
  from sklearn.preprocessing import StandardScaler
17
  from sklearn.linear_model import LinearRegression
 
 
18
  import io, re, itertools
19
  from io import StringIO
 
20
 
21
  # ─────────────────────────── PASTEL THEME ────────────────────────────
22
- BG_LIGHT = "#F9F5F0" # soft cream background
23
- PANEL_PASTEL= "#FFFFFF" # white cards
24
- ACCENT_PINK = "#E8A2A2" # soft pastel pink
25
- ACCENT_MINT = "#A8D8C9" # soft pastel mint
26
- ACCENT_LAV = "#C9B6E4" # soft lavender
27
- ACCENT_PEACH= "#F4C9B0" # soft peach
28
- ACCENT_GOLD = "#E6C8A0" # warm sand
29
- TEXT_SOFT = "#5C4B3A" # warm brown text
30
- TEXT_LIGHT = "#8B7A6B" # muted text
31
- GRID_SOFT = "#E8DFD3" # soft grid lines
 
 
 
32
 
33
  def style_fig(fig):
34
- """Apply pastel styling to matplotlib figures"""
35
  fig.patch.set_facecolor(BG_LIGHT)
36
  for ax in fig.get_axes():
37
  ax.set_facecolor(PANEL_PASTEL)
@@ -47,7 +59,7 @@ def style_fig(fig):
47
  # ─────────────────────────── DATA PARSING ─────────────────────────────
48
 
49
  def parse_data(file_obj=None, text_input=None):
50
- """Parse uploaded CSV / pasted text β†’ clean DataFrame."""
51
  raw = None
52
  if file_obj is not None:
53
  try:
@@ -62,46 +74,63 @@ def parse_data(file_obj=None, text_input=None):
62
  else:
63
  raise ValueError("No data provided.")
64
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65
  cols = list(raw.columns)
66
  id_col = cols[0]
67
  phen_col = cols[1]
68
  snp_cols = cols[2:]
69
-
 
70
  raw = raw[pd.to_numeric(raw[phen_col], errors="coerce").notna()].copy()
71
  raw[phen_col] = raw[phen_col].astype(float)
72
-
 
73
  geno = raw[snp_cols].apply(pd.to_numeric, errors="coerce")
74
- geno = geno.where(~geno.isin([-1, -9]), np.nan)
75
-
76
  df = pd.DataFrame()
77
  df["ID"] = raw[id_col].values
78
  df["Phenotype"] = raw[phen_col].values
79
  for c in snp_cols:
80
  df[c] = geno[c].values
81
-
82
- return df, snp_cols
83
-
84
-
85
- def parse_marker_info(snp_cols):
86
- """Extract chromosome and position from marker names."""
87
  chroms, positions = [], []
88
  for m in snp_cols:
89
- m_clean = str(m).strip()
90
- mat = re.match(r"[Cc]hr(\d+)[_\-](\d+)", m_clean)
91
- if mat:
92
- chroms.append(int(mat.group(1)))
93
- positions.append(int(mat.group(2)))
94
  else:
95
- num = re.findall(r"\d+", m_clean)
96
- chroms.append(int(num[0]) if num else 1)
97
- positions.append(int(num[1]) if len(num) > 1 else len(positions) + 1)
98
- return np.array(chroms), np.array(positions)
99
-
 
 
 
 
 
 
100
 
101
  # ─────────────────────────── STATISTICAL MODELS ───────────────────────
102
 
103
  def impute_genotypes(geno_matrix):
104
- """Mean imputation for missing genotype values."""
105
  mat = geno_matrix.copy().astype(float)
106
  for j in range(mat.shape[1]):
107
  col = mat[:, j]
@@ -110,16 +139,20 @@ def impute_genotypes(geno_matrix):
110
  mat[:, j] = col
111
  return mat
112
 
113
-
114
  def compute_maf(G):
115
- """Minor Allele Frequency per SNP."""
116
  freqs = np.nanmean(G, axis=0) / 2
117
  maf = np.where(freqs > 0.5, 1 - freqs, freqs)
118
  return maf
119
 
 
 
 
 
 
 
 
120
 
121
  def build_kinship(G):
122
- """VanRaden (2008) genomic relationship matrix."""
123
  p = np.nanmean(G, axis=0) / 2
124
  Z = G - 2 * p
125
  denom = 2 * np.sum(p * (1 - p))
@@ -128,9 +161,7 @@ def build_kinship(G):
128
  K = Z @ Z.T / denom
129
  return K
130
 
131
-
132
  def ols_gwas(y, G):
133
- """Model 1 β€” Ordinary Least Squares (simple linear regression)."""
134
  n, m = G.shape
135
  pvals = np.ones(m)
136
  betas = np.zeros(m)
@@ -144,9 +175,7 @@ def ols_gwas(y, G):
144
  betas[j] = slope
145
  return pvals, betas
146
 
147
-
148
  def mlm_gwas(y, G, K):
149
- """Model 2 β€” Mixed Linear Model (EMMA-like)."""
150
  n, m = G.shape
151
  pvals = np.ones(m)
152
  betas = np.zeros(m)
@@ -166,9 +195,7 @@ def mlm_gwas(y, G, K):
166
  betas[j] = slope
167
  return pvals, betas
168
 
169
-
170
  def glm_gwas(y, G):
171
- """Model 3 β€” General Linear Model with PCA correction."""
172
  n, m = G.shape
173
  pvals = np.ones(m)
174
  betas = np.zeros(m)
@@ -188,73 +215,7 @@ def glm_gwas(y, G):
188
  betas[j] = slope
189
  return pvals, betas
190
 
191
-
192
- def compressed_mlm_gwas(y, G, K):
193
- """Model 4 β€” Compressed MLM."""
194
- n, m = G.shape
195
- pvals = np.ones(m)
196
- betas = np.zeros(m)
197
- k_diag = np.diag(K)
198
- groups = pd.qcut(k_diag, q=min(3, n), labels=False, duplicates="drop")
199
- g_means = np.zeros((n, groups.max() + 1))
200
- for g in range(groups.max() + 1):
201
- idx = np.where(groups == g)[0]
202
- if len(idx):
203
- g_means[:, g] = K[:, idx].mean(axis=1)
204
- reg = LinearRegression().fit(g_means, y)
205
- y_res = y - reg.predict(g_means)
206
- for j in range(m):
207
- x = G[:, j]
208
- x_res = x - LinearRegression().fit(g_means, x).predict(g_means)
209
- if x_res.std() < 1e-8:
210
- continue
211
- slope, intercept, r, p, se = stats.linregress(x_res, y_res)
212
- pvals[j] = p
213
- betas[j] = slope
214
- return pvals, betas
215
-
216
-
217
- def blink_gwas(y, G):
218
- """Model 5 β€” BLINK-inspired."""
219
- n, m = G.shape
220
- pvals = np.ones(m)
221
- betas = np.zeros(m)
222
- ols_p, ols_b = ols_gwas(y, G)
223
- top_idx = np.argsort(ols_p)[:min(2, m)]
224
- covars = G[:, top_idx] if len(top_idx) > 0 else np.ones((n, 1))
225
- reg = LinearRegression().fit(covars, y)
226
- y_adj = y - reg.predict(covars)
227
- for j in range(m):
228
- x = G[:, j]
229
- if x.std() < 1e-8:
230
- continue
231
- slope, intercept, r, p, se = stats.linregress(x, y_adj)
232
- pvals[j] = p
233
- betas[j] = slope
234
- return pvals, betas
235
-
236
-
237
- def farm_cpu_gwas(y, G, K):
238
- """Model 6 β€” FarmCPU-inspired."""
239
- n, m = G.shape
240
- pvals = np.ones(m)
241
- betas = np.zeros(m)
242
- mlm_p, mlm_b = mlm_gwas(y, G, K)
243
- sig_idx = np.argsort(mlm_p)[:min(3, m)]
244
- pseudo = G[:, sig_idx] if len(sig_idx) else np.ones((n, 1))
245
- reg = LinearRegression().fit(pseudo, y)
246
- y_adj = y - reg.predict(pseudo)
247
- for j in range(m):
248
- x = G[:, j]
249
- if x.std() < 1e-8:
250
- continue
251
- slope, intercept, r, p, se = stats.linregress(x, y_adj)
252
- pvals[j] = p
253
- betas[j] = slope
254
- return pvals, betas
255
-
256
-
257
- # ─────────────────────────── PLOTTING FUNCTIONS ───────────────────────
258
 
259
  def fig_to_pil(fig):
260
  buf = io.BytesIO()
@@ -263,605 +224,794 @@ def fig_to_pil(fig):
263
  from PIL import Image
264
  return Image.open(buf).copy()
265
 
266
-
267
  def plot_manhattan(pvals, chroms, positions, title="Manhattan Plot"):
268
- """Pastel Manhattan plot"""
269
  fig, ax = plt.subplots(figsize=(14, 5))
270
  style_fig(fig)
271
- ax = fig.axes[0]
272
-
273
- sig_line = -np.log10(5e-8)
274
- sug_line = -np.log10(1e-5)
275
  log_p = -np.log10(np.clip(pvals, 1e-300, 1))
276
-
 
277
  chrom_list = sorted(set(chroms))
278
- palette = [ACCENT_PINK, ACCENT_MINT, ACCENT_LAV, ACCENT_PEACH, ACCENT_GOLD, "#E3B8C8", "#B8D4E3", "#D4C5E8"]
279
  chrom_colors = {c: palette[i % len(palette)] for i, c in enumerate(chrom_list)}
280
-
281
  x_offset = 0
282
- tick_pos = []
283
- tick_lab = []
284
- x_coords = np.zeros(len(pvals))
285
-
286
  for ch in chrom_list:
287
  mask = chroms == ch
288
  pos = positions[mask]
289
  order = np.argsort(pos)
290
  x_vals = pos[order] - pos.min() + x_offset
291
  x_coords[np.where(mask)[0][order]] = x_vals
292
- mid = x_vals.mean() if len(x_vals) > 1 else x_vals[0]
293
- tick_pos.append(mid)
294
  tick_lab.append(f"Chr{ch}")
295
  ax.axvspan(x_offset, x_offset + pos.max() - pos.min(), alpha=0.08, color=chrom_colors[ch])
 
296
  x_offset += (pos.max() - pos.min()) + max(positions) * 0.01
297
-
298
- for ch in chrom_list:
299
- mask = chroms == ch
300
- ax.scatter(x_coords[mask], log_p[mask], c=chrom_colors[ch], s=22, alpha=0.85, edgecolors="none", zorder=3)
301
-
302
  sig_mask = log_p >= sig_line
303
  if sig_mask.any():
304
- ax.scatter(x_coords[sig_mask], log_p[sig_mask], c=ACCENT_GOLD, s=55, zorder=5, edgecolors="white", linewidths=0.8, marker="*", label="Genome-wide significant")
305
-
306
- ax.axhline(sig_line, color=ACCENT_PINK, lw=1.5, ls="--", label="p = 5Γ—10⁻⁸")
307
- ax.axhline(sug_line, color=ACCENT_PEACH, lw=1.2, ls=":", label="p = 1Γ—10⁻⁡")
308
-
309
  ax.set_xticks(tick_pos)
310
- ax.set_xticklabels(tick_lab, fontsize=8, rotation=45)
311
- ax.set_ylabel("βˆ’log₁₀(p-value)", color=TEXT_SOFT)
312
- ax.set_title(title, fontsize=13, fontweight="bold", color=ACCENT_PINK, pad=12)
313
- ax.legend(fontsize=8, facecolor=PANEL_PASTEL, edgecolor=GRID_SOFT, labelcolor=TEXT_SOFT, loc="upper right")
314
- ax.set_xlim(0, x_offset)
315
- ax.set_ylim(0, max(log_p.max() + 0.5, sig_line + 1))
316
  fig.tight_layout()
317
  return fig
318
 
319
-
320
  def plot_qq(pvals, title="QQ Plot"):
321
- """Pastel QQ plot with confidence interval"""
322
  fig, ax = plt.subplots(figsize=(6, 6))
323
  style_fig(fig)
324
- ax = fig.axes[0]
325
-
326
  n = len(pvals)
327
  obs = np.sort(-np.log10(np.clip(pvals, 1e-300, 1)))[::-1]
328
  exp = -np.log10(np.linspace(1/n, 1, n)[::-1])
329
-
330
- ci_lower = -np.log10(stats.beta.ppf(0.975, np.arange(1, n + 1), np.arange(n, 0, -1)))
331
- ci_upper = -np.log10(stats.beta.ppf(0.025, np.arange(1, n + 1), np.arange(n, 0, -1)))
332
- idx = np.argsort(exp)
333
- ax.fill_between(exp[idx], ci_lower[idx], ci_upper[idx], alpha=0.25, color=ACCENT_MINT, label="95% CI")
334
-
335
- ax.scatter(exp, obs, c=ACCENT_LAV, s=30, edgecolors="none", alpha=0.9, zorder=4)
336
- max_val = max(exp.max(), obs.max()) + 0.3
337
- ax.plot([0, max_val], [0, max_val], color=ACCENT_PINK, lw=1.8, ls="--", label="Expected")
338
-
339
  lam = np.median(stats.chi2.ppf(1 - pvals, df=1)) / stats.chi2.ppf(0.5, df=1)
340
- ax.text(0.05, 0.92, f"Ξ» (GC) = {lam:.4f}", transform=ax.transAxes, color=ACCENT_PEACH, fontsize=11, fontweight="bold")
341
-
342
- ax.set_xlabel("Expected βˆ’log₁₀(p)", color=TEXT_SOFT)
343
- ax.set_ylabel("Observed βˆ’log₁₀(p)", color=TEXT_SOFT)
344
- ax.set_title(title, fontsize=13, fontweight="bold", color=ACCENT_PINK, pad=10)
345
- ax.legend(fontsize=9, facecolor=PANEL_PASTEL, edgecolor=GRID_SOFT, labelcolor=TEXT_SOFT)
346
  fig.tight_layout()
347
  return fig
348
 
349
-
350
- def plot_pca(G, y, sample_ids=None):
351
- """Pastel PCA plot with scree"""
352
- fig, axes = plt.subplots(1, 2, figsize=(13, 5))
353
  style_fig(fig)
354
-
355
  scaler = StandardScaler()
356
  G_sc = scaler.fit_transform(G)
357
- n_comp = min(5, G_sc.shape[0] - 1, G_sc.shape[1])
358
  pca = PCA(n_components=n_comp)
359
  pcs = pca.fit_transform(G_sc)
360
  var_exp = pca.explained_variance_ratio_ * 100
361
-
362
- pastel_cmap = LinearSegmentedColormap.from_list("pastel", [ACCENT_PINK, ACCENT_MINT, ACCENT_LAV])
363
- sc = axes[0].scatter(pcs[:, 0], pcs[:, 1], c=y, cmap=pastel_cmap, s=80, edgecolors="white", linewidths=0.5, zorder=4)
364
- cbar = fig.colorbar(sc, ax=axes[0], pad=0.02)
365
- cbar.set_label("Phenotype", color=TEXT_SOFT, fontsize=9)
366
- cbar.ax.yaxis.set_tick_params(color=TEXT_SOFT)
367
- plt.setp(cbar.ax.yaxis.get_ticklabels(), color=TEXT_SOFT)
368
-
369
- axes[0].set_xlabel(f"PC1 ({var_exp[0]:.1f}%)", color=TEXT_SOFT)
370
- axes[0].set_ylabel(f"PC2 ({var_exp[1]:.1f}%)" if n_comp > 1 else "PC2", color=TEXT_SOFT)
371
- axes[0].set_title("PCA β€” Population Structure", fontsize=12, fontweight="bold", color=ACCENT_PINK)
372
-
373
- axes[1].bar(range(1, n_comp + 1), var_exp, color=[ACCENT_PINK, ACCENT_MINT, ACCENT_LAV, ACCENT_PEACH, ACCENT_GOLD][:n_comp], edgecolor=BG_LIGHT, linewidth=0.5, zorder=3)
374
- axes[1].plot(range(1, n_comp + 1), np.cumsum(var_exp), color=ACCENT_GOLD, marker="o", ms=6, lw=2, label="Cumulative")
375
- axes[1].set_xlabel("Principal Component", color=TEXT_SOFT)
376
- axes[1].set_ylabel("Variance Explained (%)", color=TEXT_SOFT)
377
- axes[1].set_title("Scree Plot", fontsize=12, fontweight="bold", color=ACCENT_PINK)
378
- axes[1].legend(fontsize=9, facecolor=PANEL_PASTEL, edgecolor=GRID_SOFT, labelcolor=TEXT_SOFT)
379
-
 
 
 
 
 
 
 
 
 
 
 
 
380
  fig.tight_layout()
381
  return fig
382
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
383
 
384
- def plot_ld_decay(G, positions, chroms):
385
- """Pastel LD decay plot"""
386
- fig, axes = plt.subplots(1, 2, figsize=(13, 5))
387
  style_fig(fig)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
388
 
 
 
 
 
389
  m = G.shape[1]
390
  dists, r2s = [], []
391
- chrom_list = sorted(set(chroms))
392
-
393
- for ch in chrom_list:
394
- idx = np.where(chroms == ch)[0]
395
- if len(idx) < 2:
396
- continue
397
- for i, j in itertools.combinations(idx, 2):
398
- xi = G[:, i]
399
- xj = G[:, j]
400
- mask = ~(np.isnan(xi) | np.isnan(xj))
401
- if mask.sum() < 4:
402
- continue
403
- r, p = stats.pearsonr(xi[mask], xj[mask])
404
- d = abs(positions[j] - positions[i])
405
  dists.append(d)
406
- r2s.append(r ** 2)
407
-
408
- if len(dists) == 0:
409
- axes[0].text(0.5, 0.5, "Insufficient data for LD", transform=axes[0].transAxes, ha="center", color=TEXT_SOFT)
410
- axes[1].text(0.5, 0.5, "Insufficient data for LD", transform=axes[1].transAxes, ha="center", color=TEXT_SOFT)
411
- fig.tight_layout()
412
- return fig
413
-
414
- axes[0].scatter(np.array(dists) / 1000, r2s, alpha=0.4, s=18, color=ACCENT_MINT, edgecolors="none", zorder=3)
415
-
416
- n_bins = min(15, len(dists))
417
- bin_edges = np.quantile(dists, np.linspace(0, 1, n_bins + 1))
418
- bin_mid, bin_r2 = [], []
419
- for k in range(n_bins):
420
- mask = (dists >= bin_edges[k]) & (dists < bin_edges[k + 1])
421
- if mask.sum() > 0:
422
- bin_mid.append(np.mean(dists[mask]) / 1000)
423
- bin_r2.append(np.mean(r2s[mask]))
424
-
425
- axes[0].plot(bin_mid, bin_r2, color=ACCENT_PINK, lw=2.5, zorder=5, label="Mean rΒ²")
426
- axes[0].axhline(0.1, color=ACCENT_GOLD, ls=":", lw=1.5, label="rΒ² = 0.1 threshold")
427
- axes[0].set_xlabel("Distance (kb)", color=TEXT_SOFT)
428
- axes[0].set_ylabel("rΒ² (LD)", color=TEXT_SOFT)
429
- axes[0].set_title("LD Decay", fontsize=12, fontweight="bold", color=ACCENT_PINK)
430
- axes[0].set_ylim(0, 1.05)
431
- axes[0].legend(fontsize=9, facecolor=PANEL_PASTEL, edgecolor=GRID_SOFT, labelcolor=TEXT_SOFT)
432
-
433
- m2 = min(m, 20)
434
- R = np.zeros((m2, m2))
435
- for i in range(m2):
436
- for j in range(m2):
437
  if i == j:
438
- R[i, j] = 1.0
439
- continue
440
- xi = G[:, i]
441
- xj = G[:, j]
442
- mask = ~(np.isnan(xi) | np.isnan(xj))
443
- if mask.sum() < 3:
444
- continue
445
- r, _ = stats.pearsonr(xi[mask], xj[mask])
446
- R[i, j] = r ** 2
447
-
448
- pastel_ld_cmap = LinearSegmentedColormap.from_list("pastel_ld", [BG_LIGHT, ACCENT_MINT, ACCENT_PINK])
449
- im = axes[1].imshow(R, cmap=pastel_ld_cmap, vmin=0, vmax=1, aspect="auto")
450
- cbar = fig.colorbar(im, ax=axes[1], pad=0.02)
451
- cbar.set_label("rΒ²", color=TEXT_SOFT)
452
- cbar.ax.yaxis.set_tick_params(color=TEXT_SOFT)
453
- plt.setp(cbar.ax.yaxis.get_ticklabels(), color=TEXT_SOFT)
454
- axes[1].set_title("LD Heatmap (first 20 SNPs)", fontsize=12, fontweight="bold", color=ACCENT_PINK)
455
- axes[1].set_xlabel("SNP index", color=TEXT_SOFT)
456
- axes[1].set_ylabel("SNP index", color=TEXT_SOFT)
457
-
 
 
 
 
 
 
 
 
458
  fig.tight_layout()
459
  return fig
460
 
461
-
462
- def plot_effect_sizes(results_df, model_name):
463
- """Pastel effect size plot and volcano"""
464
- fig, axes = plt.subplots(1, 2, figsize=(13, 5))
465
  style_fig(fig)
466
-
467
- df = results_df.sort_values("Beta", ascending=True).reset_index(drop=True)
468
- colors = [ACCENT_LAV if b < 0 else ACCENT_MINT for b in df["Beta"]]
469
-
470
- axes[0].barh(range(len(df)), df["Beta"], color=colors, edgecolor=BG_LIGHT, linewidth=0.3, zorder=3)
471
- axes[0].axvline(0, color=TEXT_SOFT, lw=0.8)
472
- axes[0].set_yticks(range(len(df)))
473
- axes[0].set_yticklabels([s[:18] for s in df["SNP"]], fontsize=7)
474
- axes[0].set_xlabel("Effect Size (Ξ²)", color=TEXT_SOFT)
475
- axes[0].set_title(f"Effect Sizes β€” {model_name}", fontsize=11, fontweight="bold", color=ACCENT_PINK)
476
- neg_p = mpatches.Patch(color=ACCENT_LAV, label="Negative effect")
477
- pos_p = mpatches.Patch(color=ACCENT_MINT, label="Positive effect")
478
- axes[0].legend(handles=[pos_p, neg_p], fontsize=8, facecolor=PANEL_PASTEL, edgecolor=GRID_SOFT, labelcolor=TEXT_SOFT)
479
-
480
- log_p = -np.log10(np.clip(results_df["P_value"].values, 1e-300, 1))
481
- betas = results_df["Beta"].values
482
- sig_thr = -np.log10(0.05 / len(results_df))
483
- colors2 = np.where(log_p >= sig_thr, ACCENT_GOLD, np.where(betas > 0, ACCENT_MINT, ACCENT_LAV))
484
- axes[1].scatter(betas, log_p, c=colors2, s=35, edgecolors="none", alpha=0.85, zorder=4)
485
- axes[1].axhline(sig_thr, color=ACCENT_PINK, lw=1.5, ls="--", label="Bonferroni (Ξ±=0.05)")
486
- axes[1].axvline(0, color=TEXT_SOFT, lw=0.7, ls=":")
487
- axes[1].set_xlabel("Effect Size (Ξ²)", color=TEXT_SOFT)
488
- axes[1].set_ylabel("βˆ’log₁₀(p)", color=TEXT_SOFT)
489
- axes[1].set_title("Volcano Plot", fontsize=11, fontweight="bold", color=ACCENT_PINK)
490
- axes[1].legend(fontsize=9, facecolor=PANEL_PASTEL, edgecolor=GRID_SOFT, labelcolor=TEXT_SOFT)
491
-
 
 
 
 
 
 
 
 
 
 
 
 
 
492
  fig.tight_layout()
493
  return fig
494
 
495
-
496
- def plot_maf(maf, snp_names):
497
- """Pastel MAF distribution"""
498
- fig, axes = plt.subplots(1, 2, figsize=(12, 5))
499
  style_fig(fig)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
500
 
501
- axes[0].hist(maf, bins=20, color=ACCENT_MINT, edgecolor=BG_LIGHT, linewidth=0.5, zorder=3)
502
- axes[0].axvline(0.05, color=ACCENT_PINK, lw=1.8, ls="--", label="MAF = 0.05")
503
- axes[0].set_xlabel("Minor Allele Frequency", color=TEXT_SOFT)
504
- axes[0].set_ylabel("Count", color=TEXT_SOFT)
505
- axes[0].set_title("MAF Distribution", fontsize=12, fontweight="bold", color=ACCENT_PINK)
506
- axes[0].legend(fontsize=9, facecolor=PANEL_PASTEL, edgecolor=GRID_SOFT, labelcolor=TEXT_SOFT)
507
-
508
- order = np.argsort(maf)[::-1]
509
- bar_c = [ACCENT_MINT if m >= 0.05 else ACCENT_LAV for m in maf[order]]
510
- axes[1].bar(range(len(maf)), maf[order], color=bar_c, edgecolor=BG_LIGHT, linewidth=0.3, zorder=3)
511
- axes[1].axhline(0.05, color=ACCENT_GOLD, lw=1.5, ls=":", label="MAF threshold 0.05")
512
- axes[1].set_xticks(range(len(maf)))
513
- axes[1].set_xticklabels([snp_names[i][:12] for i in order], rotation=90, fontsize=6)
514
- axes[1].set_ylabel("MAF", color=TEXT_SOFT)
515
- axes[1].set_title("Per-SNP MAF", fontsize=12, fontweight="bold", color=ACCENT_PINK)
516
- axes[1].legend(fontsize=9, facecolor=PANEL_PASTEL, edgecolor=GRID_SOFT, labelcolor=TEXT_SOFT)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
517
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
518
  fig.tight_layout()
519
  return fig
520
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
521
 
522
- def plot_phenotype(y, sample_ids=None):
523
- """Pastel phenotype distribution"""
524
- fig, axes = plt.subplots(1, 2, figsize=(12, 5))
525
  style_fig(fig)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
526
 
527
- axes[0].hist(y, bins=15, color=ACCENT_LAV, edgecolor=BG_LIGHT, linewidth=0.5, zorder=3, alpha=0.85)
528
- mn, sd = y.mean(), y.std()
529
- axes[0].axvline(mn, color=ACCENT_PINK, lw=1.8, ls="--", label=f"Mean = {mn:.2f}")
530
- axes[0].axvline(mn - sd, color=ACCENT_GOLD, lw=1.2, ls=":", label=f"Β±1 SD")
531
- axes[0].axvline(mn + sd, color=ACCENT_GOLD, lw=1.2, ls=":")
532
- axes[0].set_xlabel("Phenotype Value", color=TEXT_SOFT)
533
- axes[0].set_ylabel("Frequency", color=TEXT_SOFT)
534
- axes[0].set_title("Phenotype Distribution", fontsize=12, fontweight="bold", color=ACCENT_PINK)
535
- axes[0].legend(fontsize=9, facecolor=PANEL_PASTEL, edgecolor=GRID_SOFT, labelcolor=TEXT_SOFT)
536
-
537
- bp = axes[1].boxplot(y, vert=True, patch_artist=True, medianprops=dict(color=ACCENT_PINK, lw=2))
538
- for patch in bp["boxes"]:
539
- patch.set_facecolor(ACCENT_MINT + "55")
540
- patch.set_edgecolor(ACCENT_MINT)
541
- jitter = np.random.uniform(-0.1, 0.1, size=len(y))
542
- axes[1].scatter(1 + jitter, y, color=ACCENT_GOLD, s=30, alpha=0.8, zorder=5, edgecolors="none")
543
- axes[1].set_xticks([1])
544
- axes[1].set_xticklabels(["Phenotype"])
545
- axes[1].set_ylabel("Value", color=TEXT_SOFT)
546
- axes[1].set_title("Box Plot", fontsize=12, fontweight="bold", color=ACCENT_PINK)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
547
  fig.tight_layout()
548
  return fig
549
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
550
 
551
- def make_results_table(pvals, betas, snp_names, chroms, positions, model_name):
552
- """Create formatted results table"""
553
- bonferroni = 0.05 / len(pvals)
554
- df = pd.DataFrame({
555
- "SNP": snp_names,
556
- "Chr": chroms,
557
- "Pos": positions,
558
- "Beta": np.round(betas, 5),
559
- "P_value": pvals,
560
- "-log10P": np.round(-np.log10(np.clip(pvals, 1e-300, 1)), 4),
561
- "Sig": ["***" if p < bonferroni else ("**" if p < 0.001 else ("*" if p < 0.05 else "")) for p in pvals],
562
- }).sort_values("P_value").reset_index(drop=True)
563
- return df
 
 
 
 
 
 
 
 
 
 
 
 
 
 
564
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
565
 
566
  # ─────────────────────────── MAIN PIPELINE ────────────────────────────
567
 
568
  def run_gwas(file_obj, text_input, selected_models, maf_threshold):
569
- """Master function called by Gradio."""
570
  try:
571
- df, snp_cols = parse_data(file_obj, text_input)
572
  except Exception as e:
573
- return [None] * 12 + [f"❌ Data parsing error: {e}"]
574
-
575
  y = df["Phenotype"].values.astype(float)
576
  ids = df["ID"].values
577
  G_raw = df[snp_cols].values.astype(float)
578
  G = impute_genotypes(G_raw)
579
  n, m = G.shape
580
-
581
- chroms, positions = parse_marker_info(snp_cols)
582
  maf_vals = compute_maf(G)
583
-
584
  maf_thr = float(maf_threshold)
585
  keep = maf_vals >= maf_thr
586
  if keep.sum() < 2:
587
  keep = np.ones(m, dtype=bool)
 
588
  G_filt = G[:, keep]
589
- maf_filt = maf_vals[keep]
590
  snp_filt = np.array(snp_cols)[keep]
591
- chr_filt = chroms[keep]
592
- pos_filt = positions[keep]
593
-
 
 
 
 
594
  K = build_kinship(G_filt)
595
-
596
  model_funcs = {
597
- "OLS (Simple Linear Regression)": lambda: ols_gwas(y, G_filt),
598
- "MLM (Mixed Linear Model)": lambda: mlm_gwas(y, G_filt, K),
599
- "GLM (PCA-corrected)": lambda: glm_gwas(y, G_filt),
600
- "Compressed MLM": lambda: compressed_mlm_gwas(y, G_filt, K),
601
- "BLINK": lambda: blink_gwas(y, G_filt),
602
- "FarmCPU": lambda: farm_cpu_gwas(y, G_filt, K),
603
  }
604
-
605
  models_to_run = selected_models if selected_models else list(model_funcs.keys())
606
-
607
  all_results = {}
608
  primary_p = None
609
  primary_b = None
610
- primary_name = None
611
-
612
  for mname in models_to_run:
613
  if mname in model_funcs:
614
  p, b = model_funcs[mname]()
615
  all_results[mname] = (p, b)
616
  if primary_p is None:
617
- primary_p = p
618
- primary_b = b
619
- primary_name = mname
620
-
621
  if primary_p is None:
622
- return [None] * 12 + ["❌ No models selected or run."]
623
-
624
- fig_pheno = plot_phenotype(y, ids)
625
- fig_maf = plot_maf(maf_vals, snp_cols)
626
- fig_pca = plot_pca(G_filt, y, ids)
627
- fig_ld = plot_ld_decay(G_filt, pos_filt, chr_filt)
628
- fig_manh = plot_manhattan(primary_p, chr_filt, pos_filt, title=f"Manhattan β€” {primary_name}")
629
- fig_qq = plot_qq(primary_p, title=f"QQ Plot β€” {primary_name}")
630
-
631
- res_df = make_results_table(primary_p, primary_b, snp_filt, chr_filt, pos_filt, primary_name)
632
- fig_eff = plot_effect_sizes(res_df, primary_name)
633
-
634
- fig_multi = None
635
- if len(all_results) > 1:
636
- fig_multi, ax = plt.subplots(figsize=(8, 6))
637
- style_fig(fig_multi)
638
- ax = fig_multi.axes[0]
639
- colors_m = [ACCENT_PINK, ACCENT_MINT, ACCENT_LAV, ACCENT_PEACH, ACCENT_GOLD, "#D4C5E8"]
640
- for idx2, (mn, (p2, _)) in enumerate(all_results.items()):
641
- n2 = len(p2)
642
- obs2 = np.sort(-np.log10(np.clip(p2, 1e-300, 1)))[::-1]
643
- exp2 = -np.log10(np.linspace(1/n2, 1, n2)[::-1])
644
- ax.plot(np.sort(exp2), np.sort(obs2), color=colors_m[idx2 % len(colors_m)], lw=1.8, label=mn[:28], alpha=0.9)
645
- ax.plot([0, obs2.max()], [0, obs2.max()], color=TEXT_SOFT, lw=1, ls="--")
646
- ax.set_xlabel("Expected βˆ’log₁₀(p)", color=TEXT_SOFT)
647
- ax.set_ylabel("Observed βˆ’log₁₀(p)", color=TEXT_SOFT)
648
- ax.set_title("Multi-Model QQ Comparison", fontsize=12, fontweight="bold", color=ACCENT_PINK)
649
- ax.legend(fontsize=7, facecolor=PANEL_PASTEL, edgecolor=GRID_SOFT, labelcolor=TEXT_SOFT)
650
- fig_multi.tight_layout()
651
-
 
 
 
 
 
 
 
 
 
 
 
 
 
652
  bonf = 0.05 / len(primary_p)
653
- n_sig = (primary_p < bonf).sum()
654
- n_sug = ((primary_p < 1e-5) & (primary_p >= bonf)).sum()
 
 
 
 
 
 
 
 
655
  lam = np.median(stats.chi2.ppf(1 - np.clip(primary_p, 1e-10, 1), df=1)) / stats.chi2.ppf(0.5, df=1)
656
-
657
  summary = f"""
658
- ╔══════════════════════════════════════════════════════════════════════╗
659
- β•‘ 🌸 GWAS ANALYSIS SUMMARY 🌸 β•‘
660
- ╠══════════════════════════════════════════════════════════════════════╣
661
- β•‘ Samples : {n} β•‘
662
- β•‘ SNPs (raw) : {m} β•‘
663
- β•‘ SNPs (after MAF β‰₯ {maf_thr:.2f}) : {G_filt.shape[1]} β•‘
664
- β•‘ Models run : {', '.join(all_results.keys())} β•‘
665
- β•‘ Primary model : {primary_name} β•‘
666
- β•‘ β•‘
667
- β•‘ Bonferroni threshold : {bonf:.2e} β•‘
668
- β•‘ Genome-wide significant : {n_sig} β•‘
669
- β•‘ Suggestive hits : {n_sug} β•‘
670
- β•‘ Genomic inflation Ξ» : {lam:.4f} β•‘
671
- β•‘ β•‘
672
- β•‘ πŸ† Top 5 SNPs ({primary_name}): β•‘
673
- {res_df[['SNP', 'Chr', 'Pos', 'Beta', 'P_value', 'Sig']].head(5).to_string(index=False)}
674
- β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•
675
- """.strip()
676
-
677
- img_pheno = fig_to_pil(fig_pheno)
678
- img_maf = fig_to_pil(fig_maf)
679
- img_pca = fig_to_pil(fig_pca)
680
- img_ld = fig_to_pil(fig_ld)
681
- img_manh = fig_to_pil(fig_manh)
682
- img_qq = fig_to_pil(fig_qq)
683
- img_eff = fig_to_pil(fig_eff)
684
- img_multi = fig_to_pil(fig_multi) if fig_multi else None
685
-
686
- plt.close("all")
687
-
688
- return (img_pheno, img_maf, img_pca, img_ld, img_manh, img_qq, img_eff, img_multi, res_df, summary)
689
-
690
-
691
- # ─────────────────────────── PASTEL GRADIO UI ─────────────────────────
692
-
693
- SAMPLE_DATA = """\
694
- ID,Phenotype,chr1_134521_SNP1,chr1_134810_SNP2,chr1_178766_SNP3,chr1_210328_SNP4,chr1_216213_SNP5,chr1_216683_SNP6,chr1_216716_SNP7,chr1_216965_SNP8
695
- IRRI-1,25.34,0,0,0,2,2,-1,0,0
696
- IRRI-75,23.34,0,0,0,0,0,-1,-1,0
697
- IRRI-84,26.67,2,0,2,0,0,-1,-1,0
698
- IRRI-93,23.00,0,0,0,1,0,-1,0,2
699
- IRRI-9,28.34,0,0,0,0,0,2,0,0
700
- IRRI-17,18.67,0,0,0,0,0,2,0,0
701
- IRRI-25,20.00,2,0,2,0,0,-1,-1,0
702
- IRRI-34,37.00,0,0,0,0,0,2,0,0
703
- IRRI-42,30.67,0,0,0,0,0,2,0,0
704
- IRRI-50,22.00,0,0,0,2,2,-1,0,0
705
  """
 
 
 
 
 
 
 
 
 
 
 
 
706
 
707
  PASTEL_CSS = """
708
- body, .gradio-container {
709
- background: #F9F5F0 !important;
710
- font-family: 'Inter', 'Segoe UI', sans-serif !important;
711
- color: #5C4B3A !important;
712
- }
713
- .gr-panel, .gr-box, .gr-form {
714
- background: #FFFFFF !important;
715
- border: 1px solid #E8DFD3 !important;
716
- border-radius: 20px !important;
717
- box-shadow: 0 4px 12px rgba(0,0,0,0.03) !important;
718
- }
719
- h1, h2, h3, .gr-markdown h1, .gr-markdown h2 {
720
- color: #E8A2A2 !important;
721
- font-weight: 600 !important;
722
- }
723
- label, .gr-form label {
724
- color: #8B7A6B !important;
725
- font-size: 0.85rem !important;
726
- font-weight: 500 !important;
727
- }
728
- .gr-button-primary {
729
- background: linear-gradient(135deg, #E8A2A2, #C9B6E4) !important;
730
- color: #5C4B3A !important;
731
- font-weight: 600 !important;
732
- border: none !important;
733
- border-radius: 40px !important;
734
- padding: 10px 24px !important;
735
- transition: all 0.2s ease !important;
736
- }
737
- .gr-button-primary:hover {
738
- transform: translateY(-2px) !important;
739
- box-shadow: 0 8px 20px rgba(232, 162, 162, 0.3) !important;
740
- }
741
- .gr-button-secondary {
742
- background: #F4F0EA !important;
743
- color: #8B7A6B !important;
744
- border: 1px solid #E8DFD3 !important;
745
- border-radius: 40px !important;
746
- }
747
- textarea, input[type=text], input[type=number], .gr-textbox textarea {
748
- background: #FEFCF8 !important;
749
- color: #5C4B3A !important;
750
- border: 1px solid #E8DFD3 !important;
751
- border-radius: 16px !important;
752
- font-family: monospace !important;
753
- }
754
- .gr-check-radio {
755
- accent-color: #A8D8C9 !important;
756
- }
757
- .gr-tabs {
758
- background: transparent !important;
759
- }
760
- button.tab-nav {
761
- background: #F4F0EA !important;
762
- border-radius: 40px !important;
763
- color: #8B7A6B !important;
764
- }
765
- button.tab-nav.selected {
766
- background: #E8A2A2 !important;
767
- color: white !important;
768
- }
769
- .gr-dataframe, .dataframe {
770
- background: #FEFCF8 !important;
771
- border-radius: 16px !important;
772
- }
773
- footer {
774
- display: none !important;
775
- }
776
  """
777
 
778
- MODELS = [
779
- "OLS (Simple Linear Regression)",
780
- "MLM (Mixed Linear Model)",
781
- "GLM (PCA-corrected)",
782
- "Compressed MLM",
783
- "BLINK",
784
- "FarmCPU",
785
- ]
786
-
787
- with gr.Blocks(css=PASTEL_CSS, title="🌸 Pastel GWAS Pipeline", theme=gr.themes.Soft()) as demo:
788
 
 
789
  gr.Markdown("""
790
- # 🌸 Pastel GWAS Studio
791
- ### Genome-Wide Association Study β€” Full Statistical Suite
792
- *6 advanced models Β· Publication-quality plots Β· Soft & intuitive interface*
793
- ---
794
  """)
795
-
796
  with gr.Row():
797
  with gr.Column(scale=1):
798
- gr.Markdown("### πŸ“ β‘  Input Data")
799
- file_in = gr.File(label="Upload CSV/TSV file", file_types=[".csv", ".tsv", ".txt"])
800
- text_in = gr.Textbox(label="Or paste CSV data here", placeholder="Paste your CSV…", lines=6, value=SAMPLE_DATA)
801
-
802
- gr.Markdown("### 🧬 β‘‘ Models to Run")
803
- model_sel = gr.CheckboxGroup(choices=MODELS, value=MODELS, label="Select statistical models")
804
-
805
- gr.Markdown("### βš™οΈ β‘’ Filters")
806
- maf_thr = gr.Slider(minimum=0.0, maximum=0.5, value=0.05, step=0.01, label="MAF threshold")
807
-
808
- with gr.Row():
809
- run_btn = gr.Button("πŸš€ Run GWAS", variant="primary", size="lg")
810
- clr_btn = gr.Button("πŸ—‘ Clear", variant="secondary", size="lg")
811
-
812
- with gr.Column(scale=3):
813
- gr.Markdown("### πŸ“Š Analysis Summary")
814
- summary_out = gr.Textbox(label="", lines=18, interactive=False)
815
-
816
- gr.Markdown("---")
817
-
818
  with gr.Tabs():
819
- with gr.Tab("πŸ§ͺ Phenotype"):
820
- img_pheno = gr.Image(label="Phenotype Distribution", type="pil", height=400)
821
- with gr.Tab("πŸ“‰ MAF"):
822
- img_maf = gr.Image(label="Minor Allele Frequency", type="pil", height=400)
823
- with gr.Tab("πŸ”΅ PCA"):
824
- img_pca = gr.Image(label="Principal Component Analysis", type="pil", height=400)
825
- with gr.Tab("πŸ”— LD"):
826
- img_ld = gr.Image(label="Linkage Disequilibrium", type="pil", height=400)
827
- with gr.Tab("πŸ” Manhattan"):
828
- img_manh = gr.Image(label="Manhattan Plot", type="pil", height=450)
829
- with gr.Tab("πŸ“ˆ QQ Plot"):
830
- img_qq = gr.Image(label="QQ Plot", type="pil", height=450)
831
- with gr.Tab("βš– Effect Sizes"):
832
- img_eff = gr.Image(label="Effect Sizes & Volcano", type="pil", height=400)
833
- with gr.Tab("πŸ”€ Multi-Model QQ"):
834
- img_multi = gr.Image(label="Multi-Model Comparison", type="pil", height=450)
835
- with gr.Tab("πŸ“‹ Top Hits Table"):
836
- results_tbl = gr.Dataframe(label="GWAS Results (sorted by p-value)", interactive=False)
837
-
838
  def run_wrapper(f, t, m, maf):
839
  out = run_gwas(f, t, m, maf)
840
- if isinstance(out[-1], str) and out[-1].startswith("❌"):
841
- return [None] * 8 + [None, out[-1]]
842
- ph, mf, pc, ld, mn, qq, ef, mu, df_tbl, summ = out
843
- return ph, mf, pc, ld, mn, qq, ef, mu, df_tbl, summ
844
-
845
- run_btn.click(
846
- fn=run_wrapper,
847
- inputs=[file_in, text_in, model_sel, maf_thr],
848
- outputs=[img_pheno, img_maf, img_pca, img_ld, img_manh, img_qq, img_eff, img_multi, results_tbl, summary_out],
849
- )
850
-
851
- def clear_all():
852
- return [None] * 9 + [""]
853
-
854
- clr_btn.click(
855
- fn=clear_all,
856
- outputs=[img_pheno, img_maf, img_pca, img_ld, img_manh, img_qq, img_eff, img_multi, results_tbl, summary_out],
857
- )
858
-
859
- gr.Markdown("""
860
- ---
861
- **✨ Statistical models:** OLS · Mixed Linear Model (MLM) · PCA-corrected GLM · Compressed MLM · BLINK · FarmCPU
862
- **πŸ“Š Visualizations:** Phenotype distribution Β· MAF histogram Β· PCA + Scree Β· LD Decay + Heatmap Β· Manhattan Β· QQ Β· Effect sizes Β· Volcano Β· Multi-model QQ
863
- **🎨 Pastel design:** Soft, eye-friendly interface for comfortable genomic analysis
864
- """)
865
 
866
  if __name__ == "__main__":
867
  demo.launch(share=False, server_port=7860)
 
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
 
13
  import matplotlib.pyplot as plt
14
  import matplotlib.patches as mpatches
15
  from matplotlib.colors import LinearSegmentedColormap
16
+ from matplotlib.patches import Ellipse
17
  import warnings
18
  warnings.filterwarnings("ignore")
19
 
20
  from scipy import stats
21
+ from scipy.cluster.hierarchy import dendrogram, linkage
22
  from sklearn.decomposition import PCA
23
  from sklearn.preprocessing import StandardScaler
24
  from sklearn.linear_model import LinearRegression
25
+ from sklearn.manifold import MDS, TSNE
26
+ from scipy.spatial.distance import pdist
27
  import io, re, itertools
28
  from io import StringIO
29
+ from statsmodels.stats.multitest import multipletests
30
 
31
  # ─────────────────────────── PASTEL THEME ────────────────────────────
32
+ BG_LIGHT = "#F9F5F0"
33
+ PANEL_PASTEL= "#FFFFFF"
34
+ ACCENT_PINK = "#E8A2A2"
35
+ ACCENT_MINT = "#A8D8C9"
36
+ ACCENT_LAV = "#C9B6E4"
37
+ ACCENT_PEACH= "#F4C9B0"
38
+ ACCENT_GOLD = "#E6C8A0"
39
+ ACCENT_CORAL= "#F0B8A8"
40
+ ACCENT_SAGE = "#B8C9A8"
41
+ ACCENT_BLUE = "#B8D4E3"
42
+ TEXT_SOFT = "#5C4B3A"
43
+ TEXT_LIGHT = "#8B7A6B"
44
+ GRID_SOFT = "#E8DFD3"
45
 
46
  def style_fig(fig):
 
47
  fig.patch.set_facecolor(BG_LIGHT)
48
  for ax in fig.get_axes():
49
  ax.set_facecolor(PANEL_PASTEL)
 
59
  # ─────────────────────────── DATA PARSING ─────────────────────────────
60
 
61
  def parse_data(file_obj=None, text_input=None):
62
+ """Parse uploaded CSV with optional chromosome row."""
63
  raw = None
64
  if file_obj is not None:
65
  try:
 
74
  else:
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)
95
  id_col = cols[0]
96
  phen_col = cols[1]
97
  snp_cols = cols[2:]
98
+
99
+ # Clean data
100
  raw = raw[pd.to_numeric(raw[phen_col], errors="coerce").notna()].copy()
101
  raw[phen_col] = raw[phen_col].astype(float)
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
109
  df["Phenotype"] = raw[phen_col].values
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)
121
+ if mat:
122
+ chroms.append(int(mat.group(1)))
123
+ positions.append(int(mat.group(2)))
124
+ else:
125
+ num = re.findall(r"\d+", m_clean)
126
+ chroms.append(int(num[0]) if num else 1)
127
+ positions.append(int(num[1]) if len(num) > 1 else len(positions) + 1)
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)
135
  for j in range(mat.shape[1]):
136
  col = mat[:, j]
 
139
  mat[:, j] = col
140
  return mat
141
 
 
142
  def compute_maf(G):
 
143
  freqs = np.nanmean(G, axis=0) / 2
144
  maf = np.where(freqs > 0.5, 1 - freqs, freqs)
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):
 
156
  p = np.nanmean(G, axis=0) / 2
157
  Z = G - 2 * p
158
  denom = 2 * np.sum(p * (1 - p))
 
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)
167
  betas = np.zeros(m)
 
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)
181
  betas = np.zeros(m)
 
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)
 
215
  betas[j] = slope
216
  return pvals, betas
217
 
218
+ # ─────────────────────────── 15+ PLOTTING FUNCTIONS ───────────────────
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
219
 
220
  def fig_to_pil(fig):
221
  buf = io.BytesIO()
 
224
  from PIL import Image
225
  return Image.open(buf).copy()
226
 
 
227
  def plot_manhattan(pvals, chroms, positions, title="Manhattan Plot"):
 
228
  fig, ax = plt.subplots(figsize=(14, 5))
229
  style_fig(fig)
 
 
 
 
230
  log_p = -np.log10(np.clip(pvals, 1e-300, 1))
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
238
+ tick_pos, tick_lab, x_coords = [], [], np.zeros(len(pvals))
239
+
 
 
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
246
+ tick_pos.append(x_vals.mean())
 
247
  tick_lab.append(f"Chr{ch}")
248
  ax.axvspan(x_offset, x_offset + pos.max() - pos.min(), alpha=0.08, color=chrom_colors[ch])
249
+ ax.scatter(x_coords[mask], log_p[mask], c=chrom_colors[ch], s=20, alpha=0.8)
250
  x_offset += (pos.max() - pos.min()) + max(positions) * 0.01
251
+
 
 
 
 
252
  sig_mask = log_p >= sig_line
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)")
260
+ ax.set_title(title)
261
+ ax.legend()
 
 
262
  fig.tight_layout()
263
  return fig
264
 
 
265
  def plot_qq(pvals, title="QQ Plot"):
 
266
  fig, ax = plt.subplots(figsize=(6, 6))
267
  style_fig(fig)
 
 
268
  n = len(pvals)
269
  obs = np.sort(-np.log10(np.clip(pvals, 1e-300, 1)))[::-1]
270
  exp = -np.log10(np.linspace(1/n, 1, n)[::-1])
271
+
272
+ ci_lower = -np.log10(stats.beta.ppf(0.975, np.arange(1, n+1), np.arange(n, 0, -1)))
273
+ ci_upper = -np.log10(stats.beta.ppf(0.025, np.arange(1, n+1), np.arange(n, 0, -1)))
274
+ ax.fill_between(exp, ci_lower, ci_upper, alpha=0.25, color=ACCENT_MINT, label="95% CI")
275
+ ax.scatter(exp, obs, c=ACCENT_LAV, s=25, alpha=0.8)
276
+ ax.plot([0, max(exp)], [0, max(exp)], color=ACCENT_PINK, ls="--", lw=1.5)
277
+
 
 
 
278
  lam = np.median(stats.chi2.ppf(1 - pvals, df=1)) / stats.chi2.ppf(0.5, df=1)
279
+ ax.text(0.05, 0.92, f"Ξ» = {lam:.4f}", transform=ax.transAxes, fontsize=11)
280
+ ax.set_xlabel("Expected -log10(p)")
281
+ ax.set_ylabel("Observed -log10(p)")
282
+ ax.set_title(title)
 
 
283
  fig.tight_layout()
284
  return fig
285
 
286
+ def plot_pca(G, y, ids):
287
+ fig, axes = plt.subplots(2, 2, figsize=(14, 12))
 
 
288
  style_fig(fig)
289
+
290
  scaler = StandardScaler()
291
  G_sc = scaler.fit_transform(G)
292
+ n_comp = min(5, G_sc.shape[0]-1, G_sc.shape[1])
293
  pca = PCA(n_components=n_comp)
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}%)")
308
+ axes[0,1].set_ylabel(f"PC4 ({var_exp[3]:.1f}%)")
309
+ axes[0,1].set_title("PCA: PC3 vs PC4")
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")
317
+ axes[1,0].set_ylabel("Variance Explained (%)")
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}%)")
325
+ axes[1,1].set_title("Population Structure")
326
+
327
  fig.tight_layout()
328
  return fig
329
 
330
+ 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")
338
+ axes[0,0].axvline(y.mean() - y.std(), color=ACCENT_GOLD, lw=1.5, ls=':')
339
+ axes[0,0].set_xlabel("Phenotype")
340
+ axes[0,0].set_ylabel("Frequency")
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)
348
+ patch.set_edgecolor(ACCENT_PINK)
349
+ axes[0,1].set_xticklabels(['Phenotype'])
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)
363
+ axes[1,1].plot(x_dense, kde(x_dense), color=ACCENT_PINK, lw=2)
364
+ axes[1,1].set_xlabel("Phenotype")
365
+ axes[1,1].set_ylabel("Density")
366
+ axes[1,1].set_title("Density Plot")
367
+
368
+ fig.tight_layout()
369
+ return fig
370
 
371
+ 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")
379
+ axes[0,0].set_ylabel("Count")
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])
387
+ axes[0,1].axhline(0.05, color=ACCENT_PINK, ls='--', lw=1.5)
388
+ axes[0,1].set_xlabel("SNP Index")
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()
402
+ return fig
403
 
404
+ def plot_ld_analysis(G, positions, chroms):
405
+ fig, axes = plt.subplots(2, 2, figsize=(14, 12))
406
+ style_fig(fig)
407
+
408
  m = G.shape[1]
409
  dists, r2s = [], []
410
+
411
+ # Sample LD pairs
412
+ n_samples = min(500, m*(m-1)//2)
413
+ sampled_pairs = []
414
+ for i in range(min(50, m)):
415
+ for j in range(i+1, min(50, m)):
416
+ sampled_pairs.append((i, j))
417
+
418
+ for i, j in sampled_pairs:
419
+ xi, xj = G[:, i], G[:, j]
420
+ mask = ~(np.isnan(xi) | np.isnan(xj))
421
+ if mask.sum() >= 4:
422
+ r, _ = stats.pearsonr(xi[mask], xj[mask])
423
+ d = abs(positions[j] - positions[i]) if len(positions) > max(i,j) else 0
424
  dists.append(d)
425
+ r2s.append(r**2)
426
+
427
+ if len(dists) > 0:
428
+ axes[0,0].scatter(np.array(dists)/1000, r2s, alpha=0.5, s=20, color=ACCENT_MINT)
429
+ axes[0,0].set_xlabel("Distance (kb)")
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):
437
+ mask = (dists >= bins[k]) & (dists < bins[k+1])
438
+ if mask.sum() > 0:
439
+ bin_centers.append((bins[k] + bins[k+1])/2/1000)
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):
447
+ for j in range(m_sub):
 
 
 
 
 
 
 
 
448
  if i == j:
449
+ R[i,j] = 1
450
+ else:
451
+ xi, xj = G[:, i], G[:, j]
452
+ mask = ~(np.isnan(xi) | np.isnan(xj))
453
+ if mask.sum() >= 3:
454
+ r, _ = stats.pearsonr(xi[mask], xj[mask])
455
+ R[i,j] = r**2
456
+
457
+ im = axes[0,1].imshow(R, cmap='RdYlBu_r', vmin=0, vmax=1, aspect='auto')
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)
471
+ axes[1,1].scatter(dists_kb, r2s_arr, alpha=0.3, s=15, color=ACCENT_MINT)
472
+ axes[1,1].set_xlabel("Distance (kb)")
473
+ axes[1,1].set_ylabel("rΒ²")
474
+ axes[1,1].set_title("LD Decay Scatter")
475
+ axes[1,1].set_ylim(0, 1)
476
+
477
  fig.tight_layout()
478
  return fig
479
 
480
+ 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]
488
+ colors = [ACCENT_PINK if b < 0 else ACCENT_MINT for b in top_betas]
489
+
490
+ axes[0,0].barh(range(len(top_betas)), top_betas, color=colors)
491
+ axes[0,0].axvline(0, color='black', lw=0.5)
492
+ axes[0,0].set_yticks(range(len(top_betas)))
493
+ axes[0,0].set_yticklabels(top_names, fontsize=8)
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))
501
+ axes[0,1].scatter(betas, log_p, c=colors_v, s=30, alpha=0.7)
502
+ axes[0,1].axhline(sig_thr, color=ACCENT_PINK, ls='--', lw=1.5, label="Bonferroni")
503
+ axes[0,1].axvline(0, color='black', lw=0.5)
504
+ axes[0,1].set_xlabel("Effect Size (Ξ²)")
505
+ axes[0,1].set_ylabel("-log10(p)")
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)")
520
+ axes[1,1].set_title("Effect Size vs Significance")
521
+
522
  fig.tight_layout()
523
  return fig
524
 
525
+ def plot_heterozygosity(G, y, ids):
526
+ fig, axes = plt.subplots(2, 2, figsize=(14, 10))
 
 
527
  style_fig(fig)
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)))
547
+ axes[1,0].set_yticklabels([ids[i][:10] for i in top_idx], fontsize=8)
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]
555
+ axes[1,1].boxplot([low_group, high_group], labels=['Low Phenotype', 'High Phenotype'])
556
+ axes[1,1].set_ylabel("Heterozygosity")
557
+ axes[1,1].set_title("Heterozygosity by Phenotype Group")
558
+
559
+ fig.tight_layout()
560
+ return fig
561
 
562
+ def plot_call_rate_analysis(G, snp_names):
563
+ fig, axes = plt.subplots(2, 2, figsize=(14, 10))
564
+ style_fig(fig)
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")
572
+ axes[0,0].set_ylabel("Count")
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)
580
+ axes[0,1].fill_between(range(len(call_rate)), 0, call_rate[order], alpha=0.3, color=ACCENT_MINT)
581
+ axes[0,1].set_xlabel("SNP Index (sorted)")
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()
600
+ return fig
601
 
602
+ 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')
628
+ axes[1,1].set_xlabel("PC1")
629
+ axes[1,1].set_ylabel("PC2")
630
+ axes[1,1].set_title("Kinship PCA")
631
+
632
  fig.tight_layout()
633
  return fig
634
 
635
+ 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
+
645
+ sc = axes[0].scatter(mds_coords[:, 0], mds_coords[:, 1], c=y, cmap='coolwarm', s=60, edgecolors='white')
646
+ axes[0].set_xlabel("MDS Dimension 1")
647
+ axes[0].set_ylabel("MDS Dimension 2")
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')
656
+ axes[1].set_xlabel("t-SNE Dimension 1")
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
666
 
667
+ def plot_manhattan_by_chromosome(pvals, chroms, positions):
668
+ fig, axes = plt.subplots(2, 3, figsize=(15, 10))
 
669
  style_fig(fig)
670
+ axes = axes.flatten()
671
+
672
+ log_p = -np.log10(np.clip(pvals, 1e-300, 1))
673
+ unique_chroms = sorted(set(chroms))
674
+
675
+ for i, ch in enumerate(unique_chroms[:6]):
676
+ mask = chroms == ch
677
+ if mask.sum() > 0:
678
+ axes[i].scatter(positions[mask], log_p[mask], c=ACCENT_MINT, s=15, alpha=0.7)
679
+ axes[i].axhline(-np.log10(5e-8), color=ACCENT_PINK, ls='--', lw=1)
680
+ axes[i].set_xlabel(f"Chromosome {ch} Position")
681
+ axes[i].set_ylabel("-log10(p)")
682
+ axes[i].set_title(f"Chromosome {ch}")
683
+
684
+ for i in range(len(unique_chroms), 6):
685
+ axes[i].set_visible(False)
686
+
687
+ fig.tight_layout()
688
+ return fig
689
 
690
+ def plot_manhattan_qq_combined(pvals, chroms, positions):
691
+ fig = plt.figure(figsize=(14, 10))
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)
699
+ ax1.axhline(-np.log10(5e-8), color=ACCENT_PINK, ls='--', lw=1.5, label="Bonferroni")
700
+ ax1.set_xlabel("SNP Index")
701
+ ax1.set_ylabel("-log10(p)")
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]
709
+ exp = -np.log10(np.linspace(1/n, 1, n)[::-1])
710
+ ax2.scatter(exp, obs, c=ACCENT_LAV, s=15, alpha=0.7)
711
+ ax2.plot([0, max(exp)], [0, max(exp)], color=ACCENT_PINK, ls='--', lw=1.5)
712
+ ax2.set_xlabel("Expected -log10(p)")
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)
720
+ ax3.set_xlabel("p-value")
721
+ ax3.set_ylabel("Frequency")
722
+ ax3.set_title("P-value Distribution")
723
+
724
  fig.tight_layout()
725
  return fig
726
 
727
+ def plot_manhattan_stacked(pvals, chroms, positions):
728
+ fig, ax = plt.subplots(figsize=(14, 6))
729
+ style_fig(fig)
730
+
731
+ log_p = -np.log10(np.clip(pvals, 1e-300, 1))
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:
740
+ x_vals = np.arange(mask.sum())
741
+ y_vals = log_p[mask]
742
+ ax.scatter(x_vals + y_offset, y_vals, c=ACCENT_MINT, s=8, alpha=0.6)
743
+ ax.axvline(y_offset, color=GRID_SOFT, lw=0.5, alpha=0.5)
744
+ y_offset += mask.sum()
745
+
746
+ ax.axhline(-np.log10(5e-8), color=ACCENT_PINK, ls='--', lw=1.5)
747
+ ax.set_xlabel("SNP Index by Chromosome")
748
+ ax.set_ylabel("-log10(p)")
749
+ ax.set_title("Stacked Manhattan Plot")
750
+
751
+ fig.tight_layout()
752
+ return fig
753
 
754
+ 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
+
762
+ im = axes[0].imshow(corr_mat, cmap='coolwarm', vmin=-1, vmax=1, aspect='auto')
763
+ axes[0].set_title("SNP Correlation Matrix")
764
+ axes[0].set_xlabel("SNP Index")
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)
772
+
773
+ im2 = axes[1].imshow(top_corr, cmap='coolwarm', vmin=-1, vmax=1, aspect='auto')
774
+ axes[1].set_title("Top 20 SNPs Correlation")
775
+ axes[1].set_xlabel("SNP Index")
776
+ axes[1].set_ylabel("SNP Index")
777
+ plt.colorbar(im2, ax=axes[1], label="Correlation")
778
+
779
+ fig.tight_layout()
780
+ return fig
781
 
782
+ def plot_summary_dashboard(y, maf, pvals, betas, G):
783
+ fig, axes = plt.subplots(2, 3, figsize=(15, 10))
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):
 
828
  try:
829
+ df, snp_cols, chroms, positions = parse_data(file_obj, text_input)
830
  except Exception as e:
831
+ return [None] * 18 + [f"❌ Data parsing error: {e}"]
832
+
833
  y = df["Phenotype"].values.astype(float)
834
  ids = df["ID"].values
835
  G_raw = df[snp_cols].values.astype(float)
836
  G = impute_genotypes(G_raw)
837
  n, m = G.shape
838
+
 
839
  maf_vals = compute_maf(G)
 
840
  maf_thr = float(maf_threshold)
841
  keep = maf_vals >= maf_thr
842
  if keep.sum() < 2:
843
  keep = np.ones(m, dtype=bool)
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())
863
+
864
  all_results = {}
865
  primary_p = None
866
  primary_b = None
867
+
 
868
  for mname in models_to_run:
869
  if mname in model_funcs:
870
  p, b = model_funcs[mname]()
871
  all_results[mname] = (p, b)
872
  if primary_p is None:
873
+ primary_p, primary_b = p, b
874
+
 
 
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
  """
949
+
950
+ return img_plots + [res_df, summary]
951
+
952
+ # ─────────────────────────── GRADIO UI ─────────────────────────────
953
+
954
+ SAMPLE_DATA = """ID,Phenotype,chr1_134521_SNP1,chr1_134810_SNP2,chr1_178766_SNP3,chr1_210328_SNP4
955
+ chromosome,1,1,1,1
956
+ 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; }
964
+ .gr-panel, .gr-box { background: #FFFFFF !important; border: 1px solid #E8DFD3 !important; border-radius: 20px !important; }
965
+ 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)
1009
+ if len(out) == 18:
1010
+ return out + [None]
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)