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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +367 -729
app.py CHANGED
@@ -1,39 +1,11 @@
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
@@ -42,27 +14,18 @@ import numpy as np
42
  import matplotlib
43
  matplotlib.use('Agg')
44
  import matplotlib.pyplot as plt
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
@@ -75,23 +38,15 @@ plt.rcParams['font.size'] = 10
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
@@ -101,14 +56,12 @@ 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
 
@@ -117,16 +70,17 @@ CSS = """
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
@@ -140,591 +94,374 @@ def single_locus_regression(genotypes, phenotypes):
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):
423
- pvals[idx] = (i + 1) / len(importance)
424
 
425
  lod = -np.log10(pvals + 1e-300)
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:
719
- chrom, pos = val.split(':')[:2]
720
- chromosomes.append(chrom)
721
- try:
722
- positions.append(float(pos))
723
- except:
724
- positions.append(0)
725
  else:
726
  chromosomes.append(val)
727
- positions.append(0)
728
 
729
  # Sample data
730
  sample_data = df.iloc[1:].reset_index(drop=True)
@@ -734,50 +471,30 @@ def parse_and_qc(filepath, sample_missing=0.5, marker_missing=0.5, maf_thresh=0.
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()
@@ -785,8 +502,8 @@ def run_multi_locus_gwas(input_file, sample_missing, marker_missing, maf_thresho
785
  plots_dir = os.path.join(results_dir, 'plots')
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
 
@@ -797,198 +514,101 @@ def run_multi_locus_gwas(input_file, sample_missing, marker_missing, maf_thresho
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():
@@ -996,50 +616,61 @@ def run_multi_locus_gwas(input_file, sample_missing, marker_missing, maf_thresho
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
@@ -1049,12 +680,12 @@ def run_multi_locus_gwas(input_file, sample_missing, marker_missing, maf_thresho
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
 
@@ -1066,42 +697,49 @@ with gr.Blocks(css=CSS, title="Multi-Locus GWAS", theme=gr.themes.Soft()) as app
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
 
 
1
  # -*- coding: utf-8 -*-
2
  """
3
+ GWAS Pipeline v13.0 - Fixed Multi-Locus Statistical Models
4
+ Fixed Issues:
5
+ - Matrix dimension mismatches
6
+ - Memory optimization
7
+ - Error handling for all models
8
+ - Proper array shapes
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
  """
10
 
11
  import gradio as gr
 
14
  import matplotlib
15
  matplotlib.use('Agg')
16
  import matplotlib.pyplot as plt
 
 
17
  from scipy import stats
18
+ from scipy.optimize import minimize
 
19
  import os, warnings, tempfile, zipfile
20
  from sklearn.linear_model import (LinearRegression, Ridge, Lasso, ElasticNet,
21
+ LassoCV, RidgeCV, ElasticNetCV, BayesianRidge)
 
22
  from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor
23
  from sklearn.svm import SVR
24
  from sklearn.preprocessing import StandardScaler
25
  from sklearn.impute import SimpleImputer
26
  from sklearn.decomposition import PCA
27
+ from sklearn.model_selection import cross_val_score
 
28
  import statsmodels.api as sm
 
 
 
 
29
  warnings.filterwarnings('ignore')
30
 
31
  # Set Times New Roman
 
38
 
39
  BG_PASTEL = "#FDF8F0"
40
  PANEL_PASTEL = "#F5F0E8"
 
41
  TEXT_PASTEL = "#4A4A4A"
 
 
 
42
  MODEL_COLORS = {
43
+ 'Single_Locus': '#C5A3FF',
44
+ 'Multi_Locus': '#A8E6CF',
45
+ 'Bayesian': '#FFD3B6',
46
+ 'ML': '#FFB3BA',
47
+ 'Significant': '#E8A598'
 
 
48
  }
49
+ CHROM_COLORS = ["#E8D5F5", "#D4F1F9", "#FDE2C4", "#E2F0CB", "#FFD9E8"]
 
 
50
 
51
  # ══════════════════════════════════════════════════════════════
52
  # CSS STYLING
 
56
  <style>
57
  * { font-family: 'Times New Roman', Times, serif !important; }
58
  .gradio-container { background: linear-gradient(135deg, #FDF8F0 0%, #F5F0E8 100%) !important; padding: 15px !important; }
59
+ .main-header { background: linear-gradient(135deg, #E8D5F5 0%, #D4F1F9 100%); padding: 25px; border-radius: 20px; text-align: center; margin-bottom: 20px; }
60
+ .main-header h1 { color: #4A4A4A; font-size: 2em; margin: 0; }
61
+ .section-header { background: linear-gradient(135deg, #C5A3FF 0%, #B8D4E3 100%); padding: 8px 15px; border-radius: 12px; margin: 15px 0 10px 0; font-weight: 600; }
62
+ .card { background: #FFFEF8; border-radius: 12px; padding: 15px; margin: 8px 0; border: 1px solid #E8DCC8; }
63
+ .run-btn { background: linear-gradient(135deg, #C5A3FF 0%, #A8E6CF 100%); border: none; padding: 10px 25px; border-radius: 20px; font-weight: 600; cursor: pointer; }
64
+ footer { text-align: center; padding: 15px; margin-top: 20px; background: #FFFEF8; border-radius: 10px; }
 
 
65
  </style>
66
  """
