softwareDevelopment commited on
Commit
de3c61a
·
verified ·
1 Parent(s): 8b3752c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +835 -878
app.py CHANGED
@@ -1,7 +1,7 @@
1
  # -*- coding: utf-8 -*-
2
  """
3
- MTA Analysis Tool v4.0
4
- Premium HTML/CSS frontend · Beautiful plots · Full ZIP download
5
  """
6
 
7
  import gradio as gr
@@ -11,66 +11,60 @@ import matplotlib
11
  matplotlib.use('Agg')
12
  import matplotlib.pyplot as plt
13
  import matplotlib.patches as mpatches
14
- from matplotlib.colors import LinearSegmentedColormap
15
- import matplotlib.patheffects as pe
16
  import seaborn as sns
17
- from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor
18
- from sklearn.linear_model import LassoCV, ElasticNetCV, Ridge
19
- from sklearn.feature_selection import mutual_info_regression, f_regression
20
- from sklearn.model_selection import cross_val_score, KFold
21
- from sklearn.preprocessing import StandardScaler
22
- from sklearn.metrics import r2_score, mean_squared_error
23
  from scipy import stats
24
  import os, warnings, tempfile, zipfile
25
  warnings.filterwarnings('ignore')
26
 
27
- # ──────────────────────────────────────────────────────────────
28
- # GLOBAL PLOT THEME — dark, cinematic, scientific
29
- # ──────────────────────────────────────────────────────────────
30
- DARK_BG = "#0d1117"
31
- PANEL_BG = "#161b22"
32
- GRID_COL = "#21262d"
33
- TEXT_COL = "#e6edf3"
34
- ACCENT1 = "#58a6ff" # blue
35
- ACCENT2 = "#3fb950" # green
36
- ACCENT3 = "#f78166" # red/coral
37
- ACCENT4 = "#d2a8ff" # purple
38
- GOLD = "#e3b341" # gold
 
39
 
40
  CHROM_PALETTE = [
41
- "#58a6ff","#3fb950","#f78166","#d2a8ff","#e3b341",
42
- "#79c0ff","#56d364","#ff7b72","#bc8cff","#ffa657",
43
- "#1f6feb","#238636","#da3633","#8957e5","#d29922",
44
- "#388bfd","#2ea043","#f85149","#a371f7","#fb8f44",
45
- "#0d419d","#196c2e",
46
  ]
47
 
48
- def set_dark_style():
49
  plt.rcParams.update({
50
- 'figure.facecolor': DARK_BG,
51
- 'axes.facecolor': PANEL_BG,
52
- 'axes.edgecolor': GRID_COL,
53
- 'axes.labelcolor': TEXT_COL,
54
- 'axes.titlecolor': TEXT_COL,
55
- 'xtick.color': TEXT_COL,
56
- 'ytick.color': TEXT_COL,
57
- 'text.color': TEXT_COL,
58
- 'grid.color': GRID_COL,
59
- 'grid.linewidth': 0.6,
60
- 'figure.dpi': 150,
61
- 'font.family': 'monospace',
62
- 'axes.spines.top': False,
63
  'axes.spines.right': False,
64
- 'axes.spines.left': False,
65
- 'axes.spines.bottom':False,
66
  })
67
 
68
- # ──────────────────────────────────────────────────────────────
69
- # PLOT 1 — MANHATTAN (ultra-premium)
70
- # ──────────────────────────────────────────────────────────────
71
- def plot_manhattan(marker_names, chromosomes, p_values, consensus_set,
72
- bonf_thresh, save_path):
73
- set_dark_style()
74
 
75
  unique_chroms = sorted(set(chromosomes),
76
  key=lambda x: (int(x) if x.isdigit() else 999, x))
