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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +847 -623
app.py CHANGED
@@ -1,30 +1,32 @@
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
 
@@ -34,139 +36,540 @@ import numpy as np
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 = [], [], []
@@ -192,8 +595,7 @@ def _compute_ld_pairs(G, cM_pos, max_lag=50):
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:
@@ -202,65 +604,52 @@ def _compute_ld_pairs(G, cM_pos, max_lag=50):
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
 
@@ -275,12 +664,14 @@ def plot_ld_decay(genotypes, chromosomes, positions, save_path, max_m=120):
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."
@@ -289,145 +680,156 @@ def plot_ld_decay(genotypes, chromosomes, positions, save_path, max_m=120):
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')]
@@ -435,320 +837,125 @@ def plot_ld_decay(genotypes, chromosomes, positions, save_path, max_m=120):
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
  # ══════════════════════════════════════════════════════════════
745
  # MAIN ANALYSIS
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()
@@ -756,54 +963,51 @@ def run_mta_analysis(input_file, miss_rate_sample, miss_rate_marker, maf_thresh)
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]):
@@ -811,78 +1015,97 @@ def run_mta_analysis(input_file, miss_rate_sample, miss_rate_marker, maf_thresh)
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')
@@ -892,66 +1115,67 @@ def run_mta_analysis(input_file, miss_rate_sample, miss_rate_marker, maf_thresh)
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,
@@ -972,26 +1196,26 @@ CSS = """
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
 
984
  with gr.Row():
985
  with gr.Column(scale=1):
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
 
@@ -1003,15 +1227,14 @@ with gr.Blocks(css=CSS, title="MTA GWAS v7.5") as app:
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("---")
@@ -1019,12 +1242,12 @@ with gr.Blocks(css=CSS, title="MTA GWAS v7.5") as app:
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")
@@ -1032,12 +1255,13 @@ with gr.Blocks(css=CSS, title="MTA GWAS v7.5") as app:
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,
 
1
  # -*- coding: utf-8 -*-
2
  """
3
+ MTA Analysis Tool v8.0 β€” Complete GWAS Platform
4
  ═══════════════════════════════════════════════════════════════
5
+ INPUT FORMAT (3-header-row CSV):
6
+ Row 1 : ID | Phenotype | marker_name ...
7
+ Row 2 : - | Chr | chromosome ... (e.g. 1,2,3…)
8
+ Row 3 : - | Pos | bp_position ... (e.g. 134521…)
9
+ Row 4+: sample data | 0/1/2 genotypes (-1 or blank = missing)
10
+
11
+ MODELS (5 MRmlm-style):
12
+ 1. GLM – General Linear Model (single-marker OLS)
13
+ 2. MLM – Mixed Linear Model (kinship K as random effect via ridge)
14
+ 3. CMLM – Compressed MLM (group-mean kinship)
15
+ 4. BSLMM – Bayesian Sparse LMM (ElasticNet + bootstrap p-values)
16
+ 5. FarmCPU – Fixed & Random (iterative pseudo-QTN control)
17
+
18
+ PLOTS:
19
+ β€’ Manhattan + LOD (all 5 models)
20
+ β€’ QQ plot with correct βˆ’log₁₀(P) observed vs expected, Ξ» annotation
21
+ β€’ LD Decay scatter in bp (physical distance), chromosome-coloured,
22
+ green median decay curve, annotated decay positions in kb/Mb
23
+ β€’ Model comparison (P-value correlations)
24
+ β€’ Phenotype distribution + normality
25
+
26
+ OUTPUTS (ZIP):
27
+ gwas_results.csv | top_significant.csv | ld_decay_stats.csv
28
+ manhattan_lod.png | qq_plot.png | ld_decay_bp.png
29
+ model_comparison.png | phenotype_dist.png
30
  ═══════════════════════════════════════════════════════════════
31
  """
32
 
 
36
  import matplotlib
37
  matplotlib.use('Agg')
38
  import matplotlib.pyplot as plt
 
39
  from scipy import stats
40
  from scipy.interpolate import make_interp_spline
41
  import os, warnings, tempfile, zipfile
42
+ from sklearn.linear_model import ElasticNetCV, RidgeCV
43
  from sklearn.preprocessing import StandardScaler
44
+ from sklearn.decomposition import PCA
45
  warnings.filterwarnings('ignore')
46
 
47
  # ══════════════════════════════════════════════════════════════
48
  # THEME
49
  # ══════════════════════════════════════════════════════════════
50
+ BG = "#FDFBFF"
51
+ PANEL = "#F4EFFE"
52
+ GRID_C = "#E2D9F3"
53
+ TEXT_C = "#2D1B5E"
54
+ ACCENT = "#7C3AED"
55
+ RED_C = "#E11D48"
56
+ GOLD_C = "#D97706"
57
+ TEAL_C = "#0891B2"
58
+ GREEN_C = "#15803D"
59
+ PINK_C = "#DB2777"
60
+ ORANGE_C= "#EA580C"
61
 
62
  CHROM_PALETTE = [
63
  "#7C3AED","#DB2777","#059669","#0284C7","#D97706",
64
  "#6D28D9","#BE185D","#047857","#0369A1","#B45309",
65
  "#4F46E5","#9D174D","#065F46","#075985","#92400E",
66
+ "#7C3AED","#C026D3","#0F766E","#1D4ED8","#CA8A04",
67
  "#6366F1","#EC4899","#10B981","#3B82F6","#F59E0B",
68
  ]
69
 
70
+ MODEL_COLORS = {
71
+ 'GLM': '#7C3AED',
72
+ 'MLM': '#DB2777',
73
+ 'CMLM': '#059669',
74
+ 'BSLMM': '#D97706',
75
+ 'FarmCPU': '#0284C7',
76
+ }
77
+
78
  def _style():
79
  plt.rcParams.update({
80
+ 'figure.facecolor': BG, 'axes.facecolor': PANEL,
81
  'axes.edgecolor': GRID_C,'axes.labelcolor': TEXT_C,
82
  'axes.titlecolor': TEXT_C,'xtick.color': TEXT_C,
83
  'ytick.color': TEXT_C,'text.color': TEXT_C,
84
  'grid.color': GRID_C,'grid.linewidth': 0.7,
85
  'figure.dpi': 120, 'font.family': 'DejaVu Sans',
86
  'axes.spines.top': False, 'axes.spines.right': False,
87
+ 'legend.framealpha':0.95, 'legend.edgecolor': GRID_C,
88
  })
89
 
90
 
91
  # ══════════════════════════════════════════════════════════════
92
+ # CSV PARSER (3-row header format)
93
  # ══════════════════════════════════════════════════════════════
94
 
95
  def parse_input_csv(filepath):
96
  """
97
+ Row 0 : column headers β†’ ID | Phenotype | M1 | M2 …
98
+ Row 1 : chromosome row β†’ - | Chr/1/2… | 1 | 1 …
99
+ Row 2 : position row β†’ - | pos/4345… | bp1| bp2…
100
+ Row 3+: sample data
101
+ Genotypes: 0/1/2 (-1 or blank β†’ missing)
 