67
 
 
70
  # ══════════════════════════════════════════════════════════════
71
 
72
  def single_locus_regression(genotypes, phenotypes):
73
+ """Simple Linear Regression - Vectorized"""
74
  n_markers = genotypes.shape[1]
75
  pvals = np.ones(n_markers)
76
  effects = np.zeros(n_markers)
77
  lod = np.zeros(n_markers)
78
 
79
+ # Center data
80
  X_centered = genotypes - genotypes.mean(axis=0)
81
  y_centered = phenotypes - phenotypes.mean()
82
 
83
+ # Vectorized computation
84
  xy = np.dot(y_centered, X_centered)
85
  xx = np.sum(X_centered ** 2, axis=0)
86
  valid = xx > 1e-10
 
94
  resid = y_centered - y_pred
95
  rss = np.sum(resid ** 2)
96
  tss = np.sum(y_centered ** 2)
97
+ if rss > 0 and tss > 0:
98
+ t_stat = effects[i] / (np.sqrt(rss / (n - 2)) / np.sqrt(xx[i]) + 1e-10)
99
+ pvals[i] = 2 * (1 - stats.t.cdf(abs(t_stat), n - 2))
100
+ lod[i] = -np.log10(pvals[i] + 1e-300)
101
 
102
  return pvals, effects, lod
103
 
104
+ def multiple_locus_regression(genotypes, phenotypes, n_pcs=3):
105
  """Multiple Linear Regression with PCA"""
106
+ n_markers = genotypes.shape[1]
107
+ n_pcs = min(n_pcs, genotypes.shape[0] - 1, genotypes.shape[1])
108
+
109
+ # PCA for covariates
110
+ pca = PCA(n_components=n_pcs)
111
  pcs = pca.fit_transform(genotypes)
112
 
 
113
  pvals = np.ones(n_markers)
114
  effects = np.zeros(n_markers)
115
  lod = np.zeros(n_markers)
116
 
117
+ for i in range(min(n_markers, 1000)): # Limit for speed
118
  X = np.column_stack([pcs, genotypes[:, i]])
119
  X = sm.add_constant(X)
120
  try:
121
  model = sm.OLS(phenotypes, X).fit()
122
+ if len(model.pvalues) > 1:
123
+ pvals[i] = model.pvalues[-1]
124
+ effects[i] = model.params[-1]
125
+ lod[i] = -np.log10(pvals[i] + 1e-300)
126
  except:
127
  pass
128
 
129
  return pvals, effects, lod
130
 
131
+ def emmax_model(genotypes, phenotypes):
132
+ """EMMAX - Fixed dimension issues"""
133
  n_markers = genotypes.shape[1]
134
+ n_samples = genotypes.shape[0]
 
 
135
 
136
+ # Limit markers for speed
137
+ max_markers = min(n_markers, 500)
 
 
138
 
139
+ pvals = np.ones(max_markers)
140
+ effects = np.zeros(max_markers)
141
+ lod = np.zeros(max_markers)
142
 
143
+ # Calculate kinship using subset
144
+ n_kinship_markers = min(300, n_markers)
145
+ kinship_idx = np.random.choice(n_markers, n_kinship_markers, replace=False)
146
+ genotypes_subset = genotypes[:, kinship_idx]
147
+
148
+ # Center genotypes
149
+ genotypes_centered = genotypes_subset - genotypes_subset.mean(axis=0)
150
+
151
+ # Calculate kinship matrix
152
+ kinship = np.dot(genotypes_centered, genotypes_centered.T) / n_kinship_markers
153
+
154
+ # Add small diagonal to ensure positive definite
155
+ kinship = kinship + np.eye(n_samples) * 0.01
156
+
157
+ # Eigen decomposition
158
+ try:
159
+ eigenvals, eigenvecs = np.linalg.eigh(kinship)
160
+ eigenvals = np.maximum(eigenvals, 1e-6)
161
+ except:
162
+ # Fallback: use identity matrix
163
+ eigenvals = np.ones(n_samples)
164
+ eigenvecs = np.eye(n_samples)
165
+
166
+ # Center phenotypes
167
+ y = phenotypes - phenotypes.mean()
168
+
169
+ # Test markers
170
+ for i in range(max_markers):
171
  try:
172
+ X = genotypes[:, i].reshape(-1, 1)
173
+ X = np.column_stack([np.ones(n_samples), X])
174
+
175
+ # Transform data
176
+ yt = eigenvecs.T @ y
177
+ Xt = eigenvecs.T @ X
178
+
179
+ # Fit model
180
  model = sm.OLS(yt, Xt).fit()
181
+ if len(model.pvalues) > 1:
182
+ pvals[i] = model.pvalues[1]
183
+ effects[i] = model.params[1]
184
+ lod[i] = -np.log10(pvals[i] + 1e-300)
185
  except:
186
  pass
187
 
188
+ # Pad to original length if needed
189
+ if n_markers > max_markers:
190
+ full_pvals = np.ones(n_markers)
191
+ full_pvals[:max_markers] = pvals
192
+ full_effects = np.zeros(n_markers)
193
+ full_effects[:max_markers] = effects
194
+ full_lod = np.zeros(n_markers)
195
+ full_lod[:max_markers] = lod
196
+ return full_pvals, full_effects, full_lod
197
+
198
  return pvals, effects, lod
199
 
200
  # ══════════════════════════════════════════════════════════════
201
  # MULTI-LOCUS MODELS
202
  # ══════════════════════════════════════════════════════════════
203
 
204
+ def lasso_model(genotypes, phenotypes):
205
+ """LASSO - Least Absolute Shrinkage"""
206
  scaler = StandardScaler()
207
  X_scaled = scaler.fit_transform(genotypes)
208
 
209
+ lasso = LassoCV(cv=3, random_state=42, max_iter=1000)
210
  lasso.fit(X_scaled, phenotypes)
211
 
212
  coefficients = lasso.coef_
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
213
 
214
+ # Simple p-value approximation
215
+ coef_norm = np.abs(coefficients) / (np.abs(coefficients).max() + 1e-10)
216
+ pvals = np.exp(-coef_norm * 5)
217
  lod = -np.log10(pvals + 1e-300)
218
 
219
+ return pvals, coefficients, lod
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
220
 
221
+ def elasticnet_model(genotypes, phenotypes):
222
+ """ElasticNet regression"""
223
  scaler = StandardScaler()
224
  X_scaled = scaler.fit_transform(genotypes)
225
 
226
+ enet = ElasticNetCV(cv=3, random_state=42, max_iter=1000)
227
+ enet.fit(X_scaled, phenotypes)
 
 
228
 
229
+ coefficients = enet.coef_
230
+ coef_norm = np.abs(coefficients) / (np.abs(coefficients).max() + 1e-10)
231
+ pvals = np.exp(-coef_norm * 5)
 
 
 
 
 
 
 
 
 
 
 
232
  lod = -np.log10(pvals + 1e-300)
 
233
 
234
+ return pvals, coefficients, lod, enet.score(X_scaled, phenotypes)
235
 
236
+ def ridge_model(genotypes, phenotypes):
237
+ """Ridge regression"""
238
  scaler = StandardScaler()
239
  X_scaled = scaler.fit_transform(genotypes)
 
 
 
240
 
241
+ ridge = RidgeCV(cv=3)
242
+ ridge.fit(X_scaled, phenotypes)
 
 
 
 
243
 
244
+ coefficients = ridge.coef_
245
+ coef_norm = np.abs(coefficients) / (np.abs(coefficients).max() + 1e-10)
246
+ pvals = np.exp(-coef_norm * 3)
 
 
 
 
 
 
 
 
 
 
247
  lod = -np.log10(pvals + 1e-300)
 
248
 
249
+ return pvals, coefficients, lod, ridge.score(X_scaled, phenotypes)
250
 
251
  # ══════════════════════════════════════════════════════════════
252
  # BAYESIAN MODELS
253
  # ══════════════════════════════════════════════════════════════
254
 
255
+ def bayesian_ridge_model(genotypes, phenotypes):
256
  """Bayesian Ridge Regression"""
257
  scaler = StandardScaler()
258
  X_scaled = scaler.fit_transform(genotypes)
259
 
260
+ # Limit features for speed
261
+ max_features = min(X_scaled.shape[1], 1000)
262
+ if X_scaled.shape[1] > max_features:
263
+ idx = np.random.choice(X_scaled.shape[1], max_features, replace=False)
264
+ X_scaled = X_scaled[:, idx]
265
+ else:
266
+ idx = np.arange(X_scaled.shape[1])
 
 
 
 
 
 
 
 
 
