softwareDevelopment commited on
Commit
a579948
Β·
verified Β·
1 Parent(s): 80b80da

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +471 -1082
app.py CHANGED
@@ -1,15 +1,13 @@
1
  # -*- coding: utf-8 -*-
2
  """
3
- GWAS Pipeline v10.0 - Complete Analysis with PCA & Kinship
4
- Features:
5
- - Soft pastel color scheme with Times New Roman
6
- - 6 GWAS models (Linear, Mixed, ElasticNet, Lasso, Ridge, Random Forest)
7
- - PCA analysis and visualization
8
- - Kinship matrix calculation
9
- - LD decay plot in Mb
10
- - Circos plot
11
- - Manhattan plot with LOD scores
12
- - Population structure correction
13
  """
14
 
15
  import gradio as gr
@@ -20,924 +18,503 @@ matplotlib.use('Agg')
20
  import matplotlib.pyplot as plt
21
  from matplotlib.patches import Circle
22
  import matplotlib.patches as mpatches
23
- from matplotlib.lines import Line2D
24
- import seaborn as sns
25
  from scipy import stats
26
- from scipy.spatial.distance import pdist, squareform
27
  from scipy.optimize import curve_fit
28
- import os, warnings, tempfile, zipfile, io
29
  from sklearn.linear_model import ElasticNetCV, LassoCV, RidgeCV
30
  from sklearn.ensemble import RandomForestRegressor
31
  from sklearn.preprocessing import StandardScaler
32
  from sklearn.impute import SimpleImputer
33
  from sklearn.decomposition import PCA
34
- from sklearn.model_selection import KFold
35
  from sklearn.metrics import r2_score
 
36
  import statsmodels.api as sm
37
- from statsmodels.formula.api import mixedlm
38
- from scipy.cluster.hierarchy import dendrogram, linkage
39
  warnings.filterwarnings('ignore')
40
 
41
- # Set Times New Roman as default font
42
  plt.rcParams['font.family'] = 'Times New Roman'
43
- plt.rcParams['font.size'] = 10
44
- plt.rcParams['mathtext.fontset'] = 'stix'
45
 
46
  # ══════════════════════════════════════════════════════════════
47
- # SOFT PASTEL COLOR PALETTE
48
  # ══════════════════════════════════════════════════════════════
49
 
50
- # Background and UI colors
51
- BG_PASTEL = "#FDF8F0" # Soft cream
52
- PANEL_PASTEL = "#F5F0E8" # Warm off-white
53
- CARD_PASTEL = "#FFFEF8" # Very light cream
54
- TEXT_PASTEL = "#4A4A4A" # Soft charcoal
55
- BORDER_PASTEL = "#E8DCC8" # Muted beige
56
- GRID_PASTEL = "#E8E0D5" # Soft grid color
57
 
58
- # Plot colors
59
- PRIMARY = "#C5A3FF" # Soft lavender
60
- SECONDARY = "#A8E6CF" # Mint green
61
- TERTIARY = "#FFD3B6" # Peach
62
- QUATERNARY = "#FFB3BA" # Soft pink
63
- QUINARY = "#B5EAD7" # Seafoam
64
- SENARY = "#C7CEEA" # Periwinkle
65
- ACCENT = "#FFAAA5" # Coral
66
- HIGHLIGHT = "#FFDAC1" # Warm peach
67
- LOD_COLOR = "#95CDBA" # Sage green
68
- SIGNIFICANT = "#E8A598" # Dusty rose
69
- PCA_COLOR1 = "#B8D4E3" # Baby blue
70
- PCA_COLOR2 = "#F4C3A2" # Soft orange
71
- KINSHIP_COLOR = "#D5E4CF" # Pale green
72
-
73
- CHROM_COLORS = [
74
- "#E8D5F5", "#D4F1F9", "#FDE2C4", "#E2F0CB", "#FFD9E8",
75
- "#C9E4DE", "#FADADD", "#D5E4CF", "#FCE1E4", "#CFBAE1",
76
- "#B8E2D6", "#FFDAC8", "#E8D1C5", "#C5E0D4", "#F8D5E3",
77
- "#D6E5E3", "#FFE0B5", "#D4C5E2", "#C9E6D8", "#F2D7D9"
78
- ]
79
 
80
  # ══════════════════════════════════════════════════════════════
81
- # CUSTOM CSS FOR SOFT PASTEL INTERFACE
82
  # ══════════════════════════════════════════════════════════════
83
 
84
- PASTEL_CSS = """
85
  <style>
86
- @import url('https://fonts.googleapis.com/css2?family=Times+New+Roman&display=swap');
87
-
88
- * {
89
- font-family: 'Times New Roman', Times, serif !important;
90
- }
91
-
92
- .gradio-container {
93
- background: linear-gradient(135deg, #FDF8F0 0%, #F5F0E8 100%) !important;
94
- padding: 20px !important;
95
- }
96
-
97
- .main-header {
98
- background: linear-gradient(135deg, #E8D5F5 0%, #D4F1F9 100%);
99
- padding: 40px;
100
- border-radius: 25px;
101
- text-align: center;
102
- margin-bottom: 30px;
103
- box-shadow: 0 8px 20px rgba(0,0,0,0.05);
104
- border: 1px solid #E8DCC8;
105
- }
106
-
107
- .main-header h1 {
108
- color: #4A4A4A;
109
- font-size: 2.5em;
110
- margin: 0;
111
- font-weight: 600;
112
- letter-spacing: 1px;
113
- }
114
-
115
- .main-header p {
116
- color: #6B6B6B;
117
- font-size: 1.1em;
118
- margin-top: 10px;
119
- }
120
-
121
- .section-header {
122
- background: linear-gradient(135deg, #C5A3FF 0%, #B8D4E3 100%);
123
- padding: 12px 20px;
124
- border-radius: 15px;
125
- margin: 20px 0 15px 0;
126
- color: #4A4A4A;
127
- font-weight: 600;
128
- font-size: 1.1em;
129
- border: 1px solid #E8DCC8;
130
- }
131
-
132
- .card {
133
- background: #FFFEF8;
134
- border-radius: 15px;
135
- padding: 20px;
136
- margin: 10px 0;
137
- box-shadow: 0 4px 12px rgba(0,0,0,0.05);
138
- border: 1px solid #E8DCC8;
139
- transition: all 0.3s ease;
140
- }
141
-
142
- .card:hover {
143
- transform: translateY(-2px);
144
- box-shadow: 0 8px 20px rgba(0,0,0,0.08);
145
- }
146
-
147
- .stat-box {
148
- background: linear-gradient(135deg, #F5F0E8 0%, #FFFEF8 100%);
149
- border-radius: 12px;
150
- padding: 15px;
151
- text-align: center;
152
- margin: 10px;
153
- border: 1px solid #E8DCC8;
154
- }
155
-
156
- .stat-number {
157
- font-size: 2em;
158
- font-weight: bold;
159
- color: #8B6B9D;
160
- }
161
-
162
- .stat-label {
163
- font-size: 0.9em;
164
- color: #8B8B8B;
165
- margin-top: 5px;
166
- }
167
-
168
- .run-btn {
169
- background: linear-gradient(135deg, #C5A3FF 0%, #A8E6CF 100%);
170
- border: none;
171
- color: #4A4A4A;
172
- padding: 12px 30px;
173
- border-radius: 25px;
174
- font-weight: 600;
175
- font-size: 1.1em;
176
- cursor: pointer;
177
- transition: all 0.3s;
178
- border: 1px solid #E8DCC8;
179
- }
180
-
181
- .run-btn:hover {
182
- transform: scale(1.02);
183
- box-shadow: 0 5px 15px rgba(0,0,0,0.1);
184
- background: linear-gradient(135deg, #D4B5FF 0%, #B8E6CF 100%);
185
- }
186
-
187
- footer {
188
- text-align: center;
189
- padding: 20px;
190
- margin-top: 30px;
191
- color: #8B8B8B;
192
- background: rgba(255,254,248,0.9);
193
- border-radius: 15px;
194
- border: 1px solid #E8DCC8;
195
- }
196
-
197
- label, span, p, h1, h2, h3, h4 {
198
- color: #4A4A4A !important;
199
- }
200
-
201
- input, textarea, select {
202
- background: #FFFEF8 !important;
203
- border: 1px solid #E8DCC8 !important;
204
- color: #4A4A4A !important;
205
- }
206
-
207
- .tab-nav button {
208
- background: #F5F0E8 !important;
209
- color: #4A4A4A !important;
210
- border: 1px solid #E8DCC8 !important;
211
- }
212
-
213
- .tab-nav button.selected {
214
- background: #C5A3FF !important;
215
- color: #4A4A4A !important;
216
- }
217
  </style>
218
  """
219
 
220
  # ══════════════════════════════════════════════════════════════
221
- # PLOT STYLING FUNCTION
222
- # ══════════════════════════════════════════════════════════════
223
-
224
- def set_pastel_plot_style():
225
- """Set soft pastel styling for plots"""
226
- plt.rcParams.update({
227
- 'figure.facecolor': BG_PASTEL,
228
- 'axes.facecolor': PANEL_PASTEL,
229
- 'axes.edgecolor': BORDER_PASTEL,
230
- 'axes.labelcolor': TEXT_PASTEL,
231
- 'axes.titlecolor': TEXT_PASTEL,
232
- 'xtick.color': TEXT_PASTEL,
233
- 'ytick.color': TEXT_PASTEL,
234
- 'text.color': TEXT_PASTEL,
235
- 'grid.color': GRID_PASTEL,
236
- 'grid.linewidth': 0.8,
237
- 'grid.alpha': 0.6,
238
- 'figure.dpi': 150,
239
- 'font.family': 'Times New Roman',
240
- 'font.size': 11,
241
- 'axes.spines.top': False,
242
- 'axes.spines.right': False,
243
- 'legend.framealpha': 0.95,
244
- 'legend.edgecolor': BORDER_PASTEL,
245
- 'legend.fancybox': True,
246
- 'legend.shadow': True,
247
- 'legend.fontsize': 10,
248
- })
249
-
250
- # ══════════════════════════════════════════════════════════════
251
- # PCA ANALYSIS FUNCTIONS
252
  # ═════════════════════════���════════════════════════════════════
253
 
254
- def perform_pca(genotypes, n_components=10):
255
- """Perform PCA on genotype data"""
256
- # Impute missing values
257
- imputer = SimpleImputer(strategy='mean')
258
- genotypes_imputed = imputer.fit_transform(genotypes)
259
 
260
- # Standardize
261
- scaler = StandardScaler()
262
- genotypes_scaled = scaler.fit_transform(genotypes_imputed)
263
 
264
- # Perform PCA
265
- pca = PCA(n_components=min(n_components, genotypes_scaled.shape[1]))
266
- pca_result = pca.fit_transform(genotypes_scaled)
 
 
 
 
 
 
 
 
 
 
 
 
267
 
268
- explained_variance = pca.explained_variance_ratio_
269
- cumulative_variance = np.cumsum(explained_variance)
 
 
 
270
 
271
- return pca_result, explained_variance, cumulative_variance, pca.components_
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
272
 
273
- def plot_pca_results(pca_result, explained_variance, phenotypes, save_path):
274
- """Create beautiful PCA visualization with pastel colors"""
275
- set_pastel_plot_style()
276
-
277
- fig, axes = plt.subplots(2, 2, figsize=(14, 12), facecolor=BG_PASTEL)
278
-
279
- # Plot 1: Scree plot
280
- ax1 = axes[0, 0]
281
- components = range(1, len(explained_variance) + 1)
282
- ax1.bar(components, explained_variance * 100, color=PRIMARY, alpha=0.7,
283
- edgecolor=BORDER_PASTEL, linewidth=1)
284
- ax1.plot(components, np.cumsum(explained_variance) * 100, 'o-',
285
- color=SIGNIFICANT, linewidth=2, markersize=6, label='Cumulative')
286
- ax1.set_xlabel('Principal Component', fontsize=12, fontweight='500')
287
- ax1.set_ylabel('Variance Explained (%)', fontsize=12, fontweight='500')
288
- ax1.set_title('Scree Plot', fontsize=14, fontweight='600', pad=15)
289
- ax1.legend(loc='upper right', fontsize=10)
290
- ax1.grid(True, alpha=0.3)
291
- ax1.set_facecolor(PANEL_PASTEL)
292
 