102
  """
103
+ df = pd.read_csv(filepath, header=0, dtype=str)
104
  marker_cols = df.columns[2:].tolist()
105
+
106
+ chr_row = df.iloc[0] # chromosome numbers
107
+ pos_row = df.iloc[1] # physical positions (bp)
108
 
109
  chrom_dict, pos_dict = {}, {}
110
  for m in marker_cols:
111
+ # chromosome
112
+ cv = str(chr_row[m]).strip()
113
+ cv = cv[:-2] if cv.endswith('.0') else cv
114
+ cv = cv.replace('chr','').replace('Chr','').strip()
115
+ chrom_dict[m] = cv if cv not in ('', 'nan', '-') else '0'
116
+
117
+ # physical position
118
+ pv = str(pos_row[m]).strip()
119
+ try:
120
+ pos_dict[m] = float(pv)
121
+ except ValueError:
122
+ # fall back to position encoded in marker name: chr1_134521_…
123
+ name_parts = m.split('_')
124
+ bp = 0.0
125
+ for part in name_parts:
126
+ try:
127
+ bp = float(part)
128
+ if bp > 1000: # looks like a bp value
129
+ break
130
+ except ValueError:
131
+ continue
132
+ pos_dict[m] = bp
133
+
134
+ df_s = df.iloc[2:].reset_index(drop=True)
135
  sample_ids = df_s.iloc[:, 0].astype(str).values
136
  phenotypes = pd.to_numeric(df_s.iloc[:, 1], errors='coerce').values
 
 
 
 
137
 
138
+ geno_raw = (df_s[marker_cols]
139
+ .apply(pd.to_numeric, errors='coerce')
140
+ .replace(-1, np.nan) # -1 β†’ NaN
141
+ .where(lambda x: x.isin([0, 1, 2]) | x.isna(), other=np.nan))
142
+
143
+ chromosomes = [chrom_dict[m] for m in marker_cols]
144
+ positions = [pos_dict[m] for m in marker_cols]
145
+
146
+ return (sample_ids, phenotypes,
147
+ geno_raw.values, marker_cols,
148
+ chromosomes, positions)
149
+
150
+
151
+ # ══════════════════════════════════════════════════════════════
152
+ # KINSHIP MATRIX
153
+ # ══════════════════════════════════════════════════════════════
154
+
155
+ def compute_kinship(G):
156
+ """
157
+ Centered IBS kinship matrix K = X X' / p
158
+ where X is mean-centred, standardised genotype matrix.
159
+ """
160
+ X = G.astype(float).copy()
161
+ # standardise each marker
162
+ mu = np.nanmean(X, 0)
163
+ std = np.nanstd(X, 0)
164
+ std[std < 1e-9] = 1.0
165
+ X = (X - mu) / std
166
+ X = np.nan_to_num(X, 0)
167
+ n = X.shape[0]
168
+ K = (X @ X.T) / X.shape[1]
169
+ # normalize so diagonal mean = 1
170
+ d = np.diag(K).mean()
171
+ if d > 0:
172
+ K /= d
173
+ return K
174
+
175
+
176
+ # ══════════════════════════════════════════════════════════════
177
+ # MODEL 1: GLM (standard single-marker OLS)
178
+ # ══════════════════════════════════════════════════════════════
179
+
180
+ def model_glm(G, y):
181
+ """Single-marker OLS regression. Returns (p_values, betas, ses, r2s)."""
182
+ n, m = G.shape
183
+ pv = np.ones(m); bv = np.zeros(m)
184
+ sv = np.zeros(m); rv = np.zeros(m)
185
+ for i in range(m):
186
+ x = G[:, i]
187
+ if x.std() < 1e-9: continue
188
+ sl, _, r, p, se = stats.linregress(x, y)
189
+ pv[i] = max(p, 1e-300) if np.isfinite(p) else 1.0
190
+ bv[i] = sl; sv[i] = se; rv[i] = r**2
191
+ return pv, bv, sv, rv
192
 
193
 
194
  # ══════════════════════════════════════════════════════════════
195
+ # MODEL 2: MLM (Mixed Linear Model via EMMA-lite)
196
  # ══════════════════════════════════════════════════════════════
197
 
198
+ def model_mlm(G, y, K):
199
  """
200
+ Approximate MLM: decorrelate y using PCA of K (top PCs as covariates),
201
+ then run per-marker OLS on residuals. Fast EMMA-lite approach.
 
202
  """
203
+ # Use top PCs of K as population-structure covariates
204
+ n = len(y)
205
+ n_pc = min(5, n - 2)
206
+ eigvals, eigvecs = np.linalg.eigh(K)
207
+ idx = np.argsort(eigvals)[::-1]
208
+ Q = eigvecs[:, idx[:n_pc]] # n Γ— n_pc
209
+
210
+ # partial out Q from y
211
+ Qy = Q @ np.linalg.lstsq(Q, y, rcond=None)[0]
212
+ y_r = y - Qy
213
+
214
+ m = G.shape[1]
215
+ pv = np.ones(m); bv = np.zeros(m)
216
+ sv = np.zeros(m); rv = np.zeros(m)
217
+ for i in range(m):
218
+ x = G[:, i]
219
+ if x.std() < 1e-9: continue
220
+ # partial out Q from x too
221
+ Qx = Q @ np.linalg.lstsq(Q, x, rcond=None)[0]
222
+ xr = x - Qx
223
+ if xr.std() < 1e-9: continue
224
+ sl, _, r, p, se = stats.linregress(xr, y_r)
225
+ pv[i] = max(p, 1e-300) if np.isfinite(p) else 1.0
226
+ bv[i] = sl; sv[i] = se; rv[i] = r**2
227
+ return pv, bv, sv, rv
228
 
229
 
230
+ # ══════════════════════════════════════════════════════════════
231
+ # MODEL 3: CMLM (Compressed MLM)
232
+ # ══════════════════════════════════════════════════════════════
233
+
234
+ def model_cmlm(G, y, K, n_groups=None):
235
  """
236
+ CMLM: cluster individuals into groups using K, use group means
237
+ as kinship covariates instead of full K.
238
  """
239
+ from sklearn.cluster import KMeans
240
+ n = len(y)
241
+ if n_groups is None:
242
+ n_groups = max(2, min(20, n // 10))
243
+
244
+ # Spectral embedding of K for clustering
245
+ eigvals, eigvecs = np.linalg.eigh(K)
246
+ idx = np.argsort(eigvals)[::-1]
247
+ emb = eigvecs[:, idx[:min(10, n-1)]]
248
+
249
+ km = KMeans(n_clusters=n_groups, random_state=42, n_init=5)
250
+ labs = km.fit_predict(emb)
251
+
252
+ # group-mean compressed kinship covariates
253
+ Q = np.zeros((n, n_groups))
254
+ for g in range(n_groups):
255
+ Q[:, g] = (labs == g).astype(float)
256
+ # normalize columns
257
+ col_sum = Q.sum(0)
258
+ col_sum[col_sum == 0] = 1
259
+ Q = Q / col_sum
260
+
261
+ Qy = Q @ np.linalg.lstsq(Q, y, rcond=None)[0]
262
+ y_r = y - Qy
263
+
264
+ m = G.shape[1]
265
+ pv = np.ones(m); bv = np.zeros(m)
266
+ sv = np.zeros(m); rv = np.zeros(m)
267
+ for i in range(m):
268
+ x = G[:, i]
269
+ if x.std() < 1e-9: continue
270
+ Qx = Q @ np.linalg.lstsq(Q, x, rcond=None)[0]
271
+ xr = x - Qx
272
+ if xr.std() < 1e-9: continue
273
+ sl, _, r, p, se = stats.linregress(xr, y_r)
274
+ pv[i] = max(p, 1e-300) if np.isfinite(p) else 1.0
275
+ bv[i] = sl; sv[i] = se; rv[i] = r**2
276
+ return pv, bv, sv, rv
277
+
278
+
279
+ # ══════════════════════════════════════════════════════════════
280
+ # MODEL 4: BSLMM (Bayesian Sparse LMM via ElasticNet)
281
+ # ══════════════════════════════════════════════════════════════
282
+
283
+ def model_bslmm(G, y, n_boot=20):
284
+ """
285
+ BSLMM approximation: ElasticNet sparse selection + bootstrap
286
+ p-values from coefficient stability across bootstrap samples.
287
+ """
288
+ sc = StandardScaler()
289
+ Xs = sc.fit_transform(G)
290
+ en = ElasticNetCV(cv=3, random_state=42, max_iter=3000, n_jobs=-1,
291
+ l1_ratio=[.1,.5,.7,.9,.95,1])
292
+ en.fit(Xs, y)
293
+ coef = en.coef_
294
+
295
+ boots = []
296
+ rng = np.random.default_rng(42)
297
+ for _ in range(n_boot):
298
+ idx = rng.integers(0, len(y), len(y))
299
+ eb = ElasticNetCV(cv=3, random_state=42, max_iter=2000,
300
+ l1_ratio=[.1,.5,.9,1])
301
+ try:
302
+ eb.fit(Xs[idx], y[idx])
303
+ boots.append(eb.coef_)
304
+ except Exception:
305
+ boots.append(coef.copy())
306
+
307
+ boot_arr = np.array(boots)
308
+ pv = np.ones(len(coef))
309
+ for i in range(len(coef)):
310
+ sd = boot_arr[:, i].std()
311
+ if sd > 0:
312
+ z = abs(coef[i]) / (sd + 1e-12)
313
+ pv[i] = max(2*(1 - stats.norm.cdf(z)), 1e-300)
314
+ return pv, coef
315
+
316
+
317
+ # ══════════════════════════════════════════════════════════════
318
+ # MODEL 5: FarmCPU (Fixed & Random Circulating Probability)
319
+ # ══════════════════════════════════════════════════════════════
320
+
321
+ def model_farmcpu(G, y, K, max_iter=3):
322
+ """
323
+ FarmCPU approximation:
324
+ - Iteratively selects pseudo-QTNs (top significant markers from previous iter)
325
+ - Conditions each marker test on pseudo-QTNs as fixed covariates
326
+ - Controls false positives better than MLM alone
327
+ """
328
+ n, m = G.shape
329
+ pv_prev = np.ones(m)
330
+
331
+ # Step 0: initial GLM scan
332
+ pv_cur, bv, sv, rv = model_glm(G, y)
333
+
334
+ for iteration in range(max_iter):
335
+ # select top pseudo-QTNs (top 10 or top 0.01%)
336
+ n_qtns = max(1, min(10, int(m * 0.001)))
337
+ top_idx = np.argsort(pv_cur)[:n_qtns]
338
+
339
+ # Build covariate matrix from pseudo-QTNs
340
+ covs = G[:, top_idx] # n Γ— n_qtns
341
+
342
+ # Condition y on pseudo-QTNs
343
+ try:
344
+ coef_c, _, _, _ = np.linalg.lstsq(covs, y, rcond=None)
345
+ y_cond = y - covs @ coef_c
346
+ except Exception:
347
+ y_cond = y.copy()
348
+
349
+ # Re-scan
350
+ pv_new = np.ones(m)
351
+ bv_new = np.zeros(m)
352
+ sv_new = np.zeros(m)
353
+ for i in range(m):
354
+ x = G[:, i]
355
+ if x.std() < 1e-9: continue
356
+ # remove pseudo-QTN effect from marker too
357
+ try:
358
+ c2 = np.linalg.lstsq(covs, x, rcond=None)[0]
359
+ xc = x - covs @ c2
360
+ except Exception:
361
+ xc = x
362
+ if xc.std() < 1e-9: continue
363
+ sl, _, r, p, se = stats.linregress(xc, y_cond)
364
+ pv_new[i] = max(p, 1e-300) if np.isfinite(p) else 1.0
365
+ bv_new[i] = sl; sv_new[i] = se
366
+
367
+ pv_prev = pv_cur.copy()
368
+ pv_cur = pv_new.copy()
369
+
370
+ return pv_cur, bv_new, sv_new
371
 
372
 
373
  # ══════════════════════════════════════════════════════════════
374
+ # PLOT: MANHATTAN (multi-model)
375
  # ══════════════════════════════════════════════════════════════
376
 
377
+ def plot_manhattan_multi(mn, chroms, model_pvals, bonf_thresh, save_path):
378
  """