267
 
268
+ bayesian_ridge = BayesianRidge(n_iter=100, alpha_1=1e-6, lambda_1=1e-6)
269
+ bayesian_ridge.fit(X_scaled, phenotypes)
 
270
 
271
+ # Create full coefficients array
272
+ full_coefficients = np.zeros(genotypes.shape[1])
273
+ full_coefficients[idx] = bayesian_ridge.coef_
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
274
 
275
+ coef_norm = np.abs(full_coefficients) / (np.abs(full_coefficients).max() + 1e-10)
276
+ pvals = np.exp(-coef_norm * 4)
277
  lod = -np.log10(pvals + 1e-300)
278
 
279
+ return pvals, full_coefficients, lod
280
 
281
  # ══════════════════════════════════════════════════════════════
282
  # MACHINE LEARNING MODELS
283
  # ══════════════════════════════════════════════════════════════
284
 
285
+ def random_forest_model(genotypes, phenotypes):
286
  """Random Forest for feature selection"""
287
  scaler = StandardScaler()
288
  X_scaled = scaler.fit_transform(genotypes)
289
 
290
+ # Limit features for speed
291
+ max_features = min(X_scaled.shape[1], 500)
292
+ if X_scaled.shape[1] > max_features:
293
+ idx = np.random.choice(X_scaled.shape[1], max_features, replace=False)
294
+ X_scaled = X_scaled[:, idx]
295
+ else:
296
+ idx = np.arange(X_scaled.shape[1])
297
+
298
+ rf = RandomForestRegressor(n_estimators=50, random_state=42, n_jobs=-1, max_depth=10)
299
  rf.fit(X_scaled, phenotypes)
300
 
301
+ # Create full importance array
302
+ full_importance = np.zeros(genotypes.shape[1])
303
+ full_importance[idx] = rf.feature_importances_
304
 
305
+ # Calculate p-values from importance ranking
306
+ imp_rank = np.argsort(full_importance)[::-1]
307
+ pvals = np.ones(len(full_importance))
308
+ for i, pos in enumerate(imp_rank):
309
+ pvals[pos] = (i + 1) / len(full_importance)
310
 
311
  lod = -np.log10(pvals + 1e-300)
312
 
313
+ return pvals, full_importance, lod, rf.score(X_scaled, phenotypes)
314
 
315
+ def gradient_boosting_model(genotypes, phenotypes):
316
  """Gradient Boosting Machine"""
317
  scaler = StandardScaler()
318
  X_scaled = scaler.fit_transform(genotypes)
319
 
320
+ # Limit features for speed
321
+ max_features = min(X_scaled.shape[1], 500)
322
+ if X_scaled.shape[1] > max_features:
323
+ idx = np.random.choice(X_scaled.shape[1], max_features, replace=False)
324
+ X_scaled = X_scaled[:, idx]
325
+ else:
326
+ idx = np.arange(X_scaled.shape[1])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
327
 
328
+ gbm = GradientBoostingRegressor(n_estimators=50, learning_rate=0.1, max_depth=5, random_state=42)
329
+ gbm.fit(X_scaled, phenotypes)
330
 
331
+ # Create full importance array
332
+ full_importance = np.zeros(genotypes.shape[1])
333
+ full_importance[idx] = gbm.feature_importances_
334
 
335
+ imp_rank = np.argsort(full_importance)[::-1]
336
+ pvals = np.ones(len(full_importance))
337
+ for i, pos in enumerate(imp_rank):
338
+ pvals[pos] = (i + 1) / len(full_importance)
 
339
 
 
340
  lod = -np.log10(pvals + 1e-300)
341
 
342
+ return pvals, full_importance, lod, gbm.score(X_scaled, phenotypes)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
343
 
344
  # ══════════════════════════════════════════════════════════════
345
  # PLOTTING FUNCTIONS
346
  # ══════════════════════════════════════════════════════════════
347
 
