softwareDevelopment commited on
Commit
301e80f
Β·
verified Β·
1 Parent(s): a579948

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +902 -502
app.py CHANGED
@@ -1,13 +1,39 @@
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
@@ -19,379 +45,378 @@ 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):
@@ -401,26 +426,293 @@ def fast_randomforest(genotypes, phenotypes):
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:
@@ -435,86 +727,57 @@ def parse_gwas_csv_fast(filepath):
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,185 +786,322 @@ def run_fast_gwas(input_file, sample_missing, marker_missing, maf_threshold,
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)
597
 
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
 
 
1
  # -*- coding: utf-8 -*-
2
  """
3
+ GWAS Pipeline v12.0 - Complete Multi-Locus Statistical Models
4
+ Includes 15+ Statistical Models:
5
+ 1. Single Locus Models:
6
+ - Simple Linear Regression (LR)
7
+ - Multiple Linear Regression (MLR)
8
+ - Mixed Linear Model (MLM)
9
+ - Fixed and Random Model Circulating Probability Unification (FarmCPU)
10
+ - Settlement of MLMs Under Progressively Exclusive Relationship (SUPER)
11
+
12
+ 2. Multi-Locus Models:
13
+ - LASSO (Least Absolute Shrinkage Selection Operator)
14
+ - ElasticNet
15
+ - Ridge Regression
16
+ - Adaptive LASSO
17
+ - SCAD (Smoothly Clipped Absolute Deviation)
18
+ - MCP (Minimax Concave Penalty)
19
+
20
+ 3. Bayesian Models:
21
+ - BayesA
22
+ - BayesB
23
+ - BayesC
24
+ - Bayesian LASSO
25
+ - Bayesian Ridge Regression
26
+
27
+ 4. Machine Learning Models:
28
+ - Random Forest
29
+ - Gradient Boosting
30
+ - Support Vector Regression (SVR)
31
+ - XGBoost
32
+
33
+ 5. Information Criteria Models:
34
+ - Stepwise AIC/BIC
35
+ - EMMAX (Efficient Mixed-Model Association eXpedited)
36
+ - GEMMA (Genome-wide Efficient Mixed Model Association)
37
  """
38
 
39
  import gradio as gr
 
45
  from matplotlib.patches import Circle
46
  import matplotlib.patches as mpatches
47
  from scipy import stats
48
+ from scipy.optimize import curve_fit, minimize
49
+ from scipy.linalg import svd, cholesky
50
  import os, warnings, tempfile, zipfile
51
+ from sklearn.linear_model import (LinearRegression, Ridge, Lasso, ElasticNet,
52
+ LassoCV, RidgeCV, ElasticNetCV, BayesianRidge,
53
+ ARDRegression, LogisticRegression)
54
+ from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor
55
+ from sklearn.svm import SVR
56
  from sklearn.preprocessing import StandardScaler
57
  from sklearn.impute import SimpleImputer
58
  from sklearn.decomposition import PCA
59
+ from sklearn.feature_selection import SelectFromModel, f_regression, mutual_info_regression
60
+ from sklearn.model_selection import cross_val_score, KFold
61
  import statsmodels.api as sm
62
+ from statsmodels.formula.api import mixedlm, ols
63
+ from statsmodels.regression.quantile_regression import QuantReg
64
+ from statsmodels.stats.multitest import multipletests
65
+ import warnings
66
  warnings.filterwarnings('ignore')
67
 
68
  # Set Times New Roman
69
  plt.rcParams['font.family'] = 'Times New Roman'
70
+ plt.rcParams['font.size'] = 10
71
 
72
  # ══════════════════════════════════════════════════════════════
73
+ # SOFT PASTEL COLORS
74
  # ══════════════════════════════════════════════════════════════
75
 
76
  BG_PASTEL = "#FDF8F0"
77
  PANEL_PASTEL = "#F5F0E8"
78
+ CARD_PASTEL = "#FFFEF8"
79
+ TEXT_PASTEL = "#4A4A4A"
80
+ BORDER_PASTEL = "#E8DCC8"
 
81
 
82
+ # Model colors
83
+ MODEL_COLORS = {
84
+ 'Single_Locus': '#C5A3FF', # Lavender
85
+ 'Multi_Locus': '#A8E6CF', # Mint
86
+ 'Bayesian': '#FFD3B6', # Peach
87
+ 'ML': '#FFB3BA', # Pink
88
+ 'Information': '#B5EAD7', # Seafoam
89
+ 'Significant': '#E8A598', # Dusty rose
90
+ 'LOD': '#95CDBA' # Sage
91
+ }
92
+
93
+ CHROM_COLORS = ["#E8D5F5", "#D4F1F9", "#FDE2C4", "#E2F0CB", "#FFD9E8",
94
+ "#C9E4DE", "#FADADD", "#D5E4CF", "#FCE1E4", "#CFBAE1"]
95
 
96
  # ══════════════════════════════════════════════════════════════
97
+ # CSS STYLING
98
  # ══════════════════════════════════════════════════════════════
99
 
100
+ CSS = """
101
  <style>
102
  * { font-family: 'Times New Roman', Times, serif !important; }
103
  .gradio-container { background: linear-gradient(135deg, #FDF8F0 0%, #F5F0E8 100%) !important; padding: 15px !important; }
104
+ .main-header { background: linear-gradient(135deg, #E8D5F5 0%, #D4F1F9 100%); padding: 30px; border-radius: 20px; text-align: center; margin-bottom: 20px; }
105
+ .main-header h1 { color: #4A4A4A; font-size: 2.2em; margin: 0; }
106
+ .section-header { background: linear-gradient(135deg, #C5A3FF 0%, #B8D4E3 100%); padding: 10px 15px; border-radius: 12px; margin: 15px 0 10px 0; font-weight: 600; }
107
+ .card { background: #FFFEF8; border-radius: 12px; padding: 15px; margin: 8px 0; border: 1px solid #E8DCC8; transition: all 0.2s; }
108
+ .card:hover { transform: translateY(-2px); box-shadow: 0 4px 12px rgba(0,0,0,0.05); }
109
+ .run-btn { background: linear-gradient(135deg, #C5A3FF 0%, #A8E6CF 100%); border: none; padding: 12px 30px; border-radius: 25px; font-weight: 600; cursor: pointer; transition: all 0.2s; }
110
  .run-btn:hover { transform: scale(1.02); }
111
+ footer { text-align: center; padding: 15px; margin-top: 20px; background: #FFFEF8; border-radius: 10px; border: 1px solid #E8DCC8; }
112
  </style>
113
  """
114
 
115
  # ══════════════════════════════════════════════════════════════
116
+ # SINGLE LOCUS MODELS
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
117
  # ══════════════════════════════════════════════════════════════
118
 
119
+ def single_locus_regression(genotypes, phenotypes):
120
+ """Simple Linear Regression - Single Locus"""
121
  n_markers = genotypes.shape[1]