379
+ One subplot per model, stacked vertically.
380
+ model_pvals: dict {model_name: p_array}
381
+ """
382
+ _style()
383
+ unique_chroms = sorted(set(chroms),
384
+ key=lambda x: (int(x) if str(x).isdigit() else 999, str(x)))
385
+ n_models = len(model_pvals)
386
+ GAP = max(8, len(mn) // 150)
387
+
388
+ chrom_to_idx = {}
389
+ for i, c in enumerate(chroms):
390
+ chrom_to_idx.setdefault(c, []).append(i)
391
+
392
+ x_pos = np.zeros(len(mn))
393
+ chrom_xticks, offset = [], 0
394
+ for ch in unique_chroms:
395
+ idxs = chrom_to_idx.get(ch, [])
396
+ if not idxs: continue
397
+ for r, idx in enumerate(idxs):
398
+ x_pos[idx] = offset + r
399
+ chrom_xticks.append((offset + len(idxs)/2, str(ch)))
400
+ offset += len(idxs) + GAP
401
+
402
+ fig, axes = plt.subplots(n_models, 1,
403
+ figsize=(18, 3.2 * n_models),
404
+ facecolor=BG, sharex=True)
405
+ if n_models == 1:
406
+ axes = [axes]
407
+
408
+ bonf_log = -np.log10(bonf_thresh)
409
+ sug_log = 3.0
410
+
411
+ for ax, (mname, pv) in zip(axes, model_pvals.items()):
412
+ log_p = -np.log10(np.clip(pv, 1e-300, 1))
413
+ sig_set = set(np.where(pv < bonf_thresh)[0])
414
+ mcol = MODEL_COLORS.get(mname, ACCENT)
415
+
416
+ for ci, ch in enumerate(unique_chroms):
417
+ idxs = chrom_to_idx.get(ch, [])
418
+ if not idxs: continue
419
+ if ci % 2 == 0:
420
+ ax.axvspan(x_pos[idxs[0]] - 0.5, x_pos[idxs[-1]] + 0.5,
421
+ color='#EDE9FE', alpha=0.35, zorder=0)
422
+ shade = CHROM_PALETTE[ci % len(CHROM_PALETTE)]
423
+ norm = [i for i in idxs if i not in sig_set]
424
+ sel = [i for i in idxs if i in sig_set]
425
+ if norm:
426
+ ax.scatter(x_pos[norm], log_p[norm],
427
+ c=shade, s=8, alpha=0.55, linewidths=0, zorder=2)
428
+ if sel:
429
+ ax.scatter(x_pos[sel], log_p[sel],
430
+ c=RED_C, s=220, alpha=0.12, linewidths=0, zorder=3)
431
+ ax.scatter(x_pos[sel], log_p[sel],
432
+ c=RED_C, s=55, alpha=1.0,
433
+ edgecolors='white', linewidths=0.8,
434
+ marker='D', zorder=4)
435
+
436
+ ax.axhline(bonf_log, color=RED_C, ls='--', lw=1.6, alpha=0.85,
437
+ label=f'Bonferroni ({bonf_log:.1f})')
438
+ ax.axhline(sug_log, color=GOLD_C, ls=':', lw=1.4, alpha=0.8,
439
+ label='Suggestive (3)')
440
+ ax.set_xlim(-GAP, offset)
441
+ ax.set_ylim(0, max(log_p.max() * 1.15, bonf_log * 1.1, 1))
442
+ ax.set_ylabel('βˆ’log₁₀(P)', fontsize=10, fontweight='bold')
443
+ ax.set_title(f'Model: {mname}', fontsize=11, fontweight='bold',
444
+ color=mcol, pad=4)
445
+ ax.yaxis.grid(True, color=GRID_C, lw=0.6)
446
+ ax.legend(loc='upper right', fontsize=7.5, framealpha=0.9)
447
+
448
+ # count sig
449
+ n_sig = int((pv < bonf_thresh).sum())
450
+ ax.text(0.01, 0.92, f'{n_sig} significant', transform=ax.transAxes,
451
+ fontsize=8, color=RED_C, fontweight='bold')
452
+
453
+ axes[-1].set_xticks([x for x, _ in chrom_xticks])
454
+ axes[-1].set_xticklabels([l for _, l in chrom_xticks], fontsize=7)
455
+ axes[-1].set_xlabel('Chromosome', fontsize=11, fontweight='bold')
456
+
457
+ plt.suptitle('GWAS Manhattan Plots β€” Multi-Model Comparison',
458
+ fontsize=13, fontweight='bold', y=1.01, color=TEXT_C)
459
+ plt.tight_layout(pad=1.2)
460
+ plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=BG)
461
+ plt.close(fig)
462
+
463
+
464
+ # ══════════════════════════════════════════════════════════════
465
+ # PLOT: QQ (fixed βˆ’log₁₀ calculation)
466
+ # ══════════════════════════════════════════════════════════════
467
+
468
+ def plot_qq_multi(model_pvals, bonf_thresh, save_path):
469
+ """
470
+ One QQ panel per model in a grid.
471
+ Correct βˆ’log₁₀(P) observed vs expected uniform.
472
+ """
473
+ _style()
474
+ n_models = len(model_pvals)
475
+ ncols = min(3, n_models)
476
+ nrows = (n_models + ncols - 1) // ncols
477
+
478
+ fig, axes = plt.subplots(nrows, ncols,
479
+ figsize=(5.5 * ncols, 5 * nrows),
480
+ facecolor=BG, squeeze=False)
481
+
482
+ bonf_log = -np.log10(bonf_thresh)
483
+ lam_dict = {}
484
+
485
+ for idx, (mname, pv_raw) in enumerate(model_pvals.items()):
486
+ row, col = divmod(idx, ncols)
487
+ ax = axes[row][col]
488
+ ax.set_facecolor(PANEL)
489
+
490
+ # ── correct observed βˆ’log₁₀(P) ──────────────────────────────────────
491
+ pv = np.array(pv_raw, dtype=float)
492
+ pv = pv[np.isfinite(pv) & (pv > 0) & (pv <= 1)]
493
+ if len(pv) == 0:
494
+ ax.text(0.5, 0.5, 'No valid p-values',
495
+ ha='center', va='center', transform=ax.transAxes)
496
+ continue
497
+
498
+ n = len(pv)
499
+ obs_log = -np.log10(np.sort(pv)) # largest first after sort
500
+ # expected quantiles of Uniform(0,1)
501
+ exp_log = -np.log10(np.arange(1, n + 1) / (n + 1))
502
+ # sort both descending (largest first β†’ plot top-right)
503
+ obs_log = obs_log[::-1] # ascending now (smallest p β†’ rightmost)
504
+ exp_log = exp_log[::-1]
505
+
506
+ # genomic inflation Ξ» from median chiΒ²
507
+ chi2_obs = stats.chi2.ppf(1 - pv, df=1)
508
+ chi2_obs = chi2_obs[np.isfinite(chi2_obs) & (chi2_obs > 0)]
509
+ lam = (np.median(chi2_obs) / stats.chi2.ppf(0.5, df=1)
510
+ if len(chi2_obs) > 0 else 1.0)
511
+ lam_dict[mname] = lam
512
+
513
+ mcol = MODEL_COLORS.get(mname, ACCENT)
514
+
515
+ # colour dots by significance
516
+ colors_dot = np.where(obs_log >= bonf_log, RED_C, mcol)
517
+ ax.scatter(exp_log, obs_log, c=colors_dot, s=10,
518
+ alpha=0.65, linewidths=0, zorder=2)
519
+
520
+ maxv = max(obs_log.max(), exp_log.max()) * 1.08
521
+ ax.plot([0, maxv], [0, maxv], color='#374151',
522
+ lw=1.5, ls='--', zorder=3, label='Expected (y=x)')
523
+
524
+ # Bonferroni line
525
+ ax.axhline(bonf_log, color=RED_C, ls=':', lw=1.3, alpha=0.8,
526
+ label=f'Bonferroni ({bonf_log:.1f})')
527
+
528
+ # 95% confidence band
529
+ ci_up = -np.log10(stats.beta.ppf(0.025, np.arange(1,n+1),
530
+ np.arange(n,0,-1)) + 1e-300)
531
+ ci_lo = -np.log10(stats.beta.ppf(0.975, np.arange(1,n+1),
532
+ np.arange(n,0,-1)) + 1e-300)
533
+ ci_up = ci_up[::-1]; ci_lo = ci_lo[::-1]
534
+ ax.fill_between(exp_log, ci_lo, ci_up,
535
+ color=mcol, alpha=0.12, zorder=1,
536
+ label='95% CI')
537
+
538
+ ax.set_xlim(0, maxv); ax.set_ylim(0, maxv)
539
+ ax.set_xlabel('Expected βˆ’log₁₀(P)', fontsize=10, fontweight='bold')
540
+ ax.set_ylabel('Observed βˆ’log₁₀(P)', fontsize=10, fontweight='bold')
541
+ ax.set_title(f'{mname} QQ Plot', fontsize=11, fontweight='bold',
542
+ color=mcol)
543
+ ax.text(0.05, 0.92,
544
+ f'Ξ» = {lam:.3f}',
545
+ transform=ax.transAxes, fontsize=11, fontweight='bold',
546
+ color=mcol,
547
+ bbox=dict(boxstyle='round', facecolor=BG,
548
+ edgecolor=mcol, alpha=0.9, lw=1.2))
549
+ ax.legend(fontsize=7.5, loc='upper left')
550
+ ax.grid(True, color=GRID_C, lw=0.6)
551
+
552
+ # hide unused panels
553
+ for extra in range(n_models, nrows * ncols):
554
+ r, c = divmod(extra, ncols)
555
+ axes[r][c].set_visible(False)
556
+
557
+ plt.suptitle('QQ Plots β€” Multi-Model (Ξ» = genomic inflation factor)',
558
+ fontsize=13, fontweight='bold', color=TEXT_C)
559
+ plt.tight_layout(pad=1.5)
560
+ plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=BG)
561
+ plt.close(fig)
562
+ return lam_dict
563
+
564
+
565
+ # ══════════════════════════════════════════════════════════════
566
+ # LD COMPUTATION (vectorised)
567
+ # ══════════════════════════════════════════════════════════════
568
+
569
+ def _compute_ld_pairs_bp(G, bp_pos, max_lag=60):
570
+ """
571
+ Return (dist_bp, r2, dp) for all lagged pairs.
572
+ bp_pos: physical positions in bp (integers).
573
  """
574
  n = G.shape[1]
575
  dists, r2s, dps = [], [], []
 
595
  np.minimum(p1*p2, (1-p1)*(1-p2)))
596
  dp = np.where(Dmax > 0, np.abs(D / Dmax), 0.0)
597
 
598
+ dist = np.abs(bp_pos[lag:] - bp_pos[:n - lag])
 
599
  dists.append(dist); r2s.append(r2); dps.append(dp)
600
 
601
  if not dists:
 
604
 
605
 
606
  # ══════════════════════════════════════════════════════════════
607
+ # PLOT: LD DECAY (bp-based scatter)
608
  # ══════════════════════════════════════════════════════════════
609
 
610
+ def plot_ld_decay_bp(genotypes, chromosomes, positions, save_path, max_m=120):
611
  """
