Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,39 +1,11 @@
|
|
| 1 |
# -*- coding: utf-8 -*-
|
| 2 |
"""
|
| 3 |
-
GWAS Pipeline
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 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
|
| 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.
|
| 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',
|
| 85 |
-
'Multi_Locus': '#A8E6CF',
|
| 86 |
-
'Bayesian': '#FFD3B6',
|
| 87 |
-
'ML': '#FFB3BA',
|
| 88 |
-
'
|
| 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:
|
| 105 |
-
.main-header h1 { color: #4A4A4A; font-size:
|
| 106 |
-
.section-header { background: linear-gradient(135deg, #C5A3FF 0%, #B8D4E3 100%); padding:
|
| 107 |
-
.card { background: #FFFEF8; border-radius: 12px; padding: 15px; margin: 8px 0; border: 1px solid #E8DCC8;
|
| 108 |
-
.
|
| 109 |
-
|
| 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 -
|
| 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 |
-
#
|
| 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 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
|
| 148 |
return pvals, effects, lod
|
| 149 |
|
| 150 |
-
def multiple_locus_regression(genotypes, phenotypes,
|
| 151 |
"""Multiple Linear Regression with PCA"""
|
| 152 |
-
|
| 153 |
-
|
|
|
|
|
|
|
|
|
|
| 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 |
-
|
| 167 |
-
|
| 168 |
-
|
|
|
|
| 169 |
except:
|
| 170 |
pass
|
| 171 |
|
| 172 |
return pvals, effects, lod
|
| 173 |
|
| 174 |
-
def emmax_model(genotypes, phenotypes
|
| 175 |
-
"""EMMAX -
|
| 176 |
n_markers = genotypes.shape[1]
|
| 177 |
-
|
| 178 |
-
effects = np.zeros(n_markers)
|
| 179 |
-
lod = np.zeros(n_markers)
|
| 180 |
|
| 181 |
-
#
|
| 182 |
-
|
| 183 |
-
genotypes_centered = genotypes - genotypes.mean(axis=0)
|
| 184 |
-
kinship = np.cov(genotypes_centered.T)
|
| 185 |
|
| 186 |
-
|
| 187 |
-
|
|
|
|
| 188 |
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 198 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 199 |
model = sm.OLS(yt, Xt).fit()
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
|
|
|
| 203 |
except:
|
| 204 |
pass
|
| 205 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 206 |
return pvals, effects, lod
|
| 207 |
|
| 208 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 209 |
# MULTI-LOCUS MODELS
|
| 210 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 211 |
|
| 212 |
-
def lasso_model(genotypes, phenotypes
|
| 213 |
-
"""LASSO - Least Absolute Shrinkage
|
| 214 |
scaler = StandardScaler()
|
| 215 |
X_scaled = scaler.fit_transform(genotypes)
|
| 216 |
|
| 217 |
-
lasso = LassoCV(cv=
|
| 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
|
| 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
|
| 280 |
-
"""
|
| 281 |
scaler = StandardScaler()
|
| 282 |
X_scaled = scaler.fit_transform(genotypes)
|
| 283 |
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
coefficients = np.zeros(p)
|
| 287 |
-
lambda_val = 0.1 * np.sqrt(np.log(p) / n)
|
| 288 |
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 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,
|
| 307 |
|
| 308 |
-
def
|
| 309 |
-
"""
|
| 310 |
scaler = StandardScaler()
|
| 311 |
X_scaled = scaler.fit_transform(genotypes)
|
| 312 |
-
n, p = X_scaled.shape
|
| 313 |
-
|
| 314 |
-
coefficients = np.zeros(p)
|
| 315 |
|
| 316 |
-
|
| 317 |
-
|
| 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 |
-
|
| 324 |
-
|
| 325 |
-
|
| 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,
|
| 340 |
|
| 341 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 342 |
# BAYESIAN MODELS
|
| 343 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 344 |
|
| 345 |
-
def
|
| 346 |
"""Bayesian Ridge Regression"""
|
| 347 |
scaler = StandardScaler()
|
| 348 |
X_scaled = scaler.fit_transform(genotypes)
|
| 349 |
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 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 |
-
|
| 368 |
-
|
| 369 |
-
lod = -np.log10(pvals + 1e-300)
|
| 370 |
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 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 |
-
|
|
|
|
| 401 |
lod = -np.log10(pvals + 1e-300)
|
| 402 |
|
| 403 |
-
return pvals,
|
| 404 |
|
| 405 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 406 |
# MACHINE LEARNING MODELS
|
| 407 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 408 |
|
| 409 |
-
def
|
| 410 |
"""Random Forest for feature selection"""
|
| 411 |
scaler = StandardScaler()
|
| 412 |
X_scaled = scaler.fit_transform(genotypes)
|
| 413 |
|
| 414 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 415 |
rf.fit(X_scaled, phenotypes)
|
| 416 |
|
| 417 |
-
|
|
|
|
|
|
|
| 418 |
|
| 419 |
-
# Calculate p-values from importance
|
| 420 |
-
imp_rank = np.argsort(
|
| 421 |
-
pvals = np.ones(len(
|
| 422 |
-
for i,
|
| 423 |
-
pvals[
|
| 424 |
|
| 425 |
lod = -np.log10(pvals + 1e-300)
|
| 426 |
|
| 427 |
-
return pvals,
|
| 428 |
|
| 429 |
-
def
|
| 430 |
"""Gradient Boosting Machine"""
|
| 431 |
scaler = StandardScaler()
|
| 432 |
X_scaled = scaler.fit_transform(genotypes)
|
| 433 |
|
| 434 |
-
|
| 435 |
-
|
| 436 |
-
|
| 437 |
-
|
| 438 |
-
|
| 439 |
-
|
| 440 |
-
|
| 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 |
-
|
| 460 |
-
|
| 461 |
|
| 462 |
-
#
|
| 463 |
-
|
| 464 |
-
|
| 465 |
|
| 466 |
-
|
| 467 |
-
|
| 468 |
-
|
| 469 |
-
|
| 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,
|
| 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
|
| 610 |
-
"""
|
| 611 |
-
|
| 612 |
-
|
| 613 |
-
|
| 614 |
-
|
| 615 |
-
|
| 616 |
-
|
| 617 |
-
|
| 618 |
-
|
| 619 |
-
|
| 620 |
-
|
| 621 |
-
|
| 622 |
-
|
| 623 |
-
|
| 624 |
-
|
| 625 |
-
|
| 626 |
-
positions = np.arange(
|
| 627 |
-
|
| 628 |
-
|
| 629 |
-
|
| 630 |
-
|
| 631 |
-
|
| 632 |
-
|
| 633 |
-
|
| 634 |
-
|
| 635 |
-
|
| 636 |
-
|
| 637 |
-
|
| 638 |
-
|
| 639 |
-
|
| 640 |
-
|
| 641 |
-
|
| 642 |
-
|
| 643 |
-
|
| 644 |
-
|
| 645 |
-
|
| 646 |
-
|
| 647 |
-
|
| 648 |
-
|
| 649 |
-
|
| 650 |
-
|
| 651 |
-
|
| 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
|
| 661 |
-
"""
|
| 662 |
fig, axes = plt.subplots(1, 2, figsize=(12, 5), facecolor=BG_PASTEL)
|
| 663 |
|
| 664 |
-
#
|
| 665 |
ax1 = axes[0]
|
| 666 |
ax1.set_facecolor(PANEL_PASTEL)
|
| 667 |
models = list(results_summary.keys())
|
| 668 |
-
n_sig = [results_summary[m]
|
| 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=
|
| 673 |
-
ax1.set_ylabel('
|
| 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,
|
|
|
|
| 678 |
|
| 679 |
-
# Mean LOD
|
| 680 |
ax2 = axes[1]
|
| 681 |
ax2.set_facecolor(PANEL_PASTEL)
|
| 682 |
-
mean_lod = [results_summary[m]
|
| 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=
|
| 687 |
ax2.set_xlabel('Mean LOD Score', fontsize=10)
|
| 688 |
-
ax2.set_title('Mean LOD
|
| 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,
|
|
|
|
| 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
|
| 702 |
-
"""
|
| 703 |
# Read data
|
| 704 |
df = pd.read_csv(filepath, header=0)
|
| 705 |
|
| 706 |
# Limit samples for speed
|
| 707 |
-
max_samples = min(
|
| 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 |
-
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 770 |
|
| 771 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 772 |
# MAIN PIPELINE
|
| 773 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 774 |
|
| 775 |
-
def
|
| 776 |
-
|
| 777 |
-
|
|
|
|
| 778 |
|
| 779 |
if input_file is None:
|
| 780 |
-
return "Please upload a CSV file", 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 |
-
#
|
| 789 |
-
genotypes, phenotypes, sample_ids, chromosomes
|
| 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 |
-
#
|
| 801 |
-
if
|
| 802 |
-
print("Running
|
| 803 |
-
|
| 804 |
-
# Simple Linear Regression
|
| 805 |
pvals, effects, lod = single_locus_regression(genotypes, phenotypes)
|
| 806 |
-
all_results['Linear Regression'] = {'pvals': pvals, 'lod': lod
|
| 807 |
model_summary['Linear Regression'] = {
|
| 808 |
'n_significant': int((pvals < bonf_threshold).sum()),
|
| 809 |
-
'mean_lod': float(
|
| 810 |
-
'max_lod': float(
|
| 811 |
}
|
| 812 |
-
|
| 813 |
-
|
|
|
|
| 814 |
pvals, effects, lod = multiple_locus_regression(genotypes, phenotypes)
|
| 815 |
-
all_results['Multiple Regression'] = {'pvals': pvals, 'lod': lod
|
| 816 |
model_summary['Multiple Regression'] = {
|
| 817 |
'n_significant': int((pvals < bonf_threshold).sum()),
|
| 818 |
-
'mean_lod': float(
|
| 819 |
-
'max_lod': float(
|
| 820 |
}
|
| 821 |
-
|
| 822 |
-
|
|
|
|
| 823 |
pvals, effects, lod = emmax_model(genotypes, phenotypes)
|
| 824 |
-
all_results['EMMAX'] = {'pvals': pvals, 'lod': lod
|
| 825 |
model_summary['EMMAX'] = {
|
| 826 |
'n_significant': int((pvals < bonf_threshold).sum()),
|
| 827 |
-
'mean_lod': float(
|
| 828 |
-
'max_lod': float(
|
| 829 |
}
|
| 830 |
|
| 831 |
-
|
| 832 |
-
|
| 833 |
-
|
| 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(
|
| 841 |
-
'max_lod': float(
|
| 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 |
-
|
| 856 |
-
|
| 857 |
-
|
| 858 |
-
|
| 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(
|
| 866 |
-
'max_lod': float(
|
| 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 |
-
|
| 880 |
-
|
| 881 |
-
|
| 882 |
-
|
|
|
|
| 883 |
'n_significant': int((pvals < bonf_threshold).sum()),
|
| 884 |
-
'mean_lod': float(
|
| 885 |
-
'max_lod': float(
|
| 886 |
-
'selected': int(n_selected)
|
| 887 |
}
|
| 888 |
|
| 889 |
-
|
| 890 |
-
|
| 891 |
-
|
| 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(
|
| 899 |
-
'max_lod': float(
|
| 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 |
-
|
| 921 |
-
|
| 922 |
-
|
| 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(
|
| 930 |
-
'max_lod': float(
|
| 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 |
-
|
| 965 |
-
|
| 966 |
-
|
| 967 |
-
|
| 968 |
-
|
| 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(
|
| 984 |
-
'max_lod': float(
|
| 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, '
|
| 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 |
-
|
| 1007 |
|
| 1008 |
# Create ZIP
|
| 1009 |
-
zip_path = os.path.join(temp_dir, '
|
| 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
|
| 1016 |
summary_df = pd.DataFrame(model_summary).T
|
| 1017 |
summary_md = summary_df.to_markdown()
|
| 1018 |
|
| 1019 |
summary = f"""
|
| 1020 |
-
## β
|
| 1021 |
|
| 1022 |
### Dataset Summary
|
| 1023 |
- **Samples:** {n_samples}
|
| 1024 |
- **Markers:** {n_markers}
|
| 1025 |
- **Bonferroni threshold:** {bonf_threshold:.2e}
|
| 1026 |
|
| 1027 |
-
### Model Results
|
| 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 |
-
- `
|
| 1037 |
-
- `plots/
|
| 1038 |
-
- `plots/model_comparison.png` - Model
|
| 1039 |
"""
|
| 1040 |
|
| 1041 |
-
|
| 1042 |
-
|
|
|
|
|
|
|
| 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="
|
| 1053 |
|
| 1054 |
gr.HTML("""
|
| 1055 |
<div class="main-header">
|
| 1056 |
-
<h1>π§¬
|
| 1057 |
-
<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
|
| 1070 |
|
| 1071 |
gr.HTML('<div class="section-header">π― Model Selection</div>')
|
| 1072 |
with gr.Row():
|
| 1073 |
-
|
| 1074 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1075 |
with gr.Row():
|
| 1076 |
-
|
| 1077 |
-
|
| 1078 |
with gr.Row():
|
| 1079 |
-
|
| 1080 |
|
| 1081 |
-
run_btn = gr.Button("π Run
|
| 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
|
| 1089 |
comparison_out = gr.Image(label="Model Comparison")
|
| 1090 |
|
| 1091 |
-
download_out = gr.File(label="Download
|
| 1092 |
-
preview_out = gr.Dataframe(label="
|
| 1093 |
|
| 1094 |
run_btn.click(
|
| 1095 |
-
fn=
|
| 1096 |
inputs=[input_file, sample_missing, marker_missing, maf_threshold,
|
| 1097 |
-
|
|
|
|
| 1098 |
outputs=[summary_out, manhattan_out, comparison_out, download_out, preview_out]
|
| 1099 |
)
|
| 1100 |
|
| 1101 |
gr.HTML("""
|
| 1102 |
<footer>
|
| 1103 |
-
<p>
|
| 1104 |
-
<p><strong>Models
|
| 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 |
|