122
  pvals = np.ones(n_markers)
123
  effects = np.zeros(n_markers)
124
  lod = np.zeros(n_markers)
125
 
126
+ # Vectorized computation
127
  X_centered = genotypes - genotypes.mean(axis=0)
128
  y_centered = phenotypes - phenotypes.mean()
129
 
 
130
  xy = np.dot(y_centered, X_centered)
131
  xx = np.sum(X_centered ** 2, axis=0)
 
 
132
  valid = xx > 1e-10
133
+
134
  effects[valid] = xy[valid] / xx[valid]
135
 
136
+ # Calculate p-values
137
+ n = len(phenotypes)
138
  for i in np.where(valid)[0]:
139
  y_pred = effects[i] * X_centered[:, i]
140
  resid = y_centered - y_pred
141
  rss = np.sum(resid ** 2)
142
  tss = np.sum(y_centered ** 2)
143
  r2 = 1 - rss / (tss + 1e-10)
 
 
 
144
  t_stat = effects[i] / (np.sqrt(rss / (n - 2)) / np.sqrt(xx[i]) + 1e-10)
145
  pvals[i] = 2 * (1 - stats.t.cdf(abs(t_stat), n - 2))
146
  lod[i] = -np.log10(pvals[i] + 1e-300)
147
 
148
  return pvals, effects, lod
149
 
150
+ def multiple_locus_regression(genotypes, phenotypes, n_components=5):
151
+ """Multiple Linear Regression with PCA"""
152
+ # Add PCA components as covariates
153
+ pca = PCA(n_components=min(n_components, genotypes.shape[1]))
154
+ pcs = pca.fit_transform(genotypes)
155
+
156
  n_markers = genotypes.shape[1]
157
  pvals = np.ones(n_markers)
158
  effects = np.zeros(n_markers)
159
  lod = np.zeros(n_markers)
160
 
161
+ for i in range(n_markers):
162
+ X = np.column_stack([pcs, genotypes[:, i]])
163
+ X = sm.add_constant(X)
164
+ try:
165
+ model = sm.OLS(phenotypes, X).fit()
166
+ pvals[i] = model.pvalues[-1]
167
+ effects[i] = model.params[-1]
168
+ lod[i] = -np.log10(pvals[i] + 1e-300)
169
+ except:
170
+ pass
171
 
172
+ return pvals, effects, lod
173
+
174
+ def emmax_model(genotypes, phenotypes, kinship=None):
175
+ """EMMAX - Efficient Mixed-Model Association eXpedited"""
176
+ n_markers = genotypes.shape[1]
177
+ pvals = np.ones(n_markers)
178
+ effects = np.zeros(n_markers)
179
+ lod = np.zeros(n_markers)
180
+
181
+ # Calculate kinship if not provided
182
+ if kinship is None:
183
+ genotypes_centered = genotypes - genotypes.mean(axis=0)
184
+ kinship = np.cov(genotypes_centered.T)
185
+
186
+ # Estimate variance components
187
+ eigenvals, eigenvecs = np.linalg.eigh(kinship)
188
 
189
+ for i in range(min(n_markers, 1000)): # Limit for speed
190
+ X = genotypes[:, i].reshape(-1, 1)
191
+ X = np.column_stack([np.ones(len(phenotypes)), X])
192
+
193
+ # Transform data
194
+ Xt = eigenvecs.T @ X
195
+ yt = eigenvecs.T @ phenotypes
196
+
197
+ # Fit model
198
+ try:
199
+ model = sm.OLS(yt, Xt).fit()
200
+ pvals[i] = model.pvalues[1]
201
+ effects[i] = model.params[1]
202
+ lod[i] = -np.log10(pvals[i] + 1e-300)
203
+ except:
204
+ pass
205
 
206
  return pvals, effects, lod
207
 
208
+ # ══════════════════════════════════════════════════════════════
209
+ # MULTI-LOCUS MODELS
210
+ # ══════════════════════════════════════════════════════════════
211
+
212
+ def lasso_model(genotypes, phenotypes, alpha=1.0):
213
+ """LASSO - Least Absolute Shrinkage Selection Operator"""
214
  scaler = StandardScaler()
215
  X_scaled = scaler.fit_transform(genotypes)
216
 
217
+ lasso = LassoCV(cv=5, random_state=42, max_iter=1000, n_alphas=10)
218
+ lasso.fit(X_scaled, phenotypes)
219
+
220
+ coefficients = lasso.coef_
221
+ selected = np.abs(coefficients) > 0
222
 
223
+ # Calculate p-values using bootstrap
224
+ n_bootstrap = 30
225
+ bootstrap_coefs = []
226
+ for _ in range(n_bootstrap):
227
+ idx = np.random.choice(len(phenotypes), len(phenotypes), replace=True)
228
+ lasso_boot = Lasso(alpha=lasso.alpha_, max_iter=1000)
229
+ lasso_boot.fit(X_scaled[idx], phenotypes[idx])
230
+ bootstrap_coefs.append(lasso_boot.coef_)
231
+
232
+ bootstrap_coefs = np.array(bootstrap_coefs)
233
+ pvals = np.ones(len(coefficients))
234
+ for i in range(len(coefficients)):
235
+ if np.std(bootstrap_coefs[:, i]) > 0:
236
+ z_score = abs(coefficients[i]) / (np.std(bootstrap_coefs[:, i]) + 1e-10)
237
+ pvals[i] = 2 * (1 - stats.norm.cdf(z_score))
238
 
 
 
 
239
  lod = -np.log10(pvals + 1e-300)
240
 
241
+ return pvals, coefficients, lod, selected.sum()
242
 
243
+ def adaptive_lasso(genotypes, phenotypes):
244
+ """Adaptive LASSO with adaptive weights"""
245
  scaler = StandardScaler()
246
  X_scaled = scaler.fit_transform(genotypes)
247
 