612
+ LD decay scatter in bp:
613
+ - X-axis: physical distance in bp (shown as kb/Mb labels)
614
+ - Chromosome-coloured scatter dots
615
+ - Green filled cubic-spline median decay curve
616
+ - Annotated: half-decay, rΒ²=0.2, rΒ²=0.1 positions in kb or Mb
617
+ - Interpretation text panel below
 
 
618
  """
619
  _style()
 
620
  unique_chroms = sorted(set(chromosomes),
621
  key=lambda x: (int(x) if str(x).isdigit() else 999, str(x)))
622
 
623
+ chrom_to_idx = {}
 
 
 
624
  for gi, ch in enumerate(chromosomes):
625
+ chrom_to_idx.setdefault(str(ch), []).append(gi)
626
 
627
+ bp_arr_global = np.array(positions, dtype=float)
628
+
629
+ # If all positions are 0 or identical β†’ extract from marker names
630
+ # (already handled by parser, but double-check)
631
+ if bp_arr_global.max() == 0:
632
+ bp_arr_global = np.arange(len(positions), dtype=float) * 1000
633
 
 
 
 
 
 
 
 
 
 
 
 
 
634
  all_dist, all_r2, all_dp, all_ch = [], [], [], []
635
  chrom_stats = {}
636
 
637
  for ch in unique_chroms:
638
+ idxs = chrom_to_idx.get(str(ch), [])
639
  if len(idxs) < 4:
640
  continue
641
  if len(idxs) > max_m:
642
  idxs = sorted(np.random.choice(idxs, max_m, replace=False))
643
 
644
+ G_ch = genotypes[:, idxs].copy().astype(float)
645
+ bp_ch = bp_arr_global[idxs]
646
+
647
+ # Sort by position within chromosome
648
+ sort_order = np.argsort(bp_ch)
649
+ G_ch = G_ch[:, sort_order]
650
+ bp_ch = bp_ch[sort_order]
651
 
652
+ dist, r2, dp = _compute_ld_pairs_bp(G_ch, bp_ch, max_lag=60)
653
  if len(dist) == 0:
654
  continue
655
 
 
664
  'mean_r2': float(np.mean(r2)),
665
  'mean_dprime': float(np.mean(dp)),
666
  'max_r2': float(np.max(r2)),
667
+ 'max_dist_bp': float(dist.max()) if len(dist) else 0,
668
  }
669
 
670
  if not all_dist:
671
  fig, ax = plt.subplots(figsize=(10, 6), facecolor=BG)
672
+ ax.text(0.5, 0.5, 'No LD data available\n(need β‰₯4 markers per chromosome)',
673
+ ha='center', va='center', transform=ax.transAxes,
674
+ fontsize=13, color=TEXT_C)
675
  plt.savefig(save_path, dpi=120, bbox_inches='tight')
676
  plt.close(fig)
677
  return chrom_stats, "No LD data available."
 
680
  r2_arr = np.array(all_r2, dtype=float)
681
  ch_arr = np.array(all_ch, dtype=str)
682
 
683
+ # Determine display unit (bp / kb / Mb)
684
+ max_bp = float(np.percentile(dist_arr, 99))
685
+ if max_bp == 0:
686
+ max_bp = dist_arr.max()
687
+
688
+ if max_bp >= 1_000_000:
689
+ scale, unit_label = 1_000_000, 'Mb'
690
+ elif max_bp >= 1_000:
691
+ scale, unit_label = 1_000, 'kb'
692
+ else:
693
+ scale, unit_label = 1, 'bp'
694
 
695
+ dist_scaled = dist_arr / scale
696
+ max_scaled = max_bp / scale
697
 
698
+ # ── binned median curve ───────────────────────────────────────────────
699
+ mask = dist_arr <= max_bp
700
+ dv = dist_scaled[mask]
701
+ rv = r2_arr[mask]
702
+
703
+ N_BINS = 80
704
+ bins = np.linspace(0, max_scaled, N_BINS + 1)
705
  ctrs, meds = [], []
706
  for i in range(N_BINS):
707
+ m = (dv >= bins[i]) & (dv < bins[i+1])
708
  if m.sum() >= 3:
709
+ ctrs.append((bins[i] + bins[i+1]) / 2.0)
710
  meds.append(np.median(rv[m]))
711
 
712
  ctrs = np.array(ctrs, dtype=float)
713
  meds = np.array(meds, dtype=float)
714
 
715
+ # ── spline ────────────────────────────────────────────────────────────
716
+ ann = {}
717
+ xs_smooth = ys_smooth = None
718
  if len(ctrs) >= 5:
719
+ k = min(3, len(ctrs) - 1)
720
+ xs_smooth = np.linspace(ctrs[0], ctrs[-1], 2000)
721
+ spl = make_interp_spline(ctrs, meds, k=k)
722
+ ys_smooth = np.clip(spl(xs_smooth), 0, 1)
723
+
724
+ r2_start = ys_smooth[0] if ys_smooth[0] > 0 else meds[0]
725
+ for thr_name, thr_val in [('half', r2_start / 2.0),
726
+ ('r2_02', 0.20),
727
+ ('r2_01', 0.10)]:
728
+ idx_cross = np.where(ys_smooth <= thr_val)[0]
729
  if len(idx_cross):
730
+ ann[thr_name] = float(xs_smooth[idx_cross[0]])
731
+
732
+ # ── LD interpretation ─────────────────────────────────────────────────
733
+ overall_r2 = float(np.mean(r2_arr))
734
+ overall_dp = float(np.mean(all_dp))
735
+ n_pairs = len(dist_arr)
736
 
737
+ def _fmt_dist(v):
738
+ return f"{v:.2f} {unit_label}"
 
739
 
740
+ ilines = []
741
  if 'half' in ann:
742
+ speed = ("rapid" if ann['half'] < (500/scale if scale==1 else 0.5)
743
+ else "moderate" if ann['half'] < (5000/scale if scale==1 else 5)
744
+ else "slow")
745
+ ilines += [
746
+ f"β€’ LD half-decay (rΒ² β†’ 50% of peak): {_fmt_dist(ann['half'])} [{speed} decay]",
747
  ]
748
  else:
749
+ ilines += ["β€’ Half-decay not reached β€” strong LD persists across entire range."]
750
 
751
  if 'r2_02' in ann:
752
+ ilines += [f"β€’ rΒ² drops below 0.2 (GWAS tagging threshold): {_fmt_dist(ann['r2_02'])}"]
753
+ ilines += [f" β†’ Tag-SNPs spaced every {_fmt_dist(ann['r2_02'])} capture most variation."]
 
 
754
  else:
755
+ ilines += ["β€’ rΒ² stays above 0.2 throughout β€” very high LD / small genome window."]
756
 
757
  if 'r2_01' in ann:
758
+ ilines += [f"β€’ rΒ² drops below 0.1 (statistical independence): {_fmt_dist(ann['r2_01'])}"]
759
+
760
+ ilines += [
761
+ f"β€’ Overall mean rΒ² = {overall_r2:.3f} | mean D' = {overall_dp:.3f}",
762
+ f"β€’ Total pairs analysed: {n_pairs:,} | Chromosomes: {len(set(all_ch))}",
763
  ]
764
+ ld_interp = "\n".join(ilines)
765
 
766
+ # ══ FIGURE ═══════════════════════════════════════════════════════════
767
  chrom_color = {str(ch): CHROM_PALETTE[i % len(CHROM_PALETTE)]
768
  for i, ch in enumerate(unique_chroms)}
769
 
770
+ fig = plt.figure(figsize=(14, 9), facecolor=BG)
771
+ gs = fig.add_gridspec(2, 1, height_ratios=[3.8, 1], hspace=0.08)
 
772
  ax = fig.add_subplot(gs[0])
773
  axt = fig.add_subplot(gs[1])
774
  axt.axis('off')
 
775
  ax.set_facecolor('#EEE8FA')
776
 
777
+ # scatter per chromosome
778
  for ch in unique_chroms:
779
  key = str(ch)
780
  cmsk = (ch_arr == key) & mask
781
  if not cmsk.any():
782
  continue
783
+ ax.scatter(dist_scaled[cmsk], r2_arr[cmsk],
784
+ c=chrom_color[key], s=6, alpha=0.38,
785
  linewidths=0, zorder=2, label=key)
786
 
787
+ # smooth decay curve + fill
788
+ if xs_smooth is not None and len(xs_smooth) > 0:
789
+ ax.fill_between(xs_smooth, 0, ys_smooth,
790
+ color='#22C55E', alpha=0.22, zorder=3)
791
+ ax.plot(xs_smooth, ys_smooth, color=GREEN_C,
792
+ linewidth=2.4, zorder=4, label='Median rΒ² decay')
793
 
794
+ # rΒ²=0.2 dashed reference
795
+ ax.axhline(0.2, color='#111827', ls='--', lw=1.6,
796
+ alpha=0.75, zorder=5, label='rΒ² = 0.2')
797
 
798
+ # annotation vertical lines
799
  ann_styles = {
800
+ 'half': (GOLD_C, f'Β½ decay', 0.50, 0.10),
801
+ 'r2_02': (RED_C, f'rΒ²=0.2', 0.20, 0.08),
802
+ 'r2_01': (TEAL_C, f'rΒ²=0.1', 0.10, 0.06),
803
  }
804
+ for akey, (col, lbl, r2ref, offset_y) in ann_styles.items():
805
+ if akey in ann:
806
+ xv = ann[akey]
807
+ ax.axvline(xv, color=col, ls=':', lw=1.9, alpha=0.88, zorder=6)
808
  ax.annotate(
809
+ f'{lbl}\n{_fmt_dist(xv)}',
810
+ xy=(xv, r2ref),
811
+ xytext=(xv + max_scaled * 0.012, r2ref + offset_y),
812
  fontsize=8.5, fontweight='bold', color=col,
813
  arrowprops=dict(arrowstyle='->', color=col, lw=1.2),
814
+ bbox=dict(boxstyle='round,pad=0.3', fc=BG,
815
+ ec=col, alpha=0.92, lw=1.1),
816
  zorder=7,
817
  )
818
 
819
+ # axes
820
+ ax.set_xlim(0, max_scaled)
821
  ax.set_ylim(0, 1.05)
822
+ ax.set_xlabel(f'Physical distance ({unit_label})',
823
+ fontsize=12, fontweight='bold', color=TEXT_C, labelpad=6)
824
+ ax.set_ylabel('LD estimate (RΒ²)',
825
+ fontsize=12, fontweight='bold', color=TEXT_C, labelpad=6)
826
+ ax.set_title('LD Decay by Chromosome (Physical Distance)',
827
+ fontsize=14, fontweight='bold', color=TEXT_C, pad=10)
828
  ax.xaxis.grid(True, color=GRID_C, lw=0.6, alpha=0.9)
829
  ax.yaxis.grid(True, color=GRID_C, lw=0.6, alpha=0.9)
830
  ax.set_axisbelow(True)
831
 
832
+ # legend
833
  handles, labels = ax.get_legend_handles_labels()
834
  special = [(h, l) for h, l in zip(handles, labels)
835
  if l in ('Median rΒ² decay', 'rΒ² = 0.2')]
 
837
  if l not in ('Median rΒ² decay', 'rΒ² = 0.2')]
838
  leg_h = [h for h, _ in special] + [h for h, _ in chrs]
839
  leg_l = [l for _, l in special] + [f'Chr {l}' for _, l in chrs]
840
+ ncols = max(1, (len(chrs) + 9) // 10)
841
+ legend = ax.legend(leg_h, leg_l, title='Chr', title_fontsize=9,
842
+ fontsize=7.5, loc='upper right', ncol=ncols,
843
+ framealpha=0.93, edgecolor=GRID_C,
844
+ markerscale=2.2, handlelength=1.3,
845
+ borderpad=0.7, labelspacing=0.4)
 
846
  legend.get_title().set_fontweight('bold')
847
 
848
+ # interpretation text panel
849
+ interp_text = ("LD DECAY INTERPRETATION\n"
850
+ + "─" * 78 + "\n"
851
+ + ld_interp)
852
+ axt.text(0.005, 0.98, interp_text,
853
+ transform=axt.transAxes, va='top', ha='left',
854
+ fontsize=8.5, color=TEXT_C, fontfamily='monospace',
 
 
 
 
855
  bbox=dict(boxstyle='round,pad=0.5',
856
  facecolor='#EDE9FE', edgecolor=GRID_C,
857
  alpha=0.95))
858
 
859
  plt.savefig(save_path, dpi=130, bbox_inches='tight', facecolor=BG)
860
  plt.close(fig)
861
+ return chrom_stats, ld_interp
 
862
 
863
 
864
  # ══════════════════════════════════════════════════════════════
865
+ # PLOT: MODEL COMPARISON
866
  # ══════════════════════════════════════════════════════════════
867
 
868
+ def plot_model_comparison(model_pvals, save_path):
 
869
  _style()
870
+ models = list(model_pvals.keys())
871
+ n = len(models)
872
+ ncols = min(3, n*(n-1)//2 if n > 1 else 1)
873
+ pairs = [(models[i], models[j])
874
+ for i in range(n) for j in range(i+1, n)]
875
+ nrows = (len(pairs) + ncols - 1) // ncols
876
+ if not pairs:
877
+ return
878
+
879
+ fig, axes = plt.subplots(nrows, ncols,
880
+ figsize=(5.5*ncols, 5*nrows),
881
+ facecolor=BG, squeeze=False)
882
+
883
+ for idx, (ma, mb) in enumerate(pairs):
884
+ r, c = divmod(idx, ncols)
885
+ ax = axes[r][c]
886
+ ax.set_facecolor(PANEL)
887
+ pa = -np.log10(np.clip(model_pvals[ma], 1e-300, 1))
888
+ pb = -np.log10(np.clip(model_pvals[mb], 1e-300, 1))
889
+ corr = np.corrcoef(pa, pb)[0, 1]
890
+ ax.scatter(pa, pb, alpha=0.40, s=12,
891
+ color=MODEL_COLORS.get(ma, ACCENT),
892
+ edgecolors='none')
893
+ mx = max(pa.max(), pb.max()) * 1.05
894
+ ax.plot([0, mx], [0, mx], color=GOLD_C, ls='--', lw=1.2)
895
+ ax.set_xlabel(f'{ma} βˆ’log₁₀(P)', fontsize=9, fontweight='bold')
896
+ ax.set_ylabel(f'{mb} βˆ’log₁₀(P)', fontsize=9, fontweight='bold')
897
+ ax.set_title(f'{ma} vs {mb} (r={corr:.3f})',
898
+ fontsize=10, fontweight='bold')
899
+ ax.grid(True, color=GRID_C, lw=0.6, alpha=0.5)
900
+
901
+ for extra in range(len(pairs), nrows * ncols):
902
+ r, c = divmod(extra, ncols)
903
+ axes[r][c].set_visible(False)
904
+
905
+ plt.suptitle('Model P-value Concordance (βˆ’log₁₀ scale)',
906
+ fontsize=12, fontweight='bold', color=TEXT_C)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
907
  plt.tight_layout(pad=1.5)
908
  plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=BG)
909
  plt.close(fig)
910
 
911
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
912
  # ══════════════════════════════════════════════════════════════
913
  # PLOT: PHENOTYPE DISTRIBUTION
914
  # ══════════════════════════════════════════════════════════════
915
 
916
+ def plot_phenotype(phenotypes, save_path):
917
  _style()
918
  pv = phenotypes[~np.isnan(phenotypes)]
919
  fig, axes = plt.subplots(1, 2, figsize=(11, 4.5), facecolor=BG)
920
 
921
+ ax = axes[0]; ax.set_facecolor(PANEL)
922
+ ax.hist(pv, bins=30, color=ACCENT, alpha=0.72, edgecolor='white', lw=0.5)
923
+ ax.axvline(np.mean(pv), color=RED_C, ls='--', lw=1.6,
 
 
924
  label=f'Mean={np.mean(pv):.2f}')
925
+ ax.axvline(np.median(pv), color=GOLD_C, ls=':', lw=1.6,
926
  label=f'Median={np.median(pv):.2f}')
927
  ax.set_xlabel('Phenotype Value', fontsize=11, fontweight='bold')
928
+ ax.set_ylabel('Frequency', fontsize=11, fontweight='bold')
929
  ax.set_title('Phenotype Distribution', fontsize=12, fontweight='bold')
930
  ax.legend(fontsize=9)
931
  ax.grid(True, color=GRID_C, lw=0.7)
932
+ sw_s, sw_p = stats.shapiro(pv[:5000])
933
+ ax.text(0.97, 0.95, f'Shapiro-Wilk p={sw_p:.3e}',
934
+ transform=ax.transAxes, ha='right', va='top', fontsize=8.5,
935
+ bbox=dict(boxstyle='round', facecolor=BG,
936
+ edgecolor=GRID_C, alpha=0.9))
937
 
938
+ ax = axes[1]; ax.set_facecolor(PANEL)
 
939
  stats.probplot(pv, dist='norm', plot=ax)
940
  ax.get_lines()[0].set(color=ACCENT, markersize=3, alpha=0.6)
941
+ ax.get_lines()[1].set(color=RED_C, lw=1.5)
942
+ ax.set_title('Normal Q-Q (Phenotype)', fontsize=12, fontweight='bold')
943
  ax.grid(True, color=GRID_C, lw=0.7)
944
 
 
 
 
 
 
 
 
945
  plt.tight_layout(pad=1.5)
946
  plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=BG)
947
  plt.close(fig)
948
 
949
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
950
  # ══════════════════════════════════════════════════════════════
951
  # MAIN ANALYSIS
952
  # ══════════════════════════════════════════════════════════════
953
 
954
+ def run_analysis(input_file, miss_sample, miss_marker, maf_thresh,
955
+ run_glm, run_mlm, run_cmlm, run_bslmm, run_farmcpu):
956
  try:
957
  if input_file is None:
958
+ return ("⚠️ Upload a CSV file first.",
959
  None, None, None, None, None, None)
960
 
961
  tmp = tempfile.mkdtemp()
 
963
  pdir = os.path.join(rdir, 'plots')
964
  for d in [rdir, pdir]: os.makedirs(d, exist_ok=True)
965
 
966
+ ms_t = miss_sample / 100.0
967
+ mm_t = miss_marker / 100.0
968
+ mf_t = maf_thresh / 100.0
969
 
970
+ # ── Parse ────────────────────────────────────────────────────────────
971
  print("[Parse] Reading CSV…")
972
  (sids, pheno, geno,
973
+ mnames, chroms, positions) = parse_input_csv(input_file)
 
974
  n_s, n_m = len(sids), len(mnames)
975
  print(f"[Parse] {n_s} samples Γ— {n_m} markers")
976
 
977
  # ── QC ───────────────────────────────────────────────────────────────
978
+ miss_m_r = np.isnan(geno).sum(0) / max(n_s, 1)
979
+ miss_s_r = np.isnan(geno).sum(1) / max(n_m, 1)
980
+ maf_arr = np.zeros(n_m)
 
981
  for i in range(n_m):
982
  v = geno[:, i]; v = v[~np.isnan(v)]
983
  if len(v):
984
  f = np.mean(v) / 2.0
985
+ maf_arr[i] = min(f, 1 - f)
986
 
987
+ qc_m = (miss_m_r < mm_t) & (maf_arr >= mf_t)
988
+ qc_s = miss_s_r < ms_t
989
  fallback = ""
 
990
  for rs, rm in [(ms_t, mm_t),
991
  (.6,.6),(.7,.7),(.8,.8),(.9,.9),(1.,1.)]:
992
+ qm = (miss_m_r < rm) & (maf_arr >= mf_t)
993
+ qs = miss_s_r < rs
994
  if qs.sum() >= 10:
995
  qc_m, qc_s = qm, qs
996
  if rs > ms_t or rm > mm_t:
997
+ fallback = (f"\n⚠️ QC relaxed β†’ sample<{rs*100:.0f}%"
998
+ f" / marker<{rm*100:.0f}%\n")
999
  break
1000
 
1001
  geno_q = geno[np.ix_(qc_s, qc_m)].copy()
1002
  pheno_q = pheno[qc_s]
1003
  sids_q = sids[qc_s]
1004
+ mn_q = [mnames[i] for i in range(n_m) if qc_m[i]]
1005
+ ch_q = [chroms[i] for i in range(n_m) if qc_m[i]]
1006
+ pos_q = [positions[i] for i in range(n_m) if qc_m[i]]
1007
  n_q = len(mn_q)
 
1008
  print(f"[QC] {len(sids_q)} samples Γ— {n_q} markers")
1009
 
1010
+ # Impute missing genotypes with column mean
1011
  col_mu = np.nanmean(geno_q, 0)
1012
  col_mu = np.where(np.isnan(col_mu), 0, col_mu)
1013
  for i in range(geno_q.shape[1]):
 
1015
  if mk.any(): geno_q[mk, i] = col_mu[i]
1016
 
1017
  valid = ~np.isnan(pheno_q)
1018
+ geno_q = geno_q[valid]; pheno_q = pheno_q[valid]; sids_q = sids_q[valid]
 
1019
 
1020
  if len(sids_q) < 10:
1021
  return (f"## ⚠️ Only {len(sids_q)} samples passed QC. "
1022
+ "Try increasing missing-rate sliders.",
1023
  None, None, None, None, None, None)
1024
 
1025
+ bonf = 0.05 / n_q
1026
  bonf_log = -np.log10(bonf)
1027
 
1028
+ # ── Kinship (needed for MLM, CMLM, FarmCPU) ──────────────────────────
1029
+ print("[Kinship] Computing K matrix…")
1030
+ K = compute_kinship(geno_q)
1031
+
1032
+ # ── Run selected models ───────────────────────────────────────────────
1033
+ model_pvals = {}
1034
+ model_betas = {}
1035
+ model_ses = {}
1036
+
1037
+ if run_glm:
1038
+ print("[Model 1/5] GLM…")
1039
+ pv, bv, sv, rv = model_glm(geno_q, pheno_q)
1040
+ model_pvals['GLM'] = pv; model_betas['GLM'] = bv; model_ses['GLM'] = sv
1041
+
1042
+ if run_mlm:
1043
+ print("[Model 2/5] MLM…")
1044
+ pv, bv, sv, rv = model_mlm(geno_q, pheno_q, K)
1045
+ model_pvals['MLM'] = pv; model_betas['MLM'] = bv; model_ses['MLM'] = sv
1046
+
1047
+ if run_cmlm:
1048
+ print("[Model 3/5] CMLM…")
1049
+ pv, bv, sv, rv = model_cmlm(geno_q, pheno_q, K)
1050
+ model_pvals['CMLM'] = pv; model_betas['CMLM'] = bv; model_ses['CMLM'] = sv
1051
+
1052
+ if run_bslmm:
1053
+ print("[Model 4/5] BSLMM…")
1054
+ pv, bv = model_bslmm(geno_q, pheno_q)
1055
+ model_pvals['BSLMM'] = pv; model_betas['BSLMM'] = bv
1056
+
1057
+ if run_farmcpu:
1058
+ print("[Model 5/5] FarmCPU…")
1059
+ pv, bv, sv = model_farmcpu(geno_q, pheno_q, K)
1060
+ model_pvals['FarmCPU'] = pv; model_betas['FarmCPU'] = bv; model_ses['FarmCPU'] = sv
1061
+
1062
+ if not model_pvals:
1063
+ return ("## ⚠️ No models selected. Please enable at least one.",
1064
+ None, None, None, None, None, None)
1065
 
1066
+ # ── Build results CSV ─────────────────────────────────────────────────
1067
+ df = pd.DataFrame({'Marker': mn_q, 'Chromosome': ch_q,
1068
+ 'Position_bp': pos_q})
1069
+ for mname, pv in model_pvals.items():
1070
+ df[f'{mname}_P'] = pv
1071
+ df[f'{mname}_LOD'] = -np.log10(np.clip(pv, 1e-300, 1))
1072
+ df[f'{mname}_Sig'] = (pv < bonf).astype(int)
1073
+ if mname in model_betas:
1074
+ df[f'{mname}_Beta'] = model_betas[mname]
1075
+
1076
+ # Consensus: significant in β‰₯ half of run models
1077
+ sig_cols = [f'{m}_Sig' for m in model_pvals]
1078
+ df['Consensus_Sig'] = (df[sig_cols].sum(1) >= max(1, len(sig_cols)//2)).astype(int)
1079
+ df = df.sort_values(f"{list(model_pvals.keys())[0]}_P").reset_index(drop=True)
1080
+ df.insert(0, 'Rank', range(1, len(df)+1))
1081
  df.to_csv(os.path.join(rdir, 'gwas_results.csv'), index=False)
1082
 
1083
+ # Significant only (any model)
1084
+ any_sig = df[sig_cols].sum(1) > 0
1085
+ df[any_sig].to_csv(os.path.join(rdir, 'top_significant.csv'), index=False)
1086
 
1087
  # ── Plots ─────────────────────────────────────────────────────────────
1088
  print("[Plot 1/5] Phenotype distribution…")
1089
  ph_path = os.path.join(pdir, 'phenotype_dist.png')
1090
+ plot_phenotype(pheno_q, ph_path)
1091
 
1092
+ print("[Plot 2/5] Manhattan (multi-model)…")
1093
  man_path = os.path.join(pdir, 'manhattan_lod.png')
1094
+ plot_manhattan_multi(mn_q, ch_q, model_pvals, bonf, man_path)
 
 
 
1095
 
1096
+ print("[Plot 3/5] QQ plots…")
1097
  qq_path = os.path.join(pdir, 'qq_plot.png')
1098
+ lam_dict = plot_qq_multi(model_pvals, bonf, qq_path)
 
 
 
 
1099
 
1100
+ print("[Plot 4/5] LD decay (bp)…")
1101
+ ld_path = os.path.join(pdir, 'ld_decay_bp.png')
1102
+ ld_stats, ld_interp = plot_ld_decay_bp(geno_q, ch_q, pos_q, ld_path)
1103
+ ld_df = pd.DataFrame([{'Chromosome': k, **v} for k, v in ld_stats.items()])
1104
  ld_df.to_csv(os.path.join(rdir, 'ld_decay_stats.csv'), index=False)
1105
 
1106
  print("[Plot 5/5] Model comparison…")
1107
  cmp_path = os.path.join(pdir, 'model_comparison.png')
1108
+ plot_model_comparison(model_pvals, cmp_path)
1109
 
1110
  # ── ZIP ───────────────────────────────────────────────────────────────
1111
  zip_path = os.path.join(tmp, 'GWAS_Results.zip')
 
1115
  fp = os.path.join(root, f)
1116
  zf.write(fp, os.path.relpath(fp, tmp))
1117
 
1118
+ # ── Summary ───────────────────────────────────────────────────────────
1119
+ def _mdt(d, n=15):
1120
+ sub = d.head(n)
1121
+ cols = sub.columns.tolist()
1122
  def _f(v):
1123
  if isinstance(v, float):
1124
+ return f"{v:.3e}" if (v!=0 and abs(v)<0.001) else f"{v:.4f}"
1125
  return str(v)
1126
  sep = "| " + " | ".join(["---"]*len(cols)) + " |"
1127
  rows = ["| "+" | ".join(_f(row[c]) for c in cols)+" |"
1128
+ for _, row in sub.iterrows()]
1129
  return "\n".join(["| "+" | ".join(cols)+" |", sep]+rows)
1130
 
1131
+ model_summary_rows = "\n".join(
1132
+ f"| {m} | **{int((pv < bonf).sum())}** | Ξ»={lam_dict.get(m,0):.3f} | "
1133
+ f"{'⚠️ inflation' if lam_dict.get(m,1)>1.05 else 'βœ… ok'} |"
1134
+ for m, pv in model_pvals.items()
1135
+ )
1136
+
1137
+ top_cols = (['Rank','Marker','Chromosome','Position_bp'] +
1138
+ [f'{m}_P' for m in model_pvals] +
1139
+ ['Consensus_Sig'])
1140
+ top_cols = [c for c in top_cols if c in df.columns]
1141
 
1142
  summary = f"""
