Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,12 +1,14 @@
|
|
| 1 |
# -*- coding: utf-8 -*-
|
| 2 |
"""
|
| 3 |
-
|
| 4 |
Features:
|
| 5 |
-
-
|
| 6 |
-
- LOD score
|
| 7 |
-
-
|
| 8 |
-
-
|
| 9 |
-
-
|
|
|
|
|
|
|
| 10 |
"""
|
| 11 |
|
| 12 |
import gradio as gr
|
|
@@ -16,86 +18,94 @@ import matplotlib
|
|
| 16 |
matplotlib.use('Agg')
|
| 17 |
import matplotlib.pyplot as plt
|
| 18 |
import matplotlib.patches as mpatches
|
|
|
|
|
|
|
| 19 |
from matplotlib.collections import LineCollection
|
|
|
|
| 20 |
import seaborn as sns
|
| 21 |
from scipy import stats
|
| 22 |
-
from scipy.
|
| 23 |
-
import os, warnings, tempfile, zipfile
|
| 24 |
from sklearn.linear_model import ElasticNetCV, LassoCV, RidgeCV
|
| 25 |
from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor
|
| 26 |
from sklearn.preprocessing import StandardScaler
|
| 27 |
-
from sklearn.feature_selection import mutual_info_regression, f_regression
|
| 28 |
from sklearn.model_selection import cross_val_score, KFold
|
| 29 |
-
from sklearn.metrics import
|
| 30 |
import statsmodels.api as sm
|
| 31 |
from statsmodels.formula.api import mixedlm
|
| 32 |
-
from statsmodels.regression.linear_model import OLS, WLS
|
| 33 |
-
import warnings
|
| 34 |
warnings.filterwarnings('ignore')
|
| 35 |
|
| 36 |
-
# ═══════════════════════════════════════════════
|
| 37 |
-
#
|
| 38 |
-
# ═══════════════════════════════════════════════
|
| 39 |
-
BG = "#
|
| 40 |
-
PANEL = "#
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
|
| 52 |
CHROM_PALETTE = [
|
| 53 |
-
"#
|
| 54 |
-
"#
|
| 55 |
-
"#
|
| 56 |
-
"#
|
| 57 |
-
"#
|
| 58 |
]
|
| 59 |
|
| 60 |
-
def
|
| 61 |
plt.rcParams.update({
|
| 62 |
'figure.facecolor': BG,
|
| 63 |
'axes.facecolor': PANEL,
|
| 64 |
-
'axes.edgecolor':
|
| 65 |
-
'axes.labelcolor':
|
| 66 |
-
'axes.titlecolor':
|
| 67 |
-
'xtick.color':
|
| 68 |
-
'ytick.color':
|
| 69 |
-
'text.color':
|
| 70 |
-
'grid.color':
|
| 71 |
-
'grid.linewidth': 0.
|
| 72 |
'figure.dpi': 150,
|
| 73 |
'font.family': 'DejaVu Sans',
|
| 74 |
'axes.spines.top': False,
|
| 75 |
'axes.spines.right': False,
|
| 76 |
-
'
|
| 77 |
-
'
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
})
|
| 79 |
|
| 80 |
-
# ══════════════════════════════════════
|
| 81 |
-
#
|
| 82 |
-
# ═══════════════════════════════════════════════
|
| 83 |
|
| 84 |
-
def
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
set_pastel_style()
|
| 88 |
unique_chroms = sorted(set(chromosomes),
|
| 89 |
key=lambda x: (int(x) if str(x).isdigit() else 999, str(x)))
|
| 90 |
log_p = -np.log10(np.array(p_values) + 1e-300)
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
GAP = max(
|
| 94 |
x_pos = np.zeros(len(marker_names))
|
| 95 |
-
|
| 96 |
for i, c in enumerate(chromosomes):
|
| 97 |
chrom_to_idx.setdefault(c, []).append(i)
|
| 98 |
-
|
| 99 |
offset = 0
|
| 100 |
for ch in unique_chroms:
|
| 101 |
idxs = chrom_to_idx.get(ch, [])
|
|
@@ -104,847 +114,1291 @@ def plot_manhattan_with_lod(marker_names, chromosomes, p_values, lod_scores,
|
|
| 104 |
x_pos[idx] = offset + r
|
| 105 |
chrom_centers[ch] = offset + (len(idxs) - 1) / 2
|
| 106 |
offset += len(idxs) + GAP
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 122 |
for ci, ch in enumerate(unique_chroms):
|
| 123 |
idxs = chrom_to_idx.get(ch, [])
|
| 124 |
if not idxs: continue
|
| 125 |
col = CHROM_PALETTE[ci % len(CHROM_PALETTE)]
|
| 126 |
normal = [i for i in idxs if i not in sig_set]
|
| 127 |
sel = [i for i in idxs if i in sig_set]
|
| 128 |
-
|
| 129 |
if normal:
|
| 130 |
-
ax1.scatter(x_pos[normal], log_p[normal],
|
| 131 |
-
|
| 132 |
if sel:
|
| 133 |
-
ax1.scatter(x_pos[sel], log_p[sel],
|
| 134 |
-
|
| 135 |
-
ax1.scatter(x_pos[sel], log_p[sel],
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
ax1.axhline(bonf_thresh, color=
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
lod_array = np.array(lod_scores)
|
| 146 |
-
ax1_twin.scatter(x_pos, lod_array, c=TEAL_C, s=8, alpha=0.4,
|
| 147 |
-
marker='x', label='LOD Score', zorder=1)
|
| 148 |
-
ax1_twin.set_ylabel('LOD Score', fontsize=12, color=TEAL_C, fontweight='bold')
|
| 149 |
-
ax1_twin.tick_params(axis='y', colors=TEAL_C)
|
| 150 |
-
ax1_twin.set_ylim(0, max(lod_array) * 1.1 if len(lod_array) > 0 else 5)
|
| 151 |
-
|
| 152 |
ax1.set_xlim(-GAP, offset)
|
| 153 |
-
ax1.set_ylim(
|
| 154 |
-
ax1.set_ylabel('−log₁₀(P-value)', fontsize=13, color=
|
| 155 |
-
ax1.
|
| 156 |
-
|
| 157 |
-
ax1.
|
| 158 |
-
ax1.
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
ax2.axhline(3, color=GOLD_C, ls='--', lw=1.5, alpha=0.8, label='LOD ≥ 3')
|
| 172 |
ax2.set_xlim(-GAP, offset)
|
| 173 |
-
ax2.
|
| 174 |
-
ax2.
|
| 175 |
-
ax2.
|
| 176 |
-
ax2.
|
| 177 |
-
ax2.legend(
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 181 |
plt.close(fig)
|
| 182 |
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
|
|
|
|
|
|
|
|
|
| 186 |
unique_chroms = sorted(set(chromosomes),
|
| 187 |
key=lambda x: (int(x) if str(x).isdigit() else 999, str(x)))
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
chrom_stats = {}
|
| 193 |
-
|
| 194 |
for ch in unique_chroms:
|
| 195 |
idxs = [i for i, c in enumerate(chromosomes) if c == ch]
|
| 196 |
if len(idxs) < 4: continue
|
| 197 |
if len(idxs) > max_m:
|
| 198 |
idxs = sorted(np.random.choice(idxs, max_m, replace=False))
|
| 199 |
-
|
| 200 |
G = genotypes[:, idxs].copy()
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
|
|
|
|
|
|
|
|
|
| 204 |
for i in range(len(idxs)):
|
| 205 |
-
for j in range(i+1, min(i+
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
# Calculate r²
|
| 209 |
r = np.corrcoef(G[:, i], G[:, j])[0, 1]
|
| 210 |
r2 = r**2 if not np.isnan(r) else 0
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
freq2 = np.mean(col2) / 2
|
| 216 |
-
|
| 217 |
-
# Simplified D' calculation
|
| 218 |
-
p11 = np.mean((col1 == 2) & (col2 == 2)) / 2
|
| 219 |
D = p11 - freq1 * freq2
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
all_r2.append(r2)
|
| 225 |
-
all_dprime.append(
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 267 |
try:
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
|
|
|
| 274 |
except:
|
| 275 |
pass
|
| 276 |
-
|
| 277 |
-
ax.
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
ax.
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
bin_stds_dprime.append(np.std(dprime_values[mask]) / np.sqrt(mask.sum()))
|
| 309 |
-
|
| 310 |
-
ax.errorbar(bin_centers, bin_means_dprime, yerr=bin_stds_dprime,
|
| 311 |
-
fmt='o-', color=TEAL_C, capsize=3, capthick=1,
|
| 312 |
-
markersize=4, linewidth=1.5, alpha=0.7)
|
| 313 |
-
ax.axhline(0.5, color=RED_C, ls='--', lw=1.3, alpha=0.8, label="D'=0.5")
|
| 314 |
-
|
| 315 |
-
ax.set_xlabel('Distance (kb)', fontsize=12, color=TEXT_C, fontweight='bold')
|
| 316 |
-
ax.set_ylabel("Mean D'", fontsize=12, color=TEXT_C, fontweight='bold')
|
| 317 |
-
ax.set_title("Linkage Disequilibrium (D')", fontsize=14, color=TEXT_C, fontweight='bold')
|
| 318 |
-
ax.set_ylim(0, 1)
|
| 319 |
-
ax.legend(fontsize=9, facecolor=BG, edgecolor=GRID_C)
|
| 320 |
-
ax.grid(True, color=GRID_C, lw=0.8)
|
| 321 |
-
|
| 322 |
-
# Plot 3: Chromosome-specific LD
|
| 323 |
ax = axes[2]
|
| 324 |
ax.set_facecolor(PANEL)
|
| 325 |
-
if
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
ax.
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
plt.tight_layout(pad=2)
|
| 349 |
-
plt.savefig(save_path, dpi=
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 350 |
plt.close(fig)
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
fig, axes = plt.subplots(2,
|
| 359 |
-
|
| 360 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 361 |
ax = axes[0, 0]
|
| 362 |
ax.set_facecolor(PANEL)
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
for
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
ax.set_xticks(range(len(models)))
|
| 376 |
-
ax.set_yticks(range(len(models)))
|
| 377 |
-
ax.set_xticklabels(model_names, rotation=45, ha='right', fontsize=9)
|
| 378 |
-
ax.set_yticklabels(model_names, fontsize=9)
|
| 379 |
-
|
| 380 |
-
for i in range(len(models)):
|
| 381 |
-
for j in range(len(models)):
|
| 382 |
-
ax.text(j, i, f'{corr_matrix[i, j]:.2f}',
|
| 383 |
-
ha='center', va='center', color='white' if abs(corr_matrix[i, j]) > 0.6 else 'black')
|
| 384 |
-
|
| 385 |
-
plt.colorbar(im, ax=ax, shrink=0.8)
|
| 386 |
-
ax.set_title('P-value Correlations Between Models', fontsize=12, fontweight='bold')
|
| 387 |
-
|
| 388 |
-
# 2. Effect size distribution
|
| 389 |
ax = axes[0, 1]
|
| 390 |
ax.set_facecolor(PANEL)
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
|
| 398 |
-
|
| 399 |
-
|
| 400 |
-
|
| 401 |
-
|
| 402 |
-
|
| 403 |
-
|
| 404 |
-
|
| 405 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 406 |
ax = axes[1, 0]
|
| 407 |
ax.set_facecolor(PANEL)
|
| 408 |
-
|
| 409 |
-
|
| 410 |
-
|
| 411 |
-
|
| 412 |
-
|
| 413 |
-
|
| 414 |
-
|
| 415 |
-
|
| 416 |
-
|
| 417 |
-
|
| 418 |
-
|
| 419 |
-
|
| 420 |
-
|
| 421 |
-
|
| 422 |
-
|
| 423 |
-
|
| 424 |
-
# 4. Runtime comparison
|
| 425 |
ax = axes[1, 1]
|
| 426 |
ax.set_facecolor(PANEL)
|
| 427 |
-
|
| 428 |
-
|
| 429 |
-
|
| 430 |
-
|
| 431 |
-
|
| 432 |
-
|
| 433 |
-
|
| 434 |
-
|
| 435 |
-
|
| 436 |
-
|
| 437 |
-
|
| 438 |
-
|
| 439 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 440 |
plt.close(fig)
|
| 441 |
|
| 442 |
-
# ═══════════════════════════════════════════════
|
| 443 |
-
#
|
| 444 |
-
# ═══════════════════════════════════════════════
|
| 445 |
-
|
| 446 |
-
def
|
| 447 |
-
|
| 448 |
-
|
| 449 |
-
|
| 450 |
-
|
| 451 |
-
|
| 452 |
-
|
| 453 |
-
|
| 454 |
-
|
| 455 |
-
|
| 456 |
-
|
| 457 |
-
|
| 458 |
-
|
| 459 |
-
|
| 460 |
-
|
| 461 |
-
|
| 462 |
-
|
| 463 |
-
|
| 464 |
-
|
| 465 |
-
|
| 466 |
-
|
| 467 |
-
|
| 468 |
-
|
| 469 |
-
|
| 470 |
-
|
| 471 |
-
|
| 472 |
-
|
| 473 |
-
|
| 474 |
-
|
| 475 |
-
|
| 476 |
-
|
| 477 |
-
|
| 478 |
-
|
| 479 |
-
|
| 480 |
-
|
| 481 |
-
|
| 482 |
-
|
| 483 |
-
|
| 484 |
-
|
| 485 |
-
|
| 486 |
-
|
| 487 |
-
|
| 488 |
-
|
| 489 |
-
|
| 490 |
-
|
| 491 |
-
|
| 492 |
-
|
| 493 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 494 |
scaler = StandardScaler()
|
| 495 |
-
|
| 496 |
-
|
| 497 |
-
|
| 498 |
-
|
| 499 |
-
|
| 500 |
-
|
| 501 |
-
|
| 502 |
-
|
| 503 |
-
|
| 504 |
-
|
| 505 |
-
|
| 506 |
-
|
| 507 |
-
|
| 508 |
-
|
| 509 |
-
|
| 510 |
-
|
| 511 |
-
|
| 512 |
-
|
| 513 |
-
|
| 514 |
-
bootstrap_coefs = np.array(bootstrap_coefs)
|
| 515 |
-
for i in range(len(coefficients)):
|
| 516 |
-
if np.std(bootstrap_coefs[:, i]) > 0:
|
| 517 |
-
z_score = abs(coefficients[i]) / (np.std(bootstrap_coefs[:, i]) + 1e-10)
|
| 518 |
-
pvals[i] = 2 * (1 - stats.norm.cdf(z_score))
|
| 519 |
-
|
| 520 |
-
return pvals, coefficients
|
| 521 |
-
|
| 522 |
-
def machine_learning_gwas(genotypes, phenotypes, model_type='rf'):
|
| 523 |
-
"""ML-based GWAS with feature importance"""
|
| 524 |
scaler = StandardScaler()
|
| 525 |
-
|
| 526 |
-
|
| 527 |
-
|
| 528 |
-
|
| 529 |
-
|
| 530 |
-
|
| 531 |
-
|
| 532 |
-
|
| 533 |
-
|
| 534 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 535 |
kf = KFold(n_splits=5, shuffle=True, random_state=42)
|
| 536 |
-
|
| 537 |
-
|
| 538 |
-
|
| 539 |
-
|
| 540 |
-
|
| 541 |
-
|
| 542 |
-
|
| 543 |
-
|
| 544 |
-
y_pred = model.predict(X_val)
|
| 545 |
-
cv_scores.append(r2_score(y_val, y_pred))
|
| 546 |
-
importance_scores.append(model.feature_importances_)
|
| 547 |
-
|
| 548 |
-
# Average importance across folds
|
| 549 |
-
avg_importance = np.mean(importance_scores, axis=0)
|
| 550 |
-
|
| 551 |
-
# Convert importance to p-values via permutation (simplified)
|
| 552 |
n_perm = 50
|
| 553 |
-
|
| 554 |
-
|
| 555 |
-
|
| 556 |
-
|
| 557 |
-
|
| 558 |
-
|
| 559 |
-
|
| 560 |
-
pvals
|
| 561 |
-
|
| 562 |
-
|
| 563 |
-
|
| 564 |
-
|
| 565 |
-
|
| 566 |
-
|
| 567 |
-
|
| 568 |
-
|
| 569 |
-
|
| 570 |
-
|
| 571 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 572 |
df = pd.read_csv(filepath, header=0, dtype=str)
|
| 573 |
-
|
| 574 |
-
# Identify marker columns (everything after col 0=ID, col 1=Phenotype)
|
| 575 |
marker_cols = df.columns[2:].tolist()
|
| 576 |
-
|
| 577 |
-
# First row = chromosome assignments for markers
|
| 578 |
chr_row = df.iloc[0]
|
| 579 |
-
chromosome_dict = {}
|
| 580 |
-
|
| 581 |
-
|
| 582 |
for m in marker_cols:
|
| 583 |
val = str(chr_row[m]).strip()
|
| 584 |
-
# Check if contains position info (format: "chr:pos" or "chr_pos" or just "chr")
|
| 585 |
if ':' in val:
|
| 586 |
parts = val.split(':')
|
| 587 |
chromosome_dict[m] = parts[0]
|
| 588 |
-
|
| 589 |
-
|
| 590 |
-
position_dict[m] = float(parts[1])
|
| 591 |
-
except:
|
| 592 |
-
position_dict[m] = 0
|
| 593 |
-
elif '_' in val and len(val.split('_')) > 1:
|
| 594 |
-
parts = val.split('_')
|
| 595 |
-
chromosome_dict[m] = parts[0]
|
| 596 |
-
if len(parts) > 1 and parts[1].replace('.', '').isdigit():
|
| 597 |
-
try:
|
| 598 |
-
position_dict[m] = float(parts[1])
|
| 599 |
-
except:
|
| 600 |
-
position_dict[m] = 0
|
| 601 |
else:
|
| 602 |
-
|
| 603 |
-
if val.endswith('.0'):
|
| 604 |
-
val = val[:-2]
|
| 605 |
chromosome_dict[m] = val
|
| 606 |
-
position_dict[m] = 0
|
| 607 |
-
|
| 608 |
-
|
| 609 |
-
|
| 610 |
-
|
| 611 |
-
|
| 612 |
-
phenotypes = pd.to_numeric(df_samples.iloc[:, 1], errors='coerce').values
|
| 613 |
-
|
| 614 |
-
# Genotype matrix
|
| 615 |
-
geno_raw = df_samples[marker_cols].apply(pd.to_numeric, errors='coerce')
|
| 616 |
-
geno_raw = geno_raw.replace(-1, np.nan)
|
| 617 |
genotypes = geno_raw.values
|
| 618 |
-
|
| 619 |
-
|
| 620 |
-
|
| 621 |
return sample_ids, phenotypes, genotypes, marker_cols, chromosome_dict, positions
|
| 622 |
|
| 623 |
-
# ═══════════════════════════════════════════════
|
| 624 |
-
# MAIN ANALYSIS
|
| 625 |
-
# ═══════════════════════════════════════════════
|
| 626 |
|
| 627 |
-
def
|
| 628 |
-
|
| 629 |
-
include_enet, include_rf, include_gb):
|
| 630 |
-
"""Enhanced MTA analysis with multiple models"""
|
| 631 |
try:
|
| 632 |
if input_file is None:
|
| 633 |
return ("⚠️ Please upload a CSV file.", None, None, None, None, None, None, None)
|
| 634 |
-
|
| 635 |
temp_dir = tempfile.mkdtemp()
|
| 636 |
-
|
| 637 |
-
|
| 638 |
-
|
| 639 |
-
|
| 640 |
-
|
| 641 |
-
|
| 642 |
-
|
| 643 |
-
miss_m_thresh = miss_rate_marker / 100.0
|
| 644 |
-
maf_thresh_f = maf_thresh / 100.0
|
| 645 |
-
|
| 646 |
-
# Load and parse data
|
| 647 |
sample_ids, phenotypes, genotypes, marker_names, chromosome_dict, positions = \
|
| 648 |
-
|
| 649 |
-
|
| 650 |
-
n_samples = len(sample_ids)
|
| 651 |
-
|
| 652 |
-
|
| 653 |
-
|
| 654 |
-
|
| 655 |
-
|
| 656 |
-
|
| 657 |
-
|
| 658 |
-
|
| 659 |
-
|
| 660 |
-
|
| 661 |
-
|
| 662 |
-
|
| 663 |
-
freq = np.mean(valid) / 2.0
|
| 664 |
-
maf[i] = min(freq, 1.0 - freq)
|
| 665 |
-
|
| 666 |
-
# Apply QC
|
| 667 |
-
qc_m = (miss_m < miss_m_thresh) & (maf >= maf_thresh_f)
|
| 668 |
-
qc_s = miss_s < miss_s_thresh
|
| 669 |
-
|
| 670 |
-
# Adaptive QC relaxation
|
| 671 |
-
fallback_applied = False
|
| 672 |
fallback_msg = ""
|
| 673 |
-
for
|
| 674 |
-
|
| 675 |
-
|
| 676 |
-
|
| 677 |
-
|
| 678 |
-
|
| 679 |
-
|
| 680 |
-
qc_s = qc_s_try
|
| 681 |
-
if relaxed_s > miss_s_thresh or relaxed_m > miss_m_thresh:
|
| 682 |
-
fallback_applied = True
|
| 683 |
-
fallback_msg = f"\n> ⚠️ **QC thresholds auto-relaxed** to sample missing < {relaxed_s*100:.0f}% / marker missing < {relaxed_m*100:.0f}% to retain ≥10 samples.\n"
|
| 684 |
break
|
| 685 |
-
|
| 686 |
-
# Apply QC filters
|
| 687 |
geno_qc = genotypes[np.ix_(qc_s, qc_m)].copy()
|
| 688 |
pheno_qc = phenotypes[qc_s]
|
| 689 |
ids_qc = sample_ids[qc_s]
|
| 690 |
mnames_qc = [marker_names[i] for i in range(n_markers) if qc_m[i]]
|
| 691 |
-
chrom_qc
|
| 692 |
-
pos_qc
|
| 693 |
-
|
| 694 |
-
#
|
| 695 |
for i in range(geno_qc.shape[1]):
|
| 696 |
col = geno_qc[:, i]
|
| 697 |
-
|
| 698 |
-
if
|
| 699 |
-
|
| 700 |
-
|
| 701 |
-
|
| 702 |
-
|
| 703 |
-
|
| 704 |
-
geno_qc = geno_qc[valid_pheno]
|
| 705 |
-
pheno_qc = pheno_qc[valid_pheno]
|
| 706 |
-
ids_qc = ids_qc[valid_pheno]
|
| 707 |
-
|
| 708 |
-
# Minimum sample guard
|
| 709 |
if len(ids_qc) < 10:
|
| 710 |
-
|
| 711 |
-
|
| 712 |
-
|
| 713 |
-
|
| 714 |
-
|
| 715 |
-
|
| 716 |
-
|
| 717 |
-
|
| 718 |
-
|
| 719 |
-
|
| 720 |
-
|
| 721 |
-
|
| 722 |
-
|
| 723 |
-
|
| 724 |
-
|
| 725 |
-
|
| 726 |
-
|
| 727 |
-
|
| 728 |
-
|
| 729 |
-
|
| 730 |
-
|
| 731 |
-
|
| 732 |
-
|
| 733 |
-
|
| 734 |
-
|
| 735 |
-
|
| 736 |
-
|
| 737 |
-
|
| 738 |
-
|
| 739 |
-
|
| 740 |
-
|
| 741 |
-
|
| 742 |
-
|
| 743 |
-
|
| 744 |
-
|
| 745 |
-
|
| 746 |
-
|
| 747 |
-
|
| 748 |
-
if
|
| 749 |
-
print("
|
| 750 |
-
|
| 751 |
-
|
| 752 |
-
|
| 753 |
-
|
| 754 |
-
|
| 755 |
-
|
| 756 |
-
|
| 757 |
-
|
| 758 |
-
|
| 759 |
-
|
| 760 |
-
|
| 761 |
-
|
| 762 |
-
|
| 763 |
-
|
| 764 |
-
|
| 765 |
-
|
| 766 |
-
|
| 767 |
-
'
|
| 768 |
-
'
|
| 769 |
-
'
|
| 770 |
-
|
| 771 |
-
|
| 772 |
-
|
| 773 |
-
|
| 774 |
-
|
| 775 |
-
|
| 776 |
-
|
| 777 |
-
|
| 778 |
-
|
| 779 |
-
|
| 780 |
-
|
| 781 |
-
|
| 782 |
-
|
| 783 |
-
|
| 784 |
-
gwas_df['
|
| 785 |
-
|
| 786 |
-
|
| 787 |
-
|
| 788 |
-
|
| 789 |
-
gwas_df['RF_P'] = rf_pvals
|
| 790 |
-
gwas_df['RF_Imp'] = rf_imp
|
| 791 |
-
gwas_df['Significant_RF'] = (rf_pvals < 0.05/len(mnames_qc)).astype(int)
|
| 792 |
-
|
| 793 |
-
if include_gb:
|
| 794 |
-
gwas_df['GB_P'] = gb_pvals
|
| 795 |
-
gwas_df['GB_Imp'] = gb_imp
|
| 796 |
-
gwas_df['Significant_GB'] = (gb_pvals < 0.05/len(mnames_qc)).astype(int)
|
| 797 |
-
|
| 798 |
-
# Consensus significance (at least 2 models agree)
|
| 799 |
-
sig_cols = [col for col in gwas_df.columns if col.startswith('Significant_')]
|
| 800 |
-
if len(sig_cols) > 1:
|
| 801 |
-
gwas_df['Consensus_Sig'] = (gwas_df[sig_cols].sum(axis=1) >= 2).astype(int)
|
| 802 |
-
else:
|
| 803 |
-
gwas_df['Consensus_Sig'] = gwas_df[sig_cols[0]] if sig_cols else 0
|
| 804 |
-
|
| 805 |
-
gwas_df = gwas_df.sort_values('LR_P')
|
| 806 |
gwas_df['Rank'] = range(1, len(gwas_df) + 1)
|
| 807 |
-
|
| 808 |
-
# Save
|
| 809 |
-
|
| 810 |
-
|
| 811 |
-
|
| 812 |
-
|
| 813 |
-
sig_set = set(np.where(
|
| 814 |
-
|
| 815 |
-
|
| 816 |
-
|
| 817 |
-
|
| 818 |
-
|
| 819 |
-
|
| 820 |
-
|
| 821 |
-
|
| 822 |
-
|
| 823 |
-
|
| 824 |
-
|
| 825 |
-
|
| 826 |
-
|
| 827 |
-
|
| 828 |
-
|
| 829 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 830 |
with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf:
|
| 831 |
-
|
| 832 |
-
|
| 833 |
-
|
| 834 |
-
|
| 835 |
-
|
| 836 |
-
|
| 837 |
-
|
| 838 |
-
|
| 839 |
-
|
| 840 |
-
|
| 841 |
-
|
| 842 |
-
|
| 843 |
-
|
| 844 |
-
|
| 845 |
-
|
| 846 |
-
|
| 847 |
-
|
| 848 |
-
| Sample missing filter | < {miss_rate_sample:.0f}% |
|
| 849 |
{fallback_msg}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 850 |
|
| 851 |
-
###
|
| 852 |
-
|
| 853 |
-
|
| 854 |
-
| Linear Regression | ✅ Completed | {int((lr_pvals < 0.05/len(mnames_qc)).sum())} |
|
| 855 |
-
{ f"| Mixed Linear Model | ✅ Completed | {int((mlm_pvals < 0.05/len(mnames_qc)).sum())} |" if include_mlm else "| Mixed Linear Model | ❌ Skipped | - |" }
|
| 856 |
-
{ f"| ElasticNet | ✅ Completed | {int((enet_pvals < 0.05/len(mnames_qc)).sum())} |" if include_enet else "| ElasticNet | ❌ Skipped | - |" }
|
| 857 |
-
{ f"| Random Forest | ✅ Completed | {int((rf_pvals < 0.05/len(mnames_qc)).sum())} |" if include_rf else "| Random Forest | ❌ Skipped | - |" }
|
| 858 |
-
{ f"| Gradient Boosting | ✅ Completed | {int((gb_pvals < 0.05/len(mnames_qc)).sum())} |" if include_gb else "| Gradient Boosting | ❌ Skipped | - |" }
|
| 859 |
-
|
| 860 |
-
### Consensus Results
|
| 861 |
-
**Markers significant in multiple models:** {gwas_df['Consensus_Sig'].sum()}
|
| 862 |
-
|
| 863 |
-
### LD Statistics
|
| 864 |
-
Mean r²: **{np.mean([v['mean_r2'] for v in ld_stats.values()]) if ld_stats else 0:.3f}**
|
| 865 |
-
Mean D': **{np.mean([v['mean_dprime'] for v in ld_stats.values()]) if ld_stats else 0:.3f}**
|
| 866 |
-
|
| 867 |
-
### Top 10 Markers (by LR P-value)
|
| 868 |
-
{ gwas_df.head(10)[['Marker', 'Chromosome', 'LR_P', 'LR_LOD', 'Consensus_Sig']].to_markdown(index=False) }
|
| 869 |
-
|
| 870 |
-
### 📁 ZIP Contents
|
| 871 |
-
- `enhanced_gwas_results.csv` - Complete GWAS results with all models
|
| 872 |
-
- `plots/manhattan_lod.png` - Manhattan plot with LOD scores
|
| 873 |
-
- `plots/enhanced_ld_decay.png` - Comprehensive LD analysis (r², D', per-chromosome)
|
| 874 |
-
- `plots/model_comparison.png` - Model performance comparison
|
| 875 |
-
- Additional QC and summary files
|
| 876 |
"""
|
| 877 |
-
|
| 878 |
-
|
| 879 |
-
None, None, zip_path, f"Results saved to {zip_path}")
|
| 880 |
-
|
| 881 |
except Exception as e:
|
| 882 |
-
import traceback
|
| 883 |
return (f"## ❌ Error\n```\n{e}\n\n{traceback.format_exc()}\n```",
|
| 884 |
None, None, None, None, None, None, None)
|
| 885 |
|
| 886 |
-
# ═══════════════════════════════════════════════
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 887 |
# GRADIO INTERFACE
|
| 888 |
-
# ═══════════════════════════════════════════════
|
|
|
|
|
|
|
| 889 |
|
| 890 |
-
with gr.Blocks(css=THEME_CSS, title="Enhanced MTA Analysis Platform") as app:
|
| 891 |
-
|
| 892 |
gr.HTML(HERO_HTML)
|
| 893 |
-
|
| 894 |
with gr.Row():
|
| 895 |
-
|
|
|
|
| 896 |
gr.HTML(FMT_HTML)
|
| 897 |
-
|
| 898 |
-
|
| 899 |
-
input_file = gr.File(label="
|
| 900 |
-
|
| 901 |
-
|
| 902 |
-
|
| 903 |
-
gr.HTML('<div class="sec-head" style="margin-top:16px">QC Thresholds</div>')
|
| 904 |
miss_rate_sample = gr.Slider(10, 100, value=50, step=5,
|
| 905 |
-
|
| 906 |
miss_rate_marker = gr.Slider(10, 100, value=50, step=5,
|
| 907 |
-
|
| 908 |
maf_thresh = gr.Slider(0.0, 10.0, value=1.0, step=0.5,
|
| 909 |
-
|
| 910 |
-
|
| 911 |
-
gr.HTML('<div class="sec-
|
| 912 |
-
|
| 913 |
-
|
| 914 |
-
|
| 915 |
-
|
| 916 |
-
|
| 917 |
-
|
| 918 |
-
|
| 919 |
-
|
|
|
|
| 920 |
gr.HTML(PIPE_HTML)
|
| 921 |
-
|
|
|
|
| 922 |
with gr.Column(scale=2):
|
| 923 |
-
gr.HTML('<div class="sec-
|
| 924 |
-
with gr.Column(elem_classes=["
|
| 925 |
-
summary_out = gr.Markdown(
|
| 926 |
-
|
| 927 |
-
|
| 928 |
-
|
| 929 |
-
|
| 930 |
-
|
| 931 |
-
|
| 932 |
-
|
| 933 |
-
|
| 934 |
-
|
| 935 |
-
|
| 936 |
-
with gr.
|
| 937 |
-
|
| 938 |
-
|
| 939 |
-
|
| 940 |
-
|
| 941 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 942 |
run_btn.click(
|
| 943 |
-
fn=
|
| 944 |
-
inputs=[input_file,
|
| 945 |
-
|
| 946 |
-
outputs=[summary_out, manhattan_out,
|
| 947 |
-
|
| 948 |
)
|
| 949 |
|
| 950 |
if __name__ == "__main__":
|
|
|
|
| 1 |
# -*- coding: utf-8 -*-
|
| 2 |
"""
|
| 3 |
+
GWAS Nexus - Advanced Multi-Model GWAS Analysis Platform
|
| 4 |
Features:
|
| 5 |
+
- 6+ GWAS models (LR, MLM, LASSO, ElasticNet, Random Forest, Gradient Boosting, Ridge)
|
| 6 |
+
- LOD score Manhattan plots
|
| 7 |
+
- LD Decay plot in Mb
|
| 8 |
+
- Circos-style circular Manhattan plot
|
| 9 |
+
- QQ plots, Effect size plots, PCA
|
| 10 |
+
- Comprehensive LD analysis (r², D')
|
| 11 |
+
- Model comparison & consensus
|
| 12 |
"""
|
| 13 |
|
| 14 |
import gradio as gr
|
|
|
|
| 18 |
matplotlib.use('Agg')
|
| 19 |
import matplotlib.pyplot as plt
|
| 20 |
import matplotlib.patches as mpatches
|
| 21 |
+
from matplotlib.patches import FancyArrowPatch, Arc
|
| 22 |
+
import matplotlib.gridspec as gridspec
|
| 23 |
from matplotlib.collections import LineCollection
|
| 24 |
+
from matplotlib.colors import LinearSegmentedColormap
|
| 25 |
import seaborn as sns
|
| 26 |
from scipy import stats
|
| 27 |
+
from scipy.optimize import curve_fit
|
| 28 |
+
import os, warnings, tempfile, zipfile, traceback
|
| 29 |
from sklearn.linear_model import ElasticNetCV, LassoCV, RidgeCV
|
| 30 |
from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor
|
| 31 |
from sklearn.preprocessing import StandardScaler
|
|
|
|
| 32 |
from sklearn.model_selection import cross_val_score, KFold
|
| 33 |
+
from sklearn.metrics import r2_score
|
| 34 |
import statsmodels.api as sm
|
| 35 |
from statsmodels.formula.api import mixedlm
|
|
|
|
|
|
|
| 36 |
warnings.filterwarnings('ignore')
|
| 37 |
|
| 38 |
+
# ═══════════════════════════════════════════════
|
| 39 |
+
# DESIGN SYSTEM — BIOLUMINESCENT DARK THEME
|
| 40 |
+
# ═══════════════════════════════════════════════
|
| 41 |
+
BG = "#07090F"
|
| 42 |
+
PANEL = "#0D1117"
|
| 43 |
+
CARD = "#111827"
|
| 44 |
+
BORDER = "#1F2937"
|
| 45 |
+
TEXT = "#E2E8F0"
|
| 46 |
+
MUTED = "#64748B"
|
| 47 |
+
CYAN = "#06B6D4"
|
| 48 |
+
VIOLET = "#8B5CF6"
|
| 49 |
+
EMERALD = "#10B981"
|
| 50 |
+
ROSE = "#F43F5E"
|
| 51 |
+
AMBER = "#F59E0B"
|
| 52 |
+
INDIGO = "#6366F1"
|
| 53 |
+
PINK = "#EC4899"
|
| 54 |
+
TEAL = "#14B8A6"
|
| 55 |
+
LIME = "#84CC16"
|
| 56 |
+
ORANGE = "#F97316"
|
| 57 |
|
| 58 |
CHROM_PALETTE = [
|
| 59 |
+
"#06B6D4","#8B5CF6","#10B981","#F43F5E","#F59E0B",
|
| 60 |
+
"#6366F1","#EC4899","#14B8A6","#84CC16","#F97316",
|
| 61 |
+
"#0EA5E9","#A855F7","#22C55E","#EF4444","#EAB308",
|
| 62 |
+
"#4F46E5","#DB2777","#0D9488","#65A30D","#EA580C",
|
| 63 |
+
"#7DD3FC","#C4B5FD","#86EFAC","#FCA5A5","#FDE68A",
|
| 64 |
]
|
| 65 |
|
| 66 |
+
def apply_dark_theme():
|
| 67 |
plt.rcParams.update({
|
| 68 |
'figure.facecolor': BG,
|
| 69 |
'axes.facecolor': PANEL,
|
| 70 |
+
'axes.edgecolor': BORDER,
|
| 71 |
+
'axes.labelcolor': TEXT,
|
| 72 |
+
'axes.titlecolor': TEXT,
|
| 73 |
+
'xtick.color': MUTED,
|
| 74 |
+
'ytick.color': MUTED,
|
| 75 |
+
'text.color': TEXT,
|
| 76 |
+
'grid.color': BORDER,
|
| 77 |
+
'grid.linewidth': 0.6,
|
| 78 |
'figure.dpi': 150,
|
| 79 |
'font.family': 'DejaVu Sans',
|
| 80 |
'axes.spines.top': False,
|
| 81 |
'axes.spines.right': False,
|
| 82 |
+
'axes.spines.left': True,
|
| 83 |
+
'axes.spines.bottom': True,
|
| 84 |
+
'legend.framealpha': 0.15,
|
| 85 |
+
'legend.facecolor': CARD,
|
| 86 |
+
'legend.edgecolor': BORDER,
|
| 87 |
+
'axes.titlesize': 13,
|
| 88 |
+
'axes.labelsize': 11,
|
| 89 |
})
|
| 90 |
|
| 91 |
+
# ═══════════════════════════════════════════════
|
| 92 |
+
# PLOT 1: MANHATTAN + LOD DUAL PANEL
|
| 93 |
+
# ═══════════════════════════════════════════════
|
| 94 |
|
| 95 |
+
def plot_manhattan_lod(marker_names, chromosomes, p_values, lod_scores,
|
| 96 |
+
sig_set, bonf_thresh, save_path):
|
| 97 |
+
apply_dark_theme()
|
|
|
|
| 98 |
unique_chroms = sorted(set(chromosomes),
|
| 99 |
key=lambda x: (int(x) if str(x).isdigit() else 999, str(x)))
|
| 100 |
log_p = -np.log10(np.array(p_values) + 1e-300)
|
| 101 |
+
lod_arr = np.array(lod_scores)
|
| 102 |
+
|
| 103 |
+
GAP = max(10, len(marker_names) // 120)
|
| 104 |
x_pos = np.zeros(len(marker_names))
|
| 105 |
+
chrom_to_idx, chrom_centers = {}, {}
|
| 106 |
for i, c in enumerate(chromosomes):
|
| 107 |
chrom_to_idx.setdefault(c, []).append(i)
|
| 108 |
+
|
| 109 |
offset = 0
|
| 110 |
for ch in unique_chroms:
|
| 111 |
idxs = chrom_to_idx.get(ch, [])
|
|
|
|
| 114 |
x_pos[idx] = offset + r
|
| 115 |
chrom_centers[ch] = offset + (len(idxs) - 1) / 2
|
| 116 |
offset += len(idxs) + GAP
|
| 117 |
+
|
| 118 |
+
fig = plt.figure(figsize=(24, 12), facecolor=BG)
|
| 119 |
+
gs = gridspec.GridSpec(3, 1, figure=fig, hspace=0.05,
|
| 120 |
+
height_ratios=[2.5, 0.8, 1.2])
|
| 121 |
+
ax1 = fig.add_subplot(gs[0])
|
| 122 |
+
ax_sep = fig.add_subplot(gs[1])
|
| 123 |
+
ax2 = fig.add_subplot(gs[2])
|
| 124 |
+
ax_sep.set_visible(False)
|
| 125 |
+
|
| 126 |
+
for ax in [ax1, ax2]:
|
| 127 |
+
ax.set_facecolor(PANEL)
|
| 128 |
+
for ci, ch in enumerate(unique_chroms):
|
| 129 |
+
idxs = chrom_to_idx.get(ch, [])
|
| 130 |
+
if not idxs: continue
|
| 131 |
+
x0, x1 = x_pos[idxs[0]] - 0.5, x_pos[idxs[-1]] + 0.5
|
| 132 |
+
if ci % 2 == 0:
|
| 133 |
+
ax.axvspan(x0, x1, color='#1A2035', alpha=0.7, zorder=0)
|
| 134 |
+
|
| 135 |
+
# Manhattan scatter
|
| 136 |
for ci, ch in enumerate(unique_chroms):
|
| 137 |
idxs = chrom_to_idx.get(ch, [])
|
| 138 |
if not idxs: continue
|
| 139 |
col = CHROM_PALETTE[ci % len(CHROM_PALETTE)]
|
| 140 |
normal = [i for i in idxs if i not in sig_set]
|
| 141 |
sel = [i for i in idxs if i in sig_set]
|
|
|
|
| 142 |
if normal:
|
| 143 |
+
ax1.scatter(x_pos[normal], log_p[normal], c=col, s=14,
|
| 144 |
+
alpha=0.6, linewidths=0, zorder=2, rasterized=True)
|
| 145 |
if sel:
|
| 146 |
+
ax1.scatter(x_pos[sel], log_p[sel], c=ROSE, s=350,
|
| 147 |
+
alpha=0.12, linewidths=0, zorder=3)
|
| 148 |
+
ax1.scatter(x_pos[sel], log_p[sel], c=ROSE, s=80,
|
| 149 |
+
alpha=1.0, edgecolors='white', linewidths=0.8,
|
| 150 |
+
marker='*', zorder=4)
|
| 151 |
+
|
| 152 |
+
# Threshold lines
|
| 153 |
+
ax1.axhline(bonf_thresh, color=ROSE, ls='--', lw=1.8, alpha=0.9,
|
| 154 |
+
label=f'Bonferroni (α=0.05)')
|
| 155 |
+
ax1.axhline(5, color=AMBER, ls=':', lw=1.4, alpha=0.8, label='−log₁₀P = 5')
|
| 156 |
+
ax1.axhline(3, color=EMERALD, ls=':', lw=1.2, alpha=0.6, label='−log₁₀P = 3')
|
| 157 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 158 |
ax1.set_xlim(-GAP, offset)
|
| 159 |
+
ax1.set_ylim(0, log_p.max() * 1.18)
|
| 160 |
+
ax1.set_ylabel('−log₁₀(P-value)', fontsize=13, color=TEXT, fontweight='bold', labelpad=12)
|
| 161 |
+
ax1.set_title('GWAS Manhattan Plot · LOD Profile', fontsize=16,
|
| 162 |
+
color=CYAN, fontweight='bold', pad=20, loc='left')
|
| 163 |
+
ax1.set_xticks([])
|
| 164 |
+
ax1.yaxis.grid(True, color=BORDER, lw=0.6, alpha=0.9)
|
| 165 |
+
ax1.legend(loc='upper right', fontsize=9, facecolor=CARD,
|
| 166 |
+
edgecolor=BORDER, framealpha=0.9)
|
| 167 |
+
|
| 168 |
+
# LOD profile
|
| 169 |
+
ax2.plot(x_pos, lod_arr, color=CYAN, lw=1.2, alpha=0.8)
|
| 170 |
+
ax2.fill_between(x_pos, 0, lod_arr, color=CYAN, alpha=0.15)
|
| 171 |
+
ax2.axhline(3, color=AMBER, ls='--', lw=1.5, alpha=0.9, label='LOD = 3')
|
| 172 |
+
lod_sig = lod_arr >= 3
|
| 173 |
+
if lod_sig.any():
|
| 174 |
+
ax2.scatter(x_pos[lod_sig], lod_arr[lod_sig], c=AMBER, s=18,
|
| 175 |
+
alpha=0.9, zorder=3, label=f'{lod_sig.sum()} LOD≥3')
|
| 176 |
+
|
|
|
|
| 177 |
ax2.set_xlim(-GAP, offset)
|
| 178 |
+
ax2.set_ylim(0, lod_arr.max() * 1.15 if lod_arr.max() > 0 else 5)
|
| 179 |
+
ax2.set_ylabel('LOD Score', fontsize=12, color=CYAN, fontweight='bold')
|
| 180 |
+
ax2.set_xlabel('Chromosome', fontsize=12, color=TEXT, fontweight='bold')
|
| 181 |
+
ax2.yaxis.grid(True, color=BORDER, lw=0.6)
|
| 182 |
+
ax2.legend(fontsize=9, facecolor=CARD, edgecolor=BORDER)
|
| 183 |
+
|
| 184 |
+
xticks = [chrom_centers[ch] for ch in unique_chroms if ch in chrom_centers]
|
| 185 |
+
ax2.set_xticks(xticks)
|
| 186 |
+
ax2.set_xticklabels([str(ch) for ch in unique_chroms if ch in chrom_centers],
|
| 187 |
+
fontsize=8, color=MUTED)
|
| 188 |
+
|
| 189 |
+
# Color-coded chrom label strip
|
| 190 |
+
for ci, ch in enumerate(unique_chroms):
|
| 191 |
+
if ch not in chrom_centers: continue
|
| 192 |
+
col = CHROM_PALETTE[ci % len(CHROM_PALETTE)]
|
| 193 |
+
ax2.axvline(chrom_centers[ch], color=col, lw=0.4, alpha=0.3, zorder=0)
|
| 194 |
+
|
| 195 |
+
plt.savefig(save_path, dpi=180, bbox_inches='tight', facecolor=BG)
|
| 196 |
+
plt.close(fig)
|
| 197 |
+
|
| 198 |
+
# ═══════════════════════════════════════════════
|
| 199 |
+
# PLOT 2: QQ PLOT
|
| 200 |
+
# ═══════════════════════════════════════════════
|
| 201 |
+
|
| 202 |
+
def plot_qq(p_values_dict, save_path):
|
| 203 |
+
apply_dark_theme()
|
| 204 |
+
fig, ax = plt.subplots(figsize=(8, 8), facecolor=BG)
|
| 205 |
+
ax.set_facecolor(PANEL)
|
| 206 |
+
|
| 207 |
+
colors_map = {
|
| 208 |
+
'Linear': CYAN, 'MLM': VIOLET, 'LASSO': EMERALD,
|
| 209 |
+
'ElasticNet': AMBER, 'RidgeCV': INDIGO,
|
| 210 |
+
'RandomForest': ROSE, 'GradBoost': ORANGE
|
| 211 |
+
}
|
| 212 |
+
|
| 213 |
+
for name, pvals in p_values_dict.items():
|
| 214 |
+
pvals = np.array(pvals)
|
| 215 |
+
pvals = pvals[~np.isnan(pvals) & (pvals > 0)]
|
| 216 |
+
n = len(pvals)
|
| 217 |
+
expected = -np.log10(np.arange(1, n + 1) / (n + 1))
|
| 218 |
+
observed = -np.log10(np.sort(pvals))
|
| 219 |
+
col = colors_map.get(name, CYAN)
|
| 220 |
+
ax.scatter(expected, observed, s=10, alpha=0.7, color=col,
|
| 221 |
+
label=name, linewidths=0, rasterized=True)
|
| 222 |
+
|
| 223 |
+
maxval = max(6, max(-np.log10(min(p) + 1e-300) for p in p_values_dict.values() if len(p) > 0))
|
| 224 |
+
ax.plot([0, maxval], [0, maxval], '--', color=MUTED, lw=1.5, label='Expected')
|
| 225 |
+
|
| 226 |
+
# Confidence band
|
| 227 |
+
ns = [len(p) for p in p_values_dict.values() if len(p) > 0]
|
| 228 |
+
if ns:
|
| 229 |
+
n_avg = int(np.mean(ns))
|
| 230 |
+
exp_qs = np.arange(1, n_avg + 1) / (n_avg + 1)
|
| 231 |
+
upper = -np.log10(stats.beta.ppf(0.975, np.arange(1, n_avg + 1),
|
| 232 |
+
n_avg - np.arange(1, n_avg + 1) + 1))
|
| 233 |
+
lower = -np.log10(stats.beta.ppf(0.025, np.arange(1, n_avg + 1),
|
| 234 |
+
n_avg - np.arange(1, n_avg + 1) + 1))
|
| 235 |
+
exp_sorted = -np.log10(exp_qs)
|
| 236 |
+
ax.fill_between(exp_sorted[::-1], lower[::-1], upper[::-1],
|
| 237 |
+
color=MUTED, alpha=0.15, label='95% CI')
|
| 238 |
+
|
| 239 |
+
ax.set_xlim(0, maxval * 0.9)
|
| 240 |
+
ax.set_ylim(0, maxval * 1.05)
|
| 241 |
+
ax.set_xlabel('Expected −log₁₀(P)', fontsize=12, fontweight='bold')
|
| 242 |
+
ax.set_ylabel('Observed −log₁₀(P)', fontsize=12, fontweight='bold')
|
| 243 |
+
ax.set_title('QQ Plot — All Models', fontsize=14, color=CYAN, fontweight='bold')
|
| 244 |
+
ax.legend(fontsize=9, facecolor=CARD, edgecolor=BORDER, ncol=2)
|
| 245 |
+
ax.grid(True, color=BORDER, lw=0.6)
|
| 246 |
+
plt.tight_layout()
|
| 247 |
+
plt.savefig(save_path, dpi=180, bbox_inches='tight', facecolor=BG)
|
| 248 |
plt.close(fig)
|
| 249 |
|
| 250 |
+
# ═══════════════════════════════════════════════
|
| 251 |
+
# PLOT 3: LD DECAY (in Mb)
|
| 252 |
+
# ═══════════════════════════════════════════════
|
| 253 |
+
|
| 254 |
+
def plot_ld_decay_mb(genotypes, chromosomes, positions, save_path, max_m=300):
|
| 255 |
+
apply_dark_theme()
|
| 256 |
unique_chroms = sorted(set(chromosomes),
|
| 257 |
key=lambda x: (int(x) if str(x).isdigit() else 999, str(x)))
|
| 258 |
+
|
| 259 |
+
all_distances_mb, all_r2, all_dprime = [], [], []
|
| 260 |
+
chrom_half_decay = {}
|
| 261 |
+
|
|
|
|
|
|
|
| 262 |
for ch in unique_chroms:
|
| 263 |
idxs = [i for i, c in enumerate(chromosomes) if c == ch]
|
| 264 |
if len(idxs) < 4: continue
|
| 265 |
if len(idxs) > max_m:
|
| 266 |
idxs = sorted(np.random.choice(idxs, max_m, replace=False))
|
| 267 |
+
|
| 268 |
G = genotypes[:, idxs].copy()
|
| 269 |
+
pos_ch = np.array([positions[i] for i in idxs], dtype=float)
|
| 270 |
+
# Convert to Mb if positions look like bp
|
| 271 |
+
if pos_ch.max() > 1e6:
|
| 272 |
+
pos_ch = pos_ch / 1e6
|
| 273 |
+
|
| 274 |
+
ch_dists, ch_r2 = [], []
|
| 275 |
for i in range(len(idxs)):
|
| 276 |
+
for j in range(i+1, min(i+80, len(idxs))):
|
| 277 |
+
dist_mb = abs(pos_ch[j] - pos_ch[i])
|
|
|
|
|
|
|
| 278 |
r = np.corrcoef(G[:, i], G[:, j])[0, 1]
|
| 279 |
r2 = r**2 if not np.isnan(r) else 0
|
| 280 |
+
|
| 281 |
+
freq1 = np.mean(G[:, i]) / 2.0
|
| 282 |
+
freq2 = np.mean(G[:, j]) / 2.0
|
| 283 |
+
p11 = np.mean((G[:, i] >= 1) & (G[:, j] >= 1))
|
|
|
|
|
|
|
|
|
|
|
|
|
| 284 |
D = p11 - freq1 * freq2
|
| 285 |
+
Dm = min(freq1*(1-freq2), (1-freq1)*freq2) if D < 0 else min(freq1*freq2, (1-freq1)*(1-freq2))
|
| 286 |
+
dprime = abs(D / Dm) if Dm > 1e-8 else 0
|
| 287 |
+
|
| 288 |
+
all_distances_mb.append(dist_mb)
|
| 289 |
all_r2.append(r2)
|
| 290 |
+
all_dprime.append(dprime)
|
| 291 |
+
ch_dists.append(dist_mb)
|
| 292 |
+
ch_r2.append(r2)
|
| 293 |
+
|
| 294 |
+
if ch_dists:
|
| 295 |
+
d_arr = np.array(ch_dists)
|
| 296 |
+
r_arr = np.array(ch_r2)
|
| 297 |
+
bins_mb = np.linspace(0, np.percentile(d_arr, 95) + 0.01, 30)
|
| 298 |
+
bm, br = [], []
|
| 299 |
+
for bi in range(len(bins_mb)-1):
|
| 300 |
+
mask = (d_arr >= bins_mb[bi]) & (d_arr < bins_mb[bi+1])
|
| 301 |
+
if mask.sum() >= 2:
|
| 302 |
+
bm.append((bins_mb[bi]+bins_mb[bi+1])/2)
|
| 303 |
+
br.append(np.mean(r_arr[mask]))
|
| 304 |
+
if len(bm) >= 3:
|
| 305 |
+
bm, br = np.array(bm), np.array(br)
|
| 306 |
+
hdidx = np.where(br <= max(br)*0.5)[0]
|
| 307 |
+
if len(hdidx) > 0:
|
| 308 |
+
chrom_half_decay[ch] = bm[hdidx[0]]
|
| 309 |
+
|
| 310 |
+
fig, axes = plt.subplots(1, 3, figsize=(20, 6), facecolor=BG)
|
| 311 |
+
|
| 312 |
+
distances = np.array(all_distances_mb)
|
| 313 |
+
r2_vals = np.array(all_r2)
|
| 314 |
+
dprime_vals = np.array(all_dprime)
|
| 315 |
+
|
| 316 |
+
if len(distances) > 0:
|
| 317 |
+
max_dist = min(5.0, float(np.percentile(distances, 97)))
|
| 318 |
+
bins_mb = np.linspace(0, max_dist + 0.001, 50)
|
| 319 |
+
bcenters, bmeans_r2, bstds_r2, bmeans_dp, bstds_dp = [], [], [], [], []
|
| 320 |
+
|
| 321 |
+
for bi in range(len(bins_mb)-1):
|
| 322 |
+
mask = (distances >= bins_mb[bi]) & (distances < bins_mb[bi+1])
|
| 323 |
+
if mask.sum() >= 2:
|
| 324 |
+
bcenters.append((bins_mb[bi]+bins_mb[bi+1])/2)
|
| 325 |
+
bmeans_r2.append(np.mean(r2_vals[mask]))
|
| 326 |
+
bstds_r2.append(np.std(r2_vals[mask]) / np.sqrt(mask.sum()))
|
| 327 |
+
bmeans_dp.append(np.mean(dprime_vals[mask]))
|
| 328 |
+
bstds_dp.append(np.std(dprime_vals[mask]) / np.sqrt(mask.sum()))
|
| 329 |
+
|
| 330 |
+
bcenters = np.array(bcenters)
|
| 331 |
+
bmeans_r2 = np.array(bmeans_r2)
|
| 332 |
+
bmeans_dp = np.array(bmeans_dp)
|
| 333 |
+
|
| 334 |
+
# Plot 1: r² decay
|
| 335 |
+
ax = axes[0]
|
| 336 |
+
ax.set_facecolor(PANEL)
|
| 337 |
+
|
| 338 |
+
# Scatter (downsampled)
|
| 339 |
+
if len(distances) > 5000:
|
| 340 |
+
idx_s = np.random.choice(len(distances), 5000, replace=False)
|
| 341 |
+
ax.scatter(distances[idx_s], r2_vals[idx_s], c=CYAN, s=4,
|
| 342 |
+
alpha=0.15, linewidths=0, rasterized=True)
|
| 343 |
+
else:
|
| 344 |
+
ax.scatter(distances, r2_vals, c=CYAN, s=4, alpha=0.2, linewidths=0)
|
| 345 |
+
|
| 346 |
+
ax.errorbar(bcenters, bmeans_r2, yerr=bstds_r2, fmt='o-',
|
| 347 |
+
color=CYAN, capsize=3, capthick=1.2, markersize=5,
|
| 348 |
+
lw=2, alpha=0.9, zorder=5, label='Mean r²')
|
| 349 |
+
|
| 350 |
+
# Fit exponential decay
|
| 351 |
try:
|
| 352 |
+
def decay_exp(x, a, b, c):
|
| 353 |
+
return a * np.exp(-b * x) + c
|
| 354 |
+
popt, _ = curve_fit(decay_exp, bcenters, bmeans_r2,
|
| 355 |
+
p0=[0.5, 1.0, 0.05], maxfev=10000)
|
| 356 |
+
xf = np.linspace(0, max_dist, 300)
|
| 357 |
+
yf = decay_exp(xf, *popt)
|
| 358 |
+
ax.plot(xf, yf, '--', color=ROSE, lw=2, alpha=0.9, label='Exp. fit')
|
| 359 |
except:
|
| 360 |
pass
|
| 361 |
+
|
| 362 |
+
ax.axhline(0.2, color=AMBER, ls='--', lw=1.3, alpha=0.8, label='r² = 0.2')
|
| 363 |
+
ax.set_xlabel('Distance (Mb)', fontsize=11, fontweight='bold')
|
| 364 |
+
ax.set_ylabel('r²', fontsize=11, fontweight='bold')
|
| 365 |
+
ax.set_title('LD Decay — r²', fontsize=13, color=CYAN, fontweight='bold')
|
| 366 |
+
ax.set_ylim(0, 1.05)
|
| 367 |
+
ax.set_xlim(0, max_dist)
|
| 368 |
+
ax.legend(fontsize=9, facecolor=CARD, edgecolor=BORDER)
|
| 369 |
+
ax.grid(True, color=BORDER, lw=0.5)
|
| 370 |
+
|
| 371 |
+
# Plot 2: D' decay
|
| 372 |
+
ax = axes[1]
|
| 373 |
+
ax.set_facecolor(PANEL)
|
| 374 |
+
if len(distances) > 5000:
|
| 375 |
+
ax.scatter(distances[idx_s], dprime_vals[idx_s], c=VIOLET, s=4,
|
| 376 |
+
alpha=0.15, linewidths=0, rasterized=True)
|
| 377 |
+
else:
|
| 378 |
+
ax.scatter(distances, dprime_vals, c=VIOLET, s=4, alpha=0.2, linewidths=0)
|
| 379 |
+
|
| 380 |
+
ax.errorbar(bcenters, bmeans_dp, yerr=bstds_dp, fmt='o-',
|
| 381 |
+
color=VIOLET, capsize=3, capthick=1.2, markersize=5,
|
| 382 |
+
lw=2, alpha=0.9, label="Mean D'")
|
| 383 |
+
ax.axhline(0.5, color=AMBER, ls='--', lw=1.3, alpha=0.8, label="D' = 0.5")
|
| 384 |
+
ax.set_xlabel('Distance (Mb)', fontsize=11, fontweight='bold')
|
| 385 |
+
ax.set_ylabel("D'", fontsize=11, fontweight='bold')
|
| 386 |
+
ax.set_title("LD Decay — D'", fontsize=13, color=VIOLET, fontweight='bold')
|
| 387 |
+
ax.set_ylim(0, 1.05)
|
| 388 |
+
ax.set_xlim(0, max_dist)
|
| 389 |
+
ax.legend(fontsize=9, facecolor=CARD, edgecolor=BORDER)
|
| 390 |
+
ax.grid(True, color=BORDER, lw=0.5)
|
| 391 |
+
|
| 392 |
+
# Plot 3: Half-decay per chromosome
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 393 |
ax = axes[2]
|
| 394 |
ax.set_facecolor(PANEL)
|
| 395 |
+
if chrom_half_decay:
|
| 396 |
+
chroms_sorted = sorted(chrom_half_decay.keys(),
|
| 397 |
+
key=lambda x: (int(x) if str(x).isdigit() else 999, str(x)))
|
| 398 |
+
half_d = [chrom_half_decay[c] for c in chroms_sorted]
|
| 399 |
+
colors_bar = [CHROM_PALETTE[i % len(CHROM_PALETTE)] for i in range(len(chroms_sorted))]
|
| 400 |
+
bars = ax.barh(range(len(chroms_sorted)), half_d,
|
| 401 |
+
color=colors_bar, alpha=0.8, edgecolor='none', height=0.7)
|
| 402 |
+
ax.set_yticks(range(len(chroms_sorted)))
|
| 403 |
+
ax.set_yticklabels([f'Chr {c}' for c in chroms_sorted], fontsize=8, color=TEXT)
|
| 404 |
+
ax.set_xlabel('LD Half-Decay Distance (Mb)', fontsize=11, fontweight='bold')
|
| 405 |
+
ax.set_title('Per-Chromosome LD Half-Decay', fontsize=13,
|
| 406 |
+
color=EMERALD, fontweight='bold')
|
| 407 |
+
ax.grid(True, color=BORDER, lw=0.5, axis='x')
|
| 408 |
+
for bar, val in zip(bars, half_d):
|
| 409 |
+
ax.text(val + 0.005, bar.get_y() + bar.get_height()/2,
|
| 410 |
+
f'{val:.3f}', va='center', fontsize=7, color=MUTED)
|
| 411 |
+
else:
|
| 412 |
+
ax.text(0.5, 0.5, 'Insufficient data\nfor per-chromosome LD',
|
| 413 |
+
ha='center', va='center', color=MUTED, fontsize=11, transform=ax.transAxes)
|
| 414 |
+
|
| 415 |
+
plt.suptitle('Linkage Disequilibrium Analysis · Distance in Megabases',
|
| 416 |
+
fontsize=15, color=TEXT, fontweight='bold', y=1.01)
|
|
|
|
| 417 |
plt.tight_layout(pad=2)
|
| 418 |
+
plt.savefig(save_path, dpi=180, bbox_inches='tight', facecolor=BG)
|
| 419 |
+
plt.close(fig)
|
| 420 |
+
return chrom_half_decay
|
| 421 |
+
|
| 422 |
+
# ═══════════════════════════════════════════════
|
| 423 |
+
# PLOT 4: CIRCOS MANHATTAN
|
| 424 |
+
# ═══════════════════════════════════════════════
|
| 425 |
+
|
| 426 |
+
def plot_circos_manhattan(marker_names, chromosomes, p_values, lod_scores, save_path):
|
| 427 |
+
apply_dark_theme()
|
| 428 |
+
unique_chroms = sorted(set(chromosomes),
|
| 429 |
+
key=lambda x: (int(x) if str(x).isdigit() else 999, str(x)))
|
| 430 |
+
log_p = -np.log10(np.array(p_values) + 1e-300)
|
| 431 |
+
lod_arr = np.array(lod_scores)
|
| 432 |
+
|
| 433 |
+
fig, ax = plt.subplots(figsize=(14, 14), facecolor=BG, subplot_kw=dict(projection='polar'))
|
| 434 |
+
ax.set_facecolor(BG)
|
| 435 |
+
|
| 436 |
+
chrom_to_idx = {}
|
| 437 |
+
for i, c in enumerate(chromosomes):
|
| 438 |
+
chrom_to_idx.setdefault(c, []).append(i)
|
| 439 |
+
|
| 440 |
+
total_markers = len(marker_names)
|
| 441 |
+
GAP_FRAC = 0.015
|
| 442 |
+
n_chroms = len(unique_chroms)
|
| 443 |
+
total_gap = GAP_FRAC * n_chroms
|
| 444 |
+
chrom_fracs = {}
|
| 445 |
+
|
| 446 |
+
# Assign angular spans
|
| 447 |
+
for ch in unique_chroms:
|
| 448 |
+
idxs = chrom_to_idx.get(ch, [])
|
| 449 |
+
chrom_fracs[ch] = len(idxs) / total_markers * (1 - total_gap)
|
| 450 |
+
|
| 451 |
+
angle_start = {}
|
| 452 |
+
cur_angle = np.pi / 2 # Start at top
|
| 453 |
+
for ci, ch in enumerate(unique_chroms):
|
| 454 |
+
angle_start[ch] = cur_angle
|
| 455 |
+
span = chrom_fracs.get(ch, 0) * 2 * np.pi
|
| 456 |
+
cur_angle -= span + GAP_FRAC * 2 * np.pi
|
| 457 |
+
|
| 458 |
+
# Radial params
|
| 459 |
+
R_INNER = 0.5
|
| 460 |
+
R_MAX = 0.95
|
| 461 |
+
MAX_LOGP = max(log_p.max(), 1.0)
|
| 462 |
+
R_BONF = R_INNER + ((-np.log10(0.05 / total_markers)) / MAX_LOGP) * (R_MAX - R_INNER)
|
| 463 |
+
R_LOD3 = R_INNER + (3.0 / MAX_LOGP) * (R_MAX - R_INNER)
|
| 464 |
+
|
| 465 |
+
# Draw chromosome arcs & labels
|
| 466 |
+
for ci, ch in enumerate(unique_chroms):
|
| 467 |
+
idxs = chrom_to_idx.get(ch, [])
|
| 468 |
+
if not idxs: continue
|
| 469 |
+
col = CHROM_PALETTE[ci % len(CHROM_PALETTE)]
|
| 470 |
+
span = chrom_fracs.get(ch, 0) * 2 * np.pi
|
| 471 |
+
a_start = angle_start[ch]
|
| 472 |
+
a_end = a_start - span
|
| 473 |
+
|
| 474 |
+
# Background arc
|
| 475 |
+
theta_arc = np.linspace(a_start, a_end, 100)
|
| 476 |
+
ax.plot(theta_arc, [R_INNER - 0.04] * 100, '-', color=col, lw=6, alpha=0.6,
|
| 477 |
+
solid_capstyle='round')
|
| 478 |
+
|
| 479 |
+
# Chromosome label
|
| 480 |
+
a_mid = (a_start + a_end) / 2
|
| 481 |
+
ax.text(a_mid, R_INNER - 0.12, str(ch), ha='center', va='center',
|
| 482 |
+
fontsize=8, color=col, fontweight='bold', rotation=np.degrees(a_mid) - 90)
|
| 483 |
+
|
| 484 |
+
# Scatter points
|
| 485 |
+
n_ch = len(idxs)
|
| 486 |
+
for rank, idx in enumerate(idxs):
|
| 487 |
+
angle = a_start - (rank / max(n_ch - 1, 1)) * span
|
| 488 |
+
r_val = R_INNER + (log_p[idx] / MAX_LOGP) * (R_MAX - R_INNER)
|
| 489 |
+
r_val = min(r_val, R_MAX)
|
| 490 |
+
|
| 491 |
+
sig = log_p[idx] >= (-np.log10(0.05 / total_markers))
|
| 492 |
+
if sig:
|
| 493 |
+
size = 18
|
| 494 |
+
alpha = 0.95
|
| 495 |
+
color_pt = ROSE
|
| 496 |
+
elif log_p[idx] >= 3:
|
| 497 |
+
size = 8
|
| 498 |
+
alpha = 0.7
|
| 499 |
+
color_pt = AMBER
|
| 500 |
+
else:
|
| 501 |
+
size = 3
|
| 502 |
+
alpha = 0.35
|
| 503 |
+
color_pt = col
|
| 504 |
+
|
| 505 |
+
ax.scatter([angle], [r_val], c=color_pt, s=size, alpha=alpha,
|
| 506 |
+
linewidths=0, zorder=3, rasterized=True)
|
| 507 |
+
|
| 508 |
+
# Reference circles
|
| 509 |
+
for r_line, label, col_line, ls in [
|
| 510 |
+
(R_BONF, 'Bonferroni', ROSE, '--'),
|
| 511 |
+
(R_LOD3, 'LOD=3', AMBER, ':'),
|
| 512 |
+
(R_INNER, '', BORDER, '-'),
|
| 513 |
+
]:
|
| 514 |
+
theta = np.linspace(0, 2*np.pi, 360)
|
| 515 |
+
ax.plot(theta, [r_line]*360, ls=ls, color=col_line, lw=1.2, alpha=0.7)
|
| 516 |
+
if label:
|
| 517 |
+
ax.text(np.pi/4, r_line + 0.01, label, ha='center', va='bottom',
|
| 518 |
+
fontsize=8, color=col_line, alpha=0.8)
|
| 519 |
+
|
| 520 |
+
# LOD inner ring
|
| 521 |
+
R_LOD_INNER = 0.28
|
| 522 |
+
R_LOD_OUTER = 0.45
|
| 523 |
+
MAX_LOD = max(lod_arr.max(), 1.0)
|
| 524 |
+
|
| 525 |
+
for ci, ch in enumerate(unique_chroms):
|
| 526 |
+
idxs = chrom_to_idx.get(ch, [])
|
| 527 |
+
if not idxs: continue
|
| 528 |
+
span = chrom_fracs.get(ch, 0) * 2 * np.pi
|
| 529 |
+
a_start = angle_start[ch]
|
| 530 |
+
n_ch = len(idxs)
|
| 531 |
+
angles_ch = [a_start - (rank/(max(n_ch-1,1)))*span for rank in range(n_ch)]
|
| 532 |
+
lod_ch = [lod_arr[idx] for idx in idxs]
|
| 533 |
+
r_lod = [R_LOD_INNER + (l/MAX_LOD) * (R_LOD_OUTER - R_LOD_INNER) for l in lod_ch]
|
| 534 |
+
col = CHROM_PALETTE[ci % len(CHROM_PALETTE)]
|
| 535 |
+
ax.fill(angles_ch + [angles_ch[-1], angles_ch[0]],
|
| 536 |
+
r_lod + [R_LOD_INNER, R_LOD_INNER],
|
| 537 |
+
color=col, alpha=0.25, zorder=1)
|
| 538 |
+
ax.plot(angles_ch, r_lod, color=col, lw=0.8, alpha=0.7, zorder=2)
|
| 539 |
+
|
| 540 |
+
ax.set_ylim(0, 1.05)
|
| 541 |
+
ax.set_yticks([])
|
| 542 |
+
ax.set_xticks([])
|
| 543 |
+
ax.spines['polar'].set_visible(False)
|
| 544 |
+
|
| 545 |
+
# Center label
|
| 546 |
+
ax.text(0, 0, 'GWAS\nCircos', ha='center', va='center',
|
| 547 |
+
fontsize=14, color=CYAN, fontweight='bold',
|
| 548 |
+
transform=ax.transData)
|
| 549 |
+
|
| 550 |
+
# Legend
|
| 551 |
+
legend_elements = [
|
| 552 |
+
mpatches.Patch(facecolor=ROSE, label='Significant (Bonferroni)'),
|
| 553 |
+
mpatches.Patch(facecolor=AMBER, label='LOD ≥ 3'),
|
| 554 |
+
mpatches.Patch(facecolor=CYAN, alpha=0.5, label='LOD profile (inner)'),
|
| 555 |
+
]
|
| 556 |
+
ax.legend(handles=legend_elements, loc='lower right',
|
| 557 |
+
bbox_to_anchor=(1.25, -0.05), fontsize=10,
|
| 558 |
+
facecolor=CARD, edgecolor=BORDER, framealpha=0.9)
|
| 559 |
+
|
| 560 |
+
plt.title('GWAS Circos Plot · Manhattan + LOD Ring',
|
| 561 |
+
fontsize=15, color=CYAN, fontweight='bold', pad=20)
|
| 562 |
+
plt.tight_layout()
|
| 563 |
+
plt.savefig(save_path, dpi=180, bbox_inches='tight', facecolor=BG)
|
| 564 |
plt.close(fig)
|
| 565 |
+
|
| 566 |
+
# ═══════════════════════════════════════════════
|
| 567 |
+
# PLOT 5: MODEL COMPARISON
|
| 568 |
+
# ═══════════════════════════════════════════════
|
| 569 |
+
|
| 570 |
+
def plot_model_comparison(gwas_df, model_results, save_path):
|
| 571 |
+
apply_dark_theme()
|
| 572 |
+
fig, axes = plt.subplots(2, 3, figsize=(18, 11), facecolor=BG)
|
| 573 |
+
fig.suptitle('Multi-Model GWAS Comparison', fontsize=16,
|
| 574 |
+
color=CYAN, fontweight='bold', y=1.01)
|
| 575 |
+
|
| 576 |
+
pval_cols = [c for c in gwas_df.columns if c.endswith('_P')]
|
| 577 |
+
model_short = [c.replace('_P','') for c in pval_cols]
|
| 578 |
+
model_colors = [CYAN, VIOLET, EMERALD, AMBER, INDIGO, ROSE, ORANGE][:len(model_short)]
|
| 579 |
+
|
| 580 |
+
# 1. Significant markers per model
|
| 581 |
ax = axes[0, 0]
|
| 582 |
ax.set_facecolor(PANEL)
|
| 583 |
+
bonf = 0.05 / len(gwas_df)
|
| 584 |
+
sig_counts = [(gwas_df[col] < bonf).sum() for col in pval_cols]
|
| 585 |
+
bars = ax.bar(model_short, sig_counts, color=model_colors, alpha=0.8, edgecolor='none')
|
| 586 |
+
ax.set_ylabel('# Significant Markers', fontweight='bold')
|
| 587 |
+
ax.set_title('Significant Markers per Model', color=CYAN, fontweight='bold')
|
| 588 |
+
ax.grid(True, color=BORDER, lw=0.5, axis='y')
|
| 589 |
+
for bar, v in zip(bars, sig_counts):
|
| 590 |
+
ax.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 0.3,
|
| 591 |
+
str(int(v)), ha='center', fontsize=9, color=TEXT)
|
| 592 |
+
ax.tick_params(axis='x', colors=TEXT, labelsize=9)
|
| 593 |
+
|
| 594 |
+
# 2. P-value correlation heatmap
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 595 |
ax = axes[0, 1]
|
| 596 |
ax.set_facecolor(PANEL)
|
| 597 |
+
if len(pval_cols) > 1:
|
| 598 |
+
corr = gwas_df[pval_cols].corr()
|
| 599 |
+
custom_cmap = LinearSegmentedColormap.from_list(
|
| 600 |
+
'custom', [ROSE, PANEL, CYAN], N=256)
|
| 601 |
+
im = ax.imshow(corr.values, cmap=custom_cmap, vmin=-1, vmax=1, aspect='auto')
|
| 602 |
+
ax.set_xticks(range(len(model_short)))
|
| 603 |
+
ax.set_yticks(range(len(model_short)))
|
| 604 |
+
ax.set_xticklabels(model_short, rotation=45, ha='right', fontsize=9)
|
| 605 |
+
ax.set_yticklabels(model_short, fontsize=9)
|
| 606 |
+
for i in range(len(model_short)):
|
| 607 |
+
for j in range(len(model_short)):
|
| 608 |
+
ax.text(j, i, f'{corr.values[i,j]:.2f}', ha='center', va='center',
|
| 609 |
+
fontsize=8, color='white' if abs(corr.values[i,j]) > 0.5 else TEXT)
|
| 610 |
+
plt.colorbar(im, ax=ax, shrink=0.8)
|
| 611 |
+
ax.set_title('P-value Cross-Model Correlation', color=CYAN, fontweight='bold')
|
| 612 |
+
|
| 613 |
+
# 3. Effect size distributions
|
| 614 |
+
ax = axes[0, 2]
|
| 615 |
+
ax.set_facecolor(PANEL)
|
| 616 |
+
beta_cols = [c for c in gwas_df.columns if c.endswith('_Beta')]
|
| 617 |
+
for i, bc in enumerate(beta_cols[:5]):
|
| 618 |
+
data = gwas_df[bc].dropna()
|
| 619 |
+
col = model_colors[i % len(model_colors)]
|
| 620 |
+
ax.hist(data, bins=40, alpha=0.5, color=col,
|
| 621 |
+
label=bc.replace('_Beta', ''), density=True)
|
| 622 |
+
ax.set_xlabel('Effect Size (β)', fontweight='bold')
|
| 623 |
+
ax.set_ylabel('Density', fontweight='bold')
|
| 624 |
+
ax.set_title('Effect Size Distribution', color=CYAN, fontweight='bold')
|
| 625 |
+
ax.legend(fontsize=8, facecolor=CARD, edgecolor=BORDER)
|
| 626 |
+
ax.grid(True, color=BORDER, lw=0.5)
|
| 627 |
+
|
| 628 |
+
# 4. CV scores
|
| 629 |
ax = axes[1, 0]
|
| 630 |
ax.set_facecolor(PANEL)
|
| 631 |
+
cv_data = {k: v for k, v in model_results.items() if 'cv' in k.lower() and isinstance(v, float)}
|
| 632 |
+
if cv_data:
|
| 633 |
+
names = [k.replace('_cv','').replace('cv_','') for k in cv_data]
|
| 634 |
+
vals = list(cv_data.values())
|
| 635 |
+
bar_colors = model_colors[:len(names)]
|
| 636 |
+
bars = ax.bar(names, vals, color=bar_colors, alpha=0.8, edgecolor='none')
|
| 637 |
+
ax.set_ylabel('CV R²', fontweight='bold')
|
| 638 |
+
ax.set_title('Cross-Validation Performance', color=CYAN, fontweight='bold')
|
| 639 |
+
ax.set_ylim(0, max(max(vals)*1.2, 0.1))
|
| 640 |
+
ax.grid(True, color=BORDER, lw=0.5, axis='y')
|
| 641 |
+
for bar, v in zip(bars, vals):
|
| 642 |
+
ax.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 0.005,
|
| 643 |
+
f'{v:.3f}', ha='center', fontsize=9, color=TEXT)
|
| 644 |
+
ax.tick_params(axis='x', colors=TEXT, labelsize=9)
|
| 645 |
+
|
| 646 |
+
# 5. Top markers Venn-style (upset or bar)
|
|
|
|
| 647 |
ax = axes[1, 1]
|
| 648 |
ax.set_facecolor(PANEL)
|
| 649 |
+
sig_col_names = [c for c in gwas_df.columns if c.startswith('Sig_')]
|
| 650 |
+
if len(sig_col_names) >= 2:
|
| 651 |
+
consensus = gwas_df[sig_col_names].sum(axis=1)
|
| 652 |
+
cnt = consensus.value_counts().sort_index()
|
| 653 |
+
ax.bar(cnt.index.astype(str), cnt.values,
|
| 654 |
+
color=[model_colors[min(i, len(model_colors)-1)] for i in cnt.index],
|
| 655 |
+
alpha=0.8, edgecolor='none')
|
| 656 |
+
ax.set_xlabel('# Models Significant', fontweight='bold')
|
| 657 |
+
ax.set_ylabel('# Markers', fontweight='bold')
|
| 658 |
+
ax.set_title('Consensus Significance', color=CYAN, fontweight='bold')
|
| 659 |
+
ax.grid(True, color=BORDER, lw=0.5, axis='y')
|
| 660 |
+
else:
|
| 661 |
+
ax.text(0.5, 0.5, 'Enable multiple models\nfor consensus analysis',
|
| 662 |
+
ha='center', va='center', color=MUTED, fontsize=11,
|
| 663 |
+
transform=ax.transAxes)
|
| 664 |
+
|
| 665 |
+
# 6. Top-10 markers comparison
|
| 666 |
+
ax = axes[1, 2]
|
| 667 |
+
ax.set_facecolor(PANEL)
|
| 668 |
+
top10 = gwas_df.nsmallest(10, pval_cols[0])
|
| 669 |
+
x = np.arange(len(top10))
|
| 670 |
+
width = 0.8 / max(len(pval_cols), 1)
|
| 671 |
+
for i, (col_p, col_m) in enumerate(zip(pval_cols[:4], model_colors[:4])):
|
| 672 |
+
vals = -np.log10(top10[col_p].values + 1e-300)
|
| 673 |
+
offset = (i - len(pval_cols[:4])/2 + 0.5) * width
|
| 674 |
+
ax.bar(x + offset, vals, width * 0.9, color=col_m, alpha=0.8,
|
| 675 |
+
label=col_p.replace('_P',''), edgecolor='none')
|
| 676 |
+
ax.set_xticks(x)
|
| 677 |
+
ax.set_xticklabels(top10['Marker'].str[:8].values, rotation=45, ha='right', fontsize=7)
|
| 678 |
+
ax.set_ylabel('−log₁₀(P)', fontweight='bold')
|
| 679 |
+
ax.set_title('Top 10 Markers (All Models)', color=CYAN, fontweight='bold')
|
| 680 |
+
ax.legend(fontsize=8, facecolor=CARD, edgecolor=BORDER)
|
| 681 |
+
ax.grid(True, color=BORDER, lw=0.5, axis='y')
|
| 682 |
+
|
| 683 |
+
plt.tight_layout(pad=2)
|
| 684 |
+
plt.savefig(save_path, dpi=180, bbox_inches='tight', facecolor=BG)
|
| 685 |
plt.close(fig)
|
| 686 |
|
| 687 |
+
# ═══════════════════════════════════════════════
|
| 688 |
+
# PLOT 6: PCA + PHENOTYPE DISTRIBUTION
|
| 689 |
+
# ═══════════════════════════════════════════════
|
| 690 |
+
|
| 691 |
+
def plot_pca_pheno(genotypes, phenotypes, sample_ids, save_path):
|
| 692 |
+
apply_dark_theme()
|
| 693 |
+
from sklearn.decomposition import PCA
|
| 694 |
+
|
| 695 |
+
fig, axes = plt.subplots(1, 3, figsize=(18, 6), facecolor=BG)
|
| 696 |
+
|
| 697 |
+
# PCA
|
| 698 |
+
ax = axes[0]
|
| 699 |
+
ax.set_facecolor(PANEL)
|
| 700 |
+
try:
|
| 701 |
+
pca = PCA(n_components=min(10, genotypes.shape[1], genotypes.shape[0]))
|
| 702 |
+
G_std = StandardScaler().fit_transform(genotypes)
|
| 703 |
+
pcs = pca.fit_transform(G_std)
|
| 704 |
+
var_exp = pca.explained_variance_ratio_
|
| 705 |
+
|
| 706 |
+
sc = ax.scatter(pcs[:, 0], pcs[:, 1], c=phenotypes, cmap='plasma',
|
| 707 |
+
s=30, alpha=0.8, linewidths=0)
|
| 708 |
+
plt.colorbar(sc, ax=ax, label='Phenotype', shrink=0.8)
|
| 709 |
+
ax.set_xlabel(f'PC1 ({var_exp[0]*100:.1f}%)', fontweight='bold')
|
| 710 |
+
ax.set_ylabel(f'PC2 ({var_exp[1]*100:.1f}%)', fontweight='bold')
|
| 711 |
+
ax.set_title('PCA — Genotype Structure', color=CYAN, fontweight='bold')
|
| 712 |
+
ax.grid(True, color=BORDER, lw=0.5)
|
| 713 |
+
|
| 714 |
+
# PCA scree
|
| 715 |
+
ax2 = axes[1]
|
| 716 |
+
ax2.set_facecolor(PANEL)
|
| 717 |
+
n_pc = min(10, len(var_exp))
|
| 718 |
+
ax2.bar(range(1, n_pc+1), var_exp[:n_pc]*100, color=VIOLET, alpha=0.8, edgecolor='none')
|
| 719 |
+
ax2.plot(range(1, n_pc+1), np.cumsum(var_exp[:n_pc])*100,
|
| 720 |
+
'o-', color=CYAN, lw=2, markersize=5, label='Cumulative')
|
| 721 |
+
ax2.set_xlabel('Principal Component', fontweight='bold')
|
| 722 |
+
ax2.set_ylabel('Variance Explained (%)', fontweight='bold')
|
| 723 |
+
ax2.set_title('PCA Scree Plot', color=CYAN, fontweight='bold')
|
| 724 |
+
ax2.legend(fontsize=9, facecolor=CARD, edgecolor=BORDER)
|
| 725 |
+
ax2.grid(True, color=BORDER, lw=0.5, axis='y')
|
| 726 |
+
|
| 727 |
+
except Exception as e:
|
| 728 |
+
for axi in axes[:2]:
|
| 729 |
+
axi.text(0.5, 0.5, f'PCA error:\n{str(e)[:60]}',
|
| 730 |
+
ha='center', va='center', color=MUTED, transform=axi.transAxes)
|
| 731 |
+
|
| 732 |
+
# Phenotype distribution
|
| 733 |
+
ax3 = axes[2]
|
| 734 |
+
ax3.set_facecolor(PANEL)
|
| 735 |
+
pheno_clean = phenotypes[~np.isnan(phenotypes)]
|
| 736 |
+
ax3.hist(pheno_clean, bins=30, color=EMERALD, alpha=0.8, edgecolor='none', density=True)
|
| 737 |
+
|
| 738 |
+
# Overlay normal curve
|
| 739 |
+
mu, sigma = np.mean(pheno_clean), np.std(pheno_clean)
|
| 740 |
+
x_norm = np.linspace(pheno_clean.min(), pheno_clean.max(), 200)
|
| 741 |
+
ax3.plot(x_norm, stats.norm.pdf(x_norm, mu, sigma), '--', color=ROSE, lw=2, label='Normal fit')
|
| 742 |
+
|
| 743 |
+
# Shapiro-Wilk
|
| 744 |
+
if len(pheno_clean) >= 3:
|
| 745 |
+
stat_sw, p_sw = stats.shapiro(pheno_clean[:5000])
|
| 746 |
+
ax3.text(0.97, 0.95, f'Shapiro-Wilk\nW={stat_sw:.3f}, p={p_sw:.4f}',
|
| 747 |
+
transform=ax3.transAxes, ha='right', va='top', fontsize=9,
|
| 748 |
+
color=TEXT, bbox=dict(boxstyle='round', facecolor=CARD, edgecolor=BORDER, alpha=0.9))
|
| 749 |
+
|
| 750 |
+
ax3.axvline(mu, color=AMBER, ls='--', lw=1.5, label=f'Mean = {mu:.2f}')
|
| 751 |
+
ax3.set_xlabel('Phenotype Value', fontweight='bold')
|
| 752 |
+
ax3.set_ylabel('Density', fontweight='bold')
|
| 753 |
+
ax3.set_title('Phenotype Distribution', color=CYAN, fontweight='bold')
|
| 754 |
+
ax3.legend(fontsize=9, facecolor=CARD, edgecolor=BORDER)
|
| 755 |
+
ax3.grid(True, color=BORDER, lw=0.5)
|
| 756 |
+
|
| 757 |
+
plt.tight_layout(pad=2)
|
| 758 |
+
plt.savefig(save_path, dpi=180, bbox_inches='tight', facecolor=BG)
|
| 759 |
+
plt.close(fig)
|
| 760 |
+
|
| 761 |
+
# ═══════════════════════════════════════════════
|
| 762 |
+
# GWAS MODELS
|
| 763 |
+
# ═══════════════════════════════════════════════
|
| 764 |
+
|
| 765 |
+
def run_linear_regression(geno, pheno):
|
| 766 |
+
n = geno.shape[1]
|
| 767 |
+
pvals, betas, se, r2 = np.ones(n), np.zeros(n), np.zeros(n), np.zeros(n)
|
| 768 |
+
for i in range(n):
|
| 769 |
+
X = geno[:, i]
|
| 770 |
+
if np.std(X) < 1e-8: continue
|
| 771 |
+
try:
|
| 772 |
+
Xc = sm.add_constant(X)
|
| 773 |
+
m = sm.OLS(pheno, Xc).fit()
|
| 774 |
+
pvals[i] = m.pvalues[1]
|
| 775 |
+
betas[i] = m.params[1]
|
| 776 |
+
se[i] = m.bse[1]
|
| 777 |
+
r2[i] = m.rsquared
|
| 778 |
+
except: pass
|
| 779 |
+
return pvals, betas, se, r2
|
| 780 |
+
|
| 781 |
+
def run_mlm(geno, pheno):
|
| 782 |
+
n = geno.shape[1]
|
| 783 |
+
pvals, betas = np.ones(n), np.zeros(n)
|
| 784 |
+
for i in range(n):
|
| 785 |
+
X = geno[:, i]
|
| 786 |
+
if np.std(X) < 1e-8: continue
|
| 787 |
+
try:
|
| 788 |
+
df_m = pd.DataFrame({'y': pheno, 'x': X, 'g': np.arange(len(pheno))})
|
| 789 |
+
m = mixedlm('y ~ x', df_m, groups=df_m['g']).fit(disp=False)
|
| 790 |
+
pvals[i] = m.pvalues.get('x', 1.0)
|
| 791 |
+
betas[i] = m.params.get('x', 0.0)
|
| 792 |
+
except: pass
|
| 793 |
+
return pvals, betas
|
| 794 |
+
|
| 795 |
+
def run_lasso(geno, pheno):
|
| 796 |
scaler = StandardScaler()
|
| 797 |
+
X = scaler.fit_transform(geno)
|
| 798 |
+
m = LassoCV(cv=5, random_state=42, max_iter=5000).fit(X, pheno)
|
| 799 |
+
coef = m.coef_
|
| 800 |
+
# Bootstrap p-values
|
| 801 |
+
pvals = np.ones(len(coef))
|
| 802 |
+
n_boot = 80
|
| 803 |
+
boot_coef = np.zeros((n_boot, len(coef)))
|
| 804 |
+
for k in range(n_boot):
|
| 805 |
+
idx = np.random.choice(len(pheno), len(pheno), replace=True)
|
| 806 |
+
m_b = LassoCV(cv=3, random_state=k, max_iter=3000).fit(X[idx], pheno[idx])
|
| 807 |
+
boot_coef[k] = m_b.coef_
|
| 808 |
+
for i in range(len(coef)):
|
| 809 |
+
std = np.std(boot_coef[:, i])
|
| 810 |
+
if std > 1e-8:
|
| 811 |
+
z = abs(coef[i]) / std
|
| 812 |
+
pvals[i] = 2 * (1 - stats.norm.cdf(z))
|
| 813 |
+
return pvals, coef
|
| 814 |
+
|
| 815 |
+
def run_elasticnet(geno, pheno):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 816 |
scaler = StandardScaler()
|
| 817 |
+
X = scaler.fit_transform(geno)
|
| 818 |
+
m = ElasticNetCV(cv=5, random_state=42, max_iter=5000).fit(X, pheno)
|
| 819 |
+
coef = m.coef_
|
| 820 |
+
pvals = np.ones(len(coef))
|
| 821 |
+
n_boot = 80
|
| 822 |
+
boot_coef = np.zeros((n_boot, len(coef)))
|
| 823 |
+
for k in range(n_boot):
|
| 824 |
+
idx = np.random.choice(len(pheno), len(pheno), replace=True)
|
| 825 |
+
m_b = ElasticNetCV(cv=3, random_state=k, max_iter=3000).fit(X[idx], pheno[idx])
|
| 826 |
+
boot_coef[k] = m_b.coef_
|
| 827 |
+
for i in range(len(coef)):
|
| 828 |
+
std = np.std(boot_coef[:, i])
|
| 829 |
+
if std > 1e-8:
|
| 830 |
+
z = abs(coef[i]) / std
|
| 831 |
+
pvals[i] = 2 * (1 - stats.norm.cdf(z))
|
| 832 |
+
return pvals, coef
|
| 833 |
+
|
| 834 |
+
def run_ridge(geno, pheno):
|
| 835 |
+
scaler = StandardScaler()
|
| 836 |
+
X = scaler.fit_transform(geno)
|
| 837 |
+
m = RidgeCV(alphas=np.logspace(-3, 3, 30), cv=5).fit(X, pheno)
|
| 838 |
+
coef = m.coef_
|
| 839 |
+
# F-test based p-values
|
| 840 |
+
f_stats, pvals = sm.stats.stattools.jarque_bera(pheno)[:2] # fallback
|
| 841 |
+
from sklearn.feature_selection import f_regression
|
| 842 |
+
f_vals, pvals = f_regression(X, pheno)
|
| 843 |
+
return pvals, coef
|
| 844 |
+
|
| 845 |
+
def run_random_forest(geno, pheno):
|
| 846 |
+
scaler = StandardScaler()
|
| 847 |
+
X = scaler.fit_transform(geno)
|
| 848 |
kf = KFold(n_splits=5, shuffle=True, random_state=42)
|
| 849 |
+
imps, cvs = [], []
|
| 850 |
+
m = RandomForestRegressor(n_estimators=150, random_state=42, n_jobs=-1)
|
| 851 |
+
for tr, va in kf.split(X):
|
| 852 |
+
m.fit(X[tr], pheno[tr])
|
| 853 |
+
cvs.append(r2_score(pheno[va], m.predict(X[va])))
|
| 854 |
+
imps.append(m.feature_importances_)
|
| 855 |
+
avg_imp = np.mean(imps, axis=0)
|
| 856 |
+
# Permutation p-values
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 857 |
n_perm = 50
|
| 858 |
+
null_imp = np.zeros((n_perm, X.shape[1]))
|
| 859 |
+
m_full = RandomForestRegressor(n_estimators=100, random_state=99, n_jobs=-1)
|
| 860 |
+
m_full.fit(X, pheno)
|
| 861 |
+
for k in range(n_perm):
|
| 862 |
+
m_full.fit(X, np.random.permutation(pheno))
|
| 863 |
+
null_imp[k] = m_full.feature_importances_
|
| 864 |
+
pvals = np.array([np.mean(null_imp[:, i] >= avg_imp[i]) for i in range(X.shape[1])])
|
| 865 |
+
return pvals, avg_imp, float(np.mean(cvs))
|
| 866 |
+
|
| 867 |
+
def run_gradient_boosting(geno, pheno):
|
| 868 |
+
scaler = StandardScaler()
|
| 869 |
+
X = scaler.fit_transform(geno)
|
| 870 |
+
kf = KFold(n_splits=5, shuffle=True, random_state=42)
|
| 871 |
+
imps, cvs = [], []
|
| 872 |
+
m = GradientBoostingRegressor(n_estimators=120, random_state=42)
|
| 873 |
+
for tr, va in kf.split(X):
|
| 874 |
+
m.fit(X[tr], pheno[tr])
|
| 875 |
+
cvs.append(r2_score(pheno[va], m.predict(X[va])))
|
| 876 |
+
imps.append(m.feature_importances_)
|
| 877 |
+
avg_imp = np.mean(imps, axis=0)
|
| 878 |
+
n_perm = 50
|
| 879 |
+
null_imp = np.zeros((n_perm, X.shape[1]))
|
| 880 |
+
m_full = GradientBoostingRegressor(n_estimators=80, random_state=99)
|
| 881 |
+
m_full.fit(X, pheno)
|
| 882 |
+
for k in range(n_perm):
|
| 883 |
+
m_full.fit(X, np.random.permutation(pheno))
|
| 884 |
+
null_imp[k] = m_full.feature_importances_
|
| 885 |
+
pvals = np.array([np.mean(null_imp[:, i] >= avg_imp[i]) for i in range(X.shape[1])])
|
| 886 |
+
return pvals, avg_imp, float(np.mean(cvs))
|
| 887 |
+
|
| 888 |
+
# ═══════════════════════════════════════════════
|
| 889 |
+
# CSV PARSER
|
| 890 |
+
# ═══════════════════════════════════════════════
|
| 891 |
+
|
| 892 |
+
def parse_gwas_csv(filepath):
|
| 893 |
df = pd.read_csv(filepath, header=0, dtype=str)
|
|
|
|
|
|
|
| 894 |
marker_cols = df.columns[2:].tolist()
|
|
|
|
|
|
|
| 895 |
chr_row = df.iloc[0]
|
| 896 |
+
chromosome_dict, position_dict = {}, {}
|
| 897 |
+
|
|
|
|
| 898 |
for m in marker_cols:
|
| 899 |
val = str(chr_row[m]).strip()
|
|
|
|
| 900 |
if ':' in val:
|
| 901 |
parts = val.split(':')
|
| 902 |
chromosome_dict[m] = parts[0]
|
| 903 |
+
try: position_dict[m] = float(parts[1])
|
| 904 |
+
except: position_dict[m] = 0.0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 905 |
else:
|
| 906 |
+
if val.endswith('.0'): val = val[:-2]
|
|
|
|
|
|
|
| 907 |
chromosome_dict[m] = val
|
| 908 |
+
position_dict[m] = 0.0
|
| 909 |
+
|
| 910 |
+
df_s = df.iloc[1:].reset_index(drop=True)
|
| 911 |
+
sample_ids = df_s.iloc[:, 0].astype(str).values
|
| 912 |
+
phenotypes = pd.to_numeric(df_s.iloc[:, 1], errors='coerce').values
|
| 913 |
+
geno_raw = df_s[marker_cols].apply(pd.to_numeric, errors='coerce').replace(-1, np.nan)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 914 |
genotypes = geno_raw.values
|
| 915 |
+
positions = [position_dict.get(m, 0.0) for m in marker_cols]
|
| 916 |
+
|
|
|
|
| 917 |
return sample_ids, phenotypes, genotypes, marker_cols, chromosome_dict, positions
|
| 918 |
|
| 919 |
+
# ═══════════════════════════════════════════════
|
| 920 |
+
# MAIN ANALYSIS
|
| 921 |
+
# ═══════════════════════════════════════════════
|
| 922 |
|
| 923 |
+
def run_gwas_pipeline(input_file, miss_rate_sample, miss_rate_marker, maf_thresh,
|
| 924 |
+
use_mlm, use_lasso, use_enet, use_ridge, use_rf, use_gb):
|
|
|
|
|
|
|
| 925 |
try:
|
| 926 |
if input_file is None:
|
| 927 |
return ("⚠️ Please upload a CSV file.", None, None, None, None, None, None, None)
|
| 928 |
+
|
| 929 |
temp_dir = tempfile.mkdtemp()
|
| 930 |
+
plots_dir = os.path.join(temp_dir, 'plots')
|
| 931 |
+
os.makedirs(plots_dir, exist_ok=True)
|
| 932 |
+
|
| 933 |
+
miss_s = miss_rate_sample / 100.0
|
| 934 |
+
miss_m = miss_rate_marker / 100.0
|
| 935 |
+
maf_f = maf_thresh / 100.0
|
| 936 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
| 937 |
sample_ids, phenotypes, genotypes, marker_names, chromosome_dict, positions = \
|
| 938 |
+
parse_gwas_csv(input_file)
|
| 939 |
+
|
| 940 |
+
n_samples, n_markers = len(sample_ids), len(marker_names)
|
| 941 |
+
|
| 942 |
+
# QC
|
| 943 |
+
m_miss = np.isnan(genotypes).sum(axis=0) / max(n_samples, 1)
|
| 944 |
+
s_miss = np.isnan(genotypes).sum(axis=1) / max(n_markers, 1)
|
| 945 |
+
maf = np.array([min((np.nanmean(c)/2), 1-np.nanmean(c)/2)
|
| 946 |
+
if not np.all(np.isnan(c)) else 0
|
| 947 |
+
for c in genotypes.T])
|
| 948 |
+
|
| 949 |
+
qc_m = (m_miss < miss_m) & (maf >= maf_f)
|
| 950 |
+
qc_s = s_miss < miss_s
|
| 951 |
+
|
| 952 |
+
# Adaptive relaxation
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 953 |
fallback_msg = ""
|
| 954 |
+
for rs, rm in [(miss_s, miss_m),(0.6,0.6),(0.7,0.7),(0.8,0.8),(0.9,0.9),(1.0,1.0)]:
|
| 955 |
+
qc_m_t = (m_miss < rm) & (maf >= maf_f)
|
| 956 |
+
qc_s_t = s_miss < rs
|
| 957 |
+
if qc_s_t.sum() >= 10:
|
| 958 |
+
qc_m, qc_s = qc_m_t, qc_s_t
|
| 959 |
+
if rs > miss_s or rm > miss_m:
|
| 960 |
+
fallback_msg = f"\n> ⚠️ QC relaxed to sample <{rs*100:.0f}% / marker <{rm*100:.0f}%\n"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 961 |
break
|
| 962 |
+
|
|
|
|
| 963 |
geno_qc = genotypes[np.ix_(qc_s, qc_m)].copy()
|
| 964 |
pheno_qc = phenotypes[qc_s]
|
| 965 |
ids_qc = sample_ids[qc_s]
|
| 966 |
mnames_qc = [marker_names[i] for i in range(n_markers) if qc_m[i]]
|
| 967 |
+
chrom_qc = [chromosome_dict[m] for m in mnames_qc]
|
| 968 |
+
pos_qc = [positions[i] for i in range(n_markers) if qc_m[i]]
|
| 969 |
+
|
| 970 |
+
# Imputation
|
| 971 |
for i in range(geno_qc.shape[1]):
|
| 972 |
col = geno_qc[:, i]
|
| 973 |
+
nans = np.isnan(col)
|
| 974 |
+
if nans.any():
|
| 975 |
+
geno_qc[nans, i] = np.nanmean(col) if not np.all(nans) else 0.0
|
| 976 |
+
|
| 977 |
+
valid = ~np.isnan(pheno_qc)
|
| 978 |
+
geno_qc, pheno_qc, ids_qc = geno_qc[valid], pheno_qc[valid], ids_qc[valid]
|
| 979 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 980 |
if len(ids_qc) < 10:
|
| 981 |
+
return (f"## ⚠️ Only {len(ids_qc)} samples passed QC (need ≥10). "
|
| 982 |
+
f"Try increasing missing rate thresholds.",
|
| 983 |
+
None, None, None, None, None, None, None)
|
| 984 |
+
|
| 985 |
+
n_m = len(mnames_qc)
|
| 986 |
+
bonf = 0.05 / n_m
|
| 987 |
+
model_results = {}
|
| 988 |
+
|
| 989 |
+
# --- Run Models ---
|
| 990 |
+
print("▶ Linear Regression...")
|
| 991 |
+
lr_p, lr_b, lr_se, lr_r2 = run_linear_regression(geno_qc, pheno_qc)
|
| 992 |
+
model_results['LR_P'] = lr_p
|
| 993 |
+
model_results['LR_Beta'] = lr_b
|
| 994 |
+
lod_lr = -np.log10(lr_p + 1e-300)
|
| 995 |
+
|
| 996 |
+
pval_dict_for_qq = {'Linear': lr_p}
|
| 997 |
+
|
| 998 |
+
if use_mlm:
|
| 999 |
+
print("▶ Mixed Linear Model...")
|
| 1000 |
+
mlm_p, mlm_b = run_mlm(geno_qc, pheno_qc)
|
| 1001 |
+
model_results['MLM_P'] = mlm_p
|
| 1002 |
+
model_results['MLM_Beta'] = mlm_b
|
| 1003 |
+
pval_dict_for_qq['MLM'] = mlm_p
|
| 1004 |
+
|
| 1005 |
+
if use_lasso:
|
| 1006 |
+
print("▶ LASSO...")
|
| 1007 |
+
las_p, las_c = run_lasso(geno_qc, pheno_qc)
|
| 1008 |
+
model_results['LASSO_P'] = las_p
|
| 1009 |
+
model_results['LASSO_Beta'] = las_c
|
| 1010 |
+
pval_dict_for_qq['LASSO'] = las_p
|
| 1011 |
+
|
| 1012 |
+
if use_enet:
|
| 1013 |
+
print("▶ ElasticNet...")
|
| 1014 |
+
en_p, en_c = run_elasticnet(geno_qc, pheno_qc)
|
| 1015 |
+
model_results['EN_P'] = en_p
|
| 1016 |
+
model_results['EN_Beta'] = en_c
|
| 1017 |
+
pval_dict_for_qq['ElasticNet'] = en_p
|
| 1018 |
+
|
| 1019 |
+
if use_ridge:
|
| 1020 |
+
print("▶ Ridge Regression...")
|
| 1021 |
+
rd_p, rd_c = run_ridge(geno_qc, pheno_qc)
|
| 1022 |
+
model_results['Ridge_P'] = rd_p
|
| 1023 |
+
model_results['Ridge_Beta'] = rd_c
|
| 1024 |
+
pval_dict_for_qq['RidgeCV'] = rd_p
|
| 1025 |
+
|
| 1026 |
+
if use_rf:
|
| 1027 |
+
print("▶ Random Forest...")
|
| 1028 |
+
rf_p, rf_imp, rf_cv = run_random_forest(geno_qc, pheno_qc)
|
| 1029 |
+
model_results['RF_P'] = rf_p
|
| 1030 |
+
model_results['RF_Imp'] = rf_imp
|
| 1031 |
+
model_results['rf_cv'] = rf_cv
|
| 1032 |
+
pval_dict_for_qq['RandomForest'] = rf_p
|
| 1033 |
+
|
| 1034 |
+
if use_gb:
|
| 1035 |
+
print("▶ Gradient Boosting...")
|
| 1036 |
+
gb_p, gb_imp, gb_cv = run_gradient_boosting(geno_qc, pheno_qc)
|
| 1037 |
+
model_results['GB_P'] = gb_p
|
| 1038 |
+
model_results['GB_Imp'] = gb_imp
|
| 1039 |
+
model_results['gb_cv'] = gb_cv
|
| 1040 |
+
pval_dict_for_qq['GradBoost'] = gb_p
|
| 1041 |
+
|
| 1042 |
+
# Build results DataFrame
|
| 1043 |
+
gwas_df = pd.DataFrame({'Marker': mnames_qc, 'Chromosome': chrom_qc,
|
| 1044 |
+
'Position': pos_qc, 'LR_P': lr_p,
|
| 1045 |
+
'LR_Beta': lr_b, 'LR_SE': lr_se, 'LR_R2': lr_r2,
|
| 1046 |
+
'LOD': lod_lr})
|
| 1047 |
+
for k, v in model_results.items():
|
| 1048 |
+
if k in ('rf_cv', 'gb_cv'): continue
|
| 1049 |
+
if hasattr(v, '__len__') and len(v) == n_m:
|
| 1050 |
+
gwas_df[k] = v
|
| 1051 |
+
|
| 1052 |
+
# Significance flags
|
| 1053 |
+
pval_cols = [c for c in gwas_df.columns if c.endswith('_P')]
|
| 1054 |
+
for pc in pval_cols:
|
| 1055 |
+
gwas_df[f'Sig_{pc}'] = (gwas_df[pc] < bonf).astype(int)
|
| 1056 |
+
|
| 1057 |
+
sig_cols = [c for c in gwas_df.columns if c.startswith('Sig_')]
|
| 1058 |
+
gwas_df['Consensus'] = gwas_df[sig_cols].sum(axis=1)
|
| 1059 |
+
gwas_df = gwas_df.sort_values('LR_P').reset_index(drop=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1060 |
gwas_df['Rank'] = range(1, len(gwas_df) + 1)
|
| 1061 |
+
|
| 1062 |
+
# Save CSV
|
| 1063 |
+
csv_path = os.path.join(temp_dir, 'gwas_results.csv')
|
| 1064 |
+
gwas_df.to_csv(csv_path, index=False)
|
| 1065 |
+
|
| 1066 |
+
# --- Plots ---
|
| 1067 |
+
sig_set = set(np.where(lr_p < bonf)[0])
|
| 1068 |
+
bonf_thresh = -np.log10(bonf)
|
| 1069 |
+
|
| 1070 |
+
p1 = os.path.join(plots_dir, '1_manhattan_lod.png')
|
| 1071 |
+
plot_manhattan_lod(mnames_qc, chrom_qc, lr_p, lod_lr, sig_set, bonf_thresh, p1)
|
| 1072 |
+
|
| 1073 |
+
p2 = os.path.join(plots_dir, '2_qq_plot.png')
|
| 1074 |
+
plot_qq(pval_dict_for_qq, p2)
|
| 1075 |
+
|
| 1076 |
+
p3 = os.path.join(plots_dir, '3_ld_decay_mb.png')
|
| 1077 |
+
ld_stats = plot_ld_decay_mb(geno_qc, chrom_qc, pos_qc, p3)
|
| 1078 |
+
|
| 1079 |
+
p4 = os.path.join(plots_dir, '4_circos.png')
|
| 1080 |
+
plot_circos_manhattan(mnames_qc, chrom_qc, lr_p, lod_lr, p4)
|
| 1081 |
+
|
| 1082 |
+
p5 = os.path.join(plots_dir, '5_model_comparison.png')
|
| 1083 |
+
plot_model_comparison(gwas_df, model_results, p5)
|
| 1084 |
+
|
| 1085 |
+
p6 = os.path.join(plots_dir, '6_pca_pheno.png')
|
| 1086 |
+
plot_pca_pheno(geno_qc, pheno_qc, ids_qc, p6)
|
| 1087 |
+
|
| 1088 |
+
# ZIP
|
| 1089 |
+
zip_path = os.path.join(temp_dir, 'GWAS_Nexus_Results.zip')
|
| 1090 |
with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf:
|
| 1091 |
+
zf.write(csv_path, 'gwas_results.csv')
|
| 1092 |
+
for pf in [p1,p2,p3,p4,p5,p6]:
|
| 1093 |
+
if os.path.exists(pf):
|
| 1094 |
+
zf.write(pf, os.path.join('plots', os.path.basename(pf)))
|
| 1095 |
+
|
| 1096 |
+
# Summary
|
| 1097 |
+
n_sig_lr = int((lr_p < bonf).sum())
|
| 1098 |
+
consensus_n = int((gwas_df['Consensus'] >= 2).sum())
|
| 1099 |
+
models_run = ['Linear'] + (['MLM'] if use_mlm else []) + \
|
| 1100 |
+
(['LASSO'] if use_lasso else []) + (['ElasticNet'] if use_enet else []) + \
|
| 1101 |
+
(['Ridge'] if use_ridge else []) + (['RandomForest'] if use_rf else []) + \
|
| 1102 |
+
(['GradBoost'] if use_gb else [])
|
| 1103 |
+
|
| 1104 |
+
ld_mean_r2 = np.mean([v['mean_r2'] for v in ld_stats.values()]) if ld_stats else 0
|
| 1105 |
+
ld_mean_dp = np.mean([v['mean_dprime'] for v in ld_stats.values()]) if ld_stats else 0
|
| 1106 |
+
|
| 1107 |
+
summary = f"""## ✅ GWAS Nexus — Analysis Complete
|
|
|
|
| 1108 |
{fallback_msg}
|
| 1109 |
+
### 📋 Quality Control
|
| 1110 |
+
| | Raw | Post-QC |
|
| 1111 |
+
|---|---|---|
|
| 1112 |
+
| Samples | {n_samples} | **{len(ids_qc)}** |
|
| 1113 |
+
| Markers | {n_markers} | **{n_m}** |
|
| 1114 |
+
| Chromosomes | — | **{len(set(chrom_qc))}** |
|
| 1115 |
+
|
| 1116 |
+
MAF filter: ≥ {maf_thresh:.1f}% · Bonferroni α = {bonf:.2e}
|
| 1117 |
+
|
| 1118 |
+
### 🧬 GWAS Models Completed
|
| 1119 |
+
| Model | Sig. Markers |
|
| 1120 |
+
|---|---|
|
| 1121 |
+
{ chr(10).join(f"| {m} | {int((model_results.get(f'{m}_P' if m != 'Linear' else 'LR_P', np.ones(n_m)) < bonf).sum())} |" for m in models_run) }
|
| 1122 |
+
|
| 1123 |
+
**Consensus (≥2 models):** {consensus_n} markers
|
| 1124 |
+
|
| 1125 |
+
### 📐 LD Statistics
|
| 1126 |
+
- Mean r²: **{ld_mean_r2:.4f}**
|
| 1127 |
+
- Mean D': **{ld_mean_dp:.4f}**
|
| 1128 |
+
|
| 1129 |
+
### 🏆 Top 10 Markers
|
| 1130 |
+
{gwas_df[['Rank','Marker','Chromosome','LR_P','LOD','Consensus']].head(10).to_markdown(index=False)}
|
| 1131 |
|
| 1132 |
+
### 📁 Output Files
|
| 1133 |
+
`gwas_results.csv` · `manhattan_lod.png` · `qq_plot.png`
|
| 1134 |
+
`ld_decay_mb.png` · `circos.png` · `model_comparison.png` · `pca_pheno.png`
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1135 |
"""
|
| 1136 |
+
return (summary, p1, p2, p3, p4, p5, zip_path, p6)
|
| 1137 |
+
|
|
|
|
|
|
|
| 1138 |
except Exception as e:
|
|
|
|
| 1139 |
return (f"## ❌ Error\n```\n{e}\n\n{traceback.format_exc()}\n```",
|
| 1140 |
None, None, None, None, None, None, None)
|
| 1141 |
|
| 1142 |
+
# ═══════════════════════════════════════════════
|
| 1143 |
+
# THEME CSS + HTML
|
| 1144 |
+
# ═══════════════════════════════════════════════
|
| 1145 |
+
|
| 1146 |
+
THEME_CSS = """
|
| 1147 |
+
@import url('https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@300;400;500;600;700&family=JetBrains+Mono:wght@400;500&display=swap');
|
| 1148 |
+
|
| 1149 |
+
:root {
|
| 1150 |
+
--bg: #07090F;
|
| 1151 |
+
--panel: #0D1117;
|
| 1152 |
+
--card: #111827;
|
| 1153 |
+
--border: #1F2937;
|
| 1154 |
+
--text: #E2E8F0;
|
| 1155 |
+
--muted: #64748B;
|
| 1156 |
+
--cyan: #06B6D4;
|
| 1157 |
+
--violet: #8B5CF6;
|
| 1158 |
+
--emerald: #10B981;
|
| 1159 |
+
--rose: #F43F5E;
|
| 1160 |
+
--amber: #F59E0B;
|
| 1161 |
+
}
|
| 1162 |
+
|
| 1163 |
+
* { font-family: 'Space Grotesk', sans-serif !important; box-sizing: border-box; }
|
| 1164 |
+
|
| 1165 |
+
body, .gradio-container {
|
| 1166 |
+
background: var(--bg) !important;
|
| 1167 |
+
color: var(--text) !important;
|
| 1168 |
+
}
|
| 1169 |
+
|
| 1170 |
+
.gradio-container { max-width: 1400px !important; margin: 0 auto !important; }
|
| 1171 |
+
|
| 1172 |
+
.hero-wrap {
|
| 1173 |
+
background: linear-gradient(135deg, #07090F 0%, #0f172a 40%, #07090F 100%);
|
| 1174 |
+
border: 1px solid var(--border);
|
| 1175 |
+
border-radius: 20px;
|
| 1176 |
+
padding: 48px 40px 40px;
|
| 1177 |
+
margin-bottom: 24px;
|
| 1178 |
+
position: relative;
|
| 1179 |
+
overflow: hidden;
|
| 1180 |
+
}
|
| 1181 |
+
.hero-wrap::before {
|
| 1182 |
+
content: '';
|
| 1183 |
+
position: absolute; inset: 0;
|
| 1184 |
+
background: radial-gradient(ellipse 60% 50% at 50% 0%, rgba(6,182,212,0.08) 0%, transparent 70%);
|
| 1185 |
+
}
|
| 1186 |
+
.hero-tag {
|
| 1187 |
+
display: inline-block;
|
| 1188 |
+
background: rgba(6,182,212,0.1);
|
| 1189 |
+
border: 1px solid rgba(6,182,212,0.3);
|
| 1190 |
+
color: var(--cyan);
|
| 1191 |
+
font-size: 11px; font-weight: 600; letter-spacing: 2px;
|
| 1192 |
+
padding: 4px 12px; border-radius: 999px;
|
| 1193 |
+
text-transform: uppercase; margin-bottom: 20px;
|
| 1194 |
+
}
|
| 1195 |
+
.hero-title {
|
| 1196 |
+
font-size: clamp(28px, 4vw, 48px); font-weight: 700;
|
| 1197 |
+
line-height: 1.1; color: var(--text); margin-bottom: 12px;
|
| 1198 |
+
}
|
| 1199 |
+
.hero-title span { color: var(--cyan); }
|
| 1200 |
+
.hero-sub {
|
| 1201 |
+
font-size: 15px; color: var(--muted); max-width: 600px; line-height: 1.6;
|
| 1202 |
+
}
|
| 1203 |
+
.hero-badges { display: flex; gap: 8px; flex-wrap: wrap; margin-top: 20px; }
|
| 1204 |
+
.badge {
|
| 1205 |
+
font-size: 11px; font-weight: 600; padding: 4px 10px;
|
| 1206 |
+
border-radius: 6px; border: 1px solid;
|
| 1207 |
+
}
|
| 1208 |
+
.badge-c { color: var(--cyan); border-color: rgba(6,182,212,0.3); background: rgba(6,182,212,0.08); }
|
| 1209 |
+
.badge-v { color: var(--violet); border-color: rgba(139,92,246,0.3); background: rgba(139,92,246,0.08); }
|
| 1210 |
+
.badge-e { color: var(--emerald); border-color: rgba(16,185,129,0.3); background: rgba(16,185,129,0.08); }
|
| 1211 |
+
.badge-r { color: var(--rose); border-color: rgba(244,63,94,0.3); background: rgba(244,63,94,0.08); }
|
| 1212 |
+
.badge-a { color: var(--amber); border-color: rgba(245,158,11,0.3); background: rgba(245,158,11,0.08); }
|
| 1213 |
+
|
| 1214 |
+
.sec-label {
|
| 1215 |
+
font-size: 10px; font-weight: 700; letter-spacing: 2px;
|
| 1216 |
+
text-transform: uppercase; color: var(--muted);
|
| 1217 |
+
margin: 24px 0 12px; padding-left: 2px;
|
| 1218 |
+
border-left: 3px solid var(--cyan); padding-left: 10px;
|
| 1219 |
+
}
|
| 1220 |
+
|
| 1221 |
+
.ctrl-panel {
|
| 1222 |
+
background: var(--card);
|
| 1223 |
+
border: 1px solid var(--border);
|
| 1224 |
+
border-radius: 14px; padding: 20px;
|
| 1225 |
+
margin-bottom: 12px;
|
| 1226 |
+
}
|
| 1227 |
+
|
| 1228 |
+
gradio-app, .gr-block, .gr-panel,
|
| 1229 |
+
div[data-testid="column"], .gradio-column,
|
| 1230 |
+
.gradio-row, div.svelte-1gfkfd6 {
|
| 1231 |
+
background: transparent !important;
|
| 1232 |
+
}
|
| 1233 |
+
|
| 1234 |
+
.gr-form, .gr-box { background: transparent !important; }
|
| 1235 |
+
|
| 1236 |
+
label span, .gr-label { color: var(--muted) !important; font-size: 12px !important; }
|
| 1237 |
+
|
| 1238 |
+
input[type=range] { accent-color: var(--cyan) !important; }
|
| 1239 |
+
|
| 1240 |
+
.gr-button-primary {
|
| 1241 |
+
background: linear-gradient(135deg, var(--cyan), #0284C7) !important;
|
| 1242 |
+
border: none !important; border-radius: 10px !important;
|
| 1243 |
+
font-weight: 700 !important; font-size: 14px !important;
|
| 1244 |
+
color: #07090F !important; letter-spacing: 0.5px;
|
| 1245 |
+
padding: 14px 28px !important;
|
| 1246 |
+
transition: opacity 0.2s, transform 0.15s !important;
|
| 1247 |
+
}
|
| 1248 |
+
.gr-button-primary:hover {
|
| 1249 |
+
opacity: 0.9 !important; transform: translateY(-1px) !important;
|
| 1250 |
+
}
|
| 1251 |
+
|
| 1252 |
+
.result-card {
|
| 1253 |
+
background: var(--card); border: 1px solid var(--border);
|
| 1254 |
+
border-radius: 14px; padding: 24px;
|
| 1255 |
+
}
|
| 1256 |
+
.result-card h2 { color: var(--cyan) !important; }
|
| 1257 |
+
.result-card h3 { color: var(--text) !important; border-bottom: 1px solid var(--border); padding-bottom: 6px; }
|
| 1258 |
+
.result-card table { width: 100%; border-collapse: collapse; }
|
| 1259 |
+
.result-card th { color: var(--muted); font-size: 11px; font-weight: 600; text-transform: uppercase; letter-spacing: 1px; padding: 8px; border-bottom: 1px solid var(--border); }
|
| 1260 |
+
.result-card td { padding: 8px; border-bottom: 1px solid rgba(31,41,55,0.5); font-size: 13px; font-family: 'JetBrains Mono', monospace !important; }
|
| 1261 |
+
.result-card code { background: rgba(6,182,212,0.1); color: var(--cyan); padding: 2px 6px; border-radius: 4px; font-size: 12px; }
|
| 1262 |
+
|
| 1263 |
+
.pipe-info {
|
| 1264 |
+
background: rgba(6,182,212,0.05);
|
| 1265 |
+
border: 1px solid rgba(6,182,212,0.15);
|
| 1266 |
+
border-radius: 12px; padding: 16px; margin-top: 16px;
|
| 1267 |
+
}
|
| 1268 |
+
.pipe-info-title { font-size: 11px; font-weight: 700; color: var(--cyan); text-transform: uppercase; letter-spacing: 1.5px; margin-bottom: 10px; }
|
| 1269 |
+
.pipe-step { display: flex; align-items: center; gap: 10px; margin-bottom: 8px; }
|
| 1270 |
+
.pipe-dot { width: 6px; height: 6px; border-radius: 50%; background: var(--cyan); flex-shrink: 0; }
|
| 1271 |
+
.pipe-step span { font-size: 12px; color: var(--muted); }
|
| 1272 |
+
|
| 1273 |
+
.gr-checkbox-label { color: var(--text) !important; font-size: 13px !important; }
|
| 1274 |
+
.gr-file-label { color: var(--muted) !important; }
|
| 1275 |
+
|
| 1276 |
+
.img-out img { border-radius: 10px; border: 1px solid var(--border); }
|
| 1277 |
+
|
| 1278 |
+
.tab-nav button { color: var(--muted) !important; font-size: 13px !important; }
|
| 1279 |
+
.tab-nav button.selected { color: var(--cyan) !important; border-bottom-color: var(--cyan) !important; }
|
| 1280 |
+
|
| 1281 |
+
footer { display: none !important; }
|
| 1282 |
+
"""
|
| 1283 |
+
|
| 1284 |
+
HERO_HTML = """
|
| 1285 |
+
<div class="hero-wrap">
|
| 1286 |
+
<div class="hero-tag">Genome-Wide Association Studies</div>
|
| 1287 |
+
<div class="hero-title">GWAS <span>Nexus</span></div>
|
| 1288 |
+
<div class="hero-sub">
|
| 1289 |
+
Advanced multi-model GWAS platform · Manhattan, Circos, LD Decay (Mb), QQ plots ·
|
| 1290 |
+
7 statistical models including ML-based approaches · Automated QC with adaptive thresholds
|
| 1291 |
+
</div>
|
| 1292 |
+
<div class="hero-badges">
|
| 1293 |
+
<span class="badge badge-c">Linear Regression</span>
|
| 1294 |
+
<span class="badge badge-v">Mixed Linear Model</span>
|
| 1295 |
+
<span class="badge badge-e">LASSO · ElasticNet · Ridge</span>
|
| 1296 |
+
<span class="badge badge-r">Random Forest</span>
|
| 1297 |
+
<span class="badge badge-a">Gradient Boosting</span>
|
| 1298 |
+
</div>
|
| 1299 |
+
</div>
|
| 1300 |
+
"""
|
| 1301 |
+
|
| 1302 |
+
FMT_HTML = """
|
| 1303 |
+
<div class="ctrl-panel">
|
| 1304 |
+
<div style="font-size:11px;font-weight:700;color:#06B6D4;text-transform:uppercase;letter-spacing:2px;margin-bottom:12px;">CSV Format</div>
|
| 1305 |
+
<div style="font-family:'JetBrains Mono',monospace;font-size:11px;color:#64748B;line-height:1.8;">
|
| 1306 |
+
Row 1: ID, Phenotype, <span style="color:#06B6D4">Chr</span><br>
|
| 1307 |
+
Row 2+: ID, value, <span style="color:#10B981">0/1/2</span><br>
|
| 1308 |
+
Genotypes: 0=AA, 1=AB, 2=BB<br>
|
| 1309 |
+
Chr format: <span style="color:#F59E0B">1</span> or <span style="color:#F59E0B">1:12345678</span>
|
| 1310 |
+
</div>
|
| 1311 |
+
</div>
|
| 1312 |
+
"""
|
| 1313 |
+
|
| 1314 |
+
PIPE_HTML = """
|
| 1315 |
+
<div class="pipe-info">
|
| 1316 |
+
<div class="pipe-info-title">Pipeline Steps</div>
|
| 1317 |
+
<div class="pipe-step"><div class="pipe-dot"></div><span>Parse CSV & validate format</span></div>
|
| 1318 |
+
<div class="pipe-step"><div class="pipe-dot"></div><span>QC: missing rate + MAF filters</span></div>
|
| 1319 |
+
<div class="pipe-step"><div class="pipe-dot"></div><span>Genotype imputation (mean)</span></div>
|
| 1320 |
+
<div class="pipe-step"><div class="pipe-dot"></div><span>Run selected GWAS models</span></div>
|
| 1321 |
+
<div class="pipe-step"><div class="pipe-dot"></div><span>Generate 6 publication plots</span></div>
|
| 1322 |
+
<div class="pipe-step"><div class="pipe-dot"></div><span>Export ZIP with all results</span></div>
|
| 1323 |
+
</div>
|
| 1324 |
+
"""
|
| 1325 |
+
|
| 1326 |
+
# ═══════════════════════════════════════════════
|
| 1327 |
# GRADIO INTERFACE
|
| 1328 |
+
# ═══════════════════════════════════════════════
|
| 1329 |
+
|
| 1330 |
+
with gr.Blocks(css=THEME_CSS, title="GWAS Nexus", theme=gr.themes.Base()) as app:
|
| 1331 |
|
|
|
|
|
|
|
| 1332 |
gr.HTML(HERO_HTML)
|
| 1333 |
+
|
| 1334 |
with gr.Row():
|
| 1335 |
+
# LEFT COLUMN — Controls
|
| 1336 |
+
with gr.Column(scale=1, min_width=320):
|
| 1337 |
gr.HTML(FMT_HTML)
|
| 1338 |
+
|
| 1339 |
+
gr.HTML('<div class="sec-label">Data Input</div>')
|
| 1340 |
+
input_file = gr.File(label="Upload CSV", file_types=[".csv"])
|
| 1341 |
+
|
| 1342 |
+
gr.HTML('<div class="sec-label">QC Thresholds</div>')
|
|
|
|
|
|
|
| 1343 |
miss_rate_sample = gr.Slider(10, 100, value=50, step=5,
|
| 1344 |
+
label="Sample Missing Rate (%)")
|
| 1345 |
miss_rate_marker = gr.Slider(10, 100, value=50, step=5,
|
| 1346 |
+
label="Marker Missing Rate (%)")
|
| 1347 |
maf_thresh = gr.Slider(0.0, 10.0, value=1.0, step=0.5,
|
| 1348 |
+
label="MAF Threshold (%)")
|
| 1349 |
+
|
| 1350 |
+
gr.HTML('<div class="sec-label">Model Selection</div>')
|
| 1351 |
+
use_mlm = gr.Checkbox(label="Mixed Linear Model (MLM)", value=True)
|
| 1352 |
+
use_lasso = gr.Checkbox(label="LASSO Regression", value=True)
|
| 1353 |
+
use_enet = gr.Checkbox(label="ElasticNet Regression", value=True)
|
| 1354 |
+
use_ridge = gr.Checkbox(label="Ridge Regression (RidgeCV)", value=True)
|
| 1355 |
+
use_rf = gr.Checkbox(label="Random Forest", value=False)
|
| 1356 |
+
use_gb = gr.Checkbox(label="Gradient Boosting", value=False)
|
| 1357 |
+
|
| 1358 |
+
run_btn = gr.Button("⚡ Run GWAS Analysis", variant="primary", size="lg")
|
| 1359 |
+
|
| 1360 |
gr.HTML(PIPE_HTML)
|
| 1361 |
+
|
| 1362 |
+
# RIGHT COLUMN — Summary
|
| 1363 |
with gr.Column(scale=2):
|
| 1364 |
+
gr.HTML('<div class="sec-label">Analysis Summary</div>')
|
| 1365 |
+
with gr.Column(elem_classes=["result-card"]):
|
| 1366 |
+
summary_out = gr.Markdown(
|
| 1367 |
+
"*Upload a CSV file and click **Run GWAS Analysis** to begin.*"
|
| 1368 |
+
)
|
| 1369 |
+
|
| 1370 |
+
# ─── Visualizations ───
|
| 1371 |
+
gr.HTML('<div class="sec-label" style="margin-top:20px">Visualizations</div>')
|
| 1372 |
+
|
| 1373 |
+
with gr.Tabs():
|
| 1374 |
+
with gr.TabItem("📊 Manhattan + LOD"):
|
| 1375 |
+
manhattan_out = gr.Image(label="Manhattan Plot with LOD Scores",
|
| 1376 |
+
elem_classes=["img-out"])
|
| 1377 |
+
with gr.TabItem("📈 QQ Plot"):
|
| 1378 |
+
qq_out = gr.Image(label="QQ Plot — All Models",
|
| 1379 |
+
elem_classes=["img-out"])
|
| 1380 |
+
with gr.TabItem("🔗 LD Decay (Mb)"):
|
| 1381 |
+
ld_out = gr.Image(label="LD Decay Analysis in Megabases",
|
| 1382 |
+
elem_classes=["img-out"])
|
| 1383 |
+
with gr.TabItem("🌐 Circos Plot"):
|
| 1384 |
+
circos_out = gr.Image(label="Circos Manhattan Plot",
|
| 1385 |
+
elem_classes=["img-out"])
|
| 1386 |
+
with gr.TabItem("🤖 Model Comparison"):
|
| 1387 |
+
comp_out = gr.Image(label="Multi-Model Comparison",
|
| 1388 |
+
elem_classes=["img-out"])
|
| 1389 |
+
with gr.TabItem("🔬 PCA + Phenotype"):
|
| 1390 |
+
pca_out = gr.Image(label="PCA & Phenotype Distribution",
|
| 1391 |
+
elem_classes=["img-out"])
|
| 1392 |
+
|
| 1393 |
+
gr.HTML('<div class="sec-label" style="margin-top:20px">Download Results</div>')
|
| 1394 |
+
download_out = gr.File(label="⬇ Download Full Results (ZIP)")
|
| 1395 |
+
|
| 1396 |
run_btn.click(
|
| 1397 |
+
fn=run_gwas_pipeline,
|
| 1398 |
+
inputs=[input_file, miss_rate_sample, miss_rate_marker, maf_thresh,
|
| 1399 |
+
use_mlm, use_lasso, use_enet, use_ridge, use_rf, use_gb],
|
| 1400 |
+
outputs=[summary_out, manhattan_out, qq_out, ld_out,
|
| 1401 |
+
circos_out, comp_out, download_out, pca_out]
|
| 1402 |
)
|
| 1403 |
|
| 1404 |
if __name__ == "__main__":
|