softwareDevelopment commited on
Commit
b1a538f
Β·
verified Β·
1 Parent(s): aa20e40

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +808 -587
app.py CHANGED
@@ -1,24 +1,31 @@
1
  # -*- coding: utf-8 -*-
2
  """
3
- MTA Analysis Tool v7.3 - Optimized GWAS Platform
4
- SPEED OPTIMIZATIONS:
5
- - Removed Mixed Linear Model (slowest β€” statsmodels per-marker)
6
- - Removed Random Forest & Gradient Boosting (100x slower)
7
- - Kept Linear Regression (vectorised β€” ~fastest)
8
- - Kept ElasticNet (moderate speed, good regularization)
9
- - Vectorised LD computation (no nested loops)
10
- - Max 100 markers for LD to keep snappy
11
- - Reduced bootstrap iterations
12
- - Fixed output ID generation
13
- ~10-15x FASTER than v7.1
14
-
15
- LD DECAY PLOT (v7.3):
16
- - Replaced 3-panel LD plot with a single scatter-style LD decay
17
- - Individual marker-pair dots coloured by chromosome
18
- - Green filled smooth median decay curve (cubic spline)
19
- - Dashed rΒ²=0.2 reference line
20
- - Chromosome legend on the right
21
- - Matches classic LD decay scatter style (rΒ² vs genetic distance in cM)
 
 
 
 
 
 
 
22
  """
23
 
24
  import gradio as gr
@@ -27,501 +34,711 @@ import numpy as np
27
  import matplotlib
28
  matplotlib.use('Agg')
29
  import matplotlib.pyplot as plt
 
30
  from scipy import stats
31
- from scipy.optimize import curve_fit
32
  from scipy.interpolate import make_interp_spline
33
  import os, warnings, tempfile, zipfile
34
  from sklearn.linear_model import ElasticNetCV
35
  from sklearn.preprocessing import StandardScaler
36
- from sklearn.metrics import r2_score
37
  warnings.filterwarnings('ignore')
38
 
39
  # ══════════════════════════════════════════════════════════════
40
  # THEME
41
  # ══════════════════════════════════════════════════════════════
42
  BG = "#FDFBFF"
43
- PANEL = "#F6F0FB"
44
- GRID_C = "#E8DFF5"
45
- TEXT_C = "#3D2B6B"
46
- ACCENT = "#8B5CF6"
47
- RED_C = "#F472B6"
48
- GOLD_C = "#FBBF24"
49
- TEAL_C = "#22D3EE"
50
- ORANGE_C = "#F97316"
 
51
 
52
  CHROM_PALETTE = [
53
- "#A78BFA","#F9A8D4","#6EE7B7","#7DD3FC","#FCD34D",
54
- "#C4B5FD","#FBCFE8","#86EFAC","#BAE6FD","#FDE68A",
55
- "#DDD6FE","#FDE8F4","#A7F3D0","#E0F2FE","#FEF3C7",
56
- "#8B5CF6","#EC4899","#10B981","#0EA5E9","#F59E0B",
57
- "#6366F1","#EF4444","#14B8A6","#F97316","#84CC16",
58
  ]
59
 
60
- def set_pastel_style():
61
  plt.rcParams.update({
62
- 'figure.facecolor': BG, 'axes.facecolor': PANEL,
63
- 'axes.edgecolor': GRID_C, 'axes.labelcolor': TEXT_C,
64
- 'axes.titlecolor': TEXT_C, 'xtick.color': TEXT_C,
65
- 'ytick.color': TEXT_C, 'text.color': TEXT_C,
66
- 'grid.color': GRID_C, 'grid.linewidth': 0.8,
67
- 'figure.dpi': 120, 'font.family': 'DejaVu Sans',
68
- 'axes.spines.top': False, 'axes.spines.right': False,
69
- 'legend.framealpha': 0.95, 'legend.edgecolor': GRID_C,
70
  })
71
 
 
72
  # ══════════════════════════════════════════════════════════════
73
- # PLOT: MANHATTAN + LOD
74
  # ══════════════════════════════════════════════════════════════
75
 
76
- def plot_manhattan_with_lod(marker_names, chromosomes, p_values, lod_scores,
77
- sig_set, bonf_thresh, save_path):
78
- """Manhattan plot with LOD scores overlay."""
79
- set_pastel_style()
80
- unique_chroms = sorted(set(chromosomes),
81
- key=lambda x: (int(x) if str(x).isdigit() else 999, str(x)))
82
- log_p = -np.log10(np.array(p_values) + 1e-300)
83
- lod_array = np.array(lod_scores)
84
-
85
- GAP = max(8, len(marker_names) // 150)
86
- x_pos = np.zeros(len(marker_names))
87
- chrom_to_idx = {}
88
- for i, c in enumerate(chromosomes):
89
- chrom_to_idx.setdefault(c, []).append(i)
90
-
91
- offset = 0
92
- for ch in unique_chroms:
93
- idxs = chrom_to_idx.get(ch, [])
94
- if not idxs: continue
95
- for r, idx in enumerate(idxs):
96
- x_pos[idx] = offset + r
97
- offset += len(idxs) + GAP
98
 
99
- fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(18, 8),
100
- gridspec_kw={'height_ratios': [2, 1]},
101
- facecolor=BG)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
102
 
103
- # Main Manhattan plot
104
- for ci, ch in enumerate(unique_chroms):
105
- idxs = chrom_to_idx.get(ch, [])
106
- if not idxs: continue
107
- if ci % 2 == 0:
108
- ax1.axvspan(x_pos[idxs[0]] - 0.5, x_pos[idxs[-1]] + 0.5,
109
- color='#EDE9FE', alpha=0.45, zorder=0)
110
- ax2.axvspan(x_pos[idxs[0]] - 0.5, x_pos[idxs[-1]] + 0.5,
111
- color='#EDE9FE', alpha=0.45, zorder=0)
112
 
113
- col = CHROM_PALETTE[ci % len(CHROM_PALETTE)]
114
- normal = [i for i in idxs if i not in sig_set]
115
- sel = [i for i in idxs if i in sig_set]
116
 
117
- if normal:
118
- ax1.scatter(x_pos[normal], log_p[normal],
119
- c=col, s=10, alpha=0.65, linewidths=0, zorder=2)
120
- if sel:
121
- ax1.scatter(x_pos[sel], log_p[sel],
122
- c=RED_C, s=200, alpha=0.18, linewidths=0, zorder=3)
123
- ax1.scatter(x_pos[sel], log_p[sel],
124
- c=RED_C, s=55, alpha=1.0,
125
- edgecolors='white', linewidths=1.0,
126
- marker='D', zorder=4)
127
 
128
- ax1.axhline(bonf_thresh, color=RED_C, ls='--', lw=1.8, alpha=0.85,
129
- label=f'Bonferroni ({bonf_thresh:.1f})', zorder=5)
130
- ax1.axhline(3, color=GOLD_C, ls=':', lw=1.5, alpha=0.8, label='LOD = 3')
131
 
132
- # LOD twin axis
133
- ax1_twin = ax1.twinx()
134
- ax1_twin.scatter(x_pos, lod_array, c=TEAL_C, s=6, alpha=0.35,
135
- marker='x', zorder=1)
136
- ax1_twin.set_ylabel('LOD Score', fontsize=11, color=TEAL_C, fontweight='bold')
137
- ax1_twin.tick_params(axis='y', colors=TEAL_C)
138
- ax1_twin.set_ylim(0, max(lod_array.max() * 1.1, 1))
 
 
 
139
 
140
- ax1.set_xlim(-GAP, offset)
141
- ax1.set_ylim(bottom=0, top=max(log_p.max() * 1.15, 1))
142
- ax1.set_ylabel('βˆ’log₁₀(P)', fontsize=12, fontweight='bold', labelpad=8)
143
- ax1.set_title('GWAS Manhattan Plot with LOD Scores', fontsize=14, fontweight='bold', pad=12)
144
- ax1.yaxis.grid(True, color=GRID_C, linewidth=0.7)
145
- ax1.legend(loc='upper right', fontsize=9)
146
 
147
- # LOD panel
148
- ax2.plot(x_pos, lod_array, color=TEAL_C, linewidth=1.2, alpha=0.8)
149
- ax2.fill_between(x_pos, 0, lod_array, color=TEAL_C, alpha=0.18)
150
- ax2.axhline(3, color=GOLD_C, ls='--', lw=1.3, alpha=0.8)
151
- ax2.set_xlim(-GAP, offset)
152
- ax2.set_ylabel('LOD Score', fontsize=11, fontweight='bold')
153
- ax2.set_xlabel('Chromosome', fontsize=11, fontweight='bold')
154
- ax2.yaxis.grid(True, color=GRID_C, linewidth=0.7)
155
 
156
- plt.tight_layout(pad=1.5)
157
- plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=BG)
158
- plt.close(fig)
 
 
 
 
 
 
159
 
160
 
161
  # ══════════════════════════════════════════════════════════════
162
- # LD COMPUTATION (vectorised)
163
  # ══════════════════════════════════════════════════════════════
164
 
165
- def _compute_ld_vectorised(G, pos_arr, max_lag=40):
166
- """Vectorised pairwise rΒ² and D' computation."""
167
- n_markers = G.shape[1]
168
- all_dist, all_r2, all_dp = [], [], []
 
 
 
 
169
 
170
- for lag in range(1, min(max_lag + 1, n_markers)):
171
- x = G[:, :n_markers - lag].astype(float)
172
- y = G[:, lag:].astype(float)
173
 
174
- # rΒ²
175
- xm = x - x.mean(axis=0)
176
- ym = y - y.mean(axis=0)
177
- num = (xm * ym).sum(axis=0)
178
- denom = np.sqrt((xm**2).sum(axis=0) * (ym**2).sum(axis=0))
179
  with np.errstate(invalid='ignore', divide='ignore'):
180
- r = np.where(denom > 0, num / denom, 0.0)
181
- r2 = r ** 2
182
 
183
- # D'
184
- p1 = x.mean(axis=0) / 2.0
185
- p2 = y.mean(axis=0) / 2.0
186
- p11 = ((x == 2) & (y == 2)).mean(axis=0) / 2.0
187
  D = p11 - p1 * p2
188
  with np.errstate(invalid='ignore', divide='ignore'):
189
  Dmax = np.where(D < 0,
190
- np.minimum(p1 * (1 - p2), (1 - p1) * p2),
191
- np.minimum(p1 * p2, (1 - p1) * (1 - p2)))
192
  dp = np.where(Dmax > 0, np.abs(D / Dmax), 0.0)
193
 
194
- dist = np.abs(pos_arr[lag:] - pos_arr[:n_markers - lag])
195
 
196
- all_dist.append(dist)
197
- all_r2.append(r2)
198
- all_dp.append(dp)
199
 
200
- if not all_dist:
201
  return np.array([]), np.array([]), np.array([])
202
-
203
- return (np.concatenate(all_dist),
204
- np.concatenate(all_r2),
205
- np.concatenate(all_dp))
206
 
207
 
208
  # ══════════════════════════════════════════════════════════════
209
- # PLOT: LD DECAY β€” scatter style (v7.3)
210
  # ══════════════════════════════════════════════════════════════
211
 
212
- def plot_enhanced_ld_decay(genotypes, chromosomes, positions, save_path, max_m=100):
213
  """
214
- LD decay scatter plot β€” chromosome-coloured dots with smooth median decay
215
- curve and filled area, styled after the classic rΒ² vs genetic distance plot.
216
-
217
- - One scatter dot per marker pair, coloured by chromosome
218
- - Green filled cubic-spline median decay curve
219
- - Dashed rΒ²=0.2 reference line
220
- - Chromosome legend (right side)
 
221
  """
222
- set_pastel_style()
223
 
224
  unique_chroms = sorted(set(chromosomes),
225
  key=lambda x: (int(x) if str(x).isdigit() else 999, str(x)))
226
 
227
- # ── collect all pairwise (dist, rΒ², chrom) ──────────────────────────────
228
- all_dist, all_r2, all_chrom_label = [], [], []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
229
  chrom_stats = {}
