softwareDevelopment commited on
Commit
34b5e60
Β·
verified Β·
1 Parent(s): 85b6769

Update app.py

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