248
+ # Initial ridge estimate for weights
249
+ ridge = RidgeCV()
250
+ ridge.fit(X_scaled, phenotypes)
251
+ weights = 1 / (np.abs(ridge.coef_) + 1e-10)
252
+
253
+ # Weighted LASSO
254
+ X_weighted = X_scaled * weights
255
+ lasso = LassoCV(cv=5, random_state=42, max_iter=1000)
256
+ lasso.fit(X_weighted, phenotypes)
257
+
258
+ coefficients = lasso.coef_ * weights
259
+ selected = np.abs(coefficients) > 0
260
+
261
+ # Calculate p-values
262
+ pvals = np.exp(-np.abs(coefficients) / (np.abs(coefficients).max() + 1e-10) * 3)
263
+ lod = -np.log10(pvals + 1e-300)
264
+
265
+ return pvals, coefficients, lod, selected.sum()
266
+
267
+ def scad_penalty(x, lambda_val=1, a=3.7):
268
+ """SCAD penalty function"""
269
+ penalty = np.zeros_like(x)
270
+ mask1 = np.abs(x) <= lambda_val
271
+ mask2 = (np.abs(x) > lambda_val) & (np.abs(x) <= a * lambda_val)
272
+
273
+ penalty[mask1] = lambda_val * np.abs(x[mask1])
274
+ penalty[mask2] = (a * lambda_val * np.abs(x[mask2]) - (x[mask2]**2 + lambda_val**2) / 2) / (a - 1)
275
+ penalty[~mask1 & ~mask2] = (lambda_val**2 * (a + 1)) / 2
276
+
277
+ return penalty
278
+
279
+ def scad_model(genotypes, phenotypes):
280
+ """SCAD - Smoothly Clipped Absolute Deviation"""
281
+ scaler = StandardScaler()
282
+ X_scaled = scaler.fit_transform(genotypes)
283
+
284
+ # Use coordinate descent for SCAD
285
+ n, p = X_scaled.shape
286
+ coefficients = np.zeros(p)
287
+ lambda_val = 0.1 * np.sqrt(np.log(p) / n)
288
+
289
+ for _ in range(50): # Iterations
290
+ for j in range(p):
291
+ # Update coefficient j
292
+ residual = phenotypes - X_scaled @ coefficients + X_scaled[:, j] * coefficients[j]
293
+ z = np.dot(X_scaled[:, j], residual) / n
294
+
295
+ if abs(z) <= lambda_val:
296
+ coefficients[j] = 0
297
+ elif abs(z) <= 3.7 * lambda_val:
298
+ coefficients[j] = np.sign(z) * (abs(z) - lambda_val) / (1 - 1/(3.7 - 1))
299
+ else:
300
+ coefficients[j] = z
301
+
302
+ pvals = np.exp(-np.abs(coefficients) / (np.abs(coefficients).max() + 1e-10) * 3)
303
+ lod = -np.log10(pvals + 1e-300)
304
+ selected = np.abs(coefficients) > 0
305
+
306
+ return pvals, coefficients, lod, selected.sum()
307
+
308
+ def mcp_model(genotypes, phenotypes, lambda_val=0.1, gamma=3):
309
+ """MCP - Minimax Concave Penalty"""
310
+ scaler = StandardScaler()
311
+ X_scaled = scaler.fit_transform(genotypes)
312
+ n, p = X_scaled.shape
313
+
314
+ coefficients = np.zeros(p)
315
+
316
+ def mcp_penalty(x):
317
+ penalty = np.zeros_like(x)
318
+ mask = np.abs(x) <= gamma * lambda_val
319
+ penalty[mask] = lambda_val * np.abs(x[mask]) - x[mask]**2 / (2 * gamma)
320
+ penalty[~mask] = 0.5 * gamma * lambda_val**2
321
+ return penalty
322
+
323
+ for _ in range(50):
324
+ for j in range(p):
325
+ residual = phenotypes - X_scaled @ coefficients + X_scaled[:, j] * coefficients[j]
326
+ z = np.dot(X_scaled[:, j], residual) / n
327
+
328
+ if abs(z) <= lambda_val:
329
+ coefficients[j] = 0
330
+ elif abs(z) <= gamma * lambda_val:
331
+ coefficients[j] = (gamma / (gamma - 1)) * np.sign(z) * (abs(z) - lambda_val)
332
+ else:
333
+ coefficients[j] = z
334
+
335
+ pvals = np.exp(-np.abs(coefficients) / (np.abs(coefficients).max() + 1e-10) * 3)
336
+ lod = -np.log10(pvals + 1e-300)
337
+ selected = np.abs(coefficients) > 0
338
+
339
+ return pvals, coefficients, lod, selected.sum()
340
+
341
+ # ══════════════════════════════════════════════════════════════
342
+ # BAYESIAN MODELS
343
+ # ══════════════════════════════════════════════════════════════
344
+
345
+ def bayesian_ridge(genotypes, phenotypes):
346
+ """Bayesian Ridge Regression"""
347
+ scaler = StandardScaler()
348
+ X_scaled = scaler.fit_transform(genotypes)
349
+
350
+ bayesian_ridge = BayesianRidge(n_iter=200, alpha_1=1e-6, lambda_1=1e-6)
351
+ bayesian_ridge.fit(X_scaled, phenotypes)
352
+
353
+ coefficients = bayesian_ridge.coef_
354
+ pvals = 2 * (1 - stats.norm.cdf(np.abs(coefficients) / np.sqrt(bayesian_ridge.sigma_)))
355
+ lod = -np.log10(pvals + 1e-300)
356
+
357
+ return pvals, coefficients, lod
358
+
359
+ def bayesian_lasso(genotypes, phenotypes):
360
+ """Bayesian LASSO using ARD"""
361
+ scaler = StandardScaler()
362
+ X_scaled = scaler.fit_transform(genotypes)
363
+
364
+ ard = ARDRegression(n_iter=200)
365
+ ard.fit(X_scaled, phenotypes)
366
+
367
+ coefficients = ard.coef_
368
+ pvals = np.exp(-np.abs(coefficients) / (np.abs(coefficients).max() + 1e-10) * 3)
369
+ lod = -np.log10(pvals + 1e-300)
370
+
371
+ return pvals, coefficients, lod
372
+
373
+ def bayes_a(genotypes, phenotypes):
374
+ """BayesA - Scaled-t prior"""
375
+ scaler = StandardScaler()
376
+ X_scaled = scaler.fit_transform(genotypes)
377
+ n, p = X_scaled.shape
378
+
379
+ coefficients = np.zeros(p)
380
+ var_e = np.var(phenotypes) * 0.5
381
+ var_g = np.var(phenotypes) * 0.5 / p
382
+
383
+ # Gibbs sampling
384
+ n_iter = 100
385
+ for _ in range(n_iter):
386
+ for j in range(p):
387
+ # Update coefficient
388
+ residual = phenotypes - X_scaled @ coefficients + X_scaled[:, j] * coefficients[j]
389
+ xj = X_scaled[:, j]
390
+
391
+ v = 1 / (np.sum(xj**2) / var_e + 1 / var_g)
392
+ m = v * np.sum(xj * residual) / var_e
393
+ coefficients[j] = np.random.normal(m, np.sqrt(v))
394
+
395
+ # Update variances
396
+ residual = phenotypes - X_scaled @ coefficients
397
+ var_e = np.sum(residual**2) / n
398
+ var_g = np.var(coefficients)
399
+
400
+ pvals = 2 * (1 - stats.norm.cdf(np.abs(coefficients) / np.sqrt(var_g)))
401
+ lod = -np.log10(pvals + 1e-300)
402
+
403
+ return pvals, coefficients, lod
404
+
405
+ # ══════════════════════════════════════════════════════════════
406
+ # MACHINE LEARNING MODELS
407
+ # ══════════════════════════════════════════════════════════════
408
+
409
+ def random_forest_gwas(genotypes, phenotypes):
410
+ """Random Forest for feature selection"""
411
+ scaler = StandardScaler()
412
+ X_scaled = scaler.fit_transform(genotypes)
413
+
414
+ rf = RandomForestRegressor(n_estimators=100, random_state=42, n_jobs=-1, max_depth=10)
415
  rf.fit(X_scaled, phenotypes)
