softwareDevelopment commited on
Commit
85b6769
Β·
verified Β·
1 Parent(s): 67246c7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +902 -884
app.py CHANGED
@@ -1,911 +1,929 @@
1
- # -*- coding: utf-8 -*-
2
  """
3
- GWAS Pipeline v14.0 - Complete Robust GWAS Platform
4
- Fixed: NaN handling, dimension issues, all bugs
5
- Features: 10+ plots, 15 models, PCA, Kinship, LD analysis
 
6
  """
7
 
8
  import gradio as gr
9
  import pandas as pd
10
  import numpy as np
11
  import matplotlib
12
- matplotlib.use('Agg')
13
  import matplotlib.pyplot as plt
14
- from matplotlib.patches import Circle
15
  import matplotlib.patches as mpatches
16
  from matplotlib.gridspec import GridSpec
17
- import seaborn as sns
 
 
 
 
18
  from scipy import stats
19
- from scipy.optimize import curve_fit
20
- from scipy.cluster.hierarchy import dendrogram, linkage
21
- import os, warnings, tempfile, zipfile, io
22
- from sklearn.linear_model import (LinearRegression, Ridge, Lasso, ElasticNet,
23
- BayesianRidge, RidgeCV, LassoCV)
24
- from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor
25
- from sklearn.preprocessing import StandardScaler
26
- from sklearn.impute import SimpleImputer
27
  from sklearn.decomposition import PCA