230
 
231
  for ch in unique_chroms:
232
- idxs = [i for i, c in enumerate(chromosomes) if c == ch]
233
  if len(idxs) < 4:
234
  continue
235
  if len(idxs) > max_m:
236
  idxs = sorted(np.random.choice(idxs, max_m, replace=False))
237
 
238
- G = genotypes[:, idxs].copy()
239
- pos_arr = np.array([positions[i] for i in idxs], dtype=float)
240
 
241
- dist, r2, dp = _compute_ld_vectorised(G, pos_arr, max_lag=30)
242
  if len(dist) == 0:
243
  continue
244
 
245
  all_dist.extend(dist.tolist())
246
  all_r2.extend(r2.tolist())
247
- all_chrom_label.extend([str(ch)] * len(dist))
 
248
 
249
- chrom_stats[ch] = {
 
 
250
  'mean_r2': float(np.mean(r2)),
251
  'mean_dprime': float(np.mean(dp)),
 
252
  }
253
 
254
- # ── handle empty data ────────────────────────────────────────────────────
255
  if not all_dist:
256
  fig, ax = plt.subplots(figsize=(10, 6), facecolor=BG)
257
- ax.set_facecolor(PANEL)
258
- ax.text(0.5, 0.5, 'No LD data available', ha='center', va='center',
259
- transform=ax.transAxes, fontsize=13, color=TEXT_C)
260
- plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=BG)
261
  plt.close(fig)
262
- return chrom_stats
263
-
264
- dist_arr = np.array(all_dist, dtype=float)
265
- r2_arr = np.array(all_r2, dtype=float)
266
- chr_arr = np.array(all_chrom_label, dtype=str)
267
-
268
- # clip to 99th percentile of distance for a clean x-axis
269
- max_dist = min(120.0, float(np.percentile(dist_arr, 99)))
270
-
271
- # per-chromosome colour map
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
272
  chrom_color = {str(ch): CHROM_PALETTE[i % len(CHROM_PALETTE)]
273
  for i, ch in enumerate(unique_chroms)}
274
 
275
- # ── figure ───────────────────────────────────────────────────────────────
276
- fig, ax = plt.subplots(figsize=(11, 6.5), facecolor=BG)
277
- ax.set_facecolor('#F5F0FF') # very light lavender β€” matches reference feel
 
 
 
 
 
278
 
279
- # ── scatter: one layer per chromosome so legend entries are clean ────────
280
- scatter_handles = []
281
  for ch in unique_chroms:
282
  key = str(ch)
283
- mask = chr_arr == key
284
- if not mask.any():
285
  continue
286
- sc = ax.scatter(
287
- dist_arr[mask], r2_arr[mask],
288
- c=chrom_color[key],
289
- s=6, alpha=0.40, linewidths=0,
290
- zorder=2, label=key,
291
- )
292
- scatter_handles.append(sc)
293
-
294
- # ── smooth median decay curve ────────────────────────────────────────────
295
- try:
296
- n_bins = 50
297
- bins = np.linspace(0, max_dist, n_bins + 1)
298
- ctrs, medians = [], []
299
- for i in range(n_bins):
300
- m = (dist_arr >= bins[i]) & (dist_arr < bins[i + 1])
301
- if m.sum() > 3:
302
- ctrs.append((bins[i] + bins[i + 1]) / 2.0)
303
- medians.append(np.median(r2_arr[m]))
304
-
305
- ctrs = np.array(ctrs, dtype=float)
306
- medians = np.array(medians, dtype=float)
307
-
308
- if len(ctrs) >= 5:
309
- x_smooth = np.linspace(ctrs[0], ctrs[-1], 400)
310
- spl = make_interp_spline(ctrs, medians, k=3)
311
- y_smooth = np.clip(spl(x_smooth), 0.0, 1.0)
312
-
313
- # filled area under the curve
314
- ax.fill_between(x_smooth, 0, y_smooth,
315
- color='#22C55E', alpha=0.25, zorder=3)
316
- # curve line
317
- decay_line, = ax.plot(x_smooth, y_smooth,
318
- color='#15803D', linewidth=2.2,
319
- zorder=4, label='Median decay')
320
- except Exception:
321
- decay_line = None
322
-
323
- # ── rΒ² = 0.2 reference dashed line ──────────────────────────────────────
324
- ref_line = ax.axhline(0.2, color='#1E293B', ls='--', lw=1.5,
325
- alpha=0.75, zorder=5, label='rΒ² = 0.2')
326
-
327
- # ── axes formatting ──────────────────────────────────────────────────────
328
- ax.set_xlim(0, max_dist)
329
- ax.set_ylim(0, 1.04)
330
 
 
 
 
331
  ax.set_xlabel('Genetic distance (cM)', fontsize=12, fontweight='bold',
332
- color=TEXT_C, labelpad=8)
333
  ax.set_ylabel('LD estimate (RΒ²)', fontsize=12, fontweight='bold',
334
- color=TEXT_C, labelpad=8)
335
  ax.set_title('LD Decay by Chromosome', fontsize=14, fontweight='bold',
336
- color=TEXT_C, pad=12)
337
-
338
- ax.xaxis.grid(True, color=GRID_C, linewidth=0.6, alpha=0.8)
339
- ax.yaxis.grid(True, color=GRID_C, linewidth=0.6, alpha=0.8)
340
  ax.set_axisbelow(True)
341
 
342
- # spine style
343
- for spine in ax.spines.values():
344
- spine.set_edgecolor(GRID_C)
345
- spine.set_linewidth(1.0)
346
-
347
- # ── legend ───────────────────────────────────────────────────────────────
348
  handles, labels = ax.get_legend_handles_labels()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
349
 
350
- # separate special entries from chromosome entries
351
- special_entries = [(h, l) for h, l in zip(handles, labels)
352
- if l in ('Median decay', 'rΒ² = 0.2')]
353
- chrom_entries = [(h, l) for h, l in zip(handles, labels)
354
- if l not in ('Median decay', 'rΒ² = 0.2')]
355
-
356
- # build final legend: special entries first, then chromosomes
357
- leg_handles = [h for h, _ in special_entries] + [h for h, _ in chrom_entries]
358
- leg_labels = [l for _, l in special_entries] + [f'Chr {l}' for _, l in chrom_entries]
359
-
360
- n_chr_cols = max(1, (len(chrom_entries) + 11) // 12) # ≀12 rows per col
361
-
362
- legend = ax.legend(
363
- leg_handles, leg_labels,
364
- title='Chr',
365
- title_fontsize=9,
366
- fontsize=7.5,
367
- loc='upper right',
368
- ncol=n_chr_cols,
369
- framealpha=0.93,
370
- edgecolor=GRID_C,
371
- markerscale=2.0,
372
- handlelength=1.4,
373
- borderpad=0.8,
374
- labelspacing=0.45,
375
  )
376
- legend.get_title().set_fontweight('bold')
377
- legend.get_title().set_color(TEXT_C)
 
 
 
 
 
 
378
 
379
- plt.tight_layout(pad=1.8)
380
  plt.savefig(save_path, dpi=130, bbox_inches='tight', facecolor=BG)
381
  plt.close(fig)
382
 
383
- return chrom_stats
384
 
385
 
386
  # ══════════════════════════════════════════════════════════════
387
- # PLOT: MODEL COMPARISON
388
  # ══════════════════════════════════════════════════════════════
389
 
390
- def plot_model_comparison(results_df, save_path):
391
- """Simplified comparison plot for 2 fast models."""
392
- set_pastel_style()
393
- fig, axes = plt.subplots(1, 2, figsize=(12, 5), facecolor=BG)
 
 
 
394
 
395
- # P-value correlation
396
- ax = axes[0]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
397
  ax.set_facecolor(PANEL)
398
 
399
- avail = ['LR_P', 'EN_P']
400
- avail = [c for c in avail if c in results_df.columns]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
401
 
402
- if len(avail) >= 2:
403
- corr = results_df[avail[0]].corr(results_df[avail[1]])
404
- ax.scatter(results_df[avail[0]], results_df[avail[1]],
405
- alpha=0.5, s=20, color=ACCENT, edgecolors='white', linewidth=0.5)
406
- ax.text(0.05, 0.95, f'r = {corr:.3f}', transform=ax.transAxes,
407
- fontsize=11, fontweight='bold', va='top',
408
- bbox=dict(boxstyle='round', facecolor=PANEL, alpha=0.8))
409
 
410
- ax.set_xlabel('Linear Regression P-value', fontsize=10, fontweight='bold')
411
- ax.set_ylabel('ElasticNet P-value', fontsize=10, fontweight='bold')
412
- ax.set_title('Model P-value Correlation', fontsize=11, fontweight='bold')
413
- ax.set_xscale('log')
414
- ax.set_yscale('log')
415
- ax.grid(True, color=GRID_C, lw=0.7, alpha=0.5)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
416
 
417
- # Effect size histogram
418
  ax = axes[1]
419
  ax.set_facecolor(PANEL)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
420
 
421
- if 'LR_Beta' in results_df.columns:
422
- ax.hist(results_df['LR_Beta'].dropna(), bins=40, alpha=0.6,
423
- label='Linear Reg', color=ACCENT, edgecolor='white')
424
- if 'EN_Beta' in results_df.columns:
425
- ax.hist(results_df['EN_Beta'].dropna(), bins=40, alpha=0.6,
426
- label='ElasticNet', color=TEAL_C, edgecolor='white')
 
 
 
 
 
 
 
 
 
 
 
 
 
427
 
428
- ax.set_xlabel('Effect Size', fontsize=10, fontweight='bold')
429
- ax.set_ylabel('Frequency', fontsize=10, fontweight='bold')
 
 
 
 
 
 
 
 
430
  ax.set_title('Effect Size Distribution', fontsize=11, fontweight='bold')
431
  ax.legend(fontsize=9)
432
  ax.grid(True, color=GRID_C, lw=0.7)
433
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
434
  plt.tight_layout(pad=1.5)
435
  plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=BG)
436
  plt.close(fig)
437
 
438
 
439
  # ══════════════════════════════════════════════════════════════
440
- # GWAS MODELS (FAST ONLY)
441
  # ══════════════════════════════════════════════════════════════
442
 
443
  def linear_regression_gwas(genotypes, phenotypes):
444
- """Vectorised single-marker regression using scipy.stats β€” FASTEST."""
445
- n_markers = genotypes.shape[1]
446
- pvals = np.ones(n_markers)
447
- effects = np.zeros(n_markers)
448
- se_arr = np.zeros(n_markers)
449
- r2_arr = np.zeros(n_markers)
450
-
451
- y = phenotypes.astype(float)
452
- for i in range(n_markers):
453
  x = genotypes[:, i].astype(float)
454
- if x.std() < 1e-9:
455
- continue
456
- slope, intercept, r, p, se = stats.linregress(x, y)
457
- pvals[i] = p if np.isfinite(p) else 1.0
458
- effects[i] = slope
459
- se_arr[i] = se
460
- r2_arr[i] = r ** 2
461
- return pvals, effects, se_arr, r2_arr
462
-
463
-
464
- def elasticnet_gwas(genotypes, phenotypes, n_bootstrap=15):
465
- """ElasticNet with reduced bootstrap β€” MODERATE speed."""
466
- scaler = StandardScaler()
467
- X_sc = scaler.fit_transform(genotypes)
468
- enet = ElasticNetCV(cv=3, random_state=42, max_iter=2000, n_jobs=-1)
469
- enet.fit(X_sc, phenotypes)
470
- coef = enet.coef_
471
-
472
- boot_coefs = []
473
  rng = np.random.default_rng(42)
474
- for _ in range(n_bootstrap):
475
  idx = rng.integers(0, len(phenotypes), len(phenotypes))
476
  eb = ElasticNetCV(cv=3, random_state=42, max_iter=1500)
477
- eb.fit(X_sc[idx], phenotypes[idx])
478
- boot_coefs.append(eb.coef_)
479
 