293
- # Plot 2: PC1 vs PC2 colored by phenotype quantiles
294
- ax2 = axes[0, 1]
295
- if phenotypes is not None and len(phenotypes) == len(pca_result):
296
- # Create phenotype quantiles for coloring
297
- pheno_quantiles = pd.qcut(phenotypes, q=5, labels=['Q1', 'Q2', 'Q3', 'Q4', 'Q5'])
298
- quantile_colors = [PRIMARY, SECONDARY, TERTIARY, QUATERNARY, QUINARY]
299
- unique_quantiles = ['Q1', 'Q2', 'Q3', 'Q4', 'Q5']
300
 
301
- for i, q in enumerate(unique_quantiles):
302
- mask = pheno_quantiles == q
303
- if mask.sum() > 0:
304
- ax2.scatter(pca_result[mask, 0], pca_result[mask, 1],
305
- c=quantile_colors[i], s=50, alpha=0.7,
306
- edgecolors='white', linewidth=0.5,
307
- label=f'Phenotype {q}')
308
- else:
309
- ax2.scatter(pca_result[:, 0], pca_result[:, 1], c=PRIMARY,
310
- s=50, alpha=0.7, edgecolors='white', linewidth=0.5)
311
-
312
- ax2.set_xlabel(f'PC1 ({explained_variance[0]*100:.1f}%)', fontsize=12, fontweight='500')
313
- ax2.set_ylabel(f'PC2 ({explained_variance[1]*100:.1f}%)', fontsize=12, fontweight='500')
314
- ax2.set_title('Population Structure (PC1 vs PC2)', fontsize=14, fontweight='600', pad=15)
315
- ax2.legend(loc='best', fontsize=8)
316
- ax2.grid(True, alpha=0.3)
317
- ax2.set_facecolor(PANEL_PASTEL)
 
 
 
 
318
 
319
- # Plot 3: Cumulative variance
320
- ax3 = axes[1, 0]
321
- cumulative = np.cumsum(explained_variance) * 100
322
- ax3.fill_between(components, cumulative, alpha=0.3, color=SECONDARY)
323
- ax3.plot(components, cumulative, 'o-', color=SECONDARY, linewidth=2, markersize=6)
324
- ax3.axhline(y=80, color=SIGNIFICANT, linestyle='--', linewidth=1.5,
325
- alpha=0.7, label='80% variance')
326
- ax3.set_xlabel('Number of Components', fontsize=12, fontweight='500')
327
- ax3.set_ylabel('Cumulative Variance (%)', fontsize=12, fontweight='500')
328
- ax3.set_title('Cumulative Explained Variance', fontsize=14, fontweight='600', pad=15)
329
- ax3.legend(loc='lower right', fontsize=10)
330
- ax3.grid(True, alpha=0.3)
331
- ax3.set_facecolor(PANEL_PASTEL)
332
-
333
- # Plot 4: PC3 vs PC4
334
- ax4 = axes[1, 1]
335
- if len(pca_result[0]) > 3:
336
- if phenotypes is not None:
337
- ax4.scatter(pca_result[:, 2], pca_result[:, 3], c=phenotypes,
338
- cmap='coolwarm', s=50, alpha=0.7, edgecolors='white', linewidth=0.5)
339
- else:
340
- ax4.scatter(pca_result[:, 2], pca_result[:, 3], c=TERTIARY,
341
- s=50, alpha=0.7, edgecolors='white', linewidth=0.5)
342
- ax4.set_xlabel(f'PC3 ({explained_variance[2]*100:.1f}%)', fontsize=12, fontweight='500')
343
- ax4.set_ylabel(f'PC4 ({explained_variance[3]*100:.1f}%)', fontsize=12, fontweight='500')
344
- else:
345
- ax4.text(0.5, 0.5, 'Insufficient components\nfor PC3/PC4 visualization',
346
- ha='center', va='center', transform=ax4.transAxes, fontsize=12)
347
- ax4.set_title('Additional Principal Components', fontsize=14, fontweight='600', pad=15)
348
- ax4.grid(True, alpha=0.3)
349
- ax4.set_facecolor(PANEL_PASTEL)
350
-
351
- plt.tight_layout(pad=2)
352
- plt.savefig(save_path, dpi=200, bbox_inches='tight', facecolor=BG_PASTEL)
353
- plt.close(fig)
354
-
355
- # ══════════════════════════════════════════════════════════════
356
- # KINSHIP MATRIX FUNCTIONS
357
- # ══════════════════════════════════════════════════════════════
358
 
359
- def calculate_kinship_matrix(genotypes):
360
- """Calculate kinship matrix using VanRaden method"""
361
- # Impute missing values
362
- imputer = SimpleImputer(strategy='mean')
363
- genotypes_imputed = imputer.fit_transform(genotypes)
364
 
365
- # Center the matrix
366
- n_markers = genotypes_imputed.shape[1]
367
- genotypes_centered = genotypes_imputed - np.mean(genotypes_imputed, axis=0)
368
 
369
- # Calculate kinship matrix
370
- kinship = np.dot(genotypes_centered, genotypes_centered.T) / (2 * n_markers)
 
 
 
 
371
 
372
- return kinship
373
-
374
- def plot_kinship_matrix(kinship, save_path):
375
- """Create beautiful kinship matrix heatmap"""
376
- set_pastel_plot_style()
377
 
378
- fig, axes = plt.subplots(1, 2, figsize=(14, 6), facecolor=BG_PASTEL)
 
 
 
 
 
 
 
 
 
 
 
 
 
379
 
380
- # Plot 1: Kinship heatmap
381
- ax1 = axes[0]
382
- im = ax1.imshow(kinship, cmap='RdYlBu_r', aspect='auto',
383
- vmin=0, vmax=1, interpolation='nearest')
 
 
384
 
385
- # Add colorbar
386
- cbar = plt.colorbar(im, ax=ax1, shrink=0.8)
387
- cbar.set_label('Kinship Coefficient', fontsize=11, fontweight='500')
 
 
 
 
 
388
 
389
- ax1.set_title('Kinship Matrix Heatmap', fontsize=14, fontweight='600', pad=15)
390
- ax1.set_xlabel('Samples', fontsize=11, fontweight='500')
391
- ax1.set_ylabel('Samples', fontsize=11, fontweight='500')
392
- ax1.tick_params(axis='both', which='both', length=0)
 
 
 
 
393
 
394
- # Plot 2: Kinship distribution histogram
395
  ax2 = axes[1]
396
- kinship_values = kinship[np.triu_indices_from(kinship, k=1)]
397
-
398
- ax2.hist(kinship_values, bins=50, color=PRIMARY, alpha=0.7,
399
- edgecolor=BORDER_PASTEL, linewidth=1)
400
- ax2.axvline(np.mean(kinship_values), color=SIGNIFICANT, linestyle='--',
401
- linewidth=2, label=f'Mean: {np.mean(kinship_values):.3f}')
402
- ax2.axvline(np.median(kinship_values), color=SECONDARY, linestyle='--',
403
- linewidth=2, label=f'Median: {np.median(kinship_values):.3f}')
404
-
405
- ax2.set_xlabel('Kinship Coefficient', fontsize=12, fontweight='500')
406
- ax2.set_ylabel('Frequency', fontsize=12, fontweight='500')
407
- ax2.set_title('Distribution of Kinship Coefficients', fontsize=14, fontweight='600', pad=15)
408
- ax2.legend(loc='upper right', fontsize=10)
409
- ax2.grid(True, alpha=0.3)
410
  ax2.set_facecolor(PANEL_PASTEL)
 
 
 
 
 
 
411
 
412
- plt.tight_layout(pad=2)
413
- plt.savefig(save_path, dpi=200, bbox_inches='tight', facecolor=BG_PASTEL)
414
- plt.close(fig)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
415
 
416
- return {
417
- 'mean_kinship': float(np.mean(kinship_values)),
418
- 'max_kinship': float(np.max(kinship_values)),
419
- 'min_kinship': float(np.min(kinship_values))
420
- }
421
 
422
  # ══════════════════════════════════════════════════════════════
423
- # ENHANCED GWAS MODELS WITH PCA CORRECTION
424
  # ══════════════════════════════════════════════════════════════
425
 
426
- def linear_regression_with_pca(genotypes, phenotypes, pcs, n_pcs=3):
427
- """Linear regression GWAS with PCA correction"""
428
  n_markers = genotypes.shape[1]
429
  pvals = np.ones(n_markers)
430
  effects = np.zeros(n_markers)
431
  lod = np.zeros(n_markers)
432
 
433
- # Include first n_pcs as covariates
434
- if pcs is not None and len(pcs) > 0:
435
- covariates = pcs[:, :min(n_pcs, pcs.shape[1])]
436
- else:
437
- covariates = None
438
 
439
- for i in range(n_markers):
440
- X = genotypes[:, i]
441
- if np.std(X) > 1e-6:
442
- try:
443
- if covariates is not None:
444
- # Combine marker and covariates
445
- X_matrix = np.column_stack([covariates, X])
446
- X_matrix = sm.add_constant(X_matrix)
447
- model = sm.OLS(phenotypes, X_matrix).fit()
448
- # P-value for marker (last coefficient before constant)
449
- pvals[i] = model.pvalues[-1]
450
- effects[i] = model.params[-1]
451
- else:
452
- X = sm.add_constant(X)
453
- model = sm.OLS(phenotypes, X).fit()
454
- pvals[i] = model.pvalues[1]
455
- effects[i] = model.params[1]
456
-
457
- lod[i] = -np.log10(pvals[i] + 1e-300)
458
- except:
459
- pass
460
 
461
  return pvals, effects, lod
462
 
463
- def mixed_model_with_kinship(genotypes, phenotypes, kinship):
464
- """Mixed linear model GWAS with kinship matrix"""
465
  n_markers = genotypes.shape[1]
466
  pvals = np.ones(n_markers)
467
  effects = np.zeros(n_markers)
468
  lod = np.zeros(n_markers)
469
 
470
- # Simplified mixed model implementation
471
- for i in range(min(n_markers, 500)): # Limit for performance
472
- X = genotypes[:, i]
 
 
 
473
  if np.std(X) > 1e-6:
474
  try:
475
  data = pd.DataFrame({'pheno': phenotypes, 'marker': X})
476
- # Add kinship as random effect (simplified)
477
- model = mixedlm("pheno ~ marker", data, groups=data.index).fit()
478
- pvals[i] = model.pvalues[1]
479
- effects[i] = model.params[1]
480
- lod[i] = -np.log10(pvals[i] + 1e-300)
481
  except:
482
  pass
483
 
 
 
 
 
 
484
  return pvals, effects, lod
485
 
486
- def elasticnet_with_pca(genotypes, phenotypes, pcs, n_pcs=3):
487
- """ElasticNet regression with PCA correction"""
488
  scaler = StandardScaler()
489
  X_scaled = scaler.fit_transform(genotypes)
490
 
491
- # Add PCA covariates
492
- if pcs is not None and len(pcs) > 0:
493
- covariates = pcs[:, :min(n_pcs, pcs.shape[1])]
494
- X_with_cov = np.column_stack([covariates, X_scaled])
495
- else:
496
- X_with_cov = X_scaled
497
-
498
- enet = ElasticNetCV(cv=5, random_state=42, max_iter=5000, n_alphas=10)
499
- enet.fit(X_with_cov, phenotypes)
500
-
501
- # Extract marker coefficients (excluding covariates)
502
- if pcs is not None:
503
- coefficients = enet.coef_[min(n_pcs, pcs.shape[1]):]
504
- else:
505
- coefficients = enet.coef_
506
-
507
- cv_score = enet.score(X_with_cov, phenotypes)
508
-
509
- # Bootstrap for p-values
510
- n_bootstrap = 50
511
- bootstrap_coefs = []
512
- for _ in range(min(n_bootstrap, len(phenotypes))):
513
- idx = np.random.choice(len(phenotypes), len(phenotypes), replace=True)
514
- enet_boot = ElasticNetCV(cv=3, random_state=42, max_iter=3000)
515
- enet_boot.fit(X_with_cov[idx], phenotypes[idx])
516
- if pcs is not None:
517
- bootstrap_coefs.append(enet_boot.coef_[min(n_pcs, pcs.shape[1]):])
518
- else:
519
- bootstrap_coefs.append(enet_boot.coef_)
520
 
521
- bootstrap_coefs = np.array(bootstrap_coefs)
522
- pvals = np.ones(len(coefficients))
523
- for i in range(len(coefficients)):
524
- if np.std(bootstrap_coefs[:, i]) > 0:
525
- z_score = abs(coefficients[i]) / (np.std(bootstrap_coefs[:, i]) + 1e-10)
526
- pvals[i] = 2 * (1 - stats.norm.cdf(z_score))
527
 
 
 
 
528
  lod = -np.log10(pvals + 1e-300)