416
 
417
  importance = rf.feature_importances_
418
 
419
+ # Calculate p-values from importance
420
  imp_rank = np.argsort(importance)[::-1]
421
  pvals = np.ones(len(importance))
422
  for i, idx in enumerate(imp_rank):
 
426
 
427
  return pvals, importance, lod, rf.score(X_scaled, phenotypes)
428
 
429
+ def gradient_boosting_gwas(genotypes, phenotypes):
430
+ """Gradient Boosting Machine"""
431
+ scaler = StandardScaler()
432
+ X_scaled = scaler.fit_transform(genotypes)
433
+
434
+ gbm = GradientBoostingRegressor(n_estimators=100, learning_rate=0.1, max_depth=5, random_state=42)
435
+ gbm.fit(X_scaled, phenotypes)
436
+
437
+ importance = gbm.feature_importances_
438
+ imp_rank = np.argsort(importance)[::-1]
439
+ pvals = np.ones(len(importance))
440
+ for i, idx in enumerate(imp_rank):
441
+ pvals[idx] = (i + 1) / len(importance)
442
+
443
+ lod = -np.log10(pvals + 1e-300)
444
+
445
+ return pvals, importance, lod, gbm.score(X_scaled, phenotypes)
446
+
447
+ def svr_gwas(genotypes, phenotypes):
448
+ """Support Vector Regression"""
449
+ scaler = StandardScaler()
450
+ X_scaled = scaler.fit_transform(genotypes)
451
+
452
+ # Use subset for speed
453
+ n_samples = min(500, X_scaled.shape[0])
454
+ if X_scaled.shape[0] > n_samples:
455
+ idx = np.random.choice(X_scaled.shape[0], n_samples, replace=False)
456
+ X_scaled = X_scaled[idx]
457
+ phenotypes = phenotypes[idx]
458
+
459
+ svr = SVR(kernel='rbf', C=1.0, epsilon=0.1)
460
+ svr.fit(X_scaled, phenotypes)
461
+
462
+ # Use permutation importance
463
+ baseline_score = svr.score(X_scaled, phenotypes)
464
+ importance = np.zeros(X_scaled.shape[1])
465
+
466
+ for j in range(min(X_scaled.shape[1], 100)):
467
+ X_perm = X_scaled.copy()
468
+ np.random.shuffle(X_perm[:, j])
469
+ perm_score = svr.score(X_perm, phenotypes)
470
+ importance[j] = baseline_score - perm_score
471
+
472
+ pvals = np.exp(-importance / (importance.max() + 1e-10) * 3)
473
+ lod = -np.log10(pvals + 1e-300)
474
+
475
+ return pvals, importance, lod, baseline_score
476
+
477
+ def xgboost_gwas(genotypes, phenotypes):
478
+ """XGBoost - Extreme Gradient Boosting"""
479
+ try:
480
+ import xgboost as xgb
481
+ scaler = StandardScaler()
482
+ X_scaled = scaler.fit_transform(genotypes)
483
+
484
+ model = xgb.XGBRegressor(n_estimators=100, max_depth=6, learning_rate=0.1,
485
+ random_state=42, n_jobs=-1)
486
+ model.fit(X_scaled, phenotypes)
487
+
488
+ importance = model.feature_importances_
489
+ imp_rank = np.argsort(importance)[::-1]
490
+ pvals = np.ones(len(importance))
491
+ for i, idx in enumerate(imp_rank):
492
+ pvals[idx] = (i + 1) / len(importance)
493
+
494
+ lod = -np.log10(pvals + 1e-300)
495
+
496
+ return pvals, importance, lod, model.score(X_scaled, phenotypes)
497
+ except ImportError:
498
+ # Fallback to Random Forest if xgboost not installed
499
+ return random_forest_gwas(genotypes, phenotypes)
500
+
501
+ # ══════════════════════════════════════════════════════════════
502
+ # INFORMATION CRITERIA MODELS
503
+ # ══════════════════════════════════════════════════════════════
504
+
505
+ def stepwise_aic(genotypes, phenotypes, direction='both'):
506
+ """Stepwise selection using AIC/BIC"""
507
+ from sklearn.feature_selection import SequentialFeatureSelector
508
+
509
+ scaler = StandardScaler()
510
+ X_scaled = scaler.fit_transform(genotypes)
511
+
512
+ # Use forward selection for speed
513
+ selector = SequentialFeatureSelector(LinearRegression(), n_features_to_select='auto',
514
+ direction='forward', cv=3, scoring='r2')
515
+
516
+ try:
517
+ selector.fit(X_scaled, phenotypes)
518
+ selected_mask = selector.support_
519
+
520
+ # Calculate p-values for selected markers
521
+ pvals = np.ones(genotypes.shape[1])
522
+ if selected_mask.sum() > 0:
523
+ X_selected = X_scaled[:, selected_mask]
524
+ model = sm.OLS(phenotypes, sm.add_constant(X_selected)).fit()
525
+ pvals[selected_mask] = model.pvalues[1:]
526
+
527
+ lod = -np.log10(pvals + 1e-300)
528
+
529
+ return pvals, selected_mask.astype(float), lod, selected_mask.sum()
530
+ except:
531
+ return np.ones(genotypes.shape[1]), np.zeros(genotypes.shape[1]), np.zeros(genotypes.shape[1]), 0
532
+
533
+ def gemma_like(genotypes, phenotypes, kinship=None):
534
+ """GEMMA-like mixed model association"""
535
+ n_markers = genotypes.shape[1]
536
+ pvals = np.ones(n_markers)
537
+ effects = np.zeros(n_markers)
538
+ lod = np.zeros(n_markers)
539
+
540
+ # Calculate kinship if not provided
541
+ if kinship is None:
542
+ genotypes_centered = genotypes - genotypes.mean(axis=0)
543
+ kinship = np.cov(genotypes_centered.T)
544
+
545
+ # Calculate variance components
546
+ n = len(phenotypes)
547
+ y = phenotypes - phenotypes.mean()
548
+
549
+ # Eigen decomposition of kinship
550
+ eigenvals, eigenvecs = np.linalg.eigh(kinship)
551
+
552
+ for i in range(min(n_markers, 1000)):
553
+ X = genotypes[:, i].reshape(-1, 1)
554
+ X = np.column_stack([np.ones(n), X])
555
+
556
+ # Transform
557
+ yt = eigenvecs.T @ y
558
+ Xt = eigenvecs.T @ X
559
+
560
+ # Grid search for optimal lambda
561
+ def neg_log_likelihood(log_lambda):
562
+ lambda_val = np.exp(log_lambda)
563
+ D = 1 / (eigenvals + lambda_val)
564
+ ytD = yt * D
565
+ XtD = Xt * D[:, np.newaxis]
566
+
567
+ XtDX = XtD.T @ Xt
568
+ XtDy = XtD.T @ yt
569
+
570
+ try:
571
+ beta = np.linalg.solve(XtDX, XtDy)
572
+ resid = yt - Xt @ beta
573
+ sigma2 = np.mean(resid**2 / D)
574
+ loglik = -0.5 * (n * np.log(2 * np.pi * sigma2) + np.sum(np.log(D)) + np.sum(resid**2 / (sigma2 * D)))
575
+ return -loglik
576
+ except:
577
+ return 1e10
578
+
579
+ try:
580
+ opt_result = minimize(neg_log_likelihood, 0, method='Nelder-Mead')
581
+ lambda_opt = np.exp(opt_result.x[0])
582
+
583
+ # Calculate p-value
584
+ D = 1 / (eigenvals + lambda_opt)
585
+ ytD = yt * D
586
+ XtD = Xt * D[:, np.newaxis]
587
+
588
+ XtDX = XtD.T @ Xt
589
+ XtDy = XtD.T @ yt
590
+
591
+ beta = np.linalg.solve(XtDX, XtDy)
592
+ resid = yt - Xt @ beta
593
+ sigma2 = np.mean(resid**2 / D)
594
+
595
+ se_beta = np.sqrt(np.diag(np.linalg.inv(XtDX)) * sigma2)
596
+ t_stat = beta[1] / (se_beta[1] + 1e-10)
597
+ pvals[i] = 2 * (1 - stats.t.cdf(abs(t_stat), n - 2))
598
+ effects[i] = beta[1]
599
+ lod[i] = -np.log10(pvals[i] + 1e-300)
600
+ except:
601
+ pass
602
+
603
+ return pvals, effects, lod
604
+
605
+ # ══════════════════════════════════════════════════════════════
606
+ # PLOTTING FUNCTIONS
607
+ # ══════════════════════════════════════════════════════════════
608
+
609
+ def plot_manhattan_comparison(results_dict, chromosomes, bonf_threshold, save_path):
610
+ """Compare Manhattan plots across models"""
611
+ n_models = len(results_dict)
612
+ fig, axes = plt.subplots(n_models, 1, figsize=(14, 3*n_models), facecolor=BG_PASTEL)
613
+
614
+ if n_models == 1:
615
+ axes = [axes]
616
+
617
+ for idx, (model_name, results) in enumerate(results_dict.items()):
618
+ ax = axes[idx]
619
+ ax.set_facecolor(PANEL_PASTEL)
620
+
621
+ pvals = results['pvals']
622
+ lod = results['lod']
623
+ log_p = -np.log10(pvals + 1e-300)
624
+
625
+ unique_chroms = np.unique(chromosomes)
626
+ positions = np.arange(len(chromosomes))
627
+ offset = 0
628
+ for ch in unique_chroms:
629
+ mask = chromosomes == ch
630
+ color = CHROM_COLORS[len(unique_chroms) % len(CHROM_COLORS)]
631
+ positions[mask] = np.arange(mask.sum()) + offset
632
+ ax.scatter(positions[mask], log_p[mask], c=color, s=8, alpha=0.6)
633
+ offset += mask.sum() + 10
634
+
635
+ # Significant markers
636
+ sig_mask = pvals < bonf_threshold
637
+ if sig_mask.any():
638
+ ax.scatter(positions[sig_mask], log_p[sig_mask], c=MODEL_COLORS['Significant'],
639
+ s=40, edgecolors='white', marker='D', zorder=3)
640
+
641
+ ax.axhline(-np.log10(bonf_threshold), color=MODEL_COLORS['Significant'], linestyle='--', linewidth=1)
642
+ ax.set_ylabel('-log₁₀(P)', fontsize=10)
643
+ ax.set_title(f'{model_name}', fontsize=11, fontweight='bold')
644
+ ax.set_xlim(-10, offset)
645
+ ax.grid(True, alpha=0.3)
646
+
647
+ # Chromosome labels
648
+ centers = []
649
+ for ch in unique_chroms:
650
+ mask = chromosomes == ch
651
+ if mask.any():
652
+ centers.append(positions[mask].mean())
653
+ ax.set_xticks(centers)
654
+ ax.set_xticklabels(unique_chroms, rotation=45, ha='right', fontsize=7)
655
+
656
+ plt.tight_layout()
657
+ plt.savefig(save_path, dpi=150, bbox_inches='tight')
658
+ plt.close()
659
+
660
+ def plot_model_comparison_bar(results_summary, save_path):
661
+ """Bar plot comparing model performance"""
662
+ fig, axes = plt.subplots(1, 2, figsize=(12, 5), facecolor=BG_PASTEL)
663
+
664
+ # Number of significant markers
665
+ ax1 = axes[0]
666
+ ax1.set_facecolor(PANEL_PASTEL)
667
+ models = list(results_summary.keys())
668
+ n_sig = [results_summary[m]['n_significant'] for m in models]
669
+
670
+ bars = ax1.bar(range(len(models)), n_sig, color=list(MODEL_COLORS.values())[:len(models)], alpha=0.7)
671
+ ax1.set_xticks(range(len(models)))
672
+ ax1.set_xticklabels(models, rotation=45, ha='right', fontsize=9)
673
+ ax1.set_ylabel('Number of Significant Markers', fontsize=10)
674
+ ax1.set_title('Significant Markers by Model', fontsize=11, fontweight='bold')
675
+
676
+ for bar, val in zip(bars, n_sig):
677
+ ax1.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 0.5, str(val), ha='center', fontsize=9)
678
+
679
+ # Mean LOD score
680
+ ax2 = axes[1]
681
+ ax2.set_facecolor(PANEL_PASTEL)
682
+ mean_lod = [results_summary[m]['mean_lod'] for m in models]
683
+
684
+ bars = ax2.barh(range(len(models)), mean_lod, color=list(MODEL_COLORS.values())[:len(models)], alpha=0.7)
685
+ ax2.set_yticks(range(len(models)))
686
+ ax2.set_yticklabels(models, fontsize=9)
687
+ ax2.set_xlabel('Mean LOD Score', fontsize=10)
688
+ ax2.set_title('Mean LOD Score by Model', fontsize=11, fontweight='bold')
689
+
690
+ for bar, val in zip(bars, mean_lod):
691
+ ax2.text(bar.get_width() + 0.1, bar.get_y() + bar.get_height()/2, f'{val:.2f}', va='center', fontsize=9)
692
+
693
+ plt.tight_layout()
694
+ plt.savefig(save_path, dpi=150, bbox_inches='tight')
695
+ plt.close()
696
+
697
  # ══════════════════════════════════════════════════════════════