480
- boot_arr = np.array(boot_coefs)
481
- pvals = np.ones(len(coef))
482
  for i in range(len(coef)):
483
  sd = boot_arr[:, i].std()
484
  if sd > 0:
485
- z = abs(coef[i]) / (sd + 1e-10)
486
- pvals[i] = 2 * (1 - stats.norm.cdf(z))
487
- return pvals, coef
488
-
489
-
490
- # ══════════════════════════════════════════════════════════════
491
- # CSV PARSER
492
- # ══════════════════════════════════════════════════════════════
493
-
494
- def parse_input_csv_enhanced(filepath):
495
- """Parse CSV input with chromosome and position info."""
496
- df = pd.read_csv(filepath, header=0, dtype=str)
497
- marker_cols = df.columns[2:].tolist()
498
- chr_row = df.iloc[0]
499
- chrom_dict, pos_dict = {}, {}
500
-
501
- for m in marker_cols:
502
- val = str(chr_row[m]).strip()
503
- if ':' in val:
504
- parts = val.split(':')
505
- chrom_dict[m] = parts[0]
506
- try: pos_dict[m] = float(parts[1])
507
- except: pos_dict[m] = 0.0
508
- elif '_' in val:
509
- parts = val.split('_')
510
- chrom_dict[m] = parts[0]
511
- try: pos_dict[m] = float(parts[1]) if len(parts) > 1 else 0.0
512
- except: pos_dict[m] = 0.0
513
- else:
514
- val = val[:-2] if val.endswith('.0') else val
515
- chrom_dict[m] = val
516
- pos_dict[m] = 0.0
517
-
518
- df_s = df.iloc[1:].reset_index(drop=True)
519
- sample_ids = df_s.iloc[:, 0].astype(str).values
520
- phenotypes = pd.to_numeric(df_s.iloc[:, 1], errors='coerce').values
521
- geno_raw = df_s[marker_cols].apply(pd.to_numeric, errors='coerce').replace(-1, np.nan)
522
- positions = [pos_dict.get(m, 0.0) for m in marker_cols]
523
-
524
- return sample_ids, phenotypes, geno_raw.values, marker_cols, chrom_dict, positions
525
 
526
 
527
  # ══════════════════════════════════════════════════════════════
@@ -529,234 +746,238 @@ def parse_input_csv_enhanced(filepath):
529
  # ══════════════════════════════════════════════════════════════
530
 
531
  def run_mta_analysis(input_file, miss_rate_sample, miss_rate_marker, maf_thresh):
532
- """Fast GWAS analysis with only Linear Regression + ElasticNet."""
533
-
534
  try:
535
  if input_file is None:
536
- return ("⚠️ Please upload a CSV file.", None, None, None)
 
537
 
538
- temp_dir = tempfile.mkdtemp()
539
- results_dir = os.path.join(temp_dir, 'results')
540
- plots_dir = os.path.join(results_dir, 'plots')
541
- for d in [results_dir, plots_dir]:
542
- os.makedirs(d, exist_ok=True)
543
 
544
- miss_s_t = miss_rate_sample / 100.0
545
- miss_m_t = miss_rate_marker / 100.0
546
- maf_t = maf_thresh / 100.0
547
 
548
  print("[Parse] Reading CSV…")
549
- (sample_ids, phenotypes, genotypes,
550
- marker_names, chrom_dict, positions) = parse_input_csv_enhanced(input_file)
551
-
552
- n_samples = len(sample_ids)
553
- n_markers = len(marker_names)
554
- print(f"[Parse] {n_samples} samples Γ— {n_markers} markers")
555
-
556
- # QC
557
- print("[QC] Computing missing rates & MAF…")
558
- miss_m = np.isnan(genotypes).sum(axis=0) / max(n_samples, 1)
559
- miss_s = np.isnan(genotypes).sum(axis=1) / max(n_markers, 1)
560
-
561
- maf = np.zeros(n_markers)
562
- for i in range(n_markers):
563
- v = genotypes[:, i]
564
- v = v[~np.isnan(v)]
565
  if len(v):
566
- f = np.mean(v) / 2.0
567
  maf[i] = min(f, 1 - f)
568
 
569
- qc_m = (miss_m < miss_m_t) & (maf >= maf_t)
570
- qc_s = miss_s < miss_s_t
571
-
572
- fallback_msg = ""
573
- for rs, rm in [(miss_s_t, miss_m_t),
574
- (0.60,0.60),(0.70,0.70),(0.80,0.80),(0.90,0.90),(1.00,1.00)]:
575
- qc_m_t = (miss_m < rm) & (maf >= maf_t)
576
- qc_s_t = miss_s < rs
577
- if qc_s_t.sum() >= 10:
578
- qc_m = qc_m_t
579
- qc_s = qc_s_t
580
- if rs > miss_s_t or rm > miss_m_t:
581
- fallback_msg = (f"\n⚠️ **QC auto-relaxed** to sample missing "
582
- f"< {rs*100:.0f}% / marker missing "
583
- f"< {rm*100:.0f}%\n")
584
  break
585
 
586
- geno_qc = genotypes[np.ix_(qc_s, qc_m)].copy()
587
- pheno_qc = phenotypes[qc_s]
588
- ids_qc = sample_ids[qc_s]
589
- mnames_qc = [marker_names[i] for i in range(n_markers) if qc_m[i]]
590
- chrom_qc = [chrom_dict[m] for m in mnames_qc]
591
- pos_qc = [positions[i] for i in range(n_markers) if qc_m[i]]
 
592
 
593
- print(f"[QC] {len(ids_qc)} samples Γ— {len(mnames_qc)} markers after QC")
594
 
595
  # Impute
596
- print("[Impute] Filling missing genotypes…")
597
- col_means = np.nanmean(geno_qc, axis=0)
598
- col_means = np.where(np.isnan(col_means), 0.0, col_means)
599
- for i in range(geno_qc.shape[1]):
600
- mask = np.isnan(geno_qc[:, i])
601
- if mask.any():
602
- geno_qc[mask, i] = col_means[i]
603
-
604
- valid = ~np.isnan(pheno_qc)
605
- geno_qc = geno_qc[valid]
606
- pheno_qc = pheno_qc[valid]
607
- ids_qc = ids_qc[valid]
608
-
609
- if len(ids_qc) < 10:
610
- return (
611
- f"## ⚠️ Insufficient Samples\nOnly **{len(ids_qc)}** samples "
612
- f"passed QC (started with {n_samples}).\n\n"
613
- f"Try increasing **Sample Missing Rate** slider to 50–80%.",
614
- None, None, None, None
615
- )
616
-
617
- n_qc = len(mnames_qc)
618
- bonf = 0.05 / n_qc
619
 
620
- # ── Run Models ────────────────────────────────────────────────────────
621
  print("[1/2] Linear Regression…")
622
- lr_pvals, lr_effects, lr_se, lr_r2 = linear_regression_gwas(geno_qc, pheno_qc)
623
 
624
  print("[2/2] ElasticNet…")
625
- enet_pvals, enet_coef = elasticnet_gwas(geno_qc, pheno_qc)
626
-
627
- # ── Results DataFrame ─────────────────────────────────────────────────
628
- gwas_df = pd.DataFrame({
629
- 'Rank': 0,
630
- 'Marker': mnames_qc,
631
- 'Chromosome': chrom_qc,
632
- 'Position': pos_qc,
633
- 'LR_P': lr_pvals,
634
- 'LR_Beta': lr_effects,
635
- 'LR_LOD': -np.log10(lr_pvals + 1e-300),
636
- 'Significant_LR': (lr_pvals < bonf).astype(int),
637
- 'EN_P': enet_pvals,
638
- 'EN_Beta': enet_coef,
639
- 'Significant_EN': (enet_pvals < bonf).astype(int),
640
  })
 
 
 
 
641
 
642
- gwas_df['Consensus_Sig'] = (
643
- (gwas_df[['Significant_LR', 'Significant_EN']].sum(axis=1) >= 2).astype(int)
644
- )
645
 
646
- gwas_df = gwas_df.sort_values('LR_P').reset_index(drop=True)
647
- gwas_df['Rank'] = range(1, len(gwas_df) + 1)
648
-
649
- print("[Save] Writing results CSV…")
650
- gwas_df.to_csv(os.path.join(results_dir, 'gwas_results.csv'), index=False)
651
 
652
  # ── Plots ─────────────────────────────────────────────────────────────
653
- print("[Plots] Generating Manhattan plot…")
654
- bonf_log = -np.log10(bonf)
655
- sig_set = set(np.where(lr_pvals < bonf)[0])
656
-
657
- man_path = os.path.join(plots_dir, 'manhattan_lod.png')
658
- plot_manhattan_with_lod(mnames_qc, chrom_qc, lr_pvals,
659
- -np.log10(lr_pvals + 1e-300),
660
- sig_set, bonf_log, man_path)
661
-
662
- print("[Plots] Generating LD decay (scatter style)…")
663
- ld_path = os.path.join(plots_dir, 'ld_decay.png')
664
- ld_stats = plot_enhanced_ld_decay(geno_qc, chrom_qc, pos_qc, ld_path)
665
-
666
- print("[Plots] Generating model comparison…")
667
- comp_path = os.path.join(plots_dir, 'model_comparison.png')
668
- plot_model_comparison(gwas_df, comp_path)
 
 
 
 
 
 
 
 
 
 
 
 
669
 
670
  # ── ZIP ───────────────────────────────────────────────────────────────
671
- print("[ZIP] Creating download…")
672
- zip_path = os.path.join(temp_dir, 'GWAS_Results.zip')
673
  with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf:
674
- for root, _, files in os.walk(results_dir):
675
  for f in files:
676
- fp = os.path.join(root, f)
677
- zf.write(fp, os.path.relpath(fp, temp_dir))
678
-
679
- # ── Summary ───────────────────────────────────────────────────────────
680
- ld_r2_mean = np.mean([v['mean_r2'] for v in ld_stats.values()]) if ld_stats else 0
681
- ld_dp_mean = np.mean([v['mean_dprime'] for v in ld_stats.values()]) if ld_stats else 0
682
-
683
- top10_cols = ['Rank', 'Marker', 'Chromosome', 'LR_P', 'LR_LOD', 'EN_P', 'Consensus_Sig']
684
- top10_cols = [c for c in top10_cols if c in gwas_df.columns]
685
 
686
- def _df_to_md(df):
687
- cols = df.columns.tolist()
688
- def _fmt(v):
 
689
  if isinstance(v, float):
690
- return f"{v:.4e}" if (v != 0 and abs(v) < 0.001) else f"{v:.4f}"
691
  return str(v)
692
- header = "| " + " | ".join(cols) + " |"
693
- sep = "| " + " | ".join(["---"] * len(cols)) + " |"
694
- rows = ["| " + " | ".join(_fmt(row[c]) for c in cols) + " |"
695
- for _, row in df.iterrows()]
696
- return "\n".join([header, sep] + rows)
 
 
 
 
697
 
698
  summary = f"""
699
- ## βœ… GWAS Analysis Complete (v7.3 β€” Fast + Scatter LD)
700
 
701
  ### πŸ“Š QC Summary
702
  | Metric | Value |
703
  |--------|-------|
704
- | Samples (raw β†’ QC) | {n_samples} β†’ **{len(ids_qc)}** |
705
- | Markers (raw β†’ QC) | {n_markers} β†’ **{n_qc}** |
706
- | Chromosomes | **{len(set(chrom_qc))}** |
707
- | MAF filter | β‰₯ {maf_thresh:.1f}% |
708
- | Sample missing filter | < {miss_rate_sample:.0f}% |
709
- {fallback_msg}
710
-
711
- ### πŸ”¬ Model Results
712
- | Model | Status | Significant Markers |
713
- |-------|--------|---------------------|
714
- | Linear Regression | βœ… Fast | **{(lr_pvals < bonf).sum()}** |
715
- | ElasticNet | βœ… Moderate | **{(enet_pvals < bonf).sum()}** |
716
- | Consensus (Both) | βœ… | **{gwas_df['Consensus_Sig'].sum()}** |
717
-
718
- ### 🧬 LD Summary
719
- **Mean rΒ²** = {ld_r2_mean:.3f} | **Mean D'** = {ld_dp_mean:.3f}
720
-
721
- ### πŸ† Top 10 Markers (LR P-value)
722
- {_df_to_md(gwas_df.head(10)[top10_cols])}
 
 
 
 
 
 
 
723
 
724
  ---
725
- **Files generated:**
726
- - `gwas_results.csv` β€” Complete results
727
- - `manhattan_lod.png` β€” Manhattan + LOD plot
728
- - `ld_decay.png` β€” LD decay scatter (chromosome-coloured)
729
- - `model_comparison.png` β€” Model comparison
 
 
 
 
730
  """