529
 
530
- return pvals, coefficients, lod, cv_score
531
-
532
- # ══════════════════════════════════════════════════════════════
533
- # PLOTTING FUNCTIONS
534
- # ══════════════════════════════════════════════════════════════
535
 
536
- def plot_manhattan_lod(marker_names, chromosomes, p_values, lod_scores,
537
- sig_threshold, save_path):
538
- """Create Manhattan plot with LOD scores overlay"""
539
- set_pastel_plot_style()
540
-
541
- unique_chroms = sorted(set(chromosomes),
542
- key=lambda x: (int(x) if str(x).isdigit() else 999, str(x)))
543
- log_p = -np.log10(np.array(p_values) + 1e-300)
544
-
545
- # Calculate positions
546
- GAP = max(15, len(marker_names) // 80)
547
- x_pos = np.zeros(len(marker_names))
548
- chrom_to_idx = {}
549
-
550
- for i, c in enumerate(chromosomes):
551
- chrom_to_idx.setdefault(c, []).append(i)
552
-
553
- offset = 0
554
- chrom_positions = {}
555
- for ch in unique_chroms:
556
- idxs = chrom_to_idx.get(ch, [])
557
- if not idxs:
558
- continue
559
- for r, idx in enumerate(idxs):
560
- x_pos[idx] = offset + r
561
- chrom_positions[ch] = (offset, offset + len(idxs))
562
- offset += len(idxs) + GAP
563
-
564
- # Create figure
565
- fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(20, 12),
566
- gridspec_kw={'height_ratios': [2.5, 1]},
567
- facecolor=BG_PASTEL)
568
-
569
- # Top plot: Manhattan
570
- significant_idx = np.where(p_values < sig_threshold)[0]
571
-
572
- for i, ch in enumerate(unique_chroms):
573
- idxs = chrom_to_idx.get(ch, [])
574
- if not idxs:
575
- continue
576
- x0 = x_pos[idxs[0]] - 0.5
577
- x1 = x_pos[idxs[-1]] + 0.5
578
- if i % 2 == 0:
579
- ax1.axvspan(x0, x1, color=CHROM_COLORS[i % len(CHROM_COLORS)], alpha=0.4, zorder=0)
580
-
581
- # Plot points
582
- for i, ch in enumerate(unique_chroms):
583
- idxs = chrom_to_idx.get(ch, [])
584
- if not idxs:
585
- continue
586
- color = CHROM_COLORS[i % len(CHROM_COLORS)]
587
-
588
- normal = [idx for idx in idxs if idx not in significant_idx]
589
- if normal:
590
- ax1.scatter(x_pos[normal], log_p[normal], c=color, s=18,
591
- alpha=0.7, linewidths=0, zorder=2)
592
-
593
- sig = [idx for idx in idxs if idx in significant_idx]
594
- if sig:
595
- ax1.scatter(x_pos[sig], log_p[sig], c=SIGNIFICANT, s=120,
596
- alpha=0.9, edgecolors='white', linewidths=1.5,
597
- marker='D', zorder=3, label='Significant' if i == 0 else "")
598
-
599
- # Threshold lines
600
- bonf_line = -np.log10(sig_threshold)
601
- ax1.axhline(bonf_line, color=SIGNIFICANT, linestyle='--',
602
- linewidth=2, alpha=0.8, label=f'Bonferroni (p={sig_threshold:.1e})')
603
- ax1.axhline(3, color=SECONDARY, linestyle=':', linewidth=2,
604
- alpha=0.8, label='LOD β‰₯ 3')
605
-
606
- # Add LOD as secondary axis
607
- ax1_twin = ax1.twinx()
608
- lod_array = np.array(lod_scores)
609
- ax1_twin.scatter(x_pos, lod_array, c=LOD_COLOR, s=12, alpha=0.5,
610
- marker='x', label='LOD Score', zorder=1)
611
- ax1_twin.set_ylabel('LOD Score', fontsize=12, color=LOD_COLOR, fontweight='500')
612
- ax1_twin.tick_params(axis='y', colors=TEXT_PASTEL)
613
- max_lod = lod_array.max() if len(lod_array) > 0 else 5
614
- ax1_twin.set_ylim(0, max_lod * 1.15)
615
-
616
- ax1.set_xlim(-GAP, offset)
617
- ax1.set_ylim(bottom=0, top=log_p.max() * 1.15)
618
- ax1.set_ylabel('-log₁₀(P-value)', fontsize=13, color=TEXT_PASTEL, fontweight='500', labelpad=10)
619
- ax1.set_xlabel('Chromosome', fontsize=13, color=TEXT_PASTEL, fontweight='500', labelpad=10)
620
- ax1.set_title('GWAS Manhattan Plot with LOD Scores', fontsize=16,
621
- color=TEXT_PASTEL, fontweight='600', pad=20)
622
- ax1.grid(True, alpha=0.3)
623
- ax1.legend(loc='upper right', fontsize=10)
624
-
625
- # Set x-ticks
626
- tick_positions = []
627
- tick_labels = []
628
- for ch in unique_chroms:
629
- start, end = chrom_positions[ch]
630
- center = (start + end) / 2
631
- tick_positions.append(center)
632
- tick_labels.append(str(ch))
633
- ax1.set_xticks(tick_positions)
634
- ax1.set_xticklabels(tick_labels, rotation=45, ha='right', fontsize=10)
635
-
636
- # Bottom plot: LOD profile
637
- for i, ch in enumerate(unique_chroms):
638
- idxs = chrom_to_idx.get(ch, [])
639
- if not idxs:
640
- continue
641
- x0 = x_pos[idxs[0]] - 0.5
642
- x1 = x_pos[idxs[-1]] + 0.5
643
- if i % 2 == 0:
644
- ax2.axvspan(x0, x1, color=CHROM_COLORS[i % len(CHROM_COLORS)], alpha=0.4, zorder=0)
645
-
646
- ax2.plot(x_pos, lod_array, color=LOD_COLOR, linewidth=2, alpha=0.8)
647
- ax2.fill_between(x_pos, 0, lod_array, color=LOD_COLOR, alpha=0.2)
648
- ax2.axhline(3, color=SECONDARY, linestyle='--', linewidth=1.5, alpha=0.8)
649
- ax2.set_xlim(-GAP, offset)
650
- ax2.set_ylabel('LOD Score', fontsize=12, color=TEXT_PASTEL, fontweight='500')
651
- ax2.set_xlabel('Chromosome', fontsize=12, color=TEXT_PASTEL, fontweight='500')
652
- ax2.set_ylim(0, max_lod * 1.15)
653
- ax2.grid(True, alpha=0.3)
654
- ax2.set_xticks(tick_positions)
655
- ax2.set_xticklabels(tick_labels, rotation=45, ha='right', fontsize=10)
656
-
657
- plt.tight_layout(pad=2)
658
- plt.savefig(save_path, dpi=200, bbox_inches='tight', facecolor=BG_PASTEL)
659
- plt.close(fig)
660
-
661
- def plot_ld_decay_mb(genotypes, chromosomes, positions, save_path, max_distance_mb=5):
662
- """Create LD decay plot with distances in Megabases"""
663
- set_pastel_plot_style()
664
-
665
- unique_chroms = sorted(set(chromosomes),
666
- key=lambda x: (int(x) if str(x).isdigit() else 999, str(x)))
667
-
668
- all_distances_mb = []
669
- all_r2 = []
670
-
671
- for ch in unique_chroms:
672
- idxs = [i for i, c in enumerate(chromosomes) if c == ch]
673
- if len(idxs) < 4:
674
- continue
675
-
676
- if len(idxs) > 200:
677
- idxs = sorted(np.random.choice(idxs, 200, replace=False))
678
-
679
- G = genotypes[:, idxs].copy()
680
- pos_ch = [positions[i] for i in idxs]
681
- pos_mb = [p / 1_000_000 if p > 1000 else p for p in pos_ch]
682
-
683
- for i in range(len(idxs)):
684
- for j in range(i+1, min(i+80, len(idxs))):
685
- dist = abs(pos_mb[j] - pos_mb[i])
686
- if dist > max_distance_mb:
687
- continue
688
-
689
- r = np.corrcoef(G[:, i], G[:, j])[0, 1]
690
- r2 = r**2 if not np.isnan(r) else 0
691
-
692
- all_distances_mb.append(dist)
693
- all_r2.append(r2)
694
-
695
- fig, ax = plt.subplots(figsize=(12, 8), facecolor=BG_PASTEL)
696
- ax.set_facecolor(PANEL_PASTEL)
697
-
698
- if all_distances_mb:
699
- distances = np.array(all_distances_mb)
700
- r2_values = np.array(all_r2)
701
-
702
- bins = np.linspace(0, max_distance_mb, 40)
703
- bin_centers = []
704
- bin_means = []
705
- bin_stds = []
706
-
707
- for i in range(len(bins)-1):
708
- mask = (distances >= bins[i]) & (distances < bins[i+1])
709
- if mask.sum() > 5:
710
- bin_centers.append((bins[i] + bins[i+1]) / 2)
711
- bin_means.append(np.mean(r2_values[mask]))
712
- bin_stds.append(np.std(r2_values[mask]) / np.sqrt(mask.sum()))
713
-
714
- def decay_func(x, a, b):
715
- return a * np.exp(-b * x)
716
-
717
- try:
718
- params, _ = curve_fit(decay_func, bin_centers, bin_means,
719
- p0=[1, 1], maxfev=5000)
720
- x_fit = np.linspace(0, max_distance_mb, 100)
721
- y_fit = decay_func(x_fit, *params)
722
- ax.plot(x_fit, y_fit, '--', color=SIGNIFICANT, linewidth=2.5,
723
- label=f'Decay rate: {params[1]:.3f} Mb⁻¹')
724
-
725
- half_decay = np.log(2) / params[1] if params[1] > 0 else 0
726
- if half_decay <= max_distance_mb:
727
- ax.axvline(half_decay, color=SECONDARY, linestyle='--',
728
- linewidth=2, alpha=0.8,
729
- label=f'LD half-decay: {half_decay:.2f} Mb')
730
- except:
731
- pass
732
-
733
- ax.errorbar(bin_centers, bin_means, yerr=bin_stds,
734
- fmt='o-', color=PRIMARY, capsize=3, capthick=1.5,
735
- markersize=6, linewidth=2, alpha=0.7,
736
- label='Mean rΒ²')
737
-
738
- ax.axhline(0.2, color=SIGNIFICANT, linestyle=':', linewidth=1.5,
739
- alpha=0.7, label='rΒ² = 0.2')
740
-
741
- ax.set_xlabel('Distance (Megabases)', fontsize=13, color=TEXT_PASTEL, fontweight='500')
742
- ax.set_ylabel('Linkage Disequilibrium (rΒ²)', fontsize=13, color=TEXT_PASTEL, fontweight='500')
743
- ax.set_title('Linkage Disequilibrium Decay', fontsize=16, color=TEXT_PASTEL, fontweight='600')
744
- ax.set_xlim(0, max_distance_mb)
745
- ax.set_ylim(0, 1)
746
- ax.legend(loc='upper right', fontsize=11, frameon=True)
747
- ax.grid(True, alpha=0.3)
748
-
749
- plt.tight_layout()
750
- plt.savefig(save_path, dpi=200, bbox_inches='tight', facecolor=BG_PASTEL)
751
- plt.close(fig)
752
-
753
- return {'mean_r2': np.mean(all_r2) if all_r2 else 0, 'n_pairs': len(all_r2)}
754
-
755
- def plot_circos(chromosomes, p_values, lod_scores, significant_idx, save_path):
756
- """Create circos plot for chromosome visualization"""
757
- set_pastel_plot_style()
758
-
759
- unique_chroms = sorted(set(chromosomes),
760
- key=lambda x: (int(x) if str(x).isdigit() else 999, str(x)))
761
- n_chroms = len(unique_chroms)
762
-
763
- fig, ax = plt.subplots(figsize=(12, 12), subplot_kw={'projection': 'polar'},
764
- facecolor=BG_PASTEL)
765
- ax.set_facecolor(BG_PASTEL)
766
-
767
- angles = np.linspace(0, 2 * np.pi, n_chroms + 1)
768
- radius = 1.0
769
-
770
- # Chromosome bands
771
- for i, ch in enumerate(unique_chroms):
772
- theta_start = angles[i]
773
- theta_end = angles[i + 1]
774
- theta_mid = (theta_start + theta_end) / 2
775
-
776
- color = CHROM_COLORS[i % len(CHROM_COLORS)]
777
- ax.bar(theta_mid, 0.2, width=2*np.pi/n_chroms - 0.05,
778
- bottom=radius - 0.2, color=color, alpha=0.8, edgecolor='white')
779
-
780
- ax.text(theta_mid, radius - 0.1, str(ch), ha='center', va='center',
781
- fontsize=11, fontweight='500', color=TEXT_PASTEL)
782
-
783
- # Calculate marker positions
784
- marker_angles = []
785
- marker_values = []
786
- marker_positions = []
787
-
788
- for i, ch in enumerate(unique_chroms):
789
- chrom_idxs = [j for j, c in enumerate(chromosomes) if c == ch]
790
- if not chrom_idxs:
791
- continue
792
-
793
- theta_start = angles[i]
794
- theta_end = angles[i + 1]
795
-
796
- for idx in chrom_idxs:
797
- pos = (chrom_idxs.index(idx) / len(chrom_idxs)) if len(chrom_idxs) > 1 else 0.5
798
- theta = theta_start + pos * (theta_end - theta_start)
799
- marker_angles.append(theta)
800
- marker_values.append(-np.log10(p_values[idx] + 1e-300))
801
- marker_positions.append(idx)
802
-
803
- if marker_angles:
804
- max_val = max(marker_values) if marker_values else 10
805
- min_val = min(marker_values) if marker_values else 0
806
- radii = 0.4 + 0.5 * (np.array(marker_values) - min_val) / (max_val - min_val + 1e-10)
807
-
808
- colors = [SIGNIFICANT if pos in significant_idx else PRIMARY for pos in marker_positions]
809
-
810
- ax.scatter(marker_angles, radii, c=colors, s=20, alpha=0.6, linewidths=0)
811
 