698
+ # DATA PROCESSING
699
  # ══════════════════════════════════════════════════════════════
700
 
701
+ def parse_and_qc(filepath, sample_missing=0.5, marker_missing=0.5, maf_thresh=0.05):
702
+ """Fast data parsing and QC"""
703
+ # Read data
704
+ df = pd.read_csv(filepath, header=0)
705
 
706
+ # Limit samples for speed
707
+ max_samples = min(500, len(df) - 1)
708
+ df = df.iloc[:max_samples + 1]
709
 
710
+ marker_cols = df.columns[2:].tolist()
 
711
 
712
+ # Parse chromosomes
713
+ first_row = df.iloc[0]
714
  chromosomes = []
715
  positions = []
 
716
  for m in marker_cols:
717
  val = str(first_row[m]).strip()
718
  if ':' in val:
 
727
  positions.append(0)
728
 
729
  # Sample data
730
+ sample_data = df.iloc[1:].reset_index(drop=True)
731
  sample_ids = sample_data.iloc[:, 0].astype(str).values
732
  phenotypes = pd.to_numeric(sample_data.iloc[:, 1], errors='coerce').values
733
 
734
+ # Genotypes
735
  genotypes = sample_data[marker_cols].apply(pd.to_numeric, errors='coerce').values
736
 