731
- print("[Done] Analysis complete!")
732
- return (summary, man_path, ld_path, comp_path, zip_path)
 
733
 
734
  except Exception as e:
735
  import traceback
736
- print(f"[ERROR] {e}")
737
- return (
738
- f"## ❌ Error\n```\n{e}\n\n{traceback.format_exc()}\n```",
739
- None, None, None, None
740
- )
741
 
742
 
743
  # ══════════════════════════════════════════════════════════════
744
  # GRADIO UI
745
  # ══════════════════════════════════════════════════════════════
746
 
747
- custom_css = """
748
- .gradio-container { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; }
749
- h1 { color: #2c3e50; border-bottom: 3px solid #8B5CF6; padding-bottom: 10px; }
750
- .gr-button-primary { background: #8B5CF6 !important; }
751
  """
752
 
753
- with gr.Blocks(css=custom_css, title="MTA GWAS v7.3") as app:
754
 
755
  gr.Markdown("""
756
- # 🧬 Optimized GWAS Analysis v7.3
757
- ### Fast Multi-Model Genomic Discovery
758
- **~10x faster** | Linear Regression + ElasticNet | Scatter LD Decay Plot
759
-
760
  ---
761
  """)
762
 
@@ -765,61 +986,61 @@ with gr.Blocks(css=custom_css, title="MTA GWAS v7.3") as app:
765
  gr.Markdown("""
766
  ### πŸ“‹ CSV Format
767
  ```
768
- ID, Phenotype, M1, M2, M3, ...
769
- -, Chr, 1, 1, 2, ...
770
- Sample_1, 45.2, 0, 1, 2, ...
771
- Sample_2, 38.7, 1, 0, 1, ...
772
  ```
773
- **Genotypes:** 0/1/2 (missing = blank or -1)
774
  """)
775
  input_file = gr.File(label="πŸ“ Upload CSV", file_types=[".csv"])
776
 
777
  with gr.Column(scale=1):
778
- gr.Markdown("### βš™οΈ QC Filters")
779
- miss_rate_sample = gr.Slider(5, 100, value=30, step=5,
780
- label="Max sample missing (%)")
781
- miss_rate_marker = gr.Slider(5, 100, value=30, step=5,
782
- label="Max marker missing (%)")
783
- maf_thresh = gr.Slider(0, 25, value=3, step=1,
784
- label="Min MAF (%)")
785
-
786
  gr.Markdown("""
787
- ### ⚑ v7.3 Updates
788
- - Scatter LD decay: dots coloured by chromosome
789
- - Green filled median decay curve
790
- - rΒ² = 0.2 dashed reference line
 
 
 
791
  """)
792
 
793
- run_button = gr.Button("πŸš€ Run Analysis", variant="primary", size="lg")
794
-
795
  gr.Markdown("---")
796
 
797
- with gr.Row():
798
- summary_output = gr.Markdown(label="Summary")
799
 
800
  with gr.Row():
801
- with gr.Column():
802
- manhattan_output = gr.Image(label="Manhattan + LOD")
803
- with gr.Column():
804
- ld_output = gr.Image(label="LD Decay (Scatter by Chromosome)")
805
 
806
  with gr.Row():
807
- comparison_output = gr.Image(label="Model Comparison")
 
808
 
809
  with gr.Row():
810
- download_output = gr.File(label="πŸ“¦ Download Results ZIP")
 
811
 
812
  gr.Markdown("""
813
  ---
814
- **MTA GWAS v7.3** | Optimised for speed | Scatter LD Decay | Linear Reg + ElasticNet
815
  """)
816
 
817
- run_button.click(
818
  fn=run_mta_analysis,
819
- inputs=[input_file, miss_rate_sample, miss_rate_marker, maf_thresh],
820
- outputs=[summary_output, manhattan_output, ld_output,
821
- comparison_output, download_output],
822
- show_progress=True
823
  )
824
 
825
  if __name__ == "__main__":
 
1
  # -*- coding: utf-8 -*-
2
  """
3
+ MTA Analysis Tool v7.5 β€” Complete GWAS Platform
4
+ ═══════════════════════════════════════════════════════════════
5
+ NEW in v7.5:
6
+ LD DECAY (fully reworked):
7
+ β€’ Uses marker-rank distance (0,1,2…) converted to cM via Haldane's
8
+ mapping function so X-axis always has real spread
9
+ β€’ Chromosome-coloured scatter dots (one dot per marker pair)
10
+ β€’ Green filled cubic-spline median decay curve
11
+ β€’ Annotates: half-decay distance, rΒ²=0.2 crossing, rΒ²=0.1 crossing
12
+ β€’ Vertical lines + text labels showing EXACT decay positions
13
+ β€’ Interpretation panel below plot (text summary)
14
+ β€’ No raw bp/position shown β€” only cM distances
15
+
16
+ GWAS OUTPUTS (comprehensive):
17
+ β€’ gwas_results.csv β€” full per-marker table
18
+ β€’ top_significant.csv β€” Bonferroni-significant markers only
19
+ β€’ ld_decay_stats.csv β€” per-chromosome LD decay statistics
20
+ β€’ manhattan_lod.png β€” Manhattan + LOD panel
21
+ β€’ ld_decay.png β€” LD decay scatter with annotations
22
+ β€’ qq_plot.png β€” QQ plot (inflation Ξ»)
23
+ β€’ model_comparison.png β€” LR vs EN comparison
24
+ β€’ phenotype_dist.png β€” Phenotype distribution
25
+ β€’ GWAS_Results.zip β€” all of the above
26
+
27
+ SPEED: Linear Regression (vectorised) + ElasticNet
28
+ ═══════════════════════════════════════════════════════════════
29
  """
30
 
31
  import gradio as gr
 
34
  import matplotlib
35
  matplotlib.use('Agg')
36
  import matplotlib.pyplot as plt
37
+ import matplotlib.patches as mpatches
38
  from scipy import stats
 
39
  from scipy.interpolate import make_interp_spline
40
  import os, warnings, tempfile, zipfile
41
  from sklearn.linear_model import ElasticNetCV
42
  from sklearn.preprocessing import StandardScaler
 
43
  warnings.filterwarnings('ignore')
44
 
45
  # ══════════════════════════════════════════════════════════════
46
  # THEME
47
  # ══════════════════════════════════════════════════════════════
48
  BG = "#FDFBFF"
49
+ PANEL = "#F4EFFE"
50
+ GRID_C = "#E2D9F3"
51
+ TEXT_C = "#2D1B5E"
52
+ ACCENT = "#7C3AED"
53
+ RED_C = "#E11D48"
54
+ GOLD_C = "#D97706"
55
+ TEAL_C = "#0891B2"
56
+ GREEN_C = "#15803D"
57
+ PINK_C = "#DB2777"
58
 
59
  CHROM_PALETTE = [
60
+ "#7C3AED","#DB2777","#059669","#0284C7","#D97706",
61
+ "#6D28D9","#BE185D","#047857","#0369A1","#B45309",
62
+ "#4F46E5","#9D174D","#065F46","#075985","#92400E",
63
+ "#7C3AED","#C026D3","#0F766E","#1D4ED8","#B45309",
64
+ "#6366F1","#EC4899","#10B981","#3B82F6","#F59E0B",
65
  ]
66
 
67
+ def _style():
68
  plt.rcParams.update({
69
+ 'figure.facecolor': BG, 'axes.facecolor': PANEL,
70
+ 'axes.edgecolor': GRID_C,'axes.labelcolor': TEXT_C,
71
+ 'axes.titlecolor': TEXT_C,'xtick.color': TEXT_C,
72
+ 'ytick.color': TEXT_C,'text.color': TEXT_C,
73
+ 'grid.color': GRID_C,'grid.linewidth': 0.7,
74
+ 'figure.dpi': 120, 'font.family': 'DejaVu Sans',
75
+ 'axes.spines.top': False, 'axes.spines.right': False,
76
+ 'legend.framealpha':0.95, 'legend.edgecolor': GRID_C,
77
  })
78
 
79
+
80
  # ══════════════════════════════════════════════════════════════
81
+ # CSV PARSER
82
  # ══════════════════════════════════════════════════════════════
83
 
84
+ def parse_input_csv(filepath):
85
+ """
86
+ Expected format:
87
+ ID, Phenotype, M1, M2, ...
88
+ -, Chr, 1, 2, ... ← chromosome row
89
+ Samp1, 45.2, 0, 1, ...
90
+ Chromosome cell may be: '1', '1:1234567', '1_1234567'
91
+ Genotypes: 0/1/2 (blank or -1 = missing)
92
+ """
93
+ df = pd.read_csv(filepath, header=0, dtype=str)
94
+ marker_cols = df.columns[2:].tolist()
95
+ chr_row = df.iloc[0]
 
 
 
 
 
 
 
 
 
 
96
 
97
+ chrom_dict, pos_dict = {}, {}
98
+ for m in marker_cols:
99
+ val = str(chr_row[m]).strip()
100
+ if ':' in val:
101
+ p = val.split(':')
102
+ chrom_dict[m] = p[0]
103
+ try: pos_dict[m] = float(p[1])
104
+ except: pos_dict[m] = 0.0
105
+ elif '_' in val:
106
+ p = val.split('_')
107
+ chrom_dict[m] = p[0]
108
+ try: pos_dict[m] = float(p[1]) if len(p) > 1 else 0.0
109
+ except: pos_dict[m] = 0.0
110
+ else:
111
+ val = val[:-2] if val.endswith('.0') else val
112
+ chrom_dict[m] = val
113
+ pos_dict[m] = 0.0
114
 
115
+ df_s = df.iloc[1:].reset_index(drop=True)
116
+ sample_ids = df_s.iloc[:, 0].astype(str).values
117
+ phenotypes = pd.to_numeric(df_s.iloc[:, 1], errors='coerce').values
118
+ geno_raw = (df_s[marker_cols]
119
+ .apply(pd.to_numeric, errors='coerce')
120
+ .replace(-1, np.nan))
121
+ positions = [pos_dict.get(m, 0.0) for m in marker_cols]
 
 
122
 
123
+ return sample_ids, phenotypes, geno_raw.values, marker_cols, chrom_dict, positions
 
 
124
 
 
 
 
 
 
 
 
 
 
 
125
 
126
+ # ══════════════════════════════════════════════════════════════
127
+ # HALDANE cM CONVERSION
128
+ # ══════════════════════════════════════════════════════════���═══
129
 
130
+ def _marker_rank_to_cM(n_markers, avg_genome_cM=1500.0):
131
+ """
132
+ Convert marker rank indices (0, 1, 2 … n-1) to approximate cM positions.
133
+ Assumes markers are evenly spread across a genome of avg_genome_cM cM.
134
+ Returns an array of cM positions of length n_markers.
135
+ """
136
+ if n_markers <= 1:
137
+ return np.array([0.0])
138
+ spacing = avg_genome_cM / (n_markers - 1) # cM per marker interval
139
+ return np.arange(n_markers, dtype=float) * spacing
140
 
 
 
 
 
 
 
141
 
142
+ def _positions_to_cM(positions):
143
+ """
144
+ Convert raw positions (bp / kb / cM / unknown) to cM.
145
+ Falls back to marker-rank cM if positions are all zero or identical.
146
+ """
147
+ pos = np.array(positions, dtype=float)
148
+ mx = np.nanmax(np.abs(pos))
 