348
+ def plot_manhattan(p_values, lod_scores, chromosomes, bonf_threshold, save_path, title="GWAS Manhattan Plot"):
349
+ """Simple Manhattan plot"""
350
+ plt.figure(figsize=(14, 6), facecolor=BG_PASTEL)
351
+ ax = plt.gca()
352
+ ax.set_facecolor(PANEL_PASTEL)
353
+
354
+ log_p = -np.log10(p_values + 1e-300)
355
+ unique_chroms = np.unique(chromosomes)
356
+
357
+ # Position calculation
358
+ positions = np.arange(len(chromosomes))
359
+ offset = 0
360
+ chrom_centers = []
361
+
362
+ for i, ch in enumerate(unique_chroms):
363
+ mask = chromosomes == ch
364
+ n_markers = mask.sum()
365
+ positions[mask] = np.arange(n_markers) + offset
366
+ color = CHROM_COLORS[i % len(CHROM_COLORS)]
367
+ ax.scatter(positions[mask], log_p[mask], c=color, s=10, alpha=0.6)
368
+ chrom_centers.append(offset + n_markers/2)
369
+ offset += n_markers + 10
370
+
371
+ # Significant markers
372
+ sig_mask = p_values < bonf_threshold
373
+ if sig_mask.any():
374
+ ax.scatter(positions[sig_mask], log_p[sig_mask], c=MODEL_COLORS['Significant'],
375
+ s=40, edgecolors='white', marker='D', zorder=3)
376
+
377
+ # Threshold lines
378
+ ax.axhline(-np.log10(bonf_threshold), color=MODEL_COLORS['Significant'],
379
+ linestyle='--', linewidth=1.5, label='Bonferroni')
380
+ ax.axhline(3, color=MODEL_COLORS['Multi_Locus'], linestyle=':',
381
+ linewidth=1.5, label='LOD=3')
382
+
383
+ # Labels
384
+ ax.set_xlabel('Chromosome', fontsize=12)
385
+ ax.set_ylabel('-log₁₀(P-value)', fontsize=12)
386
+ ax.set_title(title, fontsize=14, fontweight='bold')
387
+ ax.set_xticks(chrom_centers)
388
+ ax.set_xticklabels(unique_chroms, rotation=45, ha='right', fontsize=9)
389
+ ax.legend(loc='upper right', fontsize=10)
390
+ ax.grid(True, alpha=0.3)
 
 
 
391
 
392
  plt.tight_layout()
393
+ plt.savefig(save_path, dpi=150, bbox_inches='tight', facecolor=BG_PASTEL)
394
  plt.close()
395
 
396
+ def plot_model_comparison(results_summary, save_path):
397
+ """Compare models"""
398
  fig, axes = plt.subplots(1, 2, figsize=(12, 5), facecolor=BG_PASTEL)
399
 
400
+ # Significant markers
401
  ax1 = axes[0]
402
  ax1.set_facecolor(PANEL_PASTEL)
403
  models = list(results_summary.keys())
404
+ n_sig = [results_summary[m].get('n_significant', 0) for m in models]
405
 
406
  bars = ax1.bar(range(len(models)), n_sig, color=list(MODEL_COLORS.values())[:len(models)], alpha=0.7)
407
  ax1.set_xticks(range(len(models)))
408
+ ax1.set_xticklabels(models, rotation=45, ha='right', fontsize=8)
409
+ ax1.set_ylabel('Significant Markers', fontsize=10)
410
  ax1.set_title('Significant Markers by Model', fontsize=11, fontweight='bold')
411
 
412
  for bar, val in zip(bars, n_sig):
413
+ ax1.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 0.5,
414
+ str(val), ha='center', fontsize=9)
415
 
416
+ # Mean LOD
417
  ax2 = axes[1]
418
  ax2.set_facecolor(PANEL_PASTEL)
419
+ mean_lod = [results_summary[m].get('mean_lod', 0) for m in models]
420
 
421
  bars = ax2.barh(range(len(models)), mean_lod, color=list(MODEL_COLORS.values())[:len(models)], alpha=0.7)
422
  ax2.set_yticks(range(len(models)))
423
+ ax2.set_yticklabels(models, fontsize=8)
424
  ax2.set_xlabel('Mean LOD Score', fontsize=10)
425
+ ax2.set_title('Mean LOD by Model', fontsize=11, fontweight='bold')
426
 
427
  for bar, val in zip(bars, mean_lod):
428
+ ax2.text(bar.get_width() + 0.1, bar.get_y() + bar.get_height()/2,
429
+ f'{val:.2f}', va='center', fontsize=9)
430
 
431
  plt.tight_layout()
432
+ plt.savefig(save_path, dpi=150, bbox_inches='tight', facecolor=BG_PASTEL)
433
  plt.close()
434
 
435
  # ══════════════════════════════════════════════════════════════
436
  # DATA PROCESSING
437
  # ══════════════════════════════════════════════════════════════
438
 
439
+ def process_data(filepath, sample_missing=0.5, marker_missing=0.5, maf_thresh=0.05):
440
+ """Process and QC data"""
441
  # Read data
442
  df = pd.read_csv(filepath, header=0)
443
 
