Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,6 +1,6 @@
|
|
| 1 |
# -*- coding: utf-8 -*-
|
| 2 |
"""
|
| 3 |
-
MTA Analysis Tool v8.
|
| 4 |
β
Persistent output directory (no tempfile cleanup race)
|
| 5 |
β
BSLMM: n_boot reduced + Ridge fallback for speed
|
| 6 |
β
FarmCPU: vectorised inner loop
|
|
@@ -268,37 +268,51 @@ def model_bslmm(G, y, n_boot=8): # β was 20, now 8
|
|
| 268 |
# MODEL 5: FarmCPU β FIXED: vectorised scan
|
| 269 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 270 |
def model_farmcpu(G, y, K, max_iter=3):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 271 |
n, m = G.shape
|
| 272 |
pv_cur, bv, sv, rv = model_glm(G, y)
|
| 273 |
|
| 274 |
for iteration in range(max_iter):
|
| 275 |
n_qtns = max(1, min(10, int(m * 0.001)))
|
| 276 |
top_idx = np.argsort(pv_cur)[:n_qtns]
|
| 277 |
-
covs = G[:, top_idx]
|
| 278 |
|
|
|
|
| 279 |
try:
|
| 280 |
-
coef_c, _, _, _ = np.linalg.lstsq(
|
| 281 |
-
|
|
|
|
| 282 |
except Exception:
|
| 283 |
y_cond = y.copy()
|
| 284 |
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
try:
|
| 288 |
-
CtC_inv = np.linalg.pinv(covs.T @ covs)
|
| 289 |
-
proj = covs @ CtC_inv @ covs.T # nΓn projector
|
| 290 |
-
G_res = G - proj @ G # nΓm (residualised)
|
| 291 |
-
except Exception:
|
| 292 |
-
G_res = G.copy()
|
| 293 |
|
| 294 |
-
# scan residualised markers against y_cond
|
| 295 |
pv_new = np.ones(m); bv_new = np.zeros(m); sv_new = np.zeros(m)
|
| 296 |
for i in range(m):
|
| 297 |
-
x =
|
| 298 |
if x.std() < 1e-9: continue
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 302 |
|
| 303 |
pv_cur = pv_new.copy()
|
| 304 |
|
|
@@ -308,8 +322,59 @@ def model_farmcpu(G, y, K, max_iter=3):
|
|
| 308 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 309 |
# PLOT: MANHATTAN
|
| 310 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 311 |
def plot_manhattan_multi(mn, chroms, model_pvals, bonf_thresh, save_path):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 312 |
_style()
|
|
|
|
|
|
|
| 313 |
unique_chroms = sorted(set(chroms),
|
| 314 |
key=lambda x: (int(x) if str(x).isdigit() else 999, str(x)))
|
| 315 |
n_models = len(model_pvals)
|
|
@@ -329,56 +394,57 @@ def plot_manhattan_multi(mn, chroms, model_pvals, bonf_thresh, save_path):
|
|
| 329 |
chrom_xticks.append((offset + len(idxs)/2, str(ch)))
|
| 330 |
offset += len(idxs) + GAP
|
| 331 |
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 337 |
|
| 338 |
bonf_log = -np.log10(bonf_thresh)
|
| 339 |
-
|
| 340 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 341 |
sig_set = set(np.where(pv < bonf_thresh)[0])
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
label=f'Bonferroni ({bonf_log:.1f})')
|
| 362 |
-
ax.axhline(3.0, color=GOLD_C, ls=':', lw=1.4, alpha=0.8,
|
| 363 |
-
label='Suggestive (3)')
|
| 364 |
-
ax.set_xlim(-GAP, offset)
|
| 365 |
-
ax.set_ylim(0, max(log_p.max()*1.15, bonf_log*1.1, 1))
|
| 366 |
-
ax.set_ylabel('βlogββ(P)', fontsize=10, fontweight='bold')
|
| 367 |
-
ax.set_title(f'Model: {mname}', fontsize=11, fontweight='bold',
|
| 368 |
-
color=MODEL_COLORS.get(mname, ACCENT), pad=4)
|
| 369 |
-
ax.yaxis.grid(True, color=GRID_C, lw=0.6)
|
| 370 |
-
ax.legend(loc='upper right', fontsize=7.5)
|
| 371 |
-
n_sig = int((pv < bonf_thresh).sum())
|
| 372 |
-
ax.text(0.01, 0.92, f'{n_sig} significant',
|
| 373 |
-
transform=ax.transAxes, fontsize=8, color=RED_C,
|
| 374 |
-
fontweight='bold')
|
| 375 |
|
| 376 |
axes[-1].set_xticks([x for x, _ in chrom_xticks])
|
| 377 |
axes[-1].set_xticklabels([l for _, l in chrom_xticks], fontsize=7)
|
| 378 |
axes[-1].set_xlabel('Chromosome', fontsize=11, fontweight='bold')
|
| 379 |
-
|
| 380 |
-
|
| 381 |
-
|
|
|
|
| 382 |
plt.savefig(save_path, dpi=100, bbox_inches='tight', facecolor=BG)
|
| 383 |
plt.close(fig)
|
| 384 |
|
|
@@ -914,7 +980,7 @@ def run_analysis(input_file, miss_sample, miss_marker, maf_thresh,
|
|
| 914 |
top_cols = [c for c in top_cols if c in df.columns]
|
| 915 |
|
| 916 |
summary = f"""
|
| 917 |
-
## β
GWAS Analysis Complete β v8.
|
| 918 |
|
| 919 |
### π QC Summary
|
| 920 |
| Metric | Value |
|
|
@@ -964,10 +1030,10 @@ h1{color:#2D1B5E;border-bottom:3px solid #7C3AED;padding-bottom:8px}
|
|
| 964 |
.progress-bar{background:#7C3AED!important}
|
| 965 |
"""
|
| 966 |
|
| 967 |
-
with gr.Blocks(css=CSS, title="MTA GWAS v8.
|
| 968 |
|
| 969 |
gr.Markdown("""
|
| 970 |
-
# 𧬠GWAS Analysis Platform v8.
|
| 971 |
### 5-Model MRmlm Suite | LD Decay in bp | Persistent Outputs | Progress Tracking
|
| 972 |
---
|
| 973 |
""")
|
|
@@ -1025,7 +1091,7 @@ with gr.Blocks(css=CSS, title="MTA GWAS v8.2") as app:
|
|
| 1025 |
ph_out = gr.Image(label="π Phenotype Distribution")
|
| 1026 |
dl_out = gr.File(label="π¦ Download All Results (ZIP)")
|
| 1027 |
|
| 1028 |
-
gr.Markdown("---\n**MTA GWAS v8.
|
| 1029 |
|
| 1030 |
run_btn.click(
|
| 1031 |
fn=run_analysis,
|
|
|
|
| 1 |
# -*- coding: utf-8 -*-
|
| 2 |
"""
|
| 3 |
+
MTA Analysis Tool v8.3 β FIXES:
|
| 4 |
β
Persistent output directory (no tempfile cleanup race)
|
| 5 |
β
BSLMM: n_boot reduced + Ridge fallback for speed
|
| 6 |
β
FarmCPU: vectorised inner loop
|
|
|
|
| 268 |
# MODEL 5: FarmCPU β FIXED: vectorised scan
|
| 269 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 270 |
def model_farmcpu(G, y, K, max_iter=3):
|
| 271 |
+
"""
|
| 272 |
+
Corrected FarmCPU:
|
| 273 |
+
- Pseudo-QTNs enter as fixed covariates in y only (not projected from G)
|
| 274 |
+
- Each marker tested raw against y_cond via OLS with df = n - q - 2
|
| 275 |
+
- This avoids the double-projection inflation seen when both X and y
|
| 276 |
+
are residualised by the same projector.
|
| 277 |
+
"""
|
| 278 |
n, m = G.shape
|
| 279 |
pv_cur, bv, sv, rv = model_glm(G, y)
|
| 280 |
|
| 281 |
for iteration in range(max_iter):
|
| 282 |
n_qtns = max(1, min(10, int(m * 0.001)))
|
| 283 |
top_idx = np.argsort(pv_cur)[:n_qtns]
|
| 284 |
+
covs = G[:, top_idx] # n Γ q pseudo-QTNs as fixed covariates
|
| 285 |
|
| 286 |
+
# Partial y on pseudo-QTNs only (leave G raw)
|
| 287 |
try:
|
| 288 |
+
coef_c, _, _, _ = np.linalg.lstsq(
|
| 289 |
+
np.column_stack([np.ones(n), covs]), y, rcond=None)
|
| 290 |
+
y_cond = y - np.column_stack([np.ones(n), covs]) @ coef_c
|
| 291 |
except Exception:
|
| 292 |
y_cond = y.copy()
|
| 293 |
|
| 294 |
+
q = covs.shape[1]
|
| 295 |
+
df = max(n - q - 2, 1) # corrected degrees of freedom
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 296 |
|
|
|
|
| 297 |
pv_new = np.ones(m); bv_new = np.zeros(m); sv_new = np.zeros(m)
|
| 298 |
for i in range(m):
|
| 299 |
+
x = G[:, i] # raw marker (NOT residualised)
|
| 300 |
if x.std() < 1e-9: continue
|
| 301 |
+
# OLS with intercept: [1, x] β y_cond
|
| 302 |
+
X2 = np.column_stack([np.ones(n), x])
|
| 303 |
+
try:
|
| 304 |
+
b, res, _, _ = np.linalg.lstsq(X2, y_cond, rcond=None)
|
| 305 |
+
except Exception:
|
| 306 |
+
continue
|
| 307 |
+
fitted = X2 @ b
|
| 308 |
+
sse = float(np.sum((y_cond - fitted)**2))
|
| 309 |
+
ssx = float(np.sum((x - x.mean())**2))
|
| 310 |
+
if ssx < 1e-12 or sse < 1e-300: continue
|
| 311 |
+
se_b = np.sqrt(sse / df / ssx)
|
| 312 |
+
t_stat = b[1] / (se_b + 1e-300)
|
| 313 |
+
p = 2 * stats.t.sf(abs(t_stat), df=df)
|
| 314 |
+
pv_new[i] = max(float(p), 1e-300) if np.isfinite(p) else 1.0
|
| 315 |
+
bv_new[i] = float(b[1]); sv_new[i] = se_b
|
| 316 |
|
| 317 |
pv_cur = pv_new.copy()
|
| 318 |
|
|
|
|
| 322 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 323 |
# PLOT: MANHATTAN
|
| 324 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 325 |
+
def _draw_manhattan_ax(ax, x_pos, log_vals, sig_set, unique_chroms,
|
| 326 |
+
chrom_to_idx, CHROM_PALETTE, bonf_line,
|
| 327 |
+
sug_line, ylabel, mcol, mname, n_sig, offset, GAP,
|
| 328 |
+
y_cap=None):
|
| 329 |
+
"""Shared drawing helper for one Manhattan subplot."""
|
| 330 |
+
for ci, ch in enumerate(unique_chroms):
|
| 331 |
+
idxs = chrom_to_idx.get(ch, [])
|
| 332 |
+
if not idxs: continue
|
| 333 |
+
if ci % 2 == 0:
|
| 334 |
+
ax.axvspan(x_pos[idxs[0]]-.5, x_pos[idxs[-1]]+.5,
|
| 335 |
+
color='#EDE9FE', alpha=0.35, zorder=0)
|
| 336 |
+
shade = CHROM_PALETTE[ci % len(CHROM_PALETTE)]
|
| 337 |
+
norm = [i for i in idxs if i not in sig_set]
|
| 338 |
+
sel = [i for i in idxs if i in sig_set]
|
| 339 |
+
if norm:
|
| 340 |
+
ax.scatter(x_pos[norm], log_vals[norm], c=shade,
|
| 341 |
+
s=8, alpha=0.55, linewidths=0, zorder=2)
|
| 342 |
+
if sel:
|
| 343 |
+
ax.scatter(x_pos[sel], log_vals[sel], c=RED_C, s=180,
|
| 344 |
+
alpha=0.15, linewidths=0, zorder=3)
|
| 345 |
+
ax.scatter(x_pos[sel], log_vals[sel], c=RED_C, s=45,
|
| 346 |
+
alpha=1.0, edgecolors='white', linewidths=0.7,
|
| 347 |
+
marker='D', zorder=4)
|
| 348 |
+
ax.axhline(bonf_line, color=RED_C, ls='--', lw=1.5, alpha=0.85,
|
| 349 |
+
label=f'Bonferroni ({bonf_line:.1f})')
|
| 350 |
+
ax.axhline(sug_line, color=GOLD_C, ls=':', lw=1.3, alpha=0.8,
|
| 351 |
+
label=f'Suggestive ({sug_line:.1f})')
|
| 352 |
+
ax.set_xlim(-GAP, offset)
|
| 353 |
+
peak = float(log_vals.max())
|
| 354 |
+
ylim_top = max(peak * 1.15, bonf_line * 1.15, 1.0)
|
| 355 |
+
if y_cap is not None:
|
| 356 |
+
ylim_top = min(ylim_top, y_cap)
|
| 357 |
+
ax.set_ylim(0, ylim_top)
|
| 358 |
+
ax.set_ylabel(ylabel, fontsize=9, fontweight='bold')
|
| 359 |
+
ax.set_title(f'Model: {mname}', fontsize=10, fontweight='bold',
|
| 360 |
+
color=mcol, pad=3)
|
| 361 |
+
ax.yaxis.grid(True, color=GRID_C, lw=0.5)
|
| 362 |
+
ax.legend(loc='upper right', fontsize=7)
|
| 363 |
+
ax.text(0.01, 0.90, f'{n_sig} sig.',
|
| 364 |
+
transform=ax.transAxes, fontsize=8, color=RED_C, fontweight='bold')
|
| 365 |
+
|
| 366 |
+
|
| 367 |
def plot_manhattan_multi(mn, chroms, model_pvals, bonf_thresh, save_path):
|
| 368 |
+
"""
|
| 369 |
+
Two panels per model:
|
| 370 |
+
Top : βlogββ(P) β standard GWAS significance scale
|
| 371 |
+
Bottom : LOD score = βlogββ(P) Γ logββ(e) / 2 β βlogββ(P) Γ 0.2171
|
| 372 |
+
Significant SNPs (red diamonds) shown on both panels.
|
| 373 |
+
FarmCPU y-axis capped at 3Γ Bonferroni to prevent inflation blowout.
|
| 374 |
+
"""
|
| 375 |
_style()
|
| 376 |
+
LOD_FACTOR = np.log10(np.e) / 2.0 # β 0.2171 PβLOD conversion
|
| 377 |
+
|
| 378 |
unique_chroms = sorted(set(chroms),
|
| 379 |
key=lambda x: (int(x) if str(x).isdigit() else 999, str(x)))
|
| 380 |
n_models = len(model_pvals)
|
|
|
|
| 394 |
chrom_xticks.append((offset + len(idxs)/2, str(ch)))
|
| 395 |
offset += len(idxs) + GAP
|
| 396 |
|
| 397 |
+
# 2 rows per model (βlog10P + LOD)
|
| 398 |
+
n_rows = n_models * 2
|
| 399 |
+
row_h = [3.0 if r % 2 == 0 else 2.2 for r in range(n_rows)]
|
| 400 |
+
fig, axes = plt.subplots(n_rows, 1,
|
| 401 |
+
figsize=(18, sum(row_h)),
|
| 402 |
+
facecolor=BG,
|
| 403 |
+
gridspec_kw={'height_ratios': row_h},
|
| 404 |
+
sharex=True)
|
| 405 |
+
axes = list(axes)
|
| 406 |
|
| 407 |
bonf_log = -np.log10(bonf_thresh)
|
| 408 |
+
bonf_lod = bonf_log * LOD_FACTOR
|
| 409 |
+
sug_log = 3.0
|
| 410 |
+
sug_lod = sug_log * LOD_FACTOR
|
| 411 |
+
|
| 412 |
+
for mi, (mname, pv) in enumerate(model_pvals.items()):
|
| 413 |
+
ax_p = axes[mi * 2] # βlog10P panel
|
| 414 |
+
ax_lod = axes[mi * 2 + 1] # LOD panel
|
| 415 |
+
for ax in (ax_p, ax_lod):
|
| 416 |
+
ax.set_facecolor(PANEL)
|
| 417 |
+
|
| 418 |
+
log_p = -np.log10(np.clip(pv, 1e-300, 1))
|
| 419 |
+
lod = log_p * LOD_FACTOR
|
| 420 |
sig_set = set(np.where(pv < bonf_thresh)[0])
|
| 421 |
+
n_sig = int(len(sig_set))
|
| 422 |
+
mcol = MODEL_COLORS.get(mname, ACCENT)
|
| 423 |
+
|
| 424 |
+
# Cap FarmCPU y-axis at 3Γ Bonferroni to prevent inflation blowout
|
| 425 |
+
y_cap_p = bonf_log * 3.5 if mname == 'FarmCPU' else None
|
| 426 |
+
y_cap_lod = bonf_lod * 3.5 if mname == 'FarmCPU' else None
|
| 427 |
+
|
| 428 |
+
_draw_manhattan_ax(ax_p, x_pos, log_p, sig_set, unique_chroms,
|
| 429 |
+
chrom_to_idx, CHROM_PALETTE, bonf_log, sug_log,
|
| 430 |
+
'βlogββ(P)', mcol, mname, n_sig, offset, GAP,
|
| 431 |
+
y_cap=y_cap_p)
|
| 432 |
+
_draw_manhattan_ax(ax_lod, x_pos, lod, sig_set, unique_chroms,
|
| 433 |
+
chrom_to_idx, CHROM_PALETTE, bonf_lod, sug_lod,
|
| 434 |
+
'LOD score', mcol, f'{mname} (LOD)', n_sig,
|
| 435 |
+
offset, GAP, y_cap=y_cap_lod)
|
| 436 |
+
|
| 437 |
+
# Subtle divider between model pairs
|
| 438 |
+
ax_lod.spines['bottom'].set_linewidth(2.0)
|
| 439 |
+
ax_lod.spines['bottom'].set_color(GRID_C)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 440 |
|
| 441 |
axes[-1].set_xticks([x for x, _ in chrom_xticks])
|
| 442 |
axes[-1].set_xticklabels([l for _, l in chrom_xticks], fontsize=7)
|
| 443 |
axes[-1].set_xlabel('Chromosome', fontsize=11, fontweight='bold')
|
| 444 |
+
|
| 445 |
+
plt.suptitle('GWAS Manhattan Plots β βlogββ(P) & LOD Score',
|
| 446 |
+
fontsize=13, fontweight='bold', y=1.005, color=TEXT_C)
|
| 447 |
+
plt.tight_layout(pad=1.0, h_pad=0.4)
|
| 448 |
plt.savefig(save_path, dpi=100, bbox_inches='tight', facecolor=BG)
|
| 449 |
plt.close(fig)
|
| 450 |
|
|
|
|
| 980 |
top_cols = [c for c in top_cols if c in df.columns]
|
| 981 |
|
| 982 |
summary = f"""
|
| 983 |
+
## β
GWAS Analysis Complete β v8.3
|
| 984 |
|
| 985 |
### π QC Summary
|
| 986 |
| Metric | Value |
|
|
|
|
| 1030 |
.progress-bar{background:#7C3AED!important}
|
| 1031 |
"""
|
| 1032 |
|
| 1033 |
+
with gr.Blocks(css=CSS, title="MTA GWAS v8.3") as app:
|
| 1034 |
|
| 1035 |
gr.Markdown("""
|
| 1036 |
+
# 𧬠GWAS Analysis Platform v8.3
|
| 1037 |
### 5-Model MRmlm Suite | LD Decay in bp | Persistent Outputs | Progress Tracking
|
| 1038 |
---
|
| 1039 |
""")
|
|
|
|
| 1091 |
ph_out = gr.Image(label="π Phenotype Distribution")
|
| 1092 |
dl_out = gr.File(label="π¦ Download All Results (ZIP)")
|
| 1093 |
|
| 1094 |
+
gr.Markdown("---\n**MTA GWAS v8.3** | Persistent output paths | Progress tracking")
|
| 1095 |
|
| 1096 |
run_btn.click(
|
| 1097 |
fn=run_analysis,
|