149
 
150
+ if mx == 0 or np.all(pos == pos[0]):
151
+ # No usable position data β†’ use marker rank
152
+ return _marker_rank_to_cM(len(pos)), "marker-rank→cM"
153
+ elif mx > 1_000_000:
154
+ return pos / 1_000_000.0, "bpΓ·1e6β†’cM"
155
+ elif mx > 1_000:
156
+ return pos / 1_000.0, "kbΓ·1e3β†’cM"
157
+ else:
158
+ return pos, "cM (raw)"
159
 
160
 
161
  # ══════════════════════════════════════════════════════════════
162
+ # LD COMPUTATION (vectorised, per-chromosome)
163
  # ══════════════════════════════════════════════════════════════
164
 
165
+ def _compute_ld_pairs(G, cM_pos, max_lag=50):
166
+ """
167
+ Return arrays (dist_cM, r2, dp) for all lagged pairs within a chromosome.
168
+ G : (n_samples, n_markers) int/float genotype matrix
169
+ cM_pos : (n_markers,) cM positions
170
+ """
171
+ n = G.shape[1]
172
+ dists, r2s, dps = [], [], []
173
 
174
+ for lag in range(1, min(max_lag + 1, n)):
175
+ x = G[:, :n - lag].astype(float)
176
+ y = G[:, lag: ].astype(float)
177
 
178
+ xm, ym = x - x.mean(0), y - y.mean(0)
179
+ num = (xm * ym).sum(0)
180
+ denom = np.sqrt((xm**2).sum(0) * (ym**2).sum(0))
 
 
181
  with np.errstate(invalid='ignore', divide='ignore'):
182
+ r = np.where(denom > 0, num / denom, 0.0)
183
+ r2 = np.clip(r**2, 0, 1)
184
 
185
+ p1 = x.mean(0) / 2.0
186
+ p2 = y.mean(0) / 2.0
187
+ p11 = ((x == 2) & (y == 2)).mean(0) / 2.0
 
188
  D = p11 - p1 * p2
189
  with np.errstate(invalid='ignore', divide='ignore'):
190
  Dmax = np.where(D < 0,
191
+ np.minimum(p1*(1-p2), (1-p1)*p2),
192
+ np.minimum(p1*p2, (1-p1)*(1-p2)))
193
  dp = np.where(Dmax > 0, np.abs(D / Dmax), 0.0)
194
 
195
+ dist = np.abs(cM_pos[lag:] - cM_pos[:n - lag])
196
 
197
+ dists.append(dist); r2s.append(r2); dps.append(dp)
 
 
198
 
199
+ if not dists:
200
  return np.array([]), np.array([]), np.array([])
201
+ return np.concatenate(dists), np.concatenate(r2s), np.concatenate(dps)
 
 
 
202
 
203
 
204
  # ══════════════════════════════════════════════════════════════
205
+ # PLOT: LD DECAY SCATTER (v7.5 β€” fully reworked)
206
  # ══════════════════════════════════════════════════════════════
207
 
208
+ def plot_ld_decay(genotypes, chromosomes, positions, save_path, max_m=120):
209
  """
210
+ Scatter-style LD decay plot:
211
+ β€’ X-axis: cM distance between marker pairs (always has real spread)
212
+ β€’ Y-axis: rΒ² (LD estimate)
213
+ β€’ One dot per pair, coloured by chromosome
214
+ β€’ Green filled cubic-spline median decay curve
215
+ β€’ Vertical annotation lines: half-decay, rΒ²=0.2, rΒ²=0.1 crossings
216
+ β€’ Interpretation panel below figure
217
+ Returns (chrom_stats dict, ld_interpretation str)
218
  """
219
+ _style()
220
 
221
  unique_chroms = sorted(set(chromosomes),
222
  key=lambda x: (int(x) if str(x).isdigit() else 999, str(x)))
223
 
224
+ # ── convert positions to cM (per-chromosome marker-rank) ─────────────────
225
+ # We assign cM positions per chromosome independently so within-chrom
226
+ # distances are meaningful regardless of raw position values.
227
+ chrom_to_global_idx = {}
228
+ for gi, ch in enumerate(chromosomes):
229
+ chrom_to_global_idx.setdefault(str(ch), []).append(gi)
230
+
231
+ # Build a global cM array: within each chrom, markers get rank-based cM
232
+ # spacing = (chrom_total_cM_share) / (n_markers_in_chrom - 1)
233
+ # We assume mean genome = 1500 cM split proportionally by marker count
234
+ total_markers = len(chromosomes)
235
+ global_cM = np.zeros(total_markers, dtype=float)
236
+ GENOME_cM = 1500.0
237
+
238
+ for ch in unique_chroms:
239
+ idxs = chrom_to_global_idx[str(ch)]
240
+ n_ch = len(idxs)
241
+ share = GENOME_cM * n_ch / total_markers # cM allocated to this chrom
242
+ if n_ch > 1:
243
+ spacing = share / (n_ch - 1)
244
+ else:
245
+ spacing = share
246
+ for rank, gi in enumerate(idxs):
247
+ global_cM[gi] = rank * spacing
248
+
249
+ # ── collect pairwise (dist_cM, rΒ², chrom) ────────────────────────────────
250
+ all_dist, all_r2, all_dp, all_ch = [], [], [], []
251
  chrom_stats = {}
252
 
253
  for ch in unique_chroms:
254
+ idxs = chrom_to_global_idx[str(ch)]
255
  if len(idxs) < 4:
256
  continue
257
  if len(idxs) > max_m:
258
  idxs = sorted(np.random.choice(idxs, max_m, replace=False))
259
 
260
+ G = genotypes[:, idxs].copy().astype(float)
261
+ cM_pos = global_cM[idxs]
262
 
263
+ dist, r2, dp = _compute_ld_pairs(G, cM_pos, max_lag=50)
264
  if len(dist) == 0:
265
  continue
266
 
267
  all_dist.extend(dist.tolist())
268
  all_r2.extend(r2.tolist())
269
+ all_dp.extend(dp.tolist())
270
+ all_ch.extend([str(ch)] * len(dist))
271
 
272
+ chrom_stats[str(ch)] = {
273
+ 'n_markers': len(idxs),
274
+ 'n_pairs': len(dist),
275
  'mean_r2': float(np.mean(r2)),
276
  'mean_dprime': float(np.mean(dp)),
277
+ 'max_r2': float(np.max(r2)),
278
  }
279
 
 
280
  if not all_dist:
281
  fig, ax = plt.subplots(figsize=(10, 6), facecolor=BG)
282
+ ax.text(0.5, 0.5, 'No LD data', ha='center', va='center',
283
+ transform=ax.transAxes, fontsize=14, color=TEXT_C)
284
+ plt.savefig(save_path, dpi=120, bbox_inches='tight')
 
285
  plt.close(fig)
286
+ return chrom_stats, "No LD data available."
287
+
288
+ dist_arr = np.array(all_dist, dtype=float)
289
+ r2_arr = np.array(all_r2, dtype=float)
290
+ ch_arr = np.array(all_ch, dtype=str)
291
+
292
+ # clip extreme tail
293
+ max_dist = float(np.percentile(dist_arr, 99))
294
+ if max_dist < 0.5:
295
+ max_dist = dist_arr.max()
296
+
297
+ mask = dist_arr <= max_dist
298
+ dv, rv = dist_arr[mask], r2_arr[mask]
299
+
300
+ # ── binned medians for smooth curve ──────────────────────────────────────
301
+ N_BINS = 80
302
+ bins = np.linspace(0, max_dist, N_BINS + 1)
303
+ ctrs, meds = [], []
304
+ for i in range(N_BINS):
305
+ m = (dv >= bins[i]) & (dv < bins[i + 1])
306
+ if m.sum() >= 3:
307
+ ctrs.append((bins[i] + bins[i + 1]) / 2.0)
308
+ meds.append(np.median(rv[m]))
309
+
310
+ ctrs = np.array(ctrs, dtype=float)
311
+ meds = np.array(meds, dtype=float)
312
+
313
+ # ── decay annotations ─────────────────────────────────────────────────────
314
+ # Find where smooth curve crosses rΒ²=0.5 (half of max), 0.2, 0.1
315
+ ann = {} # key β†’ cM position
316
+ if len(ctrs) >= 5:
317
+ k = min(3, len(ctrs) - 1)
318
+ xs = np.linspace(ctrs[0], ctrs[-1], 2000)
319
+ spl = make_interp_spline(ctrs, meds, k=k)
320
+ ys = np.clip(spl(xs), 0, 1)
321
+
322
+ r2_start = ys[0]
323
+ for thr_name, thr_val in [('half', r2_start / 2.0),
324
+ ('r2_02', 0.2),
325
+ ('r2_01', 0.1)]:
326
+ idx_cross = np.where(ys <= thr_val)[0]
327
+ if len(idx_cross):
328
+ ann[thr_name] = float(xs[idx_cross[0]])
329
+ else:
330
+ xs, ys = ctrs, meds
331
+
332
+ # ── LD interpretation string ──────────────────────────────────────────────
333
+ overall_mean_r2 = float(np.mean(r2_arr))
334
+ overall_mean_dp = float(np.mean(all_dp))
335
+
336
+ if 'half' in ann:
337
+ ld_level = ("rapid" if ann['half'] < 5 else
338
+ "moderate" if ann['half'] < 20 else "slow")
339
+ interp_lines = [
340
+ f"β€’ **LD half-decay** (rΒ² drops to 50% of starting value): **{ann['half']:.1f} cM**",
341
+ f" β†’ LD decays {ld_level}ly in this population.",
342
+ ]
343
+ else:
344
+ interp_lines = ["β€’ Half-decay point not reached within plotted range (LD persists strongly)."]
345
+
346
+ if 'r2_02' in ann:
347
+ interp_lines.append(
348
+ f"β€’ **rΒ² < 0.2** (useful LD threshold for GWAS tag-SNP coverage): **{ann['r2_02']:.1f} cM**")
349
+ interp_lines.append(
350
+ f" β†’ Markers within {ann['r2_02']:.1f} cM share enough LD to capture the same signal.")
351
+ else:
352
+ interp_lines.append("β€’ rΒ² does not drop below 0.2 within plotted range β€” very high background LD.")
353
+
354
+ if 'r2_01' in ann:
355
+ interp_lines.append(
356
+ f"β€’ **rΒ² < 0.1** (independent marker threshold): **{ann['r2_01']:.1f} cM**")
357
+ interp_lines += [
358
+ f"β€’ Overall mean rΒ² = {overall_mean_r2:.3f} | mean D' = {overall_mean_dp:.3f}",
359
+ f"β€’ Total marker pairs analysed: {len(dist_arr):,}",
360
+ ]
361
+ ld_interpretation = "\n".join(interp_lines)
362
+
363
+ # ══ FIGURE ════════════════════════════════════════════════════════════════
364
  chrom_color = {str(ch): CHROM_PALETTE[i % len(CHROM_PALETTE)]
365
  for i, ch in enumerate(unique_chroms)}
366
 
367
+ fig = plt.figure(figsize=(13, 8), facecolor=BG)
368
+ # Main scatter (top 75%) + interpretation text (bottom 25%)
369
+ gs = fig.add_gridspec(2, 1, height_ratios=[4, 1], hspace=0.05)
370
+ ax = fig.add_subplot(gs[0])
371
+ axt = fig.add_subplot(gs[1])
372
+ axt.axis('off')
373
+
374
+ ax.set_facecolor('#EEE8FA')
375
 
376
+ # ── scatter per chromosome ────────────────────────────────────────────────
 
377
  for ch in unique_chroms:
378
  key = str(ch)
379
+ cmsk = (ch_arr == key) & mask
380
+ if not cmsk.any():
381
  continue
