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