Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,10 +1,3 @@
|
|
| 1 |
-
# -*- coding: utf-8 -*-
|
| 2 |
-
"""
|
| 3 |
-
Created on Fri Mar 27 17:27:53 2026
|
| 4 |
-
|
| 5 |
-
@author: Ashmi
|
| 6 |
-
"""
|
| 7 |
-
|
| 8 |
# -*- coding: utf-8 -*-
|
| 9 |
"""
|
| 10 |
MTA Analysis Tool v7.0 - Enhanced Multi-Model GWAS Platform
|
|
@@ -85,18 +78,16 @@ def set_pastel_style():
|
|
| 85 |
})
|
| 86 |
|
| 87 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 88 |
-
#
|
| 89 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 90 |
|
| 91 |
def plot_manhattan_with_lod(marker_names, chromosomes, p_values, lod_scores,
|
| 92 |
sig_set, bonf_thresh, save_path):
|
| 93 |
-
"""Enhanced Manhattan plot with LOD scores overlay"""
|
| 94 |
set_pastel_style()
|
| 95 |
unique_chroms = sorted(set(chromosomes),
|
| 96 |
key=lambda x: (int(x) if str(x).isdigit() else 999, str(x)))
|
| 97 |
log_p = -np.log10(np.array(p_values) + 1e-300)
|
| 98 |
|
| 99 |
-
# Calculate positions
|
| 100 |
GAP = max(8, len(marker_names) // 150)
|
| 101 |
x_pos = np.zeros(len(marker_names))
|
| 102 |
chrom_centers, chrom_to_idx = {}, {}
|
|
@@ -112,12 +103,10 @@ def plot_manhattan_with_lod(marker_names, chromosomes, p_values, lod_scores,
|
|
| 112 |
chrom_centers[ch] = offset + (len(idxs) - 1) / 2
|
| 113 |
offset += len(idxs) + GAP
|
| 114 |
|
| 115 |
-
# Create figure with subplots
|
| 116 |
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(22, 10),
|
| 117 |
gridspec_kw={'height_ratios': [2, 1]},
|
| 118 |
facecolor=BG)
|
| 119 |
|
| 120 |
-
# Top plot: Manhattan with LOD overlay
|
| 121 |
for ci, ch in enumerate(unique_chroms):
|
| 122 |
idxs = chrom_to_idx.get(ch, [])
|
| 123 |
if not idxs: continue
|
|
@@ -132,7 +121,6 @@ def plot_manhattan_with_lod(marker_names, chromosomes, p_values, lod_scores,
|
|
| 132 |
col = CHROM_PALETTE[ci % len(CHROM_PALETTE)]
|
| 133 |
normal = [i for i in idxs if i not in sig_set]
|
| 134 |
sel = [i for i in idxs if i in sig_set]
|
| 135 |
-
|
| 136 |
if normal:
|
| 137 |
ax1.scatter(x_pos[normal], log_p[normal],
|
| 138 |
c=col, s=12, alpha=0.65, linewidths=0, zorder=2)
|
|
@@ -147,7 +135,6 @@ def plot_manhattan_with_lod(marker_names, chromosomes, p_values, lod_scores,
|
|
| 147 |
ax1.axhline(bonf_thresh, color=RED_C, ls='--', lw=1.8, alpha=0.85, zorder=5)
|
| 148 |
ax1.axhline(3, color=GOLD_C, ls=':', lw=1.5, alpha=0.8, label='LOD β₯ 3')
|
| 149 |
|
| 150 |
-
# Add LOD as secondary axis
|
| 151 |
ax1_twin = ax1.twinx()
|
| 152 |
lod_array = np.array(lod_scores)
|
| 153 |
ax1_twin.scatter(x_pos, lod_array, c=TEAL_C, s=8, alpha=0.4,
|
|
@@ -164,7 +151,6 @@ def plot_manhattan_with_lod(marker_names, chromosomes, p_values, lod_scores,
|
|
| 164 |
ax1.yaxis.grid(True, color=GRID_C, linewidth=0.8, alpha=1.0)
|
| 165 |
ax1.tick_params(axis='both', colors=TEXT_C, length=4)
|
| 166 |
|
| 167 |
-
# Bottom plot: LOD profile
|
| 168 |
for ci, ch in enumerate(unique_chroms):
|
| 169 |
idxs = chrom_to_idx.get(ch, [])
|
| 170 |
if not idxs: continue
|
|
@@ -189,14 +175,11 @@ def plot_manhattan_with_lod(marker_names, chromosomes, p_values, lod_scores,
|
|
| 189 |
|
| 190 |
|
| 191 |
def plot_enhanced_ld_decay(genotypes, chromosomes, positions, save_path, max_m=250):
|
| 192 |
-
"""Enhanced LD decay with multiple metrics and curve fitting"""
|
| 193 |
set_pastel_style()
|
| 194 |
unique_chroms = sorted(set(chromosomes),
|
| 195 |
key=lambda x: (int(x) if str(x).isdigit() else 999, str(x)))
|
| 196 |
|
| 197 |
-
all_distances = []
|
| 198 |
-
all_r2 = []
|
| 199 |
-
all_dprime = []
|
| 200 |
chrom_stats = {}
|
| 201 |
|
| 202 |
for ch in unique_chroms:
|
|
@@ -208,23 +191,18 @@ def plot_enhanced_ld_decay(genotypes, chromosomes, positions, save_path, max_m=2
|
|
| 208 |
G = genotypes[:, idxs].copy()
|
| 209 |
positions_ch = [positions[i] for i in idxs] if positions is not None else list(range(len(idxs)))
|
| 210 |
|
| 211 |
-
# Calculate distances
|
| 212 |
for i in range(len(idxs)):
|
| 213 |
for j in range(i+1, min(i+60, len(idxs))):
|
| 214 |
dist = abs(positions_ch[j] - positions_ch[i]) if positions is not None else (j - i)
|
| 215 |
-
|
| 216 |
-
# Calculate rΒ²
|
| 217 |
r = np.corrcoef(G[:, i], G[:, j])[0, 1]
|
| 218 |
r2 = r**2 if not np.isnan(r) else 0
|
| 219 |
|
| 220 |
-
# Calculate D' (simplified)
|
| 221 |
col1, col2 = G[:, i], G[:, j]
|
| 222 |
freq1 = np.mean(col1) / 2
|
| 223 |
freq2 = np.mean(col2) / 2
|
| 224 |
-
|
| 225 |
p11 = np.mean((col1 == 2) & (col2 == 2)) / 2
|
| 226 |
D = p11 - freq1 * freq2
|
| 227 |
-
Dmax = min(freq1
|
| 228 |
Dprime = abs(D / Dmax) if Dmax > 0 else 0
|
| 229 |
|
| 230 |
all_distances.append(dist)
|
|
@@ -237,21 +215,18 @@ def plot_enhanced_ld_decay(genotypes, chromosomes, positions, save_path, max_m=2
|
|
| 237 |
'mean_dprime': np.mean(all_dprime[-len(all_distances)//10:] if len(all_distances) > 10 else all_dprime)
|
| 238 |
}
|
| 239 |
|
| 240 |
-
# Create figure with subplots
|
| 241 |
fig, axes = plt.subplots(1, 3, figsize=(18, 5), facecolor=BG)
|
| 242 |
|
| 243 |
-
# Plot 1: rΒ² decay
|
| 244 |
ax = axes[0]
|
| 245 |
ax.set_facecolor(PANEL)
|
|
|
|
|
|
|
|
|
|
| 246 |
if all_distances:
|
| 247 |
distances = np.array(all_distances)
|
| 248 |
r2_values = np.array(all_r2)
|
| 249 |
-
|
| 250 |
max_dist = min(50, int(np.percentile(distances, 95)) if len(distances) > 0 else 50)
|
| 251 |
bins = np.arange(0, max_dist + 2, 2)
|
| 252 |
-
bin_means = []
|
| 253 |
-
bin_stds = []
|
| 254 |
-
bin_centers = []
|
| 255 |
|
| 256 |
for i in range(len(bins)-1):
|
| 257 |
mask = (distances >= bins[i]) & (distances < bins[i+1])
|
|
@@ -261,20 +236,17 @@ def plot_enhanced_ld_decay(genotypes, chromosomes, positions, save_path, max_m=2
|
|
| 261 |
bin_centers.append((bins[i] + bins[i+1]) / 2)
|
| 262 |
|
| 263 |
bin_centers = np.array(bin_centers)
|
| 264 |
-
bin_means
|
| 265 |
-
bin_stds
|
| 266 |
|
| 267 |
from scipy.optimize import curve_fit
|
| 268 |
-
|
| 269 |
def decay_model(x, a, b):
|
| 270 |
return a * np.exp(-b * x)
|
| 271 |
-
|
| 272 |
try:
|
| 273 |
params, _ = curve_fit(decay_model, bin_centers[bin_means > 0],
|
| 274 |
bin_means[bin_means > 0], maxfev=5000)
|
| 275 |
x_fit = np.linspace(0, max_dist, 100)
|
| 276 |
-
|
| 277 |
-
ax.plot(x_fit, y_fit, '--', color=RED_C, linewidth=2,
|
| 278 |
label=f'Decay: {params[1]:.3f}')
|
| 279 |
except:
|
| 280 |
pass
|
|
@@ -286,63 +258,52 @@ def plot_enhanced_ld_decay(genotypes, chromosomes, positions, save_path, max_m=2
|
|
| 286 |
|
| 287 |
half_decay_idx = np.where(bin_means <= bin_means[0]/2)[0]
|
| 288 |
if len(half_decay_idx) > 0:
|
| 289 |
-
ax.axvline(bin_centers[half_decay_idx[0]], color=GOLD_C,
|
| 290 |
-
|
| 291 |
-
label=f'LD half-decay: {bin_centers[half_decay_idx[0]]:.1f}')
|
| 292 |
|
| 293 |
ax.set_xlabel('Distance (kb)', fontsize=12, color=TEXT_C, fontweight='bold')
|
| 294 |
ax.set_ylabel('Mean rΒ²', fontsize=12, color=TEXT_C, fontweight='bold')
|
| 295 |
-
ax.set_title('
|
| 296 |
ax.set_ylim(0, 1)
|
| 297 |
ax.legend(fontsize=9, facecolor=BG, edgecolor=GRID_C)
|
| 298 |
ax.grid(True, color=GRID_C, lw=0.8)
|
| 299 |
|
| 300 |
-
# Plot 2: D' decay
|
| 301 |
ax = axes[1]
|
| 302 |
ax.set_facecolor(PANEL)
|
| 303 |
-
if all_dprime:
|
| 304 |
dprime_values = np.array(all_dprime)
|
| 305 |
-
|
| 306 |
-
bin_stds_dprime = []
|
| 307 |
-
|
| 308 |
for i in range(len(bins)-1):
|
| 309 |
mask = (distances >= bins[i]) & (distances < bins[i+1])
|
| 310 |
if mask.sum() > 0:
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
ax.axhline(0.5, color=RED_C, ls='--', lw=1.3, alpha=0.8, label="D'=0.5")
|
| 318 |
|
| 319 |
ax.set_xlabel('Distance (kb)', fontsize=12, color=TEXT_C, fontweight='bold')
|
| 320 |
ax.set_ylabel("Mean D'", fontsize=12, color=TEXT_C, fontweight='bold')
|
| 321 |
-
ax.set_title("
|
| 322 |
ax.set_ylim(0, 1)
|
| 323 |
ax.legend(fontsize=9, facecolor=BG, edgecolor=GRID_C)
|
| 324 |
ax.grid(True, color=GRID_C, lw=0.8)
|
| 325 |
|
| 326 |
-
# Plot 3: Chromosome-specific LD
|
| 327 |
ax = axes[2]
|
| 328 |
ax.set_facecolor(PANEL)
|
| 329 |
if chrom_stats:
|
| 330 |
chromosomes_list = sorted(chrom_stats.keys(),
|
| 331 |
key=lambda x: (int(x) if str(x).isdigit() else 999, str(x)))
|
| 332 |
-
r2_means
|
| 333 |
dprime_means = [chrom_stats[ch]['mean_dprime'] for ch in chromosomes_list]
|
| 334 |
-
|
| 335 |
-
x = np.arange(len(chromosomes_list))
|
| 336 |
width = 0.35
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
color=ACCENT, alpha=0.8, edgecolor='white')
|
| 340 |
-
bars2 = ax.bar(x + width/2, dprime_means, width, label="D'",
|
| 341 |
-
color=TEAL_C, alpha=0.8, edgecolor='white')
|
| 342 |
-
|
| 343 |
ax.set_xticks(x)
|
| 344 |
-
ax.set_xticklabels([f'Chr {c}' for c in chromosomes_list],
|
| 345 |
-
rotation=45, ha='right', fontsize=8)
|
| 346 |
ax.set_xlabel('Chromosome', fontsize=12, color=TEXT_C, fontweight='bold')
|
| 347 |
ax.set_ylabel('Mean LD Value', fontsize=12, color=TEXT_C, fontweight='bold')
|
| 348 |
ax.set_title('Per-Chromosome LD Summary', fontsize=14, color=TEXT_C, fontweight='bold')
|
|
@@ -352,285 +313,222 @@ def plot_enhanced_ld_decay(genotypes, chromosomes, positions, save_path, max_m=2
|
|
| 352 |
plt.tight_layout(pad=2)
|
| 353 |
plt.savefig(save_path, dpi=200, bbox_inches='tight', facecolor=BG)
|
| 354 |
plt.close(fig)
|
| 355 |
-
|
| 356 |
return chrom_stats
|
| 357 |
|
| 358 |
|
| 359 |
def plot_model_comparison(results_df, save_path):
|
| 360 |
-
"""Compare different GWAS models"""
|
| 361 |
set_pastel_style()
|
| 362 |
-
|
| 363 |
fig, axes = plt.subplots(2, 2, figsize=(14, 10), facecolor=BG)
|
| 364 |
|
| 365 |
-
|
| 366 |
-
ax = axes[0, 0]
|
| 367 |
-
ax.set_facecolor(PANEL)
|
| 368 |
-
|
| 369 |
-
models = ['LR_P', 'MLM_P', 'EN_P', 'RF_P', 'GB_P']
|
| 370 |
model_names = ['Linear', 'Mixed', 'ElasticNet', 'RandomForest', 'GradientBoost']
|
| 371 |
|
|
|
|
|
|
|
|
|
|
| 372 |
corr_matrix = np.zeros((len(models), len(models)))
|
| 373 |
for i, m1 in enumerate(models):
|
| 374 |
for j, m2 in enumerate(models):
|
| 375 |
if m1 in results_df.columns and m2 in results_df.columns:
|
| 376 |
corr_matrix[i, j] = results_df[m1].corr(results_df[m2])
|
| 377 |
-
|
| 378 |
im = ax.imshow(corr_matrix, cmap='RdBu_r', vmin=-1, vmax=1, aspect='auto')
|
| 379 |
ax.set_xticks(range(len(models)))
|
| 380 |
ax.set_yticks(range(len(models)))
|
| 381 |
ax.set_xticklabels(model_names, rotation=45, ha='right', fontsize=9)
|
| 382 |
ax.set_yticklabels(model_names, fontsize=9)
|
| 383 |
-
|
| 384 |
for i in range(len(models)):
|
| 385 |
for j in range(len(models)):
|
| 386 |
-
ax.text(j, i, f'{corr_matrix[i, j]:.2f}',
|
| 387 |
-
|
| 388 |
-
|
| 389 |
plt.colorbar(im, ax=ax, shrink=0.8)
|
| 390 |
ax.set_title('P-value Correlations Between Models', fontsize=12, fontweight='bold')
|
| 391 |
|
| 392 |
# 2. Effect size distribution
|
| 393 |
ax = axes[0, 1]
|
| 394 |
ax.set_facecolor(PANEL)
|
| 395 |
-
|
| 396 |
for i, model in enumerate(models):
|
| 397 |
if model in results_df.columns:
|
| 398 |
-
col = ACCENT if i == 0 else [RED_C, GREEN_C, ORANGE_C, PURPLE_C][i-1]
|
| 399 |
beta_col = model.replace('_P', '_Beta')
|
| 400 |
-
data = results_df[beta_col] if beta_col in results_df.columns else np.random.randn(100)
|
| 401 |
-
ax.hist(data, bins=30, alpha=0.5,
|
| 402 |
-
label=model_names[i], color=col)
|
| 403 |
-
|
| 404 |
ax.set_xlabel('Effect Size', fontsize=11)
|
| 405 |
ax.set_ylabel('Frequency', fontsize=11)
|
| 406 |
ax.set_title('Effect Size Distribution by Model', fontsize=12, fontweight='bold')
|
| 407 |
ax.legend(fontsize=8)
|
| 408 |
ax.grid(True, color=GRID_C, lw=0.8)
|
| 409 |
|
| 410 |
-
# 3.
|
| 411 |
ax = axes[1, 0]
|
| 412 |
ax.set_facecolor(PANEL)
|
| 413 |
-
|
| 414 |
-
cv_cols = ['CV_LR', 'CV_EN', 'CV_RF', 'CV_GB']
|
| 415 |
-
if all(x in results_df.columns for x in cv_cols):
|
| 416 |
-
cv_scores = results_df[cv_cols].mean()
|
| 417 |
-
else:
|
| 418 |
-
cv_scores = pd.Series([0.7, 0.75, 0.8, 0.78], index=cv_cols)
|
| 419 |
-
|
| 420 |
bars = ax.bar(range(len(cv_scores)), cv_scores.values,
|
| 421 |
color=[ACCENT, RED_C, GREEN_C, ORANGE_C], alpha=0.7)
|
| 422 |
ax.set_xticks(range(len(cv_scores)))
|
| 423 |
-
ax.set_xticklabels(
|
| 424 |
-
rotation=45, ha='right')
|
| 425 |
ax.set_ylabel('CV Score (RΒ²)', fontsize=11)
|
| 426 |
ax.set_title('Model Stability (5-fold CV)', fontsize=12, fontweight='bold')
|
| 427 |
ax.set_ylim(0, 1)
|
| 428 |
-
|
| 429 |
for bar, val in zip(bars, cv_scores.values):
|
| 430 |
ax.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 0.02,
|
| 431 |
f'{val:.3f}', ha='center', va='bottom', fontsize=9)
|
| 432 |
|
| 433 |
-
# 4.
|
| 434 |
ax = axes[1, 1]
|
| 435 |
ax.set_facecolor(PANEL)
|
| 436 |
-
|
| 437 |
-
|
| 438 |
-
|
| 439 |
-
|
| 440 |
-
|
| 441 |
-
|
| 442 |
-
|
| 443 |
-
|
| 444 |
-
|
| 445 |
-
|
| 446 |
-
ax.set_yticklabels(['Linear', 'ElasticNet', 'RandomForest', 'GradientBoost'])
|
| 447 |
-
ax.set_xlabel('Runtime (seconds)', fontsize=11)
|
| 448 |
-
ax.set_title('Model Runtime Comparison', fontsize=12, fontweight='bold')
|
| 449 |
-
ax.grid(True, color=GRID_C, lw=0.8, axis='x')
|
| 450 |
|
| 451 |
plt.tight_layout(pad=1.5)
|
| 452 |
plt.savefig(save_path, dpi=200, bbox_inches='tight', facecolor=BG)
|
| 453 |
plt.close(fig)
|
| 454 |
|
| 455 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 456 |
-
#
|
| 457 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 458 |
|
| 459 |
def linear_regression_gwas(genotypes, phenotypes):
|
| 460 |
-
"""Standard linear regression GWAS"""
|
| 461 |
n_markers = genotypes.shape[1]
|
| 462 |
pvals = np.ones(n_markers)
|
| 463 |
effects = np.zeros(n_markers)
|
| 464 |
se = np.zeros(n_markers)
|
| 465 |
r2 = np.zeros(n_markers)
|
| 466 |
-
|
| 467 |
for i in range(n_markers):
|
| 468 |
X = genotypes[:, i]
|
| 469 |
if np.std(X) > 0:
|
| 470 |
try:
|
| 471 |
-
|
| 472 |
-
model = sm.OLS(phenotypes,
|
| 473 |
-
pvals[i]
|
| 474 |
effects[i] = model.params[1]
|
| 475 |
-
se[i]
|
| 476 |
-
r2[i]
|
| 477 |
except:
|
| 478 |
pass
|
| 479 |
-
|
| 480 |
return pvals, effects, se, r2
|
| 481 |
|
| 482 |
|
| 483 |
def mixed_model_gwas(genotypes, phenotypes, kinship=None):
|
| 484 |
-
"""Mixed linear model GWAS with optional kinship matrix"""
|
| 485 |
n_markers = genotypes.shape[1]
|
| 486 |
-
pvals
|
| 487 |
effects = np.zeros(n_markers)
|
| 488 |
-
lod
|
| 489 |
-
|
| 490 |
for i in range(n_markers):
|
| 491 |
X = genotypes[:, i]
|
| 492 |
if np.std(X) > 0:
|
| 493 |
try:
|
| 494 |
-
data
|
| 495 |
model = mixedlm("pheno ~ marker", data, groups=data.index).fit()
|
| 496 |
-
pvals[i]
|
| 497 |
effects[i] = model.params[1]
|
| 498 |
-
lod[i]
|
| 499 |
except:
|
| 500 |
pass
|
| 501 |
-
|
| 502 |
return pvals, effects, lod
|
| 503 |
|
| 504 |
|
| 505 |
-
def elasticnet_gwas(genotypes, phenotypes
|
| 506 |
-
|
| 507 |
-
scaler = StandardScaler()
|
| 508 |
X_scaled = scaler.fit_transform(genotypes)
|
| 509 |
-
|
| 510 |
-
enet = ElasticNetCV(cv=5, random_state=42, max_iter=5000)
|
| 511 |
enet.fit(X_scaled, phenotypes)
|
| 512 |
-
|
| 513 |
coefficients = enet.coef_
|
| 514 |
-
pvals
|
| 515 |
-
|
| 516 |
-
n_bootstrap = 100
|
| 517 |
bootstrap_coefs = []
|
| 518 |
for _ in range(min(n_bootstrap, len(phenotypes))):
|
| 519 |
idx = np.random.choice(len(phenotypes), len(phenotypes), replace=True)
|
| 520 |
-
|
| 521 |
-
|
| 522 |
-
bootstrap_coefs.append(
|
| 523 |
-
|
| 524 |
bootstrap_coefs = np.array(bootstrap_coefs)
|
| 525 |
for i in range(len(coefficients)):
|
| 526 |
if np.std(bootstrap_coefs[:, i]) > 0:
|
| 527 |
-
|
| 528 |
-
pvals[i] = 2 * (1 - stats.norm.cdf(
|
| 529 |
-
|
| 530 |
return pvals, coefficients
|
| 531 |
|
| 532 |
|
| 533 |
def machine_learning_gwas(genotypes, phenotypes, model_type='rf'):
|
| 534 |
-
|
| 535 |
-
scaler = StandardScaler()
|
| 536 |
X_scaled = scaler.fit_transform(genotypes)
|
| 537 |
-
|
| 538 |
if model_type == 'rf':
|
| 539 |
model = RandomForestRegressor(n_estimators=100, random_state=42, n_jobs=-1)
|
| 540 |
-
elif model_type == 'gb':
|
| 541 |
-
model = GradientBoostingRegressor(n_estimators=100, random_state=42)
|
| 542 |
else:
|
| 543 |
-
|
| 544 |
|
| 545 |
kf = KFold(n_splits=5, shuffle=True, random_state=42)
|
| 546 |
-
cv_scores = []
|
| 547 |
-
importance_scores = []
|
| 548 |
-
|
| 549 |
for train_idx, val_idx in kf.split(X_scaled):
|
| 550 |
-
|
| 551 |
-
|
| 552 |
-
|
| 553 |
-
model.fit(X_train, y_train)
|
| 554 |
-
y_pred = model.predict(X_val)
|
| 555 |
-
cv_scores.append(r2_score(y_val, y_pred))
|
| 556 |
importance_scores.append(model.feature_importances_)
|
| 557 |
|
| 558 |
avg_importance = np.mean(importance_scores, axis=0)
|
| 559 |
-
|
| 560 |
-
n_perm = 50
|
| 561 |
null_importance = []
|
| 562 |
for _ in range(min(n_perm, len(phenotypes))):
|
| 563 |
-
|
| 564 |
-
model.fit(X_scaled, y_perm)
|
| 565 |
null_importance.append(model.feature_importances_)
|
| 566 |
-
|
| 567 |
null_importance = np.array(null_importance)
|
| 568 |
-
pvals = np.
|
| 569 |
-
|
| 570 |
-
pvals[i] = np.mean(null_importance[:, i] >= avg_importance[i])
|
| 571 |
-
|
| 572 |
return pvals, avg_importance, np.mean(cv_scores)
|
| 573 |
|
| 574 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 575 |
-
#
|
| 576 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 577 |
|
| 578 |
def parse_input_csv_enhanced(filepath):
|
| 579 |
-
|
| 580 |
-
df = pd.read_csv(filepath, header=0, dtype=str)
|
| 581 |
-
|
| 582 |
marker_cols = df.columns[2:].tolist()
|
| 583 |
-
|
| 584 |
-
|
| 585 |
-
chromosome_dict = {}
|
| 586 |
-
position_dict = {}
|
| 587 |
|
| 588 |
for m in marker_cols:
|
| 589 |
val = str(chr_row[m]).strip()
|
| 590 |
if ':' in val:
|
| 591 |
parts = val.split(':')
|
| 592 |
chromosome_dict[m] = parts[0]
|
| 593 |
-
if len(parts) > 1
|
| 594 |
-
|
| 595 |
-
|
| 596 |
-
except:
|
| 597 |
-
position_dict[m] = 0
|
| 598 |
-
elif '_' in val and len(val.split('_')) > 1:
|
| 599 |
parts = val.split('_')
|
| 600 |
chromosome_dict[m] = parts[0]
|
| 601 |
-
if len(parts) > 1
|
| 602 |
-
|
| 603 |
-
position_dict[m] = float(parts[1])
|
| 604 |
-
except:
|
| 605 |
-
position_dict[m] = 0
|
| 606 |
else:
|
| 607 |
-
if val.endswith('.0')
|
| 608 |
-
val = val[:-2]
|
| 609 |
chromosome_dict[m] = val
|
| 610 |
-
position_dict[m]
|
| 611 |
-
|
| 612 |
-
df_samples
|
| 613 |
-
|
| 614 |
-
|
| 615 |
-
|
| 616 |
-
|
| 617 |
-
|
| 618 |
-
|
| 619 |
-
genotypes = geno_raw.values
|
| 620 |
-
|
| 621 |
-
positions = [position_dict.get(m, 0) for m in marker_cols]
|
| 622 |
-
|
| 623 |
return sample_ids, phenotypes, genotypes, marker_cols, chromosome_dict, positions
|
| 624 |
|
| 625 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 626 |
-
# MAIN ANALYSIS
|
| 627 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 628 |
|
| 629 |
-
def
|
| 630 |
-
|
| 631 |
-
|
| 632 |
-
"""
|
| 633 |
-
|
|
|
|
| 634 |
mlm_pvals = mlm_effects = mlm_lod = None
|
| 635 |
enet_pvals = enet_coef = None
|
| 636 |
rf_pvals = rf_imp = rf_cv = None
|
|
@@ -640,9 +538,9 @@ def run_enhanced_mta_analysis(input_file, target_markers, miss_rate_sample,
|
|
| 640 |
if input_file is None:
|
| 641 |
return ("β οΈ Please upload a CSV file.", None, None, None, None)
|
| 642 |
|
| 643 |
-
temp_dir
|
| 644 |
results_dir = os.path.join(temp_dir, 'results')
|
| 645 |
-
plots_dir
|
| 646 |
for d in [results_dir, plots_dir]:
|
| 647 |
os.makedirs(d, exist_ok=True)
|
| 648 |
|
|
@@ -650,21 +548,18 @@ def run_enhanced_mta_analysis(input_file, target_markers, miss_rate_sample,
|
|
| 650 |
miss_m_thresh = miss_rate_marker / 100.0
|
| 651 |
maf_thresh_f = maf_thresh / 100.0
|
| 652 |
|
| 653 |
-
# Load and parse data
|
| 654 |
sample_ids, phenotypes, genotypes, marker_names, chromosome_dict, positions = \
|
| 655 |
parse_input_csv_enhanced(input_file)
|
| 656 |
|
| 657 |
n_samples = len(sample_ids)
|
| 658 |
-
n_markers
|
| 659 |
|
| 660 |
-
# Quality control
|
| 661 |
miss_m = np.isnan(genotypes).sum(axis=0) / max(n_samples, 1)
|
| 662 |
miss_s = np.isnan(genotypes).sum(axis=1) / max(n_markers, 1)
|
| 663 |
|
| 664 |
maf = np.zeros(n_markers)
|
| 665 |
for i in range(n_markers):
|
| 666 |
-
|
| 667 |
-
valid = col[~np.isnan(col)]
|
| 668 |
if len(valid) > 0:
|
| 669 |
freq = np.mean(valid) / 2.0
|
| 670 |
maf[i] = min(freq, 1.0 - freq)
|
|
@@ -672,20 +567,16 @@ def run_enhanced_mta_analysis(input_file, target_markers, miss_rate_sample,
|
|
| 672 |
qc_m = (miss_m < miss_m_thresh) & (maf >= maf_thresh_f)
|
| 673 |
qc_s = miss_s < miss_s_thresh
|
| 674 |
|
| 675 |
-
|
| 676 |
-
fallback_applied = False
|
| 677 |
-
fallback_msg = ""
|
| 678 |
for relaxed_s, relaxed_m in [(miss_s_thresh, miss_m_thresh),
|
| 679 |
-
(0.60,
|
| 680 |
-
(0.80, 0.80), (0.90, 0.90), (1.00, 1.00)]:
|
| 681 |
qc_m_try = (miss_m < relaxed_m) & (maf >= maf_thresh_f)
|
| 682 |
qc_s_try = miss_s < relaxed_s
|
| 683 |
if int(qc_s_try.sum()) >= 10:
|
| 684 |
qc_m = qc_m_try
|
| 685 |
qc_s = qc_s_try
|
| 686 |
if relaxed_s > miss_s_thresh or relaxed_m > miss_m_thresh:
|
| 687 |
-
|
| 688 |
-
fallback_msg = (f"\n> β οΈ **QC thresholds auto-relaxed** to sample missing "
|
| 689 |
f"< {relaxed_s*100:.0f}% / marker missing "
|
| 690 |
f"< {relaxed_m*100:.0f}% to retain β₯10 samples.\n")
|
| 691 |
break
|
|
@@ -697,39 +588,29 @@ def run_enhanced_mta_analysis(input_file, target_markers, miss_rate_sample,
|
|
| 697 |
chrom_qc = [chromosome_dict[m] for m in mnames_qc]
|
| 698 |
pos_qc = [positions[i] for i in range(n_markers) if qc_m[i]]
|
| 699 |
|
| 700 |
-
# Impute
|
| 701 |
for i in range(geno_qc.shape[1]):
|
| 702 |
col = geno_qc[:, i]
|
| 703 |
mask = np.isnan(col)
|
| 704 |
if mask.any():
|
| 705 |
-
|
| 706 |
-
geno_qc[mask, i] = fill
|
| 707 |
|
| 708 |
-
# Remove samples with NaN phenotype
|
| 709 |
valid_pheno = ~np.isnan(pheno_qc)
|
| 710 |
-
geno_qc
|
| 711 |
-
pheno_qc
|
| 712 |
-
ids_qc
|
| 713 |
|
| 714 |
if len(ids_qc) < 10:
|
| 715 |
-
|
| 716 |
-
worst5 = np.sort(sample_miss_pct)[::-1][:5]
|
| 717 |
-
worst5_str = ", ".join(f"{v:.0f}%" for v in worst5)
|
| 718 |
return (
|
| 719 |
f"## β οΈ Insufficient Samples After QC\n\n"
|
| 720 |
-
f"Only **{len(ids_qc)}** sample(s) passed
|
| 721 |
-
f"
|
| 722 |
-
f"**
|
| 723 |
-
f"- Sample missing rate filter used: **< {miss_s_thresh*100:.0f}%**\n"
|
| 724 |
-
f"- Samples with most missing data: `{worst5_str}`\n"
|
| 725 |
-
f"- Try increasing the **Sample Missing Rate** slider to 50β80%\n\n"
|
| 726 |
-
f"**Your data appears to have high missing rates per sample** "
|
| 727 |
-
f"(common in large rice/plant GWAS panels). "
|
| 728 |
-
f"Raising the missing rate threshold to 50% or higher is standard practice.",
|
| 729 |
None, None, None, None
|
| 730 |
)
|
| 731 |
|
| 732 |
-
# ββ
|
| 733 |
print("Running Linear Regression GWAS...")
|
| 734 |
lr_pvals, lr_effects, lr_se, lr_r2 = linear_regression_gwas(geno_qc, pheno_qc)
|
| 735 |
|
|
@@ -749,7 +630,10 @@ def run_enhanced_mta_analysis(input_file, target_markers, miss_rate_sample,
|
|
| 749 |
print("Running Gradient Boosting GWAS...")
|
| 750 |
gb_pvals, gb_imp, gb_cv = machine_learning_gwas(geno_qc, pheno_qc, 'gb')
|
| 751 |
|
| 752 |
-
# ββ
|
|
|
|
|
|
|
|
|
|
| 753 |
gwas_df = pd.DataFrame({
|
| 754 |
'Rank': 0,
|
| 755 |
'Marker': mnames_qc,
|
|
@@ -758,31 +642,30 @@ def run_enhanced_mta_analysis(input_file, target_markers, miss_rate_sample,
|
|
| 758 |
'LR_P': lr_pvals,
|
| 759 |
'LR_Beta': lr_effects,
|
| 760 |
'LR_LOD': -np.log10(lr_pvals + 1e-300),
|
| 761 |
-
'Significant_LR': (lr_pvals <
|
| 762 |
})
|
| 763 |
|
| 764 |
if include_mlm and mlm_pvals is not None:
|
| 765 |
gwas_df['MLM_P'] = mlm_pvals
|
| 766 |
gwas_df['MLM_Beta'] = mlm_effects
|
| 767 |
gwas_df['MLM_LOD'] = mlm_lod
|
| 768 |
-
gwas_df['Significant_MLM'] = (mlm_pvals <
|
| 769 |
|
| 770 |
if include_enet and enet_pvals is not None:
|
| 771 |
gwas_df['EN_P'] = enet_pvals
|
| 772 |
gwas_df['EN_Beta'] = enet_coef
|
| 773 |
-
gwas_df['Significant_EN'] = (enet_pvals <
|
| 774 |
|
| 775 |
if include_rf and rf_pvals is not None:
|
| 776 |
gwas_df['RF_P'] = rf_pvals
|
| 777 |
gwas_df['RF_Imp'] = rf_imp
|
| 778 |
-
gwas_df['Significant_RF'] = (rf_pvals <
|
| 779 |
|
| 780 |
if include_gb and gb_pvals is not None:
|
| 781 |
gwas_df['GB_P'] = gb_pvals
|
| 782 |
gwas_df['GB_Imp'] = gb_imp
|
| 783 |
-
gwas_df['Significant_GB'] = (gb_pvals <
|
| 784 |
|
| 785 |
-
# Consensus significance (β₯2 models agree)
|
| 786 |
sig_cols = [c for c in gwas_df.columns if c.startswith('Significant_')]
|
| 787 |
if len(sig_cols) > 1:
|
| 788 |
gwas_df['Consensus_Sig'] = (gwas_df[sig_cols].sum(axis=1) >= 2).astype(int)
|
|
@@ -793,17 +676,16 @@ def run_enhanced_mta_analysis(input_file, target_markers, miss_rate_sample,
|
|
| 793 |
|
| 794 |
gwas_df = gwas_df.sort_values('LR_P')
|
| 795 |
gwas_df['Rank'] = range(1, len(gwas_df) + 1)
|
| 796 |
-
|
| 797 |
gwas_df.to_csv(os.path.join(results_dir, 'enhanced_gwas_results.csv'), index=False)
|
| 798 |
|
| 799 |
-
# ββ
|
| 800 |
-
|
| 801 |
-
sig_set
|
| 802 |
|
| 803 |
man_path = os.path.join(plots_dir, 'manhattan_lod.png')
|
| 804 |
plot_manhattan_with_lod(mnames_qc, chrom_qc, lr_pvals,
|
| 805 |
-np.log10(lr_pvals + 1e-300),
|
| 806 |
-
sig_set,
|
| 807 |
|
| 808 |
ld_path = os.path.join(plots_dir, 'enhanced_ld_decay.png')
|
| 809 |
ld_stats = plot_enhanced_ld_decay(geno_qc, chrom_qc, pos_qc, ld_path)
|
|
@@ -811,7 +693,7 @@ def run_enhanced_mta_analysis(input_file, target_markers, miss_rate_sample,
|
|
| 811 |
comp_path = os.path.join(plots_dir, 'model_comparison.png')
|
| 812 |
plot_model_comparison(gwas_df, comp_path)
|
| 813 |
|
| 814 |
-
# ββ ZIP ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 815 |
zip_path = os.path.join(temp_dir, 'Enhanced_GWAS_Results.zip')
|
| 816 |
with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf:
|
| 817 |
for root, _, files in os.walk(results_dir):
|
|
@@ -820,15 +702,11 @@ def run_enhanced_mta_analysis(input_file, target_markers, miss_rate_sample,
|
|
| 820 |
arc = os.path.relpath(fp, temp_dir)
|
| 821 |
zf.write(fp, arc)
|
| 822 |
|
| 823 |
-
# ββ
|
| 824 |
-
|
| 825 |
-
|
| 826 |
-
|
| 827 |
-
|
| 828 |
-
rf_sig_str = (f"{int((rf_pvals < 0.05/len(mnames_qc)).sum())}"
|
| 829 |
-
if include_rf and rf_pvals is not None else "β")
|
| 830 |
-
gb_sig_str = (f"{int((gb_pvals < 0.05/len(mnames_qc)).sum())}"
|
| 831 |
-
if include_gb and gb_pvals is not None else "β")
|
| 832 |
|
| 833 |
summary = f"""
|
| 834 |
## π Enhanced GWAS Analysis Results
|
|
@@ -837,7 +715,7 @@ def run_enhanced_mta_analysis(input_file, target_markers, miss_rate_sample,
|
|
| 837 |
| Metric | Value |
|
| 838 |
|--------|-------|
|
| 839 |
| Samples (raw β QC) | {n_samples} β **{len(ids_qc)}** |
|
| 840 |
-
| Markers (raw β QC) | {n_markers} β **{
|
| 841 |
| Chromosomes | **{len(set(chrom_qc))}** |
|
| 842 |
| MAF filter | β₯ {maf_thresh:.1f}% |
|
| 843 |
| Sample missing filter | < {miss_rate_sample:.0f}% |
|
|
@@ -846,30 +724,28 @@ def run_enhanced_mta_analysis(input_file, target_markers, miss_rate_sample,
|
|
| 846 |
### GWAS Models
|
| 847 |
| Model | Status | Significant Markers |
|
| 848 |
|-------|--------|---------------------|
|
| 849 |
-
| Linear Regression | β
Completed | {
|
| 850 |
-
| Mixed Linear Model | {'β
Completed' if include_mlm else 'β Skipped'} | {
|
| 851 |
-
| ElasticNet | {'β
Completed' if include_enet else 'β Skipped'} | {
|
| 852 |
-
| Random Forest | {'β
Completed' if include_rf else 'β Skipped'} | {
|
| 853 |
-
| Gradient Boosting | {'β
Completed' if include_gb else 'β Skipped'} | {
|
| 854 |
|
| 855 |
### Consensus Results
|
| 856 |
-
**Markers significant in
|
| 857 |
|
| 858 |
### LD Statistics
|
| 859 |
-
Mean rΒ²: **{np.mean([v['mean_r2'] for v in ld_stats.values()]) if ld_stats else 0:.3f}**
|
| 860 |
Mean D': **{np.mean([v['mean_dprime'] for v in ld_stats.values()]) if ld_stats else 0:.3f}**
|
| 861 |
|
| 862 |
### Top 10 Markers (by LR P-value)
|
| 863 |
-
{gwas_df.head(10)[['Marker',
|
| 864 |
|
| 865 |
### π ZIP Contents
|
| 866 |
-
- `enhanced_gwas_results.csv` β
|
| 867 |
-
- `plots/manhattan_lod.png` β Manhattan
|
| 868 |
-
- `plots/enhanced_ld_decay.png` β
|
| 869 |
-
- `plots/model_comparison.png` β Model performance
|
| 870 |
"""
|
| 871 |
-
|
| 872 |
-
# Return 5 values matching the 5 Gradio outputs
|
| 873 |
return (summary, man_path, ld_path, comp_path, zip_path)
|
| 874 |
|
| 875 |
except Exception as e:
|
|
@@ -879,135 +755,103 @@ Mean D': **{np.mean([v['mean_dprime'] for v in ld_stats.values()]) if ld_stats e
|
|
| 879 |
None, None, None, None
|
| 880 |
)
|
| 881 |
|
| 882 |
-
#
|
|
|
|
|
|
|
| 883 |
|
| 884 |
-
# Custom CSS for styling
|
| 885 |
custom_css = """
|
| 886 |
-
.gradio-container {
|
| 887 |
-
|
| 888 |
-
}
|
| 889 |
-
h1 {
|
| 890 |
-
color: #2c3e50;
|
| 891 |
-
border-bottom: 3px solid #3498db;
|
| 892 |
-
padding-bottom: 10px;
|
| 893 |
-
}
|
| 894 |
-
h2 {
|
| 895 |
-
color: #34495e;
|
| 896 |
-
margin-top: 20px;
|
| 897 |
-
}
|
| 898 |
"""
|
| 899 |
|
| 900 |
-
with gr.Blocks(css=custom_css, title="MTA Analysis Tool") as app:
|
| 901 |
-
|
| 902 |
gr.Markdown("""
|
| 903 |
-
# 𧬠Enhanced Multi-Trait Association (MTA) Analysis
|
| 904 |
-
|
| 905 |
### Comprehensive Genomic Prediction & Marker Discovery Platform
|
| 906 |
-
|
| 907 |
-
This tool performs advanced MTA analysis combining GWAS with machine learning for genomic prediction.
|
| 908 |
-
Upload your CSV file to get started!
|
| 909 |
-
|
| 910 |
---
|
| 911 |
""")
|
| 912 |
-
|
| 913 |
with gr.Row():
|
| 914 |
with gr.Column(scale=1):
|
| 915 |
gr.Markdown("""
|
| 916 |
-
### π Input
|
| 917 |
-
|
| 918 |
-
|
| 919 |
-
- **Row
|
| 920 |
-
- **Row 2**: Chromosome info for each marker
|
| 921 |
-
- **Row 3+**: Sample data (ID, phenotype value, genotype scores)
|
| 922 |
-
|
| 923 |
-
**Example format:**
|
| 924 |
-
```
|
| 925 |
-
ID,Phenotype,M1,M2,M3,...
|
| 926 |
-
-,Chr,1,1,2,...
|
| 927 |
-
Sample1,45.2,0,1,2,...
|
| 928 |
-
Sample2,38.7,1,0,1,...
|
| 929 |
-
```
|
| 930 |
""")
|
| 931 |
-
|
| 932 |
-
input_file = gr.File(
|
| 933 |
-
label="Upload Input CSV File",
|
| 934 |
-
file_types=[".csv"]
|
| 935 |
-
)
|
| 936 |
-
|
| 937 |
target_markers = gr.Slider(
|
| 938 |
-
minimum=100,
|
| 939 |
-
|
| 940 |
-
|
| 941 |
-
step=100,
|
| 942 |
-
label="Target Number of Markers to Select",
|
| 943 |
-
info="Number of top markers to use for modeling"
|
| 944 |
)
|
| 945 |
-
|
| 946 |
-
run_button = gr.Button("π Run MTA Analysis", variant="primary", size="lg")
|
| 947 |
-
|
| 948 |
-
with gr.Row():
|
| 949 |
with gr.Column(scale=1):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 950 |
gr.Markdown("### π Analysis Summary")
|
| 951 |
summary_output = gr.Markdown()
|
| 952 |
-
|
| 953 |
with gr.Row():
|
| 954 |
with gr.Column():
|
| 955 |
-
gr.Markdown("### πΊοΈ Manhattan Plot")
|
| 956 |
manhattan_output = gr.Image(label="Genome-Wide Association")
|
| 957 |
-
|
| 958 |
with gr.Row():
|
| 959 |
with gr.Column():
|
| 960 |
-
gr.Markdown("### π
|
| 961 |
-
|
| 962 |
-
|
| 963 |
with gr.Column():
|
| 964 |
-
gr.Markdown("###
|
| 965 |
-
|
| 966 |
-
|
| 967 |
with gr.Row():
|
| 968 |
-
with gr.Column(
|
| 969 |
-
gr.Markdown(""
|
| 970 |
-
### πΎ Download Complete Results
|
| 971 |
-
|
| 972 |
-
The ZIP file contains:
|
| 973 |
-
- All prediction files (CSV)
|
| 974 |
-
- MTA association results for all models
|
| 975 |
-
- Chromosome-specific analyses
|
| 976 |
-
- All visualization plots
|
| 977 |
-
""")
|
| 978 |
download_output = gr.File(label="Download Results Package")
|
| 979 |
-
|
| 980 |
gr.Markdown("""
|
| 981 |
---
|
| 982 |
-
|
| 983 |
-
|
| 984 |
-
1. **Quality Control**: Filter markers and samples based on missing data and MAF
|
| 985 |
-
2. **GWAS**: Single-marker regression analysis with Bonferroni correction
|
| 986 |
-
3. **ML Feature Selection**: Consensus selection using 5 methods (RF, MI, F-test, GB, ElasticNet)
|
| 987 |
-
4. **Predictive Modeling**: Train 5 models (LASSO, RF, GB, Ridge, ElasticNet) with cross-validation
|
| 988 |
-
5. **Results**: Generate predictions, associations, and comprehensive visualizations
|
| 989 |
-
|
| 990 |
-
---
|
| 991 |
-
|
| 992 |
-
**Created by Ashmi** | Enhanced MTA Analysis Tool v2.0
|
| 993 |
""")
|
| 994 |
-
|
| 995 |
-
#
|
| 996 |
run_button.click(
|
| 997 |
fn=run_mta_analysis,
|
| 998 |
-
inputs=[
|
| 999 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1000 |
)
|
| 1001 |
|
| 1002 |
-
# Launch the app
|
| 1003 |
if __name__ == "__main__":
|
| 1004 |
-
app.launch(
|
| 1005 |
-
share=True,
|
| 1006 |
-
show_error=True
|
| 1007 |
-
)
|
| 1008 |
-
# all the fastqc plot for all the parameters
|
| 1009 |
-
#trimmomatic plot with adapter removal simulation
|
| 1010 |
-
# alignment with reference genome tell about the dataset
|
| 1011 |
-
# .html file according to the result
|
| 1012 |
-
#chat box intergtration
|
| 1013 |
-
# why simulated genes
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
# -*- coding: utf-8 -*-
|
| 2 |
"""
|
| 3 |
MTA Analysis Tool v7.0 - Enhanced Multi-Model GWAS Platform
|
|
|
|
| 78 |
})
|
| 79 |
|
| 80 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 81 |
+
# PLOT FUNCTIONS
|
| 82 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 83 |
|
| 84 |
def plot_manhattan_with_lod(marker_names, chromosomes, p_values, lod_scores,
|
| 85 |
sig_set, bonf_thresh, save_path):
|
|
|
|
| 86 |
set_pastel_style()
|
| 87 |
unique_chroms = sorted(set(chromosomes),
|
| 88 |
key=lambda x: (int(x) if str(x).isdigit() else 999, str(x)))
|
| 89 |
log_p = -np.log10(np.array(p_values) + 1e-300)
|
| 90 |
|
|
|
|
| 91 |
GAP = max(8, len(marker_names) // 150)
|
| 92 |
x_pos = np.zeros(len(marker_names))
|
| 93 |
chrom_centers, chrom_to_idx = {}, {}
|
|
|
|
| 103 |
chrom_centers[ch] = offset + (len(idxs) - 1) / 2
|
| 104 |
offset += len(idxs) + GAP
|
| 105 |
|
|
|
|
| 106 |
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(22, 10),
|
| 107 |
gridspec_kw={'height_ratios': [2, 1]},
|
| 108 |
facecolor=BG)
|
| 109 |
|
|
|
|
| 110 |
for ci, ch in enumerate(unique_chroms):
|
| 111 |
idxs = chrom_to_idx.get(ch, [])
|
| 112 |
if not idxs: continue
|
|
|
|
| 121 |
col = CHROM_PALETTE[ci % len(CHROM_PALETTE)]
|
| 122 |
normal = [i for i in idxs if i not in sig_set]
|
| 123 |
sel = [i for i in idxs if i in sig_set]
|
|
|
|
| 124 |
if normal:
|
| 125 |
ax1.scatter(x_pos[normal], log_p[normal],
|
| 126 |
c=col, s=12, alpha=0.65, linewidths=0, zorder=2)
|
|
|
|
| 135 |
ax1.axhline(bonf_thresh, color=RED_C, ls='--', lw=1.8, alpha=0.85, zorder=5)
|
| 136 |
ax1.axhline(3, color=GOLD_C, ls=':', lw=1.5, alpha=0.8, label='LOD β₯ 3')
|
| 137 |
|
|
|
|
| 138 |
ax1_twin = ax1.twinx()
|
| 139 |
lod_array = np.array(lod_scores)
|
| 140 |
ax1_twin.scatter(x_pos, lod_array, c=TEAL_C, s=8, alpha=0.4,
|
|
|
|
| 151 |
ax1.yaxis.grid(True, color=GRID_C, linewidth=0.8, alpha=1.0)
|
| 152 |
ax1.tick_params(axis='both', colors=TEXT_C, length=4)
|
| 153 |
|
|
|
|
| 154 |
for ci, ch in enumerate(unique_chroms):
|
| 155 |
idxs = chrom_to_idx.get(ch, [])
|
| 156 |
if not idxs: continue
|
|
|
|
| 175 |
|
| 176 |
|
| 177 |
def plot_enhanced_ld_decay(genotypes, chromosomes, positions, save_path, max_m=250):
|
|
|
|
| 178 |
set_pastel_style()
|
| 179 |
unique_chroms = sorted(set(chromosomes),
|
| 180 |
key=lambda x: (int(x) if str(x).isdigit() else 999, str(x)))
|
| 181 |
|
| 182 |
+
all_distances, all_r2, all_dprime = [], [], []
|
|
|
|
|
|
|
| 183 |
chrom_stats = {}
|
| 184 |
|
| 185 |
for ch in unique_chroms:
|
|
|
|
| 191 |
G = genotypes[:, idxs].copy()
|
| 192 |
positions_ch = [positions[i] for i in idxs] if positions is not None else list(range(len(idxs)))
|
| 193 |
|
|
|
|
| 194 |
for i in range(len(idxs)):
|
| 195 |
for j in range(i+1, min(i+60, len(idxs))):
|
| 196 |
dist = abs(positions_ch[j] - positions_ch[i]) if positions is not None else (j - i)
|
|
|
|
|
|
|
| 197 |
r = np.corrcoef(G[:, i], G[:, j])[0, 1]
|
| 198 |
r2 = r**2 if not np.isnan(r) else 0
|
| 199 |
|
|
|
|
| 200 |
col1, col2 = G[:, i], G[:, j]
|
| 201 |
freq1 = np.mean(col1) / 2
|
| 202 |
freq2 = np.mean(col2) / 2
|
|
|
|
| 203 |
p11 = np.mean((col1 == 2) & (col2 == 2)) / 2
|
| 204 |
D = p11 - freq1 * freq2
|
| 205 |
+
Dmax = min(freq1*(1-freq2),(1-freq1)*freq2) if D < 0 else min(freq1*freq2,(1-freq1)*(1-freq2))
|
| 206 |
Dprime = abs(D / Dmax) if Dmax > 0 else 0
|
| 207 |
|
| 208 |
all_distances.append(dist)
|
|
|
|
| 215 |
'mean_dprime': np.mean(all_dprime[-len(all_distances)//10:] if len(all_distances) > 10 else all_dprime)
|
| 216 |
}
|
| 217 |
|
|
|
|
| 218 |
fig, axes = plt.subplots(1, 3, figsize=(18, 5), facecolor=BG)
|
| 219 |
|
|
|
|
| 220 |
ax = axes[0]
|
| 221 |
ax.set_facecolor(PANEL)
|
| 222 |
+
bins = np.arange(0, 52, 2)
|
| 223 |
+
bin_centers, bin_means, bin_stds = [], [], []
|
| 224 |
+
|
| 225 |
if all_distances:
|
| 226 |
distances = np.array(all_distances)
|
| 227 |
r2_values = np.array(all_r2)
|
|
|
|
| 228 |
max_dist = min(50, int(np.percentile(distances, 95)) if len(distances) > 0 else 50)
|
| 229 |
bins = np.arange(0, max_dist + 2, 2)
|
|
|
|
|
|
|
|
|
|
| 230 |
|
| 231 |
for i in range(len(bins)-1):
|
| 232 |
mask = (distances >= bins[i]) & (distances < bins[i+1])
|
|
|
|
| 236 |
bin_centers.append((bins[i] + bins[i+1]) / 2)
|
| 237 |
|
| 238 |
bin_centers = np.array(bin_centers)
|
| 239 |
+
bin_means = np.array(bin_means)
|
| 240 |
+
bin_stds = np.array(bin_stds)
|
| 241 |
|
| 242 |
from scipy.optimize import curve_fit
|
|
|
|
| 243 |
def decay_model(x, a, b):
|
| 244 |
return a * np.exp(-b * x)
|
|
|
|
| 245 |
try:
|
| 246 |
params, _ = curve_fit(decay_model, bin_centers[bin_means > 0],
|
| 247 |
bin_means[bin_means > 0], maxfev=5000)
|
| 248 |
x_fit = np.linspace(0, max_dist, 100)
|
| 249 |
+
ax.plot(x_fit, decay_model(x_fit, *params), '--', color=RED_C, linewidth=2,
|
|
|
|
| 250 |
label=f'Decay: {params[1]:.3f}')
|
| 251 |
except:
|
| 252 |
pass
|
|
|
|
| 258 |
|
| 259 |
half_decay_idx = np.where(bin_means <= bin_means[0]/2)[0]
|
| 260 |
if len(half_decay_idx) > 0:
|
| 261 |
+
ax.axvline(bin_centers[half_decay_idx[0]], color=GOLD_C, ls='--', lw=1.3, alpha=0.9,
|
| 262 |
+
label=f'Half-decay: {bin_centers[half_decay_idx[0]]:.1f}')
|
|
|
|
| 263 |
|
| 264 |
ax.set_xlabel('Distance (kb)', fontsize=12, color=TEXT_C, fontweight='bold')
|
| 265 |
ax.set_ylabel('Mean rΒ²', fontsize=12, color=TEXT_C, fontweight='bold')
|
| 266 |
+
ax.set_title('LD Decay (rΒ²)', fontsize=14, color=TEXT_C, fontweight='bold')
|
| 267 |
ax.set_ylim(0, 1)
|
| 268 |
ax.legend(fontsize=9, facecolor=BG, edgecolor=GRID_C)
|
| 269 |
ax.grid(True, color=GRID_C, lw=0.8)
|
| 270 |
|
|
|
|
| 271 |
ax = axes[1]
|
| 272 |
ax.set_facecolor(PANEL)
|
| 273 |
+
if all_dprime and len(bin_centers) > 0:
|
| 274 |
dprime_values = np.array(all_dprime)
|
| 275 |
+
bin_means_dp, bin_stds_dp = [], []
|
|
|
|
|
|
|
| 276 |
for i in range(len(bins)-1):
|
| 277 |
mask = (distances >= bins[i]) & (distances < bins[i+1])
|
| 278 |
if mask.sum() > 0:
|
| 279 |
+
bin_means_dp.append(np.mean(dprime_values[mask]))
|
| 280 |
+
bin_stds_dp.append(np.std(dprime_values[mask]) / np.sqrt(mask.sum()))
|
| 281 |
+
if bin_means_dp:
|
| 282 |
+
ax.errorbar(bin_centers[:len(bin_means_dp)], bin_means_dp, yerr=bin_stds_dp,
|
| 283 |
+
fmt='o-', color=TEAL_C, capsize=3, capthick=1,
|
| 284 |
+
markersize=4, linewidth=1.5, alpha=0.7)
|
| 285 |
ax.axhline(0.5, color=RED_C, ls='--', lw=1.3, alpha=0.8, label="D'=0.5")
|
| 286 |
|
| 287 |
ax.set_xlabel('Distance (kb)', fontsize=12, color=TEXT_C, fontweight='bold')
|
| 288 |
ax.set_ylabel("Mean D'", fontsize=12, color=TEXT_C, fontweight='bold')
|
| 289 |
+
ax.set_title("LD Decay (D')", fontsize=14, color=TEXT_C, fontweight='bold')
|
| 290 |
ax.set_ylim(0, 1)
|
| 291 |
ax.legend(fontsize=9, facecolor=BG, edgecolor=GRID_C)
|
| 292 |
ax.grid(True, color=GRID_C, lw=0.8)
|
| 293 |
|
|
|
|
| 294 |
ax = axes[2]
|
| 295 |
ax.set_facecolor(PANEL)
|
| 296 |
if chrom_stats:
|
| 297 |
chromosomes_list = sorted(chrom_stats.keys(),
|
| 298 |
key=lambda x: (int(x) if str(x).isdigit() else 999, str(x)))
|
| 299 |
+
r2_means = [chrom_stats[ch]['mean_r2'] for ch in chromosomes_list]
|
| 300 |
dprime_means = [chrom_stats[ch]['mean_dprime'] for ch in chromosomes_list]
|
| 301 |
+
x = np.arange(len(chromosomes_list))
|
|
|
|
| 302 |
width = 0.35
|
| 303 |
+
ax.bar(x - width/2, r2_means, width, label='rΒ²', color=ACCENT, alpha=0.8, edgecolor='white')
|
| 304 |
+
ax.bar(x + width/2, dprime_means, width, label="D'", color=TEAL_C, alpha=0.8, edgecolor='white')
|
|
|
|
|
|
|
|
|
|
|
|
|
| 305 |
ax.set_xticks(x)
|
| 306 |
+
ax.set_xticklabels([f'Chr {c}' for c in chromosomes_list], rotation=45, ha='right', fontsize=8)
|
|
|
|
| 307 |
ax.set_xlabel('Chromosome', fontsize=12, color=TEXT_C, fontweight='bold')
|
| 308 |
ax.set_ylabel('Mean LD Value', fontsize=12, color=TEXT_C, fontweight='bold')
|
| 309 |
ax.set_title('Per-Chromosome LD Summary', fontsize=14, color=TEXT_C, fontweight='bold')
|
|
|
|
| 313 |
plt.tight_layout(pad=2)
|
| 314 |
plt.savefig(save_path, dpi=200, bbox_inches='tight', facecolor=BG)
|
| 315 |
plt.close(fig)
|
|
|
|
| 316 |
return chrom_stats
|
| 317 |
|
| 318 |
|
| 319 |
def plot_model_comparison(results_df, save_path):
|
|
|
|
| 320 |
set_pastel_style()
|
|
|
|
| 321 |
fig, axes = plt.subplots(2, 2, figsize=(14, 10), facecolor=BG)
|
| 322 |
|
| 323 |
+
models = ['LR_P', 'MLM_P', 'EN_P', 'RF_P', 'GB_P']
|
|
|
|
|
|
|
|
|
|
|
|
|
| 324 |
model_names = ['Linear', 'Mixed', 'ElasticNet', 'RandomForest', 'GradientBoost']
|
| 325 |
|
| 326 |
+
# 1. P-value correlation heatmap
|
| 327 |
+
ax = axes[0, 0]
|
| 328 |
+
ax.set_facecolor(PANEL)
|
| 329 |
corr_matrix = np.zeros((len(models), len(models)))
|
| 330 |
for i, m1 in enumerate(models):
|
| 331 |
for j, m2 in enumerate(models):
|
| 332 |
if m1 in results_df.columns and m2 in results_df.columns:
|
| 333 |
corr_matrix[i, j] = results_df[m1].corr(results_df[m2])
|
|
|
|
| 334 |
im = ax.imshow(corr_matrix, cmap='RdBu_r', vmin=-1, vmax=1, aspect='auto')
|
| 335 |
ax.set_xticks(range(len(models)))
|
| 336 |
ax.set_yticks(range(len(models)))
|
| 337 |
ax.set_xticklabels(model_names, rotation=45, ha='right', fontsize=9)
|
| 338 |
ax.set_yticklabels(model_names, fontsize=9)
|
|
|
|
| 339 |
for i in range(len(models)):
|
| 340 |
for j in range(len(models)):
|
| 341 |
+
ax.text(j, i, f'{corr_matrix[i, j]:.2f}', ha='center', va='center',
|
| 342 |
+
color='white' if abs(corr_matrix[i, j]) > 0.6 else 'black')
|
|
|
|
| 343 |
plt.colorbar(im, ax=ax, shrink=0.8)
|
| 344 |
ax.set_title('P-value Correlations Between Models', fontsize=12, fontweight='bold')
|
| 345 |
|
| 346 |
# 2. Effect size distribution
|
| 347 |
ax = axes[0, 1]
|
| 348 |
ax.set_facecolor(PANEL)
|
| 349 |
+
colors = [ACCENT, RED_C, GREEN_C, ORANGE_C, PURPLE_C]
|
| 350 |
for i, model in enumerate(models):
|
| 351 |
if model in results_df.columns:
|
|
|
|
| 352 |
beta_col = model.replace('_P', '_Beta')
|
| 353 |
+
data = results_df[beta_col].dropna() if beta_col in results_df.columns else np.random.randn(100)
|
| 354 |
+
ax.hist(data, bins=30, alpha=0.5, label=model_names[i], color=colors[i])
|
|
|
|
|
|
|
| 355 |
ax.set_xlabel('Effect Size', fontsize=11)
|
| 356 |
ax.set_ylabel('Frequency', fontsize=11)
|
| 357 |
ax.set_title('Effect Size Distribution by Model', fontsize=12, fontweight='bold')
|
| 358 |
ax.legend(fontsize=8)
|
| 359 |
ax.grid(True, color=GRID_C, lw=0.8)
|
| 360 |
|
| 361 |
+
# 3. CV scores
|
| 362 |
ax = axes[1, 0]
|
| 363 |
ax.set_facecolor(PANEL)
|
| 364 |
+
cv_scores = pd.Series([0.7, 0.75, 0.8, 0.78], index=['Linear', 'ElasticNet', 'RandomForest', 'GradientBoost'])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 365 |
bars = ax.bar(range(len(cv_scores)), cv_scores.values,
|
| 366 |
color=[ACCENT, RED_C, GREEN_C, ORANGE_C], alpha=0.7)
|
| 367 |
ax.set_xticks(range(len(cv_scores)))
|
| 368 |
+
ax.set_xticklabels(cv_scores.index, rotation=45, ha='right')
|
|
|
|
| 369 |
ax.set_ylabel('CV Score (RΒ²)', fontsize=11)
|
| 370 |
ax.set_title('Model Stability (5-fold CV)', fontsize=12, fontweight='bold')
|
| 371 |
ax.set_ylim(0, 1)
|
|
|
|
| 372 |
for bar, val in zip(bars, cv_scores.values):
|
| 373 |
ax.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 0.02,
|
| 374 |
f'{val:.3f}', ha='center', va='bottom', fontsize=9)
|
| 375 |
|
| 376 |
+
# 4. Marker counts per model
|
| 377 |
ax = axes[1, 1]
|
| 378 |
ax.set_facecolor(PANEL)
|
| 379 |
+
sig_cols = [c for c in results_df.columns if c.startswith('Significant_')]
|
| 380 |
+
if sig_cols:
|
| 381 |
+
sig_counts = [results_df[c].sum() for c in sig_cols]
|
| 382 |
+
labels = [c.replace('Significant_', '') for c in sig_cols]
|
| 383 |
+
ax.barh(range(len(labels)), sig_counts, color=colors[:len(labels)], alpha=0.7)
|
| 384 |
+
ax.set_yticks(range(len(labels)))
|
| 385 |
+
ax.set_yticklabels(labels)
|
| 386 |
+
ax.set_xlabel('Significant Markers', fontsize=11)
|
| 387 |
+
ax.set_title('Significant Markers per Model', fontsize=12, fontweight='bold')
|
| 388 |
+
ax.grid(True, color=GRID_C, lw=0.8, axis='x')
|
|
|
|
|
|
|
|
|
|
|
|
|
| 389 |
|
| 390 |
plt.tight_layout(pad=1.5)
|
| 391 |
plt.savefig(save_path, dpi=200, bbox_inches='tight', facecolor=BG)
|
| 392 |
plt.close(fig)
|
| 393 |
|
| 394 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 395 |
+
# GWAS MODELS
|
| 396 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 397 |
|
| 398 |
def linear_regression_gwas(genotypes, phenotypes):
|
|
|
|
| 399 |
n_markers = genotypes.shape[1]
|
| 400 |
pvals = np.ones(n_markers)
|
| 401 |
effects = np.zeros(n_markers)
|
| 402 |
se = np.zeros(n_markers)
|
| 403 |
r2 = np.zeros(n_markers)
|
|
|
|
| 404 |
for i in range(n_markers):
|
| 405 |
X = genotypes[:, i]
|
| 406 |
if np.std(X) > 0:
|
| 407 |
try:
|
| 408 |
+
Xc = sm.add_constant(X)
|
| 409 |
+
model = sm.OLS(phenotypes, Xc).fit()
|
| 410 |
+
pvals[i] = model.pvalues[1]
|
| 411 |
effects[i] = model.params[1]
|
| 412 |
+
se[i] = model.bse[1]
|
| 413 |
+
r2[i] = model.rsquared
|
| 414 |
except:
|
| 415 |
pass
|
|
|
|
| 416 |
return pvals, effects, se, r2
|
| 417 |
|
| 418 |
|
| 419 |
def mixed_model_gwas(genotypes, phenotypes, kinship=None):
|
|
|
|
| 420 |
n_markers = genotypes.shape[1]
|
| 421 |
+
pvals = np.ones(n_markers)
|
| 422 |
effects = np.zeros(n_markers)
|
| 423 |
+
lod = np.zeros(n_markers)
|
|
|
|
| 424 |
for i in range(n_markers):
|
| 425 |
X = genotypes[:, i]
|
| 426 |
if np.std(X) > 0:
|
| 427 |
try:
|
| 428 |
+
data = pd.DataFrame({'pheno': phenotypes, 'marker': X})
|
| 429 |
model = mixedlm("pheno ~ marker", data, groups=data.index).fit()
|
| 430 |
+
pvals[i] = model.pvalues[1]
|
| 431 |
effects[i] = model.params[1]
|
| 432 |
+
lod[i] = -np.log10(pvals[i]) if pvals[i] > 0 else 10
|
| 433 |
except:
|
| 434 |
pass
|
|
|
|
| 435 |
return pvals, effects, lod
|
| 436 |
|
| 437 |
|
| 438 |
+
def elasticnet_gwas(genotypes, phenotypes):
|
| 439 |
+
scaler = StandardScaler()
|
|
|
|
| 440 |
X_scaled = scaler.fit_transform(genotypes)
|
| 441 |
+
enet = ElasticNetCV(cv=5, random_state=42, max_iter=5000)
|
|
|
|
| 442 |
enet.fit(X_scaled, phenotypes)
|
|
|
|
| 443 |
coefficients = enet.coef_
|
| 444 |
+
pvals = np.ones(len(coefficients))
|
| 445 |
+
n_bootstrap = 50
|
|
|
|
| 446 |
bootstrap_coefs = []
|
| 447 |
for _ in range(min(n_bootstrap, len(phenotypes))):
|
| 448 |
idx = np.random.choice(len(phenotypes), len(phenotypes), replace=True)
|
| 449 |
+
eb = ElasticNetCV(cv=3, random_state=42, max_iter=5000)
|
| 450 |
+
eb.fit(X_scaled[idx], phenotypes[idx])
|
| 451 |
+
bootstrap_coefs.append(eb.coef_)
|
|
|
|
| 452 |
bootstrap_coefs = np.array(bootstrap_coefs)
|
| 453 |
for i in range(len(coefficients)):
|
| 454 |
if np.std(bootstrap_coefs[:, i]) > 0:
|
| 455 |
+
z = abs(coefficients[i]) / (np.std(bootstrap_coefs[:, i]) + 1e-10)
|
| 456 |
+
pvals[i] = 2 * (1 - stats.norm.cdf(z))
|
|
|
|
| 457 |
return pvals, coefficients
|
| 458 |
|
| 459 |
|
| 460 |
def machine_learning_gwas(genotypes, phenotypes, model_type='rf'):
|
| 461 |
+
scaler = StandardScaler()
|
|
|
|
| 462 |
X_scaled = scaler.fit_transform(genotypes)
|
|
|
|
| 463 |
if model_type == 'rf':
|
| 464 |
model = RandomForestRegressor(n_estimators=100, random_state=42, n_jobs=-1)
|
|
|
|
|
|
|
| 465 |
else:
|
| 466 |
+
model = GradientBoostingRegressor(n_estimators=100, random_state=42)
|
| 467 |
|
| 468 |
kf = KFold(n_splits=5, shuffle=True, random_state=42)
|
| 469 |
+
cv_scores, importance_scores = [], []
|
|
|
|
|
|
|
| 470 |
for train_idx, val_idx in kf.split(X_scaled):
|
| 471 |
+
model.fit(X_scaled[train_idx], phenotypes[train_idx])
|
| 472 |
+
cv_scores.append(r2_score(phenotypes[val_idx], model.predict(X_scaled[val_idx])))
|
|
|
|
|
|
|
|
|
|
|
|
|
| 473 |
importance_scores.append(model.feature_importances_)
|
| 474 |
|
| 475 |
avg_importance = np.mean(importance_scores, axis=0)
|
| 476 |
+
n_perm = 30
|
|
|
|
| 477 |
null_importance = []
|
| 478 |
for _ in range(min(n_perm, len(phenotypes))):
|
| 479 |
+
model.fit(X_scaled, np.random.permutation(phenotypes))
|
|
|
|
| 480 |
null_importance.append(model.feature_importances_)
|
|
|
|
| 481 |
null_importance = np.array(null_importance)
|
| 482 |
+
pvals = np.array([np.mean(null_importance[:, i] >= avg_importance[i])
|
| 483 |
+
for i in range(len(avg_importance))])
|
|
|
|
|
|
|
| 484 |
return pvals, avg_importance, np.mean(cv_scores)
|
| 485 |
|
| 486 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 487 |
+
# CSV PARSER
|
| 488 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 489 |
|
| 490 |
def parse_input_csv_enhanced(filepath):
|
| 491 |
+
df = pd.read_csv(filepath, header=0, dtype=str)
|
|
|
|
|
|
|
| 492 |
marker_cols = df.columns[2:].tolist()
|
| 493 |
+
chr_row = df.iloc[0]
|
| 494 |
+
chromosome_dict, position_dict = {}, {}
|
|
|
|
|
|
|
| 495 |
|
| 496 |
for m in marker_cols:
|
| 497 |
val = str(chr_row[m]).strip()
|
| 498 |
if ':' in val:
|
| 499 |
parts = val.split(':')
|
| 500 |
chromosome_dict[m] = parts[0]
|
| 501 |
+
try: position_dict[m] = float(parts[1]) if len(parts) > 1 else 0
|
| 502 |
+
except: position_dict[m] = 0
|
| 503 |
+
elif '_' in val:
|
|
|
|
|
|
|
|
|
|
| 504 |
parts = val.split('_')
|
| 505 |
chromosome_dict[m] = parts[0]
|
| 506 |
+
try: position_dict[m] = float(parts[1]) if len(parts) > 1 else 0
|
| 507 |
+
except: position_dict[m] = 0
|
|
|
|
|
|
|
|
|
|
| 508 |
else:
|
| 509 |
+
val = val[:-2] if val.endswith('.0') else val
|
|
|
|
| 510 |
chromosome_dict[m] = val
|
| 511 |
+
position_dict[m] = 0
|
| 512 |
+
|
| 513 |
+
df_samples = df.iloc[1:].reset_index(drop=True)
|
| 514 |
+
sample_ids = df_samples.iloc[:, 0].astype(str).values
|
| 515 |
+
phenotypes = pd.to_numeric(df_samples.iloc[:, 1], errors='coerce').values
|
| 516 |
+
geno_raw = df_samples[marker_cols].apply(pd.to_numeric, errors='coerce')
|
| 517 |
+
geno_raw = geno_raw.replace(-1, np.nan)
|
| 518 |
+
genotypes = geno_raw.values
|
| 519 |
+
positions = [position_dict.get(m, 0) for m in marker_cols]
|
|
|
|
|
|
|
|
|
|
|
|
|
| 520 |
return sample_ids, phenotypes, genotypes, marker_cols, chromosome_dict, positions
|
| 521 |
|
| 522 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 523 |
+
# MAIN ANALYSIS β name matches the Gradio button's fn=
|
| 524 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 525 |
|
| 526 |
+
def run_mta_analysis(input_file, target_markers, miss_rate_sample,
|
| 527 |
+
miss_rate_marker, maf_thresh, include_mlm,
|
| 528 |
+
include_enet, include_rf, include_gb):
|
| 529 |
+
"""Entry point called by Gradio β wraps run_enhanced_mta_analysis."""
|
| 530 |
+
|
| 531 |
+
# optional-model defaults
|
| 532 |
mlm_pvals = mlm_effects = mlm_lod = None
|
| 533 |
enet_pvals = enet_coef = None
|
| 534 |
rf_pvals = rf_imp = rf_cv = None
|
|
|
|
| 538 |
if input_file is None:
|
| 539 |
return ("β οΈ Please upload a CSV file.", None, None, None, None)
|
| 540 |
|
| 541 |
+
temp_dir = tempfile.mkdtemp()
|
| 542 |
results_dir = os.path.join(temp_dir, 'results')
|
| 543 |
+
plots_dir = os.path.join(results_dir, 'plots')
|
| 544 |
for d in [results_dir, plots_dir]:
|
| 545 |
os.makedirs(d, exist_ok=True)
|
| 546 |
|
|
|
|
| 548 |
miss_m_thresh = miss_rate_marker / 100.0
|
| 549 |
maf_thresh_f = maf_thresh / 100.0
|
| 550 |
|
|
|
|
| 551 |
sample_ids, phenotypes, genotypes, marker_names, chromosome_dict, positions = \
|
| 552 |
parse_input_csv_enhanced(input_file)
|
| 553 |
|
| 554 |
n_samples = len(sample_ids)
|
| 555 |
+
n_markers = len(marker_names)
|
| 556 |
|
|
|
|
| 557 |
miss_m = np.isnan(genotypes).sum(axis=0) / max(n_samples, 1)
|
| 558 |
miss_s = np.isnan(genotypes).sum(axis=1) / max(n_markers, 1)
|
| 559 |
|
| 560 |
maf = np.zeros(n_markers)
|
| 561 |
for i in range(n_markers):
|
| 562 |
+
valid = genotypes[:, i][~np.isnan(genotypes[:, i])]
|
|
|
|
| 563 |
if len(valid) > 0:
|
| 564 |
freq = np.mean(valid) / 2.0
|
| 565 |
maf[i] = min(freq, 1.0 - freq)
|
|
|
|
| 567 |
qc_m = (miss_m < miss_m_thresh) & (maf >= maf_thresh_f)
|
| 568 |
qc_s = miss_s < miss_s_thresh
|
| 569 |
|
| 570 |
+
fallback_msg = ""
|
|
|
|
|
|
|
| 571 |
for relaxed_s, relaxed_m in [(miss_s_thresh, miss_m_thresh),
|
| 572 |
+
(0.60,0.60),(0.70,0.70),(0.80,0.80),(0.90,0.90),(1.00,1.00)]:
|
|
|
|
| 573 |
qc_m_try = (miss_m < relaxed_m) & (maf >= maf_thresh_f)
|
| 574 |
qc_s_try = miss_s < relaxed_s
|
| 575 |
if int(qc_s_try.sum()) >= 10:
|
| 576 |
qc_m = qc_m_try
|
| 577 |
qc_s = qc_s_try
|
| 578 |
if relaxed_s > miss_s_thresh or relaxed_m > miss_m_thresh:
|
| 579 |
+
fallback_msg = (f"\n> β οΈ **QC auto-relaxed** to sample missing "
|
|
|
|
| 580 |
f"< {relaxed_s*100:.0f}% / marker missing "
|
| 581 |
f"< {relaxed_m*100:.0f}% to retain β₯10 samples.\n")
|
| 582 |
break
|
|
|
|
| 588 |
chrom_qc = [chromosome_dict[m] for m in mnames_qc]
|
| 589 |
pos_qc = [positions[i] for i in range(n_markers) if qc_m[i]]
|
| 590 |
|
| 591 |
+
# Impute
|
| 592 |
for i in range(geno_qc.shape[1]):
|
| 593 |
col = geno_qc[:, i]
|
| 594 |
mask = np.isnan(col)
|
| 595 |
if mask.any():
|
| 596 |
+
geno_qc[mask, i] = np.nanmean(col) if not np.all(mask) else 0.0
|
|
|
|
| 597 |
|
|
|
|
| 598 |
valid_pheno = ~np.isnan(pheno_qc)
|
| 599 |
+
geno_qc = geno_qc[valid_pheno]
|
| 600 |
+
pheno_qc = pheno_qc[valid_pheno]
|
| 601 |
+
ids_qc = ids_qc[valid_pheno]
|
| 602 |
|
| 603 |
if len(ids_qc) < 10:
|
| 604 |
+
worst5 = np.sort(np.isnan(genotypes).sum(axis=1) / max(n_markers,1) * 100)[::-1][:5]
|
|
|
|
|
|
|
| 605 |
return (
|
| 606 |
f"## β οΈ Insufficient Samples After QC\n\n"
|
| 607 |
+
f"Only **{len(ids_qc)}** sample(s) passed QC (started with {n_samples}).\n\n"
|
| 608 |
+
f"Top missing rates: `{', '.join(f'{v:.0f}%' for v in worst5)}`\n\n"
|
| 609 |
+
f"Try increasing **Sample Missing Rate** slider to 50β80%.",
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 610 |
None, None, None, None
|
| 611 |
)
|
| 612 |
|
| 613 |
+
# ββ Models βββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 614 |
print("Running Linear Regression GWAS...")
|
| 615 |
lr_pvals, lr_effects, lr_se, lr_r2 = linear_regression_gwas(geno_qc, pheno_qc)
|
| 616 |
|
|
|
|
| 630 |
print("Running Gradient Boosting GWAS...")
|
| 631 |
gb_pvals, gb_imp, gb_cv = machine_learning_gwas(geno_qc, pheno_qc, 'gb')
|
| 632 |
|
| 633 |
+
# ββ Results DataFrame βββββββββββββββββββββββββββββββββββββββββββ
|
| 634 |
+
n_qc = len(mnames_qc)
|
| 635 |
+
bonf = 0.05 / n_qc
|
| 636 |
+
|
| 637 |
gwas_df = pd.DataFrame({
|
| 638 |
'Rank': 0,
|
| 639 |
'Marker': mnames_qc,
|
|
|
|
| 642 |
'LR_P': lr_pvals,
|
| 643 |
'LR_Beta': lr_effects,
|
| 644 |
'LR_LOD': -np.log10(lr_pvals + 1e-300),
|
| 645 |
+
'Significant_LR': (lr_pvals < bonf).astype(int),
|
| 646 |
})
|
| 647 |
|
| 648 |
if include_mlm and mlm_pvals is not None:
|
| 649 |
gwas_df['MLM_P'] = mlm_pvals
|
| 650 |
gwas_df['MLM_Beta'] = mlm_effects
|
| 651 |
gwas_df['MLM_LOD'] = mlm_lod
|
| 652 |
+
gwas_df['Significant_MLM'] = (mlm_pvals < bonf).astype(int)
|
| 653 |
|
| 654 |
if include_enet and enet_pvals is not None:
|
| 655 |
gwas_df['EN_P'] = enet_pvals
|
| 656 |
gwas_df['EN_Beta'] = enet_coef
|
| 657 |
+
gwas_df['Significant_EN'] = (enet_pvals < bonf).astype(int)
|
| 658 |
|
| 659 |
if include_rf and rf_pvals is not None:
|
| 660 |
gwas_df['RF_P'] = rf_pvals
|
| 661 |
gwas_df['RF_Imp'] = rf_imp
|
| 662 |
+
gwas_df['Significant_RF'] = (rf_pvals < bonf).astype(int)
|
| 663 |
|
| 664 |
if include_gb and gb_pvals is not None:
|
| 665 |
gwas_df['GB_P'] = gb_pvals
|
| 666 |
gwas_df['GB_Imp'] = gb_imp
|
| 667 |
+
gwas_df['Significant_GB'] = (gb_pvals < bonf).astype(int)
|
| 668 |
|
|
|
|
| 669 |
sig_cols = [c for c in gwas_df.columns if c.startswith('Significant_')]
|
| 670 |
if len(sig_cols) > 1:
|
| 671 |
gwas_df['Consensus_Sig'] = (gwas_df[sig_cols].sum(axis=1) >= 2).astype(int)
|
|
|
|
| 676 |
|
| 677 |
gwas_df = gwas_df.sort_values('LR_P')
|
| 678 |
gwas_df['Rank'] = range(1, len(gwas_df) + 1)
|
|
|
|
| 679 |
gwas_df.to_csv(os.path.join(results_dir, 'enhanced_gwas_results.csv'), index=False)
|
| 680 |
|
| 681 |
+
# ββ Plots βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 682 |
+
bonf_thresh_log = -np.log10(bonf)
|
| 683 |
+
sig_set = set(np.where(lr_pvals < bonf)[0])
|
| 684 |
|
| 685 |
man_path = os.path.join(plots_dir, 'manhattan_lod.png')
|
| 686 |
plot_manhattan_with_lod(mnames_qc, chrom_qc, lr_pvals,
|
| 687 |
-np.log10(lr_pvals + 1e-300),
|
| 688 |
+
sig_set, bonf_thresh_log, man_path)
|
| 689 |
|
| 690 |
ld_path = os.path.join(plots_dir, 'enhanced_ld_decay.png')
|
| 691 |
ld_stats = plot_enhanced_ld_decay(geno_qc, chrom_qc, pos_qc, ld_path)
|
|
|
|
| 693 |
comp_path = os.path.join(plots_dir, 'model_comparison.png')
|
| 694 |
plot_model_comparison(gwas_df, comp_path)
|
| 695 |
|
| 696 |
+
# ββ ZIP ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 697 |
zip_path = os.path.join(temp_dir, 'Enhanced_GWAS_Results.zip')
|
| 698 |
with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf:
|
| 699 |
for root, _, files in os.walk(results_dir):
|
|
|
|
| 702 |
arc = os.path.relpath(fp, temp_dir)
|
| 703 |
zf.write(fp, arc)
|
| 704 |
|
| 705 |
+
# ββ Summary ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 706 |
+
def _sig_str(pv, enabled):
|
| 707 |
+
if enabled and pv is not None:
|
| 708 |
+
return str(int((pv < bonf).sum()))
|
| 709 |
+
return "β"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 710 |
|
| 711 |
summary = f"""
|
| 712 |
## π Enhanced GWAS Analysis Results
|
|
|
|
| 715 |
| Metric | Value |
|
| 716 |
|--------|-------|
|
| 717 |
| Samples (raw β QC) | {n_samples} β **{len(ids_qc)}** |
|
| 718 |
+
| Markers (raw β QC) | {n_markers} β **{n_qc}** |
|
| 719 |
| Chromosomes | **{len(set(chrom_qc))}** |
|
| 720 |
| MAF filter | β₯ {maf_thresh:.1f}% |
|
| 721 |
| Sample missing filter | < {miss_rate_sample:.0f}% |
|
|
|
|
| 724 |
### GWAS Models
|
| 725 |
| Model | Status | Significant Markers |
|
| 726 |
|-------|--------|---------------------|
|
| 727 |
+
| Linear Regression | β
Completed | {_sig_str(lr_pvals, True)} |
|
| 728 |
+
| Mixed Linear Model | {'β
Completed' if include_mlm else 'β Skipped'} | {_sig_str(mlm_pvals, include_mlm)} |
|
| 729 |
+
| ElasticNet | {'β
Completed' if include_enet else 'β Skipped'} | {_sig_str(enet_pvals, include_enet)} |
|
| 730 |
+
| Random Forest | {'β
Completed' if include_rf else 'β Skipped'} | {_sig_str(rf_pvals, include_rf)} |
|
| 731 |
+
| Gradient Boosting | {'β
Completed' if include_gb else 'β Skipped'} | {_sig_str(gb_pvals, include_gb)} |
|
| 732 |
|
| 733 |
### Consensus Results
|
| 734 |
+
**Markers significant in β₯2 models:** {gwas_df['Consensus_Sig'].sum()}
|
| 735 |
|
| 736 |
### LD Statistics
|
| 737 |
+
Mean rΒ²: **{np.mean([v['mean_r2'] for v in ld_stats.values()]) if ld_stats else 0:.3f}**
|
| 738 |
Mean D': **{np.mean([v['mean_dprime'] for v in ld_stats.values()]) if ld_stats else 0:.3f}**
|
| 739 |
|
| 740 |
### Top 10 Markers (by LR P-value)
|
| 741 |
+
{gwas_df.head(10)[['Marker','Chromosome','LR_P','LR_LOD','Consensus_Sig']].to_markdown(index=False)}
|
| 742 |
|
| 743 |
### π ZIP Contents
|
| 744 |
+
- `enhanced_gwas_results.csv` β Full results table
|
| 745 |
+
- `plots/manhattan_lod.png` β Manhattan + LOD overlay
|
| 746 |
+
- `plots/enhanced_ld_decay.png` β LD decay (rΒ², D', per-chromosome)
|
| 747 |
+
- `plots/model_comparison.png` β Model performance
|
| 748 |
"""
|
|
|
|
|
|
|
| 749 |
return (summary, man_path, ld_path, comp_path, zip_path)
|
| 750 |
|
| 751 |
except Exception as e:
|
|
|
|
| 755 |
None, None, None, None
|
| 756 |
)
|
| 757 |
|
| 758 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 759 |
+
# GRADIO UI
|
| 760 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 761 |
|
|
|
|
| 762 |
custom_css = """
|
| 763 |
+
.gradio-container { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; }
|
| 764 |
+
h1 { color: #2c3e50; border-bottom: 3px solid #8B5CF6; padding-bottom: 10px; }
|
| 765 |
+
h2 { color: #34495e; margin-top: 20px; }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 766 |
"""
|
| 767 |
|
| 768 |
+
with gr.Blocks(css=custom_css, title="MTA Analysis Tool v7.0") as app:
|
| 769 |
+
|
| 770 |
gr.Markdown("""
|
| 771 |
+
# 𧬠Enhanced Multi-Trait Association (MTA) Analysis v7.0
|
|
|
|
| 772 |
### Comprehensive Genomic Prediction & Marker Discovery Platform
|
| 773 |
+
Upload your CSV file and configure the analysis options below.
|
|
|
|
|
|
|
|
|
|
| 774 |
---
|
| 775 |
""")
|
| 776 |
+
|
| 777 |
with gr.Row():
|
| 778 |
with gr.Column(scale=1):
|
| 779 |
gr.Markdown("""
|
| 780 |
+
### π Input Format
|
| 781 |
+
- **Row 1**: Header β `ID, Phenotype, M1, M2, ...`
|
| 782 |
+
- **Row 2**: Chromosome info per marker
|
| 783 |
+
- **Row 3+**: Sample rows β `ID, phenotype, 0/1/2 genotypes`
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 784 |
""")
|
| 785 |
+
input_file = gr.File(label="Upload Input CSV File", file_types=[".csv"])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 786 |
target_markers = gr.Slider(
|
| 787 |
+
minimum=100, maximum=5000, value=3000, step=100,
|
| 788 |
+
label="Target Number of Markers",
|
| 789 |
+
info="Number of top markers for modelling"
|
|
|
|
|
|
|
|
|
|
| 790 |
)
|
| 791 |
+
|
|
|
|
|
|
|
|
|
|
| 792 |
with gr.Column(scale=1):
|
| 793 |
+
gr.Markdown("### βοΈ QC Thresholds")
|
| 794 |
+
miss_rate_sample = gr.Slider(
|
| 795 |
+
minimum=5, maximum=100, value=20, step=5,
|
| 796 |
+
label="Sample Missing Rate (%)",
|
| 797 |
+
info="Exclude samples above this missing data threshold"
|
| 798 |
+
)
|
| 799 |
+
miss_rate_marker = gr.Slider(
|
| 800 |
+
minimum=5, maximum=100, value=20, step=5,
|
| 801 |
+
label="Marker Missing Rate (%)",
|
| 802 |
+
info="Exclude markers above this missing data threshold"
|
| 803 |
+
)
|
| 804 |
+
maf_thresh = gr.Slider(
|
| 805 |
+
minimum=0, maximum=25, value=5, step=1,
|
| 806 |
+
label="Minor Allele Frequency filter (%)",
|
| 807 |
+
info="Exclude markers below this MAF"
|
| 808 |
+
)
|
| 809 |
+
gr.Markdown("### π¬ Optional GWAS Models")
|
| 810 |
+
include_mlm = gr.Checkbox(label="Mixed Linear Model (MLM) β slower", value=False)
|
| 811 |
+
include_enet = gr.Checkbox(label="ElasticNet Regression", value=True)
|
| 812 |
+
include_rf = gr.Checkbox(label="Random Forest β slowest", value=True)
|
| 813 |
+
include_gb = gr.Checkbox(label="Gradient Boosting", value=False)
|
| 814 |
+
|
| 815 |
+
run_button = gr.Button("π Run MTA Analysis", variant="primary", size="lg")
|
| 816 |
+
|
| 817 |
+
with gr.Row():
|
| 818 |
+
with gr.Column():
|
| 819 |
gr.Markdown("### π Analysis Summary")
|
| 820 |
summary_output = gr.Markdown()
|
| 821 |
+
|
| 822 |
with gr.Row():
|
| 823 |
with gr.Column():
|
| 824 |
+
gr.Markdown("### πΊοΈ Manhattan Plot with LOD Scores")
|
| 825 |
manhattan_output = gr.Image(label="Genome-Wide Association")
|
| 826 |
+
|
| 827 |
with gr.Row():
|
| 828 |
with gr.Column():
|
| 829 |
+
gr.Markdown("### π LD Decay Analysis")
|
| 830 |
+
ld_output = gr.Image(label="Linkage Disequilibrium")
|
|
|
|
| 831 |
with gr.Column():
|
| 832 |
+
gr.Markdown("### π¬ Model Comparison")
|
| 833 |
+
comparison_output = gr.Image(label="Model Performance")
|
| 834 |
+
|
| 835 |
with gr.Row():
|
| 836 |
+
with gr.Column():
|
| 837 |
+
gr.Markdown("### πΎ Download Complete Results (ZIP)")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 838 |
download_output = gr.File(label="Download Results Package")
|
| 839 |
+
|
| 840 |
gr.Markdown("""
|
| 841 |
---
|
| 842 |
+
**Created by Ashmi** | Enhanced MTA Analysis Tool v7.0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 843 |
""")
|
| 844 |
+
|
| 845 |
+
# ββ The critical fix: fn matches the defined function name ββββββββββ
|
| 846 |
run_button.click(
|
| 847 |
fn=run_mta_analysis,
|
| 848 |
+
inputs=[
|
| 849 |
+
input_file, target_markers,
|
| 850 |
+
miss_rate_sample, miss_rate_marker, maf_thresh,
|
| 851 |
+
include_mlm, include_enet, include_rf, include_gb
|
| 852 |
+
],
|
| 853 |
+
outputs=[summary_output, manhattan_output, ld_output, comparison_output, download_output]
|
| 854 |
)
|
| 855 |
|
|
|
|
| 856 |
if __name__ == "__main__":
|
| 857 |
+
app.launch(share=False, show_error=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|