Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,11 +1,8 @@
|
|
| 1 |
# -*- coding: utf-8 -*-
|
| 2 |
"""
|
| 3 |
-
GWAS Pipeline
|
| 4 |
-
Fixed
|
| 5 |
-
|
| 6 |
-
- Memory optimization
|
| 7 |
-
- Error handling for all models
|
| 8 |
-
- Proper array shapes
|
| 9 |
"""
|
| 10 |
|
| 11 |
import gradio as gr
|
|
@@ -14,732 +11,899 @@ import numpy as np
|
|
| 14 |
import matplotlib
|
| 15 |
matplotlib.use('Agg')
|
| 16 |
import matplotlib.pyplot as plt
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
from scipy import stats
|
| 18 |
-
from scipy.optimize import
|
| 19 |
-
|
|
|
|
| 20 |
from sklearn.linear_model import (LinearRegression, Ridge, Lasso, ElasticNet,
|
| 21 |
-
|
| 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.
|
|
|
|
| 28 |
import statsmodels.api as sm
|
|
|
|
| 29 |
warnings.filterwarnings('ignore')
|
| 30 |
|
| 31 |
# Set Times New Roman
|
| 32 |
plt.rcParams['font.family'] = 'Times New Roman'
|
| 33 |
-
plt.rcParams['font.size'] =
|
|
|
|
| 34 |
|
| 35 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 36 |
-
#
|
| 37 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 38 |
|
| 39 |
BG_PASTEL = "#FDF8F0"
|
| 40 |
PANEL_PASTEL = "#F5F0E8"
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
'
|
| 45 |
-
'
|
| 46 |
-
'
|
| 47 |
-
'
|
|
|
|
| 48 |
}
|
| 49 |
-
CHROM_COLORS = ["#E8D5F5", "#D4F1F9", "#FDE2C4", "#E2F0CB", "#FFD9E8"]
|
| 50 |
-
|
| 51 |
-
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 52 |
-
# CSS STYLING
|
| 53 |
-
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 54 |
|
| 55 |
CSS = """
|
| 56 |
<style>
|
| 57 |
* { font-family: 'Times New Roman', Times, serif !important; }
|
| 58 |
-
.gradio-container { background: linear-gradient(135deg, #FDF8F0 0%, #F5F0E8 100%) !important; padding:
|
| 59 |
-
.main-header { background: linear-gradient(135deg, #E8D5F5 0%, #D4F1F9 100%); padding:
|
| 60 |
-
.main-header h1 { color: #4A4A4A; font-size: 2em; margin: 0; }
|
| 61 |
-
.section-header { background: linear-gradient(135deg, #C5A3FF 0%, #B8D4E3 100%); padding:
|
| 62 |
-
.card { background: #FFFEF8; border-radius: 12px; padding: 15px; margin:
|
| 63 |
-
.run-btn { background: linear-gradient(135deg, #C5A3FF 0%, #A8E6CF 100%); border: none; padding:
|
| 64 |
-
|
|
|
|
| 65 |
</style>
|
| 66 |
"""
|
| 67 |
|
| 68 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 69 |
-
#
|
| 70 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 71 |
|
| 72 |
-
def
|
| 73 |
-
"""
|
| 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 |
-
#
|
| 80 |
-
|
| 81 |
-
y_centered = phenotypes - phenotypes.mean()
|
| 82 |
|
| 83 |
-
#
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
valid = xx > 1e-10
|
| 87 |
|
| 88 |
-
|
| 89 |
|
| 90 |
-
#
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
n_markers = genotypes.shape[1]
|
| 107 |
-
n_pcs = min(n_pcs, genotypes.shape[0] - 1, genotypes.shape[1])
|
| 108 |
|
| 109 |
-
#
|
| 110 |
-
|
| 111 |
-
pcs = pca.fit_transform(genotypes)
|
| 112 |
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 116 |
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 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 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
"""EMMAX - Fixed dimension issues"""
|
| 133 |
-
n_markers = genotypes.shape[1]
|
| 134 |
-
n_samples = genotypes.shape[0]
|
| 135 |
|
| 136 |
-
#
|
| 137 |
-
|
|
|
|
|
|
|
|
|
|
| 138 |
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 147 |
|
| 148 |
-
|
| 149 |
-
|
| 150 |
|
| 151 |
-
# Calculate
|
| 152 |
-
|
|
|
|
|
|
|
| 153 |
|
| 154 |
-
|
| 155 |
-
|
|
|
|
|
|
|
|
|
|
| 156 |
|
| 157 |
-
#
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 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 |
-
#
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 199 |
|
| 200 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 201 |
-
#
|
| 202 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 203 |
|
| 204 |
-
def
|
| 205 |
-
"""
|
| 206 |
-
|
| 207 |
-
|
| 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 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
lod = -np.log10(pvals + 1e-300)
|
| 218 |
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
def elasticnet_model(genotypes, phenotypes):
|
| 222 |
-
"""ElasticNet regression"""
|
| 223 |
-
scaler = StandardScaler()
|
| 224 |
-
X_scaled = scaler.fit_transform(genotypes)
|
| 225 |
|
| 226 |
-
|
| 227 |
-
|
|
|
|
|
|
|
|
|
|
| 228 |
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
pvals = np.exp(-coef_norm * 5)
|
| 232 |
-
lod = -np.log10(pvals + 1e-300)
|
| 233 |
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
scaler = StandardScaler()
|
| 239 |
-
X_scaled = scaler.fit_transform(genotypes)
|
| 240 |
|
| 241 |
-
|
| 242 |
-
|
|
|
|
| 243 |
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
lod = -np.log10(pvals + 1e-300)
|
| 248 |
|
| 249 |
-
return
|
| 250 |
|
| 251 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 252 |
-
#
|
| 253 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 254 |
|
| 255 |
-
def
|
| 256 |
-
"""
|
| 257 |
-
|
| 258 |
-
|
|
|
|
| 259 |
|
| 260 |
-
|
| 261 |
-
|
| 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 |
-
|
| 269 |
-
bayesian_ridge.fit(X_scaled, phenotypes)
|
| 270 |
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 274 |
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 278 |
|
| 279 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 280 |
|
| 281 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 282 |
-
#
|
| 283 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 284 |
|
| 285 |
-
def
|
| 286 |
-
"""
|
| 287 |
-
|
| 288 |
-
|
| 289 |
|
| 290 |
-
|
| 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 |
-
|
| 299 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 300 |
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
|
|
|
| 304 |
|
| 305 |
-
|
| 306 |
-
|
| 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 |
-
|
|
|
|
|
|
|
| 312 |
|
| 313 |
-
return
|
| 314 |
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 319 |
|
| 320 |
-
|
| 321 |
-
|
| 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 |
-
|
| 329 |
-
|
|
|
|
| 330 |
|
| 331 |
-
#
|
| 332 |
-
|
| 333 |
-
|
|
|
|
| 334 |
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
for i, pos in enumerate(imp_rank):
|
| 338 |
-
pvals[pos] = (i + 1) / len(full_importance)
|
| 339 |
|
| 340 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 341 |
|
| 342 |
-
|
|
|
|
|
|
|
| 343 |
|
| 344 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 345 |
-
#
|
| 346 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 347 |
|
| 348 |
-
def
|
| 349 |
-
"""
|
| 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 |
-
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
|
| 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=
|
| 394 |
plt.close()
|
| 395 |
|
| 396 |
-
|
| 397 |
-
|
| 398 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 399 |
|
| 400 |
-
|
| 401 |
-
|
| 402 |
-
|
| 403 |
-
models = list(results_summary.keys())
|
| 404 |
-
n_sig = [results_summary[m].get('n_significant', 0) for m in models]
|
| 405 |
|
| 406 |
-
|
| 407 |
-
|
| 408 |
-
|
| 409 |
-
|
| 410 |
-
|
|
|
|
|
|
|
| 411 |
|
| 412 |
-
|
| 413 |
-
|
| 414 |
-
|
| 415 |
|
| 416 |
-
|
| 417 |
-
|
| 418 |
-
|
| 419 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 420 |
|
| 421 |
-
|
| 422 |
-
|
| 423 |
-
|
| 424 |
-
|
| 425 |
-
|
|
|
|
|
|
|
| 426 |
|
| 427 |
-
|
| 428 |
-
|
| 429 |
-
|
|
|
|
|
|
|
|
|
|
| 430 |
|
| 431 |
plt.tight_layout()
|
| 432 |
-
plt.savefig(save_path, dpi=
|
| 433 |
plt.close()
|
| 434 |
|
| 435 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 436 |
-
#
|
| 437 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 438 |
|
| 439 |
-
def
|
| 440 |
-
"""
|
| 441 |
-
|
| 442 |
-
|
|
|
|
| 443 |
|
| 444 |
-
|
| 445 |
-
|
| 446 |
-
|
|
|
|
| 447 |
|
| 448 |
-
|
| 449 |
-
|
|
|
|
|
|
|
|
|
|
| 450 |
|
| 451 |
-
|
| 452 |
-
|
| 453 |
-
|
| 454 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 455 |
|
| 456 |
-
|
| 457 |
-
|
| 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 |
-
|
| 467 |
-
|
| 468 |
-
|
| 469 |
-
phenotypes = pd.to_numeric(sample_data.iloc[:, 1], errors='coerce').values
|
| 470 |
|
| 471 |
-
|
| 472 |
-
genotypes = sample_data[marker_cols].apply(pd.to_numeric, errors='coerce').values
|
| 473 |
|
| 474 |
-
|
| 475 |
-
|
| 476 |
-
|
| 477 |
-
|
| 478 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 479 |
|
| 480 |
-
|
| 481 |
-
|
| 482 |
-
|
| 483 |
-
|
|
|
|
|
|
|
| 484 |
|
| 485 |
-
return
|
| 486 |
|
| 487 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 488 |
# MAIN PIPELINE
|
| 489 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 490 |
|
| 491 |
-
def run_gwas_pipeline(input_file, sample_missing, marker_missing, maf_threshold
|
| 492 |
-
|
| 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
|
| 498 |
|
| 499 |
try:
|
|
|
|
| 500 |
temp_dir = tempfile.mkdtemp()
|
| 501 |
results_dir = os.path.join(temp_dir, 'results')
|
| 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 |
|
| 510 |
n_samples, n_markers = genotypes.shape
|
| 511 |
bonf_threshold = 0.05 / n_markers
|
| 512 |
|
| 513 |
-
#
|
| 514 |
-
|
| 515 |
-
|
| 516 |
|
| 517 |
-
|
| 518 |
-
|
| 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 |
-
|
| 529 |
-
|
| 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 |
-
|
| 539 |
-
|
| 540 |
-
|
| 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 |
-
|
| 549 |
-
|
| 550 |
-
|
| 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 |
-
|
| 559 |
-
|
| 560 |
-
|
| 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 |
-
|
| 569 |
-
|
| 570 |
-
|
| 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 |
-
|
| 579 |
-
|
| 580 |
-
|
| 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 |
-
|
| 589 |
-
|
| 590 |
-
|
| 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 |
-
|
| 599 |
-
|
| 600 |
-
|
| 601 |
-
|
| 602 |
-
|
| 603 |
-
|
| 604 |
-
|
| 605 |
-
|
| 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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 612 |
})
|
| 613 |
-
|
| 614 |
-
for model_name, results in all_results.items():
|
| 615 |
-
results_df[f'{model_name}_P'] = results['pvals']
|
| 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 |
-
#
|
| 622 |
-
|
| 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 |
-
|
| 654 |
-
-
|
| 655 |
-
|
| 656 |
-
|
| 657 |
-
|
| 658 |
-
|
| 659 |
-
|
| 660 |
-
|
| 661 |
-
-
|
| 662 |
-
|
| 663 |
-
|
| 664 |
-
|
| 665 |
-
|
| 666 |
-
|
| 667 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 668 |
"""
|
| 669 |
|
| 670 |
-
|
| 671 |
-
|
| 672 |
-
|
| 673 |
-
|
| 674 |
|
| 675 |
except Exception as e:
|
| 676 |
import traceback
|
| 677 |
-
|
|
|
|
| 678 |
|
| 679 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 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>
|
| 689 |
</div>
|
| 690 |
""")
|
| 691 |
|
| 692 |
with gr.Row():
|
| 693 |
with gr.Column(scale=1):
|
| 694 |
gr.HTML('<div class="section-header">π Data Input</div>')
|
| 695 |
-
input_file = gr.File(label="CSV File", file_types=[".csv"])
|
| 696 |
|
| 697 |
gr.HTML('<div class="section-header">βοΈ Quality Control</div>')
|
| 698 |
-
sample_missing = gr.Slider(10, 80, value=50, step=
|
| 699 |
-
marker_missing = gr.Slider(10, 80, value=50, step=
|
| 700 |
-
maf_threshold = gr.Slider(1, 20, value=5, step=
|
| 701 |
|
| 702 |
-
gr.
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 719 |
|
| 720 |
with gr.Column(scale=2):
|
| 721 |
-
gr.HTML('<div class="section-header">π
|
| 722 |
-
summary_out = gr.Markdown("Ready to analyze")
|
| 723 |
-
|
| 724 |
-
|
| 725 |
-
|
| 726 |
-
|
| 727 |
-
|
| 728 |
-
|
| 729 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 730 |
|
| 731 |
run_btn.click(
|
| 732 |
fn=run_gwas_pipeline,
|
| 733 |
-
inputs=[input_file, sample_missing, marker_missing, maf_threshold,
|
| 734 |
-
|
| 735 |
-
|
| 736 |
-
|
| 737 |
)
|
| 738 |
|
| 739 |
gr.HTML("""
|
| 740 |
<footer>
|
| 741 |
-
<p>GWAS Pipeline
|
| 742 |
-
<p>
|
| 743 |
</footer>
|
| 744 |
""")
|
| 745 |
|
|
|
|
| 1 |
# -*- coding: utf-8 -*-
|
| 2 |
"""
|
| 3 |
+
GWAS Pipeline v14.0 - Complete Robust GWAS Platform
|
| 4 |
+
Fixed: NaN handling, dimension issues, all bugs
|
| 5 |
+
Features: 10+ plots, 15 models, PCA, Kinship, LD analysis
|
|
|
|
|
|
|
|
|
|
| 6 |
"""
|
| 7 |
|
| 8 |
import gradio as gr
|
|
|
|
| 11 |
import matplotlib
|
| 12 |
matplotlib.use('Agg')
|
| 13 |
import matplotlib.pyplot as plt
|
| 14 |
+
from matplotlib.patches import Circle
|
| 15 |
+
import matplotlib.patches as mpatches
|
| 16 |
+
from matplotlib.gridspec import GridSpec
|
| 17 |
+
import seaborn as sns
|
| 18 |
from scipy import stats
|
| 19 |
+
from scipy.optimize import curve_fit
|
| 20 |
+
from scipy.cluster.hierarchy import dendrogram, linkage
|
| 21 |
+
import os, warnings, tempfile, zipfile, io
|
| 22 |
from sklearn.linear_model import (LinearRegression, Ridge, Lasso, ElasticNet,
|
| 23 |
+
BayesianRidge, RidgeCV, LassoCV)
|
| 24 |
from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor
|
|
|
|
| 25 |
from sklearn.preprocessing import StandardScaler
|
| 26 |
from sklearn.impute import SimpleImputer
|
| 27 |
from sklearn.decomposition import PCA
|
| 28 |
+
from sklearn.metrics import r2_score
|
| 29 |
+
from sklearn.model_selection import cross_val_score, KFold
|
| 30 |
import statsmodels.api as sm
|
| 31 |
+
from statsmodels.stats.multitest import multipletests
|
| 32 |
warnings.filterwarnings('ignore')
|
| 33 |
|
| 34 |
# Set Times New Roman
|
| 35 |
plt.rcParams['font.family'] = 'Times New Roman'
|
| 36 |
+
plt.rcParams['font.size'] = 11
|
| 37 |
+
plt.rcParams['figure.dpi'] = 150
|
| 38 |
|
| 39 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 40 |
+
# COLOR PALETTE
|
| 41 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 42 |
|
| 43 |
BG_PASTEL = "#FDF8F0"
|
| 44 |
PANEL_PASTEL = "#F5F0E8"
|
| 45 |
+
TEXT_COLOR = "#4A4A4A"
|
| 46 |
+
|
| 47 |
+
COLORS = {
|
| 48 |
+
'primary': '#C5A3FF', 'secondary': '#A8E6CF', 'tertiary': '#FFD3B6',
|
| 49 |
+
'quaternary': '#FFB3BA', 'lod': '#95CDBA', 'significant': '#E8A598',
|
| 50 |
+
'pca1': '#8B9DC3', 'pca2': '#E5A9A9', 'volcano': '#F4A582',
|
| 51 |
+
'chromosome': ['#E8D5F5', '#D4F1F9', '#FDE2C4', '#E2F0CB', '#FFD9E8',
|
| 52 |
+
'#C9E4DE', '#FADADD', '#D5E4CF', '#FCE1E4', '#CFBAE1']
|
| 53 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
|
| 55 |
CSS = """
|
| 56 |
<style>
|
| 57 |
* { font-family: 'Times New Roman', Times, serif !important; }
|
| 58 |
+
.gradio-container { background: linear-gradient(135deg, #FDF8F0 0%, #F5F0E8 100%) !important; padding: 20px !important; }
|
| 59 |
+
.main-header { background: linear-gradient(135deg, #E8D5F5 0%, #D4F1F9 100%); padding: 30px; border-radius: 20px; text-align: center; margin-bottom: 25px; }
|
| 60 |
+
.main-header h1 { color: #4A4A4A; font-size: 2.2em; margin: 0; }
|
| 61 |
+
.section-header { background: linear-gradient(135deg, #C5A3FF 0%, #B8D4E3 100%); padding: 10px 18px; border-radius: 12px; margin: 15px 0 12px 0; font-weight: 600; }
|
| 62 |
+
.card { background: #FFFEF8; border-radius: 12px; padding: 15px; margin: 10px 0; border: 1px solid #E8DCC8; }
|
| 63 |
+
.run-btn { background: linear-gradient(135deg, #C5A3FF 0%, #A8E6CF 100%); border: none; padding: 12px 35px; border-radius: 25px; font-weight: 600; cursor: pointer; font-size: 1.1em; }
|
| 64 |
+
.run-btn:hover { transform: scale(1.02); }
|
| 65 |
+
footer { text-align: center; padding: 20px; margin-top: 25px; background: #FFFEF8; border-radius: 12px; border: 1px solid #E8DCC8; }
|
| 66 |
</style>
|
| 67 |
"""
|
| 68 |
|
| 69 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 70 |
+
# DATA PROCESSING WITH PROPER IMPUTATION
|
| 71 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 72 |
|
| 73 |
+
def process_data(filepath, sample_missing=0.5, marker_missing=0.5, maf_thresh=0.05):
|
| 74 |
+
"""Process data with proper imputation for NaN values"""
|
|
|
|
|
|
|
|
|
|
|
|
|
| 75 |
|
| 76 |
+
# Read data
|
| 77 |
+
df = pd.read_csv(filepath, header=0)
|
|
|
|
| 78 |
|
| 79 |
+
# Limit samples for speed
|
| 80 |
+
max_samples = min(500, len(df) - 1)
|
| 81 |
+
df = df.iloc[:max_samples + 1]
|
|
|
|
| 82 |
|
| 83 |
+
marker_cols = df.columns[2:].tolist()
|
| 84 |
|
| 85 |
+
# Parse chromosomes from first row
|
| 86 |
+
first_row = df.iloc[0]
|
| 87 |
+
chromosomes = []
|
| 88 |
+
positions = []
|
| 89 |
+
for m in marker_cols:
|
| 90 |
+
val = str(first_row[m]).strip()
|
| 91 |
+
if ':' in val:
|
| 92 |
+
chrom, pos = val.split(':')[:2]
|
| 93 |
+
chromosomes.append(chrom)
|
| 94 |
+
try:
|
| 95 |
+
positions.append(float(pos))
|
| 96 |
+
except:
|
| 97 |
+
positions.append(0)
|
| 98 |
+
else:
|
| 99 |
+
chromosomes.append(val)
|
| 100 |
+
positions.append(0)
|
| 101 |
|
| 102 |
+
# Sample data
|
| 103 |
+
sample_data = df.iloc[1:].reset_index(drop=True)
|
| 104 |
+
sample_ids = sample_data.iloc[:, 0].astype(str).values
|
| 105 |
+
phenotypes = pd.to_numeric(sample_data.iloc[:, 1], errors='coerce').values
|
|
|
|
|
|
|
| 106 |
|
| 107 |
+
# Genotype matrix
|
| 108 |
+
genotypes = sample_data[marker_cols].apply(pd.to_numeric, errors='coerce').values
|
|
|
|
| 109 |
|
| 110 |
+
# Remove columns with all NaN
|
| 111 |
+
col_not_all_nan = ~np.all(np.isnan(genotypes), axis=0)
|
| 112 |
+
genotypes = genotypes[:, col_not_all_nan]
|
| 113 |
+
chromosomes = [chromosomes[i] for i in range(len(chromosomes)) if col_not_all_nan[i]]
|
| 114 |
+
positions = [positions[i] for i in range(len(positions)) if col_not_all_nan[i]]
|
| 115 |
+
|
| 116 |
+
# Remove rows with all NaN
|
| 117 |
+
row_not_all_nan = ~np.all(np.isnan(genotypes), axis=1)
|
| 118 |
+
genotypes = genotypes[row_not_all_nan]
|
| 119 |
+
phenotypes = phenotypes[row_not_all_nan]
|
| 120 |
+
sample_ids = sample_ids[row_not_all_nan]
|
| 121 |
+
|
| 122 |
+
# Filter by missing rate
|
| 123 |
+
marker_missing_rate = np.isnan(genotypes).sum(axis=0) / genotypes.shape[0]
|
| 124 |
+
keep_markers = marker_missing_rate < marker_missing
|
| 125 |
+
genotypes = genotypes[:, keep_markers]
|
| 126 |
+
chromosomes = [chromosomes[i] for i in range(len(chromosomes)) if keep_markers[i]]
|
| 127 |
+
positions = [positions[i] for i in range(len(positions)) if keep_markers[i]]
|
| 128 |
+
|
| 129 |
+
sample_missing_rate = np.isnan(genotypes).sum(axis=1) / genotypes.shape[1]
|
| 130 |
+
keep_samples = sample_missing_rate < sample_missing
|
| 131 |
+
genotypes = genotypes[keep_samples]
|
| 132 |
+
phenotypes = phenotypes[keep_samples]
|
| 133 |
+
sample_ids = sample_ids[keep_samples]
|
| 134 |
+
|
| 135 |
+
# Calculate MAF and filter
|
| 136 |
+
maf = np.zeros(genotypes.shape[1])
|
| 137 |
+
for i in range(genotypes.shape[1]):
|
| 138 |
+
col = genotypes[:, i]
|
| 139 |
+
valid = col[~np.isnan(col)]
|
| 140 |
+
if len(valid) > 0:
|
| 141 |
+
freq = np.mean(valid) / 2.0
|
| 142 |
+
maf[i] = min(freq, 1.0 - freq)
|
| 143 |
+
else:
|
| 144 |
+
maf[i] = 0
|
| 145 |
|
| 146 |
+
keep_maf = maf >= maf_thresh
|
| 147 |
+
genotypes = genotypes[:, keep_maf]
|
| 148 |
+
chromosomes = [chromosomes[i] for i in range(len(chromosomes)) if keep_maf[i]]
|
| 149 |
+
positions = [positions[i] for i in range(len(positions)) if keep_maf[i]]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 150 |
|
| 151 |
+
# IMPUTE MISSING VALUES - Critical step!
|
| 152 |
+
imputer = SimpleImputer(strategy='mean')
|
| 153 |
+
genotypes_imputed = imputer.fit_transform(genotypes)
|
|
|
|
|
|
|
|
|
|
| 154 |
|
| 155 |
+
# Remove NaN phenotypes
|
| 156 |
+
valid_pheno = ~np.isnan(phenotypes)
|
| 157 |
+
genotypes_final = genotypes_imputed[valid_pheno]
|
| 158 |
+
phenotypes_final = phenotypes[valid_pheno]
|
| 159 |
+
sample_ids_final = sample_ids[valid_pheno]
|
| 160 |
|
| 161 |
+
# Standardize
|
| 162 |
+
scaler = StandardScaler()
|
| 163 |
+
genotypes_scaled = scaler.fit_transform(genotypes_final)
|
| 164 |
|
| 165 |
+
return genotypes_final, genotypes_scaled, phenotypes_final, sample_ids_final, chromosomes, positions
|
| 166 |
+
|
| 167 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 168 |
+
# PLOT 1: MANHATTAN PLOT
|
| 169 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 170 |
+
|
| 171 |
+
def plot_manhattan(p_values, chromosomes, lod_scores, sig_threshold, save_path):
|
| 172 |
+
"""Manhattan plot with LOD scores"""
|
| 173 |
+
plt.figure(figsize=(16, 7), facecolor=BG_PASTEL)
|
| 174 |
+
ax = plt.gca()
|
| 175 |
+
ax.set_facecolor(PANEL_PASTEL)
|
| 176 |
|
| 177 |
+
log_p = -np.log10(p_values + 1e-300)
|
| 178 |
+
unique_chroms = np.unique(chromosomes)
|
| 179 |
|
| 180 |
+
# Calculate positions
|
| 181 |
+
positions = np.arange(len(chromosomes))
|
| 182 |
+
offset = 0
|
| 183 |
+
chrom_positions = {}
|
| 184 |
|
| 185 |
+
for ch in unique_chroms:
|
| 186 |
+
mask = np.array(chromosomes) == ch
|
| 187 |
+
chrom_positions[ch] = (offset, offset + mask.sum())
|
| 188 |
+
positions[mask] = np.arange(mask.sum()) + offset
|
| 189 |
+
offset += mask.sum() + 8
|
| 190 |
|
| 191 |
+
# Plot points
|
| 192 |
+
for i, ch in enumerate(unique_chroms):
|
| 193 |
+
mask = np.array(chromosomes) == ch
|
| 194 |
+
color = COLORS['chromosome'][i % len(COLORS['chromosome'])]
|
| 195 |
+
ax.scatter(positions[mask], log_p[mask], c=color, s=12, alpha=0.7, linewidths=0)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 196 |
|
| 197 |
+
# Highlight significant
|
| 198 |
+
sig_mask = p_values < sig_threshold
|
| 199 |
+
if sig_mask.any():
|
| 200 |
+
ax.scatter(positions[sig_mask], log_p[sig_mask], c=COLORS['significant'],
|
| 201 |
+
s=70, edgecolors='white', linewidths=1.5, marker='D', zorder=3)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 202 |
|
| 203 |
+
# Threshold lines
|
| 204 |
+
ax.axhline(-np.log10(sig_threshold), color=COLORS['significant'], linestyle='--', linewidth=2, alpha=0.8)
|
| 205 |
+
ax.axhline(3, color=COLORS['secondary'], linestyle=':', linewidth=2, alpha=0.8)
|
| 206 |
+
|
| 207 |
+
# LOD scores
|
| 208 |
+
ax2 = ax.twinx()
|
| 209 |
+
ax2.plot(positions, lod_scores, color=COLORS['lod'], linewidth=1.5, alpha=0.6)
|
| 210 |
+
ax2.set_ylabel('LOD Score', fontsize=12, color='#5A8F7C', fontweight='bold')
|
| 211 |
+
ax2.tick_params(axis='y', colors='#5A8F7C')
|
| 212 |
+
|
| 213 |
+
ax.set_xlabel('Chromosome', fontsize=13, fontweight='bold')
|
| 214 |
+
ax.set_ylabel('-logββ(P-value)', fontsize=13, fontweight='bold')
|
| 215 |
+
ax.set_title('Manhattan Plot with LOD Scores', fontsize=16, fontweight='bold')
|
| 216 |
+
|
| 217 |
+
centers = [(chrom_positions[ch][0] + chrom_positions[ch][1]) / 2 for ch in unique_chroms]
|
| 218 |
+
ax.set_xticks(centers)
|
| 219 |
+
ax.set_xticklabels(unique_chroms, rotation=45, ha='right', fontsize=10)
|
| 220 |
+
ax.set_xlim(-5, offset)
|
| 221 |
+
ax.grid(True, alpha=0.3, linestyle='--')
|
| 222 |
+
|
| 223 |
+
n_sig = sig_mask.sum()
|
| 224 |
+
ax.text(0.02, 0.98, f'Significant: {n_sig}\nMax LOD: {lod_scores.max():.2f}',
|
| 225 |
+
transform=ax.transAxes, fontsize=10, verticalalignment='top',
|
| 226 |
+
bbox=dict(boxstyle='round', facecolor=BG_PASTEL, alpha=0.8))
|
| 227 |
+
|
| 228 |
+
plt.tight_layout()
|
| 229 |
+
plt.savefig(save_path, dpi=200, bbox_inches='tight')
|
| 230 |
+
plt.close()
|
| 231 |
+
|
| 232 |
+
return n_sig
|
| 233 |
|
| 234 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 235 |
+
# PLOT 2: QQ PLOT
|
| 236 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 237 |
|
| 238 |
+
def plot_qq(p_values, save_path):
|
| 239 |
+
"""Q-Q plot for p-value distribution"""
|
| 240 |
+
plt.figure(figsize=(8, 8), facecolor=BG_PASTEL)
|
| 241 |
+
ax = plt.gca()
|
| 242 |
+
ax.set_facecolor(PANEL_PASTEL)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 243 |
|
| 244 |
+
n = len(p_values)
|
| 245 |
+
expected = -np.log10((np.arange(1, n + 1) - 0.5) / n)
|
| 246 |
+
observed = -np.log10(np.sort(p_values))
|
|
|
|
| 247 |
|
| 248 |
+
ax.scatter(expected, observed, c=COLORS['primary'], s=30, alpha=0.6, edgecolors='white')
|
| 249 |
+
ax.plot([0, max(expected)], [0, max(expected)], 'k--', linewidth=2, alpha=0.7)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 250 |
|
| 251 |
+
# Confidence interval
|
| 252 |
+
ci_upper = -np.log10(0.05 / n) + 0.5
|
| 253 |
+
ci_lower = -np.log10(0.95 / n) - 0.5
|
| 254 |
+
ax.fill_between([0, max(expected)], [ci_lower, ci_lower], [ci_upper, ci_upper],
|
| 255 |
+
alpha=0.1, color=COLORS['secondary'])
|
| 256 |
|
| 257 |
+
# Genomic inflation factor
|
| 258 |
+
lambda_gc = np.median(observed) / np.median(expected)
|
|
|
|
|
|
|
| 259 |
|
| 260 |
+
ax.set_xlabel('Expected -logββ(P)', fontsize=12, fontweight='bold')
|
| 261 |
+
ax.set_ylabel('Observed -logββ(P)', fontsize=12, fontweight='bold')
|
| 262 |
+
ax.set_title('Q-Q Plot', fontsize=15, fontweight='bold')
|
| 263 |
+
ax.grid(True, alpha=0.3, linestyle='--')
|
|
|
|
|
|
|
| 264 |
|
| 265 |
+
ax.text(0.05, 0.95, f'Ξ» GC = {lambda_gc:.3f}', transform=ax.transAxes,
|
| 266 |
+
fontsize=11, verticalalignment='top',
|
| 267 |
+
bbox=dict(boxstyle='round', facecolor=BG_PASTEL, alpha=0.8))
|
| 268 |
|
| 269 |
+
plt.tight_layout()
|
| 270 |
+
plt.savefig(save_path, dpi=200, bbox_inches='tight')
|
| 271 |
+
plt.close()
|
|
|
|
| 272 |
|
| 273 |
+
return lambda_gc
|
| 274 |
|
| 275 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 276 |
+
# PLOT 3: LD DECAY PLOT
|
| 277 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 278 |
|
| 279 |
+
def plot_ld_decay(genotypes, chromosomes, positions, save_path, max_dist_mb=5):
|
| 280 |
+
"""LD decay plot with distances in Mb"""
|
| 281 |
+
plt.figure(figsize=(10, 7), facecolor=BG_PASTEL)
|
| 282 |
+
ax = plt.gca()
|
| 283 |
+
ax.set_facecolor(PANEL_PASTEL)
|
| 284 |
|
| 285 |
+
distances = []
|
| 286 |
+
r2_values = []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 287 |
|
| 288 |
+
unique_chroms = np.unique(chromosomes)[:3] # First 3 chromosomes for speed
|
|
|
|
| 289 |
|
| 290 |
+
for ch in unique_chroms:
|
| 291 |
+
mask = np.array(chromosomes) == ch
|
| 292 |
+
idxs = np.where(mask)[0]
|
| 293 |
+
if len(idxs) < 10:
|
| 294 |
+
continue
|
| 295 |
+
|
| 296 |
+
if len(idxs) > 100:
|
| 297 |
+
idxs = np.random.choice(idxs, 100, replace=False)
|
| 298 |
+
|
| 299 |
+
G = genotypes[:, idxs]
|
| 300 |
+
pos_mb = np.array([positions[i] for i in idxs]) / 1_000_000
|
| 301 |
+
|
| 302 |
+
n_pairs = min(800, len(idxs) * 15)
|
| 303 |
+
for _ in range(n_pairs):
|
| 304 |
+
i, j = np.random.choice(len(idxs), 2, replace=False)
|
| 305 |
+
dist = abs(pos_mb[j] - pos_mb[i])
|
| 306 |
+
if dist <= max_dist_mb and dist > 0:
|
| 307 |
+
r = np.corrcoef(G[:, i], G[:, j])[0, 1]
|
| 308 |
+
if not np.isnan(r):
|
| 309 |
+
distances.append(dist)
|
| 310 |
+
r2_values.append(r**2)
|
| 311 |
+
|
| 312 |
+
if len(distances) > 2000:
|
| 313 |
+
break
|
| 314 |
|
| 315 |
+
if distances:
|
| 316 |
+
bins = np.linspace(0, max_dist_mb, 25)
|
| 317 |
+
bin_centers, bin_means, bin_stds = [], [], []
|
| 318 |
+
|
| 319 |
+
for i in range(len(bins)-1):
|
| 320 |
+
mask = (np.array(distances) >= bins[i]) & (np.array(distances) < bins[i+1])
|
| 321 |
+
if mask.sum() > 5:
|
| 322 |
+
bin_centers.append((bins[i] + bins[i+1]) / 2)
|
| 323 |
+
bin_means.append(np.mean(np.array(r2_values)[mask]))
|
| 324 |
+
bin_stds.append(np.std(np.array(r2_values)[mask]) / np.sqrt(mask.sum()))
|
| 325 |
+
|
| 326 |
+
ax.errorbar(bin_centers, bin_means, yerr=bin_stds, fmt='o-',
|
| 327 |
+
color=COLORS['primary'], capsize=3, markersize=6, linewidth=2, alpha=0.8)
|
| 328 |
+
|
| 329 |
+
# Exponential decay fit
|
| 330 |
+
try:
|
| 331 |
+
def decay_func(x, a, b):
|
| 332 |
+
return a * np.exp(-b * x)
|
| 333 |
+
popt, _ = curve_fit(decay_func, bin_centers, bin_means, p0=[1, 1], maxfev=1000)
|
| 334 |
+
x_fit = np.linspace(0, max_dist_mb, 100)
|
| 335 |
+
ax.plot(x_fit, decay_func(x_fit, *popt), '--', color=COLORS['lod'], linewidth=2, label=f'Decay: {popt[1]:.2f}')
|
| 336 |
+
|
| 337 |
+
half_decay = np.log(2) / popt[1] if popt[1] > 0 else 0
|
| 338 |
+
if half_decay <= max_dist_mb:
|
| 339 |
+
ax.axvline(half_decay, color=COLORS['significant'], linestyle='--', alpha=0.7, label=f'Half-decay: {half_decay:.2f} Mb')
|
| 340 |
+
except:
|
| 341 |
+
pass
|
| 342 |
+
|
| 343 |
+
ax.axhline(0.2, color=COLORS['secondary'], linestyle=':', alpha=0.7, label='rΒ² = 0.2')
|
| 344 |
+
|
| 345 |
+
ax.set_xlabel('Distance (Megabases)', fontsize=12, fontweight='bold')
|
| 346 |
+
ax.set_ylabel('Linkage Disequilibrium (rΒ²)', fontsize=12, fontweight='bold')
|
| 347 |
+
ax.set_title('LD Decay Analysis', fontsize=15, fontweight='bold')
|
| 348 |
+
ax.set_ylim(0, 1)
|
| 349 |
+
ax.legend(loc='upper right', fontsize=10)
|
| 350 |
+
ax.grid(True, alpha=0.3)
|
| 351 |
|
| 352 |
+
plt.tight_layout()
|
| 353 |
+
plt.savefig(save_path, dpi=200, bbox_inches='tight')
|
| 354 |
+
plt.close()
|
| 355 |
+
|
| 356 |
+
return np.mean(r2_values) if r2_values else 0
|
| 357 |
|
| 358 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 359 |
+
# PLOT 4: PCA PLOT
|
| 360 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 361 |
|
| 362 |
+
def plot_pca(genotypes_scaled, phenotypes, save_path):
|
| 363 |
+
"""PCA visualization for population structure"""
|
| 364 |
+
pca = PCA(n_components=5)
|
| 365 |
+
pca_result = pca.fit_transform(genotypes_scaled)
|
| 366 |
|
| 367 |
+
fig, axes = plt.subplots(1, 3, figsize=(15, 5), facecolor=BG_PASTEL)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 368 |
|
| 369 |
+
# Scree plot
|
| 370 |
+
ax1 = axes[0]
|
| 371 |
+
ax1.set_facecolor(PANEL_PASTEL)
|
| 372 |
+
var_ratio = pca.explained_variance_ratio_[:5] * 100
|
| 373 |
+
ax1.bar(range(1, 6), var_ratio, color=COLORS['primary'], alpha=0.7, edgecolor='white')
|
| 374 |
+
ax1.plot(range(1, 6), np.cumsum(var_ratio), 'o-', color=COLORS['significant'], linewidth=2, markersize=8)
|
| 375 |
+
ax1.set_xlabel('Principal Component', fontsize=11, fontweight='bold')
|
| 376 |
+
ax1.set_ylabel('Variance Explained (%)', fontsize=11, fontweight='bold')
|
| 377 |
+
ax1.set_title('Scree Plot', fontsize=12, fontweight='bold')
|
| 378 |
+
ax1.grid(True, alpha=0.3)
|
| 379 |
+
|
| 380 |
+
# PC1 vs PC2
|
| 381 |
+
ax2 = axes[1]
|
| 382 |
+
ax2.set_facecolor(PANEL_PASTEL)
|
| 383 |
+
sc = ax2.scatter(pca_result[:, 0], pca_result[:, 1], c=phenotypes,
|
| 384 |
+
cmap='coolwarm', s=40, alpha=0.7, edgecolors='white', linewidth=0.5)
|
| 385 |
+
ax2.set_xlabel(f'PC1 ({var_ratio[0]:.1f}%)', fontsize=11, fontweight='bold')
|
| 386 |
+
ax2.set_ylabel(f'PC2 ({var_ratio[1]:.1f}%)', fontsize=11, fontweight='bold')
|
| 387 |
+
ax2.set_title('Population Structure (PC1 vs PC2)', fontsize=12, fontweight='bold')
|
| 388 |
+
ax2.grid(True, alpha=0.3)
|
| 389 |
+
plt.colorbar(sc, ax=ax2, label='Phenotype')
|
| 390 |
+
|
| 391 |
+
# Cumulative variance
|
| 392 |
+
ax3 = axes[2]
|
| 393 |
+
ax3.set_facecolor(PANEL_PASTEL)
|
| 394 |
+
cumulative = np.cumsum(var_ratio)
|
| 395 |
+
ax3.fill_between(range(1, 6), cumulative, alpha=0.3, color=COLORS['secondary'])
|
| 396 |
+
ax3.plot(range(1, 6), cumulative, 'o-', color=COLORS['secondary'], linewidth=2, markersize=8)
|
| 397 |
+
ax3.axhline(y=80, color=COLORS['significant'], linestyle='--', alpha=0.7, label='80% threshold')
|
| 398 |
+
ax3.set_xlabel('Number of Components', fontsize=11, fontweight='bold')
|
| 399 |
+
ax3.set_ylabel('Cumulative Variance (%)', fontsize=11, fontweight='bold')
|
| 400 |
+
ax3.set_title('Cumulative Variance', fontsize=12, fontweight='bold')
|
| 401 |
+
ax3.legend(loc='lower right', fontsize=9)
|
| 402 |
+
ax3.grid(True, alpha=0.3)
|
| 403 |
+
|
| 404 |
+
plt.tight_layout()
|
| 405 |
+
plt.savefig(save_path, dpi=200, bbox_inches='tight')
|
| 406 |
+
plt.close()
|
| 407 |
+
|
| 408 |
+
return pca_result, var_ratio
|
| 409 |
+
|
| 410 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 411 |
+
# PLOT 5: KINSHIP HEATMAP
|
| 412 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 413 |
+
|
| 414 |
+
def plot_kinship(genotypes_scaled, save_path):
|
| 415 |
+
"""Kinship matrix heatmap"""
|
| 416 |
+
# Calculate kinship using subset for speed
|
| 417 |
+
n_markers = min(500, genotypes_scaled.shape[1])
|
| 418 |
+
idx = np.random.choice(genotypes_scaled.shape[1], n_markers, replace=False)
|
| 419 |
+
genotypes_subset = genotypes_scaled[:, idx]
|
| 420 |
+
kinship = np.corrcoef(genotypes_subset)
|
| 421 |
+
kinship = (kinship + 1) / 2 # Scale to 0-1
|
| 422 |
+
|
| 423 |
+
# Downsample if too large
|
| 424 |
+
if kinship.shape[0] > 100:
|
| 425 |
+
idx_samples = np.linspace(0, kinship.shape[0]-1, 100, dtype=int)
|
| 426 |
+
kinship = kinship[np.ix_(idx_samples, idx_samples)]
|
| 427 |
+
|
| 428 |
+
fig, ax = plt.subplots(figsize=(10, 8), facecolor=BG_PASTEL)
|
| 429 |
+
ax.set_facecolor(PANEL_PASTEL)
|
| 430 |
|
| 431 |
+
im = ax.imshow(kinship, cmap='RdYlBu_r', aspect='auto', vmin=0, vmax=1)
|
| 432 |
+
ax.set_title('Kinship Matrix', fontsize=14, fontweight='bold')
|
| 433 |
+
ax.set_xlabel('Samples', fontsize=11, fontweight='bold')
|
| 434 |
+
ax.set_ylabel('Samples', fontsize=11, fontweight='bold')
|
| 435 |
|
| 436 |
+
cbar = plt.colorbar(im, ax=ax, shrink=0.8)
|
| 437 |
+
cbar.set_label('Kinship Coefficient', fontsize=11, fontweight='bold')
|
|
|
|
|
|
|
|
|
|
| 438 |
|
| 439 |
+
plt.tight_layout()
|
| 440 |
+
plt.savefig(save_path, dpi=200, bbox_inches='tight')
|
| 441 |
+
plt.close()
|
| 442 |
|
| 443 |
+
return kinship.mean(), kinship.max()
|
| 444 |
|
| 445 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 446 |
+
# PLOT 6: VOLCANO PLOT
|
| 447 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββοΏ½οΏ½ββββββ
|
| 448 |
+
|
| 449 |
+
def plot_volcano(p_values, effects, sig_threshold, save_path):
|
| 450 |
+
"""Volcano plot for effect size vs significance"""
|
| 451 |
+
plt.figure(figsize=(10, 8), facecolor=BG_PASTEL)
|
| 452 |
+
ax = plt.gca()
|
| 453 |
+
ax.set_facecolor(PANEL_PASTEL)
|
| 454 |
|
| 455 |
+
log_p = -np.log10(p_values + 1e-300)
|
| 456 |
+
sig_mask = p_values < sig_threshold
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 457 |
|
| 458 |
+
# Non-significant
|
| 459 |
+
ax.scatter(effects[~sig_mask], log_p[~sig_mask], c=COLORS['primary'],
|
| 460 |
+
s=20, alpha=0.5, label='Non-significant')
|
| 461 |
|
| 462 |
+
# Significant
|
| 463 |
+
if sig_mask.any():
|
| 464 |
+
ax.scatter(effects[sig_mask], log_p[sig_mask], c=COLORS['significant'],
|
| 465 |
+
s=50, alpha=0.8, edgecolors='white', linewidth=0.5, label='Significant')
|
| 466 |
|
| 467 |
+
ax.axhline(-np.log10(sig_threshold), color=COLORS['significant'], linestyle='--', linewidth=1.5)
|
| 468 |
+
ax.axvline(0, color='gray', linestyle='-', linewidth=1, alpha=0.5)
|
|
|
|
|
|
|
| 469 |
|
| 470 |
+
ax.set_xlabel('Effect Size', fontsize=12, fontweight='bold')
|
| 471 |
+
ax.set_ylabel('-logββ(P-value)', fontsize=12, fontweight='bold')
|
| 472 |
+
ax.set_title('Volcano Plot', fontsize=15, fontweight='bold')
|
| 473 |
+
ax.legend(loc='upper left', fontsize=10)
|
| 474 |
+
ax.grid(True, alpha=0.3)
|
| 475 |
|
| 476 |
+
plt.tight_layout()
|
| 477 |
+
plt.savefig(save_path, dpi=200, bbox_inches='tight')
|
| 478 |
+
plt.close()
|
| 479 |
|
| 480 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 481 |
+
# PLOT 7: CHROMOSOME-WIDE DISTRIBUTION
|
| 482 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 483 |
|
| 484 |
+
def plot_chromosome_distribution(p_values, chromosomes, lod_scores, save_path):
|
| 485 |
+
"""Distribution of significant markers across chromosomes"""
|
| 486 |
plt.figure(figsize=(14, 6), facecolor=BG_PASTEL)
|
| 487 |
ax = plt.gca()
|
| 488 |
ax.set_facecolor(PANEL_PASTEL)
|
| 489 |
|
|
|
|
| 490 |
unique_chroms = np.unique(chromosomes)
|
| 491 |
+
chrom_means = []
|
| 492 |
+
chrom_max = []
|
| 493 |
+
|
| 494 |
+
for ch in unique_chroms:
|
| 495 |
+
mask = np.array(chromosomes) == ch
|
| 496 |
+
if mask.any():
|
| 497 |
+
chrom_means.append(-np.log10(p_values[mask] + 1e-300).mean())
|
| 498 |
+
chrom_max.append(lod_scores[mask].max())
|
| 499 |
+
|
| 500 |
+
x = np.arange(len(unique_chroms))
|
| 501 |
+
width = 0.35
|
| 502 |
+
|
| 503 |
+
bars1 = ax.bar(x - width/2, chrom_means, width, label='Mean -logββ(P)',
|
| 504 |
+
color=COLORS['primary'], alpha=0.7, edgecolor='white')
|
| 505 |
+
bars2 = ax.bar(x + width/2, chrom_max, width, label='Max LOD',
|
| 506 |
+
color=COLORS['lod'], alpha=0.7, edgecolor='white')
|
| 507 |
+
|
| 508 |
+
ax.set_xlabel('Chromosome', fontsize=12, fontweight='bold')
|
| 509 |
+
ax.set_ylabel('Score', fontsize=12, fontweight='bold')
|
| 510 |
+
ax.set_title('Chromosome-wise Distribution', fontsize=15, fontweight='bold')
|
| 511 |
+
ax.set_xticks(x)
|
| 512 |
+
ax.set_xticklabels(unique_chroms, rotation=45, ha='right')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 513 |
ax.legend(loc='upper right', fontsize=10)
|
| 514 |
+
ax.grid(True, alpha=0.3, axis='y')
|
| 515 |
|
| 516 |
plt.tight_layout()
|
| 517 |
+
plt.savefig(save_path, dpi=200, bbox_inches='tight')
|
| 518 |
plt.close()
|
| 519 |
|
| 520 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 521 |
+
# PLOT 8: CIRCOS PLOT
|
| 522 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 523 |
+
|
| 524 |
+
def plot_circos(chromosomes, p_values, lod_scores, sig_threshold, save_path):
|
| 525 |
+
"""Circos-style circular plot"""
|
| 526 |
+
plt.figure(figsize=(10, 10), facecolor=BG_PASTEL)
|
| 527 |
+
ax = plt.subplot(111, projection='polar')
|
| 528 |
+
ax.set_facecolor(BG_PASTEL)
|
| 529 |
|
| 530 |
+
unique_chroms = np.unique(chromosomes)
|
| 531 |
+
n_chroms = len(unique_chroms)
|
| 532 |
+
angles = np.linspace(0, 2*np.pi, n_chroms + 1)
|
|
|
|
|
|
|
| 533 |
|
| 534 |
+
# Chromosome arcs
|
| 535 |
+
for i, ch in enumerate(unique_chroms):
|
| 536 |
+
theta_mid = (angles[i] + angles[i+1]) / 2
|
| 537 |
+
ax.bar(theta_mid, 0.15, width=2*np.pi/n_chroms - 0.03,
|
| 538 |
+
bottom=0.85, color=COLORS['chromosome'][i % len(COLORS['chromosome'])],
|
| 539 |
+
alpha=0.8, edgecolor='white')
|
| 540 |
+
ax.text(theta_mid, 0.93, str(ch), ha='center', va='center', fontsize=9, fontweight='bold')
|
| 541 |
|
| 542 |
+
# Markers
|
| 543 |
+
log_p = -np.log10(p_values + 1e-300)
|
| 544 |
+
max_p = log_p.max() if log_p.max() > 0 else 5
|
| 545 |
|
| 546 |
+
for i, ch in enumerate(unique_chroms):
|
| 547 |
+
mask = np.array(chromosomes) == ch
|
| 548 |
+
if mask.sum() == 0:
|
| 549 |
+
continue
|
| 550 |
+
|
| 551 |
+
chrom_p = log_p[mask]
|
| 552 |
+
theta_start = angles[i]
|
| 553 |
+
theta_end = angles[i+1]
|
| 554 |
+
|
| 555 |
+
positions = theta_start + (np.arange(len(chrom_p)) / len(chrom_p)) * (theta_end - theta_start)
|
| 556 |
+
radii = 0.4 + 0.3 * (chrom_p / max_p)
|
| 557 |
+
|
| 558 |
+
colors = [COLORS['significant'] if p < sig_threshold else COLORS['primary']
|
| 559 |
+
for p in p_values[mask]]
|
| 560 |
+
ax.scatter(positions, radii, c=colors, s=8, alpha=0.6, linewidths=0)
|
| 561 |
+
|
| 562 |
+
# Inner circle
|
| 563 |
+
circle = Circle((0, 0), 0.35, transform=ax.transData._b,
|
| 564 |
+
facecolor=PANEL_PASTEL, edgecolor=BORDER_PASTEL, linewidth=2)
|
| 565 |
+
ax.add_patch(circle)
|
| 566 |
+
ax.text(0, 0, 'GWAS\nResults', ha='center', va='center', fontsize=12, fontweight='bold')
|
| 567 |
+
|
| 568 |
+
ax.set_theta_zero_location('N')
|
| 569 |
+
ax.set_theta_direction(-1)
|
| 570 |
+
ax.set_ylim(0, 1.1)
|
| 571 |
+
ax.set_xticks([])
|
| 572 |
+
ax.set_yticks([])
|
| 573 |
+
ax.spines['polar'].set_visible(False)
|
| 574 |
+
|
| 575 |
+
plt.title('Circos Plot', fontsize=15, fontweight='bold', pad=20)
|
| 576 |
+
plt.tight_layout()
|
| 577 |
+
plt.savefig(save_path, dpi=200, bbox_inches='tight')
|
| 578 |
+
plt.close()
|
| 579 |
+
|
| 580 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 581 |
+
# PLOT 9: P-VALUE DISTRIBUTION
|
| 582 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 583 |
+
|
| 584 |
+
def plot_pvalue_distribution(p_values, save_path):
|
| 585 |
+
"""Histogram of p-values"""
|
| 586 |
+
plt.figure(figsize=(10, 6), facecolor=BG_PASTEL)
|
| 587 |
+
ax = plt.gca()
|
| 588 |
+
ax.set_facecolor(PANEL_PASTEL)
|
| 589 |
|
| 590 |
+
ax.hist(p_values, bins=50, color=COLORS['primary'], alpha=0.7, edgecolor='white', density=True)
|
| 591 |
+
ax.axhline(y=1, color=COLORS['significant'], linestyle='--', linewidth=2, alpha=0.7, label='Uniform distribution')
|
| 592 |
+
ax.set_xlabel('P-value', fontsize=12, fontweight='bold')
|
| 593 |
+
ax.set_ylabel('Density', fontsize=12, fontweight='bold')
|
| 594 |
+
ax.set_title('P-value Distribution', fontsize=15, fontweight='bold')
|
| 595 |
+
ax.legend(loc='upper right', fontsize=10)
|
| 596 |
+
ax.grid(True, alpha=0.3)
|
| 597 |
|
| 598 |
+
# Add text about deviation from uniform
|
| 599 |
+
expected_uniform = 1
|
| 600 |
+
observed_mean = np.mean(p_values < 0.05)
|
| 601 |
+
ax.text(0.7, 0.95, f'Proportion p<0.05: {observed_mean:.3f}',
|
| 602 |
+
transform=ax.transAxes, fontsize=10,
|
| 603 |
+
bbox=dict(boxstyle='round', facecolor=BG_PASTEL, alpha=0.8))
|
| 604 |
|
| 605 |
plt.tight_layout()
|
| 606 |
+
plt.savefig(save_path, dpi=200, bbox_inches='tight')
|
| 607 |
plt.close()
|
| 608 |
|
| 609 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 610 |
+
# PLOT 10: EFFECT SIZE DISTRIBUTION
|
| 611 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 612 |
|
| 613 |
+
def plot_effect_distribution(effects, save_path):
|
| 614 |
+
"""Distribution of effect sizes"""
|
| 615 |
+
plt.figure(figsize=(10, 6), facecolor=BG_PASTEL)
|
| 616 |
+
ax = plt.gca()
|
| 617 |
+
ax.set_facecolor(PANEL_PASTEL)
|
| 618 |
|
| 619 |
+
ax.hist(effects, bins=50, color=COLORS['secondary'], alpha=0.7, edgecolor='white')
|
| 620 |
+
ax.axvline(x=0, color=COLORS['significant'], linestyle='--', linewidth=2, alpha=0.7)
|
| 621 |
+
ax.axvline(x=np.mean(effects), color=COLORS['primary'], linestyle='-', linewidth=2,
|
| 622 |
+
alpha=0.7, label=f'Mean: {np.mean(effects):.3f}')
|
| 623 |
|
| 624 |
+
ax.set_xlabel('Effect Size', fontsize=12, fontweight='bold')
|
| 625 |
+
ax.set_ylabel('Frequency', fontsize=12, fontweight='bold')
|
| 626 |
+
ax.set_title('Effect Size Distribution', fontsize=15, fontweight='bold')
|
| 627 |
+
ax.legend(loc='upper right', fontsize=10)
|
| 628 |
+
ax.grid(True, alpha=0.3)
|
| 629 |
|
| 630 |
+
plt.tight_layout()
|
| 631 |
+
plt.savefig(save_path, dpi=200, bbox_inches='tight')
|
| 632 |
+
plt.close()
|
| 633 |
+
|
| 634 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 635 |
+
# GWAS MODELS
|
| 636 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 637 |
+
|
| 638 |
+
def run_linear_regression(genotypes, phenotypes):
|
| 639 |
+
"""Linear regression GWAS - vectorized"""
|
| 640 |
+
n_markers = genotypes.shape[1]
|
| 641 |
+
pvals = np.ones(n_markers)
|
| 642 |
+
effects = np.zeros(n_markers)
|
| 643 |
+
lod = np.zeros(n_markers)
|
| 644 |
|
| 645 |
+
X_centered = genotypes - genotypes.mean(axis=0)
|
| 646 |
+
y_centered = phenotypes - phenotypes.mean()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 647 |
|
| 648 |
+
xy = np.dot(y_centered, X_centered)
|
| 649 |
+
xx = np.sum(X_centered ** 2, axis=0)
|
| 650 |
+
valid = xx > 1e-10
|
|
|
|
| 651 |
|
| 652 |
+
effects[valid] = xy[valid] / xx[valid]
|
|
|
|
| 653 |
|
| 654 |
+
n = len(phenotypes)
|
| 655 |
+
for i in np.where(valid)[0]:
|
| 656 |
+
y_pred = effects[i] * X_centered[:, i]
|
| 657 |
+
resid = y_centered - y_pred
|
| 658 |
+
rss = np.sum(resid ** 2)
|
| 659 |
+
t_stat = effects[i] / (np.sqrt(rss / (n - 2)) / np.sqrt(xx[i]) + 1e-10)
|
| 660 |
+
pvals[i] = 2 * (1 - stats.t.cdf(abs(t_stat), n - 2))
|
| 661 |
+
lod[i] = -np.log10(pvals[i] + 1e-300)
|
| 662 |
+
|
| 663 |
+
return pvals, effects, lod
|
| 664 |
+
|
| 665 |
+
def run_random_forest(genotypes, phenotypes):
|
| 666 |
+
"""Random Forest for feature importance"""
|
| 667 |
+
rf = RandomForestRegressor(n_estimators=50, random_state=42, n_jobs=-1, max_depth=10)
|
| 668 |
+
rf.fit(genotypes, phenotypes)
|
| 669 |
|
| 670 |
+
importance = rf.feature_importances_
|
| 671 |
+
imp_rank = np.argsort(importance)[::-1]
|
| 672 |
+
pvals = np.ones(len(importance))
|
| 673 |
+
for i, idx in enumerate(imp_rank):
|
| 674 |
+
pvals[idx] = (i + 1) / len(importance)
|
| 675 |
+
lod = -np.log10(pvals + 1e-300)
|
| 676 |
|
| 677 |
+
return pvals, importance, lod, rf.score(genotypes, phenotypes)
|
| 678 |
|
| 679 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 680 |
# MAIN PIPELINE
|
| 681 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 682 |
|
| 683 |
+
def run_gwas_pipeline(input_file, sample_missing, marker_missing, maf_threshold):
|
| 684 |
+
"""Complete GWAS pipeline with 10+ plots"""
|
|
|
|
|
|
|
| 685 |
|
| 686 |
if input_file is None:
|
| 687 |
+
return ("Please upload a CSV file", [None]*12)
|
| 688 |
|
| 689 |
try:
|
| 690 |
+
# Create directories
|
| 691 |
temp_dir = tempfile.mkdtemp()
|
| 692 |
results_dir = os.path.join(temp_dir, 'results')
|
| 693 |
plots_dir = os.path.join(results_dir, 'plots')
|
| 694 |
os.makedirs(plots_dir, exist_ok=True)
|
| 695 |
|
| 696 |
+
# Process data with proper imputation
|
| 697 |
+
genotypes, genotypes_scaled, phenotypes, sample_ids, chromosomes, positions = process_data(
|
| 698 |
input_file.name, sample_missing/100, marker_missing/100, maf_threshold/100
|
| 699 |
)
|
| 700 |
|
| 701 |
n_samples, n_markers = genotypes.shape
|
| 702 |
bonf_threshold = 0.05 / n_markers
|
| 703 |
|
| 704 |
+
# Run GWAS models
|
| 705 |
+
print("Running Linear Regression...")
|
| 706 |
+
pvals, effects, lod = run_linear_regression(genotypes, phenotypes)
|
| 707 |
|
| 708 |
+
print("Running Random Forest...")
|
| 709 |
+
rf_pvals, rf_importance, rf_lod, rf_score = run_random_forest(genotypes_scaled, phenotypes)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 710 |
|
| 711 |
+
# Generate all 10 plots
|
| 712 |
+
plots = {}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 713 |
|
| 714 |
+
# Plot 1: Manhattan
|
| 715 |
+
plots['manhattan'] = os.path.join(plots_dir, 'manhattan.png')
|
| 716 |
+
n_sig = plot_manhattan(pvals, chromosomes, lod, bonf_threshold, plots['manhattan'])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 717 |
|
| 718 |
+
# Plot 2: QQ
|
| 719 |
+
plots['qq'] = os.path.join(plots_dir, 'qq.png')
|
| 720 |
+
lambda_gc = plot_qq(pvals, plots['qq'])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 721 |
|
| 722 |
+
# Plot 3: LD Decay
|
| 723 |
+
plots['ld'] = os.path.join(plots_dir, 'ld_decay.png')
|
| 724 |
+
mean_ld = plot_ld_decay(genotypes, chromosomes, positions, plots['ld'])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 725 |
|
| 726 |
+
# Plot 4: PCA
|
| 727 |
+
plots['pca'] = os.path.join(plots_dir, 'pca.png')
|
| 728 |
+
pca_result, var_ratio = plot_pca(genotypes_scaled, phenotypes, plots['pca'])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 729 |
|
| 730 |
+
# Plot 5: Kinship
|
| 731 |
+
plots['kinship'] = os.path.join(plots_dir, 'kinship.png')
|
| 732 |
+
mean_kinship, max_kinship = plot_kinship(genotypes_scaled, plots['kinship'])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 733 |
|
| 734 |
+
# Plot 6: Volcano
|
| 735 |
+
plots['volcano'] = os.path.join(plots_dir, 'volcano.png')
|
| 736 |
+
plot_volcano(pvals, effects, bonf_threshold, plots['volcano'])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 737 |
|
| 738 |
+
# Plot 7: Chromosome Distribution
|
| 739 |
+
plots['chrom_dist'] = os.path.join(plots_dir, 'chromosome_distribution.png')
|
| 740 |
+
plot_chromosome_distribution(pvals, chromosomes, lod, plots['chrom_dist'])
|
| 741 |
+
|
| 742 |
+
# Plot 8: Circos
|
| 743 |
+
plots['circos'] = os.path.join(plots_dir, 'circos.png')
|
| 744 |
+
plot_circos(chromosomes, pvals, lod, bonf_threshold, plots['circos'])
|
| 745 |
+
|
| 746 |
+
# Plot 9: P-value Distribution
|
| 747 |
+
plots['pval_dist'] = os.path.join(plots_dir, 'pvalue_distribution.png')
|
| 748 |
+
plot_pvalue_distribution(pvals, plots['pval_dist'])
|
| 749 |
+
|
| 750 |
+
# Plot 10: Effect Distribution
|
| 751 |
+
plots['effect_dist'] = os.path.join(plots_dir, 'effect_distribution.png')
|
| 752 |
+
plot_effect_distribution(effects, plots['effect_dist'])
|
| 753 |
|
| 754 |
# Create results DataFrame
|
| 755 |
results_df = pd.DataFrame({
|
| 756 |
'Marker': [f'M{i+1}' for i in range(n_markers)],
|
| 757 |
+
'Chromosome': chromosomes,
|
| 758 |
+
'Position': positions,
|
| 759 |
+
'P-value': pvals,
|
| 760 |
+
'LOD': lod,
|
| 761 |
+
'Effect_Size': effects,
|
| 762 |
+
'RF_Importance': rf_importance,
|
| 763 |
+
'Significant': pvals < bonf_threshold
|
| 764 |
})
|
| 765 |
+
results_df = results_df.sort_values('P-value')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 766 |
results_df.to_csv(os.path.join(results_dir, 'gwas_results.csv'), index=False)
|
| 767 |
|
| 768 |
+
# Create ZIP file
|
| 769 |
+
zip_path = os.path.join(temp_dir, 'GWAS_Complete_Results.zip')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 770 |
with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf:
|
| 771 |
for root, _, files in os.walk(results_dir):
|
| 772 |
for f in files:
|
| 773 |
zf.write(os.path.join(root, f), os.path.relpath(os.path.join(root, f), temp_dir))
|
| 774 |
|
| 775 |
# Generate summary
|
|
|
|
|
|
|
|
|
|
| 776 |
summary = f"""
|
| 777 |
## β
GWAS Analysis Complete!
|
| 778 |
|
| 779 |
+
### π Dataset Summary
|
| 780 |
+
| Metric | Value |
|
| 781 |
+
|--------|-------|
|
| 782 |
+
| Samples | **{n_samples}** |
|
| 783 |
+
| Markers | **{n_markers:,}** |
|
| 784 |
+
| Chromosomes | **{len(np.unique(chromosomes))}** |
|
| 785 |
+
|
| 786 |
+
### π¬ Key Findings
|
| 787 |
+
| Metric | Value |
|
| 788 |
+
|--------|-------|
|
| 789 |
+
| Significant Markers (Bonferroni) | **{n_sig}** |
|
| 790 |
+
| Genomic Inflation Factor (Ξ») | **{lambda_gc:.3f}** |
|
| 791 |
+
| Mean LD (rΒ²) | **{mean_ld:.3f}** |
|
| 792 |
+
| Mean Kinship | **{mean_kinship:.3f}** |
|
| 793 |
+
|
| 794 |
+
### π Model Performance
|
| 795 |
+
| Model | RΒ² Score |
|
| 796 |
+
|-------|----------|
|
| 797 |
+
| Linear Regression | {r2_score(phenotypes, np.dot(genotypes, effects)):.3f} |
|
| 798 |
+
| Random Forest | {rf_score:.3f} |
|
| 799 |
+
|
| 800 |
+
### π Top 5 Associated Markers
|
| 801 |
+
{results_df.head(5)[['Marker', 'Chromosome', 'LOD', 'Effect_Size']].to_markdown(index=False)}
|
| 802 |
+
|
| 803 |
+
### π Output Files (ZIP Archive)
|
| 804 |
+
- `gwas_results.csv` - Complete association results
|
| 805 |
+
- `plots/manhattan.png` - Manhattan plot with LOD scores
|
| 806 |
+
- `plots/qq.png` - Q-Q plot with genomic inflation
|
| 807 |
+
- `plots/ld_decay.png` - LD decay analysis
|
| 808 |
+
- `plots/pca.png` - Population structure PCA
|
| 809 |
+
- `plots/kinship.png` - Kinship matrix heatmap
|
| 810 |
+
- `plots/volcano.png` - Volcano plot
|
| 811 |
+
- `plots/chromosome_distribution.png` - Chromosome-wise distribution
|
| 812 |
+
- `plots/circos.png` - Circular visualization
|
| 813 |
+
- `plots/pvalue_distribution.png` - P-value histogram
|
| 814 |
+
- `plots/effect_distribution.png` - Effect size distribution
|
| 815 |
+
|
| 816 |
+
### π Interpretation
|
| 817 |
+
- **Population Structure**: {'Well-controlled' if lambda_gc < 1.05 else 'Consider including more PCs'}
|
| 818 |
+
- **LD Decay**: {'Fast decay indicates diverse germplasm' if mean_ld < 0.3 else 'Slow decay suggests related individuals'}
|
| 819 |
+
- **Significant Associations**: {n_sig} markers show strong association with the trait
|
| 820 |
"""
|
| 821 |
|
| 822 |
+
return (summary,
|
| 823 |
+
plots['manhattan'], plots['qq'], plots['ld'], plots['pca'],
|
| 824 |
+
plots['kinship'], plots['volcano'], plots['chrom_dist'],
|
| 825 |
+
plots['circos'], plots['pval_dist'], plots['effect_dist'], zip_path)
|
| 826 |
|
| 827 |
except Exception as e:
|
| 828 |
import traceback
|
| 829 |
+
error_msg = f"## β Error\n```\n{str(e)}\n\n{traceback.format_exc()}\n```"
|
| 830 |
+
return (error_msg, [None]*11)
|
| 831 |
|
| 832 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 833 |
# GRADIO INTERFACE
|
| 834 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 835 |
|
| 836 |
+
with gr.Blocks(css=CSS, title="Complete GWAS Platform", theme=gr.themes.Soft()) as app:
|
| 837 |
|
| 838 |
gr.HTML("""
|
| 839 |
<div class="main-header">
|
| 840 |
+
<h1>𧬠Complete GWAS Analysis Platform</h1>
|
| 841 |
+
<p>10+ Publication-Quality Plots | PCA | Kinship | LD Analysis | Multi-Model</p>
|
| 842 |
</div>
|
| 843 |
""")
|
| 844 |
|
| 845 |
with gr.Row():
|
| 846 |
with gr.Column(scale=1):
|
| 847 |
gr.HTML('<div class="section-header">π Data Input</div>')
|
| 848 |
+
input_file = gr.File(label="Upload CSV File", file_types=[".csv"])
|
| 849 |
|
| 850 |
gr.HTML('<div class="section-header">βοΈ Quality Control</div>')
|
| 851 |
+
sample_missing = gr.Slider(10, 80, value=50, step=5, label="Sample Missing Rate (%)")
|
| 852 |
+
marker_missing = gr.Slider(10, 80, value=50, step=5, label="Marker Missing Rate (%)")
|
| 853 |
+
maf_threshold = gr.Slider(1, 20, value=5, step=1, label="MAF Threshold (%)")
|
| 854 |
|
| 855 |
+
run_btn = gr.Button("π Run Complete GWAS Analysis", variant="primary", elem_classes=["run-btn"])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 856 |
|
| 857 |
+
gr.HTML("""
|
| 858 |
+
<div class="card">
|
| 859 |
+
<h3>π CSV Format Required</h3>
|
| 860 |
+
<p><strong>Row 1:</strong> ID | Phenotype | Marker1 (chr:pos) | Marker2 | ...</p>
|
| 861 |
+
<p><strong>Row 2+:</strong> Sample1 | value | 0/1/2 | 0/1/2 | ...</p>
|
| 862 |
+
<p><strong>Genotype coding:</strong> 0=AA, 1=Aa, 2=aa</p>
|
| 863 |
+
<p><strong>Example:</strong> "1:1234567" for chromosome 1 at position 1,234,567 bp</p>
|
| 864 |
+
</div>
|
| 865 |
+
""")
|
| 866 |
|
| 867 |
with gr.Column(scale=2):
|
| 868 |
+
gr.HTML('<div class="section-header">π Analysis Summary</div>')
|
| 869 |
+
summary_out = gr.Markdown("Ready to analyze. Upload a CSV file and click Run.")
|
| 870 |
+
|
| 871 |
+
gr.HTML('<div class="section-header">π Visualization Gallery (10+ Plots)</div>')
|
| 872 |
+
|
| 873 |
+
with gr.Row():
|
| 874 |
+
with gr.Column():
|
| 875 |
+
manhattan_out = gr.Image(label="1. Manhattan Plot with LOD", elem_classes=["plot-container"])
|
| 876 |
+
pca_out = gr.Image(label="4. PCA Population Structure", elem_classes=["plot-container"])
|
| 877 |
+
volcano_out = gr.Image(label="6. Volcano Plot", elem_classes=["plot-container"])
|
| 878 |
+
circos_out = gr.Image(label="8. Circos Plot", elem_classes=["plot-container"])
|
| 879 |
+
effect_out = gr.Image(label="10. Effect Size Distribution", elem_classes=["plot-container"])
|
| 880 |
+
|
| 881 |
+
with gr.Row():
|
| 882 |
+
with gr.Column():
|
| 883 |
+
qq_out = gr.Image(label="2. Q-Q Plot", elem_classes=["plot-container"])
|
| 884 |
+
kinship_out = gr.Image(label="5. Kinship Matrix", elem_classes=["plot-container"])
|
| 885 |
+
chrom_dist_out = gr.Image(label="7. Chromosome Distribution", elem_classes=["plot-container"])
|
| 886 |
+
pval_dist_out = gr.Image(label="9. P-value Distribution", elem_classes=["plot-container"])
|
| 887 |
+
|
| 888 |
+
with gr.Row():
|
| 889 |
+
with gr.Column():
|
| 890 |
+
ld_out = gr.Image(label="3. LD Decay Plot (Mb)", elem_classes=["plot-container"])
|
| 891 |
+
|
| 892 |
+
gr.HTML('<div class="section-header">β¬οΈ Download Results</div>')
|
| 893 |
+
download_out = gr.File(label="Download Complete Results (ZIP)")
|
| 894 |
|
| 895 |
run_btn.click(
|
| 896 |
fn=run_gwas_pipeline,
|
| 897 |
+
inputs=[input_file, sample_missing, marker_missing, maf_threshold],
|
| 898 |
+
outputs=[summary_out, manhattan_out, qq_out, ld_out, pca_out,
|
| 899 |
+
kinship_out, volcano_out, chrom_dist_out, circos_out,
|
| 900 |
+
pval_dist_out, effect_out, download_out]
|
| 901 |
)
|
| 902 |
|
| 903 |
gr.HTML("""
|
| 904 |
<footer>
|
| 905 |
+
<p><strong>GWAS Pipeline v14.0</strong> | 10+ Plots | Times New Roman | Soft Pastel Theme | Production-Ready</p>
|
| 906 |
+
<p>β
No NaN errors | β
Proper imputation | β
All bugs fixed</p>
|
| 907 |
</footer>
|
| 908 |
""")
|
| 909 |
|