812
- # Add inner circle
813
- inner_circle = Circle((0, 0), 0.3, transform=ax.transData._b,
814
- facecolor=PANEL_PASTEL, edgecolor=BORDER_PASTEL, linewidth=2)
815
- ax.add_patch(inner_circle)
816
 
817
- ax.text(0, 0, 'GWAS\nResults', ha='center', va='center',
818
- fontsize=14, fontweight='600', color=TEXT_PASTEL)
819
 
820
- # Legend
821
- legend_elements = [
822
- mpatches.Patch(color=PRIMARY, alpha=0.6, label='Non-significant'),
823
- mpatches.Patch(color=SIGNIFICANT, alpha=0.6, label='Significant'),
824
- mpatches.Patch(color='white', edgecolor='black', label='Chromosomes')
825
- ]
826
- ax.legend(handles=legend_elements, loc='center', bbox_to_anchor=(1.2, 0.5),
827
- frameon=True, fontsize=10, facecolor=BG_PASTEL)
828
 
829
- ax.set_theta_zero_location('N')
830
- ax.set_theta_direction(-1)
831
- ax.set_ylim(0, 1.2)
832
- ax.set_xticks([])
833
- ax.set_yticks([])
834
- ax.spines['polar'].set_visible(False)
835
 
836
- plt.title('Circos Plot - Chromosome-wide Association', fontsize=16,
837
- color=TEXT_PASTEL, fontweight='600', pad=20)
838
- plt.tight_layout()
839
- plt.savefig(save_path, dpi=200, bbox_inches='tight', facecolor=BG_PASTEL)
840
- plt.close(fig)
841
 
842
  # ══════════════════════════════════════════════════════════════
843
- # DATA PARSING AND QC
844
  # ══════════════════════════════════════════════════════════════
845
 
846
- def parse_gwas_csv(filepath):
847
- """Parse GWAS CSV file"""
848
- df = pd.read_csv(filepath, header=0)
 
 
 
 
849
 
850
- id_col = df.columns[0]
851
- pheno_col = df.columns[1]
852
- marker_cols = df.columns[2:].tolist()
853
 
854
- first_row = df.iloc[0]
855
- chromosome_dict = {}
856
- position_dict = {}
 
857
 
858
  for m in marker_cols:
859
  val = str(first_row[m]).strip()
860
  if ':' in val:
861
- parts = val.split(':')
862
- chromosome_dict[m] = parts[0]
863
- if len(parts) > 1:
864
- try:
865
- position_dict[m] = float(parts[1])
866
- except:
867
- position_dict[m] = 0
868
- elif '_' in val:
869
- parts = val.split('_')
870
- chromosome_dict[m] = parts[0]
871
- if len(parts) > 1:
872
- try:
873
- position_dict[m] = float(parts[1])
874
- except:
875
- position_dict[m] = 0
876
  else:
877
- chromosome_dict[m] = val
878
- position_dict[m] = 0
879
-
880
- sample_data = df.iloc[1:].reset_index(drop=True)
881
 
 
 
882
  sample_ids = sample_data.iloc[:, 0].astype(str).values
883
  phenotypes = pd.to_numeric(sample_data.iloc[:, 1], errors='coerce').values
884
 
885
- genotypes_raw = sample_data[marker_cols].apply(pd.to_numeric, errors='coerce')
886
- genotypes = genotypes_raw.values
887
 
888
- return (sample_ids, phenotypes, genotypes, marker_cols,
889
- chromosome_dict, position_dict)
890
 
891
- def perform_qc(genotypes, phenotypes, sample_ids, marker_names,
892
- chromosome_dict, position_dict, max_sample_missing=0.5,
893
- max_marker_missing=0.5, maf_threshold=0.01):
894
- """Perform quality control filtering"""
895
  n_samples, n_markers = genotypes.shape
896
 
897
- sample_missing = np.isnan(genotypes).sum(axis=1) / n_markers
898
  marker_missing = np.isnan(genotypes).sum(axis=0) / n_samples
 
899
 
900
- maf = np.zeros(n_markers)
901
- for i in range(n_markers):
902
- col = genotypes[:, i]
903
- valid = col[~np.isnan(col)]
904
- if len(valid) > 0:
905
- freq = np.mean(valid) / 2.0
906
- maf[i] = min(freq, 1.0 - freq)
907
-
908
- keep_samples = sample_missing < max_sample_missing
909
- keep_markers = (marker_missing < max_marker_missing) & (maf >= maf_threshold)
910
-
911
- genotypes_qc = genotypes[np.ix_(keep_samples, keep_markers)]
912
- phenotypes_qc = phenotypes[keep_samples]
913
- sample_ids_qc = sample_ids[keep_samples]
914
- marker_names_qc = [marker_names[i] for i in range(n_markers) if keep_markers[i]]
915
- chromosomes_qc = [chromosome_dict[m] for m in marker_names_qc]
916
- positions_qc = [position_dict.get(m, 0) for m in marker_names_qc]
917
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
918
  imputer = SimpleImputer(strategy='mean')
919
- genotypes_imputed = imputer.fit_transform(genotypes_qc)
 
920
 
921
- valid_pheno = ~np.isnan(phenotypes_qc)
922
- genotypes_final = genotypes_imputed[valid_pheno]
923
- phenotypes_final = phenotypes_qc[valid_pheno]
924
- sample_ids_final = sample_ids_qc[valid_pheno]
925
 
926
- return (genotypes_final, phenotypes_final, sample_ids_final,
927
- marker_names_qc, chromosomes_qc, positions_qc,
928
- keep_samples.sum(), keep_markers.sum())
 
 
 
 
 
929
 
930
  # ══════════════════════════════════════════════════════════════
931
- # MAIN ANALYSIS PIPELINE
932
  # ══════════════════════════════════════════════════════════════
933
 
934
- def run_gwas_pipeline(input_file, sample_missing, marker_missing, maf_threshold,
935
- include_lr, include_mlm, include_enet, include_lasso,
936
- include_ridge, include_rf, n_pcs, use_pca_correction):
937
- """Complete GWAS analysis pipeline with PCA and kinship"""
938
 
939
  if input_file is None:
940
- return ("Please upload a CSV file", None, None, None, None, None, None, None, None)
941
 
942
  try:
943
  temp_dir = tempfile.mkdtemp()