444
  # Limit samples for speed
445
+ max_samples = min(300, len(df) - 1)
446
  df = df.iloc[:max_samples + 1]
447
 
448
  marker_cols = df.columns[2:].tolist()
449
+ n_markers_original = len(marker_cols)
450
+
451
+ # Limit markers for speed
452
+ max_markers = min(2000, n_markers_original)
453
+ if n_markers_original > max_markers:
454
+ marker_cols = marker_cols[:max_markers]
455
 
456
  # Parse chromosomes
457
  first_row = df.iloc[0]
458
  chromosomes = []
 
459
  for m in marker_cols:
460
  val = str(first_row[m]).strip()
461
  if ':' in val:
462
+ chromosomes.append(val.split(':')[0])
 
 
 
 
 
463
  else:
464
  chromosomes.append(val)
 
465
 
466
  # Sample data
467
  sample_data = df.iloc[1:].reset_index(drop=True)
 
471
  # Genotypes
472
  genotypes = sample_data[marker_cols].apply(pd.to_numeric, errors='coerce').values
473
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
474
  # Remove NaN phenotypes
475
  valid = ~np.isnan(phenotypes)
476
  genotypes = genotypes[valid]
477
  phenotypes = phenotypes[valid]
478
  sample_ids = sample_ids[valid]
479
 
480
+ # Simple imputation
481
+ col_means = np.nanmean(genotypes, axis=0)
482
+ inds = np.where(np.isnan(genotypes))
483
+ genotypes[inds] = np.take(col_means, inds[1])
484
+
485
+ return genotypes, phenotypes, sample_ids, chromosomes
486
 
487
  # ══════════════════════════════════════════════════════════════
488
  # MAIN PIPELINE
489
  # ══════════════════════════════════════════════════════════════
490
 
491
+ def run_gwas_pipeline(input_file, sample_missing, marker_missing, maf_threshold,
492
+ use_lr, use_mlr, use_emmax, use_lasso, use_enet,
493
+ use_ridge, use_bayes, use_rf, use_gbm):
494
+ """Main GWAS pipeline"""
495
 
496
  if input_file is None:
497
+ return "Please upload a CSV file", None, None, None
498
 
499
  try:
500
  temp_dir = tempfile.mkdtemp()
 
502
  plots_dir = os.path.join(results_dir, 'plots')
503
  os.makedirs(plots_dir, exist_ok=True)
504
 
505
+ # Process data
506
+ genotypes, phenotypes, sample_ids, chromosomes = process_data(
507
  input_file.name, sample_missing/100, marker_missing/100, maf_threshold/100
508
  )
509
 
 
514
  all_results = {}
515
  model_summary = {}
516
 
517
+ # Run selected models
518
+ if use_lr:
519
+ print("Running Linear Regression...")
 
 
520
  pvals, effects, lod = single_locus_regression(genotypes, phenotypes)
521
+ all_results['Linear Regression'] = {'pvals': pvals, 'lod': lod}
522
  model_summary['Linear Regression'] = {
523
  'n_significant': int((pvals < bonf_threshold).sum()),
524
+ 'mean_lod': float(np.mean(lod)),
525
+ 'max_lod': float(np.max(lod))
526
  }
527
+
528
+ if use_mlr:
529
+ print("Running Multiple Regression...")
530
  pvals, effects, lod = multiple_locus_regression(genotypes, phenotypes)
531
+ all_results['Multiple Regression'] = {'pvals': pvals, 'lod': lod}
532
  model_summary['Multiple Regression'] = {
533
  'n_significant': int((pvals < bonf_threshold).sum()),
534
+ 'mean_lod': float(np.mean(lod)),
535
+ 'max_lod': float(np.max(lod))
536
  }
537
+
538
+ if use_emmax:
539
+ print("Running EMMAX...")
540
  pvals, effects, lod = emmax_model(genotypes, phenotypes)
541
+ all_results['EMMAX'] = {'pvals': pvals, 'lod': lod}
542
  model_summary['EMMAX'] = {
543
  'n_significant': int((pvals < bonf_threshold).sum()),
544
+ 'mean_lod': float(np.mean(lod)),
545
+ 'max_lod': float(np.max(lod))
546
  }
547
 
548
+ if use_lasso:
549
+ print("Running LASSO...")
550
+ pvals, effects, lod = lasso_model(genotypes, phenotypes)
551
+ all_results['LASSO'] = {'pvals': pvals, 'lod': lod}
 
 
 
552
  model_summary['LASSO'] = {
553
  'n_significant': int((pvals < bonf_threshold).sum()),
554
+ 'mean_lod': float(np.mean(lod)),
555
+ 'max_lod': float(np.max(lod))
 
 
 
 
 
 
 
 
 
 
 
556
  }