737
+ # QC - remove high missing
738
+ marker_missing_rate = np.isnan(genotypes).sum(axis=0) / len(phenotypes)
739
+ keep_markers = marker_missing_rate < marker_missing
740
+ genotypes = genotypes[:, keep_markers]
741
+ chromosomes = [chromosomes[i] for i in range(len(chromosomes)) if keep_markers[i]]
742
+ positions = [positions[i] for i in range(len(positions)) if keep_markers[i]]
743
+
744
+ # Remove samples with high missing
745
+ sample_missing_rate = np.isnan(genotypes).sum(axis=1) / genotypes.shape[1]
746
+ keep_samples = sample_missing_rate < sample_missing
747
+ genotypes = genotypes[keep_samples]
748
+ phenotypes = phenotypes[keep_samples]
749
+ sample_ids = sample_ids[keep_samples]
750
+
751
+ # Simple MAF filter
752
+ maf = np.abs(np.nanmean(genotypes, axis=0) / 2 - 0.5) * 2
753
+ keep_maf = maf >= maf_thresh
754
+ genotypes = genotypes[:, keep_maf]
755
+ chromosomes = [chromosomes[i] for i in range(len(chromosomes)) if keep_maf[i]]
756
+ positions = [positions[i] for i in range(len(positions)) if keep_maf[i]]
757
+
758
+ # Impute
759
+ col_means = np.nanmean(genotypes, axis=0)
760
+ inds = np.where(np.isnan(genotypes))
761
+ genotypes[inds] = np.take(col_means, inds[1])
 
 
 
 
 
 
 
 
 
762
 
763
  # Remove NaN phenotypes
764
+ valid = ~np.isnan(phenotypes)
765
+ genotypes = genotypes[valid]
766
+ phenotypes = phenotypes[valid]
767
+ sample_ids = sample_ids[valid]
 
 
 
 
 
 
 
 
 
 
 
 
 
768
 
769
+ return genotypes, phenotypes, sample_ids, chromosomes, positions
 
 
 
 
 
 
 
770
 
771
  # ══════════════════════════════════════════════════════════════
772
+ # MAIN PIPELINE
773
  # ══════════════════════════════════════════════════════════════
774
 
775
+ def run_multi_locus_gwas(input_file, sample_missing, marker_missing, maf_threshold,
776
+ use_single_locus, use_multi_locus, use_bayesian, use_ml, use_information):
777
+ """Run comprehensive multi-locus GWAS"""
778
 
779
  if input_file is None:
780
+ return "Please upload a CSV file", None, None, None, None
781
 
782
  try:
783
  temp_dir = tempfile.mkdtemp()
 
786
  os.makedirs(plots_dir, exist_ok=True)
787
 
788
  # Parse data
789
+ genotypes, phenotypes, sample_ids, chromosomes, positions = parse_and_qc(
790
+ input_file.name, sample_missing/100, marker_missing/100, maf_threshold/100
791
+ )
792
 
793
+ n_samples, n_markers = genotypes.shape
794
+ bonf_threshold = 0.05 / n_markers
795
 
796
+ # Results storage
797
+ all_results = {}
798
+ model_summary = {}
 
 
799
 
800
+ # SINGLE LOCUS MODELS
801
+ if use_single_locus:
802
+ print("Running Single Locus Models...")
803
+
804
+ # Simple Linear Regression
805
+ pvals, effects, lod = single_locus_regression(genotypes, phenotypes)
806
+ all_results['Linear Regression'] = {'pvals': pvals, 'lod': lod, 'effects': effects}
807
+ model_summary['Linear Regression'] = {
808
+ 'n_significant': int((pvals < bonf_threshold).sum()),
809
+ 'mean_lod': float(lod.mean()),
810
+ 'max_lod': float(lod.max())
811
+ }
812
+
813
+ # Multiple Linear Regression
814
+ pvals, effects, lod = multiple_locus_regression(genotypes, phenotypes)
815
+ all_results['Multiple Regression'] = {'pvals': pvals, 'lod': lod, 'effects': effects}
816
+ model_summary['Multiple Regression'] = {
817
+ 'n_significant': int((pvals < bonf_threshold).sum()),
818
+ 'mean_lod': float(lod.mean()),
819
+ 'max_lod': float(lod.max())
820
+ }
821
+
822
+ # EMMAX
823
+ pvals, effects, lod = emmax_model(genotypes, phenotypes)
824
+ all_results['EMMAX'] = {'pvals': pvals, 'lod': lod, 'effects': effects}
825
+ model_summary['EMMAX'] = {
826
+ 'n_significant': int((pvals < bonf_threshold).sum()),
827
+ 'mean_lod': float(lod.mean()),
828
+ 'max_lod': float(lod.max())
829
+ }
830
 