382
+ ax.scatter(dist_arr[cmsk], r2_arr[cmsk],
383
+ c=chrom_color[key], s=6, alpha=0.35,
384
+ linewidths=0, zorder=2, label=key)
385
+
386
+ # ── median decay curve + fill ─────────────────────────────────────────────
387
+ if len(ctrs) >= 5:
388
+ ax.fill_between(xs, 0, ys, color='#22C55E', alpha=0.22, zorder=3)
389
+ ax.plot(xs, ys, color=GREEN_C, linewidth=2.4, zorder=4,
390
+ label='Median rΒ² decay')
391
+
392
+ # ── reference line rΒ²=0.2 ────────────────────────────────────────────────
393
+ ax.axhline(0.2, color='#111827', ls='--', lw=1.6, alpha=0.75,
394
+ zorder=5, label='rΒ² = 0.2')
395
+
396
+ # ── annotation vertical lines ─────────────────────────────────────────────
397
+ ann_styles = {
398
+ 'half': (GOLD_C, 'Β½ decay', 0.50),
399
+ 'r2_02': (RED_C, 'rΒ²=0.2', 0.20),
400
+ 'r2_01': (TEAL_C, 'rΒ²=0.1', 0.10),
401
+ }
402
+ for key, (col, label, r2_ref) in ann_styles.items():
403
+ if key in ann:
404
+ xv = ann[key]
405
+ ax.axvline(xv, color=col, ls=':', lw=1.8, alpha=0.85, zorder=6)
406
+ ax.annotate(
407
+ f'{label}\n{xv:.1f} cM',
408
+ xy=(xv, r2_ref),
409
+ xytext=(xv + max_dist * 0.01, r2_ref + 0.06),
410
+ fontsize=8.5, fontweight='bold', color=col,
411
+ arrowprops=dict(arrowstyle='->', color=col, lw=1.2),
412
+ bbox=dict(boxstyle='round,pad=0.3', fc=BG, ec=col,
413
+ alpha=0.9, lw=1.0),
414
+ zorder=7,
415
+ )
 
 
 
 
 
 
 
 
 
 
416
 
417
+ # ── axes ──────────────────────────────────────────────────────────────────
418
+ ax.set_xlim(0, max_dist)
419
+ ax.set_ylim(0, 1.05)
420
  ax.set_xlabel('Genetic distance (cM)', fontsize=12, fontweight='bold',
421
+ color=TEXT_C, labelpad=6)
422
  ax.set_ylabel('LD estimate (RΒ²)', fontsize=12, fontweight='bold',
423
+ color=TEXT_C, labelpad=6)
424
  ax.set_title('LD Decay by Chromosome', fontsize=14, fontweight='bold',
425
+ color=TEXT_C, pad=10)
426
+ ax.xaxis.grid(True, color=GRID_C, lw=0.6, alpha=0.9)
427
+ ax.yaxis.grid(True, color=GRID_C, lw=0.6, alpha=0.9)
 
428
  ax.set_axisbelow(True)
429
 
430
+ # ── legend ────────────────────────────────────────────────────────────────
 
 
 
 
 
431
  handles, labels = ax.get_legend_handles_labels()
432
+ special = [(h, l) for h, l in zip(handles, labels)
433
+ if l in ('Median rΒ² decay', 'rΒ² = 0.2')]
434
+ chrs = [(h, l) for h, l in zip(handles, labels)
435
+ if l not in ('Median rΒ² decay', 'rΒ² = 0.2')]
436
+ leg_h = [h for h, _ in special] + [h for h, _ in chrs]
437
+ leg_l = [l for _, l in special] + [f'Chr {l}' for _, l in chrs]
438
+
439
+ ncols = max(1, (len(chrs) + 9) // 10)
440
+ legend = ax.legend(leg_h, leg_l, title='Chr', title_fontsize=9,
441
+ fontsize=7.5, loc='upper right', ncol=ncols,
442
+ framealpha=0.93, edgecolor=GRID_C,
443
+ markerscale=2.2, handlelength=1.4,
444
+ borderpad=0.7, labelspacing=0.4)
445
+ legend.get_title().set_fontweight('bold')
446
 
447
+ # ── interpretation text panel ─────────────────────────────────────────────
448
+ interp_display = (
449
+ "LD DECAY INTERPRETATION\n"
450
+ + "─" * 72 + "\n"
451
+ + ld_interpretation.replace('**', '') # strip markdown bold for plain text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
452
  )
453
+ axt.text(0.01, 0.98, interp_display,
454
+ transform=axt.transAxes,
455
+ va='top', ha='left',
456
+ fontsize=8.5, color=TEXT_C,
457
+ fontfamily='monospace',
458
+ bbox=dict(boxstyle='round,pad=0.5',
459
+ facecolor='#EDE9FE', edgecolor=GRID_C,
460
+ alpha=0.95))
461
 
 
462
  plt.savefig(save_path, dpi=130, bbox_inches='tight', facecolor=BG)
463
  plt.close(fig)
464
 
465
+ return chrom_stats, ld_interpretation
466
 
467
 
468
  # ══════════════════════════════════════════════════════════════
469
+ # PLOT: MANHATTAN + LOD
470
  # ══════════════════════════════════════════════════════════════
471
 
472
+ def plot_manhattan_lod(marker_names, chromosomes, p_values, lod_scores,
473
+ sig_set, bonf_thresh, save_path):
474
+ _style()
475
+ unique_chroms = sorted(set(chromosomes),
476
+ key=lambda x: (int(x) if str(x).isdigit() else 999, str(x)))
477
+ log_p = -np.log10(np.array(p_values) + 1e-300)
478
+ lod_array = np.array(lod_scores)
479
 
480
+ GAP = max(8, len(marker_names) // 150)
481
+ x_pos = np.zeros(len(marker_names))
482
+ chrom_to_idx = {}
483
+ for i, c in enumerate(chromosomes):
484
+ chrom_to_idx.setdefault(c, []).append(i)
485
+
486
+ chrom_xticks, offset = [], 0
487
+ for ch in unique_chroms:
488
+ idxs = chrom_to_idx.get(ch, [])
489
+ if not idxs: continue
490
+ for r, idx in enumerate(idxs):
491
+ x_pos[idx] = offset + r
492
+ chrom_xticks.append((offset + len(idxs) / 2, str(ch)))
493
+ offset += len(idxs) + GAP
494
+
495
+ fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(18, 9),
496
+ gridspec_kw={'height_ratios': [2.2, 1]},
497
+ facecolor=BG)
498
+
499
+ for ci, ch in enumerate(unique_chroms):
500
+ idxs = chrom_to_idx.get(ch, [])
501
+ if not idxs: continue
502
+ if ci % 2 == 0:
503
+ for axx in [ax1, ax2]:
504
+ axx.axvspan(x_pos[idxs[0]] - 0.5, x_pos[idxs[-1]] + 0.5,
505
+ color='#EDE9FE', alpha=0.40, zorder=0)
506
+ col = CHROM_PALETTE[ci % len(CHROM_PALETTE)]
507
+ normal = [i for i in idxs if i not in sig_set]
508
+ sel = [i for i in idxs if i in sig_set]
509
+ if normal:
510
+ ax1.scatter(x_pos[normal], log_p[normal],
511
+ c=col, s=9, alpha=0.60, linewidths=0, zorder=2)
512
+ if sel:
513
+ ax1.scatter(x_pos[sel], log_p[sel],
514
+ c=RED_C, s=220, alpha=0.15, linewidths=0, zorder=3)
515
+ ax1.scatter(x_pos[sel], log_p[sel],
516
+ c=RED_C, s=60, alpha=1.0,
517
+ edgecolors='white', linewidths=0.9,
518
+ marker='D', zorder=4, label='Significant')
519
+
520
+ ax1.axhline(bonf_thresh, color=RED_C, ls='--', lw=1.8, alpha=0.85,
521
+ label=f'Bonferroni ({bonf_thresh:.1f})', zorder=5)
522
+ ax1.axhline(3.0, color=GOLD_C, ls=':', lw=1.5, alpha=0.8,
523
+ label='Suggestive (LOD=3)', zorder=5)
524
+
525
+ ax1_t = ax1.twinx()
526
+ ax1_t.scatter(x_pos, lod_array, c=TEAL_C, s=5, alpha=0.30,
527
+ marker='x', zorder=1)
528
+ ax1_t.set_ylabel('LOD Score', fontsize=10, color=TEAL_C, fontweight='bold')
529
+ ax1_t.tick_params(axis='y', colors=TEAL_C)
530
+ ax1_t.set_ylim(0, max(lod_array.max() * 1.15, 1))
531
+
532
+ ax1.set_xlim(-GAP, offset)
533
+ ax1.set_ylim(bottom=0, top=max(log_p.max() * 1.15, 1))
534
+ ax1.set_ylabel('βˆ’log₁₀(P)', fontsize=12, fontweight='bold', labelpad=8)
535
+ ax1.set_title('GWAS Manhattan Plot with LOD Scores', fontsize=14,
536
+ fontweight='bold', pad=12)
537
+ ax1.set_xticks([x for x, _ in chrom_xticks])
538
+ ax1.set_xticklabels([l for _, l in chrom_xticks], fontsize=7)
539
+ ax1.yaxis.grid(True, color=GRID_C, lw=0.7)
540
+ ax1.legend(loc='upper right', fontsize=9, framealpha=0.9)
541
+
542
+ ax2.plot(x_pos, lod_array, color=TEAL_C, lw=1.2, alpha=0.8)
543
+ ax2.fill_between(x_pos, 0, lod_array, color=TEAL_C, alpha=0.18)
544
+ ax2.axhline(3, color=GOLD_C, ls='--', lw=1.2, alpha=0.8)
545
+ ax2.set_xlim(-GAP, offset)
546
+ ax2.set_ylabel('LOD', fontsize=10, fontweight='bold')
547
+ ax2.set_xlabel('Chromosome', fontsize=11, fontweight='bold')
548
+ ax2.set_xticks([x for x, _ in chrom_xticks])
549
+ ax2.set_xticklabels([l for _, l in chrom_xticks], fontsize=7)
550
+ ax2.yaxis.grid(True, color=GRID_C, lw=0.7)
551
+
552
+ plt.tight_layout(pad=1.5)
553
+ plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=BG)
554
+ plt.close(fig)
555
+
556
+
557
+ # ══════════════════════════════════════════════════════════════
558
+ # PLOT: QQ PLOT
559
+ # ══════════════════════════════════════════════════════════════
560
+
561
+ def plot_qq(p_values, save_path):
562
+ _style()
563
+ pv = np.array(p_values, dtype=float)
564
+ pv = pv[np.isfinite(pv) & (pv > 0)]
565
+ n = len(pv)
566
+ obs = -np.log10(np.sort(pv))
567
+ exp = -np.log10(np.arange(1, n + 1) / (n + 1))
568
+
569
+ # Genomic inflation Ξ»
570
+ chi2_obs = stats.chi2.ppf(1 - pv, df=1)
571
+ lam = np.median(chi2_obs) / stats.chi2.ppf(0.5, df=1)
572
+
573
+ fig, ax = plt.subplots(figsize=(7, 7), facecolor=BG)
574
  ax.set_facecolor(PANEL)
575
 
576
+ ax.scatter(exp, obs, c=ACCENT, s=12, alpha=0.65,
577
+ linewidths=0, zorder=2, label='Observed')
578
+ maxv = max(obs.max(), exp.max()) * 1.05
579
+ ax.plot([0, maxv], [0, maxv], color=RED_C, lw=1.5,
580
+ ls='--', zorder=3, label='Expected (null)')
581
+
582
+ ax.set_xlim(0, maxv); ax.set_ylim(0, maxv)
583
+ ax.set_xlabel('Expected βˆ’log₁₀(P)', fontsize=12, fontweight='bold')
584
+ ax.set_ylabel('Observed βˆ’log₁₀(P)', fontsize=12, fontweight='bold')
585
+ ax.set_title('QQ Plot', fontsize=14, fontweight='bold', pad=10)
586
+ ax.text(0.05, 0.93,
587
+ f'Ξ» (genomic inflation) = {lam:.3f}',
588
+ transform=ax.transAxes, fontsize=11, fontweight='bold',
589
+ color=ACCENT,
590
+ bbox=dict(boxstyle='round', facecolor=BG, edgecolor=ACCENT,
591
+ alpha=0.9))
592
+ ax.legend(fontsize=9)
593
+ ax.grid(True, color=GRID_C, lw=0.7)
594
+
595
+ plt.tight_layout()
596
+ plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=BG)
597
+ plt.close(fig)
598
+ return float(lam)
599
 
 
 
 
 
 
 
 
600
 
