softwareDevelopment commited on
Commit
35fa1f1
·
verified ·
1 Parent(s): 7c0d438

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +71 -1470
app.py CHANGED
@@ -1,1470 +1,71 @@
1
- # -*- coding: utf-8 -*-
2
- """
3
- MTA GWAS Analysis Tool v11.0 — FULLY FIXED EDITION
4
- =====================================================
5
- FIXES:
6
- ✅ LD Decay: Proper Hill-Weir (1988) model with population size estimation
7
- ✅ Model selection: All models work correctly (GLM, MLM, CMLM, BSLMM, FarmCPU)
8
- ✅ Manhattan plot model switching: Dropdown now properly updates plots
9
- ✅ Matrix dimensionality: Fixed all linear algebra operations
10
- ✅ BSLMM: Fixed cross-validation and bootstrapping
11
- ✅ FarmCPU: Fixed iterative conditioning
12
- ✅ ALL plots: White background, black/dark text
13
- """
14
-
15
- import gradio as gr
16
- import pandas as pd
17
- import numpy as np
18
- import matplotlib
19
- matplotlib.use('Agg')
20
- import matplotlib.pyplot as plt
21
- import matplotlib.patches as mpatches
22
- from matplotlib.gridspec import GridSpec
23
- from matplotlib.colors import LinearSegmentedColormap
24
- from scipy import stats
25
- from scipy.optimize import curve_fit, minimize_scalar
26
- import os, warnings, zipfile
27
- from pathlib import Path
28
- from sklearn.linear_model import ElasticNetCV, RidgeCV
29
- from sklearn.preprocessing import StandardScaler
30
- from sklearn.decomposition import PCA
31
- from sklearn.cluster import KMeans
32
- from sklearn.covariance import LedoitWolf
33
- warnings.filterwarnings('ignore')
34
-
35
- OUTPUT_DIR = Path("/tmp/gwas_outputs")
36
- OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
37
-
38
- # ══════════════════════════════════════════════════════════════
39
- # UNIVERSAL WHITE THEME
40
- # ══════════════════════════════════════════════════════════════
41
- W_BG = "#FFFFFF"
42
- W_PANEL = "#F8FAFC"
43
- W_GRID = "#DEE2E8"
44
- W_TEXT = "#1A202C"
45
- W_SUBTEXT = "#4A5568"
46
- W_BORDER = "#CBD5E0"
47
- W_ACCENT = "#2B6CB0"
48
- W_RED = "#C53030"
49
- W_GOLD = "#B7791F"
50
- W_GREEN = "#276749"
51
- W_ORANGE = "#C05621"
52
- W_PURPLE = "#553C9A"
53
-
54
- CHROM_COLORS = [
55
- "#1565C0","#2E7D32","#C62828","#F57F17","#6A1B9A",
56
- "#00695C","#AD1457","#4527A0","#0277BD","#558B2F",
57
- "#E65100","#37474F","#880E4F","#1B5E20","#BF360C",
58
- "#0D47A1","#33691E","#827717","#4A148C","#006064",
59
- ]
60
-
61
- MODEL_COLORS = {
62
- 'GLM': '#1565C0',
63
- 'MLM': '#C62828',
64
- 'CMLM': '#2E7D32',
65
- 'BSLMM': '#F57F17',
66
- 'FarmCPU': '#6A1B9A',
67
- }
68
-
69
- def _style_white():
70
- plt.rcParams.update({
71
- 'figure.facecolor': W_BG,
72
- 'axes.facecolor': W_PANEL,
73
- 'axes.edgecolor': W_BORDER,
74
- 'axes.labelcolor': W_TEXT,
75
- 'axes.titlecolor': W_TEXT,
76
- 'xtick.color': W_TEXT,
77
- 'ytick.color': W_TEXT,
78
- 'text.color': W_TEXT,
79
- 'grid.color': W_GRID,
80
- 'grid.linewidth': 0.6,
81
- 'figure.dpi': 120,
82
- 'font.family': 'DejaVu Sans',
83
- 'font.size': 10,
84
- 'axes.titlesize': 12,
85
- 'axes.labelsize': 11,
86
- 'axes.spines.top': False,
87
- 'axes.spines.right': False,
88
- })
89
-
90
- # ══════════════════════════════════════════════════════════════
91
- # CSV PARSER
92
- # ══════════════════════════════════════════════════════════════
93
- def parse_input_csv(filepath):
94
- df = pd.read_csv(filepath, header=0, dtype=str)
95
- marker_cols = df.columns[2:].tolist()
96
- chr_row = df.iloc[0]
97
- pos_row = df.iloc[1]
98
- chrom_dict, pos_dict = {}, {}
99
- for m in marker_cols:
100
- cv = str(chr_row[m]).strip()
101
- cv = cv[:-2] if cv.endswith('.0') else cv
102
- cv = cv.replace('chr','').replace('Chr','').strip()
103
- chrom_dict[m] = cv if cv not in ('', 'nan', '-') else '0'
104
- pv_s = str(pos_row[m]).strip()
105
- try:
106
- pos_dict[m] = float(pv_s)
107
- except ValueError:
108
- parts = m.split('_')
109
- bp = 0.0
110
- for part in parts:
111
- try:
112
- cand = float(part)
113
- if cand > 1000:
114
- bp = cand
115
- break
116
- except ValueError:
117
- continue
118
- pos_dict[m] = bp
119
-
120
- df_s = df.iloc[2:].reset_index(drop=True)
121
- sample_ids = df_s.iloc[:, 0].astype(str).values
122
- phenotypes = pd.to_numeric(df_s.iloc[:, 1], errors='coerce').values
123
- geno_raw = (df_s[marker_cols]
124
- .apply(pd.to_numeric, errors='coerce')
125
- .replace(-1, np.nan)
126
- .where(lambda x: x.isin([0, 1, 2]) | x.isna(), other=np.nan))
127
- chromosomes = [chrom_dict[m] for m in marker_cols]
128
- positions = [pos_dict[m] for m in marker_cols]
129
- return (sample_ids, phenotypes,
130
- geno_raw.values, marker_cols, chromosomes, positions)
131
-
132
- # ══════════════════════════════════════════════════════════════
133
- # KINSHIP MATRIX (Corrected)
134
- # ══════════════════════════════════════════════════════════════
135
- def compute_kinship(G):
136
- """Compute kinship matrix using the formula K = (GG^T)/p"""
137
- X = G.astype(float).copy()
138
- # Center genotypes (0/1/2 -> -2p, 1-2p, 2-2p)
139
- p_hat = np.nanmean(X, axis=0) / 2.0
140
- p_hat = np.clip(p_hat, 0.01, 0.99)
141
- X_centered = X - 2 * p_hat
142
-
143
- # Impute missing with mean
144
- for i in range(X_centered.shape[1]):
145
- col = X_centered[:, i]
146
- nan_mask = np.isnan(col)
147
- if nan_mask.any():
148
- col[nan_mask] = np.nanmean(col)
149
- X_centered[:, i] = col
150
-
151
- # Kinship matrix
152
- K = np.dot(X_centered, X_centered.T) / X_centered.shape[1]
153
-
154
- # Scale to have mean diagonal ~1
155
- d = np.mean(np.diag(K))
156
- if d > 0:
157
- K = K / d
158
-
159
- # Ensure positive definite
160
- min_eig = np.min(np.linalg.eigvalsh(K))
161
- if min_eig < 0:
162
- K = K + np.eye(K.shape[0]) * (-min_eig + 1e-6)
163
-
164
- return K
165
-
166
- # ══════════════════════════════════════════════════════════════
167
- # MODELS (All Fixed)
168
- # ══════════════════════════════════════════════════════════════
169
-
170
- def model_glm(G, y):
171
- """General Linear Model - Simple linear regression per marker"""
172
- n, m = G.shape
173
- pv = np.ones(m)
174
- bv = np.zeros(m)
175
- sv = np.zeros(m)
176
- rv = np.zeros(m)
177
-
178
- # Center phenotype
179
- y_centered = y - np.mean(y)
180
-
181
- for i in range(m):
182
- x = G[:, i]
183
- nan_mask = np.isnan(x)
184
- if nan_mask.any():
185
- x = x.copy()
186
- x[nan_mask] = np.nanmean(x)
187
-
188
- if np.std(x) < 1e-9:
189
- continue
190
-
191
- # Linear regression
192
- x_centered = x - np.mean(x)
193
- cov = np.sum(x_centered * y_centered)
194
- var_x = np.sum(x_centered * x_centered)
195
-
196
- if var_x < 1e-12:
197
- continue
198
-
199
- b = cov / var_x
200
- y_pred = b * x_centered
201
- resid = y_centered - y_pred
202
- sse = np.sum(resid * resid)
203
- df = n - 2
204
-
205
- if df > 0 and sse > 0:
206
- se = np.sqrt(sse / df / var_x)
207
- t_stat = b / (se + 1e-12)
208
- p = 2 * stats.t.sf(np.abs(t_stat), df=df)
209
- r2 = cov * cov / (var_x * np.sum(y_centered * y_centered) + 1e-12)
210
-
211
- pv[i] = max(p, 1e-300) if np.isfinite(p) else 1.0
212
- bv[i] = b
213
- sv[i] = se
214
- rv[i] = r2
215
-
216
- return pv, bv, sv, rv
217
-
218
- def model_mlm(G, y, K, n_pc=5):
219
- """Mixed Linear Model with kinship as random effect"""
220
- n = len(y)
221
- n_pc = min(n_pc, n - 2, G.shape[1] // 10)
222
-
223
- # Get eigenvectors of kinship for PCs
224
- eigvals, eigvecs = np.linalg.eigh(K)
225
- idx = np.argsort(eigvals)[::-1]
226
- Q = eigvecs[:, idx[:max(1, n_pc)]]
227
-
228
- # Project out PCs (fixed effects)
229
- Q_pinv = np.linalg.pinv(Q)
230
- y_resid = y - Q @ (Q_pinv @ y)
231
-
232
- m = G.shape[1]
233
- pv = np.ones(m)
234
- bv = np.zeros(m)
235
- sv = np.zeros(m)
236
- rv = np.zeros(m)
237
-
238
- for i in range(m):
239
- x = G[:, i]
240
- nan_mask = np.isnan(x)
241
- if nan_mask.any():
242
- x = x.copy()
243
- x[nan_mask] = np.nanmean(x)
244
-
245
- if np.std(x) < 1e-9:
246
- continue
247
-
248
- # Project out PCs from genotype
249
- x_resid = x - Q @ (Q_pinv @ x)
250
-
251
- if np.std(x_resid) < 1e-9:
252
- continue
253
-
254
- # Regression on residuals
255
- xc = x_resid - np.mean(x_resid)
256
- yc = y_resid - np.mean(y_resid)
257
- cov = np.sum(xc * yc)
258
- var_x = np.sum(xc * xc)
259
-
260
- if var_x < 1e-12:
261
- continue
262
-
263
- b = cov / var_x
264
- y_pred = b * xc
265
- resid = yc - y_pred
266
- sse = np.sum(resid * resid)
267
- df = n - n_pc - 2
268
-
269
- if df > 0 and sse > 0:
270
- se = np.sqrt(sse / df / var_x)
271
- t_stat = b / (se + 1e-12)
272
- p = 2 * stats.t.sf(np.abs(t_stat), df=df)
273
- r2 = cov * cov / (var_x * np.sum(yc * yc) + 1e-12)
274
-
275
- pv[i] = max(p, 1e-300) if np.isfinite(p) else 1.0
276
- bv[i] = b
277
- sv[i] = se
278
- rv[i] = r2
279
-
280
- return pv, bv, sv, rv
281
-
282
- def model_cmlm(G, y, K, n_groups=None, n_pc=5):
283
- """Compressed MLM - groups individuals into clusters"""
284
- n = len(y)
285
-
286
- # Get compression groups via KMeans on kinship PCs
287
- eigvals, eigvecs = np.linalg.eigh(K)
288
- idx = np.argsort(eigvals)[::-1]
289
- emb = eigvecs[:, idx[:min(10, n-1)]]
290
-
291
- if n_groups is None:
292
- n_groups = max(2, min(20, n // 10))
293
-
294
- n_groups = min(n_groups, n - 1)
295
- km = KMeans(n_clusters=n_groups, random_state=42, n_init=5)
296
- labels = km.fit_predict(emb)
297
-
298
- # Create group indicator matrix
299
- Q = np.zeros((n, n_groups))
300
- for g in range(n_groups):
301
- Q[:, g] = (labels == g).astype(float)
302
-
303
- # Normalize
304
- col_sum = Q.sum(axis=0)
305
- col_sum[col_sum == 0] = 1
306
- Q = Q / col_sum
307
-
308
- # Project out group effects
309
- Q_pinv = np.linalg.pinv(Q)
310
- y_resid = y - Q @ (Q_pinv @ y)
311
-
312
- m = G.shape[1]
313
- pv = np.ones(m)
314
- bv = np.zeros(m)
315
- sv = np.zeros(m)
316
- rv = np.zeros(m)
317
-
318
- for i in range(m):
319
- x = G[:, i]
320
- nan_mask = np.isnan(x)
321
- if nan_mask.any():
322
- x = x.copy()
323
- x[nan_mask] = np.nanmean(x)
324
-
325
- if np.std(x) < 1e-9:
326
- continue
327
-
328
- # Project out group effects from genotype
329
- x_resid = x - Q @ (Q_pinv @ x)
330
-
331
- if np.std(x_resid) < 1e-9:
332
- continue
333
-
334
- xc = x_resid - np.mean(x_resid)
335
- yc = y_resid - np.mean(y_resid)
336
- cov = np.sum(xc * yc)
337
- var_x = np.sum(xc * xc)
338
-
339
- if var_x < 1e-12:
340
- continue
341
-
342
- b = cov / var_x
343
- y_pred = b * xc
344
- resid = yc - y_pred
345
- sse = np.sum(resid * resid)
346
- df = n - n_groups - 2
347
-
348
- if df > 0 and sse > 0:
349
- se = np.sqrt(sse / df / var_x)
350
- t_stat = b / (se + 1e-12)
351
- p = 2 * stats.t.sf(np.abs(t_stat), df=df)
352
- r2 = cov * cov / (var_x * np.sum(yc * yc) + 1e-12)
353
-
354
- pv[i] = max(p, 1e-300) if np.isfinite(p) else 1.0
355
- bv[i] = b
356
- sv[i] = se
357
- rv[i] = r2
358
-
359
- return pv, bv, sv, rv
360
-
361
- def model_bslmm(G, y, n_boot=8):
362
- """Bayesian Sparse Linear Mixed Model using Elastic Net + Bootstrap"""
363
- n, m = G.shape
364
-
365
- # Standardize genotypes
366
- scaler = StandardScaler()
367
- X_scaled = scaler.fit_transform(G)
368
- X_scaled = np.nan_to_num(X_scaled, nan=0.0)
369
-
370
- # Use Ridge for large m, ElasticNet for smaller
371
- if m > 5000:
372
- # Ridge regression with cross-validation
373
- alphas = np.logspace(-4, 4, 20)
374
- model = RidgeCV(alphas=alphas, cv=min(5, n//2))
375
- model.fit(X_scaled, y)
376
- coef = model.coef_
377
- else:
378
- # Elastic Net with cross-validation
379
- model = ElasticNetCV(
380
- cv=min(5, n//2),
381
- random_state=42,
382
- max_iter=2000,
383
- n_jobs=-1,
384
- l1_ratio=[0.1, 0.5, 0.7, 0.9, 1.0]
385
- )
386
- model.fit(X_scaled, y)
387
- coef = model.coef_
388
-
389
- # Bootstrap for standard errors and p-values
390
- boots = []
391
- rng = np.random.default_rng(42)
392
-
393
- for _ in range(n_boot):
394
- idx = rng.choice(n, n, replace=True)
395
- try:
396
- if m > 5000:
397
- boot_model = RidgeCV(alphas=alphas, cv=min(3, n//2))
398
- else:
399
- boot_model = ElasticNetCV(
400
- cv=min(3, n//2),
401
- random_state=42,
402
- max_iter=1000,
403
- l1_ratio=[0.1, 0.5, 0.9, 1.0]
404
- )
405
- boot_model.fit(X_scaled[idx], y[idx])
406
- boots.append(boot_model.coef_)
407
- except:
408
- boots.append(coef.copy())
409
-
410
- boot_arr = np.array(boots)
411
- pv = np.ones(m)
412
- se = np.zeros(m)
413
-
414
- for i in range(m):
415
- boot_se = np.std(boot_arr[:, i])
416
- if boot_se > 0:
417
- se[i] = boot_se
418
- z = np.abs(coef[i]) / (boot_se + 1e-12)
419
- pv[i] = max(2 * (1 - stats.norm.cdf(z)), 1e-300)
420
-
421
- return pv, coef, se
422
-
423
- def model_farmcpu(G, y, K, max_iter=3):
424
- """FarmCPU: Fixed and Random model Circulating Probability Unification"""
425
- n, m = G.shape
426
- n_pc = min(5, n - 2)
427
-
428
- # Get PCs from kinship
429
- eigvals, eigvecs = np.linalg.eigh(K)
430
- idx = np.argsort(eigvals)[::-1]
431
- PCs = eigvecs[:, idx[:n_pc]]
432
-
433
- # Initial GLM
434
- pv, bv, sv, rv = model_glm(G, y)
435
-
436
- for iteration in range(max_iter):
437
- # Select top markers as pseudo-QTNs
438
- n_qtns = max(2, min(20, int(m * 0.002)))
439
- top_idx = np.argsort(pv)[:n_qtns]
440
-
441
- # Build covariate matrix with PCs and selected markers
442
- covariates = [PCs]
443
- for idx_qtn in top_idx:
444
- x = G[:, idx_qtn]
445
- nan_mask = np.isnan(x)
446
- if nan_mask.any():
447
- x = x.copy()
448
- x[nan_mask] = np.nanmean(x)
449
- covariates.append(x.reshape(-1, 1))
450
-
451
- X_cov = np.hstack(covariates)
452
-
453
- # Fit full model
454
- try:
455
- beta = np.linalg.lstsq(X_cov, y, rcond=None)[0]
456
- y_resid = y - X_cov @ beta
457
- except:
458
- y_resid = y.copy()
459
-
460
- # Re-compute p-values conditioned on pseudo-QTNs
461
- df = max(n - X_cov.shape[1] - 1, 1)
462
-
463
- for i in range(m):
464
- if i in top_idx:
465
- continue
466
-
467
- x = G[:, i]
468
- nan_mask = np.isnan(x)
469
- if nan_mask.any():
470
- x = x.copy()
471
- x[nan_mask] = np.nanmean(x)
472
-
473
- if np.std(x) < 1e-9:
474
- continue
475
-
476
- # Simple regression on residuals
477
- xc = x - np.mean(x)
478
- yc = y_resid - np.mean(y_resid)
479
- cov = np.sum(xc * yc)
480
- var_x = np.sum(xc * xc)
481
-
482
- if var_x < 1e-12:
483
- continue
484
-
485
- b = cov / var_x
486
- y_pred = b * xc
487
- sse = np.sum((yc - y_pred) ** 2)
488
-
489
- if sse > 0 and df > 0:
490
- se_b = np.sqrt(sse / df / var_x)
491
- t_stat = b / (se_b + 1e-12)
492
- p = 2 * stats.t.sf(np.abs(t_stat), df=df)
493
- pv[i] = max(p, 1e-300) if np.isfinite(p) else 1.0
494
- bv[i] = b
495
- sv[i] = se_b
496
-
497
- return pv, bv, sv
498
-
499
- # ══════════════════════════════════════════════════════════════
500
- # LD DECAY - FIXED: Proper Hill-Weir (1988) Model
501
- # ══════════════════════════════════════════════════════════════
502
-
503
- def hill_weir_model(d, Ne, c=1.0):
504
- """
505
- Hill-Weir (1988) model for LD decay:
506
- E(r²) = 1 / (1 + 4 * Ne * c * d)
507
- where d is distance in Morgans, Ne is effective population size
508
- """
509
- return 1.0 / (1.0 + 4 * Ne * c * d)
510
-
511
- def compute_r2_pair(x, y):
512
- """Compute r² between two genotype vectors"""
513
- # Remove NaNs
514
- mask = ~(np.isnan(x) | np.isnan(y))
515
- if mask.sum() < 10:
516
- return 0.0
517
- x_clean = x[mask]
518
- y_clean = y[mask]
519
-
520
- # Compute correlation
521
- corr = np.corrcoef(x_clean, y_clean)[0, 1]
522
- if np.isnan(corr):
523
- return 0.0
524
- return corr ** 2
525
-
526
- def compute_ld_decay_sweep(genotypes, positions, max_dist_mb=10):
527
- """
528
- Compute LD decay across all chromosomes as a single sweep.
529
- Returns distances (Mb) and r² values.
530
- """
531
- all_dist = []
532
- all_r2 = []
533
-
534
- # Convert positions to Mb
535
- pos_mb = np.array(positions, dtype=float) / 1_000_000.0
536
-
537
- # Limit to reasonable number of pairs
538
- n_markers = genotypes.shape[1]
539
- max_pairs = min(50000, n_markers * (n_markers - 1) // 2)
540
- sample_rate = max(1, (n_markers * (n_markers - 1) // 2) // max_pairs)
541
-
542
- # Sample marker pairs
543
- rng = np.random.RandomState(42)
544
- pairs_sampled = 0
545
-
546
- for i in range(0, n_markers, max(1, sample_rate)):
547
- for j in range(i + 1, min(i + sample_rate * 10, n_markers)):
548
- # Only consider pairs within max distance
549
- dist = abs(pos_mb[j] - pos_mb[i])
550
- if dist > max_dist_mb:
551
- continue
552
-
553
- # Compute r²
554
- r2 = compute_r2_pair(genotypes[:, i], genotypes[:, j])
555
-
556
- all_dist.append(dist)
557
- all_r2.append(r2)
558
- pairs_sampled += 1
559
-
560
- if pairs_sampled >= max_pairs:
561
- break
562
-
563
- if pairs_sampled >= max_pairs:
564
- break
565
-
566
- return np.array(all_dist), np.array(all_r2)
567
-
568
- def plot_ld_decay(genotypes, chromosomes, positions, save_path):
569
- """Plot LD decay with proper Hill-Weir model fitting"""
570
- _style_white()
571
-
572
- # Compute LD sweep
573
- dist, r2 = compute_ld_decay_sweep(genotypes, positions, max_dist_mb=10)
574
-
575
- if len(dist) == 0:
576
- fig, ax = plt.subplots(figsize=(10, 6), facecolor=W_BG)
577
- ax.set_facecolor(W_PANEL)
578
- ax.text(0.5, 0.5, 'No LD pairs computed (need more markers)',
579
- ha='center', va='center', transform=ax.transAxes, fontsize=13)
580
- plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=W_BG)
581
- plt.close(fig)
582
- return {}, "No LD data available"
583
-
584
- # Bin data for fitting
585
- bins = np.linspace(0, min(10, np.percentile(dist, 98)), 50)
586
- bin_centers = []
587
- bin_means = []
588
- bin_stds = []
589
-
590
- for i in range(len(bins) - 1):
591
- mask = (dist >= bins[i]) & (dist < bins[i+1])
592
- if mask.sum() >= 5:
593
- bin_centers.append((bins[i] + bins[i+1]) / 2)
594
- bin_means.append(np.mean(r2[mask]))
595
- bin_stds.append(np.std(r2[mask]))
596
-
597
- bin_centers = np.array(bin_centers)
598
- bin_means = np.array(bin_means)
599
- bin_stds = np.array(bin_stds)
600
-
601
- # Fit Hill-Weir model
602
- fit_ok = False
603
- Ne_fit = 100
604
- r2_start = 0.5
605
- half_decay = 1.0
606
-
607
- if len(bin_centers) >= 5:
608
- try:
609
- # Fit for Ne (effective population size)
610
- def objective(Ne):
611
- pred = hill_weir_model(bin_centers, Ne)
612
- return np.sum(((bin_means - pred) / (bin_stds + 0.01)) ** 2)
613
-
614
- result = minimize_scalar(objective, bounds=(1, 10000), method='bounded')
615
- Ne_fit = result.x
616
- fit_ok = True
617
-
618
- # Get fitted curve
619
- dist_fit = np.linspace(0, min(10, bin_centers[-1]), 200)
620
- r2_fit = hill_weir_model(dist_fit, Ne_fit)
621
-
622
- # Calculate half-decay distance
623
- r2_start = hill_weir_model(0, Ne_fit)
624
- half_idx = np.where(r2_fit <= r2_start / 2)[0]
625
- if len(half_idx) > 0:
626
- half_decay = dist_fit[half_idx[0]]
627
-
628
- except:
629
- # Fallback to exponential decay
630
- try:
631
- def exp_decay(d, a, b):
632
- return a * np.exp(-b * d)
633
- popt, _ = curve_fit(exp_decay, bin_centers, bin_means,
634
- p0=[0.5, 1.0], maxfev=5000)
635
- dist_fit = np.linspace(0, bin_centers[-1], 200)
636
- r2_fit = exp_decay(dist_fit, *popt)
637
- r2_start = popt[0]
638
- half_decay = np.log(2) / popt[1] if popt[1] > 0 else 1.0
639
- fit_ok = True
640
- except:
641
- pass
642
-
643
- # Create figure
644
- fig = plt.figure(figsize=(12, 8), facecolor=W_BG)
645
- gs = GridSpec(2, 1, figure=fig, height_ratios=[3, 1], hspace=0.08)
646
-
647
- # Main plot
648
- ax = fig.add_subplot(gs[0])
649
- ax.set_facecolor(W_PANEL)
650
-
651
- # Scatter plot (subsampled for visibility)
652
- sample_rate = max(1, len(dist) // 5000)
653
- ax.scatter(dist[::sample_rate], r2[::sample_rate],
654
- c=W_ACCENT, s=3, alpha=0.3, linewidths=0, zorder=1)
655
-
656
- # Binned means with error bars
657
- if len(bin_centers) > 0:
658
- ax.errorbar(bin_centers, bin_means, yerr=bin_stds,
659
- fmt='o', color=W_RED, capsize=3,
660
- markersize=6, elinewidth=1.5, capthick=1.5,
661
- label='Binned mean ± SD', zorder=3)
662
-
663
- # Fitted curve
664
- if fit_ok and 'dist_fit' in locals():
665
- ax.plot(dist_fit, r2_fit, color=W_GREEN, lw=2.5,
666
- label=f'Hill-Weir fit (Ne = {Ne_fit:.0f})', zorder=4)
667
-
668
- # Mark half-decay
669
- ax.axvline(half_decay, color=W_ORANGE, ls='--', lw=1.5, alpha=0.8)
670
- ax.axhline(r2_start / 2, color=W_ORANGE, ls='--', lw=1.5, alpha=0.8)
671
- ax.text(half_decay + 0.05, r2_start / 2 + 0.02,
672
- f'Half-decay: {half_decay:.2f} Mb',
673
- fontsize=9, color=W_ORANGE, fontweight='bold')
674
-
675
- # Reference lines
676
- ax.axhline(0.2, color=W_GOLD, ls=':', lw=1.2, alpha=0.7, label='r² = 0.2')
677
- ax.axhline(0.1, color=W_PURPLE, ls=':', lw=1.2, alpha=0.7, label='r² = 0.1')
678
-
679
- ax.set_xlim(0, min(10, np.percentile(dist, 98) * 1.05))
680
- ax.set_ylim(-0.02, 1.02)
681
- ax.set_xlabel('Distance (Mb)', fontweight='bold', fontsize=12)
682
- ax.set_ylabel('Linkage Disequilibrium (r²)', fontweight='bold', fontsize=12)
683
- ax.set_title('Linkage Disequilibrium Decay Analysis',
684
- fontweight='bold', fontsize=14, color=W_ACCENT)
685
- ax.legend(loc='upper right', fontsize=9)
686
- ax.grid(True, color=W_GRID, lw=0.5, alpha=0.7)
687
-
688
- # Interpretation panel
689
- ax_text = fig.add_subplot(gs[1])
690
- ax_text.axis('off')
691
- ax_text.set_facecolor(W_BG)
692
-
693
- n_pairs = len(dist)
694
- mean_r2 = np.mean(r2)
695
- r2_lt_02 = np.mean(r2 < 0.2) * 100
696
-
697
- if fit_ok:
698
- interp_text = f"""
699
- LD DECAY INTERPRETATION
700
- ─────────────────────────────────────────────────────────────
701
- • Model: Hill-Weir (1988) E(r²) = 1/(1 + 4·Nₑ·c·d)
702
- • Estimated effective population size (Nₑ): {Ne_fit:.0f}
703
- • Half-decay distance (r² = {r2_start/2:.3f}): {half_decay:.3f} Mb
704
- • Mean r² across all pairs: {mean_r2:.4f}
705
- • Pairs with r² < 0.2: {r2_lt_02:.1f}%
706
- • Total pairs analysed: {n_pairs:,}
707
-
708
- Interpretation:
709
- - LD decays { 'rapidly' if half_decay < 0.5 else 'moderately' if half_decay < 2 else 'slowly' }
710
- - { 'Low' if r2_lt_02 > 70 else 'Moderate' if r2_lt_02 > 50 else 'High' } genome-wide LD
711
- """
712
- else:
713
- interp_text = f"""
714
- LD DECAY SUMMARY
715
- ─────────────────────────────────────────────────────────────
716
- • Mean r² across all pairs: {mean_r2:.4f}
717
- • Pairs with r² < 0.2: {r2_lt_02:.1f}%
718
- • Total pairs analysed: {n_pairs:,}
719
-
720
- Note: Model fitting failed - insufficient data or poor convergence.
721
- """
722
-
723
- ax_text.text(0.02, 0.95, interp_text, transform=ax_text.transAxes,
724
- fontsize=9, fontfamily='monospace', va='top',
725
- bbox=dict(boxstyle='round,pad=0.5', facecolor=W_PANEL,
726
- edgecolor=W_BORDER, alpha=0.95))
727
-
728
- plt.tight_layout()
729
- plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=W_BG)
730
- plt.close(fig)
731
-
732
- # Return stats
733
- stats_dict = {
734
- 'n_pairs': n_pairs,
735
- 'mean_r2': mean_r2,
736
- 'r2_lt_02_pct': r2_lt_02,
737
- 'half_decay_mb': half_decay if fit_ok else None,
738
- 'estimated_Ne': Ne_fit if fit_ok else None
739
- }
740
-
741
- return stats_dict, interp_text
742
-
743
- # ══════════════════════════════════════════════════════════════
744
- # MANHATTAN PLOT with proper X-axis positioning
745
- # ══════════════════════════════════════════════════════════════
746
-
747
- def build_x_positions(markers, chromosomes):
748
- """Build x-axis positions for Manhattan plot"""
749
- unique_chroms = sorted(set(chromosomes),
750
- key=lambda x: (int(x) if str(x).isdigit() else 999, str(x)))
751
-
752
- chrom_to_idx = {}
753
- for i, c in enumerate(chromosomes):
754
- chrom_to_idx.setdefault(c, []).append(i)
755
-
756
- GAP = max(8, len(markers) // 150)
757
- x_pos = np.zeros(len(markers))
758
- chrom_ticks = []
759
- offset = 0
760
-
761
- for ch in unique_chroms:
762
- idxs = chrom_to_idx.get(ch, [])
763
- if not idxs:
764
- continue
765
- for pos, idx in enumerate(idxs):
766
- x_pos[idx] = offset + pos
767
- chrom_ticks.append((offset + len(idxs) / 2, str(ch)))
768
- offset += len(idxs) + GAP
769
-
770
- return x_pos, chrom_ticks, offset, GAP, unique_chroms, chrom_to_idx
771
-
772
- def plot_manhattan_single(markers, chromosomes, pv, model_name, bonf_thresh, lod_thresh_user, save_path):
773
- """Plot Manhattan with both -log10(P) and LOD panels"""
774
- _style_white()
775
-
776
- LOD_FACTOR = np.log10(np.e) / 2.0
777
- x_pos, chrom_ticks, offset, GAP, unique_chroms, chrom_to_idx = build_x_positions(markers, chromosomes)
778
-
779
- bonf_log = -np.log10(bonf_thresh)
780
- bonf_lod = bonf_log * LOD_FACTOR
781
- sug_log = 3.0
782
- sug_lod = sug_log * LOD_FACTOR
783
-
784
- log_p = -np.log10(np.clip(pv, 1e-300, 1))
785
- lod = log_p * LOD_FACTOR
786
- sig_mask = pv < bonf_thresh
787
-
788
- fig, axes = plt.subplots(2, 1, figsize=(18, 10), facecolor=W_BG,
789
- sharex=True, gridspec_kw={'height_ratios': [1, 1], 'hspace': 0.08})
790
-
791
- fig.suptitle(f'GWAS Manhattan Plot — {model_name}',
792
- fontsize=15, fontweight='bold', color=W_TEXT, y=1.01)
793
-
794
- # Plot both panels
795
- for ax_idx, (ax, values, ylabel, bonf_line, sug_line, user_line, user_label) in enumerate([
796
- (axes[0], log_p, '-log₁₀(P)', bonf_log, sug_log, bonf_log, f'Bonferroni ({bonf_log:.2f})'),
797
- (axes[1], lod, 'LOD Score', bonf_lod, sug_lod, lod_thresh_user, f'LOD threshold ({lod_thresh_user:.1f})'),
798
- ]):
799
- ax.set_facecolor(W_PANEL)
800
-
801
- # Plot by chromosome
802
- for ci, ch in enumerate(unique_chroms):
803
- idxs = chrom_to_idx.get(ch, [])
804
- if not idxs:
805
- continue
806
-
807
- color = CHROM_COLORS[ci % len(CHROM_COLORS)]
808
-
809
- # Background shading for alternate chromosomes
810
- if ci % 2 == 0:
811
- ax.axvspan(x_pos[idxs[0]] - 0.5, x_pos[idxs[-1]] + 0.5,
812
- color='#F0F4F8', alpha=0.7, zorder=0)
813
-
814
- # Non-significant points
815
- nsig_mask = [i for i in idxs if not sig_mask[i]]
816
- if nsig_mask:
817
- ax.scatter(x_pos[nsig_mask], values[nsig_mask],
818
- c=color, s=6, alpha=0.55, linewidths=0, zorder=2)
819
-
820
- # Significant points
821
- sig_idxs = [i for i in idxs if sig_mask[i]]
822
- if sig_idxs:
823
- ax.scatter(x_pos[sig_idxs], values[sig_idxs],
824
- c=W_RED, s=40, alpha=1.0, marker='D',
825
- edgecolors='white', linewidths=0.5, zorder=4)
826
-
827
- # Threshold lines
828
- ax.axhline(bonf_line, color=W_RED, ls='--', lw=1.8, alpha=0.9,
829
- label=f'Bonferroni ({bonf_line:.2f})', zorder=5)
830
- ax.axhline(sug_line, color=W_GOLD, ls=':', lw=1.5, alpha=0.85,
831
- label=f'Suggestive ({sug_line:.2f})', zorder=5)
832
-
833
- if ax_idx == 1 and abs(user_line - bonf_lod) > 0.05:
834
- ax.axhline(user_line, color=W_ORANGE, ls='-.', lw=1.8, alpha=0.9,
835
- label=f'User LOD ({user_line:.1f})', zorder=5)
836
-
837
- y_max = max(values.max() * 1.1, bonf_line * 1.2, 1.0)
838
- ax.set_ylim(0, y_max)
839
- ax.set_ylabel(ylabel, fontweight='bold', fontsize=12)
840
- ax.grid(True, color=W_GRID, lw=0.5, alpha=0.6, axis='y')
841
- ax.legend(loc='upper right', fontsize=8, ncol=3)
842
-
843
- n_sig = sig_mask.sum()
844
- ax.text(0.01, 0.96, f'{n_sig} significant SNPs',
845
- transform=ax.transAxes, fontsize=9, color=W_RED, fontweight='bold',
846
- bbox=dict(boxstyle='round,pad=0.3', fc='#FFF5F5', ec=W_RED, alpha=0.9))
847
-
848
- axes[1].set_xticks([x for x, _ in chrom_ticks])
849
- axes[1].set_xticklabels([l for _, l in chrom_ticks], fontsize=8, fontweight='bold')
850
- axes[1].set_xlabel('Chromosome', fontweight='bold', fontsize=12)
851
- axes[1].set_xlim(-GAP, offset)
852
-
853
- # Model color indicator
854
- mcol = MODEL_COLORS.get(model_name, W_ACCENT)
855
- fig.text(0.01, 0.98, f'● {model_name}', color=mcol, fontsize=11, fontweight='bold', va='top')
856
-
857
- plt.tight_layout(pad=1.0)
858
- plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=W_BG)
859
- plt.close(fig)
860
-
861
- def plot_qq_single(pv, model_name, bonf_thresh, save_path):
862
- """QQ plot with inflation factor"""
863
- _style_white()
864
-
865
- pv = pv[np.isfinite(pv) & (pv > 0) & (pv <= 1)]
866
-
867
- fig, ax = plt.subplots(figsize=(8, 8), facecolor=W_BG)
868
- ax.set_facecolor(W_PANEL)
869
-
870
- if len(pv) == 0:
871
- ax.text(0.5, 0.5, 'No valid p-values', ha='center', va='center', fontsize=14)
872
- plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=W_BG)
873
- plt.close(fig)
874
- return 1.0
875
-
876
- n = len(pv)
877
- obs = -np.log10(np.sort(pv))
878
- exp = -np.log10((np.arange(1, n + 1) - 0.5) / n)
879
-
880
- # 95% confidence interval
881
- ci_lo = -np.log10(stats.beta.ppf(0.025, np.arange(1, n + 1), n - np.arange(1, n + 1) + 1))
882
- ci_hi = -np.log10(stats.beta.ppf(0.975, np.arange(1, n + 1), n - np.arange(1, n + 1) + 1))
883
-
884
- ax.fill_between(exp, ci_lo, ci_hi, color=MODEL_COLORS.get(model_name, W_ACCENT),
885
- alpha=0.15, label='95% CI')
886
-
887
- # Plot points
888
- bonf_line = -np.log10(bonf_thresh)
889
- above_bonf = obs > bonf_line
890
-
891
- if (~above_bonf).any():
892
- ax.scatter(exp[~above_bonf], obs[~above_bonf],
893
- c=MODEL_COLORS.get(model_name, W_ACCENT), s=15, alpha=0.6, linewidths=0)
894
- if above_bonf.any():
895
- ax.scatter(exp[above_bonf], obs[above_bonf],
896
- c=W_RED, s=25, alpha=0.9, marker='D', edgecolors='white', linewidths=0.5)
897
-
898
- # Diagonal line
899
- max_val = max(obs.max(), exp.max()) * 1.05
900
- ax.plot([0, max_val], [0, max_val], color=W_TEXT, ls='--', lw=1.5, alpha=0.8, label='y = x')
901
-
902
- # Genomic inflation factor λ
903
- chi2 = stats.chi2.ppf(1 - pv, df=1)
904
- chi2_median = np.median(chi2)
905
- lam = chi2_median / stats.chi2.ppf(0.5, df=1)
906
-
907
- lam_color = W_RED if lam > 1.1 else W_ORANGE if lam > 1.05 else W_GREEN
908
- ax.text(0.05, 0.95, f'λ = {lam:.4f}', transform=ax.transAxes,
909
- fontsize=16, fontweight='bold', color=lam_color, va='top',
910
- bbox=dict(boxstyle='round,pad=0.4', fc=W_BG, ec=lam_color, alpha=0.9))
911
-
912
- ax.set_xlim(0, max_val)
913
- ax.set_ylim(0, max_val)
914
- ax.set_xlabel('Expected -log₁₀(P)', fontweight='bold', fontsize=12)
915
- ax.set_ylabel('Observed -log₁₀(P)', fontweight='bold', fontsize=12)
916
- ax.set_title(f'QQ Plot — {model_name}', fontweight='bold', fontsize=13)
917
- ax.legend(fontsize=9)
918
- ax.grid(True, color=W_GRID, lw=0.5, alpha=0.6)
919
-
920
- plt.tight_layout()
921
- plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=W_BG)
922
- plt.close(fig)
923
-
924
- return lam
925
-
926
- # ══════════════════════════════════════════════════════════════
927
- # OTHER PLOTS (Phenotype, PCA, etc.)
928
- # ══════════════════════════════════════════════════════════════
929
-
930
- def plot_phenotype(phenotypes, save_path):
931
- _style_white()
932
- pv = phenotypes[~np.isnan(phenotypes)]
933
- fig, axes = plt.subplots(1, 2, figsize=(13, 5), facecolor=W_BG)
934
- fig.suptitle('Phenotype Distribution & Normality', fontsize=14, fontweight='bold')
935
-
936
- # Histogram
937
- ax = axes[0]
938
- ax.set_facecolor(W_PANEL)
939
- ax.hist(pv, bins=min(50, len(pv)//10), color=W_ACCENT, alpha=0.7, edgecolor='white')
940
- ax.axvline(np.mean(pv), color=W_RED, ls='--', lw=2, label=f'Mean = {np.mean(pv):.3f}')
941
- ax.axvline(np.median(pv), color=W_GOLD, ls=':', lw=2, label=f'Median = {np.median(pv):.3f}')
942
- ax.set_xlabel('Phenotype'); ax.set_ylabel('Frequency')
943
- ax.set_title('Histogram'); ax.legend(); ax.grid(True, alpha=0.3)
944
-
945
- # QQ plot
946
- ax = axes[1]
947
- ax.set_facecolor(W_PANEL)
948
- stats.probplot(pv, dist='norm', plot=ax)
949
- ax.set_title('Normal Q-Q'); ax.grid(True, alpha=0.3)
950
-
951
- plt.tight_layout()
952
- plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=W_BG)
953
- plt.close(fig)
954
-
955
- def plot_pca(genotypes, phenotypes, n_components, save_path):
956
- _style_white()
957
- G = np.nan_to_num(genotypes - np.nanmean(genotypes, 0), 0)
958
- n_comp = min(n_components, G.shape[0]-1, G.shape[1])
959
-
960
- pca = PCA(n_components=n_comp)
961
- scores = pca.fit_transform(G)
962
- evr = pca.explained_variance_ratio_ * 100
963
-
964
- fig = plt.figure(figsize=(15, 5), facecolor=W_BG)
965
- gs = GridSpec(1, 3, figure=fig, wspace=0.3)
966
-
967
- # Scree
968
- ax = fig.add_subplot(gs[0])
969
- ax.set_facecolor(W_PANEL)
970
- bars = ax.bar(range(1, n_comp+1), evr, color=W_ACCENT, alpha=0.7)
971
- ax.plot(range(1, n_comp+1), np.cumsum(evr), 'o-', color=W_RED, lw=2, label='Cumulative')
972
- ax.set_xlabel('PC'); ax.set_ylabel('Variance (%)'); ax.set_title('Scree Plot')
973
- ax.legend(); ax.grid(True, alpha=0.3)
974
-
975
- # PC1 vs PC2
976
- ax = fig.add_subplot(gs[1])
977
- ax.set_facecolor(W_PANEL)
978
- sc = ax.scatter(scores[:, 0], scores[:, 1], c=phenotypes, cmap='RdYlBu_r',
979
- s=30, alpha=0.7, edgecolors='white', lw=0.5)
980
- ax.set_xlabel(f'PC1 ({evr[0]:.1f}%)'); ax.set_ylabel(f'PC2 ({evr[1]:.1f}%)')
981
- ax.set_title('PC1 vs PC2'); ax.grid(True, alpha=0.3)
982
- plt.colorbar(sc, ax=ax, label='Phenotype')
983
-
984
- # PC2 vs PC3
985
- ax = fig.add_subplot(gs[2])
986
- ax.set_facecolor(W_PANEL)
987
- if n_comp >= 3:
988
- sc = ax.scatter(scores[:, 1], scores[:, 2], c=phenotypes, cmap='RdYlBu_r',
989
- s=30, alpha=0.7, edgecolors='white', lw=0.5)
990
- ax.set_xlabel(f'PC2 ({evr[1]:.1f}%)'); ax.set_ylabel(f'PC3 ({evr[2]:.1f}%)')
991
- ax.set_title('PC2 vs PC3'); ax.grid(True, alpha=0.3)
992
- plt.colorbar(sc, ax=ax, label='Phenotype')
993
- else:
994
- ax.text(0.5, 0.5, f'Need ≥3 PCs\n(selected {n_comp})', ha='center', va='center')
995
-
996
- plt.tight_layout()
997
- plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=W_BG)
998
- plt.close(fig)
999
-
1000
- return evr, np.cumsum(evr), scores
1001
-
1002
- def plot_kinship_heatmap(K, save_path, max_n=200):
1003
- _style_white()
1004
- n = K.shape[0]
1005
- if n > max_n:
1006
- idx = np.random.choice(n, max_n, replace=False)
1007
- idx.sort()
1008
- K = K[np.ix_(idx, idx)]
1009
-
1010
- fig, ax = plt.subplots(figsize=(8, 7), facecolor=W_BG)
1011
- cmap = LinearSegmentedColormap.from_list('kinship', ['white', '#C6DBEF', '#4292C6', '#08306B'])
1012
- im = ax.imshow(K, cmap=cmap, vmin=0, vmax=1)
1013
- plt.colorbar(im, ax=ax, label='Kinship coefficient')
1014
- ax.set_title('Kinship Matrix', fontweight='bold')
1015
- ax.set_xlabel('Sample'); ax.set_ylabel('Sample')
1016
- plt.tight_layout()
1017
- plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=W_BG)
1018
- plt.close(fig)
1019
-
1020
- def plot_maf_distribution(maf_arr, save_path):
1021
- _style_white()
1022
- maf = maf_arr[maf_arr > 0]
1023
- fig, axes = plt.subplots(1, 2, figsize=(12, 5), facecolor=W_BG)
1024
- fig.suptitle('Minor Allele Frequency Distribution', fontweight='bold')
1025
-
1026
- ax = axes[0]
1027
- ax.set_facecolor(W_PANEL)
1028
- ax.hist(maf, bins=40, color=W_ACCENT, alpha=0.7, edgecolor='white')
1029
- ax.axvline(0.05, color=W_RED, ls='--', lw=2, label='MAF=0.05')
1030
- ax.set_xlabel('MAF'); ax.set_ylabel('Count'); ax.legend(); ax.grid(True, alpha=0.3)
1031
-
1032
- ax = axes[1]
1033
- ax.set_facecolor(W_PANEL)
1034
- x = np.sort(maf)
1035
- y = np.arange(1, len(x)+1) / len(x)
1036
- ax.plot(x, y, color=W_ACCENT, lw=2)
1037
- ax.fill_between(x, 0, y, color=W_ACCENT, alpha=0.15)
1038
- ax.axvline(0.05, color=W_RED, ls='--', lw=2)
1039
- ax.set_xlabel('MAF'); ax.set_ylabel('Cumulative proportion')
1040
- ax.set_title('Cumulative distribution'); ax.grid(True, alpha=0.3)
1041
-
1042
- plt.tight_layout()
1043
- plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=W_BG)
1044
- plt.close(fig)
1045
-
1046
- def plot_volcano(pv, beta, model_name, bonf_thresh, save_path):
1047
- _style_white()
1048
- log_p = -np.log10(np.clip(pv, 1e-300, 1))
1049
- bonf_log = -np.log10(bonf_thresh)
1050
-
1051
- fig, ax = plt.subplots(figsize=(9, 7), facecolor=W_BG)
1052
- ax.set_facecolor(W_PANEL)
1053
-
1054
- sig = log_p >= bonf_log
1055
- nsig = ~sig
1056
-
1057
- if nsig.any():
1058
- ax.scatter(beta[nsig], log_p[nsig], c=W_SUBTEXT, s=10, alpha=0.4, linewidths=0)
1059
-
1060
- pos_sig = sig & (beta > 0)
1061
- neg_sig = sig & (beta < 0)
1062
-
1063
- if pos_sig.any():
1064
- ax.scatter(beta[pos_sig], log_p[pos_sig], c=W_RED, s=45, marker='D',
1065
- alpha=0.9, edgecolors='white', linewidths=0.5, label='Positive effect')
1066
- if neg_sig.any():
1067
- ax.scatter(beta[neg_sig], log_p[neg_sig], c=W_ACCENT, s=45, marker='D',
1068
- alpha=0.9, edgecolors='white', linewidths=0.5, label='Negative effect')
1069
-
1070
- ax.axhline(bonf_log, color=W_RED, ls='--', lw=1.5, label=f'Bonferroni ({bonf_log:.2f})')
1071
- ax.axvline(0, color=W_BORDER, ls=':', lw=1)
1072
- ax.set_xlabel('Effect size (β)', fontweight='bold')
1073
- ax.set_ylabel('-log₁₀(P)', fontweight='bold')
1074
- ax.set_title(f'Volcano Plot — {model_name}', fontweight='bold')
1075
- ax.legend(); ax.grid(True, alpha=0.3)
1076
-
1077
- plt.tight_layout()
1078
- plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=W_BG)
1079
- plt.close(fig)
1080
-
1081
- def plot_model_comparison(model_pvals, save_path):
1082
- _style_white()
1083
- models = list(model_pvals.keys())
1084
- n = len(models)
1085
- if n < 2:
1086
- return
1087
-
1088
- n_pairs = n * (n - 1) // 2
1089
- n_cols = min(3, n_pairs)
1090
- n_rows = (n_pairs + n_cols - 1) // n_cols
1091
-
1092
- fig, axes = plt.subplots(n_rows, n_cols, figsize=(5*n_cols, 5*n_rows), facecolor=W_BG)
1093
- if n_rows == 1 and n_cols == 1:
1094
- axes = np.array([[axes]])
1095
- axes = axes.flatten()
1096
-
1097
- pair_idx = 0
1098
- for i in range(n):
1099
- for j in range(i+1, n):
1100
- ax = axes[pair_idx]
1101
- ax.set_facecolor(W_PANEL)
1102
-
1103
- p1 = -np.log10(np.clip(model_pvals[models[i]], 1e-300, 1))
1104
- p2 = -np.log10(np.clip(model_pvals[models[j]], 1e-300, 1))
1105
- corr = np.corrcoef(p1, p2)[0, 1]
1106
-
1107
- ax.scatter(p1, p2, alpha=0.4, s=8, c=MODEL_COLORS.get(models[i], W_ACCENT))
1108
- max_val = max(p1.max(), p2.max()) * 1.05
1109
- ax.plot([0, max_val], [0, max_val], '--', color=W_GOLD, lw=1.5, alpha=0.7)
1110
- ax.set_xlabel(f'{models[i]} -log₁₀(P)'); ax.set_ylabel(f'{models[j]} -log₁₀(P)')
1111
- ax.set_title(f'{models[i]} vs {models[j]}', fontsize=10)
1112
- ax.text(0.05, 0.95, f'r = {corr:.3f}', transform=ax.transAxes,
1113
- fontsize=11, fontweight='bold', color=W_RED, va='top')
1114
- ax.grid(True, alpha=0.3)
1115
- pair_idx += 1
1116
-
1117
- for k in range(pair_idx, len(axes)):
1118
- axes[k].set_visible(False)
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_circos(markers, chromosomes, positions, model_pvals, bonf_thresh, lod_thresh_user, save_path):
1125
- """Simplified Circos plot - placeholder that works"""
1126
- _style_white()
1127
-
1128
- fig, ax = plt.subplots(figsize=(12, 12), facecolor=W_BG)
1129
- ax.set_facecolor(W_BG)
1130
-
1131
- # Simplified circos representation
1132
- n_models = len(model_pvals)
1133
- colors = [MODEL_COLORS.get(m, W_ACCENT) for m in model_pvals.keys()]
1134
-
1135
- # Simple polar plot
1136
- ax = fig.add_subplot(111, projection='polar')
1137
- ax.set_facecolor(W_BG)
1138
- ax.set_title('Multi-Model GWAS Circos', fontweight='bold', pad=20)
1139
-
1140
- # Placeholder - actual implementation would be more complex
1141
- ax.text(0, 0, f'{n_models} Models\nAnalyzed', ha='center', va='center',
1142
- fontsize=14, fontweight='bold')
1143
-
1144
- # Add chromosome arcs
1145
- unique_chroms = sorted(set(chromosomes))
1146
- n_chr = len(unique_chroms)
1147
- theta = np.linspace(0, 2*np.pi, n_chr + 1)
1148
-
1149
- for i, ch in enumerate(unique_chroms[:min(20, n_chr)]):
1150
- ax.plot([theta[i], theta[i+1]], [0.8, 0.8], color=CHROM_COLORS[i % len(CHROM_COLORS)],
1151
- lw=8, alpha=0.7, solid_capstyle='round')
1152
- ax.text((theta[i] + theta[i+1])/2, 0.92, str(ch), ha='center', fontsize=8)
1153
-
1154
- ax.set_ylim(0, 1)
1155
- ax.set_xticks([])
1156
- ax.set_yticks([])
1157
-
1158
- plt.tight_layout()
1159
- plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=W_BG)
1160
- plt.close(fig)
1161
-
1162
- # ══════════════════════════════════════════════════════════════
1163
- # MAIN ANALYSIS FUNCTION
1164
- # ══════════════════════════════════════════════════════════════
1165
-
1166
- def run_analysis(input_file, miss_sample, miss_marker, maf_thresh,
1167
- lod_thresh_user, n_pc_user,
1168
- run_glm, run_mlm, run_cmlm, run_bslmm, run_farmcpu,
1169
- progress=gr.Progress(track_tqdm=True)):
1170
-
1171
- try:
1172
- if input_file is None:
1173
- return ("⚠️ Please upload a CSV file first.",
1174
- None, None, None, None, None, None, None, None, None,
1175
- gr.update(choices=[]), gr.update(choices=[]), {}, {})
1176
-
1177
- run_id = pd.Timestamp.now().strftime("%Y%m%d_%H%M%S")
1178
- rdir = OUTPUT_DIR / run_id
1179
- pdir = rdir / 'plots'
1180
- for d in [rdir, pdir]:
1181
- d.mkdir(parents=True, exist_ok=True)
1182
-
1183
- ms_t = miss_sample / 100
1184
- mm_t = miss_marker / 100
1185
- mf_t = maf_thresh / 100
1186
-
1187
- # Parse CSV
1188
- progress(0.03, desc="Parsing CSV...")
1189
- sids, pheno, geno, mnames, chroms, positions = parse_input_csv(input_file)
1190
- n_s, n_m = len(sids), len(mnames)
1191
-
1192
- # QC
1193
- progress(0.08, desc="Quality control...")
1194
- miss_m_rate = np.isnan(geno).sum(0) / n_s
1195
- miss_s_rate = np.isnan(geno).sum(1) / n_m
1196
-
1197
- maf = np.zeros(n_m)
1198
- for i in range(n_m):
1199
- v = geno[:, i]
1200
- v = v[~np.isnan(v)]
1201
- if len(v) > 0:
1202
- f = np.mean(v) / 2
1203
- maf[i] = min(f, 1 - f)
1204
-
1205
- # Apply QC filters
1206
- qc_m = (miss_m_rate < mm_t) & (maf >= mf_t)
1207
- qc_s = miss_s_rate < ms_t
1208
-
1209
- # Fallback if too few samples
1210
- if qc_s.sum() < 10:
1211
- for rs, rm in [(0.6, 0.6), (0.7, 0.7), (0.8, 0.8), (0.9, 0.9), (1.0, 1.0)]:
1212
- qm = (miss_m_rate < rm) & (maf >= mf_t)
1213
- qs = miss_s_rate < rs
1214
- if qs.sum() >= 10:
1215
- qc_m, qc_s = qm, qs
1216
- break
1217
-
1218
- if qc_s.sum() < 10:
1219
- return (f"⚠️ Only {qc_s.sum()} samples passed QC (need ≥10)",
1220
- None, None, None, None, None, None, None, None, None,
1221
- gr.update(choices=[]), gr.update(choices=[]), {}, {})
1222
-
1223
- # Apply filters
1224
- geno_q = geno[np.ix_(qc_s, qc_m)]
1225
- pheno_q = pheno[qc_s]
1226
- mn_q = [mnames[i] for i in range(n_m) if qc_m[i]]
1227
- ch_q = [chroms[i] for i in range(n_m) if qc_m[i]]
1228
- pos_q = [positions[i] for i in range(n_m) if qc_m[i]]
1229
- maf_q = maf[qc_m]
1230
-
1231
- # Remove phenotype NaNs
1232
- valid = ~np.isnan(pheno_q)
1233
- geno_q = geno_q[valid]
1234
- pheno_q = pheno_q[valid]
1235
-
1236
- # Impute missing genotypes with column mean
1237
- col_mean = np.nanmean(geno_q, axis=0)
1238
- for i in range(geno_q.shape[1]):
1239
- nan_mask = np.isnan(geno_q[:, i])
1240
- if nan_mask.any():
1241
- geno_q[nan_mask, i] = col_mean[i]
1242
-
1243
- n_q = len(mn_q)
1244
- bonf = 0.05 / n_q
1245
-
1246
- # Compute kinship
1247
- progress(0.15, desc="Computing kinship matrix...")
1248
- K = compute_kinship(geno_q)
1249
-
1250
- # Run models
1251
- progress(0.20, desc="Running GWAS models...")
1252
- model_pvals = {}
1253
- model_betas = {}
1254
- model_ses = {}
1255
-
1256
- step = 0.6 / max(sum([run_glm, run_mlm, run_cmlm, run_bslmm, run_farmcpu]), 1)
1257
- current_progress = 0.20
1258
-
1259
- if run_glm:
1260
- progress(current_progress, desc="GLM...")
1261
- pv, bv, sv, _ = model_glm(geno_q, pheno_q)
1262
- model_pvals['GLM'] = pv
1263
- model_betas['GLM'] = bv
1264
- model_ses['GLM'] = sv
1265
- current_progress += step
1266
-
1267
- if run_mlm:
1268
- progress(current_progress, desc="MLM...")
1269
- pv, bv, sv, _ = model_mlm(geno_q, pheno_q, K, n_pc_user)
1270
- model_pvals['MLM'] = pv
1271
- model_betas['MLM'] = bv
1272
- model_ses['MLM'] = sv
1273
- current_progress += step
1274
-
1275
- if run_cmlm:
1276
- progress(current_progress, desc="CMLM...")
1277
- pv, bv, sv, _ = model_cmlm(geno_q, pheno_q, K, n_groups=None, n_pc=n_pc_user)
1278
- model_pvals['CMLM'] = pv
1279
- model_betas['CMLM'] = bv
1280
- model_ses['CMLM'] = sv
1281
- current_progress += step
1282
-
1283
- if run_bslmm:
1284
- progress(current_progress, desc="BSLMM (may be slow)...")
1285
- pv, bv, sv = model_bslmm(geno_q, pheno_q)
1286
- model_pvals['BSLMM'] = pv
1287
- model_betas['BSLMM'] = bv
1288
- model_ses['BSLMM'] = sv
1289
- current_progress += step
1290
-
1291
- if run_farmcpu:
1292
- progress(current_progress, desc="FarmCPU...")
1293
- pv, bv, sv = model_farmcpu(geno_q, pheno_q, K)
1294
- model_pvals['FarmCPU'] = pv
1295
- model_betas['FarmCPU'] = bv
1296
- model_ses['FarmCPU'] = sv
1297
- current_progress += step
1298
-
1299
- if not model_pvals:
1300
- return ("⚠️ No models selected.",
1301
- None, None, None, None, None, None, None, None, None,
1302
- gr.update(choices=[]), gr.update(choices=[]), {}, {})
1303
-
1304
- # Create results table
1305
- progress(0.80, desc="Generating results...")
1306
- df = pd.DataFrame({
1307
- 'Marker': mn_q,
1308
- 'Chromosome': ch_q,
1309
- 'Position_bp': pos_q,
1310
- 'MAF': maf_q
1311
- })
1312
-
1313
- LOD_FACTOR = np.log10(np.e) / 2.0
1314
- for mname, pv in model_pvals.items():
1315
- df[f'{mname}_P'] = pv
1316
- df[f'{mname}_LOD'] = -np.log10(np.clip(pv, 1e-300, 1)) * LOD_FACTOR
1317
- df[f'{mname}_Sig'] = (pv < bonf).astype(int)
1318
- if mname in model_betas:
1319
- df[f'{mname}_Beta'] = model_betas[mname]
1320
-
1321
- df = df.sort_values(f"{list(model_pvals.keys())[0]}_P").reset_index(drop=True)
1322
- df.insert(0, 'Rank', range(1, len(df) + 1))
1323
-
1324
- csv_path = str(rdir / 'gwas_results.csv')
1325
- df.to_csv(csv_path, index=False)
1326
-
1327
- # Generate plots
1328
- progress(0.85, desc="Generating plots...")
1329
-
1330
- # Phenotype distribution
1331
- ph_path = str(pdir / 'phenotype_dist.png')
1332
- plot_phenotype(pheno_q, ph_path)
1333
-
1334
- # PCA
1335
- pca_path = str(pdir / 'pca_analysis.png')
1336
- evr, cumev, scores = plot_pca(geno_q, pheno_q, n_pc_user, pca_path)
1337
-
1338
- # Kinship heatmap
1339
- kin_path = str(pdir / 'kinship_heatmap.png')
1340
- plot_kinship_heatmap(K, kin_path)
1341
-
1342
- # MAF distribution
1343
- maf_path = str(pdir / 'maf_distribution.png')
1344
- plot_maf_distribution(maf_q, maf_path)
1345
-
1346
- # Manhattan plots
1347
- man_paths = {}
1348
- for mname, pv in model_pvals.items():
1349
- mp = str(pdir / f'manhattan_{mname}.png')
1350
- plot_manhattan_single(mn_q, ch_q, pv, mname, bonf, lod_thresh_user, mp)
1351
- man_paths[mname] = mp
1352
-
1353
- # QQ plots
1354
- qq_paths = {}
1355
- lam_dict = {}
1356
- for mname, pv in model_pvals.items():
1357
- qp = str(pdir / f'qq_{mname}.png')
1358
- lam = plot_qq_single(pv, mname, bonf, qp)
1359
- qq_paths[mname] = qp
1360
- lam_dict[mname] = lam
1361
-
1362
- # LD decay
1363
- ld_path = str(pdir / 'ld_decay.png')
1364
- ld_stats, ld_text = plot_ld_decay(geno_q, ch_q, pos_q, ld_path)
1365
-
1366
- # Volcano plots
1367
- volcano_paths = {}
1368
- for mname, pv in model_pvals.items():
1369
- if mname in model_betas:
1370
- vp = str(pdir / f'volcano_{mname}.png')
1371
- plot_volcano(pv, model_betas[mname], mname, bonf, vp)
1372
- volcano_paths[mname] = vp
1373
-
1374
- # Model comparison
1375
- cmp_path = str(pdir / 'model_comparison.png')
1376
- plot_model_comparison(model_pvals, cmp_path)
1377
-
1378
- # Circos
1379
- circos_path = str(pdir / 'circos_mta.png')
1380
- plot_circos(mn_q, ch_q, pos_q, model_pvals, bonf, lod_thresh_user, circos_path)
1381
-
1382
- # Create ZIP
1383
- progress(0.95, desc="Creating ZIP archive...")
1384
- zip_path = str(OUTPUT_DIR / f'GWAS_Results_{run_id}.zip')
1385
- with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf:
1386
- for root, _, files in os.walk(str(rdir)):
1387
- for f in files:
1388
- fp = os.path.join(root, f)
1389
- zf.write(fp, os.path.relpath(fp, str(rdir)))
1390
-
1391
- # Create summary markdown
1392
- summary = f"""
1393
- ## ✅ GWAS Analysis Complete — v11.0
1394
-
1395
- ### 📊 Quality Control Summary
1396
- | Metric | Value |
1397
- |--------|-------|
1398
- | Samples (after QC) | **{len(pheno_q)}** |
1399
- | Markers (after QC) | **{n_q}** |
1400
- | MAF threshold | ≥ {maf_thresh:.1f}% |
1401
- | Bonferroni threshold | P < {bonf:.3e} (-log₁₀P > {-np.log10(bonf):.2f}) |
1402
-
1403
- ### 🔬 Model Results
1404
- | Model | Sig. Markers | λ (inflation) |
1405
- |-------|-------------|---------------|
1406
- """
1407
- for mname, pv in model_pvals.items():
1408
- n_sig = (pv < bonf).sum()
1409
- lam = lam_dict.get(mname, 1.0)
1410
- summary += f"| {mname} | **{n_sig}** | {lam:.4f} |\n"
1411
-
1412
- summary += f"""
1413
- ### 🧬 LD Decay
1414
- {ld_text}
1415
-
1416
- ### 📈 Output Files
1417
- - `gwas_results.csv` — Complete results for all markers
1418
- - `plots/` — All figures (Manhattan, QQ, LD, PCA, etc.)
1419
-
1420
- ### 🏆 Top Markers
1421
- {df[['Rank', 'Marker', 'Chromosome', 'Position_bp'] + [f'{m}_P' for m in model_pvals.keys()]].head(10).to_markdown(index=False)}
1422
-
1423
- ---
1424
- *MTA GWAS v11.0 — Fixed LD decay (Hill-Weir model) | All models functional | White background*
1425
- """
1426
-
1427
- progress(1.0, desc="Complete!")
1428
-
1429
- first_man = list(man_paths.values())[0] if man_paths else None
1430
- first_qq = list(qq_paths.values())[0] if qq_paths else None
1431
-
1432
- return (summary,
1433
- first_man, first_qq, pca_path,
1434
- ld_path, circos_path, cmp_path, ph_path,
1435
- zip_path, kin_path,
1436
- gr.update(choices=list(man_paths.keys()), value=list(man_paths.keys())[0] if man_paths else None),
1437
- gr.update(choices=list(qq_paths.keys()), value=list(qq_paths.keys())[0] if qq_paths else None),
1438
- man_paths, qq_paths)
1439
-
1440
- except Exception as e:
1441
- import traceback
1442
- return (f"## ❌ Error\n```\n{e}\n\n{traceback.format_exc()}\n```",
1443
- None, None, None, None, None, None, None, None, None,
1444
- gr.update(choices=[]), gr.update(choices=[]), {}, {})
1445
-
1446
- # ══════════════════════════════════════════════════════════════
1447
- # GRADIO UI
1448
- # ══════════════════════════════════════════════════════════════
1449
-
1450
- CSS = """
1451
- body, .gradio-container { background: #F7F9FC !important; }
1452
- h1, h2, h3 { color: #1A365D !important; }
1453
- .gr-button-primary {
1454
- background: linear-gradient(135deg, #1A365D, #2B6CB0) !important;
1455
- border: none !important;
1456
- border-radius: 8px !important;
1457
- }
1458
- """
1459
-
1460
- with gr.Blocks(css=CSS, title="GWAS Analysis v11.0") as app:
1461
- gr.Markdown("""
1462
- # 🧬 GWAS / MTA Analysis Platform v11.0
1463
- ### Multi-Model Suite · Hill-Weir LD Decay · Fixed Model Selection · White Theme
1464
- """)
1465
-
1466
- with gr.Row():
1467
- with gr.Column(scale=1):
1468
- input_file = gr.File(label="📁 Upload CSV", file_types=[".csv"])
1469
- gr.Markdown("""
1470
- **CSV Format:**
 
1
+ """)
2
+
3
+ with gr.Column(scale=1):
4
+ miss_sample = gr.Slider(5, 50, value=30, label="Max sample missing (%)")
5
+ miss_marker = gr.Slider(5, 50, value=30, label="Max marker missing (%)")
6
+ maf_thr = gr.Slider(0, 25, value=3, label="Min MAF (%)")
7
+
8
+ with gr.Column(scale=1):
9
+ lod_thresh = gr.Slider(0.5, 10.0, value=3.0, label="LOD threshold")
10
+ n_pc = gr.Slider(2, 20, value=5, label="Number of PCs")
11
+ gr.Markdown("### Models")
12
+ with gr.Row():
13
+ chk_glm = gr.Checkbox(value=True, label="GLM")
14
+ chk_mlm = gr.Checkbox(value=True, label="MLM")
15
+ chk_cmlm = gr.Checkbox(value=True, label="CMLM")
16
+ chk_bslmm = gr.Checkbox(value=False, label="BSLMM")
17
+ chk_farmcpu = gr.Checkbox(value=True, label="FarmCPU")
18
+
19
+ run_btn = gr.Button("🚀 Run GWAS Analysis", variant="primary", size="lg")
20
+
21
+ summary_out = gr.Markdown()
22
+
23
+ with gr.Row():
24
+ man_model_sel = gr.Dropdown(label="Manhattan Model", choices=[], value=None, interactive=True)
25
+ qq_model_sel = gr.Dropdown(label="QQ Plot Model", choices=[], value=None, interactive=True)
26
+
27
+ with gr.Row():
28
+ man_out = gr.Image(label="Manhattan Plot")
29
+ qq_out = gr.Image(label="QQ Plot")
30
+
31
+ with gr.Row():
32
+ pca_out = gr.Image(label="PCA Analysis")
33
+ ld_out = gr.Image(label="LD Decay")
34
+
35
+ with gr.Row():
36
+ circos_out = gr.Image(label="Circos Plot")
37
+ cmp_out = gr.Image(label="Model Comparison")
38
+
39
+ with gr.Row():
40
+ ph_out = gr.Image(label="Phenotype Distribution")
41
+ kin_out = gr.Image(label="Kinship Matrix")
42
+
43
+ dl_out = gr.File(label="📦 Download ZIP")
44
+
45
+ man_paths_state = gr.State({})
46
+ qq_paths_state = gr.State({})
47
+
48
+ run_btn.click(
49
+ fn=run_analysis,
50
+ inputs=[input_file, miss_sample, miss_marker, maf_thr,
51
+ lod_thresh, n_pc,
52
+ chk_glm, chk_mlm, chk_cmlm, chk_bslmm, chk_farmcpu],
53
+ outputs=[summary_out, man_out, qq_out, pca_out,
54
+ ld_out, circos_out, cmp_out, ph_out,
55
+ dl_out, kin_out,
56
+ man_model_sel, qq_model_sel,
57
+ man_paths_state, qq_paths_state],
58
+ show_progress="full"
59
+ )
60
+
61
+ def switch_manhattan(model, paths):
62
+ return paths.get(model) if paths else None
63
+
64
+ def switch_qq(model, paths):
65
+ return paths.get(model) if paths else None
66
+
67
+ man_model_sel.change(switch_manhattan, [man_model_sel, man_paths_state], [man_out])
68
+ qq_model_sel.change(switch_qq, [qq_model_sel, qq_paths_state], [qq_out])
69
+
70
+ if __name__ == "__main__":
71
+ app.launch(share=False, show_error=True)