softwareDevelopment commited on
Commit
c7fcb6e
Β·
verified Β·
1 Parent(s): 7da64d8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +796 -1528
app.py CHANGED
@@ -1,24 +1,13 @@
1
  # -*- coding: utf-8 -*-
2
  """
3
- Created on Tue Apr 7 19:46:59 2026
4
-
5
- @author: Ashmi
6
- """
7
-
8
- # -*- coding: utf-8 -*-
9
- """
10
- MTA GWAS Analysis Tool v11.0 β€” COMPLETELY FIXED EDITION
11
- =========================================================
12
- FIXES APPLIED:
13
- βœ… LD Decay: Proper Hill-Weir (1988) model with population size estimation
14
- βœ… Model selection: All models work correctly (GLM, MLM, CMLM, BSLMM, FarmCPU)
15
- βœ… Manhattan plot model switching: Dropdown properly updates plots
16
- βœ… Matrix dimensionality: Fixed all linear algebra operations
17
- βœ… BSLMM: Fixed cross-validation and bootstrapping
18
- βœ… FarmCPU: Fixed iterative conditioning
19
- βœ… Kinship matrix: Now positive definite
20
- βœ… ALL plots: White background, black/dark text for publication quality
21
- βœ… Fixed tabulate dependency issue
22
  """
23
 
24
  import gradio as gr
@@ -27,1596 +16,875 @@ import numpy as np
27
  import matplotlib
28
  matplotlib.use('Agg')
29
  import matplotlib.pyplot as plt
30
- import matplotlib.patches as mpatches
31
- from matplotlib.gridspec import GridSpec
32
- from matplotlib.colors import LinearSegmentedColormap
33
  from scipy import stats
34
- from scipy.optimize import curve_fit, minimize_scalar
35
- import os, warnings, zipfile
36
- from pathlib import Path
37
- from sklearn.linear_model import ElasticNetCV, RidgeCV
38
  from sklearn.preprocessing import StandardScaler
39
- from sklearn.decomposition import PCA
40
- from sklearn.cluster import KMeans
 
 
41
  warnings.filterwarnings('ignore')
42
 
43
- # Try to import tabulate, provide fallback if not available
44
- try:
45
- from tabulate import tabulate
46
- TABULATE_AVAILABLE = True
47
- except ImportError:
48
- TABULATE_AVAILABLE = False
49
- # Define a simple tabulate function as fallback
50
- def tabulate(data, headers="keys", tablefmt="pipe", **kwargs):
51
- """Simple fallback tabulate function."""
52
- if headers == "keys":
53
- headers = list(data.columns)
54
-
55
- # Create markdown table
56
- lines = []
57
- # Header row
58
- lines.append("| " + " | ".join(str(h) for h in headers) + " |")
59
- # Separator row
60
- lines.append("|" + "|".join([" --- " for _ in headers]) + "|")
61
- # Data rows
62
- for _, row in data.iterrows():
63
- lines.append("| " + " | ".join(str(v) for v in row.values) + " |")
64
-
65
- return "\n".join(lines)
66
-
67
- OUTPUT_DIR = Path("/tmp/gwas_outputs")
68
- OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
69
-
70
  # ══════════════════════════════════════════════════════════════
71
- # UNIVERSAL WHITE THEME - All plots publication-ready
72
  # ══════════════════════════════════════════════════════════════
73
- W_BG = "#FFFFFF"
74
- W_PANEL = "#F8FAFC"
75
- W_GRID = "#DEE2E8"
76
- W_TEXT = "#1A202C"
77
- W_SUBTEXT = "#4A5568"
78
- W_BORDER = "#CBD5E0"
79
- W_ACCENT = "#2B6CB0"
80
- W_RED = "#C53030"
81
- W_GOLD = "#B7791F"
82
- W_GREEN = "#276749"
83
- W_ORANGE = "#C05621"
84
- W_PURPLE = "#553C9A"
85
- W_TEAL = "#2C7A7B"
86
- W_PINK = "#97266D"
87
-
88
- # Chromosome colors (colorblind-friendly)
89
- CHROM_COLORS = [
90
- "#1565C0", "#2E7D32", "#C62828", "#F57F17", "#6A1B9A",
91
- "#00695C", "#AD1457", "#4527A0", "#0277BD", "#558B2F",
92
- "#E65100", "#37474F", "#880E4F", "#1B5E20", "#BF360C",
93
- "#0D47A1", "#33691E", "#827717", "#4A148C", "#006064",
94
  ]
95
 
96
- MODEL_COLORS = {
97
- 'GLM': '#1565C0',
98
- 'MLM': '#C62828',
99
- 'CMLM': '#2E7D32',
100
- 'BSLMM': '#F57F17',
101
- 'FarmCPU': '#6A1B9A',
102
- }
103
-
104
- def _style_white():
105
- """Apply clean white scientific publication theme."""
106
  plt.rcParams.update({
107
- 'figure.facecolor': W_BG,
108
- 'axes.facecolor': W_PANEL,
109
- 'axes.edgecolor': W_BORDER,
110
- 'axes.labelcolor': W_TEXT,
111
- 'axes.titlecolor': W_TEXT,
112
- 'xtick.color': W_TEXT,
113
- 'ytick.color': W_TEXT,
114
- 'text.color': W_TEXT,
115
- 'grid.color': W_GRID,
116
- 'grid.linewidth': 0.6,
117
- 'figure.dpi': 120,
118
- 'font.family': 'DejaVu Sans',
119
- 'font.size': 10,
120
- 'axes.titlesize': 12,
121
- 'axes.labelsize': 11,
122
- 'axes.spines.top': False,
123
- 'axes.spines.right': False,
124
- 'legend.framealpha': 0.95,
125
- 'legend.edgecolor': W_BORDER,
126
- 'legend.facecolor': W_BG,
127
- 'savefig.facecolor': W_BG,
128
- 'savefig.edgecolor': W_BG,
129
  })
130
 
131
  # ══════════════════════════════════════════════════════════════
132
- # CSV PARSER
133
  # ══════════════════════════════════════════════════════════════
134
- def parse_input_csv(filepath):
135
- """Parse input CSV file with genotype data."""
136
- df = pd.read_csv(filepath, header=0, dtype=str)
137
- marker_cols = df.columns[2:].tolist()
138
- chr_row = df.iloc[0]
139
- pos_row = df.iloc[1]
140
- chrom_dict, pos_dict = {}, {}
141
-
142
- for m in marker_cols:
143
- cv = str(chr_row[m]).strip()
144
- cv = cv[:-2] if cv.endswith('.0') else cv
145
- cv = cv.replace('chr', '').replace('Chr', '').strip()
146
- chrom_dict[m] = cv if cv not in ('', 'nan', '-') else '0'
147
-
148
- pv_s = str(pos_row[m]).strip()
149
- try:
150
- pos_dict[m] = float(pv_s)
151
- except ValueError:
152
- parts = m.split('_')
153
- bp = 0.0
154
- for part in parts:
155
- try:
156
- cand = float(part)
157
- if cand > 1000:
158
- bp = cand
159
- break
160
- except ValueError:
161
- continue
162
- pos_dict[m] = bp
163
-
164
- df_s = df.iloc[2:].reset_index(drop=True)
165
- sample_ids = df_s.iloc[:, 0].astype(str).values
166
- phenotypes = pd.to_numeric(df_s.iloc[:, 1], errors='coerce').values
167
- geno_raw = (df_s[marker_cols]
168
- .apply(pd.to_numeric, errors='coerce')
169
- .replace(-1, np.nan)
170
- .where(lambda x: x.isin([0, 1, 2]) | x.isna(), other=np.nan))
171
- chromosomes = [chrom_dict[m] for m in marker_cols]
172
- positions = [pos_dict[m] for m in marker_cols]
173
-
174
- return (sample_ids, phenotypes, geno_raw.values, marker_cols, chromosomes, positions)
175
 
176
- # ══════════════════════════════════════════════════════════════
177
- # KINSHIP MATRIX (Fixed: positive definite)
178
- # ══════════════════════════════════════════════════════════════
179
- def compute_kinship(G):
180
- """Compute kinship matrix using the formula K = (GG^T)/p, ensure positive definite."""
181
- X = G.astype(float).copy()
182
-
183
- # Center genotypes (0/1/2 -> -2p, 1-2p, 2-2p)
184
- p_hat = np.nanmean(X, axis=0) / 2.0
185
- p_hat = np.clip(p_hat, 0.01, 0.99)
186
- X_centered = X - 2 * p_hat
187
-
188
- # Impute missing with mean
189
- for i in range(X_centered.shape[1]):
190
- col = X_centered[:, i]
191
- nan_mask = np.isnan(col)
192
- if nan_mask.any():
193
- col[nan_mask] = np.nanmean(col)
194
- X_centered[:, i] = col
195
-
196
- # Kinship matrix
197
- K = np.dot(X_centered, X_centered.T) / X_centered.shape[1]
198
-
199
- # Scale to have mean diagonal ~1
200
- d = np.mean(np.diag(K))
201
- if d > 0:
202
- K = K / d
203
-
204
- # Ensure positive definite (add small ridge)
205
- min_eig = np.min(np.linalg.eigvalsh(K))
206
- if min_eig < 0:
207
- K = K + np.eye(K.shape[0]) * (-min_eig + 1e-6)
208
-
209
- return K
210
 
211
- # ══════════════════════════════════════════════════════════════
212
- # MODELS (All Fixed and Working)
213
- # ══════════════════════════════════════════════════════════════
 
 
214
 