557
+
558
+ if use_enet:
559
+ print("Running ElasticNet...")
560
+ pvals, effects, lod, score = elasticnet_model(genotypes, phenotypes)
561
+ all_results['ElasticNet'] = {'pvals': pvals, 'lod': lod}
 
 
 
 
562
  model_summary['ElasticNet'] = {
563
  'n_significant': int((pvals < bonf_threshold).sum()),
564
+ 'mean_lod': float(np.mean(lod)),
565
+ 'max_lod': float(np.max(lod))
 
 
 
 
 
 
 
 
 
 
566
  }
567
+
568
+ if use_ridge:
569
+ print("Running Ridge...")
570
+ pvals, effects, lod, score = ridge_model(genotypes, phenotypes)
571
+ all_results['Ridge'] = {'pvals': pvals, 'lod': lod}
572
+ model_summary['Ridge'] = {
573
  'n_significant': int((pvals < bonf_threshold).sum()),
574
+ 'mean_lod': float(np.mean(lod)),
575
+ 'max_lod': float(np.max(lod))
 
576
  }
577
 
578
+ if use_bayes:
579
+ print("Running Bayesian Ridge...")
580
+ pvals, effects, lod = bayesian_ridge_model(genotypes, phenotypes)
581
+ all_results['Bayesian Ridge'] = {'pvals': pvals, 'lod': lod}
 
 
 
582
  model_summary['Bayesian Ridge'] = {
583
  'n_significant': int((pvals < bonf_threshold).sum()),
584
+ 'mean_lod': float(np.mean(lod)),
585
+ 'max_lod': float(np.max(lod))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
586
  }
587
 
588
+ if use_rf:
589
+ print("Running Random Forest...")
590
+ pvals, importance, lod, score = random_forest_model(genotypes, phenotypes)
591
+ all_results['Random Forest'] = {'pvals': pvals, 'lod': lod}
 
 
 
592
  model_summary['Random Forest'] = {
593
  'n_significant': int((pvals < bonf_threshold).sum()),
594
+ 'mean_lod': float(np.mean(lod)),
595
+ 'max_lod': float(np.max(lod))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
596
  }
597
 
598
+ if use_gbm:
599
+ print("Running Gradient Boosting...")
600
+ pvals, importance, lod, score = gradient_boosting_model(genotypes, phenotypes)
601
+ all_results['Gradient Boosting'] = {'pvals': pvals, 'lod': lod}
602
+ model_summary['Gradient Boosting'] = {
 
 
 
 
 
 
 
 
 
 
 
 
 
603
  'n_significant': int((pvals < bonf_threshold).sum()),
604
+ 'mean_lod': float(np.mean(lod)),
605
+ 'max_lod': float(np.max(lod))
606
  }
607
 
608
  # Create results DataFrame
609
  results_df = pd.DataFrame({
610
  'Marker': [f'M{i+1}' for i in range(n_markers)],
611
+ 'Chromosome': chromosomes[:n_markers]
 
612
  })
613
 
614
  for model_name, results in all_results.items():
 
616
  results_df[f'{model_name}_LOD'] = results['lod']
617
 
618
  # Save results
619
+ results_df.to_csv(os.path.join(results_dir, 'gwas_results.csv'), index=False)
 
 
 
 
620
 
621
+ # Generate plots for each model
622
+ plot_paths = {}
623
+ for model_name, results in all_results.items():
624
+ if len(results['pvals']) > 0:
625
+ plot_path = os.path.join(plots_dir, f'{model_name.replace(" ", "_")}.png')
626
+ plot_manhattan(
627
+ results['pvals'], results['lod'],
628
+ np.array(chromosomes[:len(results['pvals'])]),
629
+ bonf_threshold, plot_path,
630
+ title=f"{model_name} - Manhattan Plot"
631
+ )
632
+ plot_paths[model_name] = plot_path
633
+
634
+ # Model comparison plot
635
  comparison_path = os.path.join(plots_dir, 'model_comparison.png')
636
+ plot_model_comparison(model_summary, comparison_path)
637
 
638
  # Create ZIP
639
+ zip_path = os.path.join(temp_dir, 'GWAS_Results.zip')
640
  with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf:
641
  for root, _, files in os.walk(results_dir):
642
  for f in files:
643
  zf.write(os.path.join(root, f), os.path.relpath(os.path.join(root, f), temp_dir))
644
 
645
+ # Generate summary
646
  summary_df = pd.DataFrame(model_summary).T
647
  summary_md = summary_df.to_markdown()
