Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,6 +1,6 @@
|
|
| 1 |
# -*- coding: utf-8 -*-
|
| 2 |
"""
|
| 3 |
-
MTA Analysis Tool v7.
|
| 4 |
SPEED OPTIMIZATIONS:
|
| 5 |
- Removed Mixed Linear Model (slowest β statsmodels per-marker)
|
| 6 |
- Removed Random Forest & Gradient Boosting (100x slower)
|
|
@@ -11,6 +11,14 @@ SPEED OPTIMIZATIONS:
|
|
| 11 |
- Reduced bootstrap iterations
|
| 12 |
- Fixed output ID generation
|
| 13 |
~10-15x FASTER than v7.1
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
"""
|
| 15 |
|
| 16 |
import gradio as gr
|
|
@@ -21,6 +29,7 @@ matplotlib.use('Agg')
|
|
| 21 |
import matplotlib.pyplot as plt
|
| 22 |
from scipy import stats
|
| 23 |
from scipy.optimize import curve_fit
|
|
|
|
| 24 |
import os, warnings, tempfile, zipfile
|
| 25 |
from sklearn.linear_model import ElasticNetCV
|
| 26 |
from sklearn.preprocessing import StandardScaler
|
|
@@ -45,6 +54,7 @@ CHROM_PALETTE = [
|
|
| 45 |
"#C4B5FD","#FBCFE8","#86EFAC","#BAE6FD","#FDE68A",
|
| 46 |
"#DDD6FE","#FDE8F4","#A7F3D0","#E0F2FE","#FEF3C7",
|
| 47 |
"#8B5CF6","#EC4899","#10B981","#0EA5E9","#F59E0B",
|
|
|
|
| 48 |
]
|
| 49 |
|
| 50 |
def set_pastel_style():
|
|
@@ -100,10 +110,10 @@ def plot_manhattan_with_lod(marker_names, chromosomes, p_values, lod_scores,
|
|
| 100 |
ax2.axvspan(x_pos[idxs[0]] - 0.5, x_pos[idxs[-1]] + 0.5,
|
| 101 |
color='#EDE9FE', alpha=0.45, zorder=0)
|
| 102 |
|
| 103 |
-
col
|
| 104 |
normal = [i for i in idxs if i not in sig_set]
|
| 105 |
sel = [i for i in idxs if i in sig_set]
|
| 106 |
-
|
| 107 |
if normal:
|
| 108 |
ax1.scatter(x_pos[normal], log_p[normal],
|
| 109 |
c=col, s=10, alpha=0.65, linewidths=0, zorder=2)
|
|
@@ -149,7 +159,7 @@ def plot_manhattan_with_lod(marker_names, chromosomes, p_values, lod_scores,
|
|
| 149 |
|
| 150 |
|
| 151 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 152 |
-
#
|
| 153 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 154 |
|
| 155 |
def _compute_ld_vectorised(G, pos_arr, max_lag=40):
|
|
@@ -195,13 +205,27 @@ def _compute_ld_vectorised(G, pos_arr, max_lag=40):
|
|
| 195 |
np.concatenate(all_dp))
|
| 196 |
|
| 197 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 198 |
def plot_enhanced_ld_decay(genotypes, chromosomes, positions, save_path, max_m=100):
|
| 199 |
-
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 200 |
set_pastel_style()
|
|
|
|
| 201 |
unique_chroms = sorted(set(chromosomes),
|
| 202 |
key=lambda x: (int(x) if str(x).isdigit() else 999, str(x)))
|
| 203 |
|
| 204 |
-
|
|
|
|
| 205 |
chrom_stats = {}
|
| 206 |
|
| 207 |
for ch in unique_chroms:
|
|
@@ -218,114 +242,142 @@ def plot_enhanced_ld_decay(genotypes, chromosomes, positions, save_path, max_m=1
|
|
| 218 |
if len(dist) == 0:
|
| 219 |
continue
|
| 220 |
|
| 221 |
-
|
| 222 |
all_r2.extend(r2.tolist())
|
| 223 |
-
|
| 224 |
|
| 225 |
chrom_stats[ch] = {
|
| 226 |
'mean_r2': float(np.mean(r2)),
|
| 227 |
'mean_dprime': float(np.mean(dp)),
|
| 228 |
}
|
| 229 |
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
return
|
| 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 |
-
|
| 268 |
-
|
| 269 |
-
pass
|
| 270 |
-
|
| 271 |
-
ax.errorbar(ctrs, means, yerr=errs,
|
| 272 |
-
fmt='o-', color=ACCENT, capsize=3, capthick=1,
|
| 273 |
-
markersize=4, linewidth=1.5, alpha=0.8)
|
| 274 |
-
ax.axhline(0.2, color=RED_C, ls='--', lw=1.2, alpha=0.8, label='rΒ²=0.2')
|
| 275 |
-
|
| 276 |
-
half_idx = np.where(means <= means[0] / 2)[0]
|
| 277 |
-
if len(half_idx) > 0:
|
| 278 |
-
ax.axvline(ctrs[half_idx[0]], color=GOLD_C, ls='--', lw=1.2,
|
| 279 |
-
label=f'Β½-decay β {ctrs[half_idx[0]]:.1f}')
|
| 280 |
-
|
| 281 |
-
ax.set_xlabel('Distance (kb)', fontsize=10, fontweight='bold')
|
| 282 |
-
ax.set_ylabel('Mean rΒ²', fontsize=10, fontweight='bold')
|
| 283 |
-
ax.set_title('LD Decay (rΒ²)', fontsize=12, fontweight='bold')
|
| 284 |
-
ax.set_ylim(0, 1)
|
| 285 |
-
ax.legend(fontsize=8)
|
| 286 |
-
ax.grid(True, color=GRID_C, lw=0.7)
|
| 287 |
-
|
| 288 |
-
# Panel 2: D' decay
|
| 289 |
-
ax = axes[1]
|
| 290 |
-
ax.set_facecolor(PANEL)
|
| 291 |
-
|
| 292 |
-
if all_distances:
|
| 293 |
-
ctrs_dp, means_dp, errs_dp = _bin_stats(distances, dp_arr, bins)
|
| 294 |
-
if len(means_dp) > 0:
|
| 295 |
-
ax.errorbar(ctrs_dp, means_dp, yerr=errs_dp,
|
| 296 |
-
fmt='o-', color=TEAL_C, capsize=3, capthick=1,
|
| 297 |
-
markersize=4, linewidth=1.5, alpha=0.8)
|
| 298 |
-
ax.axhline(0.5, color=RED_C, ls='--', lw=1.2, alpha=0.8, label="D'=0.5")
|
| 299 |
-
|
| 300 |
-
ax.set_xlabel('Distance (kb)', fontsize=10, fontweight='bold')
|
| 301 |
-
ax.set_ylabel("Mean D'", fontsize=10, fontweight='bold')
|
| 302 |
-
ax.set_title("LD Decay (D')", fontsize=12, fontweight='bold')
|
| 303 |
-
ax.set_ylim(0, 1)
|
| 304 |
-
ax.legend(fontsize=8)
|
| 305 |
-
ax.grid(True, color=GRID_C, lw=0.7)
|
| 306 |
-
|
| 307 |
-
# Panel 3: per-chromosome bar
|
| 308 |
-
ax = axes[2]
|
| 309 |
-
ax.set_facecolor(PANEL)
|
| 310 |
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 326 |
|
| 327 |
-
plt.tight_layout(pad=1.
|
| 328 |
-
plt.savefig(save_path, dpi=
|
| 329 |
plt.close(fig)
|
| 330 |
|
| 331 |
return chrom_stats
|
|
@@ -343,35 +395,36 @@ def plot_model_comparison(results_df, save_path):
|
|
| 343 |
# P-value correlation
|
| 344 |
ax = axes[0]
|
| 345 |
ax.set_facecolor(PANEL)
|
| 346 |
-
|
| 347 |
avail = ['LR_P', 'EN_P']
|
| 348 |
avail = [c for c in avail if c in results_df.columns]
|
| 349 |
-
|
| 350 |
if len(avail) >= 2:
|
| 351 |
corr = results_df[avail[0]].corr(results_df[avail[1]])
|
| 352 |
ax.scatter(results_df[avail[0]], results_df[avail[1]],
|
| 353 |
alpha=0.5, s=20, color=ACCENT, edgecolors='white', linewidth=0.5)
|
| 354 |
ax.text(0.05, 0.95, f'r = {corr:.3f}', transform=ax.transAxes,
|
| 355 |
-
fontsize=11, fontweight='bold', va='top',
|
| 356 |
-
facecolor=PANEL, alpha=0.8))
|
| 357 |
-
|
| 358 |
ax.set_xlabel('Linear Regression P-value', fontsize=10, fontweight='bold')
|
| 359 |
ax.set_ylabel('ElasticNet P-value', fontsize=10, fontweight='bold')
|
| 360 |
ax.set_title('Model P-value Correlation', fontsize=11, fontweight='bold')
|
| 361 |
-
ax.set_xscale('log')
|
|
|
|
| 362 |
ax.grid(True, color=GRID_C, lw=0.7, alpha=0.5)
|
| 363 |
|
| 364 |
# Effect size histogram
|
| 365 |
ax = axes[1]
|
| 366 |
ax.set_facecolor(PANEL)
|
| 367 |
-
|
| 368 |
if 'LR_Beta' in results_df.columns:
|
| 369 |
ax.hist(results_df['LR_Beta'].dropna(), bins=40, alpha=0.6,
|
| 370 |
label='Linear Reg', color=ACCENT, edgecolor='white')
|
| 371 |
if 'EN_Beta' in results_df.columns:
|
| 372 |
ax.hist(results_df['EN_Beta'].dropna(), bins=40, alpha=0.6,
|
| 373 |
label='ElasticNet', color=TEAL_C, edgecolor='white')
|
| 374 |
-
|
| 375 |
ax.set_xlabel('Effect Size', fontsize=10, fontweight='bold')
|
| 376 |
ax.set_ylabel('Frequency', fontsize=10, fontweight='bold')
|
| 377 |
ax.set_title('Effect Size Distribution', fontsize=11, fontweight='bold')
|
|
@@ -429,8 +482,8 @@ def elasticnet_gwas(genotypes, phenotypes, n_bootstrap=15):
|
|
| 429 |
for i in range(len(coef)):
|
| 430 |
sd = boot_arr[:, i].std()
|
| 431 |
if sd > 0:
|
| 432 |
-
z
|
| 433 |
-
pvals[i]
|
| 434 |
return pvals, coef
|
| 435 |
|
| 436 |
|
|
@@ -548,58 +601,55 @@ def run_mta_analysis(input_file, miss_rate_sample, miss_rate_marker, maf_thresh)
|
|
| 548 |
if mask.any():
|
| 549 |
geno_qc[mask, i] = col_means[i]
|
| 550 |
|
| 551 |
-
valid
|
| 552 |
geno_qc = geno_qc[valid]
|
| 553 |
pheno_qc = pheno_qc[valid]
|
| 554 |
ids_qc = ids_qc[valid]
|
| 555 |
|
| 556 |
if len(ids_qc) < 10:
|
| 557 |
-
worst = np.sort(np.isnan(genotypes).sum(axis=1) /
|
| 558 |
-
max(n_markers, 1) * 100)[::-1][:5]
|
| 559 |
return (
|
| 560 |
f"## β οΈ Insufficient Samples\nOnly **{len(ids_qc)}** samples "
|
| 561 |
f"passed QC (started with {n_samples}).\n\n"
|
| 562 |
f"Try increasing **Sample Missing Rate** slider to 50β80%.",
|
| 563 |
-
None, None, None
|
| 564 |
)
|
| 565 |
|
| 566 |
n_qc = len(mnames_qc)
|
| 567 |
bonf = 0.05 / n_qc
|
| 568 |
|
| 569 |
-
# ββ Run Models βββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 570 |
print("[1/2] Linear Regressionβ¦")
|
| 571 |
lr_pvals, lr_effects, lr_se, lr_r2 = linear_regression_gwas(geno_qc, pheno_qc)
|
| 572 |
|
| 573 |
print("[2/2] ElasticNetβ¦")
|
| 574 |
enet_pvals, enet_coef = elasticnet_gwas(geno_qc, pheno_qc)
|
| 575 |
|
| 576 |
-
# ββ Results DataFrame βββββββββββββββββββββββββββββββββββββββββββ
|
| 577 |
gwas_df = pd.DataFrame({
|
| 578 |
-
'Rank':
|
| 579 |
-
'Marker':
|
| 580 |
-
'Chromosome':
|
| 581 |
-
'Position':
|
| 582 |
-
'LR_P':
|
| 583 |
-
'LR_Beta':
|
| 584 |
-
'LR_LOD':
|
| 585 |
-
'Significant_LR':
|
| 586 |
-
'EN_P':
|
| 587 |
-
'EN_Beta':
|
| 588 |
-
'Significant_EN':
|
| 589 |
})
|
| 590 |
|
| 591 |
-
# Consensus
|
| 592 |
gwas_df['Consensus_Sig'] = (
|
| 593 |
(gwas_df[['Significant_LR', 'Significant_EN']].sum(axis=1) >= 2).astype(int)
|
| 594 |
)
|
| 595 |
|
| 596 |
gwas_df = gwas_df.sort_values('LR_P').reset_index(drop=True)
|
| 597 |
gwas_df['Rank'] = range(1, len(gwas_df) + 1)
|
| 598 |
-
|
| 599 |
print("[Save] Writing results CSVβ¦")
|
| 600 |
gwas_df.to_csv(os.path.join(results_dir, 'gwas_results.csv'), index=False)
|
| 601 |
|
| 602 |
-
# ββ Plots βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 603 |
print("[Plots] Generating Manhattan plotβ¦")
|
| 604 |
bonf_log = -np.log10(bonf)
|
| 605 |
sig_set = set(np.where(lr_pvals < bonf)[0])
|
|
@@ -609,15 +659,15 @@ def run_mta_analysis(input_file, miss_rate_sample, miss_rate_marker, maf_thresh)
|
|
| 609 |
-np.log10(lr_pvals + 1e-300),
|
| 610 |
sig_set, bonf_log, man_path)
|
| 611 |
|
| 612 |
-
print("[Plots] Generating LD decayβ¦")
|
| 613 |
ld_path = os.path.join(plots_dir, 'ld_decay.png')
|
| 614 |
ld_stats = plot_enhanced_ld_decay(geno_qc, chrom_qc, pos_qc, ld_path)
|
| 615 |
|
| 616 |
-
print("[Plots] Generating comparisonβ¦")
|
| 617 |
comp_path = os.path.join(plots_dir, 'model_comparison.png')
|
| 618 |
plot_model_comparison(gwas_df, comp_path)
|
| 619 |
|
| 620 |
-
# ββ ZIP ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 621 |
print("[ZIP] Creating downloadβ¦")
|
| 622 |
zip_path = os.path.join(temp_dir, 'GWAS_Results.zip')
|
| 623 |
with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf:
|
|
@@ -626,7 +676,7 @@ def run_mta_analysis(input_file, miss_rate_sample, miss_rate_marker, maf_thresh)
|
|
| 626 |
fp = os.path.join(root, f)
|
| 627 |
zf.write(fp, os.path.relpath(fp, temp_dir))
|
| 628 |
|
| 629 |
-
# ββ Summary ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 630 |
ld_r2_mean = np.mean([v['mean_r2'] for v in ld_stats.values()]) if ld_stats else 0
|
| 631 |
ld_dp_mean = np.mean([v['mean_dprime'] for v in ld_stats.values()]) if ld_stats else 0
|
| 632 |
|
|
@@ -634,7 +684,6 @@ def run_mta_analysis(input_file, miss_rate_sample, miss_rate_marker, maf_thresh)
|
|
| 634 |
top10_cols = [c for c in top10_cols if c in gwas_df.columns]
|
| 635 |
|
| 636 |
def _df_to_md(df):
|
| 637 |
-
"""Convert DataFrame to markdown table."""
|
| 638 |
cols = df.columns.tolist()
|
| 639 |
def _fmt(v):
|
| 640 |
if isinstance(v, float):
|
|
@@ -647,7 +696,7 @@ def run_mta_analysis(input_file, miss_rate_sample, miss_rate_marker, maf_thresh)
|
|
| 647 |
return "\n".join([header, sep] + rows)
|
| 648 |
|
| 649 |
summary = f"""
|
| 650 |
-
## β
GWAS Analysis Complete (v7.
|
| 651 |
|
| 652 |
### π QC Summary
|
| 653 |
| Metric | Value |
|
|
@@ -674,10 +723,10 @@ def run_mta_analysis(input_file, miss_rate_sample, miss_rate_marker, maf_thresh)
|
|
| 674 |
|
| 675 |
---
|
| 676 |
**Files generated:**
|
| 677 |
-
- `gwas_results.csv`
|
| 678 |
-
- `manhattan_lod.png`
|
| 679 |
-
- `ld_decay.png`
|
| 680 |
-
- `model_comparison.png`
|
| 681 |
"""
|
| 682 |
print("[Done] Analysis complete!")
|
| 683 |
return (summary, man_path, ld_path, comp_path, zip_path)
|
|
@@ -701,13 +750,13 @@ h1 { color: #2c3e50; border-bottom: 3px solid #8B5CF6; padding-bottom: 10px; }
|
|
| 701 |
.gr-button-primary { background: #8B5CF6 !important; }
|
| 702 |
"""
|
| 703 |
|
| 704 |
-
with gr.Blocks(css=custom_css, title="MTA GWAS v7.
|
| 705 |
|
| 706 |
gr.Markdown("""
|
| 707 |
-
# 𧬠Optimized GWAS Analysis v7.
|
| 708 |
### Fast Multi-Model Genomic Discovery
|
| 709 |
-
**~10x faster** | Linear Regression + ElasticNet |
|
| 710 |
-
|
| 711 |
---
|
| 712 |
""")
|
| 713 |
|
|
@@ -734,7 +783,12 @@ with gr.Blocks(css=custom_css, title="MTA GWAS v7.2") as app:
|
|
| 734 |
maf_thresh = gr.Slider(0, 25, value=3, step=1,
|
| 735 |
label="Min MAF (%)")
|
| 736 |
|
| 737 |
-
gr.Markdown("
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 738 |
|
| 739 |
run_button = gr.Button("π Run Analysis", variant="primary", size="lg")
|
| 740 |
|
|
@@ -747,7 +801,7 @@ with gr.Blocks(css=custom_css, title="MTA GWAS v7.2") as app:
|
|
| 747 |
with gr.Column():
|
| 748 |
manhattan_output = gr.Image(label="Manhattan + LOD")
|
| 749 |
with gr.Column():
|
| 750 |
-
ld_output = gr.Image(label="LD Decay")
|
| 751 |
|
| 752 |
with gr.Row():
|
| 753 |
comparison_output = gr.Image(label="Model Comparison")
|
|
@@ -757,14 +811,14 @@ with gr.Blocks(css=custom_css, title="MTA GWAS v7.2") as app:
|
|
| 757 |
|
| 758 |
gr.Markdown("""
|
| 759 |
---
|
| 760 |
-
**MTA GWAS v7.
|
| 761 |
""")
|
| 762 |
|
| 763 |
run_button.click(
|
| 764 |
fn=run_mta_analysis,
|
| 765 |
inputs=[input_file, miss_rate_sample, miss_rate_marker, maf_thresh],
|
| 766 |
-
outputs=[summary_output, manhattan_output, ld_output,
|
| 767 |
-
|
| 768 |
show_progress=True
|
| 769 |
)
|
| 770 |
|
|
|
|
| 1 |
# -*- coding: utf-8 -*-
|
| 2 |
"""
|
| 3 |
+
MTA Analysis Tool v7.3 - Optimized GWAS Platform
|
| 4 |
SPEED OPTIMIZATIONS:
|
| 5 |
- Removed Mixed Linear Model (slowest β statsmodels per-marker)
|
| 6 |
- Removed Random Forest & Gradient Boosting (100x slower)
|
|
|
|
| 11 |
- Reduced bootstrap iterations
|
| 12 |
- Fixed output ID generation
|
| 13 |
~10-15x FASTER than v7.1
|
| 14 |
+
|
| 15 |
+
LD DECAY PLOT (v7.3):
|
| 16 |
+
- Replaced 3-panel LD plot with a single scatter-style LD decay
|
| 17 |
+
- Individual marker-pair dots coloured by chromosome
|
| 18 |
+
- Green filled smooth median decay curve (cubic spline)
|
| 19 |
+
- Dashed rΒ²=0.2 reference line
|
| 20 |
+
- Chromosome legend on the right
|
| 21 |
+
- Matches classic LD decay scatter style (rΒ² vs genetic distance in cM)
|
| 22 |
"""
|
| 23 |
|
| 24 |
import gradio as gr
|
|
|
|
| 29 |
import matplotlib.pyplot as plt
|
| 30 |
from scipy import stats
|
| 31 |
from scipy.optimize import curve_fit
|
| 32 |
+
from scipy.interpolate import make_interp_spline
|
| 33 |
import os, warnings, tempfile, zipfile
|
| 34 |
from sklearn.linear_model import ElasticNetCV
|
| 35 |
from sklearn.preprocessing import StandardScaler
|
|
|
|
| 54 |
"#C4B5FD","#FBCFE8","#86EFAC","#BAE6FD","#FDE68A",
|
| 55 |
"#DDD6FE","#FDE8F4","#A7F3D0","#E0F2FE","#FEF3C7",
|
| 56 |
"#8B5CF6","#EC4899","#10B981","#0EA5E9","#F59E0B",
|
| 57 |
+
"#6366F1","#EF4444","#14B8A6","#F97316","#84CC16",
|
| 58 |
]
|
| 59 |
|
| 60 |
def set_pastel_style():
|
|
|
|
| 110 |
ax2.axvspan(x_pos[idxs[0]] - 0.5, x_pos[idxs[-1]] + 0.5,
|
| 111 |
color='#EDE9FE', alpha=0.45, zorder=0)
|
| 112 |
|
| 113 |
+
col = CHROM_PALETTE[ci % len(CHROM_PALETTE)]
|
| 114 |
normal = [i for i in idxs if i not in sig_set]
|
| 115 |
sel = [i for i in idxs if i in sig_set]
|
| 116 |
+
|
| 117 |
if normal:
|
| 118 |
ax1.scatter(x_pos[normal], log_p[normal],
|
| 119 |
c=col, s=10, alpha=0.65, linewidths=0, zorder=2)
|
|
|
|
| 159 |
|
| 160 |
|
| 161 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 162 |
+
# LD COMPUTATION (vectorised)
|
| 163 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 164 |
|
| 165 |
def _compute_ld_vectorised(G, pos_arr, max_lag=40):
|
|
|
|
| 205 |
np.concatenate(all_dp))
|
| 206 |
|
| 207 |
|
| 208 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 209 |
+
# PLOT: LD DECAY β scatter style (v7.3)
|
| 210 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 211 |
+
|
| 212 |
def plot_enhanced_ld_decay(genotypes, chromosomes, positions, save_path, max_m=100):
|
| 213 |
+
"""
|
| 214 |
+
LD decay scatter plot β chromosome-coloured dots with smooth median decay
|
| 215 |
+
curve and filled area, styled after the classic rΒ² vs genetic distance plot.
|
| 216 |
+
|
| 217 |
+
- One scatter dot per marker pair, coloured by chromosome
|
| 218 |
+
- Green filled cubic-spline median decay curve
|
| 219 |
+
- Dashed rΒ²=0.2 reference line
|
| 220 |
+
- Chromosome legend (right side)
|
| 221 |
+
"""
|
| 222 |
set_pastel_style()
|
| 223 |
+
|
| 224 |
unique_chroms = sorted(set(chromosomes),
|
| 225 |
key=lambda x: (int(x) if str(x).isdigit() else 999, str(x)))
|
| 226 |
|
| 227 |
+
# ββ collect all pairwise (dist, rΒ², chrom) ββββββββββββββββββββββββββββββ
|
| 228 |
+
all_dist, all_r2, all_chrom_label = [], [], []
|
| 229 |
chrom_stats = {}
|
| 230 |
|
| 231 |
for ch in unique_chroms:
|
|
|
|
| 242 |
if len(dist) == 0:
|
| 243 |
continue
|
| 244 |
|
| 245 |
+
all_dist.extend(dist.tolist())
|
| 246 |
all_r2.extend(r2.tolist())
|
| 247 |
+
all_chrom_label.extend([str(ch)] * len(dist))
|
| 248 |
|
| 249 |
chrom_stats[ch] = {
|
| 250 |
'mean_r2': float(np.mean(r2)),
|
| 251 |
'mean_dprime': float(np.mean(dp)),
|
| 252 |
}
|
| 253 |
|
| 254 |
+
# ββ handle empty data ββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 255 |
+
if not all_dist:
|
| 256 |
+
fig, ax = plt.subplots(figsize=(10, 6), facecolor=BG)
|
| 257 |
+
ax.set_facecolor(PANEL)
|
| 258 |
+
ax.text(0.5, 0.5, 'No LD data available', ha='center', va='center',
|
| 259 |
+
transform=ax.transAxes, fontsize=13, color=TEXT_C)
|
| 260 |
+
plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=BG)
|
| 261 |
+
plt.close(fig)
|
| 262 |
+
return chrom_stats
|
| 263 |
+
|
| 264 |
+
dist_arr = np.array(all_dist, dtype=float)
|
| 265 |
+
r2_arr = np.array(all_r2, dtype=float)
|
| 266 |
+
chr_arr = np.array(all_chrom_label, dtype=str)
|
| 267 |
+
|
| 268 |
+
# clip to 99th percentile of distance for a clean x-axis
|
| 269 |
+
max_dist = min(120.0, float(np.percentile(dist_arr, 99)))
|
| 270 |
+
|
| 271 |
+
# per-chromosome colour map
|
| 272 |
+
chrom_color = {str(ch): CHROM_PALETTE[i % len(CHROM_PALETTE)]
|
| 273 |
+
for i, ch in enumerate(unique_chroms)}
|
| 274 |
+
|
| 275 |
+
# ββ figure βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 276 |
+
fig, ax = plt.subplots(figsize=(11, 6.5), facecolor=BG)
|
| 277 |
+
ax.set_facecolor('#F5F0FF') # very light lavender β matches reference feel
|
| 278 |
+
|
| 279 |
+
# ββ scatter: one layer per chromosome so legend entries are clean ββββββββ
|
| 280 |
+
scatter_handles = []
|
| 281 |
+
for ch in unique_chroms:
|
| 282 |
+
key = str(ch)
|
| 283 |
+
mask = chr_arr == key
|
| 284 |
+
if not mask.any():
|
| 285 |
+
continue
|
| 286 |
+
sc = ax.scatter(
|
| 287 |
+
dist_arr[mask], r2_arr[mask],
|
| 288 |
+
c=chrom_color[key],
|
| 289 |
+
s=6, alpha=0.40, linewidths=0,
|
| 290 |
+
zorder=2, label=key,
|
| 291 |
+
)
|
| 292 |
+
scatter_handles.append(sc)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 293 |
|
| 294 |
+
# ββ smooth median decay curve ββββββββββββββββββββββββββββββββββββββββββββ
|
| 295 |
+
try:
|
| 296 |
+
n_bins = 50
|
| 297 |
+
bins = np.linspace(0, max_dist, n_bins + 1)
|
| 298 |
+
ctrs, medians = [], []
|
| 299 |
+
for i in range(n_bins):
|
| 300 |
+
m = (dist_arr >= bins[i]) & (dist_arr < bins[i + 1])
|
| 301 |
+
if m.sum() > 3:
|
| 302 |
+
ctrs.append((bins[i] + bins[i + 1]) / 2.0)
|
| 303 |
+
medians.append(np.median(r2_arr[m]))
|
| 304 |
+
|
| 305 |
+
ctrs = np.array(ctrs, dtype=float)
|
| 306 |
+
medians = np.array(medians, dtype=float)
|
| 307 |
+
|
| 308 |
+
if len(ctrs) >= 5:
|
| 309 |
+
x_smooth = np.linspace(ctrs[0], ctrs[-1], 400)
|
| 310 |
+
spl = make_interp_spline(ctrs, medians, k=3)
|
| 311 |
+
y_smooth = np.clip(spl(x_smooth), 0.0, 1.0)
|
| 312 |
+
|
| 313 |
+
# filled area under the curve
|
| 314 |
+
ax.fill_between(x_smooth, 0, y_smooth,
|
| 315 |
+
color='#22C55E', alpha=0.25, zorder=3)
|
| 316 |
+
# curve line
|
| 317 |
+
decay_line, = ax.plot(x_smooth, y_smooth,
|
| 318 |
+
color='#15803D', linewidth=2.2,
|
| 319 |
+
zorder=4, label='Median decay')
|
| 320 |
+
except Exception:
|
| 321 |
+
decay_line = None
|
| 322 |
+
|
| 323 |
+
# ββ rΒ² = 0.2 reference dashed line ββββββββββββββββββββββββββββββββββββββ
|
| 324 |
+
ref_line = ax.axhline(0.2, color='#1E293B', ls='--', lw=1.5,
|
| 325 |
+
alpha=0.75, zorder=5, label='rΒ² = 0.2')
|
| 326 |
+
|
| 327 |
+
# ββ axes formatting ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 328 |
+
ax.set_xlim(0, max_dist)
|
| 329 |
+
ax.set_ylim(0, 1.04)
|
| 330 |
+
|
| 331 |
+
ax.set_xlabel('Genetic distance (cM)', fontsize=12, fontweight='bold',
|
| 332 |
+
color=TEXT_C, labelpad=8)
|
| 333 |
+
ax.set_ylabel('LD estimate (RΒ²)', fontsize=12, fontweight='bold',
|
| 334 |
+
color=TEXT_C, labelpad=8)
|
| 335 |
+
ax.set_title('LD Decay by Chromosome', fontsize=14, fontweight='bold',
|
| 336 |
+
color=TEXT_C, pad=12)
|
| 337 |
+
|
| 338 |
+
ax.xaxis.grid(True, color=GRID_C, linewidth=0.6, alpha=0.8)
|
| 339 |
+
ax.yaxis.grid(True, color=GRID_C, linewidth=0.6, alpha=0.8)
|
| 340 |
+
ax.set_axisbelow(True)
|
| 341 |
+
|
| 342 |
+
# spine style
|
| 343 |
+
for spine in ax.spines.values():
|
| 344 |
+
spine.set_edgecolor(GRID_C)
|
| 345 |
+
spine.set_linewidth(1.0)
|
| 346 |
+
|
| 347 |
+
# ββ legend βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 348 |
+
handles, labels = ax.get_legend_handles_labels()
|
| 349 |
+
|
| 350 |
+
# separate special entries from chromosome entries
|
| 351 |
+
special_entries = [(h, l) for h, l in zip(handles, labels)
|
| 352 |
+
if l in ('Median decay', 'rΒ² = 0.2')]
|
| 353 |
+
chrom_entries = [(h, l) for h, l in zip(handles, labels)
|
| 354 |
+
if l not in ('Median decay', 'rΒ² = 0.2')]
|
| 355 |
+
|
| 356 |
+
# build final legend: special entries first, then chromosomes
|
| 357 |
+
leg_handles = [h for h, _ in special_entries] + [h for h, _ in chrom_entries]
|
| 358 |
+
leg_labels = [l for _, l in special_entries] + [f'Chr {l}' for _, l in chrom_entries]
|
| 359 |
+
|
| 360 |
+
n_chr_cols = max(1, (len(chrom_entries) + 11) // 12) # β€12 rows per col
|
| 361 |
+
|
| 362 |
+
legend = ax.legend(
|
| 363 |
+
leg_handles, leg_labels,
|
| 364 |
+
title='Chr',
|
| 365 |
+
title_fontsize=9,
|
| 366 |
+
fontsize=7.5,
|
| 367 |
+
loc='upper right',
|
| 368 |
+
ncol=n_chr_cols,
|
| 369 |
+
framealpha=0.93,
|
| 370 |
+
edgecolor=GRID_C,
|
| 371 |
+
markerscale=2.0,
|
| 372 |
+
handlelength=1.4,
|
| 373 |
+
borderpad=0.8,
|
| 374 |
+
labelspacing=0.45,
|
| 375 |
+
)
|
| 376 |
+
legend.get_title().set_fontweight('bold')
|
| 377 |
+
legend.get_title().set_color(TEXT_C)
|
| 378 |
|
| 379 |
+
plt.tight_layout(pad=1.8)
|
| 380 |
+
plt.savefig(save_path, dpi=130, bbox_inches='tight', facecolor=BG)
|
| 381 |
plt.close(fig)
|
| 382 |
|
| 383 |
return chrom_stats
|
|
|
|
| 395 |
# P-value correlation
|
| 396 |
ax = axes[0]
|
| 397 |
ax.set_facecolor(PANEL)
|
| 398 |
+
|
| 399 |
avail = ['LR_P', 'EN_P']
|
| 400 |
avail = [c for c in avail if c in results_df.columns]
|
| 401 |
+
|
| 402 |
if len(avail) >= 2:
|
| 403 |
corr = results_df[avail[0]].corr(results_df[avail[1]])
|
| 404 |
ax.scatter(results_df[avail[0]], results_df[avail[1]],
|
| 405 |
alpha=0.5, s=20, color=ACCENT, edgecolors='white', linewidth=0.5)
|
| 406 |
ax.text(0.05, 0.95, f'r = {corr:.3f}', transform=ax.transAxes,
|
| 407 |
+
fontsize=11, fontweight='bold', va='top',
|
| 408 |
+
bbox=dict(boxstyle='round', facecolor=PANEL, alpha=0.8))
|
| 409 |
+
|
| 410 |
ax.set_xlabel('Linear Regression P-value', fontsize=10, fontweight='bold')
|
| 411 |
ax.set_ylabel('ElasticNet P-value', fontsize=10, fontweight='bold')
|
| 412 |
ax.set_title('Model P-value Correlation', fontsize=11, fontweight='bold')
|
| 413 |
+
ax.set_xscale('log')
|
| 414 |
+
ax.set_yscale('log')
|
| 415 |
ax.grid(True, color=GRID_C, lw=0.7, alpha=0.5)
|
| 416 |
|
| 417 |
# Effect size histogram
|
| 418 |
ax = axes[1]
|
| 419 |
ax.set_facecolor(PANEL)
|
| 420 |
+
|
| 421 |
if 'LR_Beta' in results_df.columns:
|
| 422 |
ax.hist(results_df['LR_Beta'].dropna(), bins=40, alpha=0.6,
|
| 423 |
label='Linear Reg', color=ACCENT, edgecolor='white')
|
| 424 |
if 'EN_Beta' in results_df.columns:
|
| 425 |
ax.hist(results_df['EN_Beta'].dropna(), bins=40, alpha=0.6,
|
| 426 |
label='ElasticNet', color=TEAL_C, edgecolor='white')
|
| 427 |
+
|
| 428 |
ax.set_xlabel('Effect Size', fontsize=10, fontweight='bold')
|
| 429 |
ax.set_ylabel('Frequency', fontsize=10, fontweight='bold')
|
| 430 |
ax.set_title('Effect Size Distribution', fontsize=11, fontweight='bold')
|
|
|
|
| 482 |
for i in range(len(coef)):
|
| 483 |
sd = boot_arr[:, i].std()
|
| 484 |
if sd > 0:
|
| 485 |
+
z = abs(coef[i]) / (sd + 1e-10)
|
| 486 |
+
pvals[i] = 2 * (1 - stats.norm.cdf(z))
|
| 487 |
return pvals, coef
|
| 488 |
|
| 489 |
|
|
|
|
| 601 |
if mask.any():
|
| 602 |
geno_qc[mask, i] = col_means[i]
|
| 603 |
|
| 604 |
+
valid = ~np.isnan(pheno_qc)
|
| 605 |
geno_qc = geno_qc[valid]
|
| 606 |
pheno_qc = pheno_qc[valid]
|
| 607 |
ids_qc = ids_qc[valid]
|
| 608 |
|
| 609 |
if len(ids_qc) < 10:
|
|
|
|
|
|
|
| 610 |
return (
|
| 611 |
f"## β οΈ Insufficient Samples\nOnly **{len(ids_qc)}** samples "
|
| 612 |
f"passed QC (started with {n_samples}).\n\n"
|
| 613 |
f"Try increasing **Sample Missing Rate** slider to 50β80%.",
|
| 614 |
+
None, None, None, None
|
| 615 |
)
|
| 616 |
|
| 617 |
n_qc = len(mnames_qc)
|
| 618 |
bonf = 0.05 / n_qc
|
| 619 |
|
| 620 |
+
# ββ Run Models ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 621 |
print("[1/2] Linear Regressionβ¦")
|
| 622 |
lr_pvals, lr_effects, lr_se, lr_r2 = linear_regression_gwas(geno_qc, pheno_qc)
|
| 623 |
|
| 624 |
print("[2/2] ElasticNetβ¦")
|
| 625 |
enet_pvals, enet_coef = elasticnet_gwas(geno_qc, pheno_qc)
|
| 626 |
|
| 627 |
+
# ββ Results DataFrame βββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 628 |
gwas_df = pd.DataFrame({
|
| 629 |
+
'Rank': 0,
|
| 630 |
+
'Marker': mnames_qc,
|
| 631 |
+
'Chromosome': chrom_qc,
|
| 632 |
+
'Position': pos_qc,
|
| 633 |
+
'LR_P': lr_pvals,
|
| 634 |
+
'LR_Beta': lr_effects,
|
| 635 |
+
'LR_LOD': -np.log10(lr_pvals + 1e-300),
|
| 636 |
+
'Significant_LR': (lr_pvals < bonf).astype(int),
|
| 637 |
+
'EN_P': enet_pvals,
|
| 638 |
+
'EN_Beta': enet_coef,
|
| 639 |
+
'Significant_EN': (enet_pvals < bonf).astype(int),
|
| 640 |
})
|
| 641 |
|
|
|
|
| 642 |
gwas_df['Consensus_Sig'] = (
|
| 643 |
(gwas_df[['Significant_LR', 'Significant_EN']].sum(axis=1) >= 2).astype(int)
|
| 644 |
)
|
| 645 |
|
| 646 |
gwas_df = gwas_df.sort_values('LR_P').reset_index(drop=True)
|
| 647 |
gwas_df['Rank'] = range(1, len(gwas_df) + 1)
|
| 648 |
+
|
| 649 |
print("[Save] Writing results CSVβ¦")
|
| 650 |
gwas_df.to_csv(os.path.join(results_dir, 'gwas_results.csv'), index=False)
|
| 651 |
|
| 652 |
+
# ββ Plots βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 653 |
print("[Plots] Generating Manhattan plotβ¦")
|
| 654 |
bonf_log = -np.log10(bonf)
|
| 655 |
sig_set = set(np.where(lr_pvals < bonf)[0])
|
|
|
|
| 659 |
-np.log10(lr_pvals + 1e-300),
|
| 660 |
sig_set, bonf_log, man_path)
|
| 661 |
|
| 662 |
+
print("[Plots] Generating LD decay (scatter style)β¦")
|
| 663 |
ld_path = os.path.join(plots_dir, 'ld_decay.png')
|
| 664 |
ld_stats = plot_enhanced_ld_decay(geno_qc, chrom_qc, pos_qc, ld_path)
|
| 665 |
|
| 666 |
+
print("[Plots] Generating model comparisonβ¦")
|
| 667 |
comp_path = os.path.join(plots_dir, 'model_comparison.png')
|
| 668 |
plot_model_comparison(gwas_df, comp_path)
|
| 669 |
|
| 670 |
+
# ββ ZIP βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 671 |
print("[ZIP] Creating downloadβ¦")
|
| 672 |
zip_path = os.path.join(temp_dir, 'GWAS_Results.zip')
|
| 673 |
with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf:
|
|
|
|
| 676 |
fp = os.path.join(root, f)
|
| 677 |
zf.write(fp, os.path.relpath(fp, temp_dir))
|
| 678 |
|
| 679 |
+
# ββ Summary βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 680 |
ld_r2_mean = np.mean([v['mean_r2'] for v in ld_stats.values()]) if ld_stats else 0
|
| 681 |
ld_dp_mean = np.mean([v['mean_dprime'] for v in ld_stats.values()]) if ld_stats else 0
|
| 682 |
|
|
|
|
| 684 |
top10_cols = [c for c in top10_cols if c in gwas_df.columns]
|
| 685 |
|
| 686 |
def _df_to_md(df):
|
|
|
|
| 687 |
cols = df.columns.tolist()
|
| 688 |
def _fmt(v):
|
| 689 |
if isinstance(v, float):
|
|
|
|
| 696 |
return "\n".join([header, sep] + rows)
|
| 697 |
|
| 698 |
summary = f"""
|
| 699 |
+
## β
GWAS Analysis Complete (v7.3 β Fast + Scatter LD)
|
| 700 |
|
| 701 |
### π QC Summary
|
| 702 |
| Metric | Value |
|
|
|
|
| 723 |
|
| 724 |
---
|
| 725 |
**Files generated:**
|
| 726 |
+
- `gwas_results.csv` β Complete results
|
| 727 |
+
- `manhattan_lod.png` β Manhattan + LOD plot
|
| 728 |
+
- `ld_decay.png` β LD decay scatter (chromosome-coloured)
|
| 729 |
+
- `model_comparison.png` β Model comparison
|
| 730 |
"""
|
| 731 |
print("[Done] Analysis complete!")
|
| 732 |
return (summary, man_path, ld_path, comp_path, zip_path)
|
|
|
|
| 750 |
.gr-button-primary { background: #8B5CF6 !important; }
|
| 751 |
"""
|
| 752 |
|
| 753 |
+
with gr.Blocks(css=custom_css, title="MTA GWAS v7.3") as app:
|
| 754 |
|
| 755 |
gr.Markdown("""
|
| 756 |
+
# 𧬠Optimized GWAS Analysis v7.3
|
| 757 |
### Fast Multi-Model Genomic Discovery
|
| 758 |
+
**~10x faster** | Linear Regression + ElasticNet | Scatter LD Decay Plot
|
| 759 |
+
|
| 760 |
---
|
| 761 |
""")
|
| 762 |
|
|
|
|
| 783 |
maf_thresh = gr.Slider(0, 25, value=3, step=1,
|
| 784 |
label="Min MAF (%)")
|
| 785 |
|
| 786 |
+
gr.Markdown("""
|
| 787 |
+
### β‘ v7.3 Updates
|
| 788 |
+
- Scatter LD decay: dots coloured by chromosome
|
| 789 |
+
- Green filled median decay curve
|
| 790 |
+
- rΒ² = 0.2 dashed reference line
|
| 791 |
+
""")
|
| 792 |
|
| 793 |
run_button = gr.Button("π Run Analysis", variant="primary", size="lg")
|
| 794 |
|
|
|
|
| 801 |
with gr.Column():
|
| 802 |
manhattan_output = gr.Image(label="Manhattan + LOD")
|
| 803 |
with gr.Column():
|
| 804 |
+
ld_output = gr.Image(label="LD Decay (Scatter by Chromosome)")
|
| 805 |
|
| 806 |
with gr.Row():
|
| 807 |
comparison_output = gr.Image(label="Model Comparison")
|
|
|
|
| 811 |
|
| 812 |
gr.Markdown("""
|
| 813 |
---
|
| 814 |
+
**MTA GWAS v7.3** | Optimised for speed | Scatter LD Decay | Linear Reg + ElasticNet
|
| 815 |
""")
|
| 816 |
|
| 817 |
run_button.click(
|
| 818 |
fn=run_mta_analysis,
|
| 819 |
inputs=[input_file, miss_rate_sample, miss_rate_marker, maf_thresh],
|
| 820 |
+
outputs=[summary_output, manhattan_output, ld_output,
|
| 821 |
+
comparison_output, download_output],
|
| 822 |
show_progress=True
|
| 823 |
)
|
| 824 |
|