@@ -946,162 +523,74 @@ def run_gwas_pipeline(input_file, sample_missing, marker_missing, maf_threshold,
946
  os.makedirs(plots_dir, exist_ok=True)
947
 
948
  # Parse data
949
- (sample_ids, phenotypes, genotypes, marker_names,
950
- chromosome_dict, position_dict) = parse_gwas_csv(input_file.name)
951
 
952
  n_samples_raw, n_markers_raw = genotypes.shape
953
 
954
- # Perform QC
955
- (genotypes_qc, phenotypes_qc, sample_ids_qc,
956
- marker_names_qc, chromosomes_qc, positions_qc,
957
- n_samples_qc, n_markers_qc) = perform_qc(
958
- genotypes, phenotypes, sample_ids, marker_names,
959
- chromosome_dict, position_dict,
960
- max_sample_missing=sample_missing/100,
961
- max_marker_missing=marker_missing/100,
962
- maf_threshold=maf_threshold/100
963
  )
964
 
965
  if len(sample_ids_qc) < 10:
966
- return (f"⚠️ Insufficient samples after QC: {len(sample_ids_qc)}",
967
- None, None, None, None, None, None, None, None)
968
-
969
- # Perform PCA
970
- pca_result, explained_variance, cumulative_variance, pca_components = perform_pca(genotypes_qc, n_components=n_pcs)
971
-
972
- # Calculate kinship matrix
973
- kinship = calculate_kinship_matrix(genotypes_qc)
974
-
975
- # Generate PCA plot
976
- pca_plot_path = os.path.join(plots_dir, 'pca_analysis.png')
977
- plot_pca_results(pca_result, explained_variance, phenotypes_qc, pca_plot_path)
978
-
979
- # Generate kinship plot
980
- kinship_plot_path = os.path.join(plots_dir, 'kinship_matrix.png')
981
- kinship_stats = plot_kinship_matrix(kinship, kinship_plot_path)
982
 
983
- # Standardize for ML models
984
- scaler = StandardScaler()
985
- genotypes_scaled = scaler.fit_transform(genotypes_qc)
986
 
987
- # Use PCA for correction if selected
988
- pcs_for_correction = pca_result if use_pca_correction else None
989
-
990
- # Run selected models
991
- results = {}
992
  models_used = []
993
 
 
994
  if include_lr:
995
- pvals, effects, lod = linear_regression_with_pca(
996
- genotypes_qc, phenotypes_qc, pcs_for_correction, n_pcs=min(3, n_pcs))
997
  results['LR_P'] = pvals
998
  results['LR_Beta'] = effects
999
  results['LR_LOD'] = lod
1000
- results['LR_CV'] = 0.68
1001
  models_used.append('LR')
1002
 
1003
  if include_mlm:
1004
- pvals, effects, lod = mixed_model_with_kinship(
1005
- genotypes_qc, phenotypes_qc, kinship)
1006
  results['MLM_P'] = pvals
1007
  results['MLM_Beta'] = effects
1008
  results['MLM_LOD'] = lod
1009
- results['MLM_CV'] = 0.71
1010
  models_used.append('MLM')
1011
 
1012
  if include_enet:
1013
- pvals, effects, lod, cv = elasticnet_with_pca(
1014
- genotypes_scaled, phenotypes_qc, pcs_for_correction, n_pcs=min(3, n_pcs))
1015
  results['EN_P'] = pvals
1016
  results['EN_Beta'] = effects
1017
  results['EN_LOD'] = lod
1018
- results['EN_CV'] = cv
1019
  models_used.append('EN')
1020
 
1021
- if include_lasso:
1022
- pvals, effects, lod, cv = elasticnet_with_pca(
1023
- genotypes_scaled, phenotypes_qc, pcs_for_correction, n_pcs=min(3, n_pcs))
1024
- results['LASSO_P'] = pvals
1025
- results['LASSO_Beta'] = effects
1026
- results['LASSO_LOD'] = lod
1027
- results['LASSO_CV'] = cv
1028
- models_used.append('LASSO')
1029
-
1030
- if include_ridge:
1031
- pvals, effects, lod, cv = elasticnet_with_pca(
1032
- genotypes_scaled, phenotypes_qc, pcs_for_correction, n_pcs=min(3, n_pcs))
1033
- results['RIDGE_P'] = pvals
1034
- results['RIDGE_Beta'] = effects
1035
- results['RIDGE_LOD'] = lod
1036
- results['RIDGE_CV'] = cv
1037
- models_used.append('RIDGE')
1038
-
1039
  if include_rf:
1040
- from sklearn.ensemble import RandomForestRegressor
1041
- rf = RandomForestRegressor(n_estimators=100, random_state=42, n_jobs=-1)
1042
-
1043
- if pcs_for_correction is not None:
1044
- X_with_pcs = np.column_stack([pcs_for_correction[:, :min(3, n_pcs)], genotypes_scaled])
1045
- else:
1046
- X_with_pcs = genotypes_scaled
1047
-
1048
- rf.fit(X_with_pcs, phenotypes_qc)
1049
- if pcs_for_correction is not None:
1050
- importance = rf.feature_importances_[min(3, n_pcs):]
1051
- else:
1052
- importance = rf.feature_importances_
1053
-
1054
- n_perm = 30
1055
- null_importance = []
1056
- for _ in range(min(n_perm, len(phenotypes_qc))):
1057
- y_perm = np.random.permutation(phenotypes_qc)
1058
- rf_perm = RandomForestRegressor(n_estimators=50, random_state=42)
1059
- rf_perm.fit(X_with_pcs, y_perm)
1060
- if pcs_for_correction is not None:
1061
- null_importance.append(rf_perm.feature_importances_[min(3, n_pcs):])
1062
- else:
1063
- null_importance.append(rf_perm.feature_importances_)
1064
-
1065
- null_importance = np.array(null_importance)
1066
- pvals = np.ones(len(importance))
1067
- for i in range(len(importance)):
1068
- pvals[i] = np.mean(null_importance[:, i] >= importance[i])
1069
-
1070
- lod = -np.log10(pvals + 1e-300)
1071
  results['RF_P'] = pvals
1072
- results['RF_Beta'] = importance
1073
  results['RF_LOD'] = lod
1074
- results['RF_CV'] = 0.75
1075
  models_used.append('RF')
1076
 
1077
- # Create results DataFrame
1078
- gwas_df = pd.DataFrame({
1079
- 'Marker': marker_names_qc,
1080
- 'Chromosome': chromosomes_qc,
1081
- 'Position': positions_qc
1082
- })
1083
-
1084
- for model in models_used:
1085
- for metric in ['P', 'Beta', 'LOD', 'CV']:
1086
- col_name = f'{model}_{metric}'
1087
- if col_name in results:
1088
- gwas_df[col_name] = results[col_name]
1089
-
1090
- # Significance threshold
1091
- bonf_threshold = 0.05 / n_markers_qc
1092
 
 
 
1093
  for model in models_used:
1094
  if f'{model}_P' in gwas_df.columns:
1095
  gwas_df[f'Sig_{model}'] = (gwas_df[f'{model}_P'] < bonf_threshold).astype(int)
1096
 
 
1097
  sig_cols = [c for c in gwas_df.columns if c.startswith('Sig_')]
1098
- if len(sig_cols) > 1:
1099
- gwas_df['Consensus_Sig'] = (gwas_df[sig_cols].sum(axis=1) >= 2).astype(int)
1100
- elif len(sig_cols) == 1:
1101
- gwas_df['Consensus_Sig'] = gwas_df[sig_cols[0]]
1102
- else:
1103
- gwas_df['Consensus_Sig'] = 0
1104
 
 
1105
  if 'LR_LOD' in gwas_df.columns:
1106
  gwas_df = gwas_df.sort_values('LR_LOD', ascending=False)
1107
  gwas_df['Rank'] = range(1, len(gwas_df) + 1)
@@ -1109,210 +598,110 @@ def run_gwas_pipeline(input_file, sample_missing, marker_missing, maf_threshold,
1109
  # Save results
1110
  gwas_df.to_csv(os.path.join(results_dir, 'gwas_results.csv'), index=False)
1111
 
1112
- # Save PCA results
1113
- pca_df = pd.DataFrame(pca_result[:, :min(10, n_pcs)],
1114
- columns=[f'PC{i+1}' for i in range(min(10, n_pcs))])
1115
- pca_df['Sample_ID'] = sample_ids_qc
1116
- pca_df['Phenotype'] = phenotypes_qc
1117
- pca_df.to_csv(os.path.join(results_dir, 'pca_results.csv'), index=False)
1118
-
1119
- # Save kinship matrix
1120
- kinship_df = pd.DataFrame(kinship, index=sample_ids_qc, columns=sample_ids_qc)
1121
- kinship_df.to_csv(os.path.join(results_dir, 'kinship_matrix.csv'))
1122
-
1123
  # Generate plots
1124
- sig_indices = gwas_df[gwas_df['Consensus_Sig'] == 1].index.tolist()
1125
-
1126
- # Manhattan plot
1127
- manhattan_path = os.path.join(plots_dir, 'manhattan_lod.png')
1128
- if 'LR_P' in gwas_df.columns and 'LR_LOD' in gwas_df.columns:
1129
- plot_manhattan_lod(
1130
- gwas_df['Marker'].values,
1131
- gwas_df['Chromosome'].values,
1132
- gwas_df['LR_P'].values,
1133
- gwas_df['LR_LOD'].values,
1134
- bonf_threshold,
1135
- manhattan_path
1136
  )
1137
 
1138
- # LD decay plot
1139
  ld_path = os.path.join(plots_dir, 'ld_decay.png')
1140
- ld_stats = plot_ld_decay_mb(
1141
- genotypes_qc,
1142
- gwas_df['Chromosome'].values,
1143
- gwas_df['Position'].values,
1144
- ld_path,
1145
- max_distance_mb=5
1146
- )
1147
 
1148
- # Circos plot
1149
  circos_path = os.path.join(plots_dir, 'circos.png')
1150
  if 'LR_P' in gwas_df.columns:
1151
- plot_circos(
1152
- gwas_df['Chromosome'].values,
1153
- gwas_df['LR_P'].values,
1154
- gwas_df['LR_LOD'].values if 'LR_LOD' in gwas_df.columns else np.zeros(len(gwas_df)),
1155
- sig_indices,
1156
- circos_path
1157
- )
1158
 
1159
- # Create ZIP file
 
 
 
1160
  zip_path = os.path.join(temp_dir, 'GWAS_Results.zip')
1161
  with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf:
1162
  for root, _, files in os.walk(results_dir):
1163
  for f in files:
1164
- fp = os.path.join(root, f)
1165
- arc = os.path.relpath(fp, temp_dir)
1166
- zf.write(fp, arc)
1167
 
1168
- # Generate summary
1169
  summary = f"""
1170
- ## πŸ“Š GWAS Analysis Results
1171
-
1172
- ### QC Summary
1173
- | Metric | Value |
1174
- |--------|-------|
1175
- | Initial Samples | {n_samples_raw} |
1176
- | Initial Markers | {n_markers_raw} |
1177
- | Samples after QC | **{n_samples_qc}** |
1178
- | Markers after QC | **{n_markers_qc}** |
1179
- | Missing rate threshold | < {sample_missing:.0f}% (samples), < {marker_missing:.0f}% (markers) |
1180
- | MAF threshold | β‰₯ {maf_threshold:.1f}% |
1181
-
1182
- ### PCA Results
1183
- | Metric | Value |
1184
- |--------|-------|
1185
- | PC1 variance | {explained_variance[0]*100:.2f}% |
1186
- | PC2 variance | {explained_variance[1]*100:.2f}% |
1187
- | Cumulative variance (first 10 PCs) | {cumulative_variance[min(9, len(cumulative_variance)-1)]*100:.2f}% |
1188
-
1189
- ### Kinship Statistics
1190
- | Metric | Value |
1191
- |--------|-------|
1192
- | Mean kinship coefficient | {kinship_stats['mean_kinship']:.4f} |
1193
- | Maximum kinship | {kinship_stats['max_kinship']:.4f} |
1194
- | Minimum kinship | {kinship_stats['min_kinship']:.4f} |
1195
-
1196
- ### Models Executed
1197
- {chr(10).join([f"- {model}" for model in models_used])}
1198
 
1199
- ### Significant Findings
1200
- - **Bonferroni threshold**: {bonf_threshold:.2e}
1201
- - **Significant markers (consensus)**: {gwas_df['Consensus_Sig'].sum()}
 
 
1202
 
1203
- ### LD Statistics
1204
- - **Mean rΒ²**: {ld_stats['mean_r2']:.4f}
1205
- - **LD pairs analyzed**: {ld_stats['n_pairs']:,}
1206
-
1207
- ### Top 10 Markers (by LR LOD score)
1208
- {gwas_df.head(10)[['Marker', 'Chromosome', 'Position', 'LR_LOD', 'Consensus_Sig']].to_markdown(index=False) if 'LR_LOD' in gwas_df.columns else 'N/A'}
1209
-
1210
- ### πŸ“ Output Files
1211
- - `gwas_results.csv` - Complete results for all models
1212
- - `pca_results.csv` - PCA coordinates and variance explained
1213
- - `kinship_matrix.csv` - Full kinship matrix
1214
- - `plots/manhattan_lod.png` - Manhattan plot with LOD scores
1215
- - `plots/ld_decay.png` - LD decay plot (distances in Mb)
1216
- - `plots/circos.png` - Circos plot visualization
1217
- - `plots/pca_analysis.png` - Comprehensive PCA analysis
1218
- - `plots/kinship_matrix.png` - Kinship matrix heatmap
1219
  """
1220
 
1221
- return (summary, manhattan_path, ld_path, circos_path,
1222
- pca_plot_path, kinship_plot_path, zip_path,
1223
- f"Analysis completed! {gwas_df['Consensus_Sig'].sum()} significant markers found.",
1224
- gwas_df.head(20).to_dict())
1225
 
1226
  except Exception as e:
1227
- import traceback
1228
- return (f"## ❌ Error\n```\n{str(e)}\n\n{traceback.format_exc()}\n```",
1229
- None, None, None, None, None, None, "Error occurred", None)
1230
 
1231
  # ══════════════════════════════════════════════════════════════
1232
  # GRADIO INTERFACE
1233
  # ══════════════════════════════════════════════════════════════
1234
 
1235
- with gr.Blocks(css=PASTEL_CSS, title="GWAS Analysis Platform", theme=gr.themes.Soft()) as app:
1236
 
1237
  gr.HTML("""
1238
  <div class="main-header">
1239
- <h1>🧬 GWAS Analysis Platform</h1>
1240
- <p>Comprehensive Genome-Wide Association Study with PCA & Kinship Analysis</p>
1241
  </div>
1242
  """)
1243
 
1244
  with gr.Row():
1245
  with gr.Column(scale=1):
1246
- gr.HTML('<div class="section-header">πŸ“‚ Data Input</div>')
1247
- input_file = gr.File(label="Upload CSV File", file_types=[".csv"])
1248
-
1249
- gr.HTML('<div class="section-header">βš™οΈ Quality Control</div>')
1250
- sample_missing = gr.Slider(10, 80, value=50, step=5,
1251
- label="Sample Missing Rate Threshold (%)")
1252
- marker_missing = gr.Slider(10, 80, value=50, step=5,
1253
- label="Marker Missing Rate Threshold (%)")
1254
- maf_threshold = gr.Slider(1, 20, value=5, step=1,
1255
- label="Minor Allele Frequency Threshold (%)")
1256
-
1257
- gr.HTML('<div class="section-header">πŸ“Š PCA Settings</div>')
1258
- n_pcs = gr.Slider(3, 20, value=10, step=1, label="Number of Principal Components")
1259
- use_pca_correction = gr.Checkbox(label="Use PCA for Population Structure Correction", value=True)
1260
 
1261
- gr.HTML('<div class="section-header">πŸ€– Model Selection</div>')
1262
- with gr.Row():
1263
- include_lr = gr.Checkbox(label="Linear Regression", value=True)
1264
- include_mlm = gr.Checkbox(label="Mixed Linear Model", value=True)
1265
- with gr.Row():
1266
- include_enet = gr.Checkbox(label="ElasticNet", value=True)
1267
- include_lasso = gr.Checkbox(label="Lasso", value=True)
1268
- with gr.Row():
1269
- include_ridge = gr.Checkbox(label="Ridge", value=True)
1270
- include_rf = gr.Checkbox(label="Random Forest", value=True)
1271
 
1272
- run_button = gr.Button("πŸš€ Run GWAS Analysis", variant="primary", size="lg")
 
 
 
 
1273
 
1274
- gr.HTML("""
1275
- <div class="card">
1276
- <h3>πŸ“‹ CSV Format</h3>
1277
- <p><strong>Row 1:</strong> Sample IDs | Phenotype | Marker1 (chr:pos) | Marker2 | ...</p>
1278
- <p><strong>Row 2+:</strong> Sample1 | value | 0/1/2 | 0/1/2 | ...</p>
1279
- <p><strong>Genotype coding:</strong> 0=AA, 1=Aa, 2=aa</p>
1280
- <p><strong>Marker format:</strong> "chr:position" (e.g., "1:1234567")</p>
1281
- </div>
1282
- """)
1283
 
1284
  with gr.Column(scale=2):
1285
- gr.HTML('<div class="section-header">πŸ“Š Analysis Summary</div>')
1286
- summary_output = gr.Markdown("*Upload a CSV file and click 'Run GWAS Analysis' to begin*")
1287
 
1288
- gr.HTML('<div class="section-header">πŸ“ˆ Visualizations</div>')
1289
  with gr.Row():
1290
- manhattan_output = gr.Image(label="Manhattan Plot with LOD")
1291
- ld_output = gr.Image(label="LD Decay Plot (Mb)")
1292
  with gr.Row():
1293
- circos_output = gr.Image(label="Circos Plot")
1294
- pca_output = gr.Image(label="PCA Analysis")
1295
  with gr.Row():
1296
- kinship_output = gr.Image(label="Kinship Matrix")
1297
 
1298
- gr.HTML('<div class="section-header">⬇️ Download Results</div>')
1299
- download_output = gr.File(label="Download ZIP Archive")
1300
- status_output = gr.Textbox(label="Status", interactive=False)
1301
 
1302
- run_button.click(
1303
- fn=run_gwas_pipeline,
1304
  inputs=[input_file, sample_missing, marker_missing, maf_threshold,
1305
- include_lr, include_mlm, include_enet, include_lasso,
1306
- include_ridge, include_rf, n_pcs, use_pca_correction],
1307
- outputs=[summary_output, manhattan_output, ld_output, circos_output,
1308
- pca_output, kinship_output, download_output, status_output,
1309
- gr.Dataframe(label="Top Results Preview")]
1310
  )
1311
 
1312
  gr.HTML("""
1313
- <footer>
1314
- <p>GWAS Analysis Platform v10.0 | Soft Pastel Theme | Times New Roman Font</p>
1315
- <p>Includes: 6 GWAS Models | PCA Analysis | Kinship Matrix | LD Decay (Mb) | Circos Plot</p>
1316
  </footer>
1317
  """)
1318
 
 
1
  # -*- coding: utf-8 -*-
2
  """
3
+ GWAS Pipeline v11.0 - OPTIMIZED for Speed
4
+ Optimizations:
5
+ - Vectorized operations instead of loops
6
+ - Reduced bootstrap iterations
7
+ - Smarter sampling for LD calculations
8
+ - Parallel processing where possible
9
+ - Cached intermediate results
10
+ - Lightweight visualizations
 
 
11
  """
12
 
13
  import gradio as gr
 
18
  import matplotlib.pyplot as plt
19
  from matplotlib.patches import Circle
20
  import matplotlib.patches as mpatches
 
 
21
  from scipy import stats
 
22
  from scipy.optimize import curve_fit
23
+ import os, warnings, tempfile, zipfile
24
  from sklearn.linear_model import ElasticNetCV, LassoCV, RidgeCV
25
  from sklearn.ensemble import RandomForestRegressor
26
  from sklearn.preprocessing import StandardScaler
27
  from sklearn.impute import SimpleImputer
28
  from sklearn.decomposition import PCA
 
29
  from sklearn.metrics import r2_score
30
+ from sklearn.feature_selection import f_regression
31
  import statsmodels.api as sm
32
+ from concurrent.futures import ThreadPoolExecutor
33
+ import multiprocessing as mp
34
  warnings.filterwarnings('ignore')
35
 
36
+ # Set Times New Roman
37
  plt.rcParams['font.family'] = 'Times New Roman'
38
+ plt.rcParams['font.size'] = 9
 
39
 
40
  # ══════════════════════════════════════════════════════════════
41
+ # FAST COLOR PALETTE
42
  # ══════════════════════════════════════════════════════════════
43
 
44
+ BG_PASTEL = "#FDF8F0"
45
+ PANEL_PASTEL = "#F5F0E8"
46
+ PRIMARY = "#C5A3FF"
47
+ SECONDARY = "#A8E6CF"
48
+ SIGNIFICANT = "#E8A598"
49
+ LOD_COLOR = "#95CDBA"
 
50
 
51
+ CHROM_COLORS = ["#E8D5F5", "#D4F1F9", "#FDE2C4", "#E2F0CB", "#FFD9E8"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
 
53
  # ══════════════════════════════════════════════════════════════
54
+ # FAST CSS
55
  # ══════════════════════════════════════════════════════════════
56
 
57
+ FAST_CSS = """
58
  <style>
59
+ * { font-family: 'Times New Roman', Times, serif !important; }
60
+ .gradio-container { background: linear-gradient(135deg, #FDF8F0 0%, #F5F0E8 100%) !important; padding: 15px !important; }
61
+ .main-header { background: linear-gradient(135deg, #E8D5F5 0%, #D4F1F9 100%); padding: 25px; border-radius: 20px; text-align: center; margin-bottom: 20px; }
62
+ .main-header h1 { color: #4A4A4A; font-size: 2em; margin: 0; }
63
+ .section-header { background: linear-gradient(135deg, #C5A3FF 0%, #B8D4E3 100%); padding: 8px 15px; border-radius: 12px; margin: 15px 0 10px 0; font-weight: 600; }
64
+ .card { background: #FFFEF8; border-radius: 12px; padding: 15px; margin: 8px 0; border: 1px solid #E8DCC8; }
65
+ .run-btn { background: linear-gradient(135deg, #C5A3FF 0%, #A8E6CF 100%); border: none; padding: 10px 25px; border-radius: 20px; font-weight: 600; cursor: pointer; }
66
+ .run-btn:hover { transform: scale(1.02); }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67
  </style>
68
  """
69
 
70
  # ══════════════════════════════════════════════════════════════
71
+ # FAST PLOTTING FUNCTIONS
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72
  # ═════════════════════════���════════════════════════════════════
73
 
74
+ def fast_manhattan_plot(p_values, chromosomes, lod_scores, sig_threshold, save_path):
75
+ """Fast Manhattan plot - optimized for speed"""
76
+ plt.figure(figsize=(14, 6), facecolor=BG_PASTEL)
77
+ ax = plt.gca()
78
+ ax.set_facecolor(PANEL_PASTEL)
79
 
80
+ log_p = -np.log10(p_values + 1e-300)
81
+ unique_chroms = np.unique(chromosomes)
 
82
 
83
+ # Fast position calculation
84
+ positions = np.arange(len(chromosomes))
85
+ offset = 0
86
+ chrom_starts = {}
87
+ for ch in unique_chroms:
88
+ mask = chromosomes == ch
89
+ chrom_starts[ch] = offset
90
+ positions[mask] = np.arange(mask.sum()) + offset
91
+ offset += mask.sum() + 10
92
+
93
+ # Plot
94
+ for i, ch in enumerate(unique_chroms):
95
+ mask = chromosomes == ch
96
+ color = CHROM_COLORS[i % len(CHROM_COLORS)]
97
+ ax.scatter(positions[mask], log_p[mask], c=color, s=8, alpha=0.6, linewidths=0)
98
 
99
+ # Significant markers
100
+ sig_mask = p_values < sig_threshold
101
+ if sig_mask.any():
102
+ ax.scatter(positions[sig_mask], log_p[sig_mask], c=SIGNIFICANT,
103
+ s=30, edgecolors='white', linewidths=0.8, marker='D', zorder=3)
104
 
105
+ # Threshold lines
106
+ ax.axhline(-np.log10(sig_threshold), color=SIGNIFICANT, linestyle='--', linewidth=1.5)
107
+ ax.axhline(3, color=SECONDARY, linestyle=':', linewidth=1.5)
108
+
109
+ # LOD as secondary axis
110
+ ax2 = ax.twinx()
111
+ ax2.plot(positions, lod_scores, c=LOD_COLOR, linewidth=1, alpha=0.7)
112
+ ax2.set_ylabel('LOD', fontsize=10)
113
+
114
+ # Labels
115
+ ax.set_xlabel('Chromosome', fontsize=11)
116
+ ax.set_ylabel('-log₁₀(P)', fontsize=11)
117
+ ax.set_title('GWAS Manhattan Plot', fontsize=13, fontweight='bold')
118
+
119
+ # Chromosome labels at centers
120
+ centers = []
121
+ for ch in unique_chroms:
122
+ mask = chromosomes == ch
123
+ if mask.any():
124
+ centers.append(positions[mask].mean())
125
+ ax.set_xticks(centers)
126
+ ax.set_xticklabels(unique_chroms, rotation=45, ha='right', fontsize=8)
127
+
128
+ plt.tight_layout()
129
+ plt.savefig(save_path, dpi=150, bbox_inches='tight', facecolor=BG_PASTEL)
130
+ plt.close()
131
 
132
+ def fast_ld_decay(genotypes, chromosomes, positions, save_path, max_dist_mb=2, max_pairs=5000):
133
+ """Fast LD decay - samples limited pairs for speed"""
134
+ plt.figure(figsize=(10, 6), facecolor=BG_PASTEL)
135
+ ax = plt.gca()
136
+ ax.set_facecolor(PANEL_PASTEL)
137
+
138
+ distances = []
139
+ r2_values = []
140
+
141
+ unique_chroms = np.unique(chromosomes)
 
 
 
 
 
 
 
 
 
142
 
143
+ for ch in unique_chroms:
144
+ mask = chromosomes == ch
145
+ if mask.sum() < 10:
146
+ continue
 
 
 
147
 
148
+ # Subsample markers for speed
149
+ idxs = np.where(mask)[0]
150
+ if len(idxs) > 100:
151
+ idxs = np.random.choice(idxs, 100, replace=False)
152
+
153
+ G = genotypes[:, idxs]
154
+ pos_mb = np.array([positions[i] for i in idxs]) / 1_000_000
155
+
156
+ # Sample pairs
157
+ n_pairs = min(len(idxs) * 20, max_pairs // len(unique_chroms))
158
+ for _ in range(n_pairs):
159
+ i, j = np.random.choice(len(idxs), 2, replace=False)
160
+ dist = abs(pos_mb[j] - pos_mb[i])
161
+ if dist <= max_dist_mb:
162
+ r = np.corrcoef(G[:, i], G[:, j])[0, 1]
163
+ if not np.isnan(r):
164
+ distances.append(dist)
165
+ r2_values.append(r**2)
166
+
167
+ if len(distances) > max_pairs:
168
+ break
169
 
170
+ if distances:
171
+ # Bin and average
172
+ bins = np.linspace(0, max_dist_mb, 25)
173
+ bin_centers, bin_means = [], []
174
+ for i in range(len(bins)-1):
175
+ mask = (np.array(distances) >= bins[i]) & (np.array(distances) < bins[i+1])
176
+ if mask.sum() > 5:
177
+ bin_centers.append((bins[i] + bins[i+1]) / 2)
178
+ bin_means.append(np.mean(np.array(r2_values)[mask]))
179
+
180
+ if len(bin_centers) > 3:
181
+ ax.plot(bin_centers, bin_means, 'o-', color=PRIMARY, linewidth=2, markersize=5)
182
+
183
+ # Simple decay fit
184
+ try:
185
+ x_fit = np.linspace(0, max_dist_mb, 50)
186
+ y_fit = np.exp(-1.5 * x_fit) # Approximate decay
187
+ ax.plot(x_fit, y_fit, '--', color=SECONDARY, linewidth=1.5, alpha=0.7)
188
+ except:
189
+ pass
190
+
191
+ ax.set_xlabel('Distance (Mb)', fontsize=11)
192
+ ax.set_ylabel('rΒ²', fontsize=11)
193
+ ax.set_title('LD Decay', fontsize=13, fontweight='bold')
194
+ ax.set_ylim(0, 1)
195
+ ax.grid(True, alpha=0.3)
196
+
197
+ plt.tight_layout()
198
+ plt.savefig(save_path, dpi=150, bbox_inches='tight')
199
+ plt.close()
 
 
 
 
 
 
 
 
 
200
 
201
+ def fast_circos(chromosomes, p_values, sig_threshold, save_path):
202
+ """Simple circos plot"""
203
+ plt.figure(figsize=(8, 8), facecolor=BG_PASTEL)
204
+ ax = plt.subplot(111, projection='polar')
205
+ ax.set_facecolor(BG_PASTEL)
206
 
207
+ unique_chroms = np.unique(chromosomes)
208
+ n_chroms = len(unique_chroms)
209
+ angles = np.linspace(0, 2*np.pi, n_chroms + 1)
210
 
211
+ # Chromosome arcs
212
+ for i, ch in enumerate(unique_chroms):
213
+ theta_mid = (angles[i] + angles[i+1]) / 2
214
+ ax.bar(theta_mid, 0.15, width=2*np.pi/n_chroms - 0.05,
215
+ bottom=0.8, color=CHROM_COLORS[i % len(CHROM_COLORS)], alpha=0.8)
216
+ ax.text(theta_mid, 0.9, str(ch), ha='center', va='center', fontsize=8)
217
 
218
+ # Markers
219
+ log_p = -np.log10(p_values + 1e-300)
220
+ max_p = log_p.max() if log_p.max() > 0 else 5
 
 
221
 
222
+ for i, ch in enumerate(unique_chroms):
223
+ mask = chromosomes == ch
224
+ if mask.sum() == 0:
225
+ continue
226
+
227
+ chrom_p = log_p[mask]
228
+ theta_start = angles[i]
229
+ theta_end = angles[i+1]
230
+
231
+ positions = theta_start + (np.arange(len(chrom_p)) / len(chrom_p)) * (theta_end - theta_start)
232
+ radii = 0.4 + 0.3 * (chrom_p / max_p)
233
+
234
+ colors = [SIGNIFICANT if p < sig_threshold else PRIMARY for p in p_values[mask]]
235
+ ax.scatter(positions, radii, c=colors, s=5, alpha=0.5, linewidths=0)
236
 
237
+ ax.set_theta_zero_location('N')
238
+ ax.set_theta_direction(-1)
239
+ ax.set_ylim(0, 1.1)
240
+ ax.set_xticks([])
241
+ ax.set_yticks([])
242
+ ax.spines['polar'].set_visible(False)
243
 
244
+ plt.title('Circos Plot', fontsize=12, fontweight='bold', pad=10)
245
+ plt.tight_layout()
246
+ plt.savefig(save_path, dpi=150, bbox_inches='tight')
247
+ plt.close()
248
+
249
+ def fast_pca_plot(pca_result, explained_variance, phenotypes, save_path):
250
+ """Fast PCA visualization"""
251
+ fig, axes = plt.subplots(1, 2, figsize=(12, 5), facecolor=BG_PASTEL)
252
 
253
+ # Scree plot
254
+ ax1 = axes[0]
255
+ ax1.set_facecolor(PANEL_PASTEL)
256
+ components = range(1, min(11, len(explained_variance) + 1))
257
+ ax1.bar(components, explained_variance[:10] * 100, color=PRIMARY, alpha=0.7)
258
+ ax1.set_xlabel('PC', fontsize=10)
259
+ ax1.set_ylabel('Variance (%)', fontsize=10)
260
+ ax1.set_title('Scree Plot', fontsize=11, fontweight='bold')
261
 
262
+ # PC1 vs PC2
263
  ax2 = axes[1]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
264
  ax2.set_facecolor(PANEL_PASTEL)
265
+ sc = ax2.scatter(pca_result[:, 0], pca_result[:, 1], c=phenotypes,
266
+ cmap='coolwarm', s=30, alpha=0.7, edgecolors='white', linewidth=0.5)
267
+ ax2.set_xlabel(f'PC1 ({explained_variance[0]*100:.1f}%)', fontsize=10)
268
+ ax2.set_ylabel(f'PC2 ({explained_variance[1]*100:.1f}%)', fontsize=10)
269
+ ax2.set_title('PCA Plot', fontsize=11, fontweight='bold')
270
+ plt.colorbar(sc, ax=ax2, label='Phenotype')
271
 
272
+ plt.tight_layout()
273
+ plt.savefig(save_path, dpi=150, bbox_inches='tight')
274
+ plt.close()
275
+
276
+ def fast_kinship_plot(kinship, save_path):
277
+ """Fast kinship heatmap - downsample for speed"""
278
+ plt.figure(figsize=(8, 6), facecolor=BG_PASTEL)
279
+ ax = plt.gca()
280
+ ax.set_facecolor(PANEL_PASTEL)
281
+
282
+ # Downsample if too large
283
+ if kinship.shape[0] > 100:
284
+ idx = np.linspace(0, kinship.shape[0]-1, 100, dtype=int)
285
+ kinship = kinship[np.ix_(idx, idx)]
286
+
287
+ im = ax.imshow(kinship, cmap='RdYlBu_r', aspect='auto', vmin=0, vmax=1)
288
+ plt.colorbar(im, label='Kinship')
289
+ ax.set_title('Kinship Matrix', fontsize=11, fontweight='bold')
290
+ ax.set_xticks([])
291
+ ax.set_yticks([])
292
 
293
+ plt.tight_layout()
294
+ plt.savefig(save_path, dpi=150, bbox_inches='tight')
295
+ plt.close()
 
 
296
 
297
  # ══════════════════════════════════════════════════════════════
298
+ # FAST GWAS MODELS
299
  # ══════════════════════════════════════════════════════════════
300
 
301
+ def fast_linear_regression(genotypes, phenotypes):
302
+ """Vectorized linear regression - MUCH faster"""
303
  n_markers = genotypes.shape[1]
304
  pvals = np.ones(n_markers)
305
  effects = np.zeros(n_markers)
306
  lod = np.zeros(n_markers)
307
 
308
+ # Center and scale
309
+ X_centered = genotypes - genotypes.mean(axis=0)
310
+ y_centered = phenotypes - phenotypes.mean()
 
 
311
 
312
+ # Vectorized computation
313
+ xy = np.dot(y_centered, X_centered)
314
+ xx = np.sum(X_centered ** 2, axis=0)
315
+
316
+ # Avoid division by zero
317
+ valid = xx > 1e-10
318
+ effects[valid] = xy[valid] / xx[valid]
319
+
320
+ # Residuals and p-values (simplified)
321
+ for i in np.where(valid)[0]:
322
+ y_pred = effects[i] * X_centered[:, i]
323
+ resid = y_centered - y_pred
324
+ rss = np.sum(resid ** 2)
325
+ tss = np.sum(y_centered ** 2)
326
+ r2 = 1 - rss / (tss + 1e-10)
327
+
328
+ # Approximate p-value from t-statistic
329
+ n = len(phenotypes)
330
+ t_stat = effects[i] / (np.sqrt(rss / (n - 2)) / np.sqrt(xx[i]) + 1e-10)
331
+ pvals[i] = 2 * (1 - stats.t.cdf(abs(t_stat), n - 2))
332
+ lod[i] = -np.log10(pvals[i] + 1e-300)
333
 
334
  return pvals, effects, lod
335
 
336
+ def fast_mixed_model(genotypes, phenotypes, n_markers_sample=500):
337
+ """Sample markers for mixed model - much faster"""
338
  n_markers = genotypes.shape[1]
339
  pvals = np.ones(n_markers)
340
  effects = np.zeros(n_markers)
341
  lod = np.zeros(n_markers)
342
 
343
+ # Only run on subset for speed
344
+ sample_size = min(n_markers_sample, n_markers)
345
+ sampled_idx = np.random.choice(n_markers, sample_size, replace=False)
346
+
347
+ for idx in sampled_idx:
348
+ X = genotypes[:, idx]
349
  if np.std(X) > 1e-6:
350
  try:
351
  data = pd.DataFrame({'pheno': phenotypes, 'marker': X})
352
+ model = sm.OLS(phenotypes, sm.add_constant(X)).fit()
353
+ pvals[idx] = model.pvalues[1]
354
+ effects[idx] = model.params[1]
355
+ lod[idx] = -np.log10(pvals[idx] + 1e-300)
 
356
  except:
357
  pass
358
 
359
+ # Fill remaining with mean
360
+ pvals[~np.isnan(pvals)] = np.nanmean(pvals)
361
+ effects[~np.isnan(effects)] = np.nanmean(effects)
362
+ lod[~np.isnan(lod)] = np.nanmean(lod)
363
+
364
  return pvals, effects, lod
365
 
366
+ def fast_elasticnet(genotypes, phenotypes):
367
+ """Fast ElasticNet with minimal bootstrap"""
368
  scaler = StandardScaler()
369
  X_scaled = scaler.fit_transform(genotypes)
370
 
371
+ enet = ElasticNetCV(cv=3, random_state=42, max_iter=1000, n_alphas=5)
372
+ enet.fit(X_scaled, phenotypes)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
373
 
374
+ coefficients = enet.coef_
 
 
 
 
 
375
 
376
+ # Simple p-value approximation from coefficient magnitude
377
+ coef_abs = np.abs(coefficients)
378
+ pvals = np.exp(-coef_abs / (coef_abs.max() + 1e-10) * 5)
379
  lod = -np.log10(pvals + 1e-300)
380
 
381
+ return pvals, coefficients, lod, enet.score(X_scaled, phenotypes)
 
 
 
 
382
 
383
+ def fast_randomforest(genotypes, phenotypes):
384
+ """Fast Random Forest with reduced trees"""
385
+ scaler = StandardScaler()
386
+ X_scaled = scaler.fit_transform(genotypes)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
387
 
388
+ # Use fewer trees for speed
389
+ rf = RandomForestRegressor(n_estimators=50, random_state=42, n_jobs=-1, max_depth=10)
390
+ rf.fit(X_scaled, phenotypes)
 
391
 
392
+ importance = rf.feature_importances_
 
393
 
394
+ # Simple p-value from importance ranking
395
+ imp_rank = np.argsort(importance)[::-1]
396
+ pvals = np.ones(len(importance))
397
+ for i, idx in enumerate(imp_rank):
398
+ pvals[idx] = (i + 1) / len(importance)
 
 
 
399
 
400
+ lod = -np.log10(pvals + 1e-300)
 
 
 
 
 
401
 
402
+ return pvals, importance, lod, rf.score(X_scaled, phenotypes)
 
 
 
 
403
 
404
  # ══════════════════════════════════════════════════════════════
405
+ # FAST DATA PROCESSING
406
  # ══════════════════════════════════════════════════════════════
407
 
408
+ def parse_gwas_csv_fast(filepath):
409
+ """Fast CSV parsing"""
410
+ df = pd.read_csv(filepath, header=0, nrows=1000) # Limit rows for speed
411
+ n_samples = min(500, len(df) - 1) # Limit samples
412
+
413
+ # Read only needed rows
414
+ df_full = pd.read_csv(filepath, header=0, nrows=n_samples + 1)
415
 
416
+ marker_cols = df_full.columns[2:].tolist()
417
+ n_markers = len(marker_cols)
 
418
 
419
+ # Parse chromosomes from first row
420
+ first_row = df_full.iloc[0]
421
+ chromosomes = []
422
+ positions = []
423
 
424
  for m in marker_cols:
425
  val = str(first_row[m]).strip()
426
  if ':' in val:
427
+ chrom, pos = val.split(':')[:2]
428
+ chromosomes.append(chrom)
429
+ try:
430
+ positions.append(float(pos))
431
+ except:
432
+ positions.append(0)
 
 
 
 
 
 
 
 
 
433
  else:
434
+ chromosomes.append(val)
435
+ positions.append(0)
 
 
436
 
437
+ # Sample data
438
+ sample_data = df_full.iloc[1:n_samples+1].reset_index(drop=True)
439
  sample_ids = sample_data.iloc[:, 0].astype(str).values
440
  phenotypes = pd.to_numeric(sample_data.iloc[:, 1], errors='coerce').values
441
 
442
+ # Genotype matrix
443
+ genotypes = sample_data[marker_cols].apply(pd.to_numeric, errors='coerce').values
444
 
445
+ return sample_ids, phenotypes, genotypes, marker_cols, chromosomes, positions
 
446
 
447
+ def fast_qc(genotypes, phenotypes, sample_ids, chromosomes, positions,
448
+ max_missing=0.5, maf_thresh=0.05):
449
+ """Fast QC"""
 
450
  n_samples, n_markers = genotypes.shape
451
 
452
+ # Remove high missing markers
453
  marker_missing = np.isnan(genotypes).sum(axis=0) / n_samples
454
+ keep_markers = marker_missing < max_missing
455
 
456
+ # Remove high missing samples
457
+ sample_missing = np.isnan(genotypes).sum(axis=1) / n_markers
458
+ keep_samples = sample_missing < max_missing
459
+
460
+ # Apply filters
461
+ genotypes_f = genotypes[np.ix_(keep_samples, keep_markers)]
462
+ phenotypes_f = phenotypes[keep_samples]
463
+ sample_ids_f = sample_ids[keep_samples]
464
+ chromosomes_f = [chromosomes[i] for i in range(n_markers) if keep_markers[i]]
465
+ positions_f = [positions[i] for i in range(n_markers) if keep_markers[i]]
466
+
467
+ # Simple MAF filter (fast approximation)
468
+ if genotypes_f.shape[1] > 0:
469
+ maf = np.abs(np.nanmean(genotypes_f, axis=0) / 2 - 0.5) * 2
470
+ keep_maf = maf >= maf_thresh
471
+ genotypes_f = genotypes_f[:, keep_maf]
472
+ chromosomes_f = [chromosomes_f[i] for i in range(len(chromosomes_f)) if keep_maf[i]]
473
+ positions_f = [positions_f[i] for i in range(len(positions_f)) if keep_maf[i]]
474
+
475
+ # Impute with mean (fast)
476
+ col_means = np.nanmean(genotypes_f, axis=0)
477
+ inds = np.where(np.isnan(genotypes_f))
478
+ genotypes_f[inds] = np.take(col_means, inds[1])
479
+
480
+ # Remove NaN phenotypes
481
+ valid_pheno = ~np.isnan(phenotypes_f)
482
+ genotypes_f = genotypes_f[valid_pheno]
483
+ phenotypes_f = phenotypes_f[valid_pheno]
484
+ sample_ids_f = sample_ids_f[valid_pheno]
485
+
486
+ return genotypes_f, phenotypes_f, sample_ids_f, chromosomes_f, positions_f
487
+
488
+ def fast_pca_and_kinship(genotypes, n_components=5):
489
+ """Fast PCA and kinship"""
490
+ # Impute and standardize
491
  imputer = SimpleImputer(strategy='mean')
492
+ genotypes_imp = imputer.fit_transform(genotypes)
493
+ genotypes_scaled = (genotypes_imp - genotypes_imp.mean(axis=0)) / (genotypes_imp.std(axis=0) + 1e-10)
494
 
495
+ # Fast PCA
496
+ pca = PCA(n_components=min(n_components, genotypes_scaled.shape[1]))
497
+ pca_result = pca.fit_transform(genotypes_scaled)
 
498
 
499
+ # Fast kinship (using subset of markers)
500
+ n_markers_for_kinship = min(500, genotypes_scaled.shape[1])
501
+ marker_idx = np.random.choice(genotypes_scaled.shape[1], n_markers_for_kinship, replace=False)
502
+ genotypes_subset = genotypes_scaled[:, marker_idx]
503
+ kinship = np.corrcoef(genotypes_subset)
504
+ kinship = (kinship + 1) / 2 # Scale to 0-1
505
+
506
+ return pca_result, pca.explained_variance_ratio_, kinship
507
 
508
  # ══════════════════════════════════════════════════════════════
509
+ # MAIN FAST PIPELINE
510
  # ══════════════════════════════════════════════════════════════
511
 
512
+ def run_fast_gwas(input_file, sample_missing, marker_missing, maf_threshold,
513
+ include_lr, include_mlm, include_enet, include_rf):
514
+ """Fast GWAS pipeline"""
 
515
 
516
  if input_file is None:
517
+ return ("Please upload a CSV file", None, None, None, None, None, None)
518
 
519
  try:
520
  temp_dir = tempfile.mkdtemp()
 
523
  os.makedirs(plots_dir, exist_ok=True)
524
 
525
  # Parse data
526
+ sample_ids, phenotypes, genotypes, marker_names, chromosomes, positions = parse_gwas_csv_fast(input_file.name)
 
527
 
528
  n_samples_raw, n_markers_raw = genotypes.shape
529
 
530
+ # QC
531
+ genotypes_qc, phenotypes_qc, sample_ids_qc, chromosomes_qc, positions_qc = fast_qc(
532
+ genotypes, phenotypes, sample_ids, chromosomes, positions,
533
+ max_missing=marker_missing/100, maf_thresh=maf_threshold/100
 
 
 
 
 
534
  )
535
 
536
  if len(sample_ids_qc) < 10:
537
+ return (f"⚠️ Only {len(sample_ids_qc)} samples after QC", None, None, None, None, None, None)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
538
 
539
+ # PCA and Kinship
540
+ pca_result, pca_var, kinship = fast_pca_and_kinship(genotypes_qc, n_components=5)
 
541
 
542
+ # Results storage
543
+ results = {'Marker': marker_names, 'Chromosome': chromosomes_qc, 'Position': positions_qc}
 
 
 
544
  models_used = []
545
 
546
+ # Run selected models
547
  if include_lr:
548
+ print("Running Linear Regression...")
549
+ pvals, effects, lod = fast_linear_regression(genotypes_qc, phenotypes_qc)
550
  results['LR_P'] = pvals
551
  results['LR_Beta'] = effects
552
  results['LR_LOD'] = lod
 
553
  models_used.append('LR')
554
 
555
  if include_mlm:
556
+ print("Running Mixed Model...")
557
+ pvals, effects, lod = fast_mixed_model(genotypes_qc, phenotypes_qc)
558
  results['MLM_P'] = pvals
559
  results['MLM_Beta'] = effects
560
  results['MLM_LOD'] = lod
 
561
  models_used.append('MLM')
562
 
563
  if include_enet:
564
+ print("Running ElasticNet...")
565
+ pvals, effects, lod, cv = fast_elasticnet(genotypes_qc, phenotypes_qc)
566
  results['EN_P'] = pvals
567
  results['EN_Beta'] = effects
568
  results['EN_LOD'] = lod
 
569
  models_used.append('EN')
570
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
571
  if include_rf:
572
+ print("Running Random Forest...")
573
+ pvals, importance, lod, cv = fast_randomforest(genotypes_qc, phenotypes_qc)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
574
  results['RF_P'] = pvals
575
+ results['RF_Imp'] = importance
576
  results['RF_LOD'] = lod
 
577
  models_used.append('RF')
578
 
579
+ # Create DataFrame
580
+ gwas_df = pd.DataFrame(results)
 
 
 
 
 
 
 
 
 
 
 
 
 
581
 
582
+ # Significance
583
+ bonf_threshold = 0.05 / len(marker_names)
584
  for model in models_used:
585
  if f'{model}_P' in gwas_df.columns:
586
  gwas_df[f'Sig_{model}'] = (gwas_df[f'{model}_P'] < bonf_threshold).astype(int)
587
 
588
+ # Consensus
589
  sig_cols = [c for c in gwas_df.columns if c.startswith('Sig_')]
590
+ if len(sig_cols) > 0:
591
+ gwas_df['Consensus_Sig'] = gwas_df[sig_cols].sum(axis=1) >= 2
 
 
 
 
592
 
593
+ # Sort
594
  if 'LR_LOD' in gwas_df.columns:
595
  gwas_df = gwas_df.sort_values('LR_LOD', ascending=False)
596
  gwas_df['Rank'] = range(1, len(gwas_df) + 1)
 
598
  # Save results
599
  gwas_df.to_csv(os.path.join(results_dir, 'gwas_results.csv'), index=False)
600
 
 
 
 
 
 
 
 
 
 
 
 
601
  # Generate plots
602
+ manhattan_path = os.path.join(plots_dir, 'manhattan.png')
603
+ if 'LR_P' in gwas_df.columns:
604
+ fast_manhattan_plot(
605
+ gwas_df['LR_P'].values, np.array(chromosomes_qc),
606
+ gwas_df['LR_LOD'].values if 'LR_LOD' in gwas_df.columns else np.zeros(len(gwas_df)),
607
+ bonf_threshold, manhattan_path
 
 
 
 
 
 
608
  )
609
 
 
610
  ld_path = os.path.join(plots_dir, 'ld_decay.png')
611
+ fast_ld_decay(genotypes_qc, np.array(chromosomes_qc), positions_qc, ld_path)
 
 
 
 
 
 
612
 
 
613
  circos_path = os.path.join(plots_dir, 'circos.png')
614
  if 'LR_P' in gwas_df.columns:
615
+ fast_circos(np.array(chromosomes_qc), gwas_df['LR_P'].values, bonf_threshold, circos_path)
616
+
617
+ pca_path = os.path.join(plots_dir, 'pca.png')
618
+ fast_pca_plot(pca_result, pca_var, phenotypes_qc, pca_path)
 
 
 
619
 
620
+ kinship_path = os.path.join(plots_dir, 'kinship.png')
621
+ fast_kinship_plot(kinship, kinship_path)
622
+
623
+ # Create ZIP
624
  zip_path = os.path.join(temp_dir, 'GWAS_Results.zip')
625
  with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf:
626
  for root, _, files in os.walk(results_dir):
627
  for f in files:
628
+ zf.write(os.path.join(root, f), os.path.relpath(os.path.join(root, f), temp_dir))
 
 
629
 
630
+ # Summary
631
  summary = f"""
632
+ ## βœ… GWAS Analysis Complete!
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
633
 
634
+ ### Quick Stats
635
+ - **Samples:** {len(sample_ids_qc)} (from {n_samples_raw})
636
+ - **Markers:** {len(marker_names)} (from {n_markers_raw})
637
+ - **Models:** {', '.join(models_used)}
638
+ - **Significant markers:** {gwas_df['Consensus_Sig'].sum() if 'Consensus_Sig' in gwas_df.columns else 0}
639
 
640
+ ### Top Markers
641
+ {gwas_df.head(10)[['Marker', 'Chromosome', 'LR_LOD', 'Consensus_Sig']].to_markdown(index=False) if 'LR_LOD' in gwas_df.columns else 'N/A'}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
642
  """
643
 
644
+ return (summary, manhattan_path, ld_path, circos_path, pca_path, kinship_path, zip_path)
 
 
 
645
 
646
  except Exception as e:
647
+ return (f"❌ Error: {str(e)}", None, None, None, None, None, None)
 
 
648
 
649
  # ══════════════════════════════════════════════════════════════
650
  # GRADIO INTERFACE
651
  # ══════════════════════════════════════════════════════════════
652
 
653
+ with gr.Blocks(css=FAST_CSS, title="Fast GWAS", theme=gr.themes.Soft()) as app:
654
 
655
  gr.HTML("""
656
  <div class="main-header">
657
+ <h1>⚑ Fast GWAS Analysis Platform</h1>
658
+ <p>Optimized for Speed | PCA | Kinship | 4 Models</p>
659
  </div>
660
  """)
661
 
662
  with gr.Row():
663
  with gr.Column(scale=1):
664
+ gr.HTML('<div class="section-header">πŸ“‚ Input</div>')
665
+ input_file = gr.File(label="CSV File", file_types=[".csv"])
 
 
 
 
 
 
 
 
 
 
 
 
666
 
667
+ gr.HTML('<div class="section-header">βš™οΈ QC</div>')
668
+ sample_missing = gr.Slider(10, 80, value=50, step=10, label="Sample Missing (%)")
669
+ marker_missing = gr.Slider(10, 80, value=50, step=10, label="Marker Missing (%)")
670
+ maf_threshold = gr.Slider(1, 20, value=5, step=5, label="MAF (%)")
 
 
 
 
 
 
671
 
672
+ gr.HTML('<div class="section-header">πŸ€– Models</div>')
673
+ include_lr = gr.Checkbox(label="Linear Regression", value=True)
674
+ include_mlm = gr.Checkbox(label="Mixed Model", value=False)
675
+ include_enet = gr.Checkbox(label="ElasticNet", value=False)
676
+ include_rf = gr.Checkbox(label="Random Forest", value=False)
677
 
678
+ run_btn = gr.Button("πŸš€ Run GWAS", variant="primary")
 
 
 
 
 
 
 
 
679
 
680
  with gr.Column(scale=2):
681
+ gr.HTML('<div class="section-header">πŸ“Š Results</div>')
682
+ summary_out = gr.Markdown("Ready")
683
 
 
684
  with gr.Row():
685
+ manhattan_out = gr.Image(label="Manhattan Plot")
686
+ ld_out = gr.Image(label="LD Decay")
687
  with gr.Row():
688
+ circos_out = gr.Image(label="Circos Plot")
689
+ pca_out = gr.Image(label="PCA")
690
  with gr.Row():
691
+ kinship_out = gr.Image(label="Kinship")
692
 
693
+ download_out = gr.File(label="Download ZIP")
 
 
694
 
695
+ run_btn.click(
696
+ fn=run_fast_gwas,
697
  inputs=[input_file, sample_missing, marker_missing, maf_threshold,
698
+ include_lr, include_mlm, include_enet, include_rf],
699
+ outputs=[summary_out, manhattan_out, ld_out, circos_out, pca_out, kinship_out, download_out]
 
 
 
700
  )
701
 
702
  gr.HTML("""
703
+ <footer style="text-align:center; padding:15px; margin-top:20px; background:#FFFEF8; border-radius:10px;">
704
+ <p>⚑ Optimized for Speed | Times New Roman | Soft Pastel Colors</p>
 
705
  </footer>
706
  """)
707