1143
+ ## βœ… GWAS Analysis Complete β€” v8.0
1144
 
1145
  ### πŸ“Š QC Summary
1146
  | Metric | Value |
1147
+ |---|---|
1148
  | Samples (raw β†’ QC) | {n_s} β†’ **{len(sids_q)}** |
1149
  | Markers (raw β†’ QC) | {n_m} β†’ **{n_q}** |
1150
  | Chromosomes | **{len(set(ch_q))}** |
1151
+ | MAF β‰₯ | {maf_thresh:.1f}% |
1152
+ | Sample missing < | {miss_sample:.0f}% |
1153
+ | Marker missing < | {miss_marker:.0f}% |
1154
  {fallback}
1155
 
1156
+ ### πŸ”¬ Model Results
1157
+ | Model | Sig. Markers (Bonferroni) | Ξ» | Status |
1158
+ |---|---|---|---|
1159
+ {model_summary_rows}
 
 
1160
 
1161
+ **Bonferroni threshold:** P < {bonf:.3e} &nbsp;|&nbsp; βˆ’log₁₀P > {bonf_log:.2f}
1162
 
1163
+ ### 🧬 LD Decay (Physical Distance)
 
 
 
 
1164
  {ld_interp}
1165
 
1166
+ ### πŸ† Top 15 Markers
1167
+ {_mdt(df[top_cols])}
1168
 