28
- from sklearn.metrics import r2_score
29
- from sklearn.model_selection import cross_val_score, KFold
30
- import statsmodels.api as sm
31
- from statsmodels.stats.multitest import multipletests
32
- warnings.filterwarnings('ignore')
33
-
34
- # Set Times New Roman
35
- plt.rcParams['font.family'] = 'Times New Roman'
36
- plt.rcParams['font.size'] = 11
37
- plt.rcParams['figure.dpi'] = 150
38
-
39
- # ══════════════════════════════════════════════════════════════
40
- # COLOR PALETTE
41
- # ══════════════════════════════════════════════════════════════
42
-
43
- BG_PASTEL = "#FDF8F0"
44
- PANEL_PASTEL = "#F5F0E8"
45
- TEXT_COLOR = "#4A4A4A"
46
-
47
- COLORS = {
48
- 'primary': '#C5A3FF', 'secondary': '#A8E6CF', 'tertiary': '#FFD3B6',
49
- 'quaternary': '#FFB3BA', 'lod': '#95CDBA', 'significant': '#E8A598',
50
- 'pca1': '#8B9DC3', 'pca2': '#E5A9A9', 'volcano': '#F4A582',
51
- 'chromosome': ['#E8D5F5', '#D4F1F9', '#FDE2C4', '#E2F0CB', '#FFD9E8',
52
- '#C9E4DE', '#FADADD', '#D5E4CF', '#FCE1E4', '#CFBAE1']
53
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54
 
55
- CSS = """
56
- <style>
57
- * { font-family: 'Times New Roman', Times, serif !important; }
58
- .gradio-container { background: linear-gradient(135deg, #FDF8F0 0%, #F5F0E8 100%) !important; padding: 20px !important; }
59
- .main-header { background: linear-gradient(135deg, #E8D5F5 0%, #D4F1F9 100%); padding: 30px; border-radius: 20px; text-align: center; margin-bottom: 25px; }
60
- .main-header h1 { color: #4A4A4A; font-size: 2.2em; margin: 0; }
61
- .section-header { background: linear-gradient(135deg, #C5A3FF 0%, #B8D4E3 100%); padding: 10px 18px; border-radius: 12px; margin: 15px 0 12px 0; font-weight: 600; }
62
- .card { background: #FFFEF8; border-radius: 12px; padding: 15px; margin: 10px 0; border: 1px solid #E8DCC8; }
63
- .run-btn { background: linear-gradient(135deg, #C5A3FF 0%, #A8E6CF 100%); border: none; padding: 12px 35px; border-radius: 25px; font-weight: 600; cursor: pointer; font-size: 1.1em; }
64
- .run-btn:hover { transform: scale(1.02); }
65
- footer { text-align: center; padding: 20px; margin-top: 25px; background: #FFFEF8; border-radius: 12px; border: 1px solid #E8DCC8; }
66
- </style>
67
- """
68
 
69
- # ══════════════════════════════════════════════════════════════
70
- # DATA PROCESSING WITH PROPER IMPUTATION
71
- # ══════════════════════════════════════════════════════════════
72
-
73
- def process_data(filepath, sample_missing=0.5, marker_missing=0.5, maf_thresh=0.05):
74
- """Process data with proper imputation for NaN values"""
75
-
76
- # Read data
77
- df = pd.read_csv(filepath, header=0)
78
-
79
- # Limit samples for speed
80
- max_samples = min(500, len(df) - 1)
81
- df = df.iloc[:max_samples + 1]
82
-
83
- marker_cols = df.columns[2:].tolist()
84
-
85
- # Parse chromosomes from first row
86
- first_row = df.iloc[0]
87
- chromosomes = []
88
- positions = []
89
- for m in marker_cols:
90
- val = str(first_row[m]).strip()
91
- if ':' in val:
92
- chrom, pos = val.split(':')[:2]
93
- chromosomes.append(chrom)
94
- try:
95
- positions.append(float(pos))
96
- except:
97
- positions.append(0)
98
- else:
99
- chromosomes.append(val)
100
- positions.append(0)
101
-
102
- # Sample data
103
- sample_data = df.iloc[1:].reset_index(drop=True)
104
- sample_ids = sample_data.iloc[:, 0].astype(str).values
105
- phenotypes = pd.to_numeric(sample_data.iloc[:, 1], errors='coerce').values
106
-
107
- # Genotype matrix
108
- genotypes = sample_data[marker_cols].apply(pd.to_numeric, errors='coerce').values
109
-
110
- # Remove columns with all NaN
111
- col_not_all_nan = ~np.all(np.isnan(genotypes), axis=0)
112
- genotypes = genotypes[:, col_not_all_nan]
113
- chromosomes = [chromosomes[i] for i in range(len(chromosomes)) if col_not_all_nan[i]]
114
- positions = [positions[i] for i in range(len(positions)) if col_not_all_nan[i]]
115
-
116
- # Remove rows with all NaN
117
- row_not_all_nan = ~np.all(np.isnan(genotypes), axis=1)
118
- genotypes = genotypes[row_not_all_nan]
119
- phenotypes = phenotypes[row_not_all_nan]
120
- sample_ids = sample_ids[row_not_all_nan]
121
-
122
- # Filter by missing rate
123
- marker_missing_rate = np.isnan(genotypes).sum(axis=0) / genotypes.shape[0]
124
- keep_markers = marker_missing_rate < marker_missing
125
- genotypes = genotypes[:, keep_markers]
126
- chromosomes = [chromosomes[i] for i in range(len(chromosomes)) if keep_markers[i]]
127
- positions = [positions[i] for i in range(len(positions)) if keep_markers[i]]
128
-
129
- sample_missing_rate = np.isnan(genotypes).sum(axis=1) / genotypes.shape[1]
130
- keep_samples = sample_missing_rate < sample_missing
131
- genotypes = genotypes[keep_samples]
132
- phenotypes = phenotypes[keep_samples]
133
- sample_ids = sample_ids[keep_samples]
134
-
135
- # Calculate MAF and filter
136
- maf = np.zeros(genotypes.shape[1])
137
- for i in range(genotypes.shape[1]):
138
- col = genotypes[:, i]
139
- valid = col[~np.isnan(col)]
140
- if len(valid) > 0:
141
- freq = np.mean(valid) / 2.0
142
- maf[i] = min(freq, 1.0 - freq)
143
- else:
144
- maf[i] = 0
145
-
146
- keep_maf = maf >= maf_thresh
147
- genotypes = genotypes[:, keep_maf]
148
- chromosomes = [chromosomes[i] for i in range(len(chromosomes)) if keep_maf[i]]
149
- positions = [positions[i] for i in range(len(positions)) if keep_maf[i]]
150
-
151
- # IMPUTE MISSING VALUES - Critical step!
152
- imputer = SimpleImputer(strategy='mean')
153
- genotypes_imputed = imputer.fit_transform(genotypes)
154
-
155
- # Remove NaN phenotypes
156
- valid_pheno = ~np.isnan(phenotypes)
157
- genotypes_final = genotypes_imputed[valid_pheno]
158
- phenotypes_final = phenotypes[valid_pheno]
159
- sample_ids_final = sample_ids[valid_pheno]
160
-
161
- # Standardize
162
  scaler = StandardScaler()
163
- genotypes_scaled = scaler.fit_transform(genotypes_final)
164
-
165
- return genotypes_final, genotypes_scaled, phenotypes_final, sample_ids_final, chromosomes, positions
166
-
167
- # ══════════════════════════════════════════════════════════════
168
- # PLOT 1: MANHATTAN PLOT
169
- # ══════════════════════════════════════════════════════════════
170
-
171
- def plot_manhattan(p_values, chromosomes, lod_scores, sig_threshold, save_path):
172
- """Manhattan plot with LOD scores"""
173
- plt.figure(figsize=(16, 7), facecolor=BG_PASTEL)
174
- ax = plt.gca()
175
- ax.set_facecolor(PANEL_PASTEL)
176
-
177
- log_p = -np.log10(p_values + 1e-300)
178
- unique_chroms = np.unique(chromosomes)
179
-
180
- # Calculate positions
181
- positions = np.arange(len(chromosomes))
182
- offset = 0
183
- chrom_positions = {}
184
-
185
- for ch in unique_chroms:
186
- mask = np.array(chromosomes) == ch
187
- chrom_positions[ch] = (offset, offset + mask.sum())
188
- positions[mask] = np.arange(mask.sum()) + offset
189
- offset += mask.sum() + 8
190
-
191
- # Plot points
192
- for i, ch in enumerate(unique_chroms):
193
- mask = np.array(chromosomes) == ch
194
- color = COLORS['chromosome'][i % len(COLORS['chromosome'])]
195
- ax.scatter(positions[mask], log_p[mask], c=color, s=12, alpha=0.7, linewidths=0)
196
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
197
  # Highlight significant
198
- sig_mask = p_values < sig_threshold
199
  if sig_mask.any():
200
- ax.scatter(positions[sig_mask], log_p[sig_mask], c=COLORS['significant'],
201
- s=70, edgecolors='white', linewidths=1.5, marker='D', zorder=3)
202
-
203
- # Threshold lines
204
- ax.axhline(-np.log10(sig_threshold), color=COLORS['significant'], linestyle='--', linewidth=2, alpha=0.8)
205
- ax.axhline(3, color=COLORS['secondary'], linestyle=':', linewidth=2, alpha=0.8)
206
-
207
- # LOD scores
208
- ax2 = ax.twinx()
209
- ax2.plot(positions, lod_scores, color=COLORS['lod'], linewidth=1.5, alpha=0.6)
210
- ax2.set_ylabel('LOD Score', fontsize=12, color='#5A8F7C', fontweight='bold')
211
- ax2.tick_params(axis='y', colors='#5A8F7C')
212
-
213
- ax.set_xlabel('Chromosome', fontsize=13, fontweight='bold')
214
- ax.set_ylabel('-log₁₀(P-value)', fontsize=13, fontweight='bold')
215
- ax.set_title('Manhattan Plot with LOD Scores', fontsize=16, fontweight='bold')
216
-
217
- centers = [(chrom_positions[ch][0] + chrom_positions[ch][1]) / 2 for ch in unique_chroms]
218
- ax.set_xticks(centers)
219
- ax.set_xticklabels(unique_chroms, rotation=45, ha='right', fontsize=10)
220
- ax.set_xlim(-5, offset)
221
- ax.grid(True, alpha=0.3, linestyle='--')
222
-
223
- n_sig = sig_mask.sum()
224
- ax.text(0.02, 0.98, f'Significant: {n_sig}\nMax LOD: {lod_scores.max():.2f}',
225
- transform=ax.transAxes, fontsize=10, verticalalignment='top',
226
- bbox=dict(boxstyle='round', facecolor=BG_PASTEL, alpha=0.8))
227
-
228
- plt.tight_layout()
229
- plt.savefig(save_path, dpi=200, bbox_inches='tight')
230
- plt.close()
231
-
232
- return n_sig
233
-
234
- # ══════════════════════════════════════════════════════════════
235
- # PLOT 2: QQ PLOT
236
- # ══════════════════════════════════════════════════════════════
237
-
238
- def plot_qq(p_values, save_path):
239
- """Q-Q plot for p-value distribution"""
240
- plt.figure(figsize=(8, 8), facecolor=BG_PASTEL)
241
- ax = plt.gca()
242
- ax.set_facecolor(PANEL_PASTEL)
243
-
244
- n = len(p_values)
245
- expected = -np.log10((np.arange(1, n + 1) - 0.5) / n)
246
- observed = -np.log10(np.sort(p_values))
247
-
248
- ax.scatter(expected, observed, c=COLORS['primary'], s=30, alpha=0.6, edgecolors='white')
249
- ax.plot([0, max(expected)], [0, max(expected)], 'k--', linewidth=2, alpha=0.7)
250
-
251
- # Confidence interval
252
- ci_upper = -np.log10(0.05 / n) + 0.5
253
- ci_lower = -np.log10(0.95 / n) - 0.5
254
- ax.fill_between([0, max(expected)], [ci_lower, ci_lower], [ci_upper, ci_upper],
255
- alpha=0.1, color=COLORS['secondary'])
256
-
257
- # Genomic inflation factor
258
- lambda_gc = np.median(observed) / np.median(expected)
259
-
260
- ax.set_xlabel('Expected -log₁₀(P)', fontsize=12, fontweight='bold')
261
- ax.set_ylabel('Observed -log₁₀(P)', fontsize=12, fontweight='bold')
262
- ax.set_title('Q-Q Plot', fontsize=15, fontweight='bold')
263
- ax.grid(True, alpha=0.3, linestyle='--')
264
-
265
- ax.text(0.05, 0.95, f'Ξ» GC = {lambda_gc:.3f}', transform=ax.transAxes,
266
- fontsize=11, verticalalignment='top',
267
- bbox=dict(boxstyle='round', facecolor=BG_PASTEL, alpha=0.8))
268
-
269
- plt.tight_layout()
270
- plt.savefig(save_path, dpi=200, bbox_inches='tight')
271
- plt.close()
272
-
273
- return lambda_gc
274
-
275
- # ══════════════════════════════════════════════════════════════
276
- # PLOT 3: LD DECAY PLOT
277
- # ══════════════════════════════════════════════════════════════
278
-
279
- def plot_ld_decay(genotypes, chromosomes, positions, save_path, max_dist_mb=5):
280
- """LD decay plot with distances in Mb"""
281
- plt.figure(figsize=(10, 7), facecolor=BG_PASTEL)
282
- ax = plt.gca()
283
- ax.set_facecolor(PANEL_PASTEL)
284
-
285
- distances = []
286
- r2_values = []
287
-
288
- unique_chroms = np.unique(chromosomes)[:3] # First 3 chromosomes for speed
289
-
290
- for ch in unique_chroms:
291
- mask = np.array(chromosomes) == ch
292
- idxs = np.where(mask)[0]
293
- if len(idxs) < 10:
294
- continue
295
-
296
- if len(idxs) > 100:
297
- idxs = np.random.choice(idxs, 100, replace=False)
298
-
299
- G = genotypes[:, idxs]
300
- pos_mb = np.array([positions[i] for i in idxs]) / 1_000_000
301
-
302
- n_pairs = min(800, len(idxs) * 15)
303
- for _ in range(n_pairs):
304
- i, j = np.random.choice(len(idxs), 2, replace=False)
305
- dist = abs(pos_mb[j] - pos_mb[i])
306
- if dist <= max_dist_mb and dist > 0:
307
- r = np.corrcoef(G[:, i], G[:, j])[0, 1]
308
- if not np.isnan(r):
309
- distances.append(dist)
310
- r2_values.append(r**2)
311
-
312
- if len(distances) > 2000:
313
- break
314
-
315
- if distances:
316
- bins = np.linspace(0, max_dist_mb, 25)
317
- bin_centers, bin_means, bin_stds = [], [], []
318
-
319
- for i in range(len(bins)-1):
320
- mask = (np.array(distances) >= bins[i]) & (np.array(distances) < bins[i+1])
321
- if mask.sum() > 5:
322
- bin_centers.append((bins[i] + bins[i+1]) / 2)
323
- bin_means.append(np.mean(np.array(r2_values)[mask]))
324
- bin_stds.append(np.std(np.array(r2_values)[mask]) / np.sqrt(mask.sum()))
325
-
326
- ax.errorbar(bin_centers, bin_means, yerr=bin_stds, fmt='o-',
327
- color=COLORS['primary'], capsize=3, markersize=6, linewidth=2, alpha=0.8)
328
-
329
- # Exponential decay fit
330
- try:
331
- def decay_func(x, a, b):
332
- return a * np.exp(-b * x)
333
- popt, _ = curve_fit(decay_func, bin_centers, bin_means, p0=[1, 1], maxfev=1000)
334
- x_fit = np.linspace(0, max_dist_mb, 100)
335
- ax.plot(x_fit, decay_func(x_fit, *popt), '--', color=COLORS['lod'], linewidth=2, label=f'Decay: {popt[1]:.2f}')
336
-
337
- half_decay = np.log(2) / popt[1] if popt[1] > 0 else 0
338
- if half_decay <= max_dist_mb:
339
- ax.axvline(half_decay, color=COLORS['significant'], linestyle='--', alpha=0.7, label=f'Half-decay: {half_decay:.2f} Mb')
340
- except:
341
- pass
342
-
343
- ax.axhline(0.2, color=COLORS['secondary'], linestyle=':', alpha=0.7, label='rΒ² = 0.2')
344
-
345
- ax.set_xlabel('Distance (Megabases)', fontsize=12, fontweight='bold')
346
- ax.set_ylabel('Linkage Disequilibrium (rΒ²)', fontsize=12, fontweight='bold')
347
- ax.set_title('LD Decay Analysis', fontsize=15, fontweight='bold')
348
- ax.set_ylim(0, 1)
349
- ax.legend(loc='upper right', fontsize=10)
350
- ax.grid(True, alpha=0.3)
351
-
352
- plt.tight_layout()
353
- plt.savefig(save_path, dpi=200, bbox_inches='tight')
354
- plt.close()
355
-
356
- return np.mean(r2_values) if r2_values else 0
357
-
358
- # ══════════════════════════════════════════════════════════════
359
- # PLOT 4: PCA PLOT
360
- # ══════════════════════════════════════════════════════════════
361
-
362
- def plot_pca(genotypes_scaled, phenotypes, save_path):
363
- """PCA visualization for population structure"""
364
- pca = PCA(n_components=5)
365
- pca_result = pca.fit_transform(genotypes_scaled)
366
-
367
- fig, axes = plt.subplots(1, 3, figsize=(15, 5), facecolor=BG_PASTEL)
368
-
369
  # Scree plot
370
- ax1 = axes[0]
371
- ax1.set_facecolor(PANEL_PASTEL)
372
- var_ratio = pca.explained_variance_ratio_[:5] * 100
373
- ax1.bar(range(1, 6), var_ratio, color=COLORS['primary'], alpha=0.7, edgecolor='white')
374
- ax1.plot(range(1, 6), np.cumsum(var_ratio), 'o-', color=COLORS['significant'], linewidth=2, markersize=8)
375
- ax1.set_xlabel('Principal Component', fontsize=11, fontweight='bold')
376
- ax1.set_ylabel('Variance Explained (%)', fontsize=11, fontweight='bold')
377
- ax1.set_title('Scree Plot', fontsize=12, fontweight='bold')
378
- ax1.grid(True, alpha=0.3)
379
-
380
- # PC1 vs PC2
381
- ax2 = axes[1]
382
- ax2.set_facecolor(PANEL_PASTEL)
383
- sc = ax2.scatter(pca_result[:, 0], pca_result[:, 1], c=phenotypes,
384
- cmap='coolwarm', s=40, alpha=0.7, edgecolors='white', linewidth=0.5)
385
- ax2.set_xlabel(f'PC1 ({var_ratio[0]:.1f}%)', fontsize=11, fontweight='bold')
386
- ax2.set_ylabel(f'PC2 ({var_ratio[1]:.1f}%)', fontsize=11, fontweight='bold')
387
- ax2.set_title('Population Structure (PC1 vs PC2)', fontsize=12, fontweight='bold')
388
- ax2.grid(True, alpha=0.3)
389
- plt.colorbar(sc, ax=ax2, label='Phenotype')
390
-
391
- # Cumulative variance
392
- ax3 = axes[2]
393
- ax3.set_facecolor(PANEL_PASTEL)
394
- cumulative = np.cumsum(var_ratio)
395
- ax3.fill_between(range(1, 6), cumulative, alpha=0.3, color=COLORS['secondary'])
396
- ax3.plot(range(1, 6), cumulative, 'o-', color=COLORS['secondary'], linewidth=2, markersize=8)
397
- ax3.axhline(y=80, color=COLORS['significant'], linestyle='--', alpha=0.7, label='80% threshold')
398
- ax3.set_xlabel('Number of Components', fontsize=11, fontweight='bold')
399
- ax3.set_ylabel('Cumulative Variance (%)', fontsize=11, fontweight='bold')
400
- ax3.set_title('Cumulative Variance', fontsize=12, fontweight='bold')
401
- ax3.legend(loc='lower right', fontsize=9)
402
- ax3.grid(True, alpha=0.3)
403
-
404
- plt.tight_layout()
405
- plt.savefig(save_path, dpi=200, bbox_inches='tight')
406
- plt.close()
407
-
408
- return pca_result, var_ratio
409
-
410
- # ══════════════════════════════════════════════════════════════
411
- # PLOT 5: KINSHIP HEATMAP
412
- # ══════════════════════════════════════════════════════════════
413
-
414
- def plot_kinship(genotypes_scaled, save_path):
415
- """Kinship matrix heatmap"""
416
- # Calculate kinship using subset for speed
417
- n_markers = min(500, genotypes_scaled.shape[1])
418
- idx = np.random.choice(genotypes_scaled.shape[1], n_markers, replace=False)
419
- genotypes_subset = genotypes_scaled[:, idx]
420
- kinship = np.corrcoef(genotypes_subset)
421
- kinship = (kinship + 1) / 2 # Scale to 0-1
422
-
423
- # Downsample if too large
424
- if kinship.shape[0] > 100:
425
- idx_samples = np.linspace(0, kinship.shape[0]-1, 100, dtype=int)
426
- kinship = kinship[np.ix_(idx_samples, idx_samples)]
427
-
428
- fig, ax = plt.subplots(figsize=(10, 8), facecolor=BG_PASTEL)
429
- ax.set_facecolor(PANEL_PASTEL)
430
-
431
- im = ax.imshow(kinship, cmap='RdYlBu_r', aspect='auto', vmin=0, vmax=1)
432
- ax.set_title('Kinship Matrix', fontsize=14, fontweight='bold')
433
- ax.set_xlabel('Samples', fontsize=11, fontweight='bold')
434
- ax.set_ylabel('Samples', fontsize=11, fontweight='bold')
435
-
436
- cbar = plt.colorbar(im, ax=ax, shrink=0.8)
437
- cbar.set_label('Kinship Coefficient', fontsize=11, fontweight='bold')
438
-
439
- plt.tight_layout()
440
- plt.savefig(save_path, dpi=200, bbox_inches='tight')
441
- plt.close()
442
-
443
- return kinship.mean(), kinship.max()
444
-
445
- # ══════════════════════════════════════════════════════════════
446
- # PLOT 6: VOLCANO PLOT
447
- # ══════════════════════════════════════════════════════════════
448
-
449
- def plot_volcano(p_values, effects, sig_threshold, save_path):
450
- """Volcano plot for effect size vs significance"""
451
- plt.figure(figsize=(10, 8), facecolor=BG_PASTEL)
452
- ax = plt.gca()
453
- ax.set_facecolor(PANEL_PASTEL)
454
-
455
- log_p = -np.log10(p_values + 1e-300)
456
- sig_mask = p_values < sig_threshold
457
-
458
- # Non-significant
459
- ax.scatter(effects[~sig_mask], log_p[~sig_mask], c=COLORS['primary'],
460
- s=20, alpha=0.5, label='Non-significant')
461
-
462
- # Significant
463
- if sig_mask.any():
464
- ax.scatter(effects[sig_mask], log_p[sig_mask], c=COLORS['significant'],
465
- s=50, alpha=0.8, edgecolors='white', linewidth=0.5, label='Significant')
466
-
467
- ax.axhline(-np.log10(sig_threshold), color=COLORS['significant'], linestyle='--', linewidth=1.5)
468
- ax.axvline(0, color='gray', linestyle='-', linewidth=1, alpha=0.5)
469
-
470
- ax.set_xlabel('Effect Size', fontsize=12, fontweight='bold')
471
- ax.set_ylabel('-log₁₀(P-value)', fontsize=12, fontweight='bold')
472
- ax.set_title('Volcano Plot', fontsize=15, fontweight='bold')
473
- ax.legend(loc='upper left', fontsize=10)
474
- ax.grid(True, alpha=0.3)
475
-
476
- plt.tight_layout()
477
- plt.savefig(save_path, dpi=200, bbox_inches='tight')
478
- plt.close()
479
-
480
- # ══════════════════════════════════════════════════════════════
481
- # PLOT 7: CHROMOSOME-WIDE DISTRIBUTION
482
- # ══════════════════════════════════════════════════════════════
483
-
484
- def plot_chromosome_distribution(p_values, chromosomes, lod_scores, save_path):
485
- """Distribution of significant markers across chromosomes"""
486
- plt.figure(figsize=(14, 6), facecolor=BG_PASTEL)
487
- ax = plt.gca()
488
- ax.set_facecolor(PANEL_PASTEL)
489
-
490
- unique_chroms = np.unique(chromosomes)
491
- chrom_means = []
492
- chrom_max = []
493
-
494
- for ch in unique_chroms:
495
- mask = np.array(chromosomes) == ch
496
- if mask.any():
497
- chrom_means.append(-np.log10(p_values[mask] + 1e-300).mean())
498
- chrom_max.append(lod_scores[mask].max())
499
-
500
- x = np.arange(len(unique_chroms))
501
- width = 0.35
502
-
503
- bars1 = ax.bar(x - width/2, chrom_means, width, label='Mean -log₁₀(P)',
504
- color=COLORS['primary'], alpha=0.7, edgecolor='white')
505
- bars2 = ax.bar(x + width/2, chrom_max, width, label='Max LOD',
506
- color=COLORS['lod'], alpha=0.7, edgecolor='white')
507
-
508
- ax.set_xlabel('Chromosome', fontsize=12, fontweight='bold')
509
- ax.set_ylabel('Score', fontsize=12, fontweight='bold')
510
- ax.set_title('Chromosome-wise Distribution', fontsize=15, fontweight='bold')
511
- ax.set_xticks(x)
512
- ax.set_xticklabels(unique_chroms, rotation=45, ha='right')
513
- ax.legend(loc='upper right', fontsize=10)
514
- ax.grid(True, alpha=0.3, axis='y')
515
-
516
- plt.tight_layout()
517
- plt.savefig(save_path, dpi=200, bbox_inches='tight')
518
- plt.close()
519
-
520
- # ══════════════════════════════════════════════════════════════
521
- # PLOT 8: CIRCOS PLOT
522
- # ══════════════════════════════════════════════════════════════
523
-
524
- def plot_circos(chromosomes, p_values, lod_scores, sig_threshold, save_path):
525
- """Circos-style circular plot"""
526
- plt.figure(figsize=(10, 10), facecolor=BG_PASTEL)
527
- ax = plt.subplot(111, projection='polar')
528
- ax.set_facecolor(BG_PASTEL)
529
-
530
- unique_chroms = np.unique(chromosomes)
531
- n_chroms = len(unique_chroms)
532
- angles = np.linspace(0, 2*np.pi, n_chroms + 1)
533
-
534
- # Chromosome arcs
535
- for i, ch in enumerate(unique_chroms):
536
- theta_mid = (angles[i] + angles[i+1]) / 2
537
- ax.bar(theta_mid, 0.15, width=2*np.pi/n_chroms - 0.03,
538
- bottom=0.85, color=COLORS['chromosome'][i % len(COLORS['chromosome'])],
539
- alpha=0.8, edgecolor='white')
540
- ax.text(theta_mid, 0.93, str(ch), ha='center', va='center', fontsize=9, fontweight='bold')
541
-
542
- # Markers
543
- log_p = -np.log10(p_values + 1e-300)
544
- max_p = log_p.max() if log_p.max() > 0 else 5
545
-
546
- for i, ch in enumerate(unique_chroms):
547
- mask = np.array(chromosomes) == ch
548
- if mask.sum() == 0:
549
  continue
550
-
551
- chrom_p = log_p[mask]
552
- theta_start = angles[i]
553
- theta_end = angles[i+1]
554
-
555
- positions = theta_start + (np.arange(len(chrom_p)) / len(chrom_p)) * (theta_end - theta_start)
556
- radii = 0.4 + 0.3 * (chrom_p / max_p)
557
-
558
- colors = [COLORS['significant'] if p < sig_threshold else COLORS['primary']
559
- for p in p_values[mask]]
560
- ax.scatter(positions, radii, c=colors, s=8, alpha=0.6, linewidths=0)
561
-
562
- # Inner circle
563
- circle = Circle((0, 0), 0.35, transform=ax.transData._b,
564
- facecolor=PANEL_PASTEL, edgecolor=BORDER_PASTEL, linewidth=2)
565
- ax.add_patch(circle)
566
- ax.text(0, 0, 'GWAS\nResults', ha='center', va='center', fontsize=12, fontweight='bold')
567
-
568
- ax.set_theta_zero_location('N')
569
- ax.set_theta_direction(-1)
570
- ax.set_ylim(0, 1.1)
571
- ax.set_xticks([])
572
- ax.set_yticks([])
573
- ax.spines['polar'].set_visible(False)
574
-
575
- plt.title('Circos Plot', fontsize=15, fontweight='bold', pad=20)
576
- plt.tight_layout()
577
- plt.savefig(save_path, dpi=200, bbox_inches='tight')
578
- plt.close()
579
-
580
- # ══════════════════════════════════════════════════════════════
581
- # PLOT 9: P-VALUE DISTRIBUTION
582
- # ══════════════════════════════════════════════════════════════
583
-
584
- def plot_pvalue_distribution(p_values, save_path):
585
- """Histogram of p-values"""
586
- plt.figure(figsize=(10, 6), facecolor=BG_PASTEL)
587
- ax = plt.gca()
588
- ax.set_facecolor(PANEL_PASTEL)
589
-
590
- ax.hist(p_values, bins=50, color=COLORS['primary'], alpha=0.7, edgecolor='white', density=True)
591
- ax.axhline(y=1, color=COLORS['significant'], linestyle='--', linewidth=2, alpha=0.7, label='Uniform distribution')
592
- ax.set_xlabel('P-value', fontsize=12, fontweight='bold')
593
- ax.set_ylabel('Density', fontsize=12, fontweight='bold')
594
- ax.set_title('P-value Distribution', fontsize=15, fontweight='bold')
595
- ax.legend(loc='upper right', fontsize=10)
596
- ax.grid(True, alpha=0.3)
597
-
598
- # Add text about deviation from uniform
599
- expected_uniform = 1
600
- observed_mean = np.mean(p_values < 0.05)
601
- ax.text(0.7, 0.95, f'Proportion p<0.05: {observed_mean:.3f}',
602
- transform=ax.transAxes, fontsize=10,
603
- bbox=dict(boxstyle='round', facecolor=BG_PASTEL, alpha=0.8))
604
-
605
- plt.tight_layout()
606
- plt.savefig(save_path, dpi=200, bbox_inches='tight')
607
- plt.close()
608
-
609
- # ══════════════════════════════════════════════════════════════
610
- # PLOT 10: EFFECT SIZE DISTRIBUTION
611
- # ══════════════════════════════════════════════════════════════
612
-
613
- def plot_effect_distribution(effects, save_path):
614
- """Distribution of effect sizes"""
615
- plt.figure(figsize=(10, 6), facecolor=BG_PASTEL)
616
- ax = plt.gca()
617
- ax.set_facecolor(PANEL_PASTEL)
618
-
619
- ax.hist(effects, bins=50, color=COLORS['secondary'], alpha=0.7, edgecolor='white')
620
- ax.axvline(x=0, color=COLORS['significant'], linestyle='--', linewidth=2, alpha=0.7)
621
- ax.axvline(x=np.mean(effects), color=COLORS['primary'], linestyle='-', linewidth=2,
622
- alpha=0.7, label=f'Mean: {np.mean(effects):.3f}')
623
-
624
- ax.set_xlabel('Effect Size', fontsize=12, fontweight='bold')
625
- ax.set_ylabel('Frequency', fontsize=12, fontweight='bold')
626
- ax.set_title('Effect Size Distribution', fontsize=15, fontweight='bold')
627
- ax.legend(loc='upper right', fontsize=10)
628
- ax.grid(True, alpha=0.3)
629
-
630
- plt.tight_layout()
631
- plt.savefig(save_path, dpi=200, bbox_inches='tight')
632
- plt.close()
633
-
634
- # ══════════════════════════════════════════════════════════════
635
- # GWAS MODELS
636
- # ══════════════════════════════════════════════════════════════
637
-
638
- def run_linear_regression(genotypes, phenotypes):
639
- """Linear regression GWAS - vectorized"""
640
- n_markers = genotypes.shape[1]
641
- pvals = np.ones(n_markers)
642
- effects = np.zeros(n_markers)
643
- lod = np.zeros(n_markers)
644
-
645
- X_centered = genotypes - genotypes.mean(axis=0)
646
- y_centered = phenotypes - phenotypes.mean()
647
-
648
- xy = np.dot(y_centered, X_centered)
649
- xx = np.sum(X_centered ** 2, axis=0)
650
- valid = xx > 1e-10
651
-
652
- effects[valid] = xy[valid] / xx[valid]
653
-
654
- n = len(phenotypes)
655
- for i in np.where(valid)[0]:
656
- y_pred = effects[i] * X_centered[:, i]
657
- resid = y_centered - y_pred
658
- rss = np.sum(resid ** 2)
659
- t_stat = effects[i] / (np.sqrt(rss / (n - 2)) / np.sqrt(xx[i]) + 1e-10)
660
- pvals[i] = 2 * (1 - stats.t.cdf(abs(t_stat), n - 2))
661
- lod[i] = -np.log10(pvals[i] + 1e-300)
662
-
663
- return pvals, effects, lod
664
-
665
- def run_random_forest(genotypes, phenotypes):
666
- """Random Forest for feature importance"""
667
- rf = RandomForestRegressor(n_estimators=50, random_state=42, n_jobs=-1, max_depth=10)
668
- rf.fit(genotypes, phenotypes)
669
-
670
- importance = rf.feature_importances_
671
- imp_rank = np.argsort(importance)[::-1]
672
- pvals = np.ones(len(importance))
673
- for i, idx in enumerate(imp_rank):
674
- pvals[idx] = (i + 1) / len(importance)
675
- lod = -np.log10(pvals + 1e-300)
676
-
677
- return pvals, importance, lod, rf.score(genotypes, phenotypes)
678
-
679
- # ══════════════════════════════════════════════════════════════
680
- # MAIN PIPELINE
681
- # ══════════════════════════════════════════════════════════════
682
-
683
- def run_gwas_pipeline(input_file, sample_missing, marker_missing, maf_threshold):
684
- """Complete GWAS pipeline with 10+ plots"""
685
-
686
- if input_file is None:
687
- return ("Please upload a CSV file", [None]*12)
688
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
689
  try:
690
- # Create directories
691
- temp_dir = tempfile.mkdtemp()
692
- results_dir = os.path.join(temp_dir, 'results')
693
- plots_dir = os.path.join(results_dir, 'plots')
694
- os.makedirs(plots_dir, exist_ok=True)
695
-
696
- # Process data with proper imputation
697
- genotypes, genotypes_scaled, phenotypes, sample_ids, chromosomes, positions = process_data(
698
- input_file.name, sample_missing/100, marker_missing/100, maf_threshold/100
699
- )
700
-
701
- n_samples, n_markers = genotypes.shape
702
- bonf_threshold = 0.05 / n_markers
703
-
704
- # Run GWAS models
705
- print("Running Linear Regression...")
706
- pvals, effects, lod = run_linear_regression(genotypes, phenotypes)
707
-
708
- print("Running Random Forest...")
709
- rf_pvals, rf_importance, rf_lod, rf_score = run_random_forest(genotypes_scaled, phenotypes)
710
-
711
- # Generate all 10 plots
712
- plots = {}
713
-
714
- # Plot 1: Manhattan
715
- plots['manhattan'] = os.path.join(plots_dir, 'manhattan.png')
716
- n_sig = plot_manhattan(pvals, chromosomes, lod, bonf_threshold, plots['manhattan'])
717
-
718
- # Plot 2: QQ
719
- plots['qq'] = os.path.join(plots_dir, 'qq.png')
720
- lambda_gc = plot_qq(pvals, plots['qq'])
721
-
722
- # Plot 3: LD Decay
723
- plots['ld'] = os.path.join(plots_dir, 'ld_decay.png')
724
- mean_ld = plot_ld_decay(genotypes, chromosomes, positions, plots['ld'])
725
-
726
- # Plot 4: PCA
727
- plots['pca'] = os.path.join(plots_dir, 'pca.png')
728
- pca_result, var_ratio = plot_pca(genotypes_scaled, phenotypes, plots['pca'])
729
-
730
- # Plot 5: Kinship
731
- plots['kinship'] = os.path.join(plots_dir, 'kinship.png')
732
- mean_kinship, max_kinship = plot_kinship(genotypes_scaled, plots['kinship'])
733
-
734
- # Plot 6: Volcano
735
- plots['volcano'] = os.path.join(plots_dir, 'volcano.png')
736
- plot_volcano(pvals, effects, bonf_threshold, plots['volcano'])
737
-
738
- # Plot 7: Chromosome Distribution
739
- plots['chrom_dist'] = os.path.join(plots_dir, 'chromosome_distribution.png')
740
- plot_chromosome_distribution(pvals, chromosomes, lod, plots['chrom_dist'])
741
-
742
- # Plot 8: Circos
743
- plots['circos'] = os.path.join(plots_dir, 'circos.png')
744
- plot_circos(chromosomes, pvals, lod, bonf_threshold, plots['circos'])
745
-
746
- # Plot 9: P-value Distribution
747
- plots['pval_dist'] = os.path.join(plots_dir, 'pvalue_distribution.png')
748
- plot_pvalue_distribution(pvals, plots['pval_dist'])
749
-
750
- # Plot 10: Effect Distribution
751
- plots['effect_dist'] = os.path.join(plots_dir, 'effect_distribution.png')
752
- plot_effect_distribution(effects, plots['effect_dist'])
753
-
754
- # Create results DataFrame
755
- results_df = pd.DataFrame({
756
- 'Marker': [f'M{i+1}' for i in range(n_markers)],
757
- 'Chromosome': chromosomes,
758
- 'Position': positions,
759
- 'P-value': pvals,
760
- 'LOD': lod,
761
- 'Effect_Size': effects,
762
- 'RF_Importance': rf_importance,
763
- 'Significant': pvals < bonf_threshold
764
- })
765
- results_df = results_df.sort_values('P-value')
766
- results_df.to_csv(os.path.join(results_dir, 'gwas_results.csv'), index=False)
767
-
768
- # Create ZIP file
769
- zip_path = os.path.join(temp_dir, 'GWAS_Complete_Results.zip')
770
- with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf:
771
- for root, _, files in os.walk(results_dir):
772
- for f in files:
773
- zf.write(os.path.join(root, f), os.path.relpath(os.path.join(root, f), temp_dir))
774
-
775
- # Generate summary
776
- summary = f"""
777
- ## βœ… GWAS Analysis Complete!
778
-
779
- ### πŸ“Š Dataset Summary
780
- | Metric | Value |
781
- |--------|-------|
782
- | Samples | **{n_samples}** |
783
- | Markers | **{n_markers:,}** |
784
- | Chromosomes | **{len(np.unique(chromosomes))}** |
785
-
786
- ### πŸ”¬ Key Findings
787
- | Metric | Value |
788
- |--------|-------|
789
- | Significant Markers (Bonferroni) | **{n_sig}** |
790
- | Genomic Inflation Factor (Ξ») | **{lambda_gc:.3f}** |
791
- | Mean LD (rΒ²) | **{mean_ld:.3f}** |
792
- | Mean Kinship | **{mean_kinship:.3f}** |
793
-
794
- ### πŸ“ˆ Model Performance
795
- | Model | RΒ² Score |
796
- |-------|----------|
797
- | Linear Regression | {r2_score(phenotypes, np.dot(genotypes, effects)):.3f} |
798
- | Random Forest | {rf_score:.3f} |
799
-
800
- ### πŸ† Top 5 Associated Markers
801
- {results_df.head(5)[['Marker', 'Chromosome', 'LOD', 'Effect_Size']].to_markdown(index=False)}
802
-
803
- ### πŸ“ Output Files (ZIP Archive)
804
- - `gwas_results.csv` - Complete association results
805
- - `plots/manhattan.png` - Manhattan plot with LOD scores
806
- - `plots/qq.png` - Q-Q plot with genomic inflation
807
- - `plots/ld_decay.png` - LD decay analysis
808
- - `plots/pca.png` - Population structure PCA
809
- - `plots/kinship.png` - Kinship matrix heatmap
810
- - `plots/volcano.png` - Volcano plot
811
- - `plots/chromosome_distribution.png` - Chromosome-wise distribution
812
- - `plots/circos.png` - Circular visualization
813
- - `plots/pvalue_distribution.png` - P-value histogram
814
- - `plots/effect_distribution.png` - Effect size distribution
815
-
816
- ### πŸ“ Interpretation
817
- - **Population Structure**: {'Well-controlled' if lambda_gc < 1.05 else 'Consider including more PCs'}
818
- - **LD Decay**: {'Fast decay indicates diverse germplasm' if mean_ld < 0.3 else 'Slow decay suggests related individuals'}
819
- - **Significant Associations**: {n_sig} markers show strong association with the trait
820
- """
821
-
822
- return (summary,
823
- plots['manhattan'], plots['qq'], plots['ld'], plots['pca'],
824
- plots['kinship'], plots['volcano'], plots['chrom_dist'],
825
- plots['circos'], plots['pval_dist'], plots['effect_dist'], zip_path)
826
-
827
  except Exception as e:
828
- import traceback
829
- error_msg = f"## ❌ Error\n```\n{str(e)}\n\n{traceback.format_exc()}\n```"
830
- return (error_msg, [None]*11)
831
-
832
- # ══════════════════════════════════════════════════════════════
833
- # GRADIO INTERFACE
834
- # ══════════════════════════════════════════════════════════════
835
-
836
- with gr.Blocks(css=CSS, title="Complete GWAS Platform", theme=gr.themes.Soft()) as app:
837
-
838
- gr.HTML("""
839
- <div class="main-header">
840
- <h1>🧬 Complete GWAS Analysis Platform</h1>
841
- <p>10+ Publication-Quality Plots | PCA | Kinship | LD Analysis | Multi-Model</p>
842
- </div>
843
- """)
844
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
845
  with gr.Row():
846
  with gr.Column(scale=1):
847
- gr.HTML('<div class="section-header">πŸ“‚ Data Input</div>')
848
- input_file = gr.File(label="Upload CSV File", file_types=[".csv"])
849
-
850
- gr.HTML('<div class="section-header">βš™οΈ Quality Control</div>')
851
- sample_missing = gr.Slider(10, 80, value=50, step=5, label="Sample Missing Rate (%)")
852
- marker_missing = gr.Slider(10, 80, value=50, step=5, label="Marker Missing Rate (%)")
853
- maf_threshold = gr.Slider(1, 20, value=5, step=1, label="MAF Threshold (%)")
854
-
855
- run_btn = gr.Button("πŸš€ Run Complete GWAS Analysis", variant="primary", elem_classes=["run-btn"])
856
-
857
- gr.HTML("""
858
- <div class="card">
859
- <h3>πŸ“‹ CSV Format Required</h3>
860
- <p><strong>Row 1:</strong> ID | Phenotype | Marker1 (chr:pos) | Marker2 | ...</p>
861
- <p><strong>Row 2+:</strong> Sample1 | value | 0/1/2 | 0/1/2 | ...</p>
862
- <p><strong>Genotype coding:</strong> 0=AA, 1=Aa, 2=aa</p>
863
- <p><strong>Example:</strong> "1:1234567" for chromosome 1 at position 1,234,567 bp</p>
864
- </div>
865
- """)
866
-
867
- with gr.Column(scale=2):
868
- gr.HTML('<div class="section-header">πŸ“Š Analysis Summary</div>')
869
- summary_out = gr.Markdown("Ready to analyze. Upload a CSV file and click Run.")
870
-
871
- gr.HTML('<div class="section-header">πŸ“ˆ Visualization Gallery (10+ Plots)</div>')
872
-
873
- with gr.Row():
874
- with gr.Column():
875
- manhattan_out = gr.Image(label="1. Manhattan Plot with LOD", elem_classes=["plot-container"])
876
- pca_out = gr.Image(label="4. PCA Population Structure", elem_classes=["plot-container"])
877
- volcano_out = gr.Image(label="6. Volcano Plot", elem_classes=["plot-container"])
878
- circos_out = gr.Image(label="8. Circos Plot", elem_classes=["plot-container"])
879
- effect_out = gr.Image(label="10. Effect Size Distribution", elem_classes=["plot-container"])
880
-
881
- with gr.Row():
882
- with gr.Column():
883
- qq_out = gr.Image(label="2. Q-Q Plot", elem_classes=["plot-container"])
884
- kinship_out = gr.Image(label="5. Kinship Matrix", elem_classes=["plot-container"])
885
- chrom_dist_out = gr.Image(label="7. Chromosome Distribution", elem_classes=["plot-container"])
886
- pval_dist_out = gr.Image(label="9. P-value Distribution", elem_classes=["plot-container"])
887
-
888
- with gr.Row():
889
- with gr.Column():
890
- ld_out = gr.Image(label="3. LD Decay Plot (Mb)", elem_classes=["plot-container"])
891
-
892
- gr.HTML('<div class="section-header">⬇️ Download Results</div>')
893
- download_out = gr.File(label="Download Complete Results (ZIP)")
894
-
 
 
 
895
  run_btn.click(
896
- fn=run_gwas_pipeline,
897
- inputs=[input_file, sample_missing, marker_missing, maf_threshold],
898
- outputs=[summary_out, manhattan_out, qq_out, ld_out, pca_out,
899
- kinship_out, volcano_out, chrom_dist_out, circos_out,
900
- pval_dist_out, effect_out, download_out]
901
  )
902
-
903
- gr.HTML("""
904
- <footer>
905
- <p><strong>GWAS Pipeline v14.0</strong> | 10+ Plots | Times New Roman | Soft Pastel Theme | Production-Ready</p>
906
- <p>βœ… No NaN errors | βœ… Proper imputation | βœ… All bugs fixed</p>
907
- </footer>
908
- """)
 
 
 
 
 
 
 
909
 
910
  if __name__ == "__main__":
911
- app.launch(share=True, debug=False)
 
 
1
  """
2
+ ╔══════════════════════════════════════════════════════════════════════╗
3
+ β•‘ GWAS PIPELINE β€” Genome-Wide Association Study Suite β•‘
4
+ β•‘ Full statistical analysis with interactive Gradio UI β•‘
5
+ β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•
6
  """
7
 
8
  import gradio as gr
9
  import pandas as pd
10
  import numpy as np
11
  import matplotlib
12
+ matplotlib.use("Agg")
13
  import matplotlib.pyplot as plt
 
14
  import matplotlib.patches as mpatches
15
  from matplotlib.gridspec import GridSpec
16
+ from matplotlib.colors import LinearSegmentedColormap
17
+ import matplotlib.ticker as ticker
18
+ import warnings
19
+ warnings.filterwarnings("ignore")
20
+
21
  from scipy import stats
22
+ from scipy.spatial.distance import pdist, squareform
 
 
 
 
 
 
 
23
  from sklearn.decomposition import PCA
24
+ from sklearn.preprocessing import StandardScaler
25
+ from sklearn.linear_model import LinearRegression
26
+ import io, os, re, itertools
27
+ from io import StringIO
28
+
29
+ # ─────────────────────────── THEME PALETTE ────────────────────────────
30
+ DARK = "#0d0f1a"
31
+ PANEL = "#131626"
32
+ ACCENT1 = "#00e5ff" # cyan
33
+ ACCENT2 = "#ff4081" # pink
34
+ ACCENT3 = "#b2ff59" # lime
35
+ GOLD = "#ffd740"
36
+ MUTED = "#8892b0"
37
+ TEXT = "#ccd6f6"
38
+ GRID_COL = "#1e2340"
39
+
40
+ def style_fig(fig):
41
+ fig.patch.set_facecolor(DARK)
42
+ for ax in fig.get_axes():
43
+ ax.set_facecolor(PANEL)
44
+ ax.tick_params(colors=TEXT, labelsize=9)
45
+ ax.xaxis.label.set_color(TEXT)
46
+ ax.yaxis.label.set_color(TEXT)
47
+ ax.title.set_color(ACCENT1)
48
+ for spine in ax.spines.values():
49
+ spine.set_edgecolor(GRID_COL)
50
+ ax.grid(color=GRID_COL, linewidth=0.5, linestyle="--", alpha=0.7)
51
+ return fig
52
+
53
+ # ─────────────────────────── DATA PARSING ─────────────────────────────
54
+
55
+ def parse_data(file_obj=None, text_input=None):
56
+ """Parse uploaded CSV / pasted text β†’ clean DataFrame."""
57
+ raw = None
58
+ if file_obj is not None:
59
+ try:
60
+ raw = pd.read_csv(file_obj.name, sep=None, engine="python")
61
+ except Exception:
62
+ raw = pd.read_csv(file_obj.name, sep="\t")
63
+ elif text_input and text_input.strip():
64
+ try:
65
+ raw = pd.read_csv(StringIO(text_input), sep=None, engine="python")
66
+ except Exception:
67
+ raw = pd.read_csv(StringIO(text_input), sep="\t")
68
+ else:
69
+ raise ValueError("No data provided.")
70
+
71
+ # Identify ID and phenotype columns
72
+ cols = list(raw.columns)
73
+ id_col = cols[0]
74
+ phen_col = cols[1]
75
+
76
+ snp_cols = cols[2:]
77
+
78
+ # Drop rows where phenotype is missing / header artefacts
79
+ raw = raw[pd.to_numeric(raw[phen_col], errors="coerce").notna()].copy()
80
+ raw[phen_col] = raw[phen_col].astype(float)
81
+
82
+ # Replace missing genotype codes (-1, -9, 'NA') β†’ NaN
83
+ geno = raw[snp_cols].apply(pd.to_numeric, errors="coerce")
84
+ geno = geno.where(~geno.isin([-1, -9]), np.nan)
85
+
86
+ df = pd.DataFrame()
87
+ df["ID"] = raw[id_col].values
88
+ df["Phenotype"] = raw[phen_col].values
89
+ for c in snp_cols:
90
+ df[c] = geno[c].values
91
+
92
+ return df, snp_cols
93
+
94
+
95
+ def parse_marker_info(snp_cols):
96
+ """
97
+ Extract chromosome and position from marker names like
98
+ 'chr1_134521_LOC_Os01g01280' β†’ chrom=1, pos=134521
99
+ Falls back to sequential numbering.
100
+ """
101
+ chroms, positions = [], []
102
+ for m in snp_cols:
103
+ m_clean = str(m).strip()
104
+ mat = re.match(r"[Cc]hr(\d+)[_\-](\d+)", m_clean)
105
+ if mat:
106
+ chroms.append(int(mat.group(1)))
107
+ positions.append(int(mat.group(2)))
108
+ else:
109
+ num = re.findall(r"\d+", m_clean)
110
+ chroms.append(int(num[0]) if num else 1)
111
+ positions.append(int(num[1]) if len(num) > 1 else len(positions) + 1)
112
+ return np.array(chroms), np.array(positions)
113
+
114
+
115
+ # ─────────────────────────── STATISTICAL MODELS ───────────────────────
116
+
117
+ def impute_genotypes(geno_matrix):
118
+ """Mean imputation for missing genotype values."""
119
+ mat = geno_matrix.copy().astype(float)
120
+ for j in range(mat.shape[1]):
121
+ col = mat[:, j]
122
+ m = np.nanmean(col)
123
+ col[np.isnan(col)] = m if not np.isnan(m) else 0
124
+ mat[:, j] = col
125
+ return mat
126
+
127
+
128
+ def compute_maf(G):
129
+ """Minor Allele Frequency per SNP."""
130
+ freqs = np.nanmean(G, axis=0) / 2
131
+ maf = np.where(freqs > 0.5, 1 - freqs, freqs)
132
+ return maf
133
+
134
+
135
+ def build_kinship(G):
136
+ """VanRaden (2008) genomic relationship matrix."""
137
+ p = np.nanmean(G, axis=0) / 2
138
+ Z = G - 2 * p
139
+ denom = 2 * np.sum(p * (1 - p))
140
+ if denom == 0:
141
+ denom = 1
142
+ K = Z @ Z.T / denom
143
+ return K
144
+
145
+
146
+ def ols_gwas(y, G):
147
+ """Model 1 β€” Ordinary Least Squares (simple linear regression)."""
148
+ n, m = G.shape
149
+ pvals = np.ones(m)
150
+ betas = np.zeros(m)
151
+ for j in range(m):
152
+ x = G[:, j]
153
+ x = (x - x.mean())
154
+ if x.std() < 1e-8:
155
+ continue
156
+ slope, intercept, r, p, se = stats.linregress(x, y)
157
+ pvals[j] = p
158
+ betas[j] = slope
159
+ return pvals, betas
160
+
161
+
162
+ def mlm_gwas(y, G, K):
163
+ """Model 2 β€” Mixed Linear Model (EMMA-like, PC correction as K proxy)."""
164
+ n, m = G.shape
165
+ pvals = np.ones(m)
166
+ betas = np.zeros(m)
167
+ # Use top PCs of K as random-effect covariates
168
+ eigvals, eigvecs = np.linalg.eigh(K + np.eye(n) * 1e-6)
169
+ idx = np.argsort(eigvals)[::-1]
170
+ n_pcs = min(3, n - 2)
171
+ Q = eigvecs[:, idx[:n_pcs]]
172
+ # Regress y on Q to get residuals
173
+ reg = LinearRegression().fit(Q, y)
174
+ y_res = y - reg.predict(Q)
175
+ for j in range(m):
176
+ x = G[:, j]
177
+ x_res = x - LinearRegression().fit(Q, x).predict(Q)
178
+ if x_res.std() < 1e-8:
179
+ continue
180
+ slope, intercept, r, p, se = stats.linregress(x_res, y_res)
181
+ pvals[j] = p
182
+ betas[j] = slope
183
+ return pvals, betas
184
 
 
 
 
 
 
 
 
 
 
 
 
 
 
185
 
186
+ def glm_gwas(y, G):
187
+ """Model 3 β€” General Linear Model with population structure (PCA correction)."""
188
+ n, m = G.shape
189
+ pvals = np.ones(m)
190
+ betas = np.zeros(m)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
191
  scaler = StandardScaler()
192
+ G_sc = scaler.fit_transform(G)
193
+ pca = PCA(n_components=min(3, n - 2))
194
+ PCs = pca.fit_transform(G_sc)
195
+ reg = LinearRegression().fit(PCs, y)
196
+ y_adj = y - reg.predict(PCs)
197
+ for j in range(m):
198
+ x = G[:, j]
199
+ if x.std() < 1e-8:
200
+ continue
201
+ x_adj = x - LinearRegression().fit(PCs, x).predict(PCs)
202
+ slope, intercept, r, p, se = stats.linregress(x_adj, y_adj)
203
+ pvals[j] = p
204
+ betas[j] = slope
205
+ return pvals, betas
206
+
207
+
208
+ def compressed_mlm_gwas(y, G, K):
209
+ """Model 4 β€” Compressed MLM (group-based K compression)."""
210
+ n, m = G.shape
211
+ pvals = np.ones(m)
212
+ betas = np.zeros(m)
213
+ # Cluster individuals using K diagonal
214
+ k_diag = np.diag(K)
215
+ groups = pd.qcut(k_diag, q=min(3, n), labels=False, duplicates="drop")
216
+ g_means = np.zeros((n, groups.max() + 1))
217
+ for g in range(groups.max() + 1):
218
+ idx = np.where(groups == g)[0]
219
+ if len(idx):
220
+ g_means[:, g] = K[:, idx].mean(axis=1)
221
+ reg = LinearRegression().fit(g_means, y)
222
+ y_res = y - reg.predict(g_means)
223
+ for j in range(m):
224
+ x = G[:, j]
225
+ x_res = x - LinearRegression().fit(g_means, x).predict(g_means)
226
+ if x_res.std() < 1e-8:
227
+ continue
228
+ slope, intercept, r, p, se = stats.linregress(x_res, y_res)
229
+ pvals[j] = p
230
+ betas[j] = slope
231
+ return pvals, betas
232
+
233
+
234
+ def blink_gwas(y, G):
235
+ """Model 5 β€” BLINK-inspired (Bayesian-Likelihood iterative, simplified)."""
236
+ n, m = G.shape
237
+ pvals = np.ones(m)
238
+ betas = np.zeros(m)
239
+ # Iterative: start with OLS, then add top hits as covariates
240
+ ols_p, ols_b = ols_gwas(y, G)
241
+ # Use top 2 hits as fixed covariates
242
+ top_idx = np.argsort(ols_p)[:min(2, m)]
243
+ covars = G[:, top_idx] if len(top_idx) > 0 else np.ones((n, 1))
244
+ reg = LinearRegression().fit(covars, y)
245
+ y_adj = y - reg.predict(covars)
246
+ for j in range(m):
247
+ x = G[:, j]
248
+ if x.std() < 1e-8:
249
+ continue
250
+ slope, intercept, r, p, se = stats.linregress(x, y_adj)
251
+ pvals[j] = p
252
+ betas[j] = slope
253
+ return pvals, betas
254
+
255
+
256
+ def farm_cpu_gwas(y, G, K):
257
+ """Model 6 β€” FarmCPU-inspired (Fixed & Random Model Circulating Probability Unification)."""
258
+ n, m = G.shape
259
+ pvals = np.ones(m)
260
+ betas = np.zeros(m)
261
+ # Step 1: MLM step
262
+ mlm_p, mlm_b = mlm_gwas(y, G, K)
263
+ # Step 2: Top signals as pseudo-QTNs
264
+ sig_idx = np.argsort(mlm_p)[:min(3, m)]
265
+ pseudo = G[:, sig_idx] if len(sig_idx) else np.ones((n, 1))
266
+ # Step 3: Fixed-effect model using pseudo-QTNs
267
+ reg = LinearRegression().fit(pseudo, y)
268
+ y_adj = y - reg.predict(pseudo)
269
+ for j in range(m):
270
+ x = G[:, j]
271
+ if x.std() < 1e-8:
272
+ continue
273
+ slope, intercept, r, p, se = stats.linregress(x, y_adj)
274
+ pvals[j] = p
275
+ betas[j] = slope
276
+ return pvals, betas
277
+
278
+
279
+ # ─────────────────────────── PLOTTING FUNCTIONS ───────────────────────
280
+
281
+ def fig_to_pil(fig):
282
+ buf = io.BytesIO()
283
+ fig.savefig(buf, format="png", dpi=150, bbox_inches="tight",
284
+ facecolor=fig.get_facecolor())
285
+ buf.seek(0)
286
+ from PIL import Image
287
+ return Image.open(buf).copy()
288
+
289
+
290
+ # ── 1. Manhattan Plot ──────────────────────────────────────────────────
291
+ def plot_manhattan(pvals, chroms, positions, title="Manhattan Plot"):
292
+ fig, ax = plt.subplots(figsize=(14, 5))
293
+ style_fig(fig)
294
+ ax = fig.axes[0]
295
+
296
+ sig_line = -np.log10(5e-8)
297
+ sug_line = -np.log10(1e-5)
298
+ log_p = -np.log10(np.clip(pvals, 1e-300, 1))
299
+
300
+ chrom_list = sorted(set(chroms))
301
+ palette = [ACCENT1, ACCENT2, ACCENT3, GOLD, "#ff9100", "#e040fb",
302
+ "#64ffda", "#ff6d00", "#40c4ff", "#69f0ae",
303
+ "#ffab40", "#ea80fc"]
304
+ chrom_colors = {c: palette[i % len(palette)] for i, c in enumerate(chrom_list)}
305
+
306
+ x_offset = 0
307
+ tick_pos = []
308
+ tick_lab = []
309
+ x_coords = np.zeros(len(pvals))
310
+
311
+ for ch in chrom_list:
312
+ mask = chroms == ch
313
+ pos = positions[mask]
314
+ order = np.argsort(pos)
315
+ x_vals = pos[order] - pos.min() + x_offset
316
+ x_coords[np.where(mask)[0][order]] = x_vals
317
+ mid = x_vals.mean() if len(x_vals) > 1 else x_vals[0]
318
+ tick_pos.append(mid)
319
+ tick_lab.append(f"Chr{ch}")
320
+ # shade alternate chromosomes
321
+ ax.axvspan(x_offset, x_offset + pos.max() - pos.min(),
322
+ alpha=0.05, color=chrom_colors[ch])
323
+ x_offset += (pos.max() - pos.min()) + max(positions) * 0.01
324
+
325
+ # Scatter
326
+ for ch in chrom_list:
327
+ mask = chroms == ch
328
+ ax.scatter(x_coords[mask], log_p[mask],
329
+ c=chrom_colors[ch], s=22, alpha=0.85,
330
+ edgecolors="none", zorder=3)
331
+
332
  # Highlight significant
333
+ sig_mask = log_p >= sig_line
334
  if sig_mask.any():
335
+ ax.scatter(x_coords[sig_mask], log_p[sig_mask],
336
+ c=GOLD, s=55, zorder=5, edgecolors="white",
337
+ linewidths=0.5, marker="*", label="Genome-wide significant")
338
+
339
+ ax.axhline(sig_line, color=ACCENT2, lw=1.2, ls="--", label="p = 5Γ—10⁻⁸")
340
+ ax.axhline(sug_line, color=GOLD, lw=1.0, ls=":", label="p = 1Γ—10⁻⁡")
341
+
342
+ ax.set_xticks(tick_pos)
343
+ ax.set_xticklabels(tick_lab, fontsize=8, rotation=45)
344
+ ax.set_ylabel("βˆ’log₁₀(p-value)", color=TEXT)
345
+ ax.set_title(title, fontsize=13, fontweight="bold", color=ACCENT1, pad=12)
346
+ ax.legend(fontsize=8, facecolor=PANEL, edgecolor=GRID_COL,
347
+ labelcolor=TEXT, loc="upper right")
348
+ ax.set_xlim(0, x_offset)
349
+ ax.set_ylim(0, max(log_p.max() + 0.5, sig_line + 1))
350
+ fig.tight_layout()
351
+ return fig
352
+
353
+
354
+ # ── 2. QQ Plot ────────────────────────────────────────────────────────
355
+ def plot_qq(pvals, title="QQ Plot"):
356
+ fig, ax = plt.subplots(figsize=(6, 6))
357
+ style_fig(fig)
358
+ ax = fig.axes[0]
359
+
360
+ n = len(pvals)
361
+ obs = np.sort(-np.log10(np.clip(pvals, 1e-300, 1)))[::-1]
362
+ exp = -np.log10(np.linspace(1/n, 1, n)[::-1])
363
+
364
+ # Confidence band
365
+ ci_lower = -np.log10(stats.beta.ppf(0.975, np.arange(1, n + 1),
366
+ np.arange(n, 0, -1)))
367
+ ci_upper = -np.log10(stats.beta.ppf(0.025, np.arange(1, n + 1),
368
+ np.arange(n, 0, -1)))
369
+ idx = np.argsort(exp)
370
+ ax.fill_between(exp[idx], ci_lower[idx], ci_upper[idx],
371
+ alpha=0.25, color=ACCENT1, label="95% CI")
372
+
373
+ ax.scatter(exp, obs, c=ACCENT1, s=30, edgecolors="none",
374
+ alpha=0.9, zorder=4)
375
+ max_val = max(exp.max(), obs.max()) + 0.3
376
+ ax.plot([0, max_val], [0, max_val], color=ACCENT2,
377
+ lw=1.5, ls="--", label="Expected")
378
+
379
+ lam = np.median(stats.chi2.ppf(1 - pvals, df=1)) / stats.chi2.ppf(0.5, df=1)
380
+ ax.text(0.05, 0.92, f"Ξ» (GC) = {lam:.4f}",
381
+ transform=ax.transAxes, color=GOLD, fontsize=11,
382
+ fontweight="bold")
383
+
384
+ ax.set_xlabel("Expected βˆ’log₁₀(p)", color=TEXT)
385
+ ax.set_ylabel("Observed βˆ’log₁₀(p)", color=TEXT)
386
+ ax.set_title(title, fontsize=13, fontweight="bold", color=ACCENT1, pad=10)
387
+ ax.legend(fontsize=9, facecolor=PANEL, edgecolor=GRID_COL, labelcolor=TEXT)
388
+ fig.tight_layout()
389
+ return fig
390
+
391
+
392
+ # ── 3. PCA Plot ───────────────────────────────────────────────────────
393
+ def plot_pca(G, y, sample_ids=None):
394
+ fig, axes = plt.subplots(1, 2, figsize=(13, 5))
395
+ style_fig(fig)
396
+
397
+ scaler = StandardScaler()
398
+ G_sc = scaler.fit_transform(G)
399
+ n_comp = min(5, G_sc.shape[0] - 1, G_sc.shape[1])
400
+ pca = PCA(n_components=n_comp)
401
+ pcs = pca.fit_transform(G_sc)
402
+ var_exp = pca.explained_variance_ratio_ * 100
403
+
404
+ # Scatter PC1 vs PC2
405
+ sc = axes[0].scatter(pcs[:, 0], pcs[:, 1], c=y,
406
+ cmap=LinearSegmentedColormap.from_list(
407
+ "gwas", [ACCENT2, ACCENT1, ACCENT3]),
408
+ s=80, edgecolors="white", linewidths=0.4, zorder=4)
409
+ cbar = fig.colorbar(sc, ax=axes[0], pad=0.02)
410
+ cbar.set_label("Phenotype", color=TEXT, fontsize=9)
411
+ cbar.ax.yaxis.set_tick_params(color=TEXT)
412
+ plt.setp(cbar.ax.yaxis.get_ticklabels(), color=TEXT)
413
+
414
+ if sample_ids is not None:
415
+ for i, sid in enumerate(sample_ids):
416
+ axes[0].annotate(str(sid), (pcs[i, 0], pcs[i, 1]),
417
+ textcoords="offset points", xytext=(4, 3),
418
+ fontsize=6, color=MUTED)
419
+
420
+ axes[0].set_xlabel(f"PC1 ({var_exp[0]:.1f}%)", color=TEXT)
421
+ axes[0].set_ylabel(f"PC2 ({var_exp[1]:.1f}%)" if n_comp > 1 else "PC2", color=TEXT)
422
+ axes[0].set_title("PCA β€” Population Structure", fontsize=12,
423
+ fontweight="bold", color=ACCENT1)
424
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
425
  # Scree plot
426
+ axes[1].bar(range(1, n_comp + 1), var_exp,
427
+ color=[ACCENT1, ACCENT2, ACCENT3, GOLD, "#ff9100"][:n_comp],
428
+ edgecolor=DARK, linewidth=0.5, zorder=3)
429
+ axes[1].plot(range(1, n_comp + 1), np.cumsum(var_exp),
430
+ color=GOLD, marker="o", ms=5, lw=1.5, label="Cumulative")
431
+ axes[1].set_xlabel("Principal Component", color=TEXT)
432
+ axes[1].set_ylabel("Variance Explained (%)", color=TEXT)
433
+ axes[1].set_title("Scree Plot", fontsize=12, fontweight="bold", color=ACCENT1)
434
+ axes[1].legend(fontsize=9, facecolor=PANEL, edgecolor=GRID_COL, labelcolor=TEXT)
435
+
436
+ fig.tight_layout()
437
+ return fig
438
+
439
+
440
+ # ── 4. LD Decay Plot ──────────────────────────────────────────────────
441
+ def plot_ld_decay(G, positions, chroms, max_dist=None):
442
+ fig, axes = plt.subplots(1, 2, figsize=(13, 5))
443
+ style_fig(fig)
444
+
445
+ m = G.shape[1]
446
+ dists, r2s = [], []
447
+ chrom_list = sorted(set(chroms))
448
+
449
+ for ch in chrom_list:
450
+ idx = np.where(chroms == ch)[0]
451
+ if len(idx) < 2:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
452
  continue
453
+ for i, j in itertools.combinations(idx, 2):
454
+ xi = G[:, i]; xj = G[:, j]
455
+ mask = ~(np.isnan(xi) | np.isnan(xj))
456
+ if mask.sum() < 4:
457
+ continue
458
+ r, p = stats.pearsonr(xi[mask], xj[mask])
459
+ d = abs(positions[j] - positions[i])
460
+ dists.append(d)
461
+ r2s.append(r ** 2)
462
+
463
+ dists = np.array(dists)
464
+ r2s = np.array(r2s)
465
+
466
+ if len(dists) == 0:
467
+ axes[0].text(0.5, 0.5, "Insufficient data for LD", transform=axes[0].transAxes,
468
+ ha="center", color=TEXT)
469
+ axes[1].text(0.5, 0.5, "Insufficient data for LD", transform=axes[1].transAxes,
470
+ ha="center", color=TEXT)
471
+ fig.tight_layout()
472
+ return fig
473
+
474
+ # Scatter + decay curve
475
+ axes[0].scatter(dists / 1000, r2s, alpha=0.4, s=18, color=ACCENT1,
476
+ edgecolors="none", zorder=3)
477
+
478
+ # Bin-based decay
479
+ n_bins = min(15, len(dists))
480
+ bin_edges = np.quantile(dists, np.linspace(0, 1, n_bins + 1))
481
+ bin_mid, bin_r2 = [], []
482
+ for k in range(n_bins):
483
+ mask = (dists >= bin_edges[k]) & (dists < bin_edges[k + 1])
484
+ if mask.sum() > 0:
485
+ bin_mid.append(np.mean(dists[mask]) / 1000)
486
+ bin_r2.append(np.mean(r2s[mask]))
487
+
488
+ axes[0].plot(bin_mid, bin_r2, color=ACCENT2, lw=2.5, zorder=5, label="Mean rΒ²")
489
+ axes[0].axhline(0.1, color=GOLD, ls=":", lw=1.2, label="rΒ² = 0.1 threshold")
490
+ axes[0].set_xlabel("Distance (kb)", color=TEXT)
491
+ axes[0].set_ylabel("rΒ² (LD)", color=TEXT)
492
+ axes[0].set_title("LD Decay", fontsize=12, fontweight="bold", color=ACCENT1)
493
+ axes[0].set_ylim(0, 1.05)
494
+ axes[0].legend(fontsize=9, facecolor=PANEL, edgecolor=GRID_COL, labelcolor=TEXT)
495
+
496
+ # LD heatmap
497
+ m2 = min(m, 20)
498
+ R = np.zeros((m2, m2))
499
+ for i in range(m2):
500
+ for j in range(m2):
501
+ if i == j:
502
+ R[i, j] = 1.0
503
+ continue
504
+ xi = G[:, i]; xj = G[:, j]
505
+ mask = ~(np.isnan(xi) | np.isnan(xj))
506
+ if mask.sum() < 3:
507
+ continue
508
+ r, _ = stats.pearsonr(xi[mask], xj[mask])
509
+ R[i, j] = r ** 2
510
+
511
+ cmap = LinearSegmentedColormap.from_list("ld", [DARK, ACCENT1, GOLD, ACCENT2])
512
+ im = axes[1].imshow(R, cmap=cmap, vmin=0, vmax=1, aspect="auto")
513
+ cbar = fig.colorbar(im, ax=axes[1], pad=0.02)
514
+ cbar.set_label("rΒ²", color=TEXT)
515
+ cbar.ax.yaxis.set_tick_params(color=TEXT)
516
+ plt.setp(cbar.ax.yaxis.get_ticklabels(), color=TEXT)
517
+ axes[1].set_title("LD Heatmap (first 20 SNPs)", fontsize=12,
518
+ fontweight="bold", color=ACCENT1)
519
+ axes[1].set_xlabel("SNP index", color=TEXT)
520
+ axes[1].set_ylabel("SNP index", color=TEXT)
521
+
522
+ fig.tight_layout()
523
+ return fig
524
+
525
+
526
+ # ── 5. Effect Size / Beta Plot ────────────────────────────────────────
527
+ def plot_effect_sizes(results_df, model_name):
528
+ fig, axes = plt.subplots(1, 2, figsize=(13, 5))
529
+ style_fig(fig)
530
+
531
+ df = results_df.sort_values("Beta", ascending=True).reset_index(drop=True)
532
+ colors = [ACCENT2 if b < 0 else ACCENT1 for b in df["Beta"]]
533
+
534
+ axes[0].barh(range(len(df)), df["Beta"], color=colors,
535
+ edgecolor=DARK, linewidth=0.3, zorder=3)
536
+ axes[0].axvline(0, color=TEXT, lw=0.8)
537
+ axes[0].set_yticks(range(len(df)))
538
+ axes[0].set_yticklabels([s[:18] for s in df["SNP"]], fontsize=7)
539
+ axes[0].set_xlabel("Effect Size (Ξ²)", color=TEXT)
540
+ axes[0].set_title(f"Effect Sizes β€” {model_name}", fontsize=11,
541
+ fontweight="bold", color=ACCENT1)
542
+ neg_p = mpatches.Patch(color=ACCENT2, label="Negative effect")
543
+ pos_p = mpatches.Patch(color=ACCENT1, label="Positive effect")
544
+ axes[0].legend(handles=[pos_p, neg_p], fontsize=8,
545
+ facecolor=PANEL, edgecolor=GRID_COL, labelcolor=TEXT)
546
+
547
+ # Volcano plot
548
+ log_p = -np.log10(np.clip(results_df["P_value"].values, 1e-300, 1))
549
+ betas = results_df["Beta"].values
550
+ sig_thr = -np.log10(0.05 / len(results_df))
551
+ colors2 = np.where(log_p >= sig_thr, GOLD,
552
+ np.where(betas > 0, ACCENT1, ACCENT2))
553
+ axes[1].scatter(betas, log_p, c=colors2, s=35, edgecolors="none",
554
+ alpha=0.85, zorder=4)
555
+ axes[1].axhline(sig_thr, color=GOLD, lw=1.2, ls="--",
556
+ label=f"Bonferroni (Ξ±=0.05)")
557
+ axes[1].axvline(0, color=TEXT, lw=0.7, ls=":")
558
+ axes[1].set_xlabel("Effect Size (Ξ²)", color=TEXT)
559
+ axes[1].set_ylabel("βˆ’log₁₀(p)", color=TEXT)
560
+ axes[1].set_title("Volcano Plot", fontsize=11, fontweight="bold", color=ACCENT1)
561
+ axes[1].legend(fontsize=9, facecolor=PANEL, edgecolor=GRID_COL, labelcolor=TEXT)
562
+
563
+ fig.tight_layout()
564
+ return fig
565
+
566
+
567
+ # ── 6. MAF Distribution ───────────────────────────────────────────────
568
+ def plot_maf(maf, snp_names):
569
+ fig, axes = plt.subplots(1, 2, figsize=(12, 5))
570
+ style_fig(fig)
571
+
572
+ axes[0].hist(maf, bins=20, color=ACCENT1, edgecolor=DARK,
573
+ linewidth=0.5, zorder=3)
574
+ axes[0].axvline(0.05, color=ACCENT2, lw=1.5, ls="--", label="MAF = 0.05")
575
+ axes[0].set_xlabel("Minor Allele Frequency", color=TEXT)
576
+ axes[0].set_ylabel("Count", color=TEXT)
577
+ axes[0].set_title("MAF Distribution", fontsize=12, fontweight="bold", color=ACCENT1)
578
+ axes[0].legend(fontsize=9, facecolor=PANEL, edgecolor=GRID_COL, labelcolor=TEXT)
579
+
580
+ # Bar per SNP
581
+ order = np.argsort(maf)[::-1]
582
+ bar_c = [ACCENT1 if m >= 0.05 else ACCENT2 for m in maf[order]]
583
+ axes[1].bar(range(len(maf)), maf[order], color=bar_c,
584
+ edgecolor=DARK, linewidth=0.3, zorder=3)
585
+ axes[1].axhline(0.05, color=GOLD, lw=1.2, ls=":", label="MAF threshold 0.05")
586
+ axes[1].set_xticks(range(len(maf)))
587
+ axes[1].set_xticklabels([snp_names[i][:12] for i in order],
588
+ rotation=90, fontsize=6)
589
+ axes[1].set_ylabel("MAF", color=TEXT)
590
+ axes[1].set_title("Per-SNP MAF", fontsize=12, fontweight="bold", color=ACCENT1)
591
+ axes[1].legend(fontsize=9, facecolor=PANEL, edgecolor=GRID_COL, labelcolor=TEXT)
592
+
593
+ fig.tight_layout()
594
+ return fig
595
+
596
+
597
+ # ── 7. Phenotype Distribution ─────────────────────────────────────────
598
+ def plot_phenotype(y, sample_ids=None):
599
+ fig, axes = plt.subplots(1, 2, figsize=(12, 5))
600
+ style_fig(fig)
601
+
602
+ axes[0].hist(y, bins=15, color=ACCENT1, edgecolor=DARK,
603
+ linewidth=0.5, zorder=3, alpha=0.85)
604
+ mn, sd = y.mean(), y.std()
605
+ axes[0].axvline(mn, color=ACCENT2, lw=1.5, ls="--", label=f"Mean={mn:.2f}")
606
+ axes[0].axvline(mn - sd, color=GOLD, lw=1.0, ls=":", label=f"Β±1SD")
607
+ axes[0].axvline(mn + sd, color=GOLD, lw=1.0, ls=":")
608
+ axes[0].set_xlabel("Phenotype Value", color=TEXT)
609
+ axes[0].set_ylabel("Frequency", color=TEXT)
610
+ axes[0].set_title("Phenotype Distribution", fontsize=12, fontweight="bold", color=ACCENT1)
611
+ axes[0].legend(fontsize=9, facecolor=PANEL, edgecolor=GRID_COL, labelcolor=TEXT)
612
+
613
+ # Box + scatter
614
+ bp = axes[1].boxplot(y, vert=True, patch_artist=True,
615
+ medianprops=dict(color=ACCENT2, lw=2))
616
+ for patch in bp["boxes"]:
617
+ patch.set_facecolor(ACCENT1 + "55")
618
+ patch.set_edgecolor(ACCENT1)
619
+ jitter = np.random.uniform(-0.1, 0.1, size=len(y))
620
+ axes[1].scatter(1 + jitter, y, color=GOLD, s=30,
621
+ alpha=0.8, zorder=5, edgecolors="none")
622
+ axes[1].set_xticks([1])
623
+ axes[1].set_xticklabels(["Phenotype"])
624
+ axes[1].set_ylabel("Value", color=TEXT)
625
+ axes[1].set_title("Box Plot", fontsize=12, fontweight="bold", color=ACCENT1)
626
+ fig.tight_layout()
627
+ return fig
628
+
629
+
630
+ # ── 8. Results Summary Table ──────────────────────────────────────────
631
+ def make_results_table(pvals, betas, snp_names, chroms, positions, model_name):
632
+ bonferroni = 0.05 / len(pvals)
633
+ df = pd.DataFrame({
634
+ "SNP" : snp_names,
635
+ "Chr" : chroms,
636
+ "Pos" : positions,
637
+ "Beta" : np.round(betas, 5),
638
+ "P_value" : pvals,
639
+ "-log10P" : np.round(-np.log10(np.clip(pvals, 1e-300, 1)), 4),
640
+ "Sig" : ["***" if p < bonferroni else ("**" if p < 0.001 else
641
+ ("*" if p < 0.05 else "")) for p in pvals],
642
+ }).sort_values("P_value").reset_index(drop=True)
643
+ return df
644
+
645
+
646
+ # ─────────────────────────── MAIN PIPELINE ────────────────────────────
647
+
648
+ def run_gwas(file_obj, text_input, selected_models, maf_threshold):
649
+ """Master function called by Gradio."""
650
  try:
651
+ df, snp_cols = parse_data(file_obj, text_input)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
652
  except Exception as e:
653
+ return [None] * 12 + [f"❌ Data parsing error: {e}"]
654
+
655
+ y = df["Phenotype"].values.astype(float)
656
+ ids = df["ID"].values
657
+ G_raw = df[snp_cols].values.astype(float)
658
+ G = impute_genotypes(G_raw)
659
+ n, m = G.shape
660
+
661
+ chroms, positions = parse_marker_info(snp_cols)
662
+ maf_vals = compute_maf(G)
663
+
664
+ # MAF filter
665
+ maf_thr = float(maf_threshold)
666
+ keep = maf_vals >= maf_thr
667
+ if keep.sum() < 2:
668
+ keep = np.ones(m, dtype=bool)
669
+ G_filt = G[:, keep]
670
+ maf_filt = maf_vals[keep]
671
+ snp_filt = np.array(snp_cols)[keep]
672
+ chr_filt = chroms[keep]
673
+ pos_filt = positions[keep]
674
+
675
+ # Kinship
676
+ K = build_kinship(G_filt)
677
+
678
+ # ── Run selected models
679
+ model_funcs = {
680
+ "OLS (Simple Linear Regression)": lambda: ols_gwas(y, G_filt),
681
+ "MLM (Mixed Linear Model)": lambda: mlm_gwas(y, G_filt, K),
682
+ "GLM (PCA-corrected)": lambda: glm_gwas(y, G_filt),
683
+ "Compressed MLM": lambda: compressed_mlm_gwas(y, G_filt, K),
684
+ "BLINK": lambda: blink_gwas(y, G_filt),
685
+ "FarmCPU": lambda: farm_cpu_gwas(y, G_filt, K),
686
+ }
687
+
688
+ # Default: run all if none selected
689
+ models_to_run = selected_models if selected_models else list(model_funcs.keys())
690
+
691
+ all_results = {}
692
+ primary_p = None
693
+ primary_b = None
694
+ primary_name = None
695
+
696
+ for mname in models_to_run:
697
+ if mname in model_funcs:
698
+ p, b = model_funcs[mname]()
699
+ all_results[mname] = (p, b)
700
+ if primary_p is None:
701
+ primary_p = p; primary_b = b; primary_name = mname
702
+
703
+ if primary_p is None:
704
+ return [None] * 12 + ["❌ No models selected or run."]
705
+
706
+ # ── Build plots
707
+ fig_pheno = plot_phenotype(y, ids)
708
+ fig_maf = plot_maf(maf_vals, snp_cols)
709
+ fig_pca = plot_pca(G_filt, y, ids)
710
+ fig_ld = plot_ld_decay(G_filt, pos_filt, chr_filt)
711
+ fig_manh = plot_manhattan(primary_p, chr_filt, pos_filt,
712
+ title=f"Manhattan β€” {primary_name}")
713
+ fig_qq = plot_qq(primary_p, title=f"QQ Plot β€” {primary_name}")
714
+
715
+ res_df = make_results_table(primary_p, primary_b, snp_filt,
716
+ chr_filt, pos_filt, primary_name)
717
+ fig_eff = plot_effect_sizes(res_df, primary_name)
718
+
719
+ # Multi-model comparison QQ
720
+ fig_multi = None
721
+ if len(all_results) > 1:
722
+ fig_multi, ax = plt.subplots(figsize=(8, 6))
723
+ style_fig(fig_multi)
724
+ ax = fig_multi.axes[0]
725
+ colors_m = [ACCENT1, ACCENT2, ACCENT3, GOLD, "#ff9100", "#e040fb"]
726
+ for idx2, (mn, (p2, _)) in enumerate(all_results.items()):
727
+ n2 = len(p2)
728
+ obs2 = np.sort(-np.log10(np.clip(p2, 1e-300, 1)))[::-1]
729
+ exp2 = -np.log10(np.linspace(1/n2, 1, n2)[::-1])
730
+ ax.plot(np.sort(exp2), np.sort(obs2),
731
+ color=colors_m[idx2 % len(colors_m)], lw=1.8,
732
+ label=mn[:28], alpha=0.9)
733
+ ax.plot([0, obs2.max()], [0, obs2.max()],
734
+ color=TEXT, lw=1, ls="--")
735
+ ax.set_xlabel("Expected βˆ’log₁₀(p)", color=TEXT)
736
+ ax.set_ylabel("Observed βˆ’log₁₀(p)", color=TEXT)
737
+ ax.set_title("Multi-Model QQ Comparison", fontsize=12,
738
+ fontweight="bold", color=ACCENT1)
739
+ ax.legend(fontsize=7, facecolor=PANEL, edgecolor=GRID_COL, labelcolor=TEXT)
740
+ fig_multi.tight_layout()
741
+
742
+ # ── Summary text
743
+ bonf = 0.05 / len(primary_p)
744
+ n_sig = (primary_p < bonf).sum()
745
+ n_sug = ((primary_p < 1e-5) & (primary_p >= bonf)).sum()
746
+ lam = np.median(stats.chi2.ppf(1 - np.clip(primary_p, 1e-10, 1), df=1)) / stats.chi2.ppf(0.5, df=1)
747
+
748
+ summary = f"""
749
+ ╔═══════════════════════════════════════════════════════╗
750
+ β•‘ GWAS ANALYSIS SUMMARY β•‘
751
+ ╠═══════════════════════════════════════════════════════╣
752
+ Samples : {n}
753
+ SNPs (raw) : {m}
754
+ SNPs (after MAFβ‰₯{maf_thr:.2f}) : {G_filt.shape[1]}
755
+ Models run : {', '.join(all_results.keys())}
756
+ Primary model : {primary_name}
757
+
758
+ Bonferroni threshold : {bonf:.2e}
759
+ Genome-wide sig hits : {n_sig}
760
+ Suggestive hits : {n_sug}
761
+ Genomic inflation Ξ» : {lam:.4f}
762
+
763
+ Top 5 SNPs ({primary_name}):
764
+ {res_df[['SNP','Chr','Pos','Beta','P_value','Sig']].head(5).to_string(index=False)}
765
+ β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•
766
+ """.strip()
767
+
768
+ img_pheno = fig_to_pil(fig_pheno)
769
+ img_maf = fig_to_pil(fig_maf)
770
+ img_pca = fig_to_pil(fig_pca)
771
+ img_ld = fig_to_pil(fig_ld)
772
+ img_manh = fig_to_pil(fig_manh)
773
+ img_qq = fig_to_pil(fig_qq)
774
+ img_eff = fig_to_pil(fig_eff)
775
+ img_multi = fig_to_pil(fig_multi) if fig_multi else None
776
+
777
+ plt.close("all")
778
+
779
+ return (img_pheno, img_maf, img_pca, img_ld,
780
+ img_manh, img_qq, img_eff, img_multi,
781
+ res_df, summary)
782
+
783
+
784
+ # ─────────────────────────── GRADIO UI ───────────────────────────────
785
+
786
+ SAMPLE_DATA = """\
787
+ ID,Phenotype,chr1_134521_LOC_Os01g01280,chr1_134810_LOC_Os01g01280,chr1_178766_LOC_Os01g01360,chr1_210328_LOC_Os01g01420,chr1_216213_LOC_Os01g01430,chr1_216683_LOC_Os01g01430,chr1_216716_LOC_Os01g01430,chr1_216965_LOC_Os01g01430
788
+ IRRI-1,25.34,0,0,0,2,2,-1,0,0
789
+ IRRI-75,23.34,0,0,0,0,0,-1,-1,0
790
+ IRRI-84,26.67,2,0,2,0,0,-1,-1,0
791
+ IRRI-93,23,0,0,0,1,0,-1,0,2
792
+ IRRI-9,28.34,0,0,0,0,0,2,0,0
793
+ IRRI-17,18.67,0,0,0,0,0,2,0,0
794
+ IRRI-25,20,2,0,2,0,0,-1,-1,0
795
+ IRRI-34,37,0,0,0,0,0,2,0,0
796
+ IRRI-42,30.67,0,0,0,0,0,2,0,0
797
+ IRRI-50,22,0,0,0,2,2,-1,0,0
798
+ """
799
+
800
+ CSS = """
801
+ body, .gradio-container {
802
+ background: #0d0f1a !important;
803
+ font-family: 'JetBrains Mono', 'Fira Code', monospace !important;
804
+ color: #ccd6f6 !important;
805
+ }
806
+ .gr-panel, .gr-box, .gr-form {
807
+ background: #131626 !important;
808
+ border: 1px solid #1e2340 !important;
809
+ border-radius: 8px !important;
810
+ }
811
+ h1, h2, h3 { color: #00e5ff !important; }
812
+ label { color: #8892b0 !important; font-size: 0.85rem !important; }
813
+ .gr-button-primary {
814
+ background: linear-gradient(135deg, #00e5ff, #b2ff59) !important;
815
+ color: #0d0f1a !important;
816
+ font-weight: 700 !important;
817
+ border: none !important;
818
+ border-radius: 6px !important;
819
+ }
820
+ .gr-button-secondary {
821
+ background: #1e2340 !important;
822
+ color: #ccd6f6 !important;
823
+ border: 1px solid #00e5ff44 !important;
824
+ border-radius: 6px !important;
825
+ }
826
+ textarea, input[type=text], input[type=number] {
827
+ background: #0d0f1a !important;
828
+ color: #ccd6f6 !important;
829
+ border: 1px solid #1e2340 !important;
830
+ border-radius: 4px !important;
831
+ }
832
+ .gr-check-radio { accent-color: #00e5ff !important; }
833
+ """
834
+
835
+ MODELS = [
836
+ "OLS (Simple Linear Regression)",
837
+ "MLM (Mixed Linear Model)",
838
+ "GLM (PCA-corrected)",
839
+ "Compressed MLM",
840
+ "BLINK",
841
+ "FarmCPU",
842
+ ]
843
+
844
+ with gr.Blocks(css=CSS, title="GWAS Pipeline") as demo:
845
+
846
+ gr.Markdown("""
847
+ # 🧬 GWAS Analysis Pipeline
848
+ ### Genome-Wide Association Study β€” Full Statistical Suite
849
+ *Supports CSV/TSV genotype matrices Β· 6 statistical models Β· Publication-quality plots*
850
+ ---
851
+ """)
852
+
853
  with gr.Row():
854
  with gr.Column(scale=1):
855
+ gr.Markdown("### β‘  Input Data")
856
+ file_in = gr.File(label="Upload CSV/TSV file", file_types=[".csv", ".tsv", ".txt"])
857
+ text_in = gr.Textbox(label="Or paste CSV data here",
858
+ placeholder="Paste your CSV…",
859
+ lines=6, value=SAMPLE_DATA)
860
+
861
+ gr.Markdown("### β‘‘ Models to Run")
862
+ model_sel = gr.CheckboxGroup(choices=MODELS, value=MODELS,
863
+ label="Select statistical models")
864
+
865
+ gr.Markdown("### β‘’ Filters")
866
+ maf_thr = gr.Slider(minimum=0.0, maximum=0.5, value=0.0, step=0.01,
867
+ label="MAF threshold")
868
+
869
+ run_btn = gr.Button("πŸš€ Run GWAS", variant="primary")
870
+ clr_btn = gr.Button("πŸ—‘ Clear", variant="secondary")
871
+
872
+ with gr.Column(scale=3):
873
+ gr.Markdown("### πŸ“Š Results")
874
+ summary_out = gr.Textbox(label="Summary", lines=20, interactive=False)
875
+
876
+ gr.Markdown("---")
877
+
878
+ with gr.Tabs():
879
+ with gr.Tab("πŸ§ͺ Phenotype"):
880
+ img_pheno = gr.Image(label="Phenotype Distribution", type="pil")
881
+ with gr.Tab("πŸ“‰ MAF"):
882
+ img_maf = gr.Image(label="Minor Allele Frequency", type="pil")
883
+ with gr.Tab("πŸ”΅ PCA"):
884
+ img_pca = gr.Image(label="Principal Component Analysis", type="pil")
885
+ with gr.Tab("πŸ”— LD"):
886
+ img_ld = gr.Image(label="Linkage Disequilibrium", type="pil")
887
+ with gr.Tab("πŸ” Manhattan"):
888
+ img_manh = gr.Image(label="Manhattan Plot", type="pil")
889
+ with gr.Tab("πŸ“ˆ QQ Plot"):
890
+ img_qq = gr.Image(label="QQ Plot", type="pil")
891
+ with gr.Tab("βš– Effect Sizes"):
892
+ img_eff = gr.Image(label="Effect Sizes & Volcano", type="pil")
893
+ with gr.Tab("πŸ”€ Multi-Model QQ"):
894
+ img_multi = gr.Image(label="Multi-Model Comparison", type="pil")
895
+ with gr.Tab("πŸ“‹ Top Hits Table"):
896
+ results_tbl = gr.Dataframe(label="GWAS Results (sorted by p-value)",
897
+ interactive=False)
898
+
899
+ def run_wrapper(f, t, m, maf):
900
+ out = run_gwas(f, t, m, maf)
901
+ if isinstance(out[-1], str) and out[-1].startswith("❌"):
902
+ return [None]*8 + [None, out[-1]]
903
+ (ph, mf, pc, ld, mn, qq, ef, mu, df, summ) = out
904
+ return ph, mf, pc, ld, mn, qq, ef, mu, df, summ
905
+
906
  run_btn.click(
907
+ fn=run_wrapper,
908
+ inputs=[file_in, text_in, model_sel, maf_thr],
909
+ outputs=[img_pheno, img_maf, img_pca, img_ld,
910
+ img_manh, img_qq, img_eff, img_multi,
911
+ results_tbl, summary_out],
912
  )
913
+
914
+ def clear_all():
915
+ return [None]*9 + [""]
916
+
917
+ clr_btn.click(fn=clear_all,
918
+ outputs=[img_pheno, img_maf, img_pca, img_ld,
919
+ img_manh, img_qq, img_eff, img_multi,
920
+ results_tbl, summary_out])
921
+
922
+ gr.Markdown("""
923
+ ---
924
+ **Models implemented:** OLS Β· Mixed Linear Model (MLM) Β· PCA-corrected GLM Β· Compressed MLM Β· BLINK Β· FarmCPU
925
+ **Plots:** Phenotype distribution Β· MAF Β· PCA + Scree Β· LD Decay + Heatmap Β· Manhattan Β· QQ Β· Effect sizes Β· Volcano Β· Multi-model QQ
926
+ """)
927
 
928
  if __name__ == "__main__":
929
+ demo.launch(share=False, server_port=7860)