831
+ # MULTI-LOCUS MODELS
832
+ if use_multi_locus:
833
+ print("Running Multi-Locus Models...")
834
+
835
+ # LASSO
836
+ pvals, effects, lod, n_selected = lasso_model(genotypes, phenotypes)
837
+ all_results['LASSO'] = {'pvals': pvals, 'lod': lod, 'effects': effects}
838
+ model_summary['LASSO'] = {
839
+ 'n_significant': int((pvals < bonf_threshold).sum()),
840
+ 'mean_lod': float(lod.mean()),
841
+ 'max_lod': float(lod.max()),
842
+ 'selected': int(n_selected)
843
+ }
844
+
845
+ # Adaptive LASSO
846
+ pvals, effects, lod, n_selected = adaptive_lasso(genotypes, phenotypes)
847
+ all_results['Adaptive LASSO'] = {'pvals': pvals, 'lod': lod, 'effects': effects}
848
+ model_summary['Adaptive LASSO'] = {
849
+ 'n_significant': int((pvals < bonf_threshold).sum()),
850
+ 'mean_lod': float(lod.mean()),
851
+ 'max_lod': float(lod.max()),
852
+ 'selected': int(n_selected)
853
+ }
854
+
855
+ # ElasticNet
856
+ enet = ElasticNetCV(cv=3, random_state=42, max_iter=1000)
857
+ scaler = StandardScaler()
858
+ X_scaled = scaler.fit_transform(genotypes)
859
+ enet.fit(X_scaled, phenotypes)
860
+ pvals = np.exp(-np.abs(enet.coef_) / (np.abs(enet.coef_).max() + 1e-10) * 3)
861
+ lod = -np.log10(pvals + 1e-300)
862
+ all_results['ElasticNet'] = {'pvals': pvals, 'lod': lod, 'effects': enet.coef_}
863
+ model_summary['ElasticNet'] = {
864
+ 'n_significant': int((pvals < bonf_threshold).sum()),
865
+ 'mean_lod': float(lod.mean()),
866
+ 'max_lod': float(lod.max())
867
+ }
868
+
869
+ # SCAD
870
+ pvals, effects, lod, n_selected = scad_model(genotypes, phenotypes)
871
+ all_results['SCAD'] = {'pvals': pvals, 'lod': lod, 'effects': effects}
872
+ model_summary['SCAD'] = {
873
+ 'n_significant': int((pvals < bonf_threshold).sum()),
874
+ 'mean_lod': float(lod.mean()),
875
+ 'max_lod': float(lod.max()),
876
+ 'selected': int(n_selected)
877
+ }
878
+
879
+ # MCP
880
+ pvals, effects, lod, n_selected = mcp_model(genotypes, phenotypes)
881
+ all_results['MCP'] = {'pvals': pvals, 'lod': lod, 'effects': effects}
882
+ model_summary['MCP'] = {
883
+ 'n_significant': int((pvals < bonf_threshold).sum()),
884
+ 'mean_lod': float(lod.mean()),
885
+ 'max_lod': float(lod.max()),
886
+ 'selected': int(n_selected)
887
+ }
888
 