1169
  ---
1170
  **Output files:**
1171
+ - `gwas_results.csv` β€” all markers, all model statistics
1172
+ - `top_significant.csv` β€” any-model Bonferroni-significant markers
1173
  - `ld_decay_stats.csv` β€” per-chromosome LD statistics
1174
+ - `manhattan_lod.png` β€” per-model Manhattan plots
1175
+ - `qq_plot.png` β€” QQ + Ξ» for each model
1176
+ - `ld_decay_bp.png` β€” LD decay scatter (bp/kb/Mb) with annotations
1177
+ - `model_comparison.png` β€” pairwise model concordance
1178
+ - `phenotype_dist.png` β€” phenotype distribution & normality
1179
  """
1180
  print("[Done] βœ…")
1181
  return (summary, man_path, ld_path, qq_path,
 
1196
  h1{color:#2D1B5E;border-bottom:3px solid #7C3AED;padding-bottom:8px}
1197
  """
1198
 
1199
+ with gr.Blocks(css=CSS, title="MTA GWAS v8.0") as app:
1200
 
1201
  gr.Markdown("""
1202
+ # 🧬 GWAS Analysis Platform v8.0
1203
+ ### 5-Model MRmlm Suite | LD Decay in bp | Fixed QQ Plot | Complete Outputs
 
1204
  ---
1205
  """)