648
 
649
  summary = f"""
650
+ ## βœ… GWAS Analysis Complete!
651
 
652
  ### Dataset Summary
653
  - **Samples:** {n_samples}
654
  - **Markers:** {n_markers}
655
  - **Bonferroni threshold:** {bonf_threshold:.2e}
656
 
657
+ ### Model Results
658
  {summary_md}
659
 
660
  ### Top Performing Models
661
+ - **Most significant markers:** {max(model_summary.items(), key=lambda x: x[1]['n_significant'])[0] if model_summary else 'N/A'}
662
+ - **Highest mean LOD:** {max(model_summary.items(), key=lambda x: x[1]['mean_lod'])[0] if model_summary else 'N/A'}
 
663
 
664
  ### πŸ“ Output Files
665
+ - `gwas_results.csv` - Complete results for all models
666
+ - `plots/` - Manhattan plots for each model
667
+ - `plots/model_comparison.png` - Model comparison bar chart
668
  """
669
 
670
+ # Return first plot for display
671
+ first_plot = list(plot_paths.values())[0] if plot_paths else None
672
+
673
+ return (summary, first_plot, comparison_path, zip_path, results_df.head(20))
674
 
675
  except Exception as e:
676
  import traceback
 
680
  # GRADIO INTERFACE
681
  # ══════════════════════════════════════════════════════════════
682
 
683
+ with gr.Blocks(css=CSS, title="GWAS Platform", theme=gr.themes.Soft()) as app:
684
 
685
  gr.HTML("""
686
  <div class="main-header">
687
+ <h1>🧬 GWAS Analysis Platform</h1>
688
+ <p>Multi-Model Association Analysis | Single Locus | Multi-Locus | Machine Learning</p>
689
  </div>
690
  """)
691
 
 
697
  gr.HTML('<div class="section-header">βš™οΈ Quality Control</div>')
698
  sample_missing = gr.Slider(10, 80, value=50, step=10, label="Sample Missing (%)")
699
  marker_missing = gr.Slider(10, 80, value=50, step=10, label="Marker Missing (%)")
700
+ maf_threshold = gr.Slider(1, 20, value=5, step=5, label="MAF (%)")
701
 
702
  gr.HTML('<div class="section-header">🎯 Model Selection</div>')
703
  with gr.Row():
704
+ use_lr = gr.Checkbox(label="Linear Regression", value=True)
705
+ use_mlr = gr.Checkbox(label="Multiple Regression", value=True)
706
+ with gr.Row():
707
+ use_emmax = gr.Checkbox(label="EMMAX", value=False)
708
+ use_lasso = gr.Checkbox(label="LASSO", value=False)
709
+ with gr.Row():
710
+ use_enet = gr.Checkbox(label="ElasticNet", value=False)
711
+ use_ridge = gr.Checkbox(label="Ridge", value=False)
712
  with gr.Row():
713
+ use_bayes = gr.Checkbox(label="Bayesian", value=False)
714
+ use_rf = gr.Checkbox(label="Random Forest", value=False)
715
  with gr.Row():
716
+ use_gbm = gr.Checkbox(label="Gradient Boosting", value=False)
717
 
718
+ run_btn = gr.Button("πŸš€ Run GWAS Analysis", variant="primary")
719
 
720
  with gr.Column(scale=2):
721
  gr.HTML('<div class="section-header">πŸ“Š Results</div>')
722
  summary_out = gr.Markdown("Ready to analyze")
723
 
724
  with gr.Row():
725
+ manhattan_out = gr.Image(label="Manhattan Plot")
726
  comparison_out = gr.Image(label="Model Comparison")
727
 
728
+ download_out = gr.File(label="Download ZIP")
729
+ preview_out = gr.Dataframe(label="Results Preview")
730
 
731
  run_btn.click(
732
+ fn=run_gwas_pipeline,
733
  inputs=[input_file, sample_missing, marker_missing, maf_threshold,
734
+ use_lr, use_mlr, use_emmax, use_lasso, use_enet,
735
+ use_ridge, use_bayes, use_rf, use_gbm],
736
  outputs=[summary_out, manhattan_out, comparison_out, download_out, preview_out]
737
  )
738
 
739
  gr.HTML("""
740
  <footer>
741
+ <p>GWAS Pipeline v13.0 | Fixed Dimension Issues | Times New Roman | Soft Pastel Theme</p>
742
+ <p><strong>Models:</strong> Linear Regression, Multiple Regression, EMMAX, LASSO, ElasticNet, Ridge, Bayesian, Random Forest, Gradient Boosting</p>
743
  </footer>
744
  """)
745