@@ -79,190 +73,204 @@ def plot_manhattan(marker_names, chromosomes, p_values, consensus_set,
79
  GAP = max(8, len(marker_names) // 150)
80
  x_pos = np.zeros(len(marker_names))
81
  chrom_centers, chrom_to_idx = {}, {}
82
- for i, m in enumerate(marker_names):
83
- c = chromosomes[i]
84
  chrom_to_idx.setdefault(c, []).append(i)
85
 
86
  offset = 0
87
- for chrom in unique_chroms:
88
- idxs = chrom_to_idx.get(chrom, [])
89
  if not idxs: continue
90
- for rank, idx in enumerate(idxs):
91
- x_pos[idx] = offset + rank
92
- chrom_centers[chrom] = offset + (len(idxs) - 1) / 2
93
  offset += len(idxs) + GAP
94
 
95
- fig = plt.figure(figsize=(22, 8), facecolor=DARK_BG)
96
- ax = fig.add_subplot(111, facecolor=PANEL_BG)
97
 
98
- # Subtle alternating band background per chromosome
99
- for ci, chrom in enumerate(unique_chroms):
100
- idxs = chrom_to_idx.get(chrom, [])
101
  if not idxs: continue
102
  x0 = x_pos[idxs[0]] - 0.5
103
  x1 = x_pos[idxs[-1]] + 0.5
104
- alpha = 0.06 if ci % 2 == 0 else 0.0
105
- ax.axvspan(x0, x1, color='white', alpha=alpha, zorder=0)
106
 
107
- # Plot per chromosome
108
- for ci, chrom in enumerate(unique_chroms):
109
- idxs = chrom_to_idx.get(chrom, [])
110
  if not idxs: continue
111
  col = CHROM_PALETTE[ci % len(CHROM_PALETTE)]
112
 
113
- normal = [i for i in idxs if i not in consensus_set]
114
- sel = [i for i in idxs if i in consensus_set]
115
 
116
  if normal:
117
  ax.scatter(x_pos[normal], log_p[normal],
118
- c=col, s=10, alpha=0.55, linewidths=0, zorder=2)
119
  if sel:
120
- # Glow effect: large faint circle behind
121
  ax.scatter(x_pos[sel], log_p[sel],
122
- c=ACCENT3, s=220, alpha=0.18, linewidths=0, zorder=3)
123
  ax.scatter(x_pos[sel], log_p[sel],
124
- c=ACCENT3, s=70, alpha=1.0,
125
- edgecolors='white', linewidths=0.8,
126
  marker='D', zorder=4)
127
 
128
  # Threshold lines
129
- ax.axhline(bonf_thresh, color=ACCENT3, ls='--', lw=1.6, alpha=0.9, zorder=5)
130
- ax.text(offset * 0.01, bonf_thresh + 0.15,
131
- f'Bonferroni α=0.05', color=ACCENT3, fontsize=9, va='bottom')
132
-
133
- suggestive = -np.log10(1e-5)
134
- if suggestive < bonf_thresh:
135
- ax.axhline(suggestive, color=GOLD, ls=':', lw=1.2, alpha=0.7, zorder=5)
136
- ax.text(offset * 0.01, suggestive + 0.15,
137
- 'Suggestive 1×10⁻⁵', color=GOLD, fontsize=9, va='bottom')
 
 
138
 
139
- # Chromosome labels
140
  xtick_pos = [chrom_centers[c] for c in unique_chroms if c in chrom_centers]
141
  xtick_lab = [f'Chr {c}' for c in unique_chroms if c in chrom_centers]
142
  ax.set_xticks(xtick_pos)
143
  ax.set_xticklabels(xtick_lab,
144
- fontsize=8 if len(unique_chroms) > 12 else 10,
145
  rotation=45 if len(unique_chroms) > 14 else 0,
146
- ha='center', color=TEXT_COL)
147
  ax.set_xlim(-GAP, offset)
148
- ax.set_ylim(bottom=0, top=max(log_p) * 1.12)
149
 
150
- ax.set_ylabel('−log₁₀(P-value)', fontsize=12, color=TEXT_COL, labelpad=10)
151
- ax.set_xlabel('Chromosome', fontsize=12, color=TEXT_COL, labelpad=10)
 
 
152
  ax.set_title('Genome-Wide Association Study · Manhattan Plot',
153
- fontsize=16, color=TEXT_COL, fontweight='bold', pad=18)
154
 
155
- # Y grid lines only
156
- ax.yaxis.grid(True, color=GRID_COL, linewidth=0.6, alpha=0.8)
157
  ax.set_axisbelow(True)
 
158
 
159
- # Legend
160
- h1 = plt.Line2D([0],[0], color=ACCENT3, ls='--', lw=1.6, label='Bonferroni threshold')
161
- h2 = mpatches.Patch(color=ACCENT3, label='Selected markers (ML consensus)')
162
- h3 = plt.Line2D([0],[0], color=GOLD, ls=':', lw=1.2, label='Suggestive threshold')
163
- ax.legend(handles=[h1, h2, h3], fontsize=9,
164
- facecolor=PANEL_BG, edgecolor=GRID_COL,
165
- labelcolor=TEXT_COL, loc='upper right')
166
 
167
- # Tick styling
168
- ax.tick_params(axis='both', colors=TEXT_COL, length=3)
169
-
170
- plt.tight_layout(pad=1.5)
171
- plt.savefig(save_path, dpi=200, bbox_inches='tight', facecolor=DARK_BG)
 
 
 
 
 
 
 
 
 
172
  plt.close(fig)
173
 
174
 
175
- # ──────────────────────────────────────────────────────────────
176
  # PLOT 2 — QQ PLOT
177
- # ──────────────────────────────────────────────────────────────
178
  def plot_qq(p_values, save_path):
179
- set_dark_style()
180
 
181
- pv = np.clip(np.array(p_values)[~np.isnan(p_values)], 1e-300, 1.0)
182
- n = len(pv)
183
  obs = np.sort(pv)
184
  exp = np.linspace(1/n, 1, n)
185
  log_obs = -np.log10(obs)
186
  log_exp = -np.log10(exp)
187
 
188
- ci_up = -np.log10(stats.beta.ppf(0.025, np.arange(1,n+1), np.arange(n,0,-1)))
189
- ci_lo = np.maximum(-np.log10(stats.beta.ppf(0.975, np.arange(1,n+1), np.arange(n,0,-1))), 0)
 
190
 
191
  chi2 = stats.chi2.ppf(1 - pv, df=1)
192
  lam = np.median(chi2) / stats.chi2.ppf(0.5, df=1)
193
 
194
- fig, ax = plt.subplots(figsize=(7, 7), facecolor=DARK_BG)
195
- ax.set_facecolor(PANEL_BG)
196
 
197
  ax.fill_between(log_exp, ci_lo, ci_up,
198
- color=ACCENT1, alpha=0.15, label='95% CI')
199
- ax.scatter(log_exp, log_obs,
200
- c=log_obs, cmap='plasma', s=12, alpha=0.8,
201
- linewidths=0, zorder=3)
202
- maxv = max(log_obs.max(), log_exp.max()) * 1.05
203
- ax.plot([0, maxv], [0, maxv], color=GRID_COL, lw=1.8, ls='--', zorder=2)
204
-
205
- ax.set_xlabel('Expected −log₁₀(P)', fontsize=12, color=TEXT_COL)
206
- ax.set_ylabel('Observed −log₁₀(P)', fontsize=12, color=TEXT_COL)
207
- ax.set_title(f'QQ Plot · λ = {lam:.4f}', fontsize=15,
208
- color=TEXT_COL, fontweight='bold', pad=14)
 
 
 
 
 
 
 
 
 
 
 
 
209
  ax.set_xlim(0, maxv); ax.set_ylim(0, maxv)
 
 
 
 
210
 
211
- lam_col = ACCENT2 if lam < 1.05 else (GOLD if lam < 1.10 else ACCENT3)
212
- lam_txt = "Well-calibrated" if lam < 1.05 else ("Minor inflation" if lam < 1.10 else "Significant inflation")
213
- ax.text(0.04, 0.96, f'λ = {lam:.4f} [{lam_txt}]',
214
- transform=ax.transAxes, fontsize=10,
215
- color=lam_col, va='top',
216
- bbox=dict(boxstyle='round,pad=0.4', fc=PANEL_BG, ec=lam_col, alpha=0.85))
217
-
218
- ax.yaxis.grid(True, color=GRID_COL, lw=0.6)
219
- ax.xaxis.grid(True, color=GRID_COL, lw=0.6)
220
- ax.tick_params(colors=TEXT_COL)
221
-
222
- plt.tight_layout(pad=1.5)
223
- plt.savefig(save_path, dpi=200, bbox_inches='tight', facecolor=DARK_BG)
224
  plt.close(fig)
225
  return lam
226
 
227
 
228
- # ──────────────────────────────────────────────────────────────
229
  # PLOT 3 — LD DECAY
230
- # ──────────────────────────────────────────────────────────────
231
  def plot_ld_decay(genotypes, chromosomes, save_path, max_m=250):
232
- set_dark_style()
233
 
234
  unique_chroms = sorted(set(chromosomes),
235
  key=lambda x: (int(x) if x.isdigit() else 999, x))
236
- all_d, all_r2 = [], []
237
- chrom_mean = {}
238
 
239
- for chrom in unique_chroms:
240
- idxs = [i for i, c in enumerate(chromosomes) if c == chrom]
241
  if len(idxs) < 4: continue
242
  if len(idxs) > max_m:
243
  idxs = sorted(np.random.choice(idxs, max_m, replace=False))
244
- G = genotypes[:, idxs].copy()
245
- std = G.std(axis=0); std[std == 0] = 1
246
- G = (G - G.mean(axis=0)) / std
247
- nm = G.shape[1]
248
  dl, rl = [], []
249
- for i in range(nm - 1):
250
  for j in range(i+1, min(i+60, nm)):
251
  r = np.corrcoef(G[:,i], G[:,j])[0,1]
252
  r2 = r**2 if not np.isnan(r) else 0
253
- dl.append(j - i); rl.append(r2)
254
  if dl:
255
  all_d.extend(dl); all_r2.extend(rl)
256
- chrom_mean[chrom] = np.mean(rl)
257
 
258
- fig, axes = plt.subplots(1, 2, figsize=(16, 6), facecolor=DARK_BG)
259
 
260
  # ── Left: decay curve ──
261
- ax = axes[0]; ax.set_facecolor(PANEL_BG)
262
  if all_d:
263
- all_d = np.array(all_d); all_r2 = np.array(all_r2)
264
- max_d = min(int(all_d.max()), 50)
265
- bins = np.arange(1, max_d + 1)
 
266
  mu, se = [], []
267
  for b in bins:
268
  m = all_d == b
@@ -274,213 +282,202 @@ def plot_ld_decay(genotypes, chromosomes, save_path, max_m=250):
274
  mu = np.array(mu); se = np.array(se)
275
  v = ~np.isnan(mu)
276
 
277
- ax.fill_between(bins[v], np.clip(mu[v]-se[v],0,1), np.clip(mu[v]+se[v],0,1),
278
- color=ACCENT1, alpha=0.18)
 
 
279
 
280
- # Color gradient on the line
281
- from matplotlib.collections import LineCollection
282
- points = np.array([bins[v], mu[v]]).T.reshape(-1, 1, 2)
283
- segs = np.concatenate([points[:-1], points[1:]], axis=1)
284
- lc = LineCollection(segs, cmap='cool', linewidth=2.5, zorder=4)
285
  lc.set_array(mu[v])
286
  ax.add_collection(lc)
287
- ax.scatter(bins[v], mu[v], c=mu[v], cmap='cool', s=20, zorder=5, linewidths=0)
 
 
288
 
289
- ax.axhline(0.2, color=GOLD, ls='--', lw=1.2, alpha=0.8, label='r²=0.2 threshold')
290
 
291
- # Half-decay
292
- start_r2 = mu[v][0] if len(mu[v]) > 0 else 1.0
293
- hd = None
294
  for i, r2 in enumerate(mu[v]):
295
- if r2 <= start_r2 / 2:
296
- hd = bins[v][i]; break
297
- if hd:
298
- ax.axvline(hd, color=ACCENT3, ls='--', lw=1.2, alpha=0.8,
299
- label=f'Half-decay d={hd}')
300
-
301
- ax.set_xlabel('Marker Distance (index)', fontsize=11, color=TEXT_COL)
302
- ax.set_ylabel('Mean r²', fontsize=11, color=TEXT_COL)
303
- ax.set_title('LD Decay Curve', fontsize=14, color=TEXT_COL, fontweight='bold', pad=12)
304
- ax.set_ylim(0, 1); ax.tick_params(colors=TEXT_COL)
305
- ax.yaxis.grid(True, color=GRID_COL, lw=0.6)
306
- ax.legend(fontsize=9, facecolor=PANEL_BG, edgecolor=GRID_COL, labelcolor=TEXT_COL)
307
 
308
  # ── Right: per-chromosome bars ──
309
- ax2 = axes[1]; ax2.set_facecolor(PANEL_BG)
310
  if chrom_mean:
311
- cs = sorted(chrom_mean.keys(), key=lambda x: (int(x) if x.isdigit() else 999, x))
312
  vals = [chrom_mean[c] for c in cs]
313
  cols = [CHROM_PALETTE[i % len(CHROM_PALETTE)] for i in range(len(cs))]
314
  bars = ax2.bar(range(len(cs)), vals, color=cols,
315
- edgecolor=DARK_BG, linewidth=0.8, alpha=0.9, width=0.65)
316
  ax2.set_xticks(range(len(cs)))
317
  ax2.set_xticklabels([f'Chr {c}' for c in cs],
318
  rotation=45 if len(cs) > 10 else 0,
319
- fontsize=8, ha='right', color=TEXT_COL)
320
- ax2.set_ylim(0, 1)
321
  for bar, val in zip(bars, vals):
322
  ax2.text(bar.get_x() + bar.get_width()/2,
323
  bar.get_height() + 0.02,
324
  f'{val:.2f}', ha='center', va='bottom',
325
- fontsize=7, color=TEXT_COL)
326
- ax2.set_xlabel('Chromosome', fontsize=11, color=TEXT_COL)
327
- ax2.set_ylabel('Mean r²', fontsize=11, color=TEXT_COL)
328
- ax2.set_title('Mean LD per Chromosome', fontsize=14, color=TEXT_COL,
329
  fontweight='bold', pad=12)
330
- ax2.tick_params(colors=TEXT_COL)
331
- ax2.yaxis.grid(True, color=GRID_COL, lw=0.6)
 
332
 
333
- fig.suptitle('Linkage Disequilibrium Analysis', fontsize=16,
334
- color=TEXT_COL, fontweight='bold', y=1.02)
335
  plt.tight_layout(pad=2)
336
- plt.savefig(save_path, dpi=200, bbox_inches='tight', facecolor=DARK_BG)
337
  plt.close(fig)
338
  return chrom_mean
339
 
340
 
341
- # ──────────────────────────────────────────────────────────────
342
- # PLOT 4 — MODEL COMPARISON
343
- # ──────────────────────────────────────────────────────────────
344
- def plot_model_comparison(models, best_name, save_path):
345
- set_dark_style()
346
- names = list(models.keys())
347
- cv_r2 = [models[m]['cv'] for m in names]
348
- train_r2 = [models[m]['r2'] for m in names]
349
- rmse = [models[m]['rmse'] for m in names]
350
-
351
- fig, axes = plt.subplots(1, 2, figsize=(14, 6), facecolor=DARK_BG)
352
-
353
- # Bar chart
354
- ax = axes[0]; ax.set_facecolor(PANEL_BG)
355
- x = np.arange(len(names)); w = 0.35
356
- b1 = ax.bar(x - w/2, train_r2, w, label='Train R²',
357
- color=ACCENT1, alpha=0.8, edgecolor=DARK_BG, linewidth=0.8)
358
- b2 = ax.bar(x + w/2, cv_r2, w, label='CV R²',
359
- color=ACCENT2, alpha=0.8, edgecolor=DARK_BG, linewidth=0.8)
360
- bi = names.index(best_name)
361
- for b in [b1[bi], b2[bi]]:
362
- b.set_edgecolor(GOLD); b.set_linewidth(2.5)
363
- for xi, (tr, cv) in enumerate(zip(train_r2, cv_r2)):
364
- ax.text(xi - w/2, tr + 0.01, f'{tr:.3f}', ha='center', va='bottom', fontsize=8, color=TEXT_COL)
365
- ax.text(xi + w/2, cv + 0.01, f'{cv:.3f}', ha='center', va='bottom', fontsize=8, color=TEXT_COL)
366
- ax.set_xticks(x); ax.set_xticklabels(names, fontsize=11, color=TEXT_COL)
367
- ax.set_ylabel('R²', fontsize=12, color=TEXT_COL)
368
- ax.set_title('R² Comparison\n(Gold border = best CV model)', fontsize=13, color=TEXT_COL, fontweight='bold')
369
- ax.set_ylim(0, 1.15)
370
- ax.yaxis.grid(True, color=GRID_COL, lw=0.6)
371
- ax.tick_params(colors=TEXT_COL)
372
- ax.legend(fontsize=10, facecolor=PANEL_BG, edgecolor=GRID_COL, labelcolor=TEXT_COL)
373
-
374
- # RMSE radar-style horizontal bar
375
- ax2 = axes[1]; ax2.set_facecolor(PANEL_BG)
376
- cols = [GOLD if n == best_name else ACCENT4 for n in names]
377
- bars = ax2.barh(names, rmse, color=cols, edgecolor=DARK_BG, linewidth=0.8, alpha=0.85)
378
- for bar, val in zip(bars, rmse):
379
- ax2.text(bar.get_width() + max(rmse)*0.01, bar.get_y() + bar.get_height()/2,
380
- f'{val:.4f}', va='center', fontsize=10, color=TEXT_COL)
381
- ax2.set_xlabel('RMSE', fontsize=12, color=TEXT_COL)
382
- ax2.set_title('Root Mean Square Error\n(Lower is better)', fontsize=13, color=TEXT_COL, fontweight='bold')
383
- ax2.tick_params(colors=TEXT_COL)
384
- ax2.xaxis.grid(True, color=GRID_COL, lw=0.6)
385
-
386
- plt.tight_layout(pad=2)
387
- plt.savefig(save_path, dpi=200, bbox_inches='tight', facecolor=DARK_BG)
 
 
 
 
 
 
388
  plt.close(fig)
389
 
390
 
391
- # ──────────────────────────────────────────────────────────────
392
- # PLOT 5 — OBSERVED vs PREDICTED
393
- # ──────────────────────────────────────────────────────────────
394
- def plot_obs_pred(obs, pred, best_name, cv_r2, rmse, save_path):
395
- set_dark_style()
396
- fig, ax = plt.subplots(figsize=(8, 7), facecolor=DARK_BG)
397
- ax.set_facecolor(PANEL_BG)
398
 
399
- # Density-colored scatter
400
- from scipy.stats import gaussian_kde
401
- xy = np.vstack([obs, pred])
402
- try:
403
- z = gaussian_kde(xy)(xy)
404
- idx = z.argsort()
405
- sc = ax.scatter(obs[idx], pred[idx], c=z[idx], cmap='plasma',
406
- s=45, alpha=0.85, linewidths=0, zorder=3)
407
- plt.colorbar(sc, ax=ax, label='Density', shrink=0.8)
408
- except Exception:
409
- ax.scatter(obs, pred, c=ACCENT4, s=40, alpha=0.7, linewidths=0)
410
-
411
- lims = [min(obs.min(), pred.min()) - 1, max(obs.max(), pred.max()) + 1]
412
- ax.plot(lims, lims, color=ACCENT3, lw=2, ls='--', zorder=4, label='y = x')
413
- ax.set_xlim(lims); ax.set_ylim(lims)
414
-
415
- corr, _ = stats.pearsonr(obs, pred)
416
- ax.set_xlabel('Observed Phenotype', fontsize=12, color=TEXT_COL)
417
- ax.set_ylabel('Predicted GEBV', fontsize=12, color=TEXT_COL)
418
- ax.set_title(f'{best_name} — Observed vs Predicted', fontsize=15,
419
- color=TEXT_COL, fontweight='bold', pad=14)
420
- ax.text(0.05, 0.93,
421
- f'CV R² = {cv_r2:.4f}\nRMSE = {rmse:.4f}\nr = {corr:.4f}',
422
- transform=ax.transAxes, fontsize=11, color=TEXT_COL, va='top',
423
- bbox=dict(boxstyle='round,pad=0.5', fc=PANEL_BG, ec=ACCENT1, alpha=0.9))
424
- ax.yaxis.grid(True, color=GRID_COL, lw=0.6)
425
- ax.xaxis.grid(True, color=GRID_COL, lw=0.6)
426
- ax.tick_params(colors=TEXT_COL)
427
- ax.legend(fontsize=10, facecolor=PANEL_BG, edgecolor=GRID_COL, labelcolor=TEXT_COL)
428
-
429
- plt.tight_layout(pad=1.5)
430
- plt.savefig(save_path, dpi=200, bbox_inches='tight', facecolor=DARK_BG)
431
- plt.close(fig)
432
-
433
-
434
- # ──────────────────────────────────────────────────────────────
435
- # PLOT 6 — TOP MARKER EFFECTS
436
- # ──────────────────────────────────────────────────────────────
437
- def plot_top_markers(mta_df, best_name, chrom_list_sorted, save_path, top_n=30):
438
- set_dark_style()
439
- df = mta_df.head(top_n).copy()
440
- fig, ax = plt.subplots(figsize=(13, 9), facecolor=DARK_BG)
441
- ax.set_facecolor(PANEL_BG)
442
 
 
 
443
  col_map = {c: CHROM_PALETTE[i % len(CHROM_PALETTE)]
444
- for i, c in enumerate(chrom_list_sorted)}
445
- colors = [col_map.get(c, ACCENT1) for c in df['Chromosome']]
446
 
447
- bars = ax.barh(range(len(df)), df[f'Effect_{best_name}'].values,
448
- color=colors, edgecolor=DARK_BG, linewidth=0.6,
449
- alpha=0.88, height=0.7)
450
 
451
- ax.set_yticks(range(len(df)))
452
- ax.set_yticklabels(
453
- [f" {row['Marker']} Chr{row['Chromosome']}" for _, row in df.iterrows()],
454
- fontsize=8.5, color=TEXT_COL)
455
- ax.invert_yaxis()
456
-
457
- ax.set_xlabel(f'Effect Size ({best_name})', fontsize=12, color=TEXT_COL)
458
- ax.set_title(f'Top {top_n} Selected Markers — Effect Sizes', fontsize=15,
459
- color=TEXT_COL, fontweight='bold', pad=14)
460
- ax.tick_params(colors=TEXT_COL)
461
- ax.xaxis.grid(True, color=GRID_COL, lw=0.6)
462
 
463
- # Chromosome color legend (compact)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
464
  handles = []
465
  shown = set()
466
- for _, row in df.iterrows():
467
- c = row['Chromosome']
468
  if c not in shown:
469
- handles.append(mpatches.Patch(color=col_map.get(c, ACCENT1),
470
- label=f'Chr {c}'))
471
  shown.add(c)
472
- ax.legend(handles=handles, fontsize=8, ncol=max(1, len(shown)//6 + 1),
473
- facecolor=PANEL_BG, edgecolor=GRID_COL, labelcolor=TEXT_COL,
474
- loc='lower right')
475
 
476
- plt.tight_layout(pad=1.5)
477
- plt.savefig(save_path, dpi=200, bbox_inches='tight', facecolor=DARK_BG)
478
  plt.close(fig)
479
 
480
 
481
- # ──────────────────────────────────────────────────────────────
482
- # MAIN ANALYSIS
483
- # ──────────────────────────────────────────────────────────────
484
  def run_mta_analysis(input_file, target_markers):
485
  try:
486
  if input_file is None:
@@ -492,24 +489,27 @@ def run_mta_analysis(input_file, target_markers):
492
  for d in [results_dir, plots_dir]:
493
  os.makedirs(d, exist_ok=True)
494
 
495
- # ── LOAD ──
496
  df = pd.read_csv(input_file, sep=',', header=0)
497
- marker_cols = df.columns[3:].tolist()
498
- chrom_info_row = df.iloc[0, 3:].values.astype(str)
 
 
 
499
  chromosome_dict = {m: c for m, c in zip(marker_cols, chrom_info_row)}
500
 
501
- df_data = df.iloc[1:].reset_index(drop=True)
502
- sample_ids = df_data.iloc[:, 0].astype(str).values
503
- phenotypes = pd.to_numeric(df_data.iloc[:, 2], errors='coerce').values
504
- genotypes = df_data.iloc[:, 3:].apply(pd.to_numeric, errors='coerce').values
505
  marker_names = marker_cols
506
 
507
- unique_chromosomes = sorted(set(chrom_info_row),
508
- key=lambda x: (int(x) if x.isdigit() else 999, x))
509
  n_samples = len(sample_ids)
510
  n_markers = len(marker_names)
511
 
512
- # ── QC ──
513
  miss_m = np.isnan(genotypes).sum(axis=0) / n_samples
514
  miss_s = np.isnan(genotypes).sum(axis=1) / n_markers
515
  maf = np.array([
@@ -526,6 +526,10 @@ def run_mta_analysis(input_file, target_markers):
526
  mnames_qc = [marker_names[i] for i in range(n_markers) if qc_m[i]]
527
  chrom_qc = [chromosome_dict[m] for m in mnames_qc]
528
 
 
 
 
 
529
  for i in range(geno_qc.shape[1]):
530
  col = geno_qc[:, i]
531
  mask = np.isnan(col)
@@ -534,37 +538,52 @@ def run_mta_analysis(input_file, target_markers):
534
 
535
  TARGET = min(int(target_markers), len(mnames_qc))
536
 
537
- # ── GWAS ──
538
  pvals = np.ones(len(mnames_qc))
539
  effects = np.zeros(len(mnames_qc))
540
  gse = np.zeros(len(mnames_qc))
 
 
541
  for i in range(len(mnames_qc)):
542
  mk = geno_qc[:, i]
543
  if np.std(mk) > 0:
544
  try:
545
- r = stats.linregress(mk, pheno_qc)
546
- pvals[i] = r.pvalue
547
- effects[i] = r.slope
548
- gse[i] = r.stderr
549
- except: pass
 
 
550
 
551
  bonf = -np.log10(0.05 / len(mnames_qc))
552
  n_sig = int((pvals < 0.05/len(mnames_qc)).sum())
553
  n_sugg = int((pvals < 1e-5).sum())
 
 
 
 
 
 
 
554
 
555
- # ── ML SELECTION ──
556
  scaler = StandardScaler()
557
  X = scaler.fit_transform(geno_qc)
558
  y = pheno_qc
559
 
560
- rf_fs = RandomForestRegressor(100, max_depth=10, random_state=42, n_jobs=-1)
 
561
  rf_fs.fit(X, y)
562
- gb_fs = GradientBoostingRegressor(100, max_depth=5, random_state=42)
 
 
563
  gb_fs.fit(X, y)
 
564
  en_fs = ElasticNetCV(cv=5, random_state=42, max_iter=5000)
565
  en_fs.fit(X, y)
566
- mi = mutual_info_regression(X, y, random_state=42)
567
- fsc, _ = f_regression(X, y)
 
568
 
569
  votes = np.zeros(len(mnames_qc))
570
  for arr in [rf_fs.feature_importances_, gb_fs.feature_importances_,
@@ -572,107 +591,70 @@ def run_mta_analysis(input_file, target_markers):
572
  top = np.argsort(arr)[-TARGET:]
573
  votes[top] += 1
574
 
575
- cons_idx = np.argsort(votes)[-TARGET:]
576
- cons_set = set(cons_idx)
577
-
578
- # ── MODELS ──
579
- X_sel = X[:, cons_idx]
580
- cv5 = KFold(n_splits=5, shuffle=True, random_state=42)
581
-
582
- specs = [
583
- ('LASSO', LassoCV(cv=5, random_state=42, max_iter=10000)),
584
- ('RF', RandomForestRegressor(200, max_depth=15, random_state=42, n_jobs=-1)),
585
- ('GB', GradientBoostingRegressor(200, max_depth=7, random_state=42)),
586
- ('Ridge', Ridge(alpha=1.0)),
587
- ('ElasticNet', ElasticNetCV(cv=5, random_state=42, max_iter=5000)),
588
- ]
589
- models = {}
590
- for nm, obj in specs:
591
- obj.fit(X_sel, y)
592
- pred = obj.predict(X_sel)
593
- cv_r2 = cross_val_score(obj, X_sel, y, cv=cv5, scoring='r2').mean()
594
- eff = obj.feature_importances_ if hasattr(obj,'feature_importances_') else np.abs(obj.coef_)
595
- models[nm] = {'pred': pred,
596
- 'r2': r2_score(y, pred),
597
- 'rmse': np.sqrt(mean_squared_error(y, pred)),
598
- 'cv': cv_r2,
599
- 'eff': eff}
600
-
601
- best_name = max(models, key=lambda k: models[k]['cv'])
602
- best = models[best_name]
603
-
604
- # ── CSVs ──
605
- pred_df = pd.DataFrame({'SampleID': ids_qc, 'Observed': pheno_qc})
606
- for nm, d in models.items():
607
- pred_df[f'GEBV_{nm}'] = d['pred']
608
- pred_df[f'Residual_{nm}'] = pheno_qc - d['pred']
609
- pred_df['Best_GEBV'] = pred_df[f'GEBV_{best_name}']
610
- pred_df['Rank'] = pred_df['Best_GEBV'].rank(ascending=False).astype(int)
611
- pred_df.sort_values('Best_GEBV', ascending=False, inplace=True)
612
- pred_df.to_csv(os.path.join(results_dir,'all_model_predictions.csv'), index=False)
613
-
614
- mta_results = {}
615
- for nm, d in models.items():
616
- rows = []
617
- for ri, idx in enumerate(np.argsort(d['eff'])[::-1]):
618
- oi = cons_idx[idx]
619
- rows.append({'Rank': ri+1,
620
- 'Marker': mnames_qc[oi],
621
- 'Chromosome': chrom_qc[oi],
622
- f'Effect_{nm}': d['eff'][idx],
623
- 'Vote_Count': int(votes[oi]),
624
- 'GWAS_Pvalue': pvals[oi],
625
- 'GWAS_logP': -np.log10(pvals[oi]+1e-300),
626
- 'GWAS_Effect': effects[oi],
627
- 'GWAS_SE': gse[oi]})
628
- mdf = pd.DataFrame(rows)
629
- tot = mdf[f'Effect_{nm}'].sum()
630
- mdf[f'Contribution_pct'] = mdf[f'Effect_{nm}']/tot*100 if tot>0 else 0
631
- mta_results[nm] = mdf
632
- mdf.to_csv(os.path.join(results_dir,f'mta_associations_{nm}.csv'), index=False)
633
-
634
- # Chromosome summary
635
  chr_rows = []
636
- for ch in unique_chromosomes:
637
- ci = [i for i, c in enumerate(chrom_qc) if c == ch]
638
  if not ci: continue
639
  cp = pvals[ci]
640
  chr_rows.append({
641
- 'Chromosome': ch,
642
- 'N_Markers': len(ci),
643
- 'N_Selected': sum(1 for i in ci if i in cons_set),
644
- 'Min_Pvalue': cp.min(),
645
- 'Best_logP': -np.log10(cp.min()+1e-300),
646
- 'N_Significant': int((cp < 0.05/len(mnames_qc)).sum()),
647
- 'N_Suggestive': int((cp < 1e-5).sum()),
 
648
  })
649
  pd.DataFrame(chr_rows).to_csv(
650
- os.path.join(results_dir,'chromosome_summary.csv'), index=False)
651
 
 
652
  pd.DataFrame({
653
  'Metric': ['Samples_raw','Samples_QC','Markers_raw','Markers_QC',
654
- 'Markers_Selected','Chromosomes','N_Significant','N_Suggestive'],
655
- 'Value': [n_samples, len(ids_qc), n_markers, len(mnames_qc),
656
- TARGET, len(unique_chromosomes), n_sig, n_sugg]
 
 
657
  }).to_csv(os.path.join(results_dir,'qc_summary.csv'), index=False)
658
 
659
- # ── PLOTS ──
660
- man_path = os.path.join(plots_dir,'manhattan_plot.png')
661
- qq_path = os.path.join(plots_dir,'qq_plot.png')
662
- ld_path = os.path.join(plots_dir,'ld_decay.png')
663
- comp_path = os.path.join(plots_dir,'model_comparison.png')
664
- pred_path = os.path.join(plots_dir,'observed_vs_predicted.png')
665
- top_path = os.path.join(plots_dir,'top_marker_effects.png')
666
 
667
- plot_manhattan(mnames_qc, chrom_qc, pvals, cons_set, bonf, man_path)
668
  lam = plot_qq(pvals, qq_path)
669
  ld_summary = plot_ld_decay(geno_qc, chrom_qc, ld_path)
670
- plot_model_comparison(models, best_name, comp_path)
671
- plot_obs_pred(pheno_qc, best['pred'], best_name, best['cv'], best['rmse'], pred_path)
672
- plot_top_markers(mta_results[best_name], best_name, unique_chromosomes, top_path)
673
 
674
- # ── ZIP (ALL results) ──
675
- zip_path = os.path.join(temp_dir, 'MTA_Analysis_Results.zip')
676
  with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf:
677
  for root, _, files in os.walk(results_dir):
678
  for f in files:
@@ -680,531 +662,506 @@ def run_mta_analysis(input_file, target_markers):
680
  arc = os.path.relpath(fp, temp_dir)
681
  zf.write(fp, arc)
682
 
683
- # ── SUMMARY ──
684
- lam_txt = ("✅ Well-calibrated (λ≈1)" if lam < 1.05
685
  else "⚠️ Minor inflation — consider PCA correction" if lam < 1.10
686
  else "❌ Significant inflation — use mixed model (GEMMA/EMMAX)")
687
 
688
  gm_r2 = np.mean(list(ld_summary.values())) if ld_summary else 0
689
  ld_txt = ("Low LD — high marker density needed" if gm_r2 < 0.1
690
  else "Moderate LD — typical for diverse panels" if gm_r2 < 0.3
691
- else "High LD — consider LD pruning")
692
-
693
- acc_txt = (f"Excellent ({best['cv']*100:.1f}% variance explained)" if best['cv'] > 0.5
694
- else f"Moderate ({best['cv']*100:.1f}%) — more samples may help" if best['cv'] > 0.2
695
- else f"Low ({best['cv']*100:.1f}%) — consider larger dataset or mixed models")
696
-
697
- model_rows = "\n".join(
698
- f"| {'🏆 ' if nm==best_name else ''}{nm} | {d['cv']:.4f} | {d['r2']:.4f} | {d['rmse']:.4f} |"
699
- for nm, d in models.items())
700
-
701
- top5_rows = "\n".join(
702
- f"| {int(r['Rank'])} | {r['Marker']} | Chr {r['Chromosome']} | "
703
- f"{r[f'Effect_{best_name}']:.6f} | {int(r['Vote_Count'])}/5 | {r['GWAS_logP']:.3f} |"
704
- for _, r in mta_results[best_name].head(5).iterrows())
705
-
706
- top5_samples = "\n".join(
707
- f"| {int(r['Rank'])} | {r['SampleID']} | {r['Observed']:.3f} | {r['Best_GEBV']:.3f} |"
708
- for _, r in pred_df.head(5).iterrows())
709
 
710
  summary = f"""
711
- ## Dataset & QC
712
  | Metric | Value |
713
  |--------|-------|
714
- | Samples (raw → QC) | {n_samples} → {len(ids_qc)} |
715
- | Markers (raw → QC) | {n_markers} → {len(mnames_qc)} |
716
- | Markers selected | **{TARGET}** |
717
- | Chromosomes | {len(unique_chromosomes)} |
 
718
 
719
- ## GWAS
720
  | Metric | Value |
721
  |--------|-------|
722
- | Bonferroni threshold | −log₁₀p = {bonf:.3f} |
723
- | Significant markers | **{n_sig}** |
724
- | Suggestive markers | {n_sugg} |
 
725
  | Genomic inflation λ | **{lam:.4f}** — {lam_txt} |
726
 
727
- ## LD Summary
728
  Global mean r² = **{gm_r2:.4f}** — {ld_txt}
729
 
730
- ## Model Performance
731
- | Model | CV R² | Train R² | RMSE |
732
- |-------|--------|-----------|------|
733
- {model_rows}
734
 
735
- **Best Model:** {best_name} — {acc_txt}
 
 
 
736
 
737
- ## Top 5 Markers ({best_name})
738
- | Rank | Marker | Chromosome | Effect | Votes | GWAS −log₁₀p |
739
- |------|--------|------------|--------|-------|--------------|
740
- {top5_rows}
741
-
742
- ## Top 5 Samples (Highest GEBV)
743
- | Rank | Sample | Observed | GEBV |
744
- |------|--------|----------|------|
745
- {top5_samples}
746
-
747
- ## Output Files in ZIP
748
- - `results/all_model_predictions.csv`
749
- - `results/mta_associations_<Model>.csv` (×5)
750
- - `results/chromosome_summary.csv`
751
- - `results/qc_summary.csv`
752
  - `results/plots/manhattan_plot.png`
753
  - `results/plots/qq_plot.png`
754
  - `results/plots/ld_decay.png`
755
- - `results/plots/model_comparison.png`
756
- - `results/plots/observed_vs_predicted.png`
757
- - `results/plots/top_marker_effects.png`
758
  """
759
- return summary, man_path, qq_path, ld_path, comp_path, pred_path, zip_path
760
 
761
  except Exception as e:
762
  import traceback
763
- return f"## Error\n```\n{e}\n\n{traceback.format_exc()}\n```", None,None,None,None,None,None
 
764
 
765
 
766
- # ──────────────────────────────────────────────────────────────
767
- # HTML / CSS THEME
768
- # ──────────────────────────────────────────────────────────────
769
- HEAD_HTML = """
770
  <style>
771
- @import url('https://fonts.googleapis.com/css2?family=Space+Mono:wght@400;700&family=Syne:wght@400;600;800&display=swap');
772
-
773
- :root {
774
- --bg: #0d1117;
775
- --surface: #161b22;
776
- --surface2: #21262d;
777
- --border: #30363d;
778
- --accent: #58a6ff;
779
- --green: #3fb950;
780
- --red: #f78166;
781
- --gold: #e3b341;
782
- --purple: #d2a8ff;
783
- --text: #e6edf3;
784
- --muted: #8b949e;
785
- --radius: 12px;
786
- }
787
-
788
- /* ── Global ── */
789
- body, .gradio-container {
790
- background: var(--bg) !important;
791
- color: var(--text) !important;
792
- font-family: 'Syne', sans-serif !important;
793
- }
794
-
795
- /* ── Hero Banner ── */
796
- .mta-hero {
797
- background: linear-gradient(135deg, #0d1117 0%, #161b22 40%, #0d2137 100%);
798
- border: 1px solid var(--border);
799
- border-radius: 18px;
800
- padding: 48px 56px 40px;
801
- margin-bottom: 28px;
802
- position: relative;
803
- overflow: hidden;
804
- }
805
- .mta-hero::before {
806
- content: '';
807
- position: absolute;
808
- top: -80px; right: -80px;
809
- width: 320px; height: 320px;
810
- border-radius: 50%;
811
- background: radial-gradient(circle, rgba(88,166,255,0.10) 0%, transparent 70%);
812
- pointer-events: none;
813
- }
814
- .mta-hero::after {
815
- content: '';
816
- position: absolute;
817
- bottom: -60px; left: 120px;
818
- width: 240px; height: 240px;
819
- border-radius: 50%;
820
- background: radial-gradient(circle, rgba(63,185,80,0.08) 0%, transparent 70%);
821
- pointer-events: none;
822
- }
823
- .mta-badge {
824
- display: inline-block;
825
- background: rgba(88,166,255,0.12);
826
- border: 1px solid rgba(88,166,255,0.30);
827
- color: var(--accent);
828
- font-family: 'Space Mono', monospace;
829
- font-size: 11px;
830
- letter-spacing: 2px;
831
- padding: 4px 14px;
832
- border-radius: 20px;
833
- margin-bottom: 18px;
834
- }
835
- .mta-title {
836
- font-family: 'Syne', sans-serif;
837
- font-weight: 800;
838
- font-size: 38px;
839
- color: var(--text);
840
- line-height: 1.15;
841
- margin: 0 0 12px;
842
- letter-spacing: -0.5px;
843
- }
844
- .mta-title span { color: var(--accent); }
845
- .mta-subtitle {
846
- color: var(--muted);
847
- font-size: 15px;
848
- font-family: 'Space Mono', monospace;
849
- letter-spacing: 0.3px;
850
- margin: 0;
851
- }
852
- .mta-pills {
853
- display: flex; gap: 10px; flex-wrap: wrap;
854
- margin-top: 22px;
855
- }
856
- .mta-pill {
857
- background: var(--surface2);
858
- border: 1px solid var(--border);
859
- border-radius: 20px;
860
- padding: 5px 14px;
861
- font-size: 12px;
862
- color: var(--muted);
863
- font-family: 'Space Mono', monospace;
864
- }
865
-
866
- /* ── Section labels ── */
867
- .section-label {
868
- font-family: 'Space Mono', monospace;
869
- font-size: 10px;
870
- letter-spacing: 2.5px;
871
- color: var(--accent);
872
- text-transform: uppercase;
873
- margin-bottom: 14px;
874
- display: flex;
875
- align-items: center;
876
- gap: 10px;
877
- }
878
- .section-label::after {
879
- content: '';
880
- flex: 1;
881
- height: 1px;
882
- background: var(--border);
883
- }
884
-
885
- /* ── Format box ── */
886
- .format-box {
887
- background: var(--surface);
888
- border: 1px solid var(--border);
889
- border-left: 3px solid var(--accent);
890
- border-radius: var(--radius);
891
- padding: 20px 24px;
892
- font-family: 'Space Mono', monospace;
893
- font-size: 12px;
894
- color: var(--muted);
895
- line-height: 1.9;
896
- }
897
- .format-box .col-tag {
898
- color: var(--accent);
899
- font-weight: 700;
900
- }
901
- .format-box .val-tag { color: var(--green); }
902
- .format-box .comment { color: var(--muted); opacity: 0.6; }
903
-
904
- /* ── Run button ── */
905
- .run-btn button {
906
- background: linear-gradient(135deg, #1f6feb, #388bfd) !important;
907
- border: none !important;
908
- border-radius: 10px !important;
909
- color: white !important;
910
- font-family: 'Syne', sans-serif !important;
911
- font-weight: 700 !important;
912
- font-size: 16px !important;
913
- letter-spacing: 0.5px !important;
914
- padding: 14px 0 !important;
915
- width: 100% !important;
916
- cursor: pointer !important;
917
- transition: all 0.2s ease !important;
918
- box-shadow: 0 4px 24px rgba(31,111,235,0.35) !important;
919
- }
920
- .run-btn button:hover {
921
- transform: translateY(-2px) !important;
922
- box-shadow: 0 8px 32px rgba(31,111,235,0.50) !important;
923
- }
924
-
925
- /* ── Download button ── */
926
- .dl-btn button, .dl-btn a {
927
- background: linear-gradient(135deg, #238636, #2ea043) !important;
928
- border: none !important;
929
- border-radius: 10px !important;
930
- color: white !important;
931
- font-family: 'Syne', sans-serif !important;
932
- font-weight: 700 !important;
933
- font-size: 15px !important;
934
- padding: 12px 0 !important;
935
- width: 100% !important;
936
- display: block !important;
937
- text-align: center !important;
938
- box-shadow: 0 4px 20px rgba(35,134,54,0.35) !important;
939
- transition: all 0.2s ease !important;
940
- text-decoration: none !important;
941
- }
942
- .dl-btn button:hover { transform: translateY(-2px) !important; }
943
-
944
- /* ── Slider ── */
945
- input[type=range] { accent-color: var(--accent) !important; }
946
-
947
- /* ── Cards ── */
948
- .stat-grid {
949
- display: grid;
950
- grid-template-columns: repeat(4, 1fr);
951
- gap: 12px;
952
- margin-bottom: 28px;
953
- }
954
- .stat-card {
955
- background: var(--surface);
956
- border: 1px solid var(--border);
957
- border-radius: var(--radius);
958
- padding: 18px 20px;
959
- text-align: center;
960
- }
961
- .stat-card .stat-val {
962
- font-family: 'Space Mono', monospace;
963
- font-size: 28px;
964
- font-weight: 700;
965
- color: var(--accent);
966
- }
967
- .stat-card .stat-label {
968
- font-size: 11px;
969
- color: var(--muted);
970
- margin-top: 4px;
971
- text-transform: uppercase;
972
- letter-spacing: 1px;
973
- }
974
-
975
- /* ── Plot containers ── */
976
- .plot-card {
977
- background: var(--surface);
978
- border: 1px solid var(--border);
979
- border-radius: var(--radius);
980
- overflow: hidden;
981
- }
982
- .plot-title {
983
- padding: 14px 20px 0;
984
- font-family: 'Space Mono', monospace;
985
- font-size: 11px;
986
- color: var(--muted);
987
- letter-spacing: 1.5px;
988
- text-transform: uppercase;
989
- }
990
-
991
- /* ── Summary markdown ── */
992
- .summary-wrap .prose, .summary-wrap p,
993
- .summary-wrap table, .summary-wrap th, .summary-wrap td {
994
- color: var(--text) !important;
995
- font-family: 'Space Mono', monospace !important;
996
- font-size: 12.5px !important;
997
- }
998
- .summary-wrap table {
999
- width: 100%;
1000
- border-collapse: collapse;
1001
- margin: 12px 0;
1002
- }
1003
- .summary-wrap th {
1004
- background: var(--surface2) !important;
1005
- padding: 8px 12px !important;
1006
- text-align: left;
1007
- border: 1px solid var(--border) !important;
1008
- color: var(--accent) !important;
1009
- }
1010
- .summary-wrap td {
1011
- padding: 7px 12px !important;
1012
- border: 1px solid var(--border) !important;
1013
- }
1014
- .summary-wrap h2 {
1015
- color: var(--accent) !important;
1016
- font-family: 'Syne', sans-serif !important;
1017
- font-size: 15px !important;
1018
- margin-top: 22px !important;
1019
- border-bottom: 1px solid var(--border);
1020
- padding-bottom: 6px;
1021
- }
1022
-
1023
- /* ── Pipeline steps ── */
1024
- .pipeline {
1025
- display: flex;
1026
- gap: 0;
1027
- margin: 28px 0 0;
1028
- }
1029
- .pipe-step {
1030
- flex: 1;
1031
- background: var(--surface);
1032
- border: 1px solid var(--border);
1033
- padding: 16px 14px;
1034
- text-align: center;
1035
- position: relative;
1036
- }
1037
- .pipe-step:not(:last-child)::after {
1038
- content: '→';
1039
- position: absolute;
1040
- right: -13px;
1041
- top: 50%;
1042
- transform: translateY(-50%);
1043
- color: var(--accent);
1044
- font-size: 16px;
1045
- z-index: 1;
1046
- background: var(--surface);
1047
- padding: 0 2px;
1048
- }
1049
- .pipe-step:first-child { border-radius: var(--radius) 0 0 var(--radius); }
1050
- .pipe-step:last-child { border-radius: 0 var(--radius) var(--radius) 0; }
1051
- .pipe-num {
1052
- font-family: 'Space Mono', monospace;
1053
- font-size: 18px;
1054
- font-weight: 700;
1055
- color: var(--accent);
1056
- display: block;
1057
- }
1058
- .pipe-name {
1059
- font-size: 11px;
1060
- color: var(--muted);
1061
- margin-top: 4px;
1062
- display: block;
1063
- }
1064
-
1065
- /* ── Gradio overrides ── */
1066
- .gr-box, .gr-panel, .gr-form, .gr-block,
1067
- .gradio-container .wrap, .gradio-container .gap,
1068
- .gradio-container .block { background: transparent !important; border: none !important; }
1069
- .gradio-container label { color: var(--text) !important; font-family: 'Syne', sans-serif !important; }
1070
- .gradio-container .gr-input, .gradio-container input,
1071
- .gradio-container textarea, .gradio-container select {
1072
- background: var(--surface) !important;
1073
- border: 1px solid var(--border) !important;
1074
- color: var(--text) !important;
1075
- border-radius: 8px !important;
1076
- }
1077
- .gradio-container .output-markdown { background: transparent !important; }
1078
- footer { display: none !important; }
1079
- .gradio-container .built-with { display: none !important; }
1080
  </style>
1081
  """
1082
 
1083
  HERO_HTML = """
1084
- <div class="mta-hero">
1085
- <div class="mta-badge">GENOMICS · GWAS · ML</div>
1086
- <h1 class="mta-title">Multi-Trait<br><span>Association Analysis</span></h1>
1087
- <p class="mta-subtitle">GWAS · Genomic Prediction · LD Decay · ML Feature Selection</p>
1088
- <div class="mta-pills">
1089
- <span class="mta-pill">Manhattan Plot</span>
1090
- <span class="mta-pill">QQ Plot + λ</span>
1091
- <span class="mta-pill">LD Decay</span>
1092
- <span class="mta-pill">5 ML Models</span>
1093
- <span class="mta-pill">GEBV Ranking</span>
1094
- <span class="mta-pill">ZIP Export</span>
1095
  </div>
1096
  </div>
1097
  """
1098
 
1099
- FORMAT_HTML = """
1100
- <div class="section-label">Input Format</div>
1101
- <div class="format-box">
1102
- <span class="col-tag">Col 1</span> Sample ID &nbsp;
1103
- <span class="col-tag">Col 2</span> Chromosome &nbsp;
1104
- <span class="col-tag">Col 3</span> Phenotype &nbsp;
1105
- <span class="col-tag">Col 4+</span> Markers<br><br>
1106
- <span class="col-tag">ID</span>, <span class="col-tag">Chr</span>, <span class="col-tag">Pheno</span>, <span class="val-tag">M0001</span>, <span class="val-tag">M0002</span>, ...<br>
1107
- <span class="comment">- , - , - ,</span> <span class="val-tag">1</span> , <span class="val-tag">1</span> , ... <span class="comment">&larr; marker chromosome row</span><br>
1108
- S1 , 1 , <span class="val-tag">45.2</span> , <span class="val-tag">0</span> , <span class="val-tag">1</span> , ...<br>
1109
- S2 , 2 , <span class="val-tag">38.7</span> , <span class="val-tag">1</span> , <span class="val-tag">2</span> , ...
 
 
 
 
 
1110
  </div>
1111
  """
1112
 
1113
- PIPELINE_HTML = """
1114
- <div class="section-label" style="margin-top:32px">Analysis Pipeline</div>
1115
  <div class="pipeline">
1116
- <div class="pipe-step"><span class="pipe-num">01</span><span class="pipe-name">QC Filter</span></div>
1117
  <div class="pipe-step"><span class="pipe-num">02</span><span class="pipe-name">GWAS</span></div>
1118
  <div class="pipe-step"><span class="pipe-num">03</span><span class="pipe-name">QQ / LD</span></div>
1119
- <div class="pipe-step"><span class="pipe-num">04</span><span class="pipe-name">ML Select</span></div>
1120
- <div class="pipe-step"><span class="pipe-num">05</span><span class="pipe-name">5 Models</span></div>
1121
- <div class="pipe-step"><span class="pipe-num">06</span><span class="pipe-name">Export ZIP</span></div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1122
  </div>
1123
  """
1124
 
1125
- # ──────────────────────────────────────────────────────────────
1126
  # GRADIO APP
1127
- # ──────────────────────────────────────────────────────────────
1128
- with gr.Blocks(css=HEAD_HTML, title="MTA Analysis") as app:
1129
 
1130
  gr.HTML(HERO_HTML)
1131
 
1132
  with gr.Row():
1133
- # ── LEFT: controls ──
1134
- with gr.Column(scale=1, min_width=320):
1135
- gr.HTML(FORMAT_HTML)
1136
- gr.HTML('<div class="section-label" style="margin-top:24px">Upload & Configure</div>')
1137
-
1138
- input_file = gr.File(
1139
- label="CSV Input File",
1140
- file_types=[".csv"])
1141
 
 
1142
  target_markers = gr.Slider(
1143
- minimum=100, maximum=5000, value=3000, step=100,
1144
- label="Target Markers to Select",
1145
- info="Top markers used in predictive models")
1146
 
1147
  with gr.Row(elem_classes=["run-btn"]):
1148
- run_button = gr.Button("⚡ Run Analysis", variant="primary", size="lg")
1149
 
1150
- gr.HTML(PIPELINE_HTML)
1151
 
1152
- # ── RIGHT: summary ──
1153
  with gr.Column(scale=2):
1154
- gr.HTML('<div class="section-label">Results Summary</div>')
1155
- with gr.Column(elem_classes=["summary-wrap"]):
1156
- summary_output = gr.Markdown(
1157
- value="*Results will appear here after analysis…*")
1158
 
1159
  # ── PLOTS ──
1160
- gr.HTML('<div class="section-label" style="margin-top:32px">Visualizations</div>')
1161
 
1162
- gr.HTML('<div class="plot-title">GWAS — Manhattan Plot</div>')
1163
- manhattan_output = gr.Image(show_label=False, elem_classes=["plot-card"])
 
1164
 
1165
  with gr.Row():
1166
- with gr.Column():
1167
- gr.HTML('<div class="plot-title">QQ Plot — Genomic Inflation</div>')
1168
- qq_output = gr.Image(show_label=False, elem_classes=["plot-card"])
1169
- with gr.Column():
1170
- gr.HTML('<div class="plot-title">Linkage Disequilibrium Decay</div>')
1171
- ld_output = gr.Image(show_label=False, elem_classes=["plot-card"])
1172
 
1173
  with gr.Row():
1174
- with gr.Column():
1175
- gr.HTML('<div class="plot-title">Model Performance Comparison</div>')
1176
- comparison_output = gr.Image(show_label=False, elem_classes=["plot-card"])
1177
- with gr.Column():
1178
- gr.HTML('<div class="plot-title">Observed vs Predicted (Best Model)</div>')
1179
- prediction_output = gr.Image(show_label=False, elem_classes=["plot-card"])
1180
 
1181
  # ── DOWNLOAD ──
1182
- gr.HTML('<div class="section-label" style="margin-top:32px">Export</div>')
1183
  with gr.Row():
1184
  with gr.Column(scale=1):
1185
- gr.HTML("""
1186
- <div style="background:#161b22;border:1px solid #30363d;border-radius:12px;padding:20px 24px;margin-bottom:8px">
1187
- <div style="font-family:'Space Mono',monospace;font-size:11px;color:#8b949e;letter-spacing:1.5px;text-transform:uppercase;margin-bottom:10px">ZIP Contents</div>
1188
- <div style="font-family:'Space Mono',monospace;font-size:12px;color:#e6edf3;line-height:2">
1189
- 📊 all_model_predictions.csv<br>
1190
- 🧬 mta_associations_×5.csv<br>
1191
- 🗺️ chromosome_summary.csv<br>
1192
- 🔬 qc_summary.csv<br>
1193
- 🖼️ 6 publication-quality plots
1194
- </div>
1195
- </div>
1196
- """)
1197
- with gr.Row(elem_classes=["dl-btn"]):
1198
- download_output = gr.File(label="⬇ Download All Results (ZIP)")
1199
- with gr.Column(scale=2):
1200
  pass
1201
 
1202
- # ── WIRE UP ──
1203
- run_button.click(
1204
  fn=run_mta_analysis,
1205
  inputs=[input_file, target_markers],
1206
- outputs=[summary_output, manhattan_output, qq_output, ld_output,
1207
- comparison_output, prediction_output, download_output])
1208
 
1209
  if __name__ == "__main__":
1210
  app.launch(share=True, show_error=True)
 
1
  # -*- coding: utf-8 -*-
2
  """
3
+ MTA Analysis Tool v5.0
4
+ White theme · Dark-blue text · GWAS only · Bug-fixed · Attractive UI
5
  """
6
 
7
  import gradio as gr
 
11
  matplotlib.use('Agg')
12
  import matplotlib.pyplot as plt
13
  import matplotlib.patches as mpatches
14
+ from matplotlib.collections import LineCollection
 
15
  import seaborn as sns
 
 
 
 
 
 
16
  from scipy import stats
17
  import os, warnings, tempfile, zipfile
18
  warnings.filterwarnings('ignore')
19
 
20
+ # ══════════════════════════════════════════════════════════════
21
+ # PLOT THEME — clean white, navy/blue palette
22
+ # ══════════════════════════════════════════════════════════════
23
+ BG = "#FFFFFF"
24
+ PANEL = "#F8FAFD"
25
+ GRID_C = "#E2EAF4"
26
+ TEXT_C = "#0D2B5E" # dark navy
27
+ MUTED_C = "#5A7599"
28
+ ACCENT = "#1A56DB" # royal blue
29
+ RED_C = "#E53E3E" # significance red
30
+ GOLD_C = "#D97706" # suggestive amber
31
+ GREEN_C = "#0D9488" # teal green
32
+ PURPLE_C = "#7C3AED"
33
 
34
  CHROM_PALETTE = [
35
+ "#1A56DB","#0D9488","#E53E3E","#7C3AED","#D97706",
36
+ "#0891B2","#059669","#DC2626","#6D28D9","#B45309",
37
+ "#2563EB","#10B981","#EF4444","#8B5CF6","#F59E0B",
38
+ "#0284C7","#34D399","#F87171","#A78BFA","#FCD34D",
39
+ "#1D4ED8","#047857",
40
  ]
41
 
42
+ def set_white_style():
43
  plt.rcParams.update({
44
+ 'figure.facecolor' : BG,
45
+ 'axes.facecolor' : PANEL,
46
+ 'axes.edgecolor' : GRID_C,
47
+ 'axes.labelcolor' : TEXT_C,
48
+ 'axes.titlecolor' : TEXT_C,
49
+ 'xtick.color' : TEXT_C,
50
+ 'ytick.color' : TEXT_C,
51
+ 'text.color' : TEXT_C,
52
+ 'grid.color' : GRID_C,
53
+ 'grid.linewidth' : 0.8,
54
+ 'figure.dpi' : 150,
55
+ 'font.family' : 'DejaVu Sans',
56
+ 'axes.spines.top' : False,
57
  'axes.spines.right': False,
58
+ 'legend.framealpha': 0.95,
59
+ 'legend.edgecolor' : GRID_C,
60
  })
61
 
62
+
63
+ # ══════════════════════════════════════════════════════════════
64
+ # PLOT 1 — MANHATTAN
65
+ # ══════════════════════════════════════════════════════════════
66
+ def plot_manhattan(marker_names, chromosomes, p_values, sig_set, bonf_thresh, save_path):
67
+ set_white_style()
68
 
69
  unique_chroms = sorted(set(chromosomes),
70
  key=lambda x: (int(x) if x.isdigit() else 999, x))
 
73
  GAP = max(8, len(marker_names) // 150)
74
  x_pos = np.zeros(len(marker_names))
75
  chrom_centers, chrom_to_idx = {}, {}
76
+ for i, c in enumerate(chromosomes):
 
77
  chrom_to_idx.setdefault(c, []).append(i)
78
 
79
  offset = 0
80
+ for ch in unique_chroms:
81
+ idxs = chrom_to_idx.get(ch, [])
82
  if not idxs: continue
83
+ for r, idx in enumerate(idxs):
84
+ x_pos[idx] = offset + r
85
+ chrom_centers[ch] = offset + (len(idxs) - 1) / 2
86
  offset += len(idxs) + GAP
87
 
88
+ fig = plt.figure(figsize=(22, 7), facecolor=BG)
89
+ ax = fig.add_subplot(111, facecolor=PANEL)
90
 
91
+ # Alternating chromosome bands
92
+ for ci, ch in enumerate(unique_chroms):
93
+ idxs = chrom_to_idx.get(ch, [])
94
  if not idxs: continue
95
  x0 = x_pos[idxs[0]] - 0.5
96
  x1 = x_pos[idxs[-1]] + 0.5
97
+ if ci % 2 == 0:
98
+ ax.axvspan(x0, x1, color='#EBF2FF', alpha=0.55, zorder=0)
99
 
100
+ for ci, ch in enumerate(unique_chroms):
101
+ idxs = chrom_to_idx.get(ch, [])
 
102
  if not idxs: continue
103
  col = CHROM_PALETTE[ci % len(CHROM_PALETTE)]
104
 
105
+ normal = [i for i in idxs if i not in sig_set]
106
+ sel = [i for i in idxs if i in sig_set]
107
 
108
  if normal:
109
  ax.scatter(x_pos[normal], log_p[normal],
110
+ c=col, s=12, alpha=0.60, linewidths=0, zorder=2)
111
  if sel:
112
+ # shadow glow
113
  ax.scatter(x_pos[sel], log_p[sel],
114
+ c=RED_C, s=260, alpha=0.15, linewidths=0, zorder=3)
115
  ax.scatter(x_pos[sel], log_p[sel],
116
+ c=RED_C, s=70, alpha=1.0,
117
+ edgecolors='white', linewidths=1.0,
118
  marker='D', zorder=4)
119
 
120
  # Threshold lines
121
+ ax.axhline(bonf_thresh, color=RED_C, ls='--', lw=1.8, alpha=0.85, zorder=5)
122
+ ax.text(offset * 0.005, bonf_thresh + log_p.max()*0.02,
123
+ f'Bonferroni α=0.05', color=RED_C, fontsize=9,
124
+ fontweight='bold', va='bottom')
125
+
126
+ sugg = -np.log10(1e-5)
127
+ if sugg < bonf_thresh:
128
+ ax.axhline(sugg, color=GOLD_C, ls=':', lw=1.5, alpha=0.8, zorder=5)
129
+ ax.text(offset * 0.005, sugg + log_p.max()*0.02,
130
+ 'Suggestive 1×10⁻⁵', color=GOLD_C, fontsize=9,
131
+ fontweight='bold', va='bottom')
132
 
 
133
  xtick_pos = [chrom_centers[c] for c in unique_chroms if c in chrom_centers]
134
  xtick_lab = [f'Chr {c}' for c in unique_chroms if c in chrom_centers]
135
  ax.set_xticks(xtick_pos)
136
  ax.set_xticklabels(xtick_lab,
137
+ fontsize=8.5 if len(unique_chroms) > 12 else 10,
138
  rotation=45 if len(unique_chroms) > 14 else 0,
139
+ ha='center', color=TEXT_C, fontweight='600')
140
  ax.set_xlim(-GAP, offset)
141
+ ax.set_ylim(bottom=0, top=log_p.max() * 1.16)
142
 
143
+ ax.set_ylabel('−log₁₀(P-value)', fontsize=13, color=TEXT_C,
144
+ fontweight='bold', labelpad=10)
145
+ ax.set_xlabel('Chromosome', fontsize=13, color=TEXT_C,
146
+ fontweight='bold', labelpad=10)
147
  ax.set_title('Genome-Wide Association Study · Manhattan Plot',
148
+ fontsize=17, color=TEXT_C, fontweight='bold', pad=20)
149
 
150
+ ax.yaxis.grid(True, color=GRID_C, linewidth=0.8, alpha=1.0)
 
151
  ax.set_axisbelow(True)
152
+ ax.tick_params(axis='both', colors=TEXT_C, length=4)
153
 
154
+ h_sig = mpatches.Patch(color=RED_C, label='Significant markers')
155
+ h_bonf = plt.Line2D([0],[0], color=RED_C, ls='--', lw=1.8, label='Bonferroni threshold')
156
+ h_sugg = plt.Line2D([0],[0], color=GOLD_C, ls=':', lw=1.5, label='Suggestive (1×10⁻⁵)')
157
+ ax.legend(handles=[h_sig, h_bonf, h_sugg], fontsize=10,
158
+ loc='upper right', facecolor=BG, edgecolor=GRID_C)
 
 
159
 
160
+ # Top annotation: highlight strongest hit per chrom
161
+ for ch in unique_chroms:
162
+ idxs = chrom_to_idx.get(ch, [])
163
+ if not idxs: continue
164
+ best = max(idxs, key=lambda i: log_p[i])
165
+ if log_p[best] >= bonf_thresh:
166
+ ax.annotate(marker_names[best],
167
+ xy=(x_pos[best], log_p[best]),
168
+ xytext=(0, 10), textcoords='offset points',
169
+ fontsize=6.5, color=TEXT_C, ha='center',
170
+ arrowprops=dict(arrowstyle='-', color=MUTED_C, lw=0.6))
171
+
172
+ plt.tight_layout(pad=1.8)
173
+ plt.savefig(save_path, dpi=200, bbox_inches='tight', facecolor=BG)
174
  plt.close(fig)
175
 
176
 
177
+ # ══════════════════════════════════════════════════════════════
178
  # PLOT 2 — QQ PLOT
179
+ # ══════════════════════════════════════════════════════════════
180
  def plot_qq(p_values, save_path):
181
+ set_white_style()
182
 
183
+ pv = np.clip(np.array(p_values)[~np.isnan(p_values)], 1e-300, 1.0)
184
+ n = len(pv)
185
  obs = np.sort(pv)
186
  exp = np.linspace(1/n, 1, n)
187
  log_obs = -np.log10(obs)
188
  log_exp = -np.log10(exp)
189
 
190
+ ci_up = -np.log10(stats.beta.ppf(0.025, np.arange(1,n+1), np.arange(n,0,-1)))
191
+ ci_lo = np.maximum(
192
+ -np.log10(stats.beta.ppf(0.975, np.arange(1,n+1), np.arange(n,0,-1))), 0)
193
 
194
  chi2 = stats.chi2.ppf(1 - pv, df=1)
195
  lam = np.median(chi2) / stats.chi2.ppf(0.5, df=1)
196
 
197
+ fig, ax = plt.subplots(figsize=(7, 7), facecolor=BG)
198
+ ax.set_facecolor(PANEL)
199
 
200
  ax.fill_between(log_exp, ci_lo, ci_up,
201
+ color=ACCENT, alpha=0.12, label='95% Confidence Band')
202
+
203
+ sc = ax.scatter(log_exp, log_obs, c=log_obs, cmap='RdYlBu_r',
204
+ s=14, alpha=0.80, linewidths=0, zorder=3)
205
+ plt.colorbar(sc, ax=ax, shrink=0.75, label='−log₁₀(P)')
206
+
207
+ maxv = max(log_obs.max(), log_exp.max()) * 1.06
208
+ ax.plot([0, maxv], [0, maxv], color=MUTED_C, lw=1.8, ls='--',
209
+ label='Expected null', zorder=2)
210
+
211
+ lam_col = GREEN_C if lam < 1.05 else (GOLD_C if lam < 1.10 else RED_C)
212
+ lam_lbl = ("Well-calibrated" if lam < 1.05
213
+ else "Minor inflation" if lam < 1.10 else "Significant inflation")
214
+ ax.text(0.05, 0.95,
215
+ f'λ = {lam:.4f}\n{lam_lbl}',
216
+ transform=ax.transAxes, fontsize=11, va='top', color=lam_col,
217
+ fontweight='bold',
218
+ bbox=dict(boxstyle='round,pad=0.5', fc=BG, ec=lam_col, lw=1.5, alpha=0.9))
219
+
220
+ ax.set_xlabel('Expected −log₁₀(P)', fontsize=13, color=TEXT_C, fontweight='bold')
221
+ ax.set_ylabel('Observed −log₁₀(P)', fontsize=13, color=TEXT_C, fontweight='bold')
222
+ ax.set_title('QQ Plot · Genomic Inflation Check',
223
+ fontsize=15, color=TEXT_C, fontweight='bold', pad=16)
224
  ax.set_xlim(0, maxv); ax.set_ylim(0, maxv)
225
+ ax.legend(fontsize=10, facecolor=BG, edgecolor=GRID_C)
226
+ ax.yaxis.grid(True, color=GRID_C, lw=0.8)
227
+ ax.xaxis.grid(True, color=GRID_C, lw=0.8)
228
+ ax.tick_params(colors=TEXT_C)
229
 
230
+ plt.tight_layout(pad=1.8)
231
+ plt.savefig(save_path, dpi=200, bbox_inches='tight', facecolor=BG)
 
 
 
 
 
 
 
 
 
 
 
232
  plt.close(fig)
233
  return lam
234
 
235
 
236
+ # ══════════════════════════════════════════════════════════════
237
  # PLOT 3 — LD DECAY
238
+ # ══════════════════════════════════════════════════════════════
239
  def plot_ld_decay(genotypes, chromosomes, save_path, max_m=250):
240
+ set_white_style()
241
 
242
  unique_chroms = sorted(set(chromosomes),
243
  key=lambda x: (int(x) if x.isdigit() else 999, x))
244
+ all_d, all_r2, chrom_mean = [], [], {}
 
245
 
246
+ for ch in unique_chroms:
247
+ idxs = [i for i,c in enumerate(chromosomes) if c == ch]
248
  if len(idxs) < 4: continue
249
  if len(idxs) > max_m:
250
  idxs = sorted(np.random.choice(idxs, max_m, replace=False))
251
+ G = genotypes[:, idxs].copy()
252
+ std = G.std(axis=0); std[std==0] = 1
253
+ G = (G - G.mean(axis=0)) / std
254
+ nm = G.shape[1]
255
  dl, rl = [], []
256
+ for i in range(nm-1):
257
  for j in range(i+1, min(i+60, nm)):
258
  r = np.corrcoef(G[:,i], G[:,j])[0,1]
259
  r2 = r**2 if not np.isnan(r) else 0
260
+ dl.append(j-i); rl.append(r2)
261
  if dl:
262
  all_d.extend(dl); all_r2.extend(rl)
263
+ chrom_mean[ch] = np.mean(rl)
264
 
265
+ fig, axes = plt.subplots(1, 2, figsize=(16, 6), facecolor=BG)
266
 
267
  # ── Left: decay curve ──
268
+ ax = axes[0]; ax.set_facecolor(PANEL)
269
  if all_d:
270
+ all_d = np.array(all_d)
271
+ all_r2 = np.array(all_r2)
272
+ max_d = min(int(all_d.max()), 50)
273
+ bins = np.arange(1, max_d+1)
274
  mu, se = [], []
275
  for b in bins:
276
  m = all_d == b
 
282
  mu = np.array(mu); se = np.array(se)
283
  v = ~np.isnan(mu)
284
 
285
+ ax.fill_between(bins[v],
286
+ np.clip(mu[v]-se[v], 0, 1),
287
+ np.clip(mu[v]+se[v], 0, 1),
288
+ color=ACCENT, alpha=0.15, label='±1 SE')
289
 
290
+ # gradient line
291
+ pts = np.array([bins[v], mu[v]]).T.reshape(-1, 1, 2)
292
+ segs = np.concatenate([pts[:-1], pts[1:]], axis=1)
293
+ lc = LineCollection(segs, cmap='Blues', linewidth=2.8, zorder=4)
 
294
  lc.set_array(mu[v])
295
  ax.add_collection(lc)
296
+ ax.scatter(bins[v], mu[v], c=mu[v], cmap='Blues',
297
+ s=22, zorder=5, linewidths=0.5,
298
+ edgecolors=MUTED_C)
299
 
300
+ ax.axhline(0.2, color=RED_C, ls='--', lw=1.3, alpha=0.8, label='r²=0.2 threshold')
301
 
302
+ start = mu[v][0] if len(mu[v]) > 0 else 1.0
 
 
303
  for i, r2 in enumerate(mu[v]):
304
+ if r2 <= start/2:
305
+ ax.axvline(bins[v][i], color=GOLD_C, ls='--', lw=1.3, alpha=0.9,
306
+ label=f'Half-decay at d={bins[v][i]}')
307
+ break
308
+
309
+ ax.set_xlabel('Marker Distance (index)', fontsize=12, color=TEXT_C, fontweight='bold')
310
+ ax.set_ylabel('Mean r²', fontsize=12, color=TEXT_C, fontweight='bold')
311
+ ax.set_title('LD Decay Across Chromosomes', fontsize=14, color=TEXT_C,
312
+ fontweight='bold', pad=12)
313
+ ax.set_ylim(0, 1); ax.tick_params(colors=TEXT_C)
314
+ ax.yaxis.grid(True, color=GRID_C, lw=0.8)
315
+ ax.legend(fontsize=9, facecolor=BG, edgecolor=GRID_C)
316
 
317
  # ── Right: per-chromosome bars ──
318
+ ax2 = axes[1]; ax2.set_facecolor(PANEL)
319
  if chrom_mean:
320
+ cs = sorted(chrom_mean.keys(), key=lambda x: (int(x) if x.isdigit() else 999, x))
321
  vals = [chrom_mean[c] for c in cs]
322
  cols = [CHROM_PALETTE[i % len(CHROM_PALETTE)] for i in range(len(cs))]
323
  bars = ax2.bar(range(len(cs)), vals, color=cols,
324
+ edgecolor='white', linewidth=0.8, alpha=0.88, width=0.65)
325
  ax2.set_xticks(range(len(cs)))
326
  ax2.set_xticklabels([f'Chr {c}' for c in cs],
327
  rotation=45 if len(cs) > 10 else 0,
328
+ fontsize=8.5, ha='right', color=TEXT_C)
 
329
  for bar, val in zip(bars, vals):
330
  ax2.text(bar.get_x() + bar.get_width()/2,
331
  bar.get_height() + 0.02,
332
  f'{val:.2f}', ha='center', va='bottom',
333
+ fontsize=8, color=TEXT_C, fontweight='600')
334
+ ax2.set_xlabel('Chromosome', fontsize=12, color=TEXT_C, fontweight='bold')
335
+ ax2.set_ylabel('Mean r²', fontsize=12, color=TEXT_C, fontweight='bold')
336
+ ax2.set_title('Mean LD per Chromosome', fontsize=14, color=TEXT_C,
337
  fontweight='bold', pad=12)
338
+ ax2.set_ylim(0, 1.15)
339
+ ax2.tick_params(colors=TEXT_C)
340
+ ax2.yaxis.grid(True, color=GRID_C, lw=0.8)
341
 
342
+ fig.suptitle('Linkage Disequilibrium (LD) Analysis',
343
+ fontsize=16, color=TEXT_C, fontweight='bold', y=1.01)
344
  plt.tight_layout(pad=2)
345
+ plt.savefig(save_path, dpi=200, bbox_inches='tight', facecolor=BG)
346
  plt.close(fig)
347
  return chrom_mean
348
 
349
 
350
+ # ══════════════════════════════════════════════════════════════
351
+ # PLOT 4 — GWAS EFFECT SIZE VOLCANO
352
+ # ══════════════════════════════════════════════════════════════
353
+ def plot_volcano(marker_names, effects, p_values, bonf_thresh, save_path, top_n=10):
354
+ set_white_style()
355
+
356
+ log_p = -np.log10(np.array(p_values) + 1e-300)
357
+ sig_mask = log_p >= bonf_thresh
358
+ sug_mask = (log_p >= -np.log10(1e-5)) & ~sig_mask
359
+
360
+ fig, ax = plt.subplots(figsize=(10, 7), facecolor=BG)
361
+ ax.set_facecolor(PANEL)
362
+
363
+ # Non-significant
364
+ ns = ~sig_mask & ~sug_mask
365
+ ax.scatter(np.array(effects)[ns], log_p[ns],
366
+ c=MUTED_C, s=10, alpha=0.35, linewidths=0, zorder=1, label='Non-significant')
367
+ # Suggestive
368
+ if sug_mask.any():
369
+ ax.scatter(np.array(effects)[sug_mask], log_p[sug_mask],
370
+ c=GOLD_C, s=20, alpha=0.65, linewidths=0, zorder=2, label='Suggestive')
371
+ # Significant
372
+ if sig_mask.any():
373
+ ax.scatter(np.array(effects)[sig_mask], log_p[sig_mask],
374
+ c=RED_C, s=55, alpha=0.90,
375
+ edgecolors='white', linewidths=0.7,
376
+ zorder=3, label='Significant')
377
+
378
+ ax.axhline(bonf_thresh, color=RED_C, ls='--', lw=1.6, alpha=0.8)
379
+ ax.axhline(-np.log10(1e-5), color=GOLD_C, ls=':', lw=1.3, alpha=0.8)
380
+ ax.axvline(0, color=MUTED_C, lw=0.8, ls='-', alpha=0.4)
381
+
382
+ # Annotate top hits
383
+ top_idx = np.argsort(log_p)[-top_n:]
384
+ for i in top_idx:
385
+ if log_p[i] >= bonf_thresh:
386
+ ax.annotate(marker_names[i],
387
+ xy=(effects[i], log_p[i]),
388
+ xytext=(6, 3), textcoords='offset points',
389
+ fontsize=7, color=TEXT_C,
390
+ arrowprops=dict(arrowstyle='->', color=MUTED_C, lw=0.6))
391
+
392
+ ax.set_xlabel('Effect Size (β)', fontsize=13, color=TEXT_C, fontweight='bold')
393
+ ax.set_ylabel('−log₁₀(P-value)', fontsize=13, color=TEXT_C, fontweight='bold')
394
+ ax.set_title('GWAS Volcano Plot · Effect Size vs Significance',
395
+ fontsize=15, color=TEXT_C, fontweight='bold', pad=16)
396
+ ax.legend(fontsize=10, facecolor=BG, edgecolor=GRID_C)
397
+ ax.yaxis.grid(True, color=GRID_C, lw=0.8)
398
+ ax.xaxis.grid(True, color=GRID_C, lw=0.8)
399
+ ax.tick_params(colors=TEXT_C)
400
+
401
+ plt.tight_layout(pad=1.8)
402
+ plt.savefig(save_path, dpi=200, bbox_inches='tight', facecolor=BG)
403
  plt.close(fig)
404
 
405
 
406
+ # ══════════════════════════════════════════════════════════════
407
+ # PLOT 5 — TOP GWAS HITS (bar chart)
408
+ # ══════════════════════════════════════════════════════════════
409
+ def plot_top_hits(marker_names, chromosomes, p_values, effects, bonf_thresh,
410
+ save_path, top_n=25):
411
+ set_white_style()
 
412
 
413
+ log_p = -np.log10(np.array(p_values) + 1e-300)
414
+ order = np.argsort(log_p)[-top_n:][::-1]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
415
 
416
+ unique_chroms = sorted(set(chromosomes),
417
+ key=lambda x: (int(x) if x.isdigit() else 999, x))
418
  col_map = {c: CHROM_PALETTE[i % len(CHROM_PALETTE)]
419
+ for i,c in enumerate(unique_chroms)}
 
420
 
421
+ fig, axes = plt.subplots(1, 2, figsize=(16, 8), facecolor=BG)
 
 
422
 
423
+ # Left: −log10(p) bars
424
+ ax = axes[0]; ax.set_facecolor(PANEL)
425
+ labels = [f"{marker_names[i]} (Chr {chromosomes[i]})" for i in order]
426
+ vals = [log_p[i] for i in order]
427
+ cols = [col_map.get(chromosomes[i], ACCENT) for i in order]
 
 
 
 
 
 
428
 
429
+ bars = ax.barh(range(len(order)), vals, color=cols,
430
+ edgecolor='white', linewidth=0.6, alpha=0.88, height=0.65)
431
+ ax.axvline(bonf_thresh, color=RED_C, ls='--', lw=1.5, alpha=0.9, label='Bonferroni')
432
+ ax.set_yticks(range(len(order)))
433
+ ax.set_yticklabels(labels, fontsize=8.5, color=TEXT_C)
434
+ ax.invert_yaxis()
435
+ ax.set_xlabel('−log₁₀(P-value)', fontsize=12, color=TEXT_C, fontweight='bold')
436
+ ax.set_title(f'Top {top_n} GWAS Hits', fontsize=14, color=TEXT_C,
437
+ fontweight='bold', pad=12)
438
+ ax.xaxis.grid(True, color=GRID_C, lw=0.8)
439
+ ax.tick_params(colors=TEXT_C)
440
+ ax.legend(fontsize=9, facecolor=BG, edgecolor=GRID_C)
441
+ for bar, val in zip(bars, vals):
442
+ ax.text(bar.get_width() + 0.05, bar.get_y() + bar.get_height()/2,
443
+ f'{val:.2f}', va='center', fontsize=8, color=TEXT_C)
444
+
445
+ # Right: effect size bars (positive=blue, negative=red)
446
+ ax2 = axes[1]; ax2.set_facecolor(PANEL)
447
+ eff_vals = [effects[i] for i in order]
448
+ eff_cols = [ACCENT if e >= 0 else RED_C for e in eff_vals]
449
+ ax2.barh(range(len(order)), eff_vals, color=eff_cols,
450
+ edgecolor='white', linewidth=0.6, alpha=0.85, height=0.65)
451
+ ax2.axvline(0, color=MUTED_C, lw=1.0, ls='-', alpha=0.5)
452
+ ax2.set_yticks(range(len(order)))
453
+ ax2.set_yticklabels(labels, fontsize=8.5, color=TEXT_C)
454
+ ax2.invert_yaxis()
455
+ ax2.set_xlabel('Effect Size (β)', fontsize=12, color=TEXT_C, fontweight='bold')
456
+ ax2.set_title('Effect Directions of Top Hits', fontsize=14, color=TEXT_C,
457
+ fontweight='bold', pad=12)
458
+ ax2.xaxis.grid(True, color=GRID_C, lw=0.8)
459
+ ax2.tick_params(colors=TEXT_C)
460
+
461
+ # Chromosome legend
462
  handles = []
463
  shown = set()
464
+ for i in order:
465
+ c = chromosomes[i]
466
  if c not in shown:
467
+ handles.append(mpatches.Patch(color=col_map[c], label=f'Chr {c}'))
 
468
  shown.add(c)
469
+ ax.legend(handles=handles + [plt.Line2D([0],[0], color=RED_C, ls='--',
470
+ lw=1.5, label='Bonferroni')],
471
+ fontsize=8, facecolor=BG, edgecolor=GRID_C, loc='lower right')
472
 
473
+ plt.tight_layout(pad=2)
474
+ plt.savefig(save_path, dpi=200, bbox_inches='tight', facecolor=BG)
475
  plt.close(fig)
476
 
477
 
478
+ # ══════════════════════════════════════════════════════════════
479
+ # MAIN ANALYSIS (GWAS only — no GEBV)
480
+ # ══════════════════════════════════════════════════════════════
481
  def run_mta_analysis(input_file, target_markers):
482
  try:
483
  if input_file is None:
 
489
  for d in [results_dir, plots_dir]:
490
  os.makedirs(d, exist_ok=True)
491
 
492
+ # ── LOAD ──────────────────────────────────
493
  df = pd.read_csv(input_file, sep=',', header=0)
494
+ # Col 0=ID, Col 1=Chromosome, Col 2=Phenotype, Col 3+=Markers
495
+ # Row 0 = marker chromosome assignments, Row 1+ = samples
496
+
497
+ marker_cols = df.columns[3:].tolist()
498
+ chrom_info_row = df.iloc[0, 3:].values.astype(str)
499
  chromosome_dict = {m: c for m, c in zip(marker_cols, chrom_info_row)}
500
 
501
+ df_data = df.iloc[1:].reset_index(drop=True)
502
+ sample_ids = df_data.iloc[:, 0].astype(str).values
503
+ phenotypes = pd.to_numeric(df_data.iloc[:, 2], errors='coerce').values
504
+ genotypes = df_data.iloc[:, 3:].apply(pd.to_numeric, errors='coerce').values
505
  marker_names = marker_cols
506
 
507
+ unique_chroms = sorted(set(chrom_info_row),
508
+ key=lambda x: (int(x) if x.isdigit() else 999, x))
509
  n_samples = len(sample_ids)
510
  n_markers = len(marker_names)
511
 
512
+ # ── QC ────────────────────────────────────
513
  miss_m = np.isnan(genotypes).sum(axis=0) / n_samples
514
  miss_s = np.isnan(genotypes).sum(axis=1) / n_markers
515
  maf = np.array([
 
526
  mnames_qc = [marker_names[i] for i in range(n_markers) if qc_m[i]]
527
  chrom_qc = [chromosome_dict[m] for m in mnames_qc]
528
 
529
+ n_rm_m = n_markers - len(mnames_qc)
530
+ n_rm_s = n_samples - len(ids_qc)
531
+
532
+ # Impute
533
  for i in range(geno_qc.shape[1]):
534
  col = geno_qc[:, i]
535
  mask = np.isnan(col)
 
538
 
539
  TARGET = min(int(target_markers), len(mnames_qc))
540
 
541
+ # ── GWAS ──────────────────────────────────
542
  pvals = np.ones(len(mnames_qc))
543
  effects = np.zeros(len(mnames_qc))
544
  gse = np.zeros(len(mnames_qc))
545
+ r2_vals = np.zeros(len(mnames_qc))
546
+
547
  for i in range(len(mnames_qc)):
548
  mk = geno_qc[:, i]
549
  if np.std(mk) > 0:
550
  try:
551
+ res = stats.linregress(mk, pheno_qc)
552
+ pvals[i] = res.pvalue
553
+ effects[i] = res.slope
554
+ gse[i] = res.stderr
555
+ r2_vals[i] = res.rvalue**2
556
+ except:
557
+ pass
558
 
559
  bonf = -np.log10(0.05 / len(mnames_qc))
560
  n_sig = int((pvals < 0.05/len(mnames_qc)).sum())
561
  n_sugg = int((pvals < 1e-5).sum())
562
+ sig_set = set(np.where(pvals < 0.05/len(mnames_qc))[0])
563
+
564
+ # ── ML marker selection (for annotation) ──
565
+ from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor
566
+ from sklearn.linear_model import ElasticNetCV
567
+ from sklearn.feature_selection import mutual_info_regression, f_regression
568
+ from sklearn.preprocessing import StandardScaler
569
 
 
570
  scaler = StandardScaler()
571
  X = scaler.fit_transform(geno_qc)
572
  y = pheno_qc
573
 
574
+ rf_fs = RandomForestRegressor(n_estimators=100, max_depth=10,
575
+ random_state=42, n_jobs=-1)
576
  rf_fs.fit(X, y)
577
+
578
+ gb_fs = GradientBoostingRegressor(n_estimators=100, max_depth=5,
579
+ random_state=42)
580
  gb_fs.fit(X, y)
581
+
582
  en_fs = ElasticNetCV(cv=5, random_state=42, max_iter=5000)
583
  en_fs.fit(X, y)
584
+
585
+ mi = mutual_info_regression(X, y, random_state=42)
586
+ fsc, _ = f_regression(X, y)
587
 
588
  votes = np.zeros(len(mnames_qc))
589
  for arr in [rf_fs.feature_importances_, gb_fs.feature_importances_,
 
591
  top = np.argsort(arr)[-TARGET:]
592
  votes[top] += 1
593
 
594
+ ml_top_set = set(np.argsort(votes)[-TARGET:])
595
+
596
+ # ── SAVE CSVs ─────────────────────────────
597
+ gwas_df = pd.DataFrame({
598
+ 'Rank' : 0,
599
+ 'Marker' : mnames_qc,
600
+ 'Chromosome' : chrom_qc,
601
+ 'Effect_beta' : effects,
602
+ 'StdError' : gse,
603
+ 'R2' : r2_vals,
604
+ 'P_value' : pvals,
605
+ 'neglog10_P' : -np.log10(pvals + 1e-300),
606
+ 'ML_votes' : votes.astype(int),
607
+ 'Significant' : (pvals < 0.05/len(mnames_qc)).astype(int),
608
+ 'Suggestive' : ((pvals < 1e-5) & (pvals >= 0.05/len(mnames_qc))).astype(int),
609
+ })
610
+ gwas_df = gwas_df.sort_values('P_value')
611
+ gwas_df['Rank'] = range(1, len(gwas_df)+1)
612
+ gwas_df.to_csv(os.path.join(results_dir, 'gwas_results.csv'), index=False)
613
+
614
+ # Per-chromosome summary
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
615
  chr_rows = []
616
+ for ch in unique_chroms:
617
+ ci = [i for i,c in enumerate(chrom_qc) if c == ch]
618
  if not ci: continue
619
  cp = pvals[ci]
620
  chr_rows.append({
621
+ 'Chromosome' : ch,
622
+ 'N_Markers' : len(ci),
623
+ 'N_Significant' : int((cp < 0.05/len(mnames_qc)).sum()),
624
+ 'N_Suggestive' : int((cp < 1e-5).sum()),
625
+ 'Min_Pvalue' : cp.min(),
626
+ 'Best_logP' : float(-np.log10(cp.min()+1e-300)),
627
+ 'Mean_Effect' : float(np.mean(np.abs(effects[ci]))),
628
+ 'Top_Marker' : mnames_qc[ci[int(np.argmin(cp))]],
629
  })
630
  pd.DataFrame(chr_rows).to_csv(
631
+ os.path.join(results_dir, 'chromosome_summary.csv'), index=False)
632
 
633
+ # QC summary
634
  pd.DataFrame({
635
  'Metric': ['Samples_raw','Samples_QC','Markers_raw','Markers_QC',
636
+ 'Target_Selected','Chromosomes',
637
+ 'Bonferroni_threshold_logP','N_Significant','N_Suggestive'],
638
+ 'Value' : [n_samples, len(ids_qc), n_markers, len(mnames_qc),
639
+ TARGET, len(unique_chroms),
640
+ round(bonf,4), n_sig, n_sugg]
641
  }).to_csv(os.path.join(results_dir,'qc_summary.csv'), index=False)
642
 
643
+ # ── PLOTS ─────────────────────────────────
644
+ man_path = os.path.join(plots_dir, 'manhattan_plot.png')
645
+ qq_path = os.path.join(plots_dir, 'qq_plot.png')
646
+ ld_path = os.path.join(plots_dir, 'ld_decay.png')
647
+ vol_path = os.path.join(plots_dir, 'volcano_plot.png')
648
+ top_path = os.path.join(plots_dir, 'top_gwas_hits.png')
 
649
 
650
+ plot_manhattan(mnames_qc, chrom_qc, pvals, sig_set, bonf, man_path)
651
  lam = plot_qq(pvals, qq_path)
652
  ld_summary = plot_ld_decay(geno_qc, chrom_qc, ld_path)
653
+ plot_volcano(mnames_qc, effects, pvals, bonf, vol_path)
654
+ plot_top_hits(mnames_qc, chrom_qc, pvals, effects, bonf, top_path)
 
655
 
656
+ # ── ZIP (all results + plots) ──────────────
657
+ zip_path = os.path.join(temp_dir, 'GWAS_Analysis_Results.zip')
658
  with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf:
659
  for root, _, files in os.walk(results_dir):
660
  for f in files:
 
662
  arc = os.path.relpath(fp, temp_dir)
663
  zf.write(fp, arc)
664
 
665
+ # ── SUMMARY ───────────────────────────────
666
+ lam_txt = ("✅ Well-calibrated (λ ≈ 1)" if lam < 1.05
667
  else "⚠️ Minor inflation — consider PCA correction" if lam < 1.10
668
  else "❌ Significant inflation — use mixed model (GEMMA/EMMAX)")
669
 
670
  gm_r2 = np.mean(list(ld_summary.values())) if ld_summary else 0
671
  ld_txt = ("Low LD — high marker density needed" if gm_r2 < 0.1
672
  else "Moderate LD — typical for diverse panels" if gm_r2 < 0.3
673
+ else "High LD — consider LD pruning before analysis")
674
+
675
+ # Top 8 hits table
676
+ top8 = gwas_df.head(8)
677
+ top8_rows = "\n".join(
678
+ f"| {int(r['Rank'])} | `{r['Marker']}` | Chr {r['Chromosome']} | "
679
+ f"{r['Effect_beta']:+.5f} | {r['P_value']:.3e} | {r['neglog10_P']:.3f} |"
680
+ for _, r in top8.iterrows())
681
+
682
+ # Top chromosomes
683
+ chr_df = pd.DataFrame(chr_rows).sort_values('Best_logP', ascending=False)
684
+ chr_rows_txt = "\n".join(
685
+ f"| Chr {r['Chromosome']} | {int(r['N_Markers'])} | "
686
+ f"{int(r['N_Significant'])} | {r['Best_logP']:.3f} | {r['Top_Marker']} |"
687
+ for _, r in chr_df.head(5).iterrows())
 
 
 
688
 
689
  summary = f"""
690
+ ## 📋 QC Summary
691
  | Metric | Value |
692
  |--------|-------|
693
+ | Samples (raw → QC) | {n_samples} → **{len(ids_qc)}** ({n_rm_s} removed) |
694
+ | Markers (raw → QC) | {n_markers} → **{len(mnames_qc)}** ({n_rm_m} removed) |
695
+ | Chromosomes | **{len(unique_chroms)}** |
696
+ | MAF filter | > 1% |
697
+ | Missing rate filter | < 10% |
698
 
699
+ ## 🔬 GWAS Results
700
  | Metric | Value |
701
  |--------|-------|
702
+ | Total markers tested | **{len(mnames_qc)}** |
703
+ | Bonferroni threshold | −log₁₀p = **{bonf:.3f}** |
704
+ | **Significant markers** | 🔴 **{n_sig}** |
705
+ | Suggestive markers | 🟡 {n_sugg} |
706
  | Genomic inflation λ | **{lam:.4f}** — {lam_txt} |
707
 
708
+ ## 🔗 LD Summary
709
  Global mean r² = **{gm_r2:.4f}** — {ld_txt}
710
 
711
+ ## 🏆 Top 8 GWAS Hits
712
+ | Rank | Marker | Chr | Effect β | P-value | −log₁₀P |
713
+ |------|--------|-----|----------|---------|---------|
714
+ {top8_rows}
715
 
716
+ ## 🗺️ Top Chromosomes (by significance)
717
+ | Chr | Markers | Significant | Best −log₁₀P | Top Marker |
718
+ |-----|---------|-------------|--------------|------------|
719
+ {chr_rows_txt}
720
 
721
+ ## 📁 ZIP Contains
722
+ - `results/gwas_results.csv` — full GWAS with effects, p-values, ML votes
723
+ - `results/chromosome_summary.csv` — per-chromosome statistics
724
+ - `results/qc_summary.csv` — QC metrics
 
 
 
 
 
 
 
 
 
 
 
725
  - `results/plots/manhattan_plot.png`
726
  - `results/plots/qq_plot.png`
727
  - `results/plots/ld_decay.png`
728
+ - `results/plots/volcano_plot.png`
729
+ - `results/plots/top_gwas_hits.png`
 
730
  """
731
+ return summary, man_path, qq_path, ld_path, vol_path, top_path, zip_path
732
 
733
  except Exception as e:
734
  import traceback
735
+ return (f"## ❌ Error\n```\n{e}\n\n{traceback.format_exc()}\n```",
736
+ None, None, None, None, None, None)
737
 
738
 
739
+ # ══════════════════════════════════════════════════════════════
740
+ # HTML / CSS — white background, dark-blue text
741
+ # ══════════════════════════════════════════════════════════════
742
+ THEME_CSS = """
743
  <style>
744
+ @import url('https://fonts.googleapis.com/css2?family=DM+Sans:wght@300;400;500;600;700&family=DM+Mono:wght@400;500&display=swap');
745
+
746
+ :root {
747
+ --navy: #0D2B5E;
748
+ --blue: #1A56DB;
749
+ --blue2: #2563EB;
750
+ --sky: #EBF2FF;
751
+ --skymed: #C7D9F8;
752
+ --teal: #0D9488;
753
+ --red: #E53E3E;
754
+ --amber: #D97706;
755
+ --white: #FFFFFF;
756
+ --offwhite:#F8FAFD;
757
+ --border: #D1DEF0;
758
+ --muted: #5A7599;
759
+ --radius: 14px;
760
+ --shadow: 0 2px 16px rgba(13,43,94,0.08);
761
+ }
762
+
763
+ body, .gradio-container {
764
+ background: var(--white) !important;
765
+ color: var(--navy) !important;
766
+ font-family: 'DM Sans', sans-serif !important;
767
+ }
768
+
769
+ /* ── Hero ── */
770
+ .hero {
771
+ background: linear-gradient(135deg, #0D2B5E 0%, #1A56DB 55%, #2563EB 100%);
772
+ border-radius: 20px;
773
+ padding: 52px 60px 44px;
774
+ margin-bottom: 30px;
775
+ position: relative;
776
+ overflow: hidden;
777
+ box-shadow: 0 8px 40px rgba(13,43,94,0.20);
778
+ }
779
+ .hero::before {
780
+ content:'';
781
+ position:absolute; top:-100px; right:-80px;
782
+ width:350px; height:350px; border-radius:50%;
783
+ background:radial-gradient(circle,rgba(255,255,255,0.10) 0%,transparent 70%);
784
+ }
785
+ .hero::after {
786
+ content:'';
787
+ position:absolute; bottom:-80px; left:60px;
788
+ width:260px; height:260px; border-radius:50%;
789
+ background:radial-gradient(circle,rgba(255,255,255,0.07) 0%,transparent 70%);
790
+ }
791
+ .hero-badge {
792
+ display:inline-flex; align-items:center; gap:8px;
793
+ background:rgba(255,255,255,0.15);
794
+ border:1px solid rgba(255,255,255,0.25);
795
+ color:#fff;
796
+ font-family:'DM Mono',monospace;
797
+ font-size:11px; letter-spacing:2px;
798
+ padding:5px 16px; border-radius:30px;
799
+ margin-bottom:20px;
800
+ }
801
+ .hero-badge::before {
802
+ content:''; width:7px; height:7px; border-radius:50%;
803
+ background:#3fb950; animation:pulse 2s infinite;
804
+ }
805
+ @keyframes pulse {
806
+ 0%,100%{opacity:1;transform:scale(1)}
807
+ 50%{opacity:0.6;transform:scale(1.3)}
808
+ }
809
+ .hero-title {
810
+ font-family:'DM Sans',sans-serif;
811
+ font-weight:700; font-size:42px; color:#fff;
812
+ line-height:1.1; margin:0 0 12px;
813
+ letter-spacing:-0.8px;
814
+ }
815
+ .hero-title em { color:#93C5FD; font-style:normal; }
816
+ .hero-sub {
817
+ color:rgba(255,255,255,0.72);
818
+ font-family:'DM Mono',monospace;
819
+ font-size:13px; margin:0 0 24px;
820
+ }
821
+ .hero-pills {
822
+ display:flex; gap:8px; flex-wrap:wrap;
823
+ }
824
+ .hero-pill {
825
+ background:rgba(255,255,255,0.14);
826
+ border:1px solid rgba(255,255,255,0.22);
827
+ color:#fff; border-radius:20px;
828
+ padding:4px 14px; font-size:12px;
829
+ }
830
+
831
+ /* ── Section header ── */
832
+ .sec-head {
833
+ display:flex; align-items:center; gap:12px;
834
+ font-family:'DM Mono',monospace;
835
+ font-size:10px; letter-spacing:2.5px;
836
+ color:var(--blue); text-transform:uppercase;
837
+ margin:28px 0 14px;
838
+ }
839
+ .sec-head::after {
840
+ content:''; flex:1; height:1px;
841
+ background:linear-gradient(90deg,var(--border),transparent);
842
+ }
843
+
844
+ /* ── Left panel card ── */
845
+ .left-card {
846
+ background:var(--offwhite);
847
+ border:1px solid var(--border);
848
+ border-radius:var(--radius);
849
+ padding:24px;
850
+ }
851
+
852
+ /* ── Format box ── */
853
+ .fmt-box {
854
+ background:var(--white);
855
+ border:1px solid var(--border);
856
+ border-left:4px solid var(--blue);
857
+ border-radius:10px;
858
+ padding:18px 20px;
859
+ font-family:'DM Mono',monospace;
860
+ font-size:11.5px;
861
+ color:var(--muted);
862
+ line-height:2.0;
863
+ margin-bottom:20px;
864
+ }
865
+ .fmt-box .col { color:var(--blue); font-weight:600; }
866
+ .fmt-box .val { color:var(--teal); }
867
+ .fmt-box .cmt { color:var(--border); }
868
+
869
+ /* ── Run button ── */
870
+ .run-btn button {
871
+ background:linear-gradient(135deg,#1A56DB,#2563EB) !important;
872
+ border:none !important;
873
+ border-radius:12px !important;
874
+ color:#fff !important;
875
+ font-family:'DM Sans',sans-serif !important;
876
+ font-weight:600 !important;
877
+ font-size:16px !important;
878
+ padding:15px 0 !important;
879
+ width:100% !important;
880
+ box-shadow:0 4px 20px rgba(26,86,219,0.35) !important;
881
+ transition:all 0.2s !important;
882
+ cursor:pointer !important;
883
+ }
884
+ .run-btn button:hover {
885
+ transform:translateY(-2px) !important;
886
+ box-shadow:0 8px 30px rgba(26,86,219,0.45) !important;
887
+ }
888
+
889
+ /* ── Pipeline ── */
890
+ .pipeline {
891
+ display:flex; margin-top:20px;
892
+ }
893
+ .pipe-step {
894
+ flex:1;
895
+ background:var(--white);
896
+ border:1px solid var(--border);
897
+ padding:14px 8px;
898
+ text-align:center;
899
+ position:relative;
900
+ }
901
+ .pipe-step:not(:last-child)::after {
902
+ content:'›'; position:absolute;
903
+ right:-10px; top:50%; transform:translateY(-50%);
904
+ color:var(--blue); font-size:18px; font-weight:700;
905
+ background:var(--white); padding:0 2px; z-index:1;
906
+ }
907
+ .pipe-step:first-child { border-radius:10px 0 0 10px; }
908
+ .pipe-step:last-child { border-radius:0 10px 10px 0; }
909
+ .pipe-num {
910
+ font-family:'DM Mono',monospace;
911
+ font-size:17px; font-weight:500;
912
+ color:var(--blue); display:block;
913
+ }
914
+ .pipe-name {
915
+ font-size:10px; color:var(--muted);
916
+ margin-top:3px; display:block;
917
+ }
918
+
919
+ /* ── Summary card ── */
920
+ .sum-card {
921
+ background:var(--white);
922
+ border:1px solid var(--border);
923
+ border-radius:var(--radius);
924
+ padding:24px 28px;
925
+ box-shadow:var(--shadow);
926
+ }
927
+ .sum-card h2 {
928
+ color:var(--blue) !important;
929
+ font-family:'DM Sans',sans-serif !important;
930
+ font-size:15px !important;
931
+ font-weight:600 !important;
932
+ margin-top:22px !important;
933
+ padding-bottom:6px;
934
+ border-bottom:1px solid var(--border);
935
+ }
936
+ .sum-card table {
937
+ width:100%; border-collapse:collapse; margin:10px 0;
938
+ }
939
+ .sum-card th {
940
+ background:var(--sky) !important;
941
+ color:var(--navy) !important;
942
+ font-family:'DM Mono',monospace !important;
943
+ font-size:11px !important;
944
+ padding:8px 12px !important;
945
+ border:1px solid var(--border) !important;
946
+ text-align:left;
947
+ }
948
+ .sum-card td {
949
+ color:var(--navy) !important;
950
+ font-size:12.5px !important;
951
+ padding:7px 12px !important;
952
+ border:1px solid var(--border) !important;
953
+ font-family:'DM Mono',monospace !important;
954
+ }
955
+ .sum-card td code, .sum-card p code {
956
+ background:var(--sky); color:var(--blue);
957
+ border-radius:4px; padding:1px 5px;
958
+ font-family:'DM Mono',monospace;
959
+ font-size:11.5px;
960
+ }
961
+ .sum-card p { color:var(--navy) !important; font-size:13px !important; }
962
+
963
+ /* ── Plot card ── */
964
+ .plot-wrap {
965
+ background:var(--white);
966
+ border:1px solid var(--border);
967
+ border-radius:var(--radius);
968
+ overflow:hidden;
969
+ box-shadow:var(--shadow);
970
+ margin-bottom:16px;
971
+ }
972
+ .plot-label {
973
+ padding:12px 18px;
974
+ font-family:'DM Mono',monospace;
975
+ font-size:10px; letter-spacing:2px;
976
+ text-transform:uppercase;
977
+ color:var(--muted);
978
+ border-bottom:1px solid var(--border);
979
+ background:var(--offwhite);
980
+ }
981
+
982
+ /* ── Download box ── */
983
+ .dl-box {
984
+ background:var(--sky);
985
+ border:1px solid var(--skymed);
986
+ border-radius:var(--radius);
987
+ padding:20px 24px;
988
+ }
989
+ .dl-box-title {
990
+ font-family:'DM Mono',monospace;
991
+ font-size:10px; letter-spacing:2px;
992
+ color:var(--blue); text-transform:uppercase;
993
+ margin-bottom:10px;
994
+ }
995
+ .dl-box-list {
996
+ font-family:'DM Mono',monospace;
997
+ font-size:12px; color:var(--navy);
998
+ line-height:2.0;
999
+ }
1000
+ .dl-box-list span { color:var(--blue); font-weight:500; }
1001
+
1002
+ /* ── Gradio overrides ── */
1003
+ .gradio-container .block,
1004
+ .gradio-container .wrap,
1005
+ .gradio-container .gap {
1006
+ background:transparent !important;
1007
+ border:none !important;
1008
+ box-shadow:none !important;
1009
+ }
1010
+ .gradio-container label {
1011
+ color:var(--navy) !important;
1012
+ font-family:'DM Sans',sans-serif !important;
1013
+ font-weight:500 !important;
1014
+ }
1015
+ .gradio-container input,
1016
+ .gradio-container textarea {
1017
+ background:var(--white) !important;
1018
+ border:1px solid var(--border) !important;
1019
+ color:var(--navy) !important;
1020
+ border-radius:8px !important;
1021
+ font-family:'DM Sans',sans-serif !important;
1022
+ }
1023
+ .gradio-container input[type=range] {
1024
+ accent-color:var(--blue) !important;
1025
+ }
1026
+ .gradio-container .output-markdown {
1027
+ background:transparent !important;
1028
+ color:var(--navy) !important;
1029
+ }
1030
+ footer, .gradio-container .built-with,
1031
+ .gradio-container .svelte-1ipelgc { display:none !important; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1032
  </style>
1033
  """
1034
 
1035
  HERO_HTML = """
1036
+ <div class="hero">
1037
+ <div class="hero-badge">GWAS · QQ · LD DECAY · ML SELECTION</div>
1038
+ <h1 class="hero-title">Multi-Trait <em>Association</em><br>Analysis Platform</h1>
1039
+ <p class="hero-sub">Genome-Wide Association · Quality Control · LD Analysis · Marker Discovery</p>
1040
+ <div class="hero-pills">
1041
+ <span class="hero-pill">Manhattan Plot</span>
1042
+ <span class="hero-pill">QQ Plot + λ</span>
1043
+ <span class="hero-pill">LD Decay</span>
1044
+ <span class="hero-pill">Volcano Plot</span>
1045
+ <span class="hero-pill">Top Hits</span>
1046
+ <span class="hero-pill">ZIP Export</span>
1047
  </div>
1048
  </div>
1049
  """
1050
 
1051
+ FMT_HTML = """
1052
+ <div class="sec-head">Input Format</div>
1053
+ <div class="fmt-box">
1054
+ <span class="col">Col 1</span> Sample ID &nbsp;
1055
+ <span class="col">Col 2</span> Chromosome &nbsp;
1056
+ <span class="col">Col 3</span> Phenotype &nbsp;
1057
+ <span class="col">Col 4+</span> Markers<br><br>
1058
+ <span class="col">ID</span>, <span class="col">Chr</span>, <span class="col">Pheno</span>,
1059
+ <span class="val">M0001</span>, <span class="val">M0002</span>, ...<br>
1060
+ <span class="cmt">- , - , - ,</span>
1061
+ <span class="val">1</span> ,
1062
+ <span class="val">1</span> , ...
1063
+ <span class="cmt"> ← marker chr row</span><br>
1064
+ S1 , 1 , <span class="val">45.2</span> ,
1065
+ <span class="val">0</span> ,
1066
+ <span class="val">1</span> , ...
1067
  </div>
1068
  """
1069
 
1070
+ PIPE_HTML = """
1071
+ <div class="sec-head" style="margin-top:24px">Pipeline</div>
1072
  <div class="pipeline">
1073
+ <div class="pipe-step"><span class="pipe-num">01</span><span class="pipe-name">QC</span></div>
1074
  <div class="pipe-step"><span class="pipe-num">02</span><span class="pipe-name">GWAS</span></div>
1075
  <div class="pipe-step"><span class="pipe-num">03</span><span class="pipe-name">QQ / LD</span></div>
1076
+ <div class="pipe-step"><span class="pipe-num">04</span><span class="pipe-name">Volcano</span></div>
1077
+ <div class="pipe-step"><span class="pipe-num">05</span><span class="pipe-name">Export</span></div>
1078
+ </div>
1079
+ """
1080
+
1081
+ DL_HTML = """
1082
+ <div class="dl-box">
1083
+ <div class="dl-box-title">ZIP Contents</div>
1084
+ <div class="dl-box-list">
1085
+ <span>📊</span> gwas_results.csv — full marker statistics<br>
1086
+ <span>🗺️</span> chromosome_summary.csv<br>
1087
+ <span>🔬</span> qc_summary.csv<br>
1088
+ <span>🖼️</span> manhattan_plot.png<br>
1089
+ <span>🖼️</span> qq_plot.png<br>
1090
+ <span>🖼️</span> ld_decay.png<br>
1091
+ <span>🖼️</span> volcano_plot.png<br>
1092
+ <span>🖼️</span> top_gwas_hits.png
1093
+ </div>
1094
  </div>
1095
  """
1096
 
1097
+ # ══════════════════════════════════════════════════════════════
1098
  # GRADIO APP
1099
+ # ══════════════════════════════════════════════════════════════
1100
+ with gr.Blocks(css=THEME_CSS, title="MTA Analysis") as app:
1101
 
1102
  gr.HTML(HERO_HTML)
1103
 
1104
  with gr.Row():
1105
+ # ── LEFT ──
1106
+ with gr.Column(scale=1, min_width=300):
1107
+ gr.HTML(FMT_HTML)
1108
+ gr.HTML('<div class="sec-head">Configure</div>')
 
 
 
 
1109
 
1110
+ input_file = gr.File(label="Upload CSV File", file_types=[".csv"])
1111
  target_markers = gr.Slider(
1112
+ 100, 5000, value=3000, step=100,
1113
+ label="Target Markers for ML Selection",
1114
+ info="Used for feature voting; does not affect GWAS p-values")
1115
 
1116
  with gr.Row(elem_classes=["run-btn"]):
1117
+ run_btn = gr.Button("⚡ Run GWAS Analysis", variant="primary", size="lg")
1118
 
1119
+ gr.HTML(PIPE_HTML)
1120
 
1121
+ # ── RIGHT ──
1122
  with gr.Column(scale=2):
1123
+ gr.HTML('<div class="sec-head">Results Summary</div>')
1124
+ with gr.Column(elem_classes=["sum-card"]):
1125
+ summary_out = gr.Markdown(value="*Upload a CSV and click Run to begin.*")
 
1126
 
1127
  # ── PLOTS ──
1128
+ gr.HTML('<div class="sec-head" style="margin-top:10px">Visualizations</div>')
1129
 
1130
+ with gr.Column(elem_classes=["plot-wrap"]):
1131
+ gr.HTML('<div class="plot-label">Manhattan Plot — Genome-Wide Significance</div>')
1132
+ manhattan_out = gr.Image(show_label=False)
1133
 
1134
  with gr.Row():
1135
+ with gr.Column(elem_classes=["plot-wrap"]):
1136
+ gr.HTML('<div class="plot-label">QQ Plot — Genomic Inflation Factor</div>')
1137
+ qq_out = gr.Image(show_label=False)
1138
+ with gr.Column(elem_classes=["plot-wrap"]):
1139
+ gr.HTML('<div class="plot-label">LD Decay — Linkage Disequilibrium</div>')
1140
+ ld_out = gr.Image(show_label=False)
1141
 
1142
  with gr.Row():
1143
+ with gr.Column(elem_classes=["plot-wrap"]):
1144
+ gr.HTML('<div class="plot-label">Volcano Plot — Effect vs Significance</div>')
1145
+ vol_out = gr.Image(show_label=False)
1146
+ with gr.Column(elem_classes=["plot-wrap"]):
1147
+ gr.HTML('<div class="plot-label">Top GWAS Hits — Ranked by −log₁₀(P)</div>')
1148
+ top_out = gr.Image(show_label=False)
1149
 
1150
  # ── DOWNLOAD ──
1151
+ gr.HTML('<div class="sec-head" style="margin-top:10px">Export</div>')
1152
  with gr.Row():
1153
  with gr.Column(scale=1):
1154
+ gr.HTML(DL_HTML)
1155
+ with gr.Column(scale=1):
1156
+ download_out = gr.File(label="⬇ Download All Results (ZIP)")
1157
+ with gr.Column(scale=1):
 
 
 
 
 
 
 
 
 
 
 
1158
  pass
1159
 
1160
+ run_btn.click(
 
1161
  fn=run_mta_analysis,
1162
  inputs=[input_file, target_markers],
1163
+ outputs=[summary_out, manhattan_out, qq_out, ld_out,
1164
+ vol_out, top_out, download_out])
1165
 
1166
  if __name__ == "__main__":
1167
  app.launch(share=True, show_error=True)