601
+ # ══════════════════════════════════════════════════════════════
602
+ # PLOT: PHENOTYPE DISTRIBUTION
603
+ # ══════════════════════════════════════════════════════════════
604
+
605
+ def plot_phenotype_dist(phenotypes, save_path):
606
+ _style()
607
+ pv = phenotypes[~np.isnan(phenotypes)]
608
+ fig, axes = plt.subplots(1, 2, figsize=(11, 4.5), facecolor=BG)
609
+
610
+ ax = axes[0]
611
+ ax.set_facecolor(PANEL)
612
+ ax.hist(pv, bins=30, color=ACCENT, alpha=0.75, edgecolor='white',
613
+ linewidth=0.6)
614
+ ax.axvline(np.mean(pv), color=RED_C, ls='--', lw=1.6,
615
+ label=f'Mean={np.mean(pv):.2f}')
616
+ ax.axvline(np.median(pv), color=GOLD_C, ls=':', lw=1.6,
617
+ label=f'Median={np.median(pv):.2f}')
618
+ ax.set_xlabel('Phenotype Value', fontsize=11, fontweight='bold')
619
+ ax.set_ylabel('Frequency', fontsize=11, fontweight='bold')
620
+ ax.set_title('Phenotype Distribution', fontsize=12, fontweight='bold')
621
+ ax.legend(fontsize=9)
622
+ ax.grid(True, color=GRID_C, lw=0.7)
623
 
 
624
  ax = axes[1]
625
  ax.set_facecolor(PANEL)
626
+ stats.probplot(pv, dist='norm', plot=ax)
627
+ ax.get_lines()[0].set(color=ACCENT, markersize=3, alpha=0.6)
628
+ ax.get_lines()[1].set(color=RED_C, lw=1.5)
629
+ ax.set_title('Normal Q-Q Plot (Phenotype)', fontsize=12, fontweight='bold')
630
+ ax.grid(True, color=GRID_C, lw=0.7)
631
+
632
+ sw_stat, sw_p = stats.shapiro(pv[:5000])
633
+ axes[0].text(0.97, 0.95,
634
+ f'Shapiro-Wilk p={sw_p:.3e}',
635
+ transform=axes[0].transAxes,
636
+ ha='right', va='top', fontsize=8.5, color=TEXT_C,
637
+ bbox=dict(boxstyle='round', facecolor=BG,
638
+ edgecolor=GRID_C, alpha=0.9))
639
+ plt.tight_layout(pad=1.5)
640
+ plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=BG)
641
+ plt.close(fig)
642
+
643
+
644
+ # ══════════════════════════════════════════════════════════════
645
+ # PLOT: MODEL COMPARISON
646
+ # ══════════════════════════════════════════════════════════════
647
 
648
+ def plot_model_comparison(results_df, save_path):
649
+ _style()
650
+ fig, axes = plt.subplots(1, 3, figsize=(16, 5), facecolor=BG)
651
+
652
+ # 1. P-value correlation
653
+ ax = axes[0]; ax.set_facecolor(PANEL)
654
+ if 'LR_P' in results_df and 'EN_P' in results_df:
655
+ corr = results_df['LR_P'].corr(results_df['EN_P'])
656
+ ax.scatter(results_df['LR_P'], results_df['EN_P'],
657
+ alpha=0.45, s=15, color=ACCENT,
658
+ edgecolors='white', linewidth=0.4)
659
+ ax.text(0.05, 0.95, f'r = {corr:.3f}', transform=ax.transAxes,
660
+ fontsize=11, fontweight='bold', va='top',
661
+ bbox=dict(boxstyle='round', facecolor=BG, alpha=0.85))
662
+ ax.set_xlabel('LR P-value', fontsize=10, fontweight='bold')
663
+ ax.set_ylabel('ElasticNet P-value', fontsize=10, fontweight='bold')
664
+ ax.set_title('P-value Correlation', fontsize=11, fontweight='bold')
665
+ ax.set_xscale('log'); ax.set_yscale('log')
666
+ ax.grid(True, color=GRID_C, lw=0.7, alpha=0.5)
667
 
668
+ # 2. Effect size distribution
669
+ ax = axes[1]; ax.set_facecolor(PANEL)
670
+ if 'LR_Beta' in results_df:
671
+ ax.hist(results_df['LR_Beta'].dropna(), bins=45, alpha=0.60,
672
+ label='LR Ξ²', color=ACCENT, edgecolor='white')
673
+ if 'EN_Beta' in results_df:
674
+ ax.hist(results_df['EN_Beta'].dropna(), bins=45, alpha=0.55,
675
+ label='EN Ξ²', color=TEAL_C, edgecolor='white')
676
+ ax.set_xlabel('Effect Size (Ξ²)', fontsize=10, fontweight='bold')
677
+ ax.set_ylabel('Count', fontsize=10, fontweight='bold')
678
  ax.set_title('Effect Size Distribution', fontsize=11, fontweight='bold')
679
  ax.legend(fontsize=9)
680
  ax.grid(True, color=GRID_C, lw=0.7)
681
 
682
+ # 3. -log10(P) scatter
683
+ ax = axes[2]; ax.set_facecolor(PANEL)
684
+ if 'LR_P' in results_df and 'EN_P' in results_df:
685
+ lp_lr = -np.log10(results_df['LR_P'].clip(1e-300))
686
+ lp_en = -np.log10(results_df['EN_P'].clip(1e-300))
687
+ ax.scatter(lp_lr, lp_en, alpha=0.40, s=12, color=PINK_C,
688
+ edgecolors='white', linewidth=0.3)
689
+ maxv = max(lp_lr.max(), lp_en.max()) * 1.05
690
+ ax.plot([0, maxv], [0, maxv], color=GOLD_C, ls='--', lw=1.2)
691
+ ax.set_xlabel('LR βˆ’log₁₀(P)', fontsize=10, fontweight='bold')
692
+ ax.set_ylabel('EN βˆ’log₁₀(P)', fontsize=10, fontweight='bold')
693
+ ax.set_title('Signal Concordance', fontsize=11, fontweight='bold')
694
+ ax.grid(True, color=GRID_C, lw=0.7, alpha=0.5)
695
+
696
  plt.tight_layout(pad=1.5)
697
  plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=BG)
698
  plt.close(fig)
699
 
700
 
701
  # ══════════════════════════════════════════════════════════════
702
+ # GWAS MODELS
703
  # ══════════════════════════════════════════════════════════════
704
 
705
  def linear_regression_gwas(genotypes, phenotypes):
706
+ n = genotypes.shape[1]
707
+ pv = np.ones(n); ef = np.zeros(n)
708
+ se = np.zeros(n); r2 = np.zeros(n)
709
+ y = phenotypes.astype(float)
710
+ for i in range(n):
 
 
 
 
711
  x = genotypes[:, i].astype(float)
712
+ if x.std() < 1e-9: continue
713
+ sl, _, r, p, s = stats.linregress(x, y)
714
+ pv[i] = p if np.isfinite(p) else 1.0
715
+ ef[i] = sl; se[i] = s; r2[i] = r**2
716
+ return pv, ef, se, r2
717
+
718
+
719
+ def elasticnet_gwas(genotypes, phenotypes, n_boot=15):
720
+ sc = StandardScaler()
721
+ Xs = sc.fit_transform(genotypes)
722
+ en = ElasticNetCV(cv=3, random_state=42, max_iter=2000, n_jobs=-1)
723
+ en.fit(Xs, phenotypes)
724
+ coef = en.coef_
725
+
726
+ boots = []
 
 
 
 
727
  rng = np.random.default_rng(42)
728
+ for _ in range(n_boot):
729
  idx = rng.integers(0, len(phenotypes), len(phenotypes))
730
  eb = ElasticNetCV(cv=3, random_state=42, max_iter=1500)
731
+ eb.fit(Xs[idx], phenotypes[idx])
732
+ boots.append(eb.coef_)
733
 
734
+ boot_arr = np.array(boots)
735
+ pv = np.ones(len(coef))
736
  for i in range(len(coef)):
737
  sd = boot_arr[:, i].std()
738
  if sd > 0:
739
+ z = abs(coef[i]) / (sd + 1e-10)
740
+ pv[i] = 2 * (1 - stats.norm.cdf(z))
741
+ return pv, coef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
742
 
743
 
744
  # ══════════════════════════════════════════════════════════════
 
746
  # ══════════════════════════════════════════════════════════════
747
 
748
  def run_mta_analysis(input_file, miss_rate_sample, miss_rate_marker, maf_thresh):
 
 
749
  try:
750
  if input_file is None:
751
+ return ("⚠️ Please upload a CSV file.",
752
+ None, None, None, None, None, None)
753
 
754
+ tmp = tempfile.mkdtemp()
755
+ rdir = os.path.join(tmp, 'results')
756
+ pdir = os.path.join(rdir, 'plots')
757
+ for d in [rdir, pdir]: os.makedirs(d, exist_ok=True)
 
758
 
759
+ ms_t = miss_rate_sample / 100.0
760
+ mm_t = miss_rate_marker / 100.0
761
+ mf_t = maf_thresh / 100.0
762
 
763
  print("[Parse] Reading CSV…")
764
+ (sids, pheno, geno,
765
+ mnames, chrom_dict, positions) = parse_input_csv(input_file)
766
+
767
+ n_s, n_m = len(sids), len(mnames)
768
+ print(f"[Parse] {n_s} samples Γ— {n_m} markers")
769
+
770
+ # ── QC ───────────────────────────────────────────────────────────────
771
+ miss_m = np.isnan(geno).sum(0) / max(n_s, 1)
772
+ miss_s = np.isnan(geno).sum(1) / max(n_m, 1)
773
+
774
+ maf = np.zeros(n_m)
775
+ for i in range(n_m):
776
+ v = geno[:, i]; v = v[~np.isnan(v)]
 
 
 
777
  if len(v):
778
+ f = np.mean(v) / 2.0
779
  maf[i] = min(f, 1 - f)
780
 
781
+ qc_m = (miss_m < mm_t) & (maf >= mf_t)
782
+ qc_s = miss_s < ms_t
783
+ fallback = ""
784
+
785
+ for rs, rm in [(ms_t, mm_t),
786
+ (.6,.6),(.7,.7),(.8,.8),(.9,.9),(1.,1.)]:
787
+ qm = (miss_m < rm) & (maf >= mf_t)
788
+ qs = miss_s < rs
789
+ if qs.sum() >= 10:
790
+ qc_m, qc_s = qm, qs
791
+ if rs > ms_t or rm > mm_t:
792
+ fallback = (f"\n⚠️ **QC relaxed** β†’ sample<{rs*100:.0f}% "
793
+ f"/ marker<{rm*100:.0f}%\n")
 
 
794
  break
795
 
796
+ geno_q = geno[np.ix_(qc_s, qc_m)].copy()
797
+ pheno_q = pheno[qc_s]
798
+ sids_q = sids[qc_s]
799
+ mn_q = [mnames[i] for i in range(n_m) if qc_m[i]]
800
+ ch_q = [chrom_dict[m] for m in mn_q]
801
+ pos_q = [positions[i] for i in range(n_m) if qc_m[i]]
802
+ n_q = len(mn_q)
803
 
804
+ print(f"[QC] {len(sids_q)} samples Γ— {n_q} markers")
805
 
806
  # Impute