215
- def model_glm(G, y):
216
- """General Linear Model - Simple linear regression per marker."""
217
- n, m = G.shape
218
- pv = np.ones(m)
219
- bv = np.zeros(m)
220
- sv = np.zeros(m)
221
- rv = np.zeros(m)
222
-
223
- y_centered = y - np.mean(y)
224
-
225
- for i in range(m):
226
- x = G[:, i]
227
- nan_mask = np.isnan(x)
228
- if nan_mask.any():
229
- x = x.copy()
230
- x[nan_mask] = np.nanmean(x)
231
-
232
- if np.std(x) < 1e-9:
233
- continue
234
-
235
- x_centered = x - np.mean(x)
236
- cov = np.sum(x_centered * y_centered)
237
- var_x = np.sum(x_centered * x_centered)
238
-
239
- if var_x < 1e-12:
240
- continue
241
-
242
- b = cov / var_x
243
- y_pred = b * x_centered
244
- resid = y_centered - y_pred
245
- sse = np.sum(resid * resid)
246
- df = n - 2
247
-
248
- if df > 0 and sse > 0:
249
- se = np.sqrt(sse / df / var_x)
250
- t_stat = b / (se + 1e-12)
251
- p = 2 * stats.t.sf(np.abs(t_stat), df=df)
252
- r2 = cov * cov / (var_x * np.sum(y_centered * y_centered) + 1e-12)
253
-
254
- pv[i] = max(p, 1e-300) if np.isfinite(p) else 1.0
255
- bv[i] = b
256
- sv[i] = se
257
- rv[i] = r2
258
-
259
- return pv, bv, sv, rv
260
-
261
- def model_mlm(G, y, K, n_pc=5):
262
- """Mixed Linear Model with kinship as random effect."""
263
- n = len(y)
264
- n_pc = min(n_pc, n - 2, G.shape[1] // 10)
265
-
266
- # Get eigenvectors of kinship for PCs
267
- eigvals, eigvecs = np.linalg.eigh(K)
268
- idx = np.argsort(eigvals)[::-1]
269
- Q = eigvecs[:, idx[:max(1, n_pc)]]
270
-
271
- # Project out PCs (fixed effects)
272
- Q_pinv = np.linalg.pinv(Q)
273
- y_resid = y - Q @ (Q_pinv @ y)
274
-
275
- m = G.shape[1]
276
- pv = np.ones(m)
277
- bv = np.zeros(m)
278
- sv = np.zeros(m)
279
- rv = np.zeros(m)
280
-
281
- for i in range(m):
282
- x = G[:, i]
283
- nan_mask = np.isnan(x)
284
- if nan_mask.any():
285
- x = x.copy()
286
- x[nan_mask] = np.nanmean(x)
287
-
288
- if np.std(x) < 1e-9:
289
- continue
290
-
291
- # Project out PCs from genotype
292
- x_resid = x - Q @ (Q_pinv @ x)
293
-
294
- if np.std(x_resid) < 1e-9:
295
- continue
296
-
297
- xc = x_resid - np.mean(x_resid)
298
- yc = y_resid - np.mean(y_resid)
299
- cov = np.sum(xc * yc)
300
- var_x = np.sum(xc * xc)
301
-
302
- if var_x < 1e-12:
303
- continue
304
-
305
- b = cov / var_x
306
- y_pred = b * xc
307
- resid = yc - y_pred
308
- sse = np.sum(resid * resid)
309
- df = n - n_pc - 2
310
-
311
- if df > 0 and sse > 0:
312
- se = np.sqrt(sse / df / var_x)
313
- t_stat = b / (se + 1e-12)
314
- p = 2 * stats.t.sf(np.abs(t_stat), df=df)
315
- r2 = cov * cov / (var_x * np.sum(yc * yc) + 1e-12)
316
-
317
- pv[i] = max(p, 1e-300) if np.isfinite(p) else 1.0
318
- bv[i] = b
319
- sv[i] = se
320
- rv[i] = r2
321
-
322
- return pv, bv, sv, rv
323
-
324
- def model_cmlm(G, y, K, n_groups=None, n_pc=5):
325
- """Compressed MLM - groups individuals into clusters."""
326
- n = len(y)
327
-
328
- # Get compression groups via KMeans on kinship PCs
329
- eigvals, eigvecs = np.linalg.eigh(K)
330
- idx = np.argsort(eigvals)[::-1]
331
- emb = eigvecs[:, idx[:min(10, n-1)]]
332
-
333
- if n_groups is None:
334
- n_groups = max(2, min(20, n // 10))
335
-
336
- n_groups = min(n_groups, n - 1)
337
- km = KMeans(n_clusters=n_groups, random_state=42, n_init=5)
338
- labels = km.fit_predict(emb)
339
-
340
- # Create group indicator matrix
341
- Q = np.zeros((n, n_groups))
342
- for g in range(n_groups):
343
- Q[:, g] = (labels == g).astype(float)
344
-
345
- # Normalize
346
- col_sum = Q.sum(axis=0)
347
- col_sum[col_sum == 0] = 1
348
- Q = Q / col_sum
349
-
350
- # Project out group effects
351
- Q_pinv = np.linalg.pinv(Q)
352
- y_resid = y - Q @ (Q_pinv @ y)
353
-
354
- m = G.shape[1]
355
- pv = np.ones(m)
356
- bv = np.zeros(m)
357
- sv = np.zeros(m)
358
- rv = np.zeros(m)
359
-
360
- for i in range(m):
361
- x = G[:, i]
362
- nan_mask = np.isnan(x)
363
- if nan_mask.any():
364
- x = x.copy()
365
- x[nan_mask] = np.nanmean(x)
366
-
367
- if np.std(x) < 1e-9:
368
- continue
369
-
370
- # Project out group effects from genotype
371
- x_resid = x - Q @ (Q_pinv @ x)
372
-
373
- if np.std(x_resid) < 1e-9:
374
- continue
375
-
376
- xc = x_resid - np.mean(x_resid)
377
- yc = y_resid - np.mean(y_resid)
378
- cov = np.sum(xc * yc)
379
- var_x = np.sum(xc * xc)
380
-
381
- if var_x < 1e-12:
382
- continue
383
-
384
- b = cov / var_x
385
- y_pred = b * xc
386
- resid = yc - y_pred
387
- sse = np.sum(resid * resid)
388
- df = n - n_groups - 2
389
-
390
- if df > 0 and sse > 0:
391
- se = np.sqrt(sse / df / var_x)
392
- t_stat = b / (se + 1e-12)
393
- p = 2 * stats.t.sf(np.abs(t_stat), df=df)
394
- r2 = cov * cov / (var_x * np.sum(yc * yc) + 1e-12)
395
-
396
- pv[i] = max(p, 1e-300) if np.isfinite(p) else 1.0
397
- bv[i] = b
398
- sv[i] = se
399
- rv[i] = r2
400
-
401
- return pv, bv, sv, rv
402
-
403
- def model_bslmm(G, y, n_boot=8):
404
- """Bayesian Sparse Linear Mixed Model using Elastic Net + Bootstrap."""
405
- n, m = G.shape
406
-
407
- # Standardize genotypes
408
- scaler = StandardScaler()
409
- X_scaled = scaler.fit_transform(G)
410
- X_scaled = np.nan_to_num(X_scaled, nan=0.0)
411
-
412
- # Use Ridge for large m, ElasticNet for smaller
413
- if m > 5000:
414
- alphas = np.logspace(-4, 4, 20)
415
- model = RidgeCV(alphas=alphas, cv=min(5, n//2))
416
- model.fit(X_scaled, y)
417
- coef = model.coef_
418
- else:
419
- model = ElasticNetCV(
420
- cv=min(5, n//2),
421
- random_state=42,
422
- max_iter=2000,
423
- n_jobs=-1,
424
- l1_ratio=[0.1, 0.5, 0.7, 0.9, 1.0]
425
- )
426
- model.fit(X_scaled, y)
427
- coef = model.coef_
428
-
429
- # Bootstrap for standard errors and p-values
430
- boots = []
431
- rng = np.random.default_rng(42)
432
-
433
- for _ in range(n_boot):
434
- idx = rng.choice(n, n, replace=True)
435
- try:
436
- if m > 5000:
437
- boot_model = RidgeCV(alphas=alphas, cv=min(3, n//2))
438
- else:
439
- boot_model = ElasticNetCV(
440
- cv=min(3, n//2),
441
- random_state=42,
442
- max_iter=1000,
443
- l1_ratio=[0.1, 0.5, 0.9, 1.0]
444
- )
445
- boot_model.fit(X_scaled[idx], y[idx])
446
- boots.append(boot_model.coef_)
447
- except:
448
- boots.append(coef.copy())
449
-
450
- boot_arr = np.array(boots)
451
- pv = np.ones(m)
452
- se = np.zeros(m)
453
-
454
- for i in range(m):
455
- boot_se = np.std(boot_arr[:, i])
456
- if boot_se > 0:
457
- se[i] = boot_se
458
- z = np.abs(coef[i]) / (boot_se + 1e-12)
459
- pv[i] = max(2 * (1 - stats.norm.cdf(z)), 1e-300)
460
-
461
- return pv, coef, se
462
-
463
- def model_farmcpu(G, y, K, max_iter=3):
464
- """FarmCPU: Fixed and Random model Circulating Probability Unification."""
465
- n, m = G.shape
466
- n_pc = min(5, n - 2)
467
-
468
- # Get PCs from kinship
469
- eigvals, eigvecs = np.linalg.eigh(K)
470
- idx = np.argsort(eigvals)[::-1]
471
- PCs = eigvecs[:, idx[:n_pc]]
472
-
473
- # Initial GLM
474
- pv, bv, sv, rv = model_glm(G, y)
475
-
476
- for iteration in range(max_iter):
477
- # Select top markers as pseudo-QTNs
478
- n_qtns = max(2, min(20, int(m * 0.002)))
479
- top_idx = np.argsort(pv)[:n_qtns]
480
-
481
- # Build covariate matrix with PCs and selected markers
482
- covariates = [PCs]
483
- for idx_qtn in top_idx:
484
- x = G[:, idx_qtn]
485
- nan_mask = np.isnan(x)
486
- if nan_mask.any():
487
- x = x.copy()
488
- x[nan_mask] = np.nanmean(x)
489
- covariates.append(x.reshape(-1, 1))
490
-
491
- X_cov = np.hstack(covariates)
492
-
493
- # Fit full model
494
- try:
495
- beta = np.linalg.lstsq(X_cov, y, rcond=None)[0]
496
- y_resid = y - X_cov @ beta
497
- except:
498
- y_resid = y.copy()
499
-
500
- # Re-compute p-values conditioned on pseudo-QTNs
501
- df = max(n - X_cov.shape[1] - 1, 1)
502
-
503
- for i in range(m):
504
- if i in top_idx:
505
- continue
506
-
507
- x = G[:, i]
508
- nan_mask = np.isnan(x)
509
- if nan_mask.any():
510
- x = x.copy()
511
- x[nan_mask] = np.nanmean(x)
512
-
513
- if np.std(x) < 1e-9:
514
- continue
515
-
516
- xc = x - np.mean(x)
517
- yc = y_resid - np.mean(y_resid)
518
- cov = np.sum(xc * yc)
519
- var_x = np.sum(xc * xc)
520
-
521
- if var_x < 1e-12:
522
- continue
523
-
524
- b = cov / var_x
525
- y_pred = b * xc
526
- sse = np.sum((yc - y_pred) ** 2)
527
-
528
- if sse > 0 and df > 0:
529
- se_b = np.sqrt(sse / df / var_x)
530
- t_stat = b / (se_b + 1e-12)
531
- p = 2 * stats.t.sf(np.abs(t_stat), df=df)
532
- pv[i] = max(p, 1e-300) if np.isfinite(p) else 1.0
533
- bv[i] = b
534
- sv[i] = se_b
535
-
536
- return pv, bv, sv
537
 
538
- # ══════════════════════════════════════════════════════════════
539
- # LD DECAY - Proper Hill-Weir (1988) Model
540
- # ══════════════════════════════════════════════════════════════
541
 
542
- def hill_weir_model(d, Ne, c=1.0):
543
- """
544
- Hill-Weir (1988) model for LD decay:
545
- E(rΒ²) = 1 / (1 + 4 * Ne * c * d)
546
- where d is distance in Morgans, Ne is effective population size
547
- """
548
- return 1.0 / (1.0 + 4 * Ne * c * d)
549
-
550
- def compute_r2_pair(x, y):
551
- """Compute rΒ² between two genotype vectors."""
552
- mask = ~(np.isnan(x) | np.isnan(y))
553
- if mask.sum() < 10:
554
- return 0.0
555
- x_clean = x[mask]
556
- y_clean = y[mask]
557
-
558
- corr = np.corrcoef(x_clean, y_clean)[0, 1]
559
- if np.isnan(corr):
560
- return 0.0
561
- return corr ** 2
562
-
563
- def compute_ld_decay_sweep(genotypes, positions, max_dist_mb=10):
564
- """Compute LD decay across all chromosomes as a single sweep."""
565
- all_dist = []
566
- all_r2 = []
567
-
568
- # Convert positions to Mb
569
- pos_mb = np.array(positions, dtype=float) / 1_000_000.0
570
-
571
- # Limit to reasonable number of pairs
572
- n_markers = genotypes.shape[1]
573
- max_pairs = min(50000, n_markers * (n_markers - 1) // 2)
574
- sample_rate = max(1, (n_markers * (n_markers - 1) // 2) // max_pairs)
575
-
576
- # Sample marker pairs
577
- rng = np.random.RandomState(42)
578
- pairs_sampled = 0
579
-
580
- for i in range(0, n_markers, max(1, sample_rate)):
581
- for j in range(i + 1, min(i + sample_rate * 10, n_markers)):
582
- dist = abs(pos_mb[j] - pos_mb[i])
583
- if dist > max_dist_mb:
584
- continue
585
-
586
- r2 = compute_r2_pair(genotypes[:, i], genotypes[:, j])
587
-
588
- all_dist.append(dist)
589
- all_r2.append(r2)
590
- pairs_sampled += 1
591
-
592
- if pairs_sampled >= max_pairs:
593
- break
594
-
595
- if pairs_sampled >= max_pairs:
596
- break
597
-
598
- return np.array(all_dist), np.array(all_r2)
599
-
600
- def plot_ld_decay(genotypes, chromosomes, positions, save_path):
601
- """Plot LD decay with proper Hill-Weir model fitting."""
602
- _style_white()
603
-
604
- # Compute LD sweep
605
- dist, r2 = compute_ld_decay_sweep(genotypes, positions, max_dist_mb=10)
606
-
607
- if len(dist) == 0:
608
- fig, ax = plt.subplots(figsize=(10, 6), facecolor=W_BG)
609
- ax.set_facecolor(W_PANEL)
610
- ax.text(0.5, 0.5, 'No LD pairs computed (need more markers)',
611
- ha='center', va='center', transform=ax.transAxes, fontsize=13)
612
- plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=W_BG)
613
- plt.close(fig)
614
- return {}, "No LD data available"
615
-
616
- # Bin data for fitting
617
- bins = np.linspace(0, min(10, np.percentile(dist, 98)), 50)
618
- bin_centers = []
619
- bin_means = []
620
- bin_stds = []
621
-
622
- for i in range(len(bins) - 1):
623
- mask = (dist >= bins[i]) & (dist < bins[i+1])
624
- if mask.sum() >= 5:
625
- bin_centers.append((bins[i] + bins[i+1]) / 2)
626
- bin_means.append(np.mean(r2[mask]))
627
- bin_stds.append(np.std(r2[mask]))
628
-
629
- bin_centers = np.array(bin_centers)
630
- bin_means = np.array(bin_means)
631
- bin_stds = np.array(bin_stds)
632
-
633
- # Fit Hill-Weir model
634
- fit_ok = False
635
- Ne_fit = 100
636
- r2_start = 0.5
637
- half_decay = 1.0
638
-
639
- if len(bin_centers) >= 5:
640
- try:
641
- def objective(Ne):
642
- pred = hill_weir_model(bin_centers, Ne)
643
- return np.sum(((bin_means - pred) / (bin_stds + 0.01)) ** 2)
644
-
645
- result = minimize_scalar(objective, bounds=(1, 10000), method='bounded')
646
- Ne_fit = result.x
647
- fit_ok = True
648
-
649
- dist_fit = np.linspace(0, min(10, bin_centers[-1]), 200)
650
- r2_fit = hill_weir_model(dist_fit, Ne_fit)
651
-
652
- r2_start = hill_weir_model(0, Ne_fit)
653
- half_idx = np.where(r2_fit <= r2_start / 2)[0]
654
- if len(half_idx) > 0:
655
- half_decay = dist_fit[half_idx[0]]
656
- except:
657
- # Fallback to exponential decay
658
- try:
659
- def exp_decay(d, a, b):
660
- return a * np.exp(-b * d)
661
- popt, _ = curve_fit(exp_decay, bin_centers, bin_means,
662
- p0=[0.5, 1.0], maxfev=5000)
663
- dist_fit = np.linspace(0, bin_centers[-1], 200)
664
- r2_fit = exp_decay(dist_fit, *popt)
665
- r2_start = popt[0]
666
- half_decay = np.log(2) / popt[1] if popt[1] > 0 else 1.0
667
- fit_ok = True
668
- except:
669
- pass
670
-
671
- # Create figure
672
- fig = plt.figure(figsize=(12, 8), facecolor=W_BG)
673
- gs = GridSpec(2, 1, figure=fig, height_ratios=[3, 1], hspace=0.08)
674
-
675
- # Main plot
676
- ax = fig.add_subplot(gs[0])
677
- ax.set_facecolor(W_PANEL)
678
-
679
- # Scatter plot (subsampled for visibility)
680
- sample_rate = max(1, len(dist) // 5000)
681
- ax.scatter(dist[::sample_rate], r2[::sample_rate],
682
- c=W_ACCENT, s=3, alpha=0.3, linewidths=0, zorder=1)
683
-
684
- # Binned means with error bars
685
- if len(bin_centers) > 0:
686
- ax.errorbar(bin_centers, bin_means, yerr=bin_stds,
687
- fmt='o', color=W_RED, capsize=3,
688
- markersize=6, elinewidth=1.5, capthick=1.5,
689
- label='Binned mean Β± SD', zorder=3)
690
-
691
- # Fitted curve
692
- if fit_ok and 'dist_fit' in locals():
693
- ax.plot(dist_fit, r2_fit, color=W_GREEN, lw=2.5,
694
- label=f'Hill-Weir fit (Ne = {Ne_fit:.0f})', zorder=4)
695
-
696
- # Mark half-decay
697
- ax.axvline(half_decay, color=W_ORANGE, ls='--', lw=1.5, alpha=0.8)
698
- ax.axhline(r2_start / 2, color=W_ORANGE, ls='--', lw=1.5, alpha=0.8)
699
- ax.text(half_decay + 0.05, r2_start / 2 + 0.02,
700
- f'Half-decay: {half_decay:.2f} Mb',
701
- fontsize=9, color=W_ORANGE, fontweight='bold')
702
-
703
- # Reference lines
704
- ax.axhline(0.2, color=W_GOLD, ls=':', lw=1.2, alpha=0.7, label='rΒ² = 0.2')
705
- ax.axhline(0.1, color=W_PURPLE, ls=':', lw=1.2, alpha=0.7, label='rΒ² = 0.1')
706
-
707
- ax.set_xlim(0, min(10, np.percentile(dist, 98) * 1.05))
708
- ax.set_ylim(-0.02, 1.02)
709
- ax.set_xlabel('Distance (Mb)', fontweight='bold', fontsize=12)
710
- ax.set_ylabel('Linkage Disequilibrium (rΒ²)', fontweight='bold', fontsize=12)
711
- ax.set_title('Linkage Disequilibrium Decay Analysis',
712
- fontweight='bold', fontsize=14, color=W_ACCENT)
713
- ax.legend(loc='upper right', fontsize=9)
714
- ax.grid(True, color=W_GRID, lw=0.5, alpha=0.7)
715
-
716
- # Interpretation panel
717
- ax_text = fig.add_subplot(gs[1])
718
- ax_text.axis('off')
719
- ax_text.set_facecolor(W_BG)
720
-
721
- n_pairs = len(dist)
722
- mean_r2 = np.mean(r2)
723
- r2_lt_02 = np.mean(r2 < 0.2) * 100
724
-
725
- if fit_ok:
726
- interp_text = f"""
727
- LD DECAY INTERPRETATION
728
- ─────────────────────────────────────────────────────────────
729
- β€’ Model: Hill-Weir (1988) E(rΒ²) = 1/(1 + 4Β·Nβ‚‘Β·cΒ·d)
730
- β€’ Estimated effective population size (Nβ‚‘): {Ne_fit:.0f}
731
- β€’ Half-decay distance (rΒ² = {r2_start/2:.3f}): {half_decay:.3f} Mb
732
- β€’ Mean rΒ² across all pairs: {mean_r2:.4f}
733
- β€’ Pairs with rΒ² < 0.2: {r2_lt_02:.1f}%
734
- β€’ Total pairs analysed: {n_pairs:,}
735
-
736
- Interpretation:
737
- - LD decays {'rapidly' if half_decay < 0.5 else 'moderately' if half_decay < 2 else 'slowly'}
738
- - {'Low' if r2_lt_02 > 70 else 'Moderate' if r2_lt_02 > 50 else 'High'} genome-wide LD
739
- """
740
- else:
741
- interp_text = f"""
742
- LD DECAY SUMMARY
743
- ─────────────────────────────────────────────────────────────
744
- β€’ Mean rΒ² across all pairs: {mean_r2:.4f}
745
- β€’ Pairs with rΒ² < 0.2: {r2_lt_02:.1f}%
746
- β€’ Total pairs analysed: {n_pairs:,}
747
-
748
- Note: Model fitting failed - insufficient data or poor convergence.
749
- """
750
-
751
- ax_text.text(0.02, 0.95, interp_text, transform=ax_text.transAxes,
752
- fontsize=9, fontfamily='monospace', va='top',
753
- bbox=dict(boxstyle='round,pad=0.5', facecolor=W_PANEL,
754
- edgecolor=W_BORDER, alpha=0.95))
755
-
756
- plt.tight_layout()
757
- plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=W_BG)
758
  plt.close(fig)
759
-
760
- stats_dict = {
761
- 'n_pairs': n_pairs,
762
- 'mean_r2': mean_r2,
763
- 'r2_lt_02_pct': r2_lt_02,
764
- 'half_decay_mb': half_decay if fit_ok else None,
765
- 'estimated_Ne': Ne_fit if fit_ok else None
766
- }
767
-
768
- return stats_dict, interp_text
769
 
770
  # ══════════════════════════════════════════════════════════════
771
- # MANHATTAN PLOT with proper X-axis positioning
772
  # ══════════════════════════════════════════════════════════════
773
 
774
- def build_x_positions(markers, chromosomes):
775
- """Build x-axis positions for Manhattan plot."""
776
- unique_chroms = sorted(set(chromosomes),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
777
  key=lambda x: (int(x) if str(x).isdigit() else 999, str(x)))
778
-
779
- chrom_to_idx = {}
780
- for i, c in enumerate(chromosomes):
781
- chrom_to_idx.setdefault(c, []).append(i)
782
-
783
- GAP = max(8, len(markers) // 150)
784
- x_pos = np.zeros(len(markers))
785
- chrom_ticks = []
786
- offset = 0
787
-
788
  for ch in unique_chroms:
789
- idxs = chrom_to_idx.get(ch, [])
790
- if not idxs:
791
  continue
792
- for pos, idx in enumerate(idxs):
793
- x_pos[idx] = offset + pos
794
- chrom_ticks.append((offset + len(idxs) / 2, str(ch)))
795
- offset += len(idxs) + GAP
796
-
797
- return x_pos, chrom_ticks, offset, GAP, unique_chroms, chrom_to_idx
798
-
799
- def plot_manhattan_single(markers, chromosomes, pv, model_name, bonf_thresh, lod_thresh_user, save_path):
800
- """Plot Manhattan with both -log10(P) and LOD panels."""
801
- _style_white()
802
-
803
- LOD_FACTOR = np.log10(np.e) / 2.0
804
- x_pos, chrom_ticks, offset, GAP, unique_chroms, chrom_to_idx = build_x_positions(markers, chromosomes)
805
-
806
- bonf_log = -np.log10(bonf_thresh)
807
- bonf_lod = bonf_log * LOD_FACTOR
808
- sug_log = 3.0
809
- sug_lod = sug_log * LOD_FACTOR
810
-
811
- log_p = -np.log10(np.clip(pv, 1e-300, 1))
812
- lod = log_p * LOD_FACTOR
813
- sig_mask = pv < bonf_thresh
814
-
815
- fig, axes = plt.subplots(2, 1, figsize=(18, 10), facecolor=W_BG,
816
- sharex=True, gridspec_kw={'height_ratios': [1, 1], 'hspace': 0.08})
817
-
818
- fig.suptitle(f'GWAS Manhattan Plot β€” {model_name}',
819
- fontsize=15, fontweight='bold', color=W_TEXT, y=1.01)
820
-
821
- for ax_idx, (ax, values, ylabel, bonf_line, sug_line, user_line) in enumerate([
822
- (axes[0], log_p, '-log₁₀(P)', bonf_log, sug_log, bonf_log),
823
- (axes[1], lod, 'LOD Score', bonf_lod, sug_lod, lod_thresh_user),
824
- ]):
825
- ax.set_facecolor(W_PANEL)
826
-
827
- for ci, ch in enumerate(unique_chroms):
828
- idxs = chrom_to_idx.get(ch, [])
829
- if not idxs:
830
- continue
831
-
832
- color = CHROM_COLORS[ci % len(CHROM_COLORS)]
833
-
834
- if ci % 2 == 0:
835
- ax.axvspan(x_pos[idxs[0]] - 0.5, x_pos[idxs[-1]] + 0.5,
836
- color='#F0F4F8', alpha=0.7, zorder=0)
837
-
838
- nsig_mask = [i for i in idxs if not sig_mask[i]]
839
- if nsig_mask:
840
- ax.scatter(x_pos[nsig_mask], values[nsig_mask],
841
- c=color, s=6, alpha=0.55, linewidths=0, zorder=2)
842
-
843
- sig_idxs = [i for i in idxs if sig_mask[i]]
844
- if sig_idxs:
845
- ax.scatter(x_pos[sig_idxs], values[sig_idxs],
846
- c=W_RED, s=40, alpha=1.0, marker='D',
847
- edgecolors='white', linewidths=0.5, zorder=4)
848
-
849
- ax.axhline(bonf_line, color=W_RED, ls='--', lw=1.8, alpha=0.9,
850
- label=f'Bonferroni ({bonf_line:.2f})', zorder=5)
851
- ax.axhline(sug_line, color=W_GOLD, ls=':', lw=1.5, alpha=0.85,
852
- label=f'Suggestive ({sug_line:.2f})', zorder=5)
853
-
854
- if ax_idx == 1 and abs(user_line - bonf_lod) > 0.05:
855
- ax.axhline(user_line, color=W_ORANGE, ls='-.', lw=1.8, alpha=0.9,
856
- label=f'User LOD ({user_line:.1f})', zorder=5)
857
-
858
- y_max = max(values.max() * 1.1, bonf_line * 1.2, 1.0)
859
- ax.set_ylim(0, y_max)
860
- ax.set_ylabel(ylabel, fontweight='bold', fontsize=12)
861
- ax.grid(True, color=W_GRID, lw=0.5, alpha=0.6, axis='y')
862
- ax.legend(loc='upper right', fontsize=8, ncol=3)
863
-
864
- n_sig = sig_mask.sum()
865
- ax.text(0.01, 0.96, f'{n_sig} significant SNPs',
866
- transform=ax.transAxes, fontsize=9, color=W_RED, fontweight='bold',
867
- bbox=dict(boxstyle='round,pad=0.3', fc='#FFF5F5', ec=W_RED, alpha=0.9))
868
-
869
- axes[1].set_xticks([x for x, _ in chrom_ticks])
870
- axes[1].set_xticklabels([l for _, l in chrom_ticks], fontsize=8, fontweight='bold')
871
- axes[1].set_xlabel('Chromosome', fontweight='bold', fontsize=12)
872
- axes[1].set_xlim(-GAP, offset)
873
-
874
- mcol = MODEL_COLORS.get(model_name, W_ACCENT)
875
- fig.text(0.01, 0.98, f'● {model_name}', color=mcol, fontsize=11, fontweight='bold', va='top')
876
-
877
- plt.tight_layout(pad=1.0)
878
- plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=W_BG)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
879
  plt.close(fig)
880
 
 
 
 
881
  # ══════════════════════════════════════════════════════════════
882
- # QQ PLOT
883
  # ══════════════════════════════════════════════════════════════
884
 
885
- def plot_qq_single(pv, model_name, bonf_thresh, save_path):
886
- """QQ plot with inflation factor."""
887
- _style_white()
888
-
889
- pv = pv[np.isfinite(pv) & (pv > 0) & (pv <= 1)]
890
-
891
- fig, ax = plt.subplots(figsize=(8, 8), facecolor=W_BG)
892
- ax.set_facecolor(W_PANEL)
893
-
894
- if len(pv) == 0:
895
- ax.text(0.5, 0.5, 'No valid p-values', ha='center', va='center', fontsize=14)
896
- plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=W_BG)
897
- plt.close(fig)
898
- return 1.0
899
-
900
- n = len(pv)
901
- obs = -np.log10(np.sort(pv))
902
- exp = -np.log10((np.arange(1, n + 1) - 0.5) / n)
903
-
904
- # 95% confidence interval
905
- ci_lo = -np.log10(stats.beta.ppf(0.025, np.arange(1, n + 1), n - np.arange(1, n + 1) + 1))
906
- ci_hi = -np.log10(stats.beta.ppf(0.975, np.arange(1, n + 1), n - np.arange(1, n + 1) + 1))
907
-
908
- ax.fill_between(exp, ci_lo, ci_hi, color=MODEL_COLORS.get(model_name, W_ACCENT),
909
- alpha=0.15, label='95% CI')
910
-
911
- bonf_line = -np.log10(bonf_thresh)
912
- above_bonf = obs > bonf_line
913
-
914
- if (~above_bonf).any():
915
- ax.scatter(exp[~above_bonf], obs[~above_bonf],
916
- c=MODEL_COLORS.get(model_name, W_ACCENT), s=15, alpha=0.6, linewidths=0)
917
- if above_bonf.any():
918
- ax.scatter(exp[above_bonf], obs[above_bonf],
919
- c=W_RED, s=25, alpha=0.9, marker='D', edgecolors='white', linewidths=0.5)
920
-
921
- max_val = max(obs.max(), exp.max()) * 1.05
922
- ax.plot([0, max_val], [0, max_val], color=W_TEXT, ls='--', lw=1.5, alpha=0.8, label='y = x')
923
-
924
- # Genomic inflation factor Ξ»
925
- chi2 = stats.chi2.ppf(1 - pv, df=1)
926
- chi2_median = np.median(chi2)
927
- lam = chi2_median / stats.chi2.ppf(0.5, df=1)
928
-
929
- lam_color = W_RED if lam > 1.1 else W_ORANGE if lam > 1.05 else W_GREEN
930
- ax.text(0.05, 0.95, f'Ξ» = {lam:.4f}', transform=ax.transAxes,
931
- fontsize=16, fontweight='bold', color=lam_color, va='top',
932
- bbox=dict(boxstyle='round,pad=0.4', fc=W_BG, ec=lam_color, alpha=0.9))
933
-
934
- ax.set_xlim(0, max_val)
935
- ax.set_ylim(0, max_val)
936
- ax.set_xlabel('Expected -log₁₀(P)', fontweight='bold', fontsize=12)
937
- ax.set_ylabel('Observed -log₁₀(P)', fontweight='bold', fontsize=12)
938
- ax.set_title(f'QQ Plot β€” {model_name}', fontweight='bold', fontsize=13)
939
- ax.legend(fontsize=9)
940
- ax.grid(True, color=W_GRID, lw=0.5, alpha=0.6)
941
-
942
- plt.tight_layout()
943
- plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=W_BG)
 
 
 
 
 
 
 
 
944
  plt.close(fig)
945
-
946
- return lam
947
 
948
  # ══════════════════════════════════════════════════════════════
949
- # OTHER PLOTS (Phenotype, PCA, Kinship, MAF, Volcano, Comparison)
950
  # ══════════════════════════════════════════════════════════════
951
 
952
- def plot_phenotype(phenotypes, save_path):
953
- """Plot phenotype distribution and QQ normality plot."""
954
- _style_white()
955
- pv = phenotypes[~np.isnan(phenotypes)]
956
- fig, axes = plt.subplots(1, 2, figsize=(13, 5), facecolor=W_BG)
957
- fig.suptitle('Phenotype Distribution & Normality', fontsize=14, fontweight='bold')
958
-
959
- ax = axes[0]
960
- ax.set_facecolor(W_PANEL)
961
- ax.hist(pv, bins=min(50, len(pv)//10), color=W_ACCENT, alpha=0.7, edgecolor='white')
962
- ax.axvline(np.mean(pv), color=W_RED, ls='--', lw=2, label=f'Mean = {np.mean(pv):.3f}')
963
- ax.axvline(np.median(pv), color=W_GOLD, ls=':', lw=2, label=f'Median = {np.median(pv):.3f}')
964
- ax.set_xlabel('Phenotype')
965
- ax.set_ylabel('Frequency')
966
- ax.set_title('Histogram')
967
- ax.legend()
968
- ax.grid(True, alpha=0.3)
969
-
970
- ax = axes[1]
971
- ax.set_facecolor(W_PANEL)
972
- stats.probplot(pv, dist='norm', plot=ax)
973
- ax.set_title('Normal Q-Q')
974
- ax.grid(True, alpha=0.3)
975
-
976
- plt.tight_layout()
977
- plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=W_BG)
978
- plt.close(fig)
979
 
980
- def plot_pca(genotypes, phenotypes, n_components, save_path):
981
- """Plot PCA analysis: scree plot and PC scatter plots."""
982
- _style_white()
983
- G = np.nan_to_num(genotypes - np.nanmean(genotypes, 0), 0)
984
- n_comp = min(n_components, G.shape[0]-1, G.shape[1])
985
-
986
- pca = PCA(n_components=n_comp)
987
- scores = pca.fit_transform(G)
988
- evr = pca.explained_variance_ratio_ * 100
989
-
990
- fig = plt.figure(figsize=(15, 5), facecolor=W_BG)
991
- gs = GridSpec(1, 3, figure=fig, wspace=0.3)
992
-
993
- # Scree plot
994
- ax = fig.add_subplot(gs[0])
995
- ax.set_facecolor(W_PANEL)
996
- bars = ax.bar(range(1, n_comp+1), evr, color=W_ACCENT, alpha=0.7)
997
- ax.plot(range(1, n_comp+1), np.cumsum(evr), 'o-', color=W_RED, lw=2, label='Cumulative')
998
- ax.set_xlabel('PC')
999
- ax.set_ylabel('Variance (%)')
1000
- ax.set_title('Scree Plot')
1001
- ax.legend()
1002
- ax.grid(True, alpha=0.3)
1003
-
1004
- # PC1 vs PC2
1005
- ax = fig.add_subplot(gs[1])
1006
- ax.set_facecolor(W_PANEL)
1007
- sc = ax.scatter(scores[:, 0], scores[:, 1], c=phenotypes, cmap='RdYlBu_r',
1008
- s=30, alpha=0.7, edgecolors='white', lw=0.5)
1009
- ax.set_xlabel(f'PC1 ({evr[0]:.1f}%)')
1010
- ax.set_ylabel(f'PC2 ({evr[1]:.1f}%)')
1011
- ax.set_title('PC1 vs PC2')
1012
- ax.grid(True, alpha=0.3)
1013
- plt.colorbar(sc, ax=ax, label='Phenotype')
1014
-
1015
- # PC2 vs PC3
1016
- ax = fig.add_subplot(gs[2])
1017
- ax.set_facecolor(W_PANEL)
1018
- if n_comp >= 3:
1019
- sc = ax.scatter(scores[:, 1], scores[:, 2], c=phenotypes, cmap='RdYlBu_r',
1020
- s=30, alpha=0.7, edgecolors='white', lw=0.5)
1021
- ax.set_xlabel(f'PC2 ({evr[1]:.1f}%)')
1022
- ax.set_ylabel(f'PC3 ({evr[2]:.1f}%)')
1023
- ax.set_title('PC2 vs PC3')
1024
- ax.grid(True, alpha=0.3)
1025
- plt.colorbar(sc, ax=ax, label='Phenotype')
 
 
 
 
 
 
 
 
 
 
 
1026
  else:
1027
- ax.text(0.5, 0.5, f'Need β‰₯3 PCs\n(selected {n_comp})', ha='center', va='center')
1028
-
1029
- plt.tight_layout()
1030
- plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=W_BG)
1031
- plt.close(fig)
1032
-
1033
- return evr, np.cumsum(evr), scores
1034
-
1035
- def plot_kinship_heatmap(K, save_path, max_n=200):
1036
- """Plot kinship matrix heatmap."""
1037
- _style_white()
1038
- n = K.shape[0]
1039
- if n > max_n:
1040
- idx = np.random.choice(n, max_n, replace=False)
1041
- idx.sort()
1042
- K = K[np.ix_(idx, idx)]
1043
-
1044
- fig, ax = plt.subplots(figsize=(8, 7), facecolor=W_BG)
1045
- cmap = LinearSegmentedColormap.from_list('kinship', ['white', '#C6DBEF', '#4292C6', '#08306B'])
1046
- im = ax.imshow(K, cmap=cmap, vmin=0, vmax=1)
1047
- plt.colorbar(im, ax=ax, label='Kinship coefficient')
1048
- ax.set_title('Kinship Matrix', fontweight='bold')
1049
- ax.set_xlabel('Sample')
1050
- ax.set_ylabel('Sample')
1051
- plt.tight_layout()
1052
- plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=W_BG)
1053
- plt.close(fig)
1054
 
1055
- def plot_maf_distribution(maf_arr, save_path):
1056
- """Plot minor allele frequency distribution."""
1057
- _style_white()
1058
- maf = maf_arr[maf_arr > 0]
1059
- fig, axes = plt.subplots(1, 2, figsize=(12, 5), facecolor=W_BG)
1060
- fig.suptitle('Minor Allele Frequency Distribution', fontweight='bold')
1061
-
1062
- ax = axes[0]
1063
- ax.set_facecolor(W_PANEL)
1064
- ax.hist(maf, bins=40, color=W_ACCENT, alpha=0.7, edgecolor='white')
1065
- ax.axvline(0.05, color=W_RED, ls='--', lw=2, label='MAF=0.05')
1066
- ax.set_xlabel('MAF')
1067
- ax.set_ylabel('Count')
1068
- ax.legend()
1069
- ax.grid(True, alpha=0.3)
1070
-
1071
- ax = axes[1]
1072
- ax.set_facecolor(W_PANEL)
1073
- x = np.sort(maf)
1074
- y = np.arange(1, len(x)+1) / len(x)
1075
- ax.plot(x, y, color=W_ACCENT, lw=2)
1076
- ax.fill_between(x, 0, y, color=W_ACCENT, alpha=0.15)
1077
- ax.axvline(0.05, color=W_RED, ls='--', lw=2)
1078
- ax.set_xlabel('MAF')
1079
- ax.set_ylabel('Cumulative proportion')
1080
- ax.set_title('Cumulative distribution')
1081
- ax.grid(True, alpha=0.3)
1082
-
1083
- plt.tight_layout()
1084
- plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=W_BG)
1085
- plt.close(fig)
1086
 
1087
- def plot_volcano(pv, beta, model_name, bonf_thresh, save_path):
1088
- """Plot volcano plot (effect size vs -log10 p-value)."""
1089
- _style_white()
1090
- log_p = -np.log10(np.clip(pv, 1e-300, 1))
1091
- bonf_log = -np.log10(bonf_thresh)
1092
-
1093
- fig, ax = plt.subplots(figsize=(9, 7), facecolor=W_BG)
1094
- ax.set_facecolor(W_PANEL)
1095
-
1096
- sig = log_p >= bonf_log
1097
- nsig = ~sig
1098
-
1099
- if nsig.any():
1100
- ax.scatter(beta[nsig], log_p[nsig], c=W_SUBTEXT, s=10, alpha=0.4, linewidths=0)
1101
-
1102
- pos_sig = sig & (beta > 0)
1103
- neg_sig = sig & (beta < 0)
1104
-
1105
- if pos_sig.any():
1106
- ax.scatter(beta[pos_sig], log_p[pos_sig], c=W_RED, s=45, marker='D',
1107
- alpha=0.9, edgecolors='white', linewidths=0.5, label='Positive effect')
1108
- if neg_sig.any():
1109
- ax.scatter(beta[neg_sig], log_p[neg_sig], c=W_ACCENT, s=45, marker='D',
1110
- alpha=0.9, edgecolors='white', linewidths=0.5, label='Negative effect')
1111
-
1112
- ax.axhline(bonf_log, color=W_RED, ls='--', lw=1.5, label=f'Bonferroni ({bonf_log:.2f})')
1113
- ax.axvline(0, color=W_BORDER, ls=':', lw=1)
1114
- ax.set_xlabel('Effect size (Ξ²)', fontweight='bold')
1115
- ax.set_ylabel('-log₁₀(P)', fontweight='bold')
1116
- ax.set_title(f'Volcano Plot β€” {model_name}', fontweight='bold')
1117
- ax.legend()
1118
- ax.grid(True, alpha=0.3)
1119
-
1120
- plt.tight_layout()
1121
- plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=W_BG)
1122
- plt.close(fig)
1123
 
1124
- def plot_model_comparison(model_pvals, save_path):
1125
- """Plot pairwise model p-value comparisons."""
1126
- _style_white()
1127
- models = list(model_pvals.keys())
1128
- n = len(models)
1129
- if n < 2:
1130
- return
1131
-
1132
- n_pairs = n * (n - 1) // 2
1133
- n_cols = min(3, n_pairs)
1134
- n_rows = (n_pairs + n_cols - 1) // n_cols
1135
-
1136
- fig, axes = plt.subplots(n_rows, n_cols, figsize=(5*n_cols, 5*n_rows), facecolor=W_BG)
1137
- if n_rows == 1 and n_cols == 1:
1138
- axes = np.array([[axes]])
1139
- axes = axes.flatten()
1140
-
1141
- pair_idx = 0
1142
- for i in range(n):
1143
- for j in range(i+1, n):
1144
- ax = axes[pair_idx]
1145
- ax.set_facecolor(W_PANEL)
1146
-
1147
- p1 = -np.log10(np.clip(model_pvals[models[i]], 1e-300, 1))
1148
- p2 = -np.log10(np.clip(model_pvals[models[j]], 1e-300, 1))
1149
- corr = np.corrcoef(p1, p2)[0, 1]
1150
-
1151
- ax.scatter(p1, p2, alpha=0.4, s=8, c=MODEL_COLORS.get(models[i], W_ACCENT))
1152
- max_val = max(p1.max(), p2.max()) * 1.05
1153
- ax.plot([0, max_val], [0, max_val], '--', color=W_GOLD, lw=1.5, alpha=0.7)
1154
- ax.set_xlabel(f'{models[i]} -log₁₀(P)')
1155
- ax.set_ylabel(f'{models[j]} -log₁₀(P)')
1156
- ax.set_title(f'{models[i]} vs {models[j]}', fontsize=10)
1157
- ax.text(0.05, 0.95, f'r = {corr:.3f}', transform=ax.transAxes,
1158
- fontsize=11, fontweight='bold', color=W_RED, va='top')
1159
- ax.grid(True, alpha=0.3)
1160
- pair_idx += 1
1161
-
1162
- for k in range(pair_idx, len(axes)):
1163
- axes[k].set_visible(False)
1164
-
1165
- plt.tight_layout()
1166
- plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=W_BG)
1167
- plt.close(fig)
1168
 
1169
- def plot_circos(markers, chromosomes, positions, model_pvals, bonf_thresh, lod_thresh_user, save_path):
1170
- """Simplified Circos plot for multi-model comparison."""
1171
- _style_white()
1172
-
1173
- fig, ax = plt.subplots(figsize=(12, 12), facecolor=W_BG)
1174
-
1175
- # Simplified circos representation
1176
- n_models = len(model_pvals)
1177
-
1178
- # Polar plot
1179
- ax = fig.add_subplot(111, projection='polar')
1180
- ax.set_facecolor(W_BG)
1181
- ax.set_title('Multi-Model GWAS Circos', fontweight='bold', pad=20)
1182
-
1183
- # Center text
1184
- ax.text(0, 0, f'{n_models} Models\nAnalyzed', ha='center', va='center',
1185
- fontsize=14, fontweight='bold')
1186
-
1187
- # Add chromosome arcs
1188
- unique_chroms = sorted(set(chromosomes))
1189
- n_chr = len(unique_chroms)
1190
- theta = np.linspace(0, 2*np.pi, n_chr + 1)
1191
-
1192
- for i, ch in enumerate(unique_chroms[:min(20, n_chr)]):
1193
- ax.plot([theta[i], theta[i+1]], [0.8, 0.8], color=CHROM_COLORS[i % len(CHROM_COLORS)],
1194
- lw=8, alpha=0.7, solid_capstyle='round')
1195
- ax.text((theta[i] + theta[i+1])/2, 0.92, str(ch), ha='center', fontsize=8)
1196
-
1197
- # Add model rings
1198
- ring_radii = np.linspace(0.65, 0.3, n_models)
1199
- for mi, (mname, pv) in enumerate(model_pvals.items()):
1200
- if mi >= len(ring_radii):
1201
- break
1202
- r = ring_radii[mi]
1203
- color = MODEL_COLORS.get(mname, W_ACCENT)
1204
-
1205
- # Simple ring representation
1206
- theta_ring = np.linspace(0, 2*np.pi, 100)
1207
- ax.plot(theta_ring, [r] * 100, color=color, lw=2, alpha=0.5, label=mname)
1208
-
1209
- # Add label
1210
- ax.text(np.pi/2, r + 0.03, mname, ha='center', fontsize=7, color=color)
1211
-
1212
- ax.set_ylim(0, 1)
1213
- ax.set_xticks([])
1214
- ax.set_yticks([])
1215
- ax.legend(loc='center', bbox_to_anchor=(0.5, -0.05), ncol=n_models)
1216
-
1217
- plt.tight_layout()
1218
- plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=W_BG)
1219
- plt.close(fig)
1220
 
1221
  # ══════════════════════════════════════════════════════════════
1222
- # MAIN ANALYSIS FUNCTION
1223
  # ═══════════════��══════════════════════════════════════════════
1224
 
1225
- def run_analysis(input_file, miss_sample, miss_marker, maf_thresh,
1226
- lod_thresh_user, n_pc_user,
1227
- run_glm, run_mlm, run_cmlm, run_bslmm, run_farmcpu,
1228
- progress=gr.Progress(track_tqdm=True)):
1229
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1230
  try:
1231
  if input_file is None:
1232
- return ("⚠️ Please upload a CSV file first.",
1233
- None, None, None, None, None, None, None, None, None,
1234
- gr.update(choices=[]), gr.update(choices=[]), {}, {})
1235
-
1236
- run_id = pd.Timestamp.now().strftime("%Y%m%d_%H%M%S")
1237
- rdir = OUTPUT_DIR / run_id
1238
- pdir = rdir / 'plots'
1239
- for d in [rdir, pdir]:
1240
- d.mkdir(parents=True, exist_ok=True)
1241
-
1242
- ms_t = miss_sample / 100
1243
- mm_t = miss_marker / 100
1244
- mf_t = maf_thresh / 100
1245
-
1246
- # Parse CSV
1247
- progress(0.03, desc="Parsing CSV...")
1248
- sids, pheno, geno, mnames, chroms, positions = parse_input_csv(input_file)
1249
- n_s, n_m = len(sids), len(mnames)
1250
-
1251
  # QC
1252
- progress(0.08, desc="Quality control...")
1253
- miss_m_rate = np.isnan(geno).sum(0) / n_s
1254
- miss_s_rate = np.isnan(geno).sum(1) / n_m
1255
-
1256
- maf = np.zeros(n_m)
1257
- for i in range(n_m):
1258
- v = geno[:, i]
1259
  v = v[~np.isnan(v)]
1260
- if len(v) > 0:
1261
- f = np.mean(v) / 2
1262
  maf[i] = min(f, 1 - f)
1263
-
1264
- # Apply QC filters
1265
- qc_m = (miss_m_rate < mm_t) & (maf >= mf_t)
1266
- qc_s = miss_s_rate < ms_t
1267
-
1268
- # Fallback if too few samples
1269
- if qc_s.sum() < 10:
1270
- for rs, rm in [(0.6, 0.6), (0.7, 0.7), (0.8, 0.8), (0.9, 0.9), (1.0, 1.0)]:
1271
- qm = (miss_m_rate < rm) & (maf >= mf_t)
1272
- qs = miss_s_rate < rs
1273
- if qs.sum() >= 10:
1274
- qc_m, qc_s = qm, qs
1275
- break
1276
-
1277
- if qc_s.sum() < 10:
1278
- return (f"⚠️ Only {qc_s.sum()} samples passed QC (need β‰₯10)",
1279
- None, None, None, None, None, None, None, None, None,
1280
- gr.update(choices=[]), gr.update(choices=[]), {}, {})
1281
-
1282
- # Apply filters
1283
- geno_q = geno[np.ix_(qc_s, qc_m)]
1284
- pheno_q = pheno[qc_s]
1285
- mn_q = [mnames[i] for i in range(n_m) if qc_m[i]]
1286
- ch_q = [chroms[i] for i in range(n_m) if qc_m[i]]
1287
- pos_q = [positions[i] for i in range(n_m) if qc_m[i]]
1288
- maf_q = maf[qc_m]
1289
-
1290
- # Remove phenotype NaNs
1291
- valid = ~np.isnan(pheno_q)
1292
- geno_q = geno_q[valid]
1293
- pheno_q = pheno_q[valid]
1294
-
1295
- # Impute missing genotypes with column mean
1296
- col_mean = np.nanmean(geno_q, axis=0)
1297
- for i in range(geno_q.shape[1]):
1298
- nan_mask = np.isnan(geno_q[:, i])
1299
- if nan_mask.any():
1300
- geno_q[nan_mask, i] = col_mean[i]
1301
-
1302
- n_q = len(mn_q)
1303
- bonf = 0.05 / n_q
1304
-
1305
- # Compute kinship
1306
- progress(0.15, desc="Computing kinship matrix...")
1307
- K = compute_kinship(geno_q)
1308
-
1309
- # Run models
1310
- progress(0.20, desc="Running GWAS models...")
1311
- model_pvals = {}
1312
- model_betas = {}
1313
- model_ses = {}
1314
-
1315
- step = 0.6 / max(sum([run_glm, run_mlm, run_cmlm, run_bslmm, run_farmcpu]), 1)
1316
- current_progress = 0.20
1317
-
1318
- if run_glm:
1319
- progress(current_progress, desc="GLM...")
1320
- pv, bv, sv, _ = model_glm(geno_q, pheno_q)
1321
- model_pvals['GLM'] = pv
1322
- model_betas['GLM'] = bv
1323
- model_ses['GLM'] = sv
1324
- current_progress += step
1325
-
1326
- if run_mlm:
1327
- progress(current_progress, desc="MLM...")
1328
- pv, bv, sv, _ = model_mlm(geno_q, pheno_q, K, n_pc_user)
1329
- model_pvals['MLM'] = pv
1330
- model_betas['MLM'] = bv
1331
- model_ses['MLM'] = sv
1332
- current_progress += step
1333
-
1334
- if run_cmlm:
1335
- progress(current_progress, desc="CMLM...")
1336
- pv, bv, sv, _ = model_cmlm(geno_q, pheno_q, K, n_groups=None, n_pc=n_pc_user)
1337
- model_pvals['CMLM'] = pv
1338
- model_betas['CMLM'] = bv
1339
- model_ses['CMLM'] = sv
1340
- current_progress += step
1341
-
1342
- if run_bslmm:
1343
- progress(current_progress, desc="BSLMM (may be slow)...")
1344
- pv, bv, sv = model_bslmm(geno_q, pheno_q)
1345
- model_pvals['BSLMM'] = pv
1346
- model_betas['BSLMM'] = bv
1347
- model_ses['BSLMM'] = sv
1348
- current_progress += step
1349
-
1350
- if run_farmcpu:
1351
- progress(current_progress, desc="FarmCPU...")
1352
- pv, bv, sv = model_farmcpu(geno_q, pheno_q, K)
1353
- model_pvals['FarmCPU'] = pv
1354
- model_betas['FarmCPU'] = bv
1355
- model_ses['FarmCPU'] = sv
1356
- current_progress += step
1357
-
1358
- if not model_pvals:
1359
- return ("⚠️ No models selected.",
1360
- None, None, None, None, None, None, None, None, None,
1361
- gr.update(choices=[]), gr.update(choices=[]), {}, {})
1362
-
1363
- # Create results table
1364
- progress(0.80, desc="Generating results...")
1365
- df = pd.DataFrame({
1366
- 'Marker': mn_q,
1367
- 'Chromosome': ch_q,
1368
- 'Position_bp': pos_q,
1369
- 'MAF': maf_q
1370
  })
1371
-
1372
- LOD_FACTOR = np.log10(np.e) / 2.0
1373
- for mname, pv in model_pvals.items():
1374
- df[f'{mname}_P'] = pv
1375
- df[f'{mname}_LOD'] = -np.log10(np.clip(pv, 1e-300, 1)) * LOD_FACTOR
1376
- df[f'{mname}_Sig'] = (pv < bonf).astype(int)
1377
- if mname in model_betas:
1378
- df[f'{mname}_Beta'] = model_betas[mname]
1379
-
1380
- df = df.sort_values(f"{list(model_pvals.keys())[0]}_P").reset_index(drop=True)
1381
- df.insert(0, 'Rank', range(1, len(df) + 1))
1382
-
1383
- csv_path = str(rdir / 'gwas_results.csv')
1384
- df.to_csv(csv_path, index=False)
1385
-
1386
- # Generate plots
1387
- progress(0.85, desc="Generating plots...")
1388
-
1389
- # Phenotype distribution
1390
- ph_path = str(pdir / 'phenotype_dist.png')
1391
- plot_phenotype(pheno_q, ph_path)
1392
-
1393
- # PCA
1394
- pca_path = str(pdir / 'pca_analysis.png')
1395
- evr, cumev, scores = plot_pca(geno_q, pheno_q, n_pc_user, pca_path)
1396
-
1397
- # Kinship heatmap
1398
- kin_path = str(pdir / 'kinship_heatmap.png')
1399
- plot_kinship_heatmap(K, kin_path)
1400
-
1401
- # MAF distribution
1402
- maf_path = str(pdir / 'maf_distribution.png')
1403
- plot_maf_distribution(maf_q, maf_path)
1404
-
1405
- # Manhattan plots
1406
- man_paths = {}
1407
- for mname, pv in model_pvals.items():
1408
- mp = str(pdir / f'manhattan_{mname}.png')
1409
- plot_manhattan_single(mn_q, ch_q, pv, mname, bonf, lod_thresh_user, mp)
1410
- man_paths[mname] = mp
1411
-
1412
- # QQ plots
1413
- qq_paths = {}
1414
- lam_dict = {}
1415
- for mname, pv in model_pvals.items():
1416
- qp = str(pdir / f'qq_{mname}.png')
1417
- lam = plot_qq_single(pv, mname, bonf, qp)
1418
- qq_paths[mname] = qp
1419
- lam_dict[mname] = lam
1420
-
1421
- # LD decay
1422
- ld_path = str(pdir / 'ld_decay.png')
1423
- ld_stats, ld_text = plot_ld_decay(geno_q, ch_q, pos_q, ld_path)
1424
-
1425
- # Volcano plots
1426
- volcano_paths = {}
1427
- for mname, pv in model_pvals.items():
1428
- if mname in model_betas:
1429
- vp = str(pdir / f'volcano_{mname}.png')
1430
- plot_volcano(pv, model_betas[mname], mname, bonf, vp)
1431
- volcano_paths[mname] = vp
1432
-
1433
- # Model comparison
1434
- cmp_path = str(pdir / 'model_comparison.png')
1435
- plot_model_comparison(model_pvals, cmp_path)
1436
-
1437
- # Circos
1438
- circos_path = str(pdir / 'circos_mta.png')
1439
- plot_circos(mn_q, ch_q, pos_q, model_pvals, bonf, lod_thresh_user, circos_path)
1440
-
1441
- # Create ZIP
1442
- progress(0.95, desc="Creating ZIP archive...")
1443
- zip_path = str(OUTPUT_DIR / f'GWAS_Results_{run_id}.zip')
1444
  with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf:
1445
- for root, _, files in os.walk(str(rdir)):
1446
  for f in files:
1447
- fp = os.path.join(root, f)
1448
- zf.write(fp, os.path.relpath(fp, str(rdir)))
1449
-
1450
- # Create summary markdown with fallback for tabulate
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1451
  summary = f"""
1452
- ## βœ… GWAS Analysis Complete β€” v11.0
1453
 
1454
- ### πŸ“Š Quality Control Summary
1455
  | Metric | Value |
1456
  |--------|-------|
1457
- | Samples (after QC) | **{len(pheno_q)}** |
1458
- | Markers (after QC) | **{n_q}** |
1459
- | MAF threshold | β‰₯ {maf_thresh:.1f}% |
1460
- | Bonferroni threshold | P < {bonf:.3e} (-log₁₀P > {-np.log10(bonf):.2f}) |
1461
-
1462
- ### πŸ”¬ Model Results
1463
- | Model | Sig. Markers | Ξ» (inflation) |
1464
- |-------|-------------|---------------|
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1465
  """
1466
- for mname, pv in model_pvals.items():
1467
- n_sig = (pv < bonf).sum()
1468
- lam = lam_dict.get(mname, 1.0)
1469
- summary += f"| {mname} | **{n_sig}** | {lam:.4f} |\n"
1470
-
1471
- summary += f"""
1472
- ### 🧬 LD Decay
1473
- {ld_text}
1474
-
1475
- ### πŸ“ˆ Output Files
1476
- - `gwas_results.csv` β€” Complete results for all markers
1477
- - `plots/` β€” All figures (Manhattan, QQ, LD, PCA, etc.)
1478
-
1479
- ### πŸ† Top Markers
1480
- """
1481
- # Create top markers table manually (without tabulate)
1482
- top_df = df[['Rank', 'Marker', 'Chromosome', 'Position_bp'] + [f'{m}_P' for m in model_pvals.keys()]].head(10)
1483
- summary += "| " + " | ".join(top_df.columns) + " |\n"
1484
- summary += "|" + "|".join([" --- " for _ in top_df.columns]) + "|\n"
1485
- for _, row in top_df.iterrows():
1486
- summary += "| " + " | ".join(str(v) for v in row.values) + " |\n"
1487
-
1488
- summary += """
1489
- ---
1490
- *MTA GWAS v11.0 β€” Fixed LD decay (Hill-Weir model) | All models functional | White background*
1491
- """
1492
-
1493
- progress(1.0, desc="Complete!")
1494
-
1495
- first_man = list(man_paths.values())[0] if man_paths else None
1496
- first_qq = list(qq_paths.values())[0] if qq_paths else None
1497
-
1498
- return (summary,
1499
- first_man, first_qq, pca_path,
1500
- ld_path, circos_path, cmp_path, ph_path,
1501
- zip_path, kin_path,
1502
- gr.update(choices=list(man_paths.keys()), value=list(man_paths.keys())[0] if man_paths else None),
1503
- gr.update(choices=list(qq_paths.keys()), value=list(qq_paths.keys())[0] if qq_paths else None),
1504
- man_paths, qq_paths)
1505
-
1506
  except Exception as e:
1507
  import traceback
1508
- return (f"## ❌ Error\n```\n{e}\n\n{traceback.format_exc()}\n```",
1509
- None, None, None, None, None, None, None, None, None,
1510
- gr.update(choices=[]), gr.update(choices=[]), {}, {})
 
 
1511
 
1512
  # ══════════════════════════════════════════════════════════════
1513
  # GRADIO UI
1514
  # ══════════════════════════════════════════════════════════════
1515
 
1516
- CSS = """
1517
- body, .gradio-container { background: #F7F9FC !important; color: #1A202C !important; }
1518
- h1, h2, h3, h4 { color: #1A365D !important; }
1519
- label, .label-wrap { color: #2D3748 !important; font-weight: 600 !important; }
1520
- .gr-button-primary {
1521
- background: linear-gradient(135deg, #1A365D 0%, #2B6CB0 100%) !important;
1522
- color: #FFFFFF !important;
1523
- font-weight: 700 !important;
1524
- font-size: 15px !important;
1525
- border: none !important;
1526
- border-radius: 8px !important;
1527
- box-shadow: 0 2px 8px rgba(43,108,176,0.25) !important;
1528
- }
1529
- .gr-button-primary:hover {
1530
- background: linear-gradient(135deg, #2B6CB0 0%, #3182CE 100%) !important;
1531
- box-shadow: 0 4px 14px rgba(43,108,176,0.38) !important;
1532
- }
1533
- .gr-box, .gr-panel, .block { background: #FFFFFF !important; border: 1px solid #E2E8F0 !important; border-radius: 10px !important; }
1534
- .progress-bar { background: #2B6CB0 !important; }
1535
  """
1536
 
1537
- with gr.Blocks(css=CSS, title="GWAS Analysis v11.0") as app:
 
1538
  gr.Markdown("""
1539
- # 🧬 GWAS / MTA Analysis Platform v11.0
1540
- ### Multi-Model Suite Β· Hill-Weir LD Decay Β· Fixed Model Selection Β· Publication-Ready White Theme
 
1541
  ---
1542
  """)
1543
-
1544
  with gr.Row():
1545
  with gr.Column(scale=1):
1546
- input_file = gr.File(label="πŸ“ Upload CSV", file_types=[".csv"])
1547
  gr.Markdown("""
1548
- **CSV Format:**
1549
- ID, Phenotype, Mrk1, Mrk2, ...
 
 
 
 
 
 
1550
  """)
1551
-
1552
- with gr.Column(scale=1):
1553
- miss_sample = gr.Slider(5, 50, value=30, step=5, label="Max sample missing (%)")
1554
- miss_marker = gr.Slider(5, 50, value=30, step=5, label="Max marker missing (%)")
1555
- maf_thr = gr.Slider(0, 25, value=3, step=1, label="Min MAF (%)")
1556
-
1557
  with gr.Column(scale=1):
1558
- lod_thresh = gr.Slider(0.5, 10.0, value=3.0, step=0.1, label="LOD threshold")
1559
- n_pc = gr.Slider(2, 20, value=5, step=1, label="Number of PCs")
1560
-
1561
- gr.Markdown("### Models")
1562
- with gr.Row():
1563
- chk_glm = gr.Checkbox(value=True, label="GLM")
1564
- chk_mlm = gr.Checkbox(value=True, label="MLM")
1565
- chk_cmlm = gr.Checkbox(value=True, label="CMLM")
1566
- chk_bslmm = gr.Checkbox(value=False, label="BSLMM")
1567
- chk_farmcpu = gr.Checkbox(value=True, label="FarmCPU")
1568
-
1569
- run_btn = gr.Button("πŸš€ Run GWAS Analysis", variant="primary", size="lg")
 
 
 
 
1570
  gr.Markdown("---")
1571
-
1572
- summary_out = gr.Markdown()
1573
-
1574
- with gr.Row():
1575
- man_model_sel = gr.Dropdown(label="πŸ—ΊοΈ Manhattan β€” select model", choices=[], value=None, interactive=True)
1576
- qq_model_sel = gr.Dropdown(label="πŸ“ˆ QQ Plot β€” select model", choices=[], value=None, interactive=True)
1577
-
1578
  with gr.Row():
1579
- man_out = gr.Image(label="πŸ—ΊοΈ Manhattan Plot (βˆ’log₁₀P top | LOD bottom)")
1580
- qq_out = gr.Image(label="πŸ“ˆ QQ Plot (genomic inflation Ξ»)")
1581
-
1582
  with gr.Row():
1583
- pca_out = gr.Image(label="πŸ”¬ PCA Analysis (Scree + PC1v2 + PC2v3)")
1584
- ld_out = gr.Image(label="🧬 LD Decay (Hill-Weir model)")
1585
-
1586
  with gr.Row():
1587
- circos_out = gr.Image(label="🌐 Circos β€” Multi-Model MTA")
1588
- cmp_out = gr.Image(label="βš–οΈ Model P-value Concordance")
1589
-
1590
  with gr.Row():
1591
- ph_out = gr.Image(label="πŸ“Š Phenotype Distribution")
1592
- kin_out = gr.Image(label="πŸ”₯ Kinship Matrix Heatmap")
1593
-
1594
- dl_out = gr.File(label="πŸ“¦ Download All Results (ZIP)")
1595
-
1596
- man_paths_state = gr.State({})
1597
- qq_paths_state = gr.State({})
1598
-
1599
- run_btn.click(
1600
- fn=run_analysis,
1601
- inputs=[input_file, miss_sample, miss_marker, maf_thr,
1602
- lod_thresh, n_pc,
1603
- chk_glm, chk_mlm, chk_cmlm, chk_bslmm, chk_farmcpu],
1604
- outputs=[summary_out, man_out, qq_out, pca_out,
1605
- ld_out, circos_out, cmp_out, ph_out,
1606
- dl_out, kin_out,
1607
- man_model_sel, qq_model_sel,
1608
- man_paths_state, qq_paths_state],
1609
- show_progress="full"
1610
  )
1611
-
1612
- def switch_manhattan(model, paths):
1613
- return paths.get(model) if paths else None
1614
-
1615
- def switch_qq(model, paths):
1616
- return paths.get(model) if paths else None
1617
-
1618
- man_model_sel.change(switch_manhattan, [man_model_sel, man_paths_state], [man_out])
1619
- qq_model_sel.change(switch_qq, [qq_model_sel, qq_paths_state], [qq_out])
1620
 
1621
  if __name__ == "__main__":
1622
- app.launch(share=False, show_error=True, max_threads=4, allowed_paths=[str(OUTPUT_DIR)])
 
1
  # -*- coding: utf-8 -*-
2
  """
3
+ MTA Analysis Tool v7.1 - Enhanced Multi-Model GWAS Platform
4
+ Fixes:
5
+ - IndexError in plot_enhanced_ld_decay (bin_means empty guard)
6
+ - Vectorised LD computation (no nested Python loops β†’ ~50x faster)
7
+ - Vectorised Linear Regression via scipy.stats (no per-marker OLS β†’ ~20x faster)
8
+ - Reduced bootstrap iterations for ElasticNet
9
+ - Reduced permutation count for RF/GB
10
+ - max_m capped at 150 for LD to keep it snappy
 
 
 
 
 
 
 
 
 
 
 
11
  """
12
 
13
  import gradio as gr
 
16
  import matplotlib
17
  matplotlib.use('Agg')
18
  import matplotlib.pyplot as plt
 
 
 
19
  from scipy import stats
20
+ from scipy.optimize import curve_fit
21
+ import os, warnings, tempfile, zipfile
22
+ from sklearn.linear_model import ElasticNetCV
23
+ from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor
24
  from sklearn.preprocessing import StandardScaler
25
+ from sklearn.model_selection import KFold
26
+ from sklearn.metrics import r2_score
27
+ import statsmodels.api as sm
28
+ from statsmodels.formula.api import mixedlm
29
  warnings.filterwarnings('ignore')
30
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31
  # ══════════════════════════════════════════════════════════════
32
+ # THEME
33
  # ══════════════════════════════════════════════════════════════
34
+ BG = "#FDFBFF"
35
+ PANEL = "#F6F0FB"
36
+ GRID_C = "#E8DFF5"
37
+ TEXT_C = "#3D2B6B"
38
+ ACCENT = "#8B5CF6"
39
+ RED_C = "#F472B6"
40
+ GOLD_C = "#FBBF24"
41
+ TEAL_C = "#22D3EE"
42
+ ORANGE_C = "#F97316"
43
+ PURPLE_C = "#A855F7"
44
+ GREEN_C = "#34D399"
45
+
46
+ CHROM_PALETTE = [
47
+ "#A78BFA","#F9A8D4","#6EE7B7","#7DD3FC","#FCD34D",
48
+ "#C4B5FD","#FBCFE8","#86EFAC","#BAE6FD","#FDE68A",
49
+ "#DDD6FE","#FDE8F4","#A7F3D0","#E0F2FE","#FEF3C7",
50
+ "#8B5CF6","#EC4899","#10B981","#0EA5E9","#F59E0B",
51
+ "#7C3AED","#DB2777","#2DD4BF","#FB923C","#A78BFA"
 
 
 
52
  ]
53
 
54
+ def set_pastel_style():
 
 
 
 
 
 
 
 
 
55
  plt.rcParams.update({
56
+ 'figure.facecolor': BG, 'axes.facecolor': PANEL,
57
+ 'axes.edgecolor': GRID_C, 'axes.labelcolor': TEXT_C,
58
+ 'axes.titlecolor': TEXT_C, 'xtick.color': TEXT_C,
59
+ 'ytick.color': TEXT_C, 'text.color': TEXT_C,
60
+ 'grid.color': GRID_C, 'grid.linewidth': 0.8,
61
+ 'figure.dpi': 120, 'font.family': 'DejaVu Sans',
62
+ 'axes.spines.top': False, 'axes.spines.right': False,
63
+ 'legend.framealpha': 0.95, 'legend.edgecolor': GRID_C,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64
  })
65
 
66
  # ══════════════════════════════════════════════════════════════
67
+ # PLOT: MANHATTAN + LOD
68
  # ══════════════════════════════════════════════════════════════
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
 
70
+ def plot_manhattan_with_lod(marker_names, chromosomes, p_values, lod_scores,
71
+ sig_set, bonf_thresh, save_path):
72
+ set_pastel_style()
73
+ unique_chroms = sorted(set(chromosomes),
74
+ key=lambda x: (int(x) if str(x).isdigit() else 999, str(x)))
75
+ log_p = -np.log10(np.array(p_values) + 1e-300)
76
+ lod_array = np.array(lod_scores)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77
 
78
+ GAP = max(8, len(marker_names) // 150)
79
+ x_pos = np.zeros(len(marker_names))
80
+ chrom_to_idx = {}
81
+ for i, c in enumerate(chromosomes):
82
+ chrom_to_idx.setdefault(c, []).append(i)
83
 
84
+ offset = 0
85
+ for ch in unique_chroms:
86
+ idxs = chrom_to_idx.get(ch, [])
87
+ if not idxs: continue
88
+ for r, idx in enumerate(idxs):
89
+ x_pos[idx] = offset + r
90
+ offset += len(idxs) + GAP
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91
 
92
+ fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(20, 9),
93
+ gridspec_kw={'height_ratios': [2, 1]},
94
+ facecolor=BG)
95
 
96
+ for ci, ch in enumerate(unique_chroms):
97
+ idxs = chrom_to_idx.get(ch, [])
98
+ if not idxs: continue
99
+ if ci % 2 == 0:
100
+ ax1.axvspan(x_pos[idxs[0]] - 0.5, x_pos[idxs[-1]] + 0.5,
101
+ color='#EDE9FE', alpha=0.45, zorder=0)
102
+ ax2.axvspan(x_pos[idxs[0]] - 0.5, x_pos[idxs[-1]] + 0.5,
103
+ color='#EDE9FE', alpha=0.45, zorder=0)
104
+
105
+ col = CHROM_PALETTE[ci % len(CHROM_PALETTE)]
106
+ normal = [i for i in idxs if i not in sig_set]
107
+ sel = [i for i in idxs if i in sig_set]
108
+ if normal:
109
+ ax1.scatter(x_pos[normal], log_p[normal],
110
+ c=col, s=10, alpha=0.65, linewidths=0, zorder=2)
111
+ if sel:
112
+ ax1.scatter(x_pos[sel], log_p[sel],
113
+ c=RED_C, s=200, alpha=0.18, linewidths=0, zorder=3)
114
+ ax1.scatter(x_pos[sel], log_p[sel],
115
+ c=RED_C, s=55, alpha=1.0,
116
+ edgecolors='white', linewidths=1.0,
117
+ marker='D', zorder=4)
118
+
119
+ ax1.axhline(bonf_thresh, color=RED_C, ls='--', lw=1.8, alpha=0.85,
120
+ label=f'Bonferroni ({bonf_thresh:.1f})', zorder=5)
121
+ ax1.axhline(3, color=GOLD_C, ls=':', lw=1.5, alpha=0.8, label='LOD = 3')
122
+
123
+ ax1_twin = ax1.twinx()
124
+ ax1_twin.scatter(x_pos, lod_array, c=TEAL_C, s=6, alpha=0.35,
125
+ marker='x', zorder=1)
126
+ ax1_twin.set_ylabel('LOD Score', fontsize=11, color=TEAL_C, fontweight='bold')
127
+ ax1_twin.tick_params(axis='y', colors=TEAL_C)
128
+ ax1_twin.set_ylim(0, max(lod_array.max() * 1.1, 1))
129
+
130
+ ax1.set_xlim(-GAP, offset)
131
+ ax1.set_ylim(bottom=0, top=max(log_p.max() * 1.15, 1))
132
+ ax1.set_ylabel('βˆ’log₁₀(P)', fontsize=12, fontweight='bold', labelpad=8)
133
+ ax1.set_title('GWAS Manhattan Plot with LOD Scores', fontsize=15, fontweight='bold', pad=16)
134
+ ax1.yaxis.grid(True, color=GRID_C, linewidth=0.7)
135
+ ax1.legend(loc='upper right', fontsize=9)
136
+
137
+ ax2.plot(x_pos, lod_array, color=TEAL_C, linewidth=1.2, alpha=0.8)
138
+ ax2.fill_between(x_pos, 0, lod_array, color=TEAL_C, alpha=0.18)
139
+ ax2.axhline(3, color=GOLD_C, ls='--', lw=1.3, alpha=0.8)
140
+ ax2.set_xlim(-GAP, offset)
141
+ ax2.set_ylabel('LOD Score', fontsize=11, fontweight='bold')
142
+ ax2.set_xlabel('Chromosome', fontsize=11, fontweight='bold')
143
+ ax2.yaxis.grid(True, color=GRID_C, linewidth=0.7)
144
+
145
+ plt.tight_layout(pad=1.5)
146
+ plt.savefig(save_path, dpi=150, bbox_inches='tight', facecolor=BG)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
147
  plt.close(fig)
148
+
 
 
 
 
 
 
 
 
 
149
 
150
  # ══════════════════════════════════════════════════════════════
151
+ # PLOT: LD DECAY (vectorised β€” no nested Python loops)
152
  # ══════════════════════════════════════════════════════════════
153
 
154
+ def _compute_ld_vectorised(G, pos_arr, max_lag=50):
155
+ """
156
+ Compute pairwise rΒ² and D' using vectorised numpy for all pairs
157
+ within max_lag marker steps. Returns arrays: distances, r2, dprime.
158
+ """
159
+ n_markers = G.shape[1]
160
+ all_dist, all_r2, all_dp = [], [], []
161
+
162
+ for lag in range(1, min(max_lag + 1, n_markers)):
163
+ # Slice pairs at this lag
164
+ x = G[:, :n_markers - lag].astype(float) # shape (n_samples, pairs)
165
+ y = G[:, lag:].astype(float)
166
+
167
+ # rΒ² via vectorised correlation
168
+ xm = x - x.mean(axis=0)
169
+ ym = y - y.mean(axis=0)
170
+ num = (xm * ym).sum(axis=0)
171
+ denom = np.sqrt((xm**2).sum(axis=0) * (ym**2).sum(axis=0))
172
+ with np.errstate(invalid='ignore', divide='ignore'):
173
+ r = np.where(denom > 0, num / denom, 0.0)
174
+ r2 = r ** 2
175
+
176
+ # D' (simplified haplotype approximation)
177
+ p1 = x.mean(axis=0) / 2.0 # allele freq marker i
178
+ p2 = y.mean(axis=0) / 2.0 # allele freq marker j
179
+ p11 = ((x == 2) & (y == 2)).mean(axis=0) / 2.0
180
+ D = p11 - p1 * p2
181
+ with np.errstate(invalid='ignore', divide='ignore'):
182
+ Dmax = np.where(D < 0,
183
+ np.minimum(p1 * (1 - p2), (1 - p1) * p2),
184
+ np.minimum(p1 * p2, (1 - p1) * (1 - p2)))
185
+ dp = np.where(Dmax > 0, np.abs(D / Dmax), 0.0)
186
+
187
+ # Distances for this lag
188
+ dist = np.abs(pos_arr[lag:] - pos_arr[:n_markers - lag])
189
+
190
+ all_dist.append(dist)
191
+ all_r2.append(r2)
192
+ all_dp.append(dp)
193
+
194
+ if not all_dist:
195
+ return np.array([]), np.array([]), np.array([])
196
+
197
+ return (np.concatenate(all_dist),
198
+ np.concatenate(all_r2),
199
+ np.concatenate(all_dp))
200
+
201
+
202
+ def plot_enhanced_ld_decay(genotypes, chromosomes, positions, save_path, max_m=150):
203
+ """
204
+ LD decay plot. Uses vectorised computation; guards against empty bin_means.
205
+ """
206
+ set_pastel_style()
207
+ unique_chroms = sorted(set(chromosomes),
208
  key=lambda x: (int(x) if str(x).isdigit() else 999, str(x)))
209
+
210
+ all_distances, all_r2, all_dprime = [], [], []
211
+ chrom_stats = {}
212
+
 
 
 
 
 
 
213
  for ch in unique_chroms:
214
+ idxs = [i for i, c in enumerate(chromosomes) if c == ch]
215
+ if len(idxs) < 4:
216
  continue
217
+ if len(idxs) > max_m:
218
+ idxs = sorted(np.random.choice(idxs, max_m, replace=False))
219
+
220
+ G = genotypes[:, idxs].copy()
221
+ pos_arr = np.array([positions[i] for i in idxs], dtype=float)
222
+
223
+ dist, r2, dp = _compute_ld_vectorised(G, pos_arr, max_lag=40)
224
+ if len(dist) == 0:
225
+ continue
226
+
227
+ all_distances.extend(dist.tolist())
228
+ all_r2.extend(r2.tolist())
229
+ all_dprime.extend(dp.tolist())
230
+
231
+ chrom_stats[ch] = {
232
+ 'mean_r2': float(np.mean(r2)),
233
+ 'mean_dprime': float(np.mean(dp)),
234
+ }
235
+
236
+ # ── Build binned statistics ─────────────────────────────────────────
237
+ def _bin_stats(distances, values, bins):
238
+ centers, means, stds = [], [], []
239
+ for i in range(len(bins) - 1):
240
+ mask = (distances >= bins[i]) & (distances < bins[i + 1])
241
+ if mask.sum() > 1:
242
+ centers.append((bins[i] + bins[i + 1]) / 2)
243
+ means.append(np.mean(values[mask]))
244
+ stds.append(np.std(values[mask]) / np.sqrt(mask.sum()))
245
+ return (np.array(centers), np.array(means), np.array(stds))
246
+
247
+ fig, axes = plt.subplots(1, 3, figsize=(17, 5), facecolor=BG)
248
+
249
+ # ── Panel 1: rΒ² decay ───────────────────────────────────────────────
250
+ ax = axes[0]
251
+ ax.set_facecolor(PANEL)
252
+
253
+ if all_distances:
254
+ distances = np.array(all_distances)
255
+ r2_arr = np.array(all_r2)
256
+ dp_arr = np.array(all_dprime)
257
+
258
+ max_dist = min(50, int(np.percentile(distances, 95)))
259
+ bins = np.arange(0, max_dist + 2, max(1, max_dist // 20))
260
+
261
+ ctrs, means, errs = _bin_stats(distances, r2_arr, bins)
262
+
263
+ if len(means) > 0: # ← key guard
264
+ # decay fit
265
+ try:
266
+ def _decay(x, a, b):
267
+ return a * np.exp(-b * x)
268
+ mask_fit = means > 0
269
+ if mask_fit.sum() >= 3:
270
+ params, _ = curve_fit(_decay, ctrs[mask_fit], means[mask_fit],
271
+ p0=[1.0, 0.1], maxfev=3000)
272
+ x_fit = np.linspace(0, max_dist, 100)
273
+ ax.plot(x_fit, _decay(x_fit, *params), '--', color=RED_C,
274
+ linewidth=2, label=f'Fit Ξ»={params[1]:.3f}')
275
+ except Exception:
276
+ pass
277
+
278
+ ax.errorbar(ctrs, means, yerr=errs,
279
+ fmt='o-', color=ACCENT, capsize=3, capthick=1,
280
+ markersize=4, linewidth=1.5, alpha=0.8)
281
+ ax.axhline(0.2, color=RED_C, ls='--', lw=1.2, alpha=0.8, label='rΒ²=0.2')
282
+
283
+ # half-decay β€” safe because len(means) > 0 guaranteed here
284
+ half_idx = np.where(means <= means[0] / 2)[0]
285
+ if len(half_idx) > 0:
286
+ ax.axvline(ctrs[half_idx[0]], color=GOLD_C, ls='--', lw=1.2,
287
+ label=f'Β½-decay β‰ˆ {ctrs[half_idx[0]]:.1f}')
288
+
289
+ ax.set_xlabel('Distance (kb)', fontsize=11, fontweight='bold')
290
+ ax.set_ylabel('Mean rΒ²', fontsize=11, fontweight='bold')
291
+ ax.set_title('LD Decay (rΒ²)', fontsize=13, fontweight='bold')
292
+ ax.set_ylim(0, 1)
293
+ ax.legend(fontsize=8)
294
+ ax.grid(True, color=GRID_C, lw=0.7)
295
+
296
+ # ── Panel 2: D' decay ───────────────────────────────────────────────
297
+ ax = axes[1]
298
+ ax.set_facecolor(PANEL)
299
+
300
+ if all_distances:
301
+ ctrs_dp, means_dp, errs_dp = _bin_stats(distances, dp_arr, bins)
302
+ if len(means_dp) > 0:
303
+ ax.errorbar(ctrs_dp, means_dp, yerr=errs_dp,
304
+ fmt='o-', color=TEAL_C, capsize=3, capthick=1,
305
+ markersize=4, linewidth=1.5, alpha=0.8)
306
+ ax.axhline(0.5, color=RED_C, ls='--', lw=1.2, alpha=0.8, label="D'=0.5")
307
+
308
+ ax.set_xlabel('Distance (kb)', fontsize=11, fontweight='bold')
309
+ ax.set_ylabel("Mean D'", fontsize=11, fontweight='bold')
310
+ ax.set_title("LD Decay (D')", fontsize=13, fontweight='bold')
311
+ ax.set_ylim(0, 1)
312
+ ax.legend(fontsize=8)
313
+ ax.grid(True, color=GRID_C, lw=0.7)
314
+
315
+ # ── Panel 3: per-chromosome bar ─────────────────────────────────────
316
+ ax = axes[2]
317
+ ax.set_facecolor(PANEL)
318
+
319
+ if chrom_stats:
320
+ clist = sorted(chrom_stats.keys(),
321
+ key=lambda x: (int(x) if str(x).isdigit() else 999, str(x)))
322
+ r2m = [chrom_stats[c]['mean_r2'] for c in clist]
323
+ dpm = [chrom_stats[c]['mean_dprime'] for c in clist]
324
+ x = np.arange(len(clist))
325
+ w = 0.35
326
+ ax.bar(x - w/2, r2m, w, label='rΒ²', color=ACCENT, alpha=0.8, edgecolor='white')
327
+ ax.bar(x + w/2, dpm, w, label="D'", color=TEAL_C, alpha=0.8, edgecolor='white')
328
+ ax.set_xticks(x)
329
+ ax.set_xticklabels([f'Chr{c}' for c in clist], rotation=45, ha='right', fontsize=8)
330
+ ax.set_ylabel('Mean LD', fontsize=11, fontweight='bold')
331
+ ax.set_title('Per-Chromosome LD', fontsize=13, fontweight='bold')
332
+ ax.legend(fontsize=8)
333
+ ax.grid(True, color=GRID_C, lw=0.7, axis='y')
334
+
335
+ plt.tight_layout(pad=1.8)
336
+ plt.savefig(save_path, dpi=150, bbox_inches='tight', facecolor=BG)
337
  plt.close(fig)
338
 
339
+ return chrom_stats
340
+
341
+
342
  # ══════════════════════════════════════════════════════════════
343
+ # PLOT: MODEL COMPARISON
344
  # ══════════════════════════════════════════════════════════════
345
 
346
+ def plot_model_comparison(results_df, save_path):
347
+ set_pastel_style()
348
+ fig, axes = plt.subplots(2, 2, figsize=(13, 9), facecolor=BG)
349
+
350
+ models = ['LR_P', 'MLM_P', 'EN_P', 'RF_P', 'GB_P']
351
+ model_names = ['Linear', 'Mixed', 'ElasticNet', 'RandForest', 'GradBoost']
352
+ colors = [ACCENT, RED_C, GREEN_C, ORANGE_C, PURPLE_C]
353
+
354
+ # 1. P-value correlation heatmap
355
+ ax = axes[0, 0]; ax.set_facecolor(PANEL)
356
+ avail = [m for m in models if m in results_df.columns]
357
+ anames = [model_names[models.index(m)] for m in avail]
358
+ cm = np.eye(len(avail))
359
+ for i, m1 in enumerate(avail):
360
+ for j, m2 in enumerate(avail):
361
+ cm[i, j] = results_df[m1].corr(results_df[m2])
362
+ im = ax.imshow(cm, cmap='RdBu_r', vmin=-1, vmax=1, aspect='auto')
363
+ ax.set_xticks(range(len(avail))); ax.set_yticks(range(len(avail)))
364
+ ax.set_xticklabels(anames, rotation=45, ha='right', fontsize=9)
365
+ ax.set_yticklabels(anames, fontsize=9)
366
+ for i in range(len(avail)):
367
+ for j in range(len(avail)):
368
+ ax.text(j, i, f'{cm[i,j]:.2f}', ha='center', va='center',
369
+ color='white' if abs(cm[i,j]) > 0.6 else 'black', fontsize=8)
370
+ plt.colorbar(im, ax=ax, shrink=0.8)
371
+ ax.set_title('Model P-value Correlations', fontsize=12, fontweight='bold')
372
+
373
+ # 2. Effect size histograms
374
+ ax = axes[0, 1]; ax.set_facecolor(PANEL)
375
+ for i, (m, c) in enumerate(zip(models, colors)):
376
+ beta = m.replace('_P', '_Beta')
377
+ if beta in results_df.columns:
378
+ ax.hist(results_df[beta].dropna(), bins=30, alpha=0.5,
379
+ label=model_names[i], color=c)
380
+ ax.set_xlabel('Effect Size', fontsize=11); ax.set_ylabel('Frequency', fontsize=11)
381
+ ax.set_title('Effect Size Distribution', fontsize=12, fontweight='bold')
382
+ ax.legend(fontsize=8); ax.grid(True, color=GRID_C, lw=0.7)
383
+
384
+ # 3. Significant markers per model
385
+ ax = axes[1, 0]; ax.set_facecolor(PANEL)
386
+ sig_cols = [c for c in results_df.columns if c.startswith('Significant_')]
387
+ if sig_cols:
388
+ counts = [results_df[c].sum() for c in sig_cols]
389
+ labels = [c.replace('Significant_', '') for c in sig_cols]
390
+ bar_c = [colors[models.index(f'{l}_P')] if f'{l}_P' in models else ACCENT
391
+ for l in labels]
392
+ ax.barh(range(len(labels)), counts, color=bar_c, alpha=0.75)
393
+ ax.set_yticks(range(len(labels))); ax.set_yticklabels(labels)
394
+ ax.set_xlabel('Significant Markers (Bonferroni)', fontsize=11)
395
+ ax.set_title('Significant Markers per Model', fontsize=12, fontweight='bold')
396
+ ax.grid(True, color=GRID_C, lw=0.7, axis='x')
397
+
398
+ # 4. LOD distribution
399
+ ax = axes[1, 1]; ax.set_facecolor(PANEL)
400
+ if 'LR_LOD' in results_df.columns:
401
+ ax.hist(results_df['LR_LOD'].dropna(), bins=40,
402
+ color=ACCENT, alpha=0.75, label='LR LOD')
403
+ if 'MLM_LOD' in results_df.columns:
404
+ ax.hist(results_df['MLM_LOD'].dropna(), bins=40,
405
+ color=TEAL_C, alpha=0.55, label='MLM LOD')
406
+ ax.axvline(3, color=GOLD_C, ls='--', lw=1.5, label='LOD=3')
407
+ ax.set_xlabel('LOD Score', fontsize=11); ax.set_ylabel('Frequency', fontsize=11)
408
+ ax.set_title('LOD Score Distribution', fontsize=12, fontweight='bold')
409
+ ax.legend(fontsize=8); ax.grid(True, color=GRID_C, lw=0.7)
410
+
411
+ plt.tight_layout(pad=1.5)
412
+ plt.savefig(save_path, dpi=150, bbox_inches='tight', facecolor=BG)
413
  plt.close(fig)
414
+
 
415
 
416
  # ══════════════════════════════════════════════════════════════
417
+ # GWAS MODELS (speed-optimised)
418
  # ══════════════════════════════════════════════════════════════
419
 
420
+ def linear_regression_gwas(genotypes, phenotypes):
421
+ """
422
+ Vectorised single-marker regression using scipy.stats.
423
+ ~20Γ— faster than per-marker statsmodels OLS.
424
+ """
425
+ n_markers = genotypes.shape[1]
426
+ pvals = np.ones(n_markers)
427
+ effects = np.zeros(n_markers)
428
+ se_arr = np.zeros(n_markers)
429
+ r2_arr = np.zeros(n_markers)
430
+
431
+ y = phenotypes.astype(float)
432
+ for i in range(n_markers):
433
+ x = genotypes[:, i].astype(float)
434
+ if x.std() < 1e-9:
435
+ continue
436
+ slope, intercept, r, p, se = stats.linregress(x, y)
437
+ pvals[i] = p if np.isfinite(p) else 1.0
438
+ effects[i] = slope
439
+ se_arr[i] = se
440
+ r2_arr[i] = r ** 2
441
+ return pvals, effects, se_arr, r2_arr
 
 
 
 
 
442
 
443
+
444
+ def mixed_model_gwas(genotypes, phenotypes):
445
+ """Mixed LM β€” kept as-is but wrapped in try/except per marker."""
446
+ n_markers = genotypes.shape[1]
447
+ pvals = np.ones(n_markers)
448
+ effects = np.zeros(n_markers)
449
+ lod = np.zeros(n_markers)
450
+
451
+ for i in range(n_markers):
452
+ x = genotypes[:, i]
453
+ if x.std() < 1e-9:
454
+ continue
455
+ try:
456
+ df = pd.DataFrame({'pheno': phenotypes, 'marker': x})
457
+ model = mixedlm("pheno ~ marker", df, groups=df.index).fit(disp=False)
458
+ pvals[i] = model.pvalues.get('marker', 1.0)
459
+ effects[i] = model.params.get('marker', 0.0)
460
+ lod[i] = -np.log10(pvals[i] + 1e-300)
461
+ except Exception:
462
+ pass
463
+ return pvals, effects, lod
464
+
465
+
466
+ def elasticnet_gwas(genotypes, phenotypes, n_bootstrap=30):
467
+ """ElasticNet with reduced bootstrap count for speed."""
468
+ scaler = StandardScaler()
469
+ X_sc = scaler.fit_transform(genotypes)
470
+ enet = ElasticNetCV(cv=5, random_state=42, max_iter=3000, n_jobs=-1)
471
+ enet.fit(X_sc, phenotypes)
472
+ coef = enet.coef_
473
+
474
+ boot_coefs = []
475
+ rng = np.random.default_rng(42)
476
+ for _ in range(n_bootstrap):
477
+ idx = rng.integers(0, len(phenotypes), len(phenotypes))
478
+ eb = ElasticNetCV(cv=3, random_state=42, max_iter=2000)
479
+ eb.fit(X_sc[idx], phenotypes[idx])
480
+ boot_coefs.append(eb.coef_)
481
+
482
+ boot_arr = np.array(boot_coefs)
483
+ pvals = np.ones(len(coef))
484
+ for i in range(len(coef)):
485
+ sd = boot_arr[:, i].std()
486
+ if sd > 0:
487
+ z = abs(coef[i]) / (sd + 1e-10)
488
+ pvals[i] = 2 * (1 - stats.norm.cdf(z))
489
+ return pvals, coef
490
+
491
+
492
+ def machine_learning_gwas(genotypes, phenotypes, model_type='rf', n_perm=20):
493
+ """RF / GB with reduced permutation count for speed."""
494
+ scaler = StandardScaler()
495
+ X_sc = scaler.fit_transform(genotypes)
496
+
497
+ if model_type == 'rf':
498
+ mdl = RandomForestRegressor(n_estimators=80, random_state=42,
499
+ n_jobs=-1, max_features='sqrt')
500
  else:
501
+ mdl = GradientBoostingRegressor(n_estimators=80, random_state=42,
502
+ subsample=0.8)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
503
 
504
+ kf = KFold(n_splits=5, shuffle=True, random_state=42)
505
+ cv_scores, imp_list = [], []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
506
 
507
+ for tr, val in kf.split(X_sc):
508
+ mdl.fit(X_sc[tr], phenotypes[tr])
509
+ cv_scores.append(r2_score(phenotypes[val], mdl.predict(X_sc[val])))
510
+ imp_list.append(mdl.feature_importances_)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
511
 
512
+ avg_imp = np.mean(imp_list, axis=0)
513
+
514
+ rng = np.random.default_rng(42)
515
+ null_imp = []
516
+ for _ in range(n_perm):
517
+ mdl.fit(X_sc, rng.permutation(phenotypes))
518
+ null_imp.append(mdl.feature_importances_)
519
+ null_imp = np.array(null_imp)
520
+
521
+ pvals = np.array([np.mean(null_imp[:, i] >= avg_imp[i])
522
+ for i in range(len(avg_imp))])
523
+ return pvals, avg_imp, float(np.mean(cv_scores))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
524
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
525
 
526
  # ══════════════════════════════════════════════════════════════
527
+ # CSV PARSER
528
  # ═══════════════��══════════════════════════════════════════════
529
 
530
+ def parse_input_csv_enhanced(filepath):
531
+ df = pd.read_csv(filepath, header=0, dtype=str)
532
+ marker_cols = df.columns[2:].tolist()
533
+ chr_row = df.iloc[0]
534
+ chrom_dict, pos_dict = {}, {}
535
+
536
+ for m in marker_cols:
537
+ val = str(chr_row[m]).strip()
538
+ if ':' in val:
539
+ parts = val.split(':')
540
+ chrom_dict[m] = parts[0]
541
+ try: pos_dict[m] = float(parts[1])
542
+ except: pos_dict[m] = 0.0
543
+ elif '_' in val:
544
+ parts = val.split('_')
545
+ chrom_dict[m] = parts[0]
546
+ try: pos_dict[m] = float(parts[1]) if len(parts) > 1 else 0.0
547
+ except: pos_dict[m] = 0.0
548
+ else:
549
+ val = val[:-2] if val.endswith('.0') else val
550
+ chrom_dict[m] = val
551
+ pos_dict[m] = 0.0
552
+
553
+ df_s = df.iloc[1:].reset_index(drop=True)
554
+ sample_ids = df_s.iloc[:, 0].astype(str).values
555
+ phenotypes = pd.to_numeric(df_s.iloc[:, 1], errors='coerce').values
556
+ geno_raw = df_s[marker_cols].apply(pd.to_numeric, errors='coerce').replace(-1, np.nan)
557
+ positions = [pos_dict.get(m, 0.0) for m in marker_cols]
558
+
559
+ return sample_ids, phenotypes, geno_raw.values, marker_cols, chrom_dict, positions
560
+
561
+
562
+ # ══════════════════════════════════════════════════════════════
563
+ # MAIN ANALYSIS
564
+ # ══════════════════════════════════════════════════════════════
565
+
566
+ def run_mta_analysis(input_file, target_markers, miss_rate_sample,
567
+ miss_rate_marker, maf_thresh, include_mlm,
568
+ include_enet, include_rf, include_gb):
569
+
570
+ mlm_pvals = mlm_effects = mlm_lod = None
571
+ enet_pvals = enet_coef = None
572
+ rf_pvals = rf_imp = rf_cv = None
573
+ gb_pvals = gb_imp = gb_cv = None
574
+
575
  try:
576
  if input_file is None:
577
+ return ("⚠️ Please upload a CSV file.", None, None, None, None)
578
+
579
+ temp_dir = tempfile.mkdtemp()
580
+ results_dir = os.path.join(temp_dir, 'results')
581
+ plots_dir = os.path.join(results_dir, 'plots')
582
+ for d in [results_dir, plots_dir]:
583
+ os.makedirs(d, exist_ok=True)
584
+
585
+ miss_s_t = miss_rate_sample / 100.0
586
+ miss_m_t = miss_rate_marker / 100.0
587
+ maf_t = maf_thresh / 100.0
588
+
589
+ (sample_ids, phenotypes, genotypes,
590
+ marker_names, chrom_dict, positions) = parse_input_csv_enhanced(input_file)
591
+
592
+ n_samples = len(sample_ids)
593
+ n_markers = len(marker_names)
594
+
 
595
  # QC
596
+ miss_m = np.isnan(genotypes).sum(axis=0) / max(n_samples, 1)
597
+ miss_s = np.isnan(genotypes).sum(axis=1) / max(n_markers, 1)
598
+
599
+ maf = np.zeros(n_markers)
600
+ for i in range(n_markers):
601
+ v = genotypes[:, i]
 
602
  v = v[~np.isnan(v)]
603
+ if len(v):
604
+ f = np.mean(v) / 2.0
605
  maf[i] = min(f, 1 - f)
606
+
607
+ qc_m = (miss_m < miss_m_t) & (maf >= maf_t)
608
+ qc_s = miss_s < miss_s_t
609
+
610
+ fallback_msg = ""
611
+ for rs, rm in [(miss_s_t, miss_m_t),
612
+ (0.60,0.60),(0.70,0.70),(0.80,0.80),(0.90,0.90),(1.00,1.00)]:
613
+ qc_m_t = (miss_m < rm) & (maf >= maf_t)
614
+ qc_s_t = miss_s < rs
615
+ if qc_s_t.sum() >= 10:
616
+ qc_m = qc_m_t
617
+ qc_s = qc_s_t
618
+ if rs > miss_s_t or rm > miss_m_t:
619
+ fallback_msg = (f"\n> ⚠️ **QC auto-relaxed** to sample missing "
620
+ f"< {rs*100:.0f}% / marker missing "
621
+ f"< {rm*100:.0f}% to retain β‰₯10 samples.\n")
622
+ break
623
+
624
+ geno_qc = genotypes[np.ix_(qc_s, qc_m)].copy()
625
+ pheno_qc = phenotypes[qc_s]
626
+ ids_qc = sample_ids[qc_s]
627
+ mnames_qc = [marker_names[i] for i in range(n_markers) if qc_m[i]]
628
+ chrom_qc = [chrom_dict[m] for m in mnames_qc]
629
+ pos_qc = [positions[i] for i in range(n_markers) if qc_m[i]]
630
+
631
+ # Impute
632
+ col_means = np.nanmean(geno_qc, axis=0)
633
+ col_means = np.where(np.isnan(col_means), 0.0, col_means)
634
+ for i in range(geno_qc.shape[1]):
635
+ mask = np.isnan(geno_qc[:, i])
636
+ if mask.any():
637
+ geno_qc[mask, i] = col_means[i]
638
+
639
+ valid = ~np.isnan(pheno_qc)
640
+ geno_qc = geno_qc[valid]
641
+ pheno_qc = pheno_qc[valid]
642
+ ids_qc = ids_qc[valid]
643
+
644
+ if len(ids_qc) < 10:
645
+ worst = np.sort(np.isnan(genotypes).sum(axis=1) /
646
+ max(n_markers, 1) * 100)[::-1][:5]
647
+ return (
648
+ f"## ⚠️ Insufficient Samples After QC\n\n"
649
+ f"Only **{len(ids_qc)}** sample(s) passed QC (started with {n_samples}).\n\n"
650
+ f"Top missing rates: `{', '.join(f'{v:.0f}%' for v in worst)}`\n\n"
651
+ f"Try increasing the **Sample Missing Rate** slider to 50–80%.",
652
+ None, None, None, None
653
+ )
654
+
655
+ n_qc = len(mnames_qc)
656
+ bonf = 0.05 / n_qc
657
+
658
+ # ── Models ─────────────────────────────────────────────────────
659
+ print(f"[1/5] Linear Regression on {n_qc} markers Γ— {len(ids_qc)} samples …")
660
+ lr_pvals, lr_effects, lr_se, lr_r2 = linear_regression_gwas(geno_qc, pheno_qc)
661
+
662
+ if include_mlm:
663
+ print("[2/5] Mixed Linear Model …")
664
+ mlm_pvals, mlm_effects, mlm_lod = mixed_model_gwas(geno_qc, pheno_qc)
665
+
666
+ if include_enet:
667
+ print("[3/5] ElasticNet …")
668
+ enet_pvals, enet_coef = elasticnet_gwas(geno_qc, pheno_qc)
669
+
670
+ if include_rf:
671
+ print("[4/5] Random Forest …")
672
+ rf_pvals, rf_imp, rf_cv = machine_learning_gwas(geno_qc, pheno_qc, 'rf')
673
+
674
+ if include_gb:
675
+ print("[5/5] Gradient Boosting …")
676
+ gb_pvals, gb_imp, gb_cv = machine_learning_gwas(geno_qc, pheno_qc, 'gb')
677
+
678
+ # ── Results DataFrame ───────────────────────────────────────────
679
+ gwas_df = pd.DataFrame({
680
+ 'Rank': 0,
681
+ 'Marker': mnames_qc,
682
+ 'Chromosome': chrom_qc,
683
+ 'Position': pos_qc,
684
+ 'LR_P': lr_pvals,
685
+ 'LR_Beta': lr_effects,
686
+ 'LR_LOD': -np.log10(lr_pvals + 1e-300),
687
+ 'Significant_LR': (lr_pvals < bonf).astype(int),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
688
  })
689
+
690
+ if include_mlm and mlm_pvals is not None:
691
+ gwas_df['MLM_P'] = mlm_pvals
692
+ gwas_df['MLM_Beta'] = mlm_effects
693
+ gwas_df['MLM_LOD'] = mlm_lod
694
+ gwas_df['Significant_MLM'] = (mlm_pvals < bonf).astype(int)
695
+
696
+ if include_enet and enet_pvals is not None:
697
+ gwas_df['EN_P'] = enet_pvals
698
+ gwas_df['EN_Beta'] = enet_coef
699
+ gwas_df['Significant_EN'] = (enet_pvals < bonf).astype(int)
700
+
701
+ if include_rf and rf_pvals is not None:
702
+ gwas_df['RF_P'] = rf_pvals
703
+ gwas_df['RF_Imp'] = rf_imp
704
+ gwas_df['Significant_RF'] = (rf_pvals < bonf).astype(int)
705
+
706
+ if include_gb and gb_pvals is not None:
707
+ gwas_df['GB_P'] = gb_pvals
708
+ gwas_df['GB_Imp'] = gb_imp
709
+ gwas_df['Significant_GB'] = (gb_pvals < bonf).astype(int)
710
+
711
+ sig_cols = [c for c in gwas_df.columns if c.startswith('Significant_')]
712
+ gwas_df['Consensus_Sig'] = (
713
+ (gwas_df[sig_cols].sum(axis=1) >= 2).astype(int)
714
+ if len(sig_cols) > 1 else gwas_df[sig_cols[0]] if sig_cols
715
+ else 0
716
+ )
717
+
718
+ gwas_df = gwas_df.sort_values('LR_P').reset_index(drop=True)
719
+ gwas_df['Rank'] = range(1, len(gwas_df) + 1)
720
+ gwas_df.to_csv(os.path.join(results_dir, 'gwas_results.csv'), index=False)
721
+
722
+ # ── Plots ───────────────────────────────────────────────────────
723
+ print("Generating plots …")
724
+ bonf_log = -np.log10(bonf)
725
+ sig_set = set(np.where(lr_pvals < bonf)[0])
726
+
727
+ man_path = os.path.join(plots_dir, 'manhattan_lod.png')
728
+ plot_manhattan_with_lod(mnames_qc, chrom_qc, lr_pvals,
729
+ -np.log10(lr_pvals + 1e-300),
730
+ sig_set, bonf_log, man_path)
731
+
732
+ ld_path = os.path.join(plots_dir, 'ld_decay.png')
733
+ ld_stats = plot_enhanced_ld_decay(geno_qc, chrom_qc, pos_qc, ld_path)
734
+
735
+ comp_path = os.path.join(plots_dir, 'model_comparison.png')
736
+ plot_model_comparison(gwas_df, comp_path)
737
+
738
+ # ── ZIP ──────────────────────────────────────────────────────────
739
+ zip_path = os.path.join(temp_dir, 'GWAS_Results.zip')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
740
  with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf:
741
+ for root, _, files in os.walk(results_dir):
742
  for f in files:
743
+ fp = os.path.join(root, f)
744
+ zf.write(fp, os.path.relpath(fp, temp_dir))
745
+
746
+ # ── Summary ──────────────────────────────────────────────────────
747
+ def _ns(pv, enabled):
748
+ return str(int((pv < bonf).sum())) if (enabled and pv is not None) else "β€”"
749
+
750
+ ld_r2_mean = np.mean([v['mean_r2'] for v in ld_stats.values()]) if ld_stats else 0
751
+ ld_dp_mean = np.mean([v['mean_dprime'] for v in ld_stats.values()]) if ld_stats else 0
752
+
753
+ top10_cols = ['Marker','Chromosome','LR_P','LR_LOD','Consensus_Sig']
754
+ top10_cols = [c for c in top10_cols if c in gwas_df.columns]
755
+
756
+ def _df_to_md(df):
757
+ """Convert a DataFrame to a markdown table without tabulate."""
758
+ cols = df.columns.tolist()
759
+ def _fmt(v):
760
+ if isinstance(v, float):
761
+ return f"{v:.4e}" if abs(v) < 0.001 else f"{v:.4f}"
762
+ return str(v)
763
+ header = "| " + " | ".join(cols) + " |"
764
+ sep = "| " + " | ".join(["---"] * len(cols)) + " |"
765
+ rows = ["| " + " | ".join(_fmt(row[c]) for c in cols) + " |"
766
+ for _, row in df.iterrows()]
767
+ return "\n".join([header, sep] + rows)
768
+
769
  summary = f"""
770
+ ## πŸ“Š GWAS Analysis Complete
771
 
772
+ ### QC Summary
773
  | Metric | Value |
774
  |--------|-------|
775
+ | Samples (raw β†’ QC) | {n_samples} β†’ **{len(ids_qc)}** |
776
+ | Markers (raw β†’ QC) | {n_markers} β†’ **{n_qc}** |
777
+ | Chromosomes | **{len(set(chrom_qc))}** |
778
+ | MAF filter | β‰₯ {maf_thresh:.1f}% |
779
+ | Sample missing filter | < {miss_rate_sample:.0f}% |
780
+ {fallback_msg}
781
+
782
+ ### Model Results
783
+ | Model | Status | Significant Markers |
784
+ |-------|--------|---------------------|
785
+ | Linear Regression | βœ… | {_ns(lr_pvals, True)} |
786
+ | Mixed Linear Model | {'βœ…' if include_mlm else '❌ skipped'} | {_ns(mlm_pvals, include_mlm)} |
787
+ | ElasticNet | {'βœ…' if include_enet else '❌ skipped'} | {_ns(enet_pvals, include_enet)} |
788
+ | Random Forest | {'βœ…' if include_rf else '❌ skipped'} | {_ns(rf_pvals, include_rf)} |
789
+ | Gradient Boosting | {'βœ…' if include_gb else '❌ skipped'} | {_ns(gb_pvals, include_gb)} |
790
+
791
+ **Consensus (β‰₯2 models):** {gwas_df['Consensus_Sig'].sum()} markers
792
+
793
+ ### LD Summary
794
+ Mean rΒ² = **{ld_r2_mean:.3f}** | Mean D' = **{ld_dp_mean:.3f}**
795
+
796
+ ### Top 10 Markers (LR P-value)
797
+ {_df_to_md(gwas_df.head(10)[top10_cols])}
798
  """
799
+ return (summary, man_path, ld_path, comp_path, zip_path)
800
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
801
  except Exception as e:
802
  import traceback
803
+ return (
804
+ f"## ❌ Error\n```\n{e}\n\n{traceback.format_exc()}\n```",
805
+ None, None, None, None
806
+ )
807
+
808
 
809
  # ══════════════════════════════════════════════════════════════
810
  # GRADIO UI
811
  # ══════════════════════════════════════════════════════════════
812
 
813
+ custom_css = """
814
+ .gradio-container { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; }
815
+ h1 { color: #2c3e50; border-bottom: 3px solid #8B5CF6; padding-bottom: 10px; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
816
  """
817
 
818
+ with gr.Blocks(css=custom_css, title="MTA Analysis Tool v7.1") as app:
819
+
820
  gr.Markdown("""
821
+ # 🧬 Enhanced MTA / GWAS Analysis v7.1
822
+ ### Multi-Model Genomic Marker Discovery Platform
823
+ Upload your CSV file, configure options, and click **Run**.
824
  ---
825
  """)
826
+
827
  with gr.Row():
828
  with gr.Column(scale=1):
 
829
  gr.Markdown("""
830
+ ### πŸ“‹ CSV Format
831
+ ```
832
+ ID, Phenotype, M1, M2, M3, ...
833
+ -, Chr, 1, 1, 2, ... ← chromosome row
834
+ S001, 45.2, 0, 1, 2, ...
835
+ S002, 38.7, 1, 0, 1, ...
836
+ ```
837
+ Genotype values: **0 / 1 / 2** (missing = blank or -1)
838
  """)
839
+ input_file = gr.File(label="Upload CSV", file_types=[".csv"])
840
+ target_markers = gr.Slider(100, 5000, value=3000, step=100,
841
+ label="Target markers for modelling")
842
+
 
 
843
  with gr.Column(scale=1):
844
+ gr.Markdown("### βš™οΈ QC Filters")
845
+ miss_rate_sample = gr.Slider(5, 100, value=20, step=5,
846
+ label="Max sample missing rate (%)")
847
+ miss_rate_marker = gr.Slider(5, 100, value=20, step=5,
848
+ label="Max marker missing rate (%)")
849
+ maf_thresh = gr.Slider(0, 25, value=5, step=1,
850
+ label="Min MAF (%)")
851
+
852
+ gr.Markdown("### πŸ”¬ Optional Models *(slower)*")
853
+ include_mlm = gr.Checkbox(label="Mixed Linear Model", value=False)
854
+ include_enet = gr.Checkbox(label="ElasticNet", value=True)
855
+ include_rf = gr.Checkbox(label="Random Forest", value=False)
856
+ include_gb = gr.Checkbox(label="Gradient Boosting", value=False)
857
+
858
+ run_button = gr.Button("πŸš€ Run Analysis", variant="primary", size="lg")
859
+
860
  gr.Markdown("---")
861
+
 
 
 
 
 
 
862
  with gr.Row():
863
+ summary_output = gr.Markdown(label="Summary")
864
+
 
865
  with gr.Row():
866
+ manhattan_output = gr.Image(label="Manhattan + LOD")
867
+
 
868
  with gr.Row():
869
+ ld_output = gr.Image(label="LD Decay")
870
+ comparison_output = gr.Image(label="Model Comparison")
871
+
872
  with gr.Row():
873
+ download_output = gr.File(label="πŸ“¦ Download ZIP")
874
+
875
+ gr.Markdown("""
876
+ ---
877
+ **Created by Ashmi** | MTA Analysis Tool v7.1
878
+ """)
879
+
880
+ run_button.click(
881
+ fn=run_mta_analysis,
882
+ inputs=[input_file, target_markers,
883
+ miss_rate_sample, miss_rate_marker, maf_thresh,
884
+ include_mlm, include_enet, include_rf, include_gb],
885
+ outputs=[summary_output, manhattan_output, ld_output,
886
+ comparison_output, download_output]
 
 
 
 
 
887
  )
 
 
 
 
 
 
 
 
 
888
 
889
  if __name__ == "__main__":
890
+ app.launch(share=False, show_error=True)