889
+ # BAYESIAN MODELS
890
+ if use_bayesian:
891
+ print("Running Bayesian Models...")
892
+
893
+ # Bayesian Ridge
894
+ pvals, effects, lod = bayesian_ridge(genotypes, phenotypes)
895
+ all_results['Bayesian Ridge'] = {'pvals': pvals, 'lod': lod, 'effects': effects}
896
+ model_summary['Bayesian Ridge'] = {
897
+ 'n_significant': int((pvals < bonf_threshold).sum()),
898
+ 'mean_lod': float(lod.mean()),
899
+ 'max_lod': float(lod.max())
900
+ }
901
+
902
+ # Bayesian LASSO
903
+ pvals, effects, lod = bayesian_lasso(genotypes, phenotypes)
904
+ all_results['Bayesian LASSO'] = {'pvals': pvals, 'lod': lod, 'effects': effects}
905
+ model_summary['Bayesian LASSO'] = {
906
+ 'n_significant': int((pvals < bonf_threshold).sum()),
907
+ 'mean_lod': float(lod.mean()),
908
+ 'max_lod': float(lod.max())
909
+ }
910
+
911
+ # BayesA
912
+ pvals, effects, lod = bayes_a(genotypes, phenotypes)
913
+ all_results['BayesA'] = {'pvals': pvals, 'lod': lod, 'effects': effects}
914
+ model_summary['BayesA'] = {
915
+ 'n_significant': int((pvals < bonf_threshold).sum()),
916
+ 'mean_lod': float(lod.mean()),
917
+ 'max_lod': float(lod.max())
918
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
919
 
920
+ # MACHINE LEARNING MODELS
921
+ if use_ml:
922
+ print("Running Machine Learning Models...")
923
+
924
+ # Random Forest
925
+ pvals, importance, lod, score = random_forest_gwas(genotypes, phenotypes)
926
+ all_results['Random Forest'] = {'pvals': pvals, 'lod': lod, 'effects': importance}
927
+ model_summary['Random Forest'] = {
928
+ 'n_significant': int((pvals < bonf_threshold).sum()),
929
+ 'mean_lod': float(lod.mean()),
930
+ 'max_lod': float(lod.max()),
931
+ 'score': float(score)
932
+ }
933
+
934
+ # Gradient Boosting
935
+ pvals, importance, lod, score = gradient_boosting_gwas(genotypes, phenotypes)
936
+ all_results['Gradient Boosting'] = {'pvals': pvals, 'lod': lod, 'effects': importance}
937
+ model_summary['Gradient Boosting'] = {
938
+ 'n_significant': int((pvals < bonf_threshold).sum()),
939
+ 'mean_lod': float(lod.mean()),
940
+ 'max_lod': float(lod.max()),
941
+ 'score': float(score)
942
+ }
943
+
944
+ # SVR
945
+ pvals, importance, lod, score = svr_gwas(genotypes, phenotypes)
946
+ all_results['SVR'] = {'pvals': pvals, 'lod': lod, 'effects': importance}
947
+ model_summary['SVR'] = {
948
+ 'n_significant': int((pvals < bonf_threshold).sum()),
949
+ 'mean_lod': float(lod.mean()),
950
+ 'max_lod': float(lod.max()),
951
+ 'score': float(score)
952
+ }
953
+
954
+ # XGBoost
955
+ pvals, importance, lod, score = xgboost_gwas(genotypes, phenotypes)
956
+ all_results['XGBoost'] = {'pvals': pvals, 'lod': lod, 'effects': importance}
957
+ model_summary['XGBoost'] = {
958
+ 'n_significant': int((pvals < bonf_threshold).sum()),
959
+ 'mean_lod': float(lod.mean()),
960
+ 'max_lod': float(lod.max()),
961
+ 'score': float(score)
962
+ }
963
 
964
+ # INFORMATION CRITERIA MODELS
965
+ if use_information:
966
+ print("Running Information Criteria Models...")
967
+
968
+ # Stepwise AIC
969
+ pvals, selected, lod, n_selected = stepwise_aic(genotypes, phenotypes)
970
+ all_results['Stepwise AIC'] = {'pvals': pvals, 'lod': lod, 'effects': selected}
971
+ model_summary['Stepwise AIC'] = {
972
+ 'n_significant': int((pvals < bonf_threshold).sum()),
973
+ 'mean_lod': float(lod.mean()),
974
+ 'max_lod': float(lod.max()),
975
+ 'selected': int(n_selected)
976
+ }
977
+
978
+ # GEMMA-like
979
+ pvals, effects, lod = gemma_like(genotypes, phenotypes)
980
+ all_results['GEMMA-like'] = {'pvals': pvals, 'lod': lod, 'effects': effects}
981
+ model_summary['GEMMA-like'] = {
982
+ 'n_significant': int((pvals < bonf_threshold).sum()),
983
+ 'mean_lod': float(lod.mean()),
984
+ 'max_lod': float(lod.max())
985
+ }
986
 
987
+ # Create results DataFrame
988
+ results_df = pd.DataFrame({
989
+ 'Marker': [f'M{i+1}' for i in range(n_markers)],
990
+ 'Chromosome': chromosomes,
991
+ 'Position': positions
992
+ })
993
 
994
+ for model_name, results in all_results.items():
995
+ results_df[f'{model_name}_P'] = results['pvals']
996
+ results_df[f'{model_name}_LOD'] = results['lod']
997
 
998
+ # Save results
999
+ results_df.to_csv(os.path.join(results_dir, 'all_models_results.csv'), index=False)
1000
+
1001
+ # Generate plots
1002
+ manhattan_path = os.path.join(plots_dir, 'manhattan_comparison.png')
1003
+ plot_manhattan_comparison(all_results, np.array(chromosomes), bonf_threshold, manhattan_path)
1004
 
1005
+ comparison_path = os.path.join(plots_dir, 'model_comparison.png')
1006
+ plot_model_comparison_bar(model_summary, comparison_path)
1007
 
1008
  # Create ZIP
1009
+ zip_path = os.path.join(temp_dir, 'Multi_Locus_GWAS_Results.zip')
1010
  with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf:
1011
  for root, _, files in os.walk(results_dir):
1012
  for f in files:
1013
  zf.write(os.path.join(root, f), os.path.relpath(os.path.join(root, f), temp_dir))
1014
 
1015
+ # Generate summary table
1016
+ summary_df = pd.DataFrame(model_summary).T
1017
+ summary_md = summary_df.to_markdown()
1018
+
1019
  summary = f"""
1020
+ ## βœ… Multi-Locus GWAS Analysis Complete!
1021
 
1022
+ ### Dataset Summary
1023
+ - **Samples:** {n_samples}
1024
+ - **Markers:** {n_markers}
1025
+ - **Bonferroni threshold:** {bonf_threshold:.2e}
 
1026
 
1027
+ ### Model Results Summary
1028
+ {summary_md}
1029
+
1030
+ ### Top Performing Models
1031
+ - **Most significant markers:** {max(model_summary.items(), key=lambda x: x[1]['n_significant'])[0]}
1032
+ - **Highest mean LOD:** {max(model_summary.items(), key=lambda x: x[1]['mean_lod'])[0]}
1033
+ - **Highest max LOD:** {max(model_summary.items(), key=lambda x: x[1]['max_lod'])[0]}
1034
+
1035
+ ### πŸ“ Output Files
1036
+ - `all_models_results.csv` - Complete results for all models
1037
+ - `plots/manhattan_comparison.png` - Manhattan plots for all models
1038
+ - `plots/model_comparison.png` - Model performance comparison
1039
  """
1040
 
1041
+ return (summary, manhattan_path, comparison_path, zip_path,
1042
+ results_df.head(20).to_dict())
1043
 
1044
  except Exception as e:
1045
+ import traceback
1046
+ return (f"❌ Error: {str(e)}\n\n{traceback.format_exc()}", None, None, None, None)
1047
 
1048
  # ══════════════════════════════════════════════════════════════
1049
  # GRADIO INTERFACE
1050
  # ══════════════════════════════════════════════════════════════
1051
 
1052
+ with gr.Blocks(css=CSS, title="Multi-Locus GWAS", theme=gr.themes.Soft()) as app:
1053
 
1054
  gr.HTML("""
1055
  <div class="main-header">
1056
+ <h1>🧬 Multi-Locus GWAS Analysis Platform</h1>
1057
+ <p>15+ Statistical Models | Single Locus | Multi-Locus | Bayesian | Machine Learning</p>
1058
  </div>
1059
  """)
1060
 
1061
  with gr.Row():
1062
  with gr.Column(scale=1):
1063
+ gr.HTML('<div class="section-header">πŸ“‚ Data Input</div>')
1064
  input_file = gr.File(label="CSV File", file_types=[".csv"])
1065
 
1066
+ gr.HTML('<div class="section-header">βš™οΈ Quality Control</div>')
1067
  sample_missing = gr.Slider(10, 80, value=50, step=10, label="Sample Missing (%)")
1068
  marker_missing = gr.Slider(10, 80, value=50, step=10, label="Marker Missing (%)")
1069
+ maf_threshold = gr.Slider(1, 20, value=5, step=5, label="MAF Threshold (%)")
1070
 
1071
+ gr.HTML('<div class="section-header">🎯 Model Selection</div>')
1072
+ with gr.Row():
1073
+ use_single_locus = gr.Checkbox(label="Single Locus (LR, MLR, EMMAX)", value=True)
1074
+ use_multi_locus = gr.Checkbox(label="Multi-Locus (LASSO, SCAD, MCP)", value=True)
1075
+ with gr.Row():
1076
+ use_bayesian = gr.Checkbox(label="Bayesian (Ridge, LASSO, BayesA)", value=False)
1077
+ use_ml = gr.Checkbox(label="Machine Learning (RF, GBM, SVR, XGB)", value=False)
1078
+ with gr.Row():
1079
+ use_information = gr.Checkbox(label="Information Criteria (AIC, GEMMA)", value=False)
1080
 
1081
+ run_btn = gr.Button("πŸš€ Run Multi-Locus GWAS", variant="primary")
1082
 
1083
  with gr.Column(scale=2):
1084
  gr.HTML('<div class="section-header">πŸ“Š Results</div>')
1085
+ summary_out = gr.Markdown("Ready to analyze")
1086
 
1087
  with gr.Row():
1088
+ manhattan_out = gr.Image(label="Manhattan Plots (All Models)")
1089
+ comparison_out = gr.Image(label="Model Comparison")
 
 
 
 
 
1090
 
1091
+ download_out = gr.File(label="Download Results ZIP")
1092
+ preview_out = gr.Dataframe(label="Top Results Preview")
1093
 
1094
  run_btn.click(
1095
+ fn=run_multi_locus_gwas,
1096
  inputs=[input_file, sample_missing, marker_missing, maf_threshold,
1097
+ use_single_locus, use_multi_locus, use_bayesian, use_ml, use_information],
1098
+ outputs=[summary_out, manhattan_out, comparison_out, download_out, preview_out]
1099
  )
1100
 
1101
  gr.HTML("""
1102
+ <footer>
1103
+ <p>Multi-Locus GWAS v12.0 | 15+ Statistical Models | Times New Roman | Soft Pastel Theme</p>
1104
+ <p><strong>Models Included:</strong> Linear Regression, Multiple Regression, EMMAX, LASSO, Adaptive LASSO, ElasticNet, SCAD, MCP, Bayesian Ridge, Bayesian LASSO, BayesA, Random Forest, Gradient Boosting, SVR, XGBoost, Stepwise AIC, GEMMA-like</p>
1105
  </footer>
1106
  """)
1107