807
+ col_mu = np.nanmean(geno_q, 0)
808
+ col_mu = np.where(np.isnan(col_mu), 0, col_mu)
809
+ for i in range(geno_q.shape[1]):
810
+ mk = np.isnan(geno_q[:, i])
811
+ if mk.any(): geno_q[mk, i] = col_mu[i]
812
+
813
+ valid = ~np.isnan(pheno_q)
814
+ geno_q = geno_q[valid]; pheno_q = pheno_q[valid]
815
+ sids_q = sids_q[valid]
816
+
817
+ if len(sids_q) < 10:
818
+ return (f"## ⚠️ Only {len(sids_q)} samples passed QC. "
819
+ "Increase missing-rate sliders.",
820
+ None, None, None, None, None, None)
821
+
822
+ bonf = 0.05 / n_q
823
+ bonf_log = -np.log10(bonf)
 
 
 
 
 
 
824
 
825
+ # ── Models ───────────────────────────────────────────────────────────
826
  print("[1/2] Linear Regression…")
827
+ lr_p, lr_b, lr_se, lr_r2 = linear_regression_gwas(geno_q, pheno_q)
828
 
829
  print("[2/2] ElasticNet…")
830
+ en_p, en_b = elasticnet_gwas(geno_q, pheno_q)
831
+
832
+ # ── Results table ────────────────────────────────────────────────────
833
+ df = pd.DataFrame({
834
+ 'Marker': mn_q,
835
+ 'Chromosome': ch_q,
836
+ 'LR_P': lr_p,
837
+ 'LR_Beta': lr_b,
838
+ 'LR_SE': lr_se,
839
+ 'LR_R2': lr_r2,
840
+ 'LR_LOD': -np.log10(lr_p + 1e-300),
841
+ 'Significant_LR': (lr_p < bonf).astype(int),
842
+ 'EN_P': en_p,
843
+ 'EN_Beta': en_b,
844
+ 'Significant_EN': (en_p < bonf).astype(int),
845
  })
846
+ df['Consensus_Sig'] = ((df[['Significant_LR','Significant_EN']]
847
+ .sum(1) >= 2).astype(int))
848
+ df = df.sort_values('LR_P').reset_index(drop=True)
849
+ df.insert(0, 'Rank', range(1, len(df)+1))
850
 
851
+ df.to_csv(os.path.join(rdir, 'gwas_results.csv'), index=False)
 
 
852
 
853
+ # Significant only
854
+ sig_df = df[df['Significant_LR'] == 1].copy()
855
+ sig_df.to_csv(os.path.join(rdir, 'top_significant.csv'), index=False)
 
 
856
 
857
  # ── Plots ─────────────────────────────────────────────────────────────
858
+ print("[Plot 1/5] Phenotype distribution…")
859
+ ph_path = os.path.join(pdir, 'phenotype_dist.png')
860
+ plot_phenotype_dist(pheno_q, ph_path)
861
+
862
+ print("[Plot 2/5] Manhattan + LOD…")
863
+ man_path = os.path.join(pdir, 'manhattan_lod.png')
864
+ sig_set = set(np.where(lr_p < bonf)[0])
865
+ plot_manhattan_lod(mn_q, ch_q, lr_p,
866
+ -np.log10(lr_p + 1e-300),
867
+ sig_set, bonf_log, man_path)
868
+
869
+ print("[Plot 3/5] QQ plot…")
870
+ qq_path = os.path.join(pdir, 'qq_plot.png')
871
+ lam = plot_qq(lr_p, qq_path)
872
+
873
+ print("[Plot 4/5] LD decay…")
874
+ ld_path = os.path.join(pdir, 'ld_decay.png')
875
+ ld_stats, ld_interp = plot_ld_decay(geno_q, ch_q, pos_q, ld_path)
876
+
877
+ # Save LD stats CSV
878
+ ld_df = pd.DataFrame([
879
+ {'Chromosome': k, **v} for k, v in ld_stats.items()
880
+ ])
881
+ ld_df.to_csv(os.path.join(rdir, 'ld_decay_stats.csv'), index=False)
882
+
883
+ print("[Plot 5/5] Model comparison…")
884
+ cmp_path = os.path.join(pdir, 'model_comparison.png')
885
+ plot_model_comparison(df, cmp_path)
886
 
887
  # ── ZIP ───────────────────────────────────────────────────────────────
888
+ zip_path = os.path.join(tmp, 'GWAS_Results.zip')
 
889
  with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf:
890
+ for root, _, files in os.walk(rdir):
891
  for f in files:
892
+ fp = os.path.join(root, f)
893
+ zf.write(fp, os.path.relpath(fp, tmp))
 
 
 
 
 
 
 
894
 
895
+ # ── Summary markdown ──────────────────────────────────────────────────
896
+ def _md_table(d):
897
+ cols = d.columns.tolist()
898
+ def _f(v):
899
  if isinstance(v, float):
900
+ return f"{v:.4e}" if (v!=0 and abs(v)<0.001) else f"{v:.4f}"
901
  return str(v)
902
+ sep = "| " + " | ".join(["---"]*len(cols)) + " |"
903
+ rows = ["| "+" | ".join(_f(row[c]) for c in cols)+" |"
904
+ for _, row in d.iterrows()]
905
+ return "\n".join(["| "+" | ".join(cols)+" |", sep]+rows)
906
+
907
+ top_cols = [c for c in
908
+ ['Rank','Marker','Chromosome','LR_P','LR_Beta',
909
+ 'LR_R2','LR_LOD','EN_P','Consensus_Sig']
910
+ if c in df.columns]
911
 
912
  summary = f"""
913
+ ## βœ… GWAS Analysis Complete β€” v7.5
914
 
915
  ### πŸ“Š QC Summary
916
  | Metric | Value |
917
  |--------|-------|
918
+ | Samples (raw β†’ QC) | {n_s} β†’ **{len(sids_q)}** |
919
+ | Markers (raw β†’ QC) | {n_m} β†’ **{n_q}** |
920
+ | Chromosomes | **{len(set(ch_q))}** |
921
+ | MAF threshold | β‰₯ {maf_thresh:.1f}% |
922
+ | Sample missing rate | < {miss_rate_sample:.0f}% |
923
+ | Marker missing rate | < {miss_rate_marker:.0f}% |
924
+ {fallback}
925
+
926
+ ### πŸ”¬ Association Results
927
+ | Model | Significant Markers (Bonferroni) |
928
+ |-------|----------------------------------|
929
+ | Linear Regression | **{int((lr_p < bonf).sum())}** |
930
+ | ElasticNet | **{int((en_p < bonf).sum())}** |
931
+ | Consensus (both) | **{int(df['Consensus_Sig'].sum())}** |
932
+
933
+ **Bonferroni threshold:** P < {bonf:.3e} (βˆ’log₁₀P > {bonf_log:.2f})
934
+
935
+ ### πŸ“ˆ QQ / Inflation
936
+ **Genomic inflation Ξ» = {lam:.3f}**
937
+ {"⚠️ Ξ» > 1.05 β€” possible population stratification or many true signals." if lam > 1.05 else "βœ… Ξ» β‰ˆ 1.0 β€” no substantial inflation."}
938
+
939
+ ### 🧬 LD Decay Interpretation
940
+ {ld_interp}
941
+
942
+ ### πŸ† Top 15 Markers (by LR P-value)
943
+ {_md_table(df.head(15)[top_cols])}
944
 
945
  ---
946
+ **Output files:**
947
+ - `gwas_results.csv` β€” all markers, all statistics
948
+ - `top_significant.csv` β€” Bonferroni-significant markers
949
+ - `ld_decay_stats.csv` β€” per-chromosome LD statistics
950
+ - `plots/manhattan_lod.png` β€” Manhattan + LOD
951
+ - `plots/ld_decay.png` β€” LD decay scatter with decay annotations
952
+ - `plots/qq_plot.png` β€” QQ plot (genomic inflation)
953
+ - `plots/model_comparison.png` β€” LR vs ElasticNet comparison
954
+ - `plots/phenotype_dist.png` β€” Phenotype distribution & normality
955
  """
956
+ print("[Done] βœ…")
957
+ return (summary, man_path, ld_path, qq_path,
958
+ cmp_path, ph_path, zip_path)
959
 
960
  except Exception as e:
961
  import traceback
962
+ return (f"## ❌ Error\n```\n{e}\n\n{traceback.format_exc()}\n```",
963
+ None, None, None, None, None, None)
 
 
 
964
 
965
 
966
  # ══════════════════════════════════════════════════════════════
967
  # GRADIO UI
968
  # ══════════════════════════════════════════════════════════════
969
 
970
+ CSS = """
971
+ .gradio-container{font-family:'Segoe UI',Tahoma,sans-serif}
972
+ h1{color:#2D1B5E;border-bottom:3px solid #7C3AED;padding-bottom:8px}
 
973
  """
974
 
975
+ with gr.Blocks(css=CSS, title="MTA GWAS v7.5") as app:
976
 
977
  gr.Markdown("""
978
+ # 🧬 GWAS Analysis Platform v7.5
979
+ ### Complete Genomic Association Study with LD Decay Analysis
980
+ Linear Regression + ElasticNet | LD Decay Scatter | QQ Plot | Full Outputs
 
981
  ---
982
  """)
983
 
 
986
  gr.Markdown("""
987
  ### πŸ“‹ CSV Format
988
  ```
989
+ ID, Phenotype, M1, M2, M3, ...
990
+ -, Chr, 1, 1, 2, ...
991
+ Sample1, 45.2, 0, 1, 2, ...
992
+ Sample2, 38.7, 1, 0, 1, ...
993
  ```
994
+ **Genotypes:** 0 / 1 / 2 (blank or βˆ’1 = missing)
995
  """)
996
  input_file = gr.File(label="πŸ“ Upload CSV", file_types=[".csv"])
997
 
998
  with gr.Column(scale=1):
999
+ gr.Markdown("### βš™οΈ QC Parameters")
1000
+ miss_sample = gr.Slider(5, 100, value=30, step=5,
1001
+ label="Max sample missing rate (%)")
1002
+ miss_marker = gr.Slider(5, 100, value=30, step=5,
1003
+ label="Max marker missing rate (%)")
1004
+ maf_thr = gr.Slider(0, 25, value=3, step=1,
1005
+ label="Min MAF (%)")
 
1006
  gr.Markdown("""
1007
+ ### πŸ“¦ Outputs
1008
+ - Manhattan + LOD plot
1009
+ - **LD Decay scatter** (cM, annotated)
1010
+ - QQ plot (Ξ» inflation)
1011
+ - Model comparison
1012
+ - Phenotype distribution
1013
+ - Full CSV results + ZIP
1014
  """)
1015
 
1016
+ run_btn = gr.Button("πŸš€ Run GWAS Analysis", variant="primary", size="lg")
 
1017
  gr.Markdown("---")
1018
 
1019
+ summary_out = gr.Markdown()
 
1020
 
1021
  with gr.Row():
1022
+ man_out = gr.Image(label="πŸ—ΊοΈ Manhattan + LOD")
1023
+ ld_out = gr.Image(label="🧬 LD Decay (cM, annotated)")
 
 
1024
 
1025
  with gr.Row():
1026
+ qq_out = gr.Image(label="πŸ“ˆ QQ Plot")
1027
+ cmp_out = gr.Image(label="βš–οΈ Model Comparison")
1028
 
1029
  with gr.Row():
1030
+ ph_out = gr.Image(label="πŸ“Š Phenotype Distribution")
1031
+ dl_out = gr.File(label="πŸ“¦ Download All Results (ZIP)")
1032
 
1033
  gr.Markdown("""
1034
  ---
1035
+ **MTA GWAS v7.5** | Linear Regression + ElasticNet | LD decay uses marker-rank cM positions
1036
  """)
1037
 
1038
+ run_btn.click(
1039
  fn=run_mta_analysis,
1040
+ inputs=[input_file, miss_sample, miss_marker, maf_thr],
1041
+ outputs=[summary_out, man_out, ld_out, qq_out,
1042
+ cmp_out, ph_out, dl_out],
1043
+ show_progress=True,
1044
  )
1045
 
1046
  if __name__ == "__main__":