1206
 
1207
  with gr.Row():
1208
  with gr.Column(scale=1):
1209
  gr.Markdown("""
1210
+ ### πŸ“‹ CSV Format (3-row header)
1211
  ```
1212
+ ID, Phenotype, M1_bp_gene, M2_bp_gene, ...
1213
+ -, Chr, 1, 1, ... ← chromosome
1214
+ -, Pos, 134521, 134810, ... ← bp position
1215
+ IRRI-1, 25.34, 0, 2, ...
1216
+ IRRI-75, 23.34, 0, 0, ...
1217
  ```
1218
+ **Genotypes:** 0/1/2 (βˆ’1 or blank = missing)
1219
  """)
1220
  input_file = gr.File(label="πŸ“ Upload CSV", file_types=[".csv"])
1221
 
 
1227
  label="Max marker missing rate (%)")
1228
  maf_thr = gr.Slider(0, 25, value=3, step=1,
1229
  label="Min MAF (%)")
1230
+
1231
+ with gr.Column(scale=1):
1232
+ gr.Markdown("### πŸ”¬ Select Models")
1233
+ chk_glm = gr.Checkbox(value=True, label="GLM β€” General Linear Model")
1234
+ chk_mlm = gr.Checkbox(value=True, label="MLM β€” Mixed Linear Model")
1235
+ chk_cmlm = gr.Checkbox(value=True, label="CMLM β€” Compressed MLM")
1236
+ chk_bslmm = gr.Checkbox(value=True, label="BSLMM β€” Bayesian Sparse LMM")
1237
+ chk_farmcpu = gr.Checkbox(value=True, label="FarmCPU β€” Fixed & Random")
 
1238
 
1239
  run_btn = gr.Button("πŸš€ Run GWAS Analysis", variant="primary", size="lg")
1240
  gr.Markdown("---")
 
1242
  summary_out = gr.Markdown()
1243
 
1244
  with gr.Row():
1245
+ man_out = gr.Image(label="πŸ—ΊοΈ Manhattan Plots (all models)")
1246
+ ld_out = gr.Image(label="🧬 LD Decay β€” bp / kb / Mb (annotated)")
1247
 
1248
  with gr.Row():
1249
+ qq_out = gr.Image(label="πŸ“ˆ QQ Plots + Ξ» (all models)")
1250
+ cmp_out = gr.Image(label="βš–οΈ Model Concordance")
1251
 
1252
  with gr.Row():
1253
  ph_out = gr.Image(label="πŸ“Š Phenotype Distribution")
 
1255
 
1256
  gr.Markdown("""
1257
  ---
1258
+ **MTA GWAS v8.0** | GLM Β· MLM Β· CMLM Β· BSLMM Β· FarmCPU | bp LD decay | Correct QQ
1259
  """)
1260
 
1261
  run_btn.click(
1262
+ fn=run_analysis,
1263
+ inputs=[input_file, miss_sample, miss_marker, maf_thr,
1264
+ chk_glm, chk_mlm, chk_cmlm, chk_bslmm, chk_farmcpu],
1265
  outputs=[summary_out, man_out, ld_out, qq_out,
1266
  cmp_out, ph_out, dl_out],
1267
  show_progress=True,