Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,7 +1,7 @@
|
|
| 1 |
# -*- coding: utf-8 -*-
|
| 2 |
"""
|
| 3 |
-
MTA Analysis Tool
|
| 4 |
-
|
| 5 |
"""
|
| 6 |
|
| 7 |
import gradio as gr
|
|
@@ -11,66 +11,60 @@ import matplotlib
|
|
| 11 |
matplotlib.use('Agg')
|
| 12 |
import matplotlib.pyplot as plt
|
| 13 |
import matplotlib.patches as mpatches
|
| 14 |
-
from matplotlib.
|
| 15 |
-
import matplotlib.patheffects as pe
|
| 16 |
import seaborn as sns
|
| 17 |
-
from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor
|
| 18 |
-
from sklearn.linear_model import LassoCV, ElasticNetCV, Ridge
|
| 19 |
-
from sklearn.feature_selection import mutual_info_regression, f_regression
|
| 20 |
-
from sklearn.model_selection import cross_val_score, KFold
|
| 21 |
-
from sklearn.preprocessing import StandardScaler
|
| 22 |
-
from sklearn.metrics import r2_score, mean_squared_error
|
| 23 |
from scipy import stats
|
| 24 |
import os, warnings, tempfile, zipfile
|
| 25 |
warnings.filterwarnings('ignore')
|
| 26 |
|
| 27 |
-
#
|
| 28 |
-
#
|
| 29 |
-
#
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
|
|
|
| 39 |
|
| 40 |
CHROM_PALETTE = [
|
| 41 |
-
"#
|
| 42 |
-
"#
|
| 43 |
-
"#
|
| 44 |
-
"#
|
| 45 |
-
"#
|
| 46 |
]
|
| 47 |
|
| 48 |
-
def
|
| 49 |
plt.rcParams.update({
|
| 50 |
-
'figure.facecolor':
|
| 51 |
-
'axes.facecolor':
|
| 52 |
-
'axes.edgecolor':
|
| 53 |
-
'axes.labelcolor':
|
| 54 |
-
'axes.titlecolor':
|
| 55 |
-
'xtick.color':
|
| 56 |
-
'ytick.color':
|
| 57 |
-
'text.color':
|
| 58 |
-
'grid.color':
|
| 59 |
-
'grid.linewidth':
|
| 60 |
-
'figure.dpi':
|
| 61 |
-
'font.family':
|
| 62 |
-
'axes.spines.top':
|
| 63 |
'axes.spines.right': False,
|
| 64 |
-
'
|
| 65 |
-
'
|
| 66 |
})
|
| 67 |
|
| 68 |
-
|
| 69 |
-
#
|
| 70 |
-
#
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
|
| 75 |
unique_chroms = sorted(set(chromosomes),
|
| 76 |
key=lambda x: (int(x) if x.isdigit() else 999, x))
|
|
@@ -79,190 +73,204 @@ def plot_manhattan(marker_names, chromosomes, p_values, consensus_set,
|
|
| 79 |
GAP = max(8, len(marker_names) // 150)
|
| 80 |
x_pos = np.zeros(len(marker_names))
|
| 81 |
chrom_centers, chrom_to_idx = {}, {}
|
| 82 |
-
for i,
|
| 83 |
-
c = chromosomes[i]
|
| 84 |
chrom_to_idx.setdefault(c, []).append(i)
|
| 85 |
|
| 86 |
offset = 0
|
| 87 |
-
for
|
| 88 |
-
idxs = chrom_to_idx.get(
|
| 89 |
if not idxs: continue
|
| 90 |
-
for
|
| 91 |
-
x_pos[idx] = offset +
|
| 92 |
-
chrom_centers[
|
| 93 |
offset += len(idxs) + GAP
|
| 94 |
|
| 95 |
-
fig = plt.figure(figsize=(22,
|
| 96 |
-
ax = fig.add_subplot(111, facecolor=
|
| 97 |
|
| 98 |
-
#
|
| 99 |
-
for ci,
|
| 100 |
-
idxs = chrom_to_idx.get(
|
| 101 |
if not idxs: continue
|
| 102 |
x0 = x_pos[idxs[0]] - 0.5
|
| 103 |
x1 = x_pos[idxs[-1]] + 0.5
|
| 104 |
-
|
| 105 |
-
|
| 106 |
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
idxs = chrom_to_idx.get(chrom, [])
|
| 110 |
if not idxs: continue
|
| 111 |
col = CHROM_PALETTE[ci % len(CHROM_PALETTE)]
|
| 112 |
|
| 113 |
-
normal = [i for i in idxs if i not in
|
| 114 |
-
sel = [i for i in idxs if i in
|
| 115 |
|
| 116 |
if normal:
|
| 117 |
ax.scatter(x_pos[normal], log_p[normal],
|
| 118 |
-
c=col, s=
|
| 119 |
if sel:
|
| 120 |
-
#
|
| 121 |
ax.scatter(x_pos[sel], log_p[sel],
|
| 122 |
-
c=
|
| 123 |
ax.scatter(x_pos[sel], log_p[sel],
|
| 124 |
-
c=
|
| 125 |
-
edgecolors='white', linewidths=
|
| 126 |
marker='D', zorder=4)
|
| 127 |
|
| 128 |
# Threshold lines
|
| 129 |
-
ax.axhline(bonf_thresh, color=
|
| 130 |
-
ax.text(offset * 0.
|
| 131 |
-
f'Bonferroni
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
ax.
|
| 137 |
-
|
|
|
|
|
|
|
| 138 |
|
| 139 |
-
# Chromosome labels
|
| 140 |
xtick_pos = [chrom_centers[c] for c in unique_chroms if c in chrom_centers]
|
| 141 |
xtick_lab = [f'Chr {c}' for c in unique_chroms if c in chrom_centers]
|
| 142 |
ax.set_xticks(xtick_pos)
|
| 143 |
ax.set_xticklabels(xtick_lab,
|
| 144 |
-
fontsize=8 if len(unique_chroms) > 12 else 10,
|
| 145 |
rotation=45 if len(unique_chroms) > 14 else 0,
|
| 146 |
-
ha='center', color=
|
| 147 |
ax.set_xlim(-GAP, offset)
|
| 148 |
-
ax.set_ylim(bottom=0, top=max(
|
| 149 |
|
| 150 |
-
ax.set_ylabel('−log₁₀(P-value)', fontsize=
|
| 151 |
-
|
|
|
|
|
|
|
| 152 |
ax.set_title('Genome-Wide Association Study · Manhattan Plot',
|
| 153 |
-
fontsize=
|
| 154 |
|
| 155 |
-
|
| 156 |
-
ax.yaxis.grid(True, color=GRID_COL, linewidth=0.6, alpha=0.8)
|
| 157 |
ax.set_axisbelow(True)
|
|
|
|
| 158 |
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
facecolor=PANEL_BG, edgecolor=GRID_COL,
|
| 165 |
-
labelcolor=TEXT_COL, loc='upper right')
|
| 166 |
|
| 167 |
-
#
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 172 |
plt.close(fig)
|
| 173 |
|
| 174 |
|
| 175 |
-
#
|
| 176 |
# PLOT 2 — QQ PLOT
|
| 177 |
-
#
|
| 178 |
def plot_qq(p_values, save_path):
|
| 179 |
-
|
| 180 |
|
| 181 |
-
pv
|
| 182 |
-
n
|
| 183 |
obs = np.sort(pv)
|
| 184 |
exp = np.linspace(1/n, 1, n)
|
| 185 |
log_obs = -np.log10(obs)
|
| 186 |
log_exp = -np.log10(exp)
|
| 187 |
|
| 188 |
-
ci_up
|
| 189 |
-
ci_lo
|
|
|
|
| 190 |
|
| 191 |
chi2 = stats.chi2.ppf(1 - pv, df=1)
|
| 192 |
lam = np.median(chi2) / stats.chi2.ppf(0.5, df=1)
|
| 193 |
|
| 194 |
-
fig, ax = plt.subplots(figsize=(7, 7), facecolor=
|
| 195 |
-
ax.set_facecolor(
|
| 196 |
|
| 197 |
ax.fill_between(log_exp, ci_lo, ci_up,
|
| 198 |
-
color=
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
ax.
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 209 |
ax.set_xlim(0, maxv); ax.set_ylim(0, maxv)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 210 |
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
ax.text(0.04, 0.96, f'λ = {lam:.4f} [{lam_txt}]',
|
| 214 |
-
transform=ax.transAxes, fontsize=10,
|
| 215 |
-
color=lam_col, va='top',
|
| 216 |
-
bbox=dict(boxstyle='round,pad=0.4', fc=PANEL_BG, ec=lam_col, alpha=0.85))
|
| 217 |
-
|
| 218 |
-
ax.yaxis.grid(True, color=GRID_COL, lw=0.6)
|
| 219 |
-
ax.xaxis.grid(True, color=GRID_COL, lw=0.6)
|
| 220 |
-
ax.tick_params(colors=TEXT_COL)
|
| 221 |
-
|
| 222 |
-
plt.tight_layout(pad=1.5)
|
| 223 |
-
plt.savefig(save_path, dpi=200, bbox_inches='tight', facecolor=DARK_BG)
|
| 224 |
plt.close(fig)
|
| 225 |
return lam
|
| 226 |
|
| 227 |
|
| 228 |
-
#
|
| 229 |
# PLOT 3 — LD DECAY
|
| 230 |
-
#
|
| 231 |
def plot_ld_decay(genotypes, chromosomes, save_path, max_m=250):
|
| 232 |
-
|
| 233 |
|
| 234 |
unique_chroms = sorted(set(chromosomes),
|
| 235 |
key=lambda x: (int(x) if x.isdigit() else 999, x))
|
| 236 |
-
all_d, all_r2 = [], []
|
| 237 |
-
chrom_mean = {}
|
| 238 |
|
| 239 |
-
for
|
| 240 |
-
idxs = [i for i,
|
| 241 |
if len(idxs) < 4: continue
|
| 242 |
if len(idxs) > max_m:
|
| 243 |
idxs = sorted(np.random.choice(idxs, max_m, replace=False))
|
| 244 |
-
G
|
| 245 |
-
std = G.std(axis=0); std[std
|
| 246 |
-
G
|
| 247 |
-
nm
|
| 248 |
dl, rl = [], []
|
| 249 |
-
for i in range(nm
|
| 250 |
for j in range(i+1, min(i+60, nm)):
|
| 251 |
r = np.corrcoef(G[:,i], G[:,j])[0,1]
|
| 252 |
r2 = r**2 if not np.isnan(r) else 0
|
| 253 |
-
dl.append(j
|
| 254 |
if dl:
|
| 255 |
all_d.extend(dl); all_r2.extend(rl)
|
| 256 |
-
chrom_mean[
|
| 257 |
|
| 258 |
-
fig, axes = plt.subplots(1, 2, figsize=(16, 6), facecolor=
|
| 259 |
|
| 260 |
# ── Left: decay curve ──
|
| 261 |
-
ax = axes[0]; ax.set_facecolor(
|
| 262 |
if all_d:
|
| 263 |
-
all_d
|
| 264 |
-
|
| 265 |
-
|
|
|
|
| 266 |
mu, se = [], []
|
| 267 |
for b in bins:
|
| 268 |
m = all_d == b
|
|
@@ -274,213 +282,202 @@ def plot_ld_decay(genotypes, chromosomes, save_path, max_m=250):
|
|
| 274 |
mu = np.array(mu); se = np.array(se)
|
| 275 |
v = ~np.isnan(mu)
|
| 276 |
|
| 277 |
-
ax.fill_between(bins[v],
|
| 278 |
-
|
|
|
|
|
|
|
| 279 |
|
| 280 |
-
#
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
lc = LineCollection(segs, cmap='cool', linewidth=2.5, zorder=4)
|
| 285 |
lc.set_array(mu[v])
|
| 286 |
ax.add_collection(lc)
|
| 287 |
-
ax.scatter(bins[v], mu[v], c=mu[v], cmap='
|
|
|
|
|
|
|
| 288 |
|
| 289 |
-
ax.axhline(0.2, color=
|
| 290 |
|
| 291 |
-
|
| 292 |
-
start_r2 = mu[v][0] if len(mu[v]) > 0 else 1.0
|
| 293 |
-
hd = None
|
| 294 |
for i, r2 in enumerate(mu[v]):
|
| 295 |
-
if r2 <=
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
ax.
|
| 302 |
-
ax.
|
| 303 |
-
|
| 304 |
-
ax.set_ylim(0, 1); ax.tick_params(colors=
|
| 305 |
-
ax.yaxis.grid(True, color=
|
| 306 |
-
ax.legend(fontsize=9, facecolor=
|
| 307 |
|
| 308 |
# ── Right: per-chromosome bars ──
|
| 309 |
-
ax2 = axes[1]; ax2.set_facecolor(
|
| 310 |
if chrom_mean:
|
| 311 |
-
cs
|
| 312 |
vals = [chrom_mean[c] for c in cs]
|
| 313 |
cols = [CHROM_PALETTE[i % len(CHROM_PALETTE)] for i in range(len(cs))]
|
| 314 |
bars = ax2.bar(range(len(cs)), vals, color=cols,
|
| 315 |
-
edgecolor=
|
| 316 |
ax2.set_xticks(range(len(cs)))
|
| 317 |
ax2.set_xticklabels([f'Chr {c}' for c in cs],
|
| 318 |
rotation=45 if len(cs) > 10 else 0,
|
| 319 |
-
fontsize=8, ha='right', color=
|
| 320 |
-
ax2.set_ylim(0, 1)
|
| 321 |
for bar, val in zip(bars, vals):
|
| 322 |
ax2.text(bar.get_x() + bar.get_width()/2,
|
| 323 |
bar.get_height() + 0.02,
|
| 324 |
f'{val:.2f}', ha='center', va='bottom',
|
| 325 |
-
fontsize=
|
| 326 |
-
ax2.set_xlabel('Chromosome', fontsize=
|
| 327 |
-
ax2.set_ylabel('Mean r²', fontsize=
|
| 328 |
-
ax2.set_title('Mean LD per Chromosome', fontsize=14, color=
|
| 329 |
fontweight='bold', pad=12)
|
| 330 |
-
ax2.
|
| 331 |
-
ax2.
|
|
|
|
| 332 |
|
| 333 |
-
fig.suptitle('Linkage Disequilibrium Analysis',
|
| 334 |
-
color=
|
| 335 |
plt.tight_layout(pad=2)
|
| 336 |
-
plt.savefig(save_path, dpi=200, bbox_inches='tight', facecolor=
|
| 337 |
plt.close(fig)
|
| 338 |
return chrom_mean
|
| 339 |
|
| 340 |
|
| 341 |
-
#
|
| 342 |
-
# PLOT 4 —
|
| 343 |
-
#
|
| 344 |
-
def
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
fig,
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
ax.
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
ax.
|
| 370 |
-
ax.
|
| 371 |
-
ax.
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
|
| 380 |
-
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
|
| 386 |
-
|
| 387 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 388 |
plt.close(fig)
|
| 389 |
|
| 390 |
|
| 391 |
-
#
|
| 392 |
-
# PLOT 5 —
|
| 393 |
-
#
|
| 394 |
-
def
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
ax.set_facecolor(PANEL_BG)
|
| 398 |
|
| 399 |
-
|
| 400 |
-
|
| 401 |
-
xy = np.vstack([obs, pred])
|
| 402 |
-
try:
|
| 403 |
-
z = gaussian_kde(xy)(xy)
|
| 404 |
-
idx = z.argsort()
|
| 405 |
-
sc = ax.scatter(obs[idx], pred[idx], c=z[idx], cmap='plasma',
|
| 406 |
-
s=45, alpha=0.85, linewidths=0, zorder=3)
|
| 407 |
-
plt.colorbar(sc, ax=ax, label='Density', shrink=0.8)
|
| 408 |
-
except Exception:
|
| 409 |
-
ax.scatter(obs, pred, c=ACCENT4, s=40, alpha=0.7, linewidths=0)
|
| 410 |
-
|
| 411 |
-
lims = [min(obs.min(), pred.min()) - 1, max(obs.max(), pred.max()) + 1]
|
| 412 |
-
ax.plot(lims, lims, color=ACCENT3, lw=2, ls='--', zorder=4, label='y = x')
|
| 413 |
-
ax.set_xlim(lims); ax.set_ylim(lims)
|
| 414 |
-
|
| 415 |
-
corr, _ = stats.pearsonr(obs, pred)
|
| 416 |
-
ax.set_xlabel('Observed Phenotype', fontsize=12, color=TEXT_COL)
|
| 417 |
-
ax.set_ylabel('Predicted GEBV', fontsize=12, color=TEXT_COL)
|
| 418 |
-
ax.set_title(f'{best_name} — Observed vs Predicted', fontsize=15,
|
| 419 |
-
color=TEXT_COL, fontweight='bold', pad=14)
|
| 420 |
-
ax.text(0.05, 0.93,
|
| 421 |
-
f'CV R² = {cv_r2:.4f}\nRMSE = {rmse:.4f}\nr = {corr:.4f}',
|
| 422 |
-
transform=ax.transAxes, fontsize=11, color=TEXT_COL, va='top',
|
| 423 |
-
bbox=dict(boxstyle='round,pad=0.5', fc=PANEL_BG, ec=ACCENT1, alpha=0.9))
|
| 424 |
-
ax.yaxis.grid(True, color=GRID_COL, lw=0.6)
|
| 425 |
-
ax.xaxis.grid(True, color=GRID_COL, lw=0.6)
|
| 426 |
-
ax.tick_params(colors=TEXT_COL)
|
| 427 |
-
ax.legend(fontsize=10, facecolor=PANEL_BG, edgecolor=GRID_COL, labelcolor=TEXT_COL)
|
| 428 |
-
|
| 429 |
-
plt.tight_layout(pad=1.5)
|
| 430 |
-
plt.savefig(save_path, dpi=200, bbox_inches='tight', facecolor=DARK_BG)
|
| 431 |
-
plt.close(fig)
|
| 432 |
-
|
| 433 |
-
|
| 434 |
-
# ──────────────────────────────────────────────────────────────
|
| 435 |
-
# PLOT 6 — TOP MARKER EFFECTS
|
| 436 |
-
# ──────────────────────────────────────────────────────────────
|
| 437 |
-
def plot_top_markers(mta_df, best_name, chrom_list_sorted, save_path, top_n=30):
|
| 438 |
-
set_dark_style()
|
| 439 |
-
df = mta_df.head(top_n).copy()
|
| 440 |
-
fig, ax = plt.subplots(figsize=(13, 9), facecolor=DARK_BG)
|
| 441 |
-
ax.set_facecolor(PANEL_BG)
|
| 442 |
|
|
|
|
|
|
|
| 443 |
col_map = {c: CHROM_PALETTE[i % len(CHROM_PALETTE)]
|
| 444 |
-
for i,
|
| 445 |
-
colors = [col_map.get(c, ACCENT1) for c in df['Chromosome']]
|
| 446 |
|
| 447 |
-
|
| 448 |
-
color=colors, edgecolor=DARK_BG, linewidth=0.6,
|
| 449 |
-
alpha=0.88, height=0.7)
|
| 450 |
|
| 451 |
-
|
| 452 |
-
ax.
|
| 453 |
-
|
| 454 |
-
|
| 455 |
-
|
| 456 |
-
|
| 457 |
-
ax.set_xlabel(f'Effect Size ({best_name})', fontsize=12, color=TEXT_COL)
|
| 458 |
-
ax.set_title(f'Top {top_n} Selected Markers — Effect Sizes', fontsize=15,
|
| 459 |
-
color=TEXT_COL, fontweight='bold', pad=14)
|
| 460 |
-
ax.tick_params(colors=TEXT_COL)
|
| 461 |
-
ax.xaxis.grid(True, color=GRID_COL, lw=0.6)
|
| 462 |
|
| 463 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 464 |
handles = []
|
| 465 |
shown = set()
|
| 466 |
-
for
|
| 467 |
-
c =
|
| 468 |
if c not in shown:
|
| 469 |
-
handles.append(mpatches.Patch(color=col_map
|
| 470 |
-
label=f'Chr {c}'))
|
| 471 |
shown.add(c)
|
| 472 |
-
ax.legend(handles=handles,
|
| 473 |
-
|
| 474 |
-
loc='lower right')
|
| 475 |
|
| 476 |
-
plt.tight_layout(pad=
|
| 477 |
-
plt.savefig(save_path, dpi=200, bbox_inches='tight', facecolor=
|
| 478 |
plt.close(fig)
|
| 479 |
|
| 480 |
|
| 481 |
-
#
|
| 482 |
-
# MAIN ANALYSIS
|
| 483 |
-
#
|
| 484 |
def run_mta_analysis(input_file, target_markers):
|
| 485 |
try:
|
| 486 |
if input_file is None:
|
|
@@ -492,24 +489,27 @@ def run_mta_analysis(input_file, target_markers):
|
|
| 492 |
for d in [results_dir, plots_dir]:
|
| 493 |
os.makedirs(d, exist_ok=True)
|
| 494 |
|
| 495 |
-
# ── LOAD ──
|
| 496 |
df = pd.read_csv(input_file, sep=',', header=0)
|
| 497 |
-
|
| 498 |
-
|
|
|
|
|
|
|
|
|
|
| 499 |
chromosome_dict = {m: c for m, c in zip(marker_cols, chrom_info_row)}
|
| 500 |
|
| 501 |
-
df_data
|
| 502 |
-
sample_ids
|
| 503 |
-
phenotypes
|
| 504 |
-
genotypes
|
| 505 |
marker_names = marker_cols
|
| 506 |
|
| 507 |
-
|
| 508 |
-
|
| 509 |
n_samples = len(sample_ids)
|
| 510 |
n_markers = len(marker_names)
|
| 511 |
|
| 512 |
-
# ── QC ──
|
| 513 |
miss_m = np.isnan(genotypes).sum(axis=0) / n_samples
|
| 514 |
miss_s = np.isnan(genotypes).sum(axis=1) / n_markers
|
| 515 |
maf = np.array([
|
|
@@ -526,6 +526,10 @@ def run_mta_analysis(input_file, target_markers):
|
|
| 526 |
mnames_qc = [marker_names[i] for i in range(n_markers) if qc_m[i]]
|
| 527 |
chrom_qc = [chromosome_dict[m] for m in mnames_qc]
|
| 528 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 529 |
for i in range(geno_qc.shape[1]):
|
| 530 |
col = geno_qc[:, i]
|
| 531 |
mask = np.isnan(col)
|
|
@@ -534,37 +538,52 @@ def run_mta_analysis(input_file, target_markers):
|
|
| 534 |
|
| 535 |
TARGET = min(int(target_markers), len(mnames_qc))
|
| 536 |
|
| 537 |
-
# ── GWAS ──
|
| 538 |
pvals = np.ones(len(mnames_qc))
|
| 539 |
effects = np.zeros(len(mnames_qc))
|
| 540 |
gse = np.zeros(len(mnames_qc))
|
|
|
|
|
|
|
| 541 |
for i in range(len(mnames_qc)):
|
| 542 |
mk = geno_qc[:, i]
|
| 543 |
if np.std(mk) > 0:
|
| 544 |
try:
|
| 545 |
-
|
| 546 |
-
pvals[i] =
|
| 547 |
-
effects[i] =
|
| 548 |
-
gse[i] =
|
| 549 |
-
|
|
|
|
|
|
|
| 550 |
|
| 551 |
bonf = -np.log10(0.05 / len(mnames_qc))
|
| 552 |
n_sig = int((pvals < 0.05/len(mnames_qc)).sum())
|
| 553 |
n_sugg = int((pvals < 1e-5).sum())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 554 |
|
| 555 |
-
# ── ML SELECTION ──
|
| 556 |
scaler = StandardScaler()
|
| 557 |
X = scaler.fit_transform(geno_qc)
|
| 558 |
y = pheno_qc
|
| 559 |
|
| 560 |
-
rf_fs = RandomForestRegressor(100, max_depth=10,
|
|
|
|
| 561 |
rf_fs.fit(X, y)
|
| 562 |
-
|
|
|
|
|
|
|
| 563 |
gb_fs.fit(X, y)
|
|
|
|
| 564 |
en_fs = ElasticNetCV(cv=5, random_state=42, max_iter=5000)
|
| 565 |
en_fs.fit(X, y)
|
| 566 |
-
|
| 567 |
-
|
|
|
|
| 568 |
|
| 569 |
votes = np.zeros(len(mnames_qc))
|
| 570 |
for arr in [rf_fs.feature_importances_, gb_fs.feature_importances_,
|
|
@@ -572,107 +591,70 @@ def run_mta_analysis(input_file, target_markers):
|
|
| 572 |
top = np.argsort(arr)[-TARGET:]
|
| 573 |
votes[top] += 1
|
| 574 |
|
| 575 |
-
|
| 576 |
-
|
| 577 |
-
|
| 578 |
-
|
| 579 |
-
|
| 580 |
-
|
| 581 |
-
|
| 582 |
-
|
| 583 |
-
|
| 584 |
-
|
| 585 |
-
|
| 586 |
-
|
| 587 |
-
|
| 588 |
-
|
| 589 |
-
|
| 590 |
-
|
| 591 |
-
|
| 592 |
-
|
| 593 |
-
|
| 594 |
-
|
| 595 |
-
|
| 596 |
-
'r2': r2_score(y, pred),
|
| 597 |
-
'rmse': np.sqrt(mean_squared_error(y, pred)),
|
| 598 |
-
'cv': cv_r2,
|
| 599 |
-
'eff': eff}
|
| 600 |
-
|
| 601 |
-
best_name = max(models, key=lambda k: models[k]['cv'])
|
| 602 |
-
best = models[best_name]
|
| 603 |
-
|
| 604 |
-
# ── CSVs ──
|
| 605 |
-
pred_df = pd.DataFrame({'SampleID': ids_qc, 'Observed': pheno_qc})
|
| 606 |
-
for nm, d in models.items():
|
| 607 |
-
pred_df[f'GEBV_{nm}'] = d['pred']
|
| 608 |
-
pred_df[f'Residual_{nm}'] = pheno_qc - d['pred']
|
| 609 |
-
pred_df['Best_GEBV'] = pred_df[f'GEBV_{best_name}']
|
| 610 |
-
pred_df['Rank'] = pred_df['Best_GEBV'].rank(ascending=False).astype(int)
|
| 611 |
-
pred_df.sort_values('Best_GEBV', ascending=False, inplace=True)
|
| 612 |
-
pred_df.to_csv(os.path.join(results_dir,'all_model_predictions.csv'), index=False)
|
| 613 |
-
|
| 614 |
-
mta_results = {}
|
| 615 |
-
for nm, d in models.items():
|
| 616 |
-
rows = []
|
| 617 |
-
for ri, idx in enumerate(np.argsort(d['eff'])[::-1]):
|
| 618 |
-
oi = cons_idx[idx]
|
| 619 |
-
rows.append({'Rank': ri+1,
|
| 620 |
-
'Marker': mnames_qc[oi],
|
| 621 |
-
'Chromosome': chrom_qc[oi],
|
| 622 |
-
f'Effect_{nm}': d['eff'][idx],
|
| 623 |
-
'Vote_Count': int(votes[oi]),
|
| 624 |
-
'GWAS_Pvalue': pvals[oi],
|
| 625 |
-
'GWAS_logP': -np.log10(pvals[oi]+1e-300),
|
| 626 |
-
'GWAS_Effect': effects[oi],
|
| 627 |
-
'GWAS_SE': gse[oi]})
|
| 628 |
-
mdf = pd.DataFrame(rows)
|
| 629 |
-
tot = mdf[f'Effect_{nm}'].sum()
|
| 630 |
-
mdf[f'Contribution_pct'] = mdf[f'Effect_{nm}']/tot*100 if tot>0 else 0
|
| 631 |
-
mta_results[nm] = mdf
|
| 632 |
-
mdf.to_csv(os.path.join(results_dir,f'mta_associations_{nm}.csv'), index=False)
|
| 633 |
-
|
| 634 |
-
# Chromosome summary
|
| 635 |
chr_rows = []
|
| 636 |
-
for ch in
|
| 637 |
-
ci = [i for i,
|
| 638 |
if not ci: continue
|
| 639 |
cp = pvals[ci]
|
| 640 |
chr_rows.append({
|
| 641 |
-
'Chromosome'
|
| 642 |
-
'N_Markers'
|
| 643 |
-
'
|
| 644 |
-
'
|
| 645 |
-
'
|
| 646 |
-
'
|
| 647 |
-
'
|
|
|
|
| 648 |
})
|
| 649 |
pd.DataFrame(chr_rows).to_csv(
|
| 650 |
-
os.path.join(results_dir,'chromosome_summary.csv'), index=False)
|
| 651 |
|
|
|
|
| 652 |
pd.DataFrame({
|
| 653 |
'Metric': ['Samples_raw','Samples_QC','Markers_raw','Markers_QC',
|
| 654 |
-
'
|
| 655 |
-
|
| 656 |
-
|
|
|
|
|
|
|
| 657 |
}).to_csv(os.path.join(results_dir,'qc_summary.csv'), index=False)
|
| 658 |
|
| 659 |
-
# ── PLOTS ──
|
| 660 |
-
man_path = os.path.join(plots_dir,'manhattan_plot.png')
|
| 661 |
-
qq_path = os.path.join(plots_dir,'qq_plot.png')
|
| 662 |
-
ld_path = os.path.join(plots_dir,'ld_decay.png')
|
| 663 |
-
|
| 664 |
-
|
| 665 |
-
top_path = os.path.join(plots_dir,'top_marker_effects.png')
|
| 666 |
|
| 667 |
-
plot_manhattan(mnames_qc, chrom_qc, pvals,
|
| 668 |
lam = plot_qq(pvals, qq_path)
|
| 669 |
ld_summary = plot_ld_decay(geno_qc, chrom_qc, ld_path)
|
| 670 |
-
|
| 671 |
-
|
| 672 |
-
plot_top_markers(mta_results[best_name], best_name, unique_chromosomes, top_path)
|
| 673 |
|
| 674 |
-
# ── ZIP (
|
| 675 |
-
zip_path = os.path.join(temp_dir, '
|
| 676 |
with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf:
|
| 677 |
for root, _, files in os.walk(results_dir):
|
| 678 |
for f in files:
|
|
@@ -680,531 +662,506 @@ def run_mta_analysis(input_file, target_markers):
|
|
| 680 |
arc = os.path.relpath(fp, temp_dir)
|
| 681 |
zf.write(fp, arc)
|
| 682 |
|
| 683 |
-
# ── SUMMARY ──
|
| 684 |
-
lam_txt = ("✅ Well-calibrated (λ≈1)" if lam < 1.05
|
| 685 |
else "⚠️ Minor inflation — consider PCA correction" if lam < 1.10
|
| 686 |
else "❌ Significant inflation — use mixed model (GEMMA/EMMAX)")
|
| 687 |
|
| 688 |
gm_r2 = np.mean(list(ld_summary.values())) if ld_summary else 0
|
| 689 |
ld_txt = ("Low LD — high marker density needed" if gm_r2 < 0.1
|
| 690 |
else "Moderate LD — typical for diverse panels" if gm_r2 < 0.3
|
| 691 |
-
else "High LD — consider LD pruning")
|
| 692 |
-
|
| 693 |
-
|
| 694 |
-
|
| 695 |
-
|
| 696 |
-
|
| 697 |
-
|
| 698 |
-
|
| 699 |
-
|
| 700 |
-
|
| 701 |
-
|
| 702 |
-
|
| 703 |
-
f"{r[
|
| 704 |
-
|
| 705 |
-
|
| 706 |
-
top5_samples = "\n".join(
|
| 707 |
-
f"| {int(r['Rank'])} | {r['SampleID']} | {r['Observed']:.3f} | {r['Best_GEBV']:.3f} |"
|
| 708 |
-
for _, r in pred_df.head(5).iterrows())
|
| 709 |
|
| 710 |
summary = f"""
|
| 711 |
-
##
|
| 712 |
| Metric | Value |
|
| 713 |
|--------|-------|
|
| 714 |
-
| Samples (raw → QC) | {n_samples} → {len(ids_qc)} |
|
| 715 |
-
| Markers (raw → QC) | {n_markers} → {len(mnames_qc)} |
|
| 716 |
-
|
|
| 717 |
-
|
|
|
|
|
| 718 |
|
| 719 |
-
## GWAS
|
| 720 |
| Metric | Value |
|
| 721 |
|--------|-------|
|
| 722 |
-
|
|
| 723 |
-
|
|
| 724 |
-
|
|
|
|
|
| 725 |
| Genomic inflation λ | **{lam:.4f}** — {lam_txt} |
|
| 726 |
|
| 727 |
-
## LD Summary
|
| 728 |
Global mean r² = **{gm_r2:.4f}** — {ld_txt}
|
| 729 |
|
| 730 |
-
##
|
| 731 |
-
|
|
| 732 |
-
|------
|
| 733 |
-
{
|
| 734 |
|
| 735 |
-
|
|
|
|
|
|
|
|
|
|
| 736 |
|
| 737 |
-
##
|
| 738 |
-
|
| 739 |
-
|
| 740 |
-
|
| 741 |
-
|
| 742 |
-
## Top 5 Samples (Highest GEBV)
|
| 743 |
-
| Rank | Sample | Observed | GEBV |
|
| 744 |
-
|------|--------|----------|------|
|
| 745 |
-
{top5_samples}
|
| 746 |
-
|
| 747 |
-
## Output Files in ZIP
|
| 748 |
-
- `results/all_model_predictions.csv`
|
| 749 |
-
- `results/mta_associations_<Model>.csv` (×5)
|
| 750 |
-
- `results/chromosome_summary.csv`
|
| 751 |
-
- `results/qc_summary.csv`
|
| 752 |
- `results/plots/manhattan_plot.png`
|
| 753 |
- `results/plots/qq_plot.png`
|
| 754 |
- `results/plots/ld_decay.png`
|
| 755 |
-
- `results/plots/
|
| 756 |
-
- `results/plots/
|
| 757 |
-
- `results/plots/top_marker_effects.png`
|
| 758 |
"""
|
| 759 |
-
return summary, man_path, qq_path, ld_path,
|
| 760 |
|
| 761 |
except Exception as e:
|
| 762 |
import traceback
|
| 763 |
-
return f"## Error\n```\n{e}\n\n{traceback.format_exc()}\n```",
|
|
|
|
| 764 |
|
| 765 |
|
| 766 |
-
#
|
| 767 |
-
# HTML / CSS
|
| 768 |
-
#
|
| 769 |
-
|
| 770 |
<style>
|
| 771 |
-
|
| 772 |
-
|
| 773 |
-
|
| 774 |
-
|
| 775 |
-
|
| 776 |
-
|
| 777 |
-
|
| 778 |
-
|
| 779 |
-
|
| 780 |
-
|
| 781 |
-
|
| 782 |
-
|
| 783 |
-
|
| 784 |
-
|
| 785 |
-
|
| 786 |
-
|
| 787 |
-
|
| 788 |
-
|
| 789 |
-
|
| 790 |
-
|
| 791 |
-
|
| 792 |
-
|
| 793 |
-
|
| 794 |
-
|
| 795 |
-
|
| 796 |
-
|
| 797 |
-
|
| 798 |
-
|
| 799 |
-
|
| 800 |
-
|
| 801 |
-
|
| 802 |
-
|
| 803 |
-
|
| 804 |
-
|
| 805 |
-
|
| 806 |
-
|
| 807 |
-
|
| 808 |
-
|
| 809 |
-
|
| 810 |
-
|
| 811 |
-
|
| 812 |
-
|
| 813 |
-
|
| 814 |
-
|
| 815 |
-
|
| 816 |
-
|
| 817 |
-
|
| 818 |
-
|
| 819 |
-
|
| 820 |
-
|
| 821 |
-
|
| 822 |
-
|
| 823 |
-
|
| 824 |
-
|
| 825 |
-
|
| 826 |
-
|
| 827 |
-
|
| 828 |
-
|
| 829 |
-
|
| 830 |
-
|
| 831 |
-
|
| 832 |
-
|
| 833 |
-
|
| 834 |
-
}
|
| 835 |
-
|
| 836 |
-
|
| 837 |
-
|
| 838 |
-
|
| 839 |
-
|
| 840 |
-
|
| 841 |
-
|
| 842 |
-
|
| 843 |
-
|
| 844 |
-
|
| 845 |
-
|
| 846 |
-
|
| 847 |
-
|
| 848 |
-
|
| 849 |
-
|
| 850 |
-
|
| 851 |
-
|
| 852 |
-
.
|
| 853 |
-
|
| 854 |
-
|
| 855 |
-
|
| 856 |
-
|
| 857 |
-
|
| 858 |
-
|
| 859 |
-
|
| 860 |
-
|
| 861 |
-
|
| 862 |
-
|
| 863 |
-
|
| 864 |
-
|
| 865 |
-
|
| 866 |
-
|
| 867 |
-
|
| 868 |
-
|
| 869 |
-
|
| 870 |
-
|
| 871 |
-
|
| 872 |
-
|
| 873 |
-
|
| 874 |
-
|
| 875 |
-
|
| 876 |
-
|
| 877 |
-
|
| 878 |
-
|
| 879 |
-
|
| 880 |
-
|
| 881 |
-
|
| 882 |
-
|
| 883 |
-
|
| 884 |
-
|
| 885 |
-
|
| 886 |
-
|
| 887 |
-
|
| 888 |
-
|
| 889 |
-
|
| 890 |
-
|
| 891 |
-
|
| 892 |
-
|
| 893 |
-
|
| 894 |
-
|
| 895 |
-
|
| 896 |
-
|
| 897 |
-
|
| 898 |
-
|
| 899 |
-
|
| 900 |
-
|
| 901 |
-
|
| 902 |
-
|
| 903 |
-
|
| 904 |
-
|
| 905 |
-
|
| 906 |
-
|
| 907 |
-
|
| 908 |
-
|
| 909 |
-
|
| 910 |
-
|
| 911 |
-
|
| 912 |
-
|
| 913 |
-
|
| 914 |
-
|
| 915 |
-
|
| 916 |
-
|
| 917 |
-
|
| 918 |
-
|
| 919 |
-
|
| 920 |
-
|
| 921 |
-
|
| 922 |
-
|
| 923 |
-
|
| 924 |
-
|
| 925 |
-
|
| 926 |
-
|
| 927 |
-
|
| 928 |
-
|
| 929 |
-
|
| 930 |
-
|
| 931 |
-
|
| 932 |
-
|
| 933 |
-
|
| 934 |
-
|
| 935 |
-
|
| 936 |
-
|
| 937 |
-
|
| 938 |
-
|
| 939 |
-
|
| 940 |
-
|
| 941 |
-
|
| 942 |
-
|
| 943 |
-
|
| 944 |
-
|
| 945 |
-
|
| 946 |
-
|
| 947 |
-
|
| 948 |
-
|
| 949 |
-
|
| 950 |
-
|
| 951 |
-
|
| 952 |
-
|
| 953 |
-
|
| 954 |
-
|
| 955 |
-
|
| 956 |
-
|
| 957 |
-
|
| 958 |
-
|
| 959 |
-
|
| 960 |
-
|
| 961 |
-
|
| 962 |
-
|
| 963 |
-
|
| 964 |
-
|
| 965 |
-
|
| 966 |
-
|
| 967 |
-
|
| 968 |
-
|
| 969 |
-
|
| 970 |
-
|
| 971 |
-
|
| 972 |
-
|
| 973 |
-
|
| 974 |
-
|
| 975 |
-
|
| 976 |
-
|
| 977 |
-
|
| 978 |
-
|
| 979 |
-
|
| 980 |
-
|
| 981 |
-
|
| 982 |
-
|
| 983 |
-
|
| 984 |
-
|
| 985 |
-
|
| 986 |
-
|
| 987 |
-
|
| 988 |
-
|
| 989 |
-
|
| 990 |
-
|
| 991 |
-
|
| 992 |
-
|
| 993 |
-
|
| 994 |
-
|
| 995 |
-
|
| 996 |
-
|
| 997 |
-
|
| 998 |
-
|
| 999 |
-
|
| 1000 |
-
|
| 1001 |
-
|
| 1002 |
-
|
| 1003 |
-
|
| 1004 |
-
|
| 1005 |
-
|
| 1006 |
-
|
| 1007 |
-
|
| 1008 |
-
|
| 1009 |
-
|
| 1010 |
-
|
| 1011 |
-
|
| 1012 |
-
|
| 1013 |
-
|
| 1014 |
-
|
| 1015 |
-
|
| 1016 |
-
|
| 1017 |
-
|
| 1018 |
-
|
| 1019 |
-
|
| 1020 |
-
|
| 1021 |
-
|
| 1022 |
-
|
| 1023 |
-
|
| 1024 |
-
|
| 1025 |
-
|
| 1026 |
-
|
| 1027 |
-
|
| 1028 |
-
|
| 1029 |
-
|
| 1030 |
-
|
| 1031 |
-
|
| 1032 |
-
|
| 1033 |
-
|
| 1034 |
-
|
| 1035 |
-
|
| 1036 |
-
|
| 1037 |
-
|
| 1038 |
-
|
| 1039 |
-
|
| 1040 |
-
|
| 1041 |
-
|
| 1042 |
-
|
| 1043 |
-
|
| 1044 |
-
|
| 1045 |
-
|
| 1046 |
-
|
| 1047 |
-
|
| 1048 |
-
|
| 1049 |
-
|
| 1050 |
-
|
| 1051 |
-
|
| 1052 |
-
|
| 1053 |
-
|
| 1054 |
-
|
| 1055 |
-
|
| 1056 |
-
|
| 1057 |
-
|
| 1058 |
-
|
| 1059 |
-
font-size: 11px;
|
| 1060 |
-
color: var(--muted);
|
| 1061 |
-
margin-top: 4px;
|
| 1062 |
-
display: block;
|
| 1063 |
-
}
|
| 1064 |
-
|
| 1065 |
-
/* ── Gradio overrides ── */
|
| 1066 |
-
.gr-box, .gr-panel, .gr-form, .gr-block,
|
| 1067 |
-
.gradio-container .wrap, .gradio-container .gap,
|
| 1068 |
-
.gradio-container .block { background: transparent !important; border: none !important; }
|
| 1069 |
-
.gradio-container label { color: var(--text) !important; font-family: 'Syne', sans-serif !important; }
|
| 1070 |
-
.gradio-container .gr-input, .gradio-container input,
|
| 1071 |
-
.gradio-container textarea, .gradio-container select {
|
| 1072 |
-
background: var(--surface) !important;
|
| 1073 |
-
border: 1px solid var(--border) !important;
|
| 1074 |
-
color: var(--text) !important;
|
| 1075 |
-
border-radius: 8px !important;
|
| 1076 |
-
}
|
| 1077 |
-
.gradio-container .output-markdown { background: transparent !important; }
|
| 1078 |
-
footer { display: none !important; }
|
| 1079 |
-
.gradio-container .built-with { display: none !important; }
|
| 1080 |
</style>
|
| 1081 |
"""
|
| 1082 |
|
| 1083 |
HERO_HTML = """
|
| 1084 |
-
<div class="
|
| 1085 |
-
<div class="
|
| 1086 |
-
<h1 class="
|
| 1087 |
-
<p class="
|
| 1088 |
-
<div class="
|
| 1089 |
-
<span class="
|
| 1090 |
-
<span class="
|
| 1091 |
-
<span class="
|
| 1092 |
-
<span class="
|
| 1093 |
-
<span class="
|
| 1094 |
-
<span class="
|
| 1095 |
</div>
|
| 1096 |
</div>
|
| 1097 |
"""
|
| 1098 |
|
| 1099 |
-
|
| 1100 |
-
<div class="
|
| 1101 |
-
<div class="
|
| 1102 |
-
<span class="col
|
| 1103 |
-
<span class="col
|
| 1104 |
-
<span class="col
|
| 1105 |
-
<span class="col
|
| 1106 |
-
<span class="col
|
| 1107 |
-
<span class="
|
| 1108 |
-
|
| 1109 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1110 |
</div>
|
| 1111 |
"""
|
| 1112 |
|
| 1113 |
-
|
| 1114 |
-
<div class="
|
| 1115 |
<div class="pipeline">
|
| 1116 |
-
<div class="pipe-step"><span class="pipe-num">01</span><span class="pipe-name">QC
|
| 1117 |
<div class="pipe-step"><span class="pipe-num">02</span><span class="pipe-name">GWAS</span></div>
|
| 1118 |
<div class="pipe-step"><span class="pipe-num">03</span><span class="pipe-name">QQ / LD</span></div>
|
| 1119 |
-
<div class="pipe-step"><span class="pipe-num">04</span><span class="pipe-name">
|
| 1120 |
-
<div class="pipe-step"><span class="pipe-num">05</span><span class="pipe-name">
|
| 1121 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1122 |
</div>
|
| 1123 |
"""
|
| 1124 |
|
| 1125 |
-
#
|
| 1126 |
# GRADIO APP
|
| 1127 |
-
#
|
| 1128 |
-
with gr.Blocks(css=
|
| 1129 |
|
| 1130 |
gr.HTML(HERO_HTML)
|
| 1131 |
|
| 1132 |
with gr.Row():
|
| 1133 |
-
# ── LEFT
|
| 1134 |
-
with gr.Column(scale=1, min_width=
|
| 1135 |
-
gr.HTML(
|
| 1136 |
-
gr.HTML('<div class="
|
| 1137 |
-
|
| 1138 |
-
input_file = gr.File(
|
| 1139 |
-
label="CSV Input File",
|
| 1140 |
-
file_types=[".csv"])
|
| 1141 |
|
|
|
|
| 1142 |
target_markers = gr.Slider(
|
| 1143 |
-
|
| 1144 |
-
label="Target Markers
|
| 1145 |
-
info="
|
| 1146 |
|
| 1147 |
with gr.Row(elem_classes=["run-btn"]):
|
| 1148 |
-
|
| 1149 |
|
| 1150 |
-
gr.HTML(
|
| 1151 |
|
| 1152 |
-
# ── RIGHT
|
| 1153 |
with gr.Column(scale=2):
|
| 1154 |
-
gr.HTML('<div class="
|
| 1155 |
-
with gr.Column(elem_classes=["
|
| 1156 |
-
|
| 1157 |
-
value="*Results will appear here after analysis…*")
|
| 1158 |
|
| 1159 |
# ── PLOTS ──
|
| 1160 |
-
gr.HTML('<div class="
|
| 1161 |
|
| 1162 |
-
gr.
|
| 1163 |
-
|
|
|
|
| 1164 |
|
| 1165 |
with gr.Row():
|
| 1166 |
-
with gr.Column():
|
| 1167 |
-
gr.HTML('<div class="plot-
|
| 1168 |
-
|
| 1169 |
-
with gr.Column():
|
| 1170 |
-
gr.HTML('<div class="plot-
|
| 1171 |
-
|
| 1172 |
|
| 1173 |
with gr.Row():
|
| 1174 |
-
with gr.Column():
|
| 1175 |
-
gr.HTML('<div class="plot-
|
| 1176 |
-
|
| 1177 |
-
with gr.Column():
|
| 1178 |
-
gr.HTML('<div class="plot-
|
| 1179 |
-
|
| 1180 |
|
| 1181 |
# ── DOWNLOAD ──
|
| 1182 |
-
gr.HTML('<div class="
|
| 1183 |
with gr.Row():
|
| 1184 |
with gr.Column(scale=1):
|
| 1185 |
-
gr.HTML(
|
| 1186 |
-
|
| 1187 |
-
|
| 1188 |
-
|
| 1189 |
-
📊 all_model_predictions.csv<br>
|
| 1190 |
-
🧬 mta_associations_×5.csv<br>
|
| 1191 |
-
🗺️ chromosome_summary.csv<br>
|
| 1192 |
-
🔬 qc_summary.csv<br>
|
| 1193 |
-
🖼️ 6 publication-quality plots
|
| 1194 |
-
</div>
|
| 1195 |
-
</div>
|
| 1196 |
-
""")
|
| 1197 |
-
with gr.Row(elem_classes=["dl-btn"]):
|
| 1198 |
-
download_output = gr.File(label="⬇ Download All Results (ZIP)")
|
| 1199 |
-
with gr.Column(scale=2):
|
| 1200 |
pass
|
| 1201 |
|
| 1202 |
-
|
| 1203 |
-
run_button.click(
|
| 1204 |
fn=run_mta_analysis,
|
| 1205 |
inputs=[input_file, target_markers],
|
| 1206 |
-
outputs=[
|
| 1207 |
-
|
| 1208 |
|
| 1209 |
if __name__ == "__main__":
|
| 1210 |
app.launch(share=True, show_error=True)
|
|
|
|
| 1 |
# -*- coding: utf-8 -*-
|
| 2 |
"""
|
| 3 |
+
MTA Analysis Tool v5.0
|
| 4 |
+
White theme · Dark-blue text · GWAS only · Bug-fixed · Attractive UI
|
| 5 |
"""
|
| 6 |
|
| 7 |
import gradio as gr
|
|
|
|
| 11 |
matplotlib.use('Agg')
|
| 12 |
import matplotlib.pyplot as plt
|
| 13 |
import matplotlib.patches as mpatches
|
| 14 |
+
from matplotlib.collections import LineCollection
|
|
|
|
| 15 |
import seaborn as sns
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
from scipy import stats
|
| 17 |
import os, warnings, tempfile, zipfile
|
| 18 |
warnings.filterwarnings('ignore')
|
| 19 |
|
| 20 |
+
# ══════════════════════════════════════════════════════════════
|
| 21 |
+
# PLOT THEME — clean white, navy/blue palette
|
| 22 |
+
# ══════════════════════════════════════════════════════════════
|
| 23 |
+
BG = "#FFFFFF"
|
| 24 |
+
PANEL = "#F8FAFD"
|
| 25 |
+
GRID_C = "#E2EAF4"
|
| 26 |
+
TEXT_C = "#0D2B5E" # dark navy
|
| 27 |
+
MUTED_C = "#5A7599"
|
| 28 |
+
ACCENT = "#1A56DB" # royal blue
|
| 29 |
+
RED_C = "#E53E3E" # significance red
|
| 30 |
+
GOLD_C = "#D97706" # suggestive amber
|
| 31 |
+
GREEN_C = "#0D9488" # teal green
|
| 32 |
+
PURPLE_C = "#7C3AED"
|
| 33 |
|
| 34 |
CHROM_PALETTE = [
|
| 35 |
+
"#1A56DB","#0D9488","#E53E3E","#7C3AED","#D97706",
|
| 36 |
+
"#0891B2","#059669","#DC2626","#6D28D9","#B45309",
|
| 37 |
+
"#2563EB","#10B981","#EF4444","#8B5CF6","#F59E0B",
|
| 38 |
+
"#0284C7","#34D399","#F87171","#A78BFA","#FCD34D",
|
| 39 |
+
"#1D4ED8","#047857",
|
| 40 |
]
|
| 41 |
|
| 42 |
+
def set_white_style():
|
| 43 |
plt.rcParams.update({
|
| 44 |
+
'figure.facecolor' : BG,
|
| 45 |
+
'axes.facecolor' : PANEL,
|
| 46 |
+
'axes.edgecolor' : GRID_C,
|
| 47 |
+
'axes.labelcolor' : TEXT_C,
|
| 48 |
+
'axes.titlecolor' : TEXT_C,
|
| 49 |
+
'xtick.color' : TEXT_C,
|
| 50 |
+
'ytick.color' : TEXT_C,
|
| 51 |
+
'text.color' : TEXT_C,
|
| 52 |
+
'grid.color' : GRID_C,
|
| 53 |
+
'grid.linewidth' : 0.8,
|
| 54 |
+
'figure.dpi' : 150,
|
| 55 |
+
'font.family' : 'DejaVu Sans',
|
| 56 |
+
'axes.spines.top' : False,
|
| 57 |
'axes.spines.right': False,
|
| 58 |
+
'legend.framealpha': 0.95,
|
| 59 |
+
'legend.edgecolor' : GRID_C,
|
| 60 |
})
|
| 61 |
|
| 62 |
+
|
| 63 |
+
# ══════════════════════════════════════════════════════════════
|
| 64 |
+
# PLOT 1 — MANHATTAN
|
| 65 |
+
# ══════════════════════════════════════════════════════════════
|
| 66 |
+
def plot_manhattan(marker_names, chromosomes, p_values, sig_set, bonf_thresh, save_path):
|
| 67 |
+
set_white_style()
|
| 68 |
|
| 69 |
unique_chroms = sorted(set(chromosomes),
|
| 70 |
key=lambda x: (int(x) if x.isdigit() else 999, x))
|
|
|
|
| 73 |
GAP = max(8, len(marker_names) // 150)
|
| 74 |
x_pos = np.zeros(len(marker_names))
|
| 75 |
chrom_centers, chrom_to_idx = {}, {}
|
| 76 |
+
for i, c in enumerate(chromosomes):
|
|
|
|
| 77 |
chrom_to_idx.setdefault(c, []).append(i)
|
| 78 |
|
| 79 |
offset = 0
|
| 80 |
+
for ch in unique_chroms:
|
| 81 |
+
idxs = chrom_to_idx.get(ch, [])
|
| 82 |
if not idxs: continue
|
| 83 |
+
for r, idx in enumerate(idxs):
|
| 84 |
+
x_pos[idx] = offset + r
|
| 85 |
+
chrom_centers[ch] = offset + (len(idxs) - 1) / 2
|
| 86 |
offset += len(idxs) + GAP
|
| 87 |
|
| 88 |
+
fig = plt.figure(figsize=(22, 7), facecolor=BG)
|
| 89 |
+
ax = fig.add_subplot(111, facecolor=PANEL)
|
| 90 |
|
| 91 |
+
# Alternating chromosome bands
|
| 92 |
+
for ci, ch in enumerate(unique_chroms):
|
| 93 |
+
idxs = chrom_to_idx.get(ch, [])
|
| 94 |
if not idxs: continue
|
| 95 |
x0 = x_pos[idxs[0]] - 0.5
|
| 96 |
x1 = x_pos[idxs[-1]] + 0.5
|
| 97 |
+
if ci % 2 == 0:
|
| 98 |
+
ax.axvspan(x0, x1, color='#EBF2FF', alpha=0.55, zorder=0)
|
| 99 |
|
| 100 |
+
for ci, ch in enumerate(unique_chroms):
|
| 101 |
+
idxs = chrom_to_idx.get(ch, [])
|
|
|
|
| 102 |
if not idxs: continue
|
| 103 |
col = CHROM_PALETTE[ci % len(CHROM_PALETTE)]
|
| 104 |
|
| 105 |
+
normal = [i for i in idxs if i not in sig_set]
|
| 106 |
+
sel = [i for i in idxs if i in sig_set]
|
| 107 |
|
| 108 |
if normal:
|
| 109 |
ax.scatter(x_pos[normal], log_p[normal],
|
| 110 |
+
c=col, s=12, alpha=0.60, linewidths=0, zorder=2)
|
| 111 |
if sel:
|
| 112 |
+
# shadow glow
|
| 113 |
ax.scatter(x_pos[sel], log_p[sel],
|
| 114 |
+
c=RED_C, s=260, alpha=0.15, linewidths=0, zorder=3)
|
| 115 |
ax.scatter(x_pos[sel], log_p[sel],
|
| 116 |
+
c=RED_C, s=70, alpha=1.0,
|
| 117 |
+
edgecolors='white', linewidths=1.0,
|
| 118 |
marker='D', zorder=4)
|
| 119 |
|
| 120 |
# Threshold lines
|
| 121 |
+
ax.axhline(bonf_thresh, color=RED_C, ls='--', lw=1.8, alpha=0.85, zorder=5)
|
| 122 |
+
ax.text(offset * 0.005, bonf_thresh + log_p.max()*0.02,
|
| 123 |
+
f'Bonferroni α=0.05', color=RED_C, fontsize=9,
|
| 124 |
+
fontweight='bold', va='bottom')
|
| 125 |
+
|
| 126 |
+
sugg = -np.log10(1e-5)
|
| 127 |
+
if sugg < bonf_thresh:
|
| 128 |
+
ax.axhline(sugg, color=GOLD_C, ls=':', lw=1.5, alpha=0.8, zorder=5)
|
| 129 |
+
ax.text(offset * 0.005, sugg + log_p.max()*0.02,
|
| 130 |
+
'Suggestive 1×10⁻⁵', color=GOLD_C, fontsize=9,
|
| 131 |
+
fontweight='bold', va='bottom')
|
| 132 |
|
|
|
|
| 133 |
xtick_pos = [chrom_centers[c] for c in unique_chroms if c in chrom_centers]
|
| 134 |
xtick_lab = [f'Chr {c}' for c in unique_chroms if c in chrom_centers]
|
| 135 |
ax.set_xticks(xtick_pos)
|
| 136 |
ax.set_xticklabels(xtick_lab,
|
| 137 |
+
fontsize=8.5 if len(unique_chroms) > 12 else 10,
|
| 138 |
rotation=45 if len(unique_chroms) > 14 else 0,
|
| 139 |
+
ha='center', color=TEXT_C, fontweight='600')
|
| 140 |
ax.set_xlim(-GAP, offset)
|
| 141 |
+
ax.set_ylim(bottom=0, top=log_p.max() * 1.16)
|
| 142 |
|
| 143 |
+
ax.set_ylabel('−log₁₀(P-value)', fontsize=13, color=TEXT_C,
|
| 144 |
+
fontweight='bold', labelpad=10)
|
| 145 |
+
ax.set_xlabel('Chromosome', fontsize=13, color=TEXT_C,
|
| 146 |
+
fontweight='bold', labelpad=10)
|
| 147 |
ax.set_title('Genome-Wide Association Study · Manhattan Plot',
|
| 148 |
+
fontsize=17, color=TEXT_C, fontweight='bold', pad=20)
|
| 149 |
|
| 150 |
+
ax.yaxis.grid(True, color=GRID_C, linewidth=0.8, alpha=1.0)
|
|
|
|
| 151 |
ax.set_axisbelow(True)
|
| 152 |
+
ax.tick_params(axis='both', colors=TEXT_C, length=4)
|
| 153 |
|
| 154 |
+
h_sig = mpatches.Patch(color=RED_C, label='Significant markers')
|
| 155 |
+
h_bonf = plt.Line2D([0],[0], color=RED_C, ls='--', lw=1.8, label='Bonferroni threshold')
|
| 156 |
+
h_sugg = plt.Line2D([0],[0], color=GOLD_C, ls=':', lw=1.5, label='Suggestive (1×10⁻⁵)')
|
| 157 |
+
ax.legend(handles=[h_sig, h_bonf, h_sugg], fontsize=10,
|
| 158 |
+
loc='upper right', facecolor=BG, edgecolor=GRID_C)
|
|
|
|
|
|
|
| 159 |
|
| 160 |
+
# Top annotation: highlight strongest hit per chrom
|
| 161 |
+
for ch in unique_chroms:
|
| 162 |
+
idxs = chrom_to_idx.get(ch, [])
|
| 163 |
+
if not idxs: continue
|
| 164 |
+
best = max(idxs, key=lambda i: log_p[i])
|
| 165 |
+
if log_p[best] >= bonf_thresh:
|
| 166 |
+
ax.annotate(marker_names[best],
|
| 167 |
+
xy=(x_pos[best], log_p[best]),
|
| 168 |
+
xytext=(0, 10), textcoords='offset points',
|
| 169 |
+
fontsize=6.5, color=TEXT_C, ha='center',
|
| 170 |
+
arrowprops=dict(arrowstyle='-', color=MUTED_C, lw=0.6))
|
| 171 |
+
|
| 172 |
+
plt.tight_layout(pad=1.8)
|
| 173 |
+
plt.savefig(save_path, dpi=200, bbox_inches='tight', facecolor=BG)
|
| 174 |
plt.close(fig)
|
| 175 |
|
| 176 |
|
| 177 |
+
# ══════════════════════════════════════════════════════════════
|
| 178 |
# PLOT 2 — QQ PLOT
|
| 179 |
+
# ══════════════════════════════════════════════════════════════
|
| 180 |
def plot_qq(p_values, save_path):
|
| 181 |
+
set_white_style()
|
| 182 |
|
| 183 |
+
pv = np.clip(np.array(p_values)[~np.isnan(p_values)], 1e-300, 1.0)
|
| 184 |
+
n = len(pv)
|
| 185 |
obs = np.sort(pv)
|
| 186 |
exp = np.linspace(1/n, 1, n)
|
| 187 |
log_obs = -np.log10(obs)
|
| 188 |
log_exp = -np.log10(exp)
|
| 189 |
|
| 190 |
+
ci_up = -np.log10(stats.beta.ppf(0.025, np.arange(1,n+1), np.arange(n,0,-1)))
|
| 191 |
+
ci_lo = np.maximum(
|
| 192 |
+
-np.log10(stats.beta.ppf(0.975, np.arange(1,n+1), np.arange(n,0,-1))), 0)
|
| 193 |
|
| 194 |
chi2 = stats.chi2.ppf(1 - pv, df=1)
|
| 195 |
lam = np.median(chi2) / stats.chi2.ppf(0.5, df=1)
|
| 196 |
|
| 197 |
+
fig, ax = plt.subplots(figsize=(7, 7), facecolor=BG)
|
| 198 |
+
ax.set_facecolor(PANEL)
|
| 199 |
|
| 200 |
ax.fill_between(log_exp, ci_lo, ci_up,
|
| 201 |
+
color=ACCENT, alpha=0.12, label='95% Confidence Band')
|
| 202 |
+
|
| 203 |
+
sc = ax.scatter(log_exp, log_obs, c=log_obs, cmap='RdYlBu_r',
|
| 204 |
+
s=14, alpha=0.80, linewidths=0, zorder=3)
|
| 205 |
+
plt.colorbar(sc, ax=ax, shrink=0.75, label='−log₁₀(P)')
|
| 206 |
+
|
| 207 |
+
maxv = max(log_obs.max(), log_exp.max()) * 1.06
|
| 208 |
+
ax.plot([0, maxv], [0, maxv], color=MUTED_C, lw=1.8, ls='--',
|
| 209 |
+
label='Expected null', zorder=2)
|
| 210 |
+
|
| 211 |
+
lam_col = GREEN_C if lam < 1.05 else (GOLD_C if lam < 1.10 else RED_C)
|
| 212 |
+
lam_lbl = ("Well-calibrated" if lam < 1.05
|
| 213 |
+
else "Minor inflation" if lam < 1.10 else "Significant inflation")
|
| 214 |
+
ax.text(0.05, 0.95,
|
| 215 |
+
f'λ = {lam:.4f}\n{lam_lbl}',
|
| 216 |
+
transform=ax.transAxes, fontsize=11, va='top', color=lam_col,
|
| 217 |
+
fontweight='bold',
|
| 218 |
+
bbox=dict(boxstyle='round,pad=0.5', fc=BG, ec=lam_col, lw=1.5, alpha=0.9))
|
| 219 |
+
|
| 220 |
+
ax.set_xlabel('Expected −log₁₀(P)', fontsize=13, color=TEXT_C, fontweight='bold')
|
| 221 |
+
ax.set_ylabel('Observed −log₁₀(P)', fontsize=13, color=TEXT_C, fontweight='bold')
|
| 222 |
+
ax.set_title('QQ Plot · Genomic Inflation Check',
|
| 223 |
+
fontsize=15, color=TEXT_C, fontweight='bold', pad=16)
|
| 224 |
ax.set_xlim(0, maxv); ax.set_ylim(0, maxv)
|
| 225 |
+
ax.legend(fontsize=10, facecolor=BG, edgecolor=GRID_C)
|
| 226 |
+
ax.yaxis.grid(True, color=GRID_C, lw=0.8)
|
| 227 |
+
ax.xaxis.grid(True, color=GRID_C, lw=0.8)
|
| 228 |
+
ax.tick_params(colors=TEXT_C)
|
| 229 |
|
| 230 |
+
plt.tight_layout(pad=1.8)
|
| 231 |
+
plt.savefig(save_path, dpi=200, bbox_inches='tight', facecolor=BG)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 232 |
plt.close(fig)
|
| 233 |
return lam
|
| 234 |
|
| 235 |
|
| 236 |
+
# ══════════════════════════════════════════════════════════════
|
| 237 |
# PLOT 3 — LD DECAY
|
| 238 |
+
# ══════════════════════════════════════════════════════════════
|
| 239 |
def plot_ld_decay(genotypes, chromosomes, save_path, max_m=250):
|
| 240 |
+
set_white_style()
|
| 241 |
|
| 242 |
unique_chroms = sorted(set(chromosomes),
|
| 243 |
key=lambda x: (int(x) if x.isdigit() else 999, x))
|
| 244 |
+
all_d, all_r2, chrom_mean = [], [], {}
|
|
|
|
| 245 |
|
| 246 |
+
for ch in unique_chroms:
|
| 247 |
+
idxs = [i for i,c in enumerate(chromosomes) if c == ch]
|
| 248 |
if len(idxs) < 4: continue
|
| 249 |
if len(idxs) > max_m:
|
| 250 |
idxs = sorted(np.random.choice(idxs, max_m, replace=False))
|
| 251 |
+
G = genotypes[:, idxs].copy()
|
| 252 |
+
std = G.std(axis=0); std[std==0] = 1
|
| 253 |
+
G = (G - G.mean(axis=0)) / std
|
| 254 |
+
nm = G.shape[1]
|
| 255 |
dl, rl = [], []
|
| 256 |
+
for i in range(nm-1):
|
| 257 |
for j in range(i+1, min(i+60, nm)):
|
| 258 |
r = np.corrcoef(G[:,i], G[:,j])[0,1]
|
| 259 |
r2 = r**2 if not np.isnan(r) else 0
|
| 260 |
+
dl.append(j-i); rl.append(r2)
|
| 261 |
if dl:
|
| 262 |
all_d.extend(dl); all_r2.extend(rl)
|
| 263 |
+
chrom_mean[ch] = np.mean(rl)
|
| 264 |
|
| 265 |
+
fig, axes = plt.subplots(1, 2, figsize=(16, 6), facecolor=BG)
|
| 266 |
|
| 267 |
# ── Left: decay curve ──
|
| 268 |
+
ax = axes[0]; ax.set_facecolor(PANEL)
|
| 269 |
if all_d:
|
| 270 |
+
all_d = np.array(all_d)
|
| 271 |
+
all_r2 = np.array(all_r2)
|
| 272 |
+
max_d = min(int(all_d.max()), 50)
|
| 273 |
+
bins = np.arange(1, max_d+1)
|
| 274 |
mu, se = [], []
|
| 275 |
for b in bins:
|
| 276 |
m = all_d == b
|
|
|
|
| 282 |
mu = np.array(mu); se = np.array(se)
|
| 283 |
v = ~np.isnan(mu)
|
| 284 |
|
| 285 |
+
ax.fill_between(bins[v],
|
| 286 |
+
np.clip(mu[v]-se[v], 0, 1),
|
| 287 |
+
np.clip(mu[v]+se[v], 0, 1),
|
| 288 |
+
color=ACCENT, alpha=0.15, label='±1 SE')
|
| 289 |
|
| 290 |
+
# gradient line
|
| 291 |
+
pts = np.array([bins[v], mu[v]]).T.reshape(-1, 1, 2)
|
| 292 |
+
segs = np.concatenate([pts[:-1], pts[1:]], axis=1)
|
| 293 |
+
lc = LineCollection(segs, cmap='Blues', linewidth=2.8, zorder=4)
|
|
|
|
| 294 |
lc.set_array(mu[v])
|
| 295 |
ax.add_collection(lc)
|
| 296 |
+
ax.scatter(bins[v], mu[v], c=mu[v], cmap='Blues',
|
| 297 |
+
s=22, zorder=5, linewidths=0.5,
|
| 298 |
+
edgecolors=MUTED_C)
|
| 299 |
|
| 300 |
+
ax.axhline(0.2, color=RED_C, ls='--', lw=1.3, alpha=0.8, label='r²=0.2 threshold')
|
| 301 |
|
| 302 |
+
start = mu[v][0] if len(mu[v]) > 0 else 1.0
|
|
|
|
|
|
|
| 303 |
for i, r2 in enumerate(mu[v]):
|
| 304 |
+
if r2 <= start/2:
|
| 305 |
+
ax.axvline(bins[v][i], color=GOLD_C, ls='--', lw=1.3, alpha=0.9,
|
| 306 |
+
label=f'Half-decay at d={bins[v][i]}')
|
| 307 |
+
break
|
| 308 |
+
|
| 309 |
+
ax.set_xlabel('Marker Distance (index)', fontsize=12, color=TEXT_C, fontweight='bold')
|
| 310 |
+
ax.set_ylabel('Mean r²', fontsize=12, color=TEXT_C, fontweight='bold')
|
| 311 |
+
ax.set_title('LD Decay Across Chromosomes', fontsize=14, color=TEXT_C,
|
| 312 |
+
fontweight='bold', pad=12)
|
| 313 |
+
ax.set_ylim(0, 1); ax.tick_params(colors=TEXT_C)
|
| 314 |
+
ax.yaxis.grid(True, color=GRID_C, lw=0.8)
|
| 315 |
+
ax.legend(fontsize=9, facecolor=BG, edgecolor=GRID_C)
|
| 316 |
|
| 317 |
# ── Right: per-chromosome bars ──
|
| 318 |
+
ax2 = axes[1]; ax2.set_facecolor(PANEL)
|
| 319 |
if chrom_mean:
|
| 320 |
+
cs = sorted(chrom_mean.keys(), key=lambda x: (int(x) if x.isdigit() else 999, x))
|
| 321 |
vals = [chrom_mean[c] for c in cs]
|
| 322 |
cols = [CHROM_PALETTE[i % len(CHROM_PALETTE)] for i in range(len(cs))]
|
| 323 |
bars = ax2.bar(range(len(cs)), vals, color=cols,
|
| 324 |
+
edgecolor='white', linewidth=0.8, alpha=0.88, width=0.65)
|
| 325 |
ax2.set_xticks(range(len(cs)))
|
| 326 |
ax2.set_xticklabels([f'Chr {c}' for c in cs],
|
| 327 |
rotation=45 if len(cs) > 10 else 0,
|
| 328 |
+
fontsize=8.5, ha='right', color=TEXT_C)
|
|
|
|
| 329 |
for bar, val in zip(bars, vals):
|
| 330 |
ax2.text(bar.get_x() + bar.get_width()/2,
|
| 331 |
bar.get_height() + 0.02,
|
| 332 |
f'{val:.2f}', ha='center', va='bottom',
|
| 333 |
+
fontsize=8, color=TEXT_C, fontweight='600')
|
| 334 |
+
ax2.set_xlabel('Chromosome', fontsize=12, color=TEXT_C, fontweight='bold')
|
| 335 |
+
ax2.set_ylabel('Mean r²', fontsize=12, color=TEXT_C, fontweight='bold')
|
| 336 |
+
ax2.set_title('Mean LD per Chromosome', fontsize=14, color=TEXT_C,
|
| 337 |
fontweight='bold', pad=12)
|
| 338 |
+
ax2.set_ylim(0, 1.15)
|
| 339 |
+
ax2.tick_params(colors=TEXT_C)
|
| 340 |
+
ax2.yaxis.grid(True, color=GRID_C, lw=0.8)
|
| 341 |
|
| 342 |
+
fig.suptitle('Linkage Disequilibrium (LD) Analysis',
|
| 343 |
+
fontsize=16, color=TEXT_C, fontweight='bold', y=1.01)
|
| 344 |
plt.tight_layout(pad=2)
|
| 345 |
+
plt.savefig(save_path, dpi=200, bbox_inches='tight', facecolor=BG)
|
| 346 |
plt.close(fig)
|
| 347 |
return chrom_mean
|
| 348 |
|
| 349 |
|
| 350 |
+
# ══════════════════════════════════════════════════════════════
|
| 351 |
+
# PLOT 4 — GWAS EFFECT SIZE VOLCANO
|
| 352 |
+
# ══════════════════════════════════════════════════════════════
|
| 353 |
+
def plot_volcano(marker_names, effects, p_values, bonf_thresh, save_path, top_n=10):
|
| 354 |
+
set_white_style()
|
| 355 |
+
|
| 356 |
+
log_p = -np.log10(np.array(p_values) + 1e-300)
|
| 357 |
+
sig_mask = log_p >= bonf_thresh
|
| 358 |
+
sug_mask = (log_p >= -np.log10(1e-5)) & ~sig_mask
|
| 359 |
+
|
| 360 |
+
fig, ax = plt.subplots(figsize=(10, 7), facecolor=BG)
|
| 361 |
+
ax.set_facecolor(PANEL)
|
| 362 |
+
|
| 363 |
+
# Non-significant
|
| 364 |
+
ns = ~sig_mask & ~sug_mask
|
| 365 |
+
ax.scatter(np.array(effects)[ns], log_p[ns],
|
| 366 |
+
c=MUTED_C, s=10, alpha=0.35, linewidths=0, zorder=1, label='Non-significant')
|
| 367 |
+
# Suggestive
|
| 368 |
+
if sug_mask.any():
|
| 369 |
+
ax.scatter(np.array(effects)[sug_mask], log_p[sug_mask],
|
| 370 |
+
c=GOLD_C, s=20, alpha=0.65, linewidths=0, zorder=2, label='Suggestive')
|
| 371 |
+
# Significant
|
| 372 |
+
if sig_mask.any():
|
| 373 |
+
ax.scatter(np.array(effects)[sig_mask], log_p[sig_mask],
|
| 374 |
+
c=RED_C, s=55, alpha=0.90,
|
| 375 |
+
edgecolors='white', linewidths=0.7,
|
| 376 |
+
zorder=3, label='Significant')
|
| 377 |
+
|
| 378 |
+
ax.axhline(bonf_thresh, color=RED_C, ls='--', lw=1.6, alpha=0.8)
|
| 379 |
+
ax.axhline(-np.log10(1e-5), color=GOLD_C, ls=':', lw=1.3, alpha=0.8)
|
| 380 |
+
ax.axvline(0, color=MUTED_C, lw=0.8, ls='-', alpha=0.4)
|
| 381 |
+
|
| 382 |
+
# Annotate top hits
|
| 383 |
+
top_idx = np.argsort(log_p)[-top_n:]
|
| 384 |
+
for i in top_idx:
|
| 385 |
+
if log_p[i] >= bonf_thresh:
|
| 386 |
+
ax.annotate(marker_names[i],
|
| 387 |
+
xy=(effects[i], log_p[i]),
|
| 388 |
+
xytext=(6, 3), textcoords='offset points',
|
| 389 |
+
fontsize=7, color=TEXT_C,
|
| 390 |
+
arrowprops=dict(arrowstyle='->', color=MUTED_C, lw=0.6))
|
| 391 |
+
|
| 392 |
+
ax.set_xlabel('Effect Size (β)', fontsize=13, color=TEXT_C, fontweight='bold')
|
| 393 |
+
ax.set_ylabel('−log₁₀(P-value)', fontsize=13, color=TEXT_C, fontweight='bold')
|
| 394 |
+
ax.set_title('GWAS Volcano Plot · Effect Size vs Significance',
|
| 395 |
+
fontsize=15, color=TEXT_C, fontweight='bold', pad=16)
|
| 396 |
+
ax.legend(fontsize=10, facecolor=BG, edgecolor=GRID_C)
|
| 397 |
+
ax.yaxis.grid(True, color=GRID_C, lw=0.8)
|
| 398 |
+
ax.xaxis.grid(True, color=GRID_C, lw=0.8)
|
| 399 |
+
ax.tick_params(colors=TEXT_C)
|
| 400 |
+
|
| 401 |
+
plt.tight_layout(pad=1.8)
|
| 402 |
+
plt.savefig(save_path, dpi=200, bbox_inches='tight', facecolor=BG)
|
| 403 |
plt.close(fig)
|
| 404 |
|
| 405 |
|
| 406 |
+
# ══════════════════════════════════════════════════════════════
|
| 407 |
+
# PLOT 5 — TOP GWAS HITS (bar chart)
|
| 408 |
+
# ══════════════════════════════════════════════════════════════
|
| 409 |
+
def plot_top_hits(marker_names, chromosomes, p_values, effects, bonf_thresh,
|
| 410 |
+
save_path, top_n=25):
|
| 411 |
+
set_white_style()
|
|
|
|
| 412 |
|
| 413 |
+
log_p = -np.log10(np.array(p_values) + 1e-300)
|
| 414 |
+
order = np.argsort(log_p)[-top_n:][::-1]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 415 |
|
| 416 |
+
unique_chroms = sorted(set(chromosomes),
|
| 417 |
+
key=lambda x: (int(x) if x.isdigit() else 999, x))
|
| 418 |
col_map = {c: CHROM_PALETTE[i % len(CHROM_PALETTE)]
|
| 419 |
+
for i,c in enumerate(unique_chroms)}
|
|
|
|
| 420 |
|
| 421 |
+
fig, axes = plt.subplots(1, 2, figsize=(16, 8), facecolor=BG)
|
|
|
|
|
|
|
| 422 |
|
| 423 |
+
# Left: −log10(p) bars
|
| 424 |
+
ax = axes[0]; ax.set_facecolor(PANEL)
|
| 425 |
+
labels = [f"{marker_names[i]} (Chr {chromosomes[i]})" for i in order]
|
| 426 |
+
vals = [log_p[i] for i in order]
|
| 427 |
+
cols = [col_map.get(chromosomes[i], ACCENT) for i in order]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 428 |
|
| 429 |
+
bars = ax.barh(range(len(order)), vals, color=cols,
|
| 430 |
+
edgecolor='white', linewidth=0.6, alpha=0.88, height=0.65)
|
| 431 |
+
ax.axvline(bonf_thresh, color=RED_C, ls='--', lw=1.5, alpha=0.9, label='Bonferroni')
|
| 432 |
+
ax.set_yticks(range(len(order)))
|
| 433 |
+
ax.set_yticklabels(labels, fontsize=8.5, color=TEXT_C)
|
| 434 |
+
ax.invert_yaxis()
|
| 435 |
+
ax.set_xlabel('−log₁₀(P-value)', fontsize=12, color=TEXT_C, fontweight='bold')
|
| 436 |
+
ax.set_title(f'Top {top_n} GWAS Hits', fontsize=14, color=TEXT_C,
|
| 437 |
+
fontweight='bold', pad=12)
|
| 438 |
+
ax.xaxis.grid(True, color=GRID_C, lw=0.8)
|
| 439 |
+
ax.tick_params(colors=TEXT_C)
|
| 440 |
+
ax.legend(fontsize=9, facecolor=BG, edgecolor=GRID_C)
|
| 441 |
+
for bar, val in zip(bars, vals):
|
| 442 |
+
ax.text(bar.get_width() + 0.05, bar.get_y() + bar.get_height()/2,
|
| 443 |
+
f'{val:.2f}', va='center', fontsize=8, color=TEXT_C)
|
| 444 |
+
|
| 445 |
+
# Right: effect size bars (positive=blue, negative=red)
|
| 446 |
+
ax2 = axes[1]; ax2.set_facecolor(PANEL)
|
| 447 |
+
eff_vals = [effects[i] for i in order]
|
| 448 |
+
eff_cols = [ACCENT if e >= 0 else RED_C for e in eff_vals]
|
| 449 |
+
ax2.barh(range(len(order)), eff_vals, color=eff_cols,
|
| 450 |
+
edgecolor='white', linewidth=0.6, alpha=0.85, height=0.65)
|
| 451 |
+
ax2.axvline(0, color=MUTED_C, lw=1.0, ls='-', alpha=0.5)
|
| 452 |
+
ax2.set_yticks(range(len(order)))
|
| 453 |
+
ax2.set_yticklabels(labels, fontsize=8.5, color=TEXT_C)
|
| 454 |
+
ax2.invert_yaxis()
|
| 455 |
+
ax2.set_xlabel('Effect Size (β)', fontsize=12, color=TEXT_C, fontweight='bold')
|
| 456 |
+
ax2.set_title('Effect Directions of Top Hits', fontsize=14, color=TEXT_C,
|
| 457 |
+
fontweight='bold', pad=12)
|
| 458 |
+
ax2.xaxis.grid(True, color=GRID_C, lw=0.8)
|
| 459 |
+
ax2.tick_params(colors=TEXT_C)
|
| 460 |
+
|
| 461 |
+
# Chromosome legend
|
| 462 |
handles = []
|
| 463 |
shown = set()
|
| 464 |
+
for i in order:
|
| 465 |
+
c = chromosomes[i]
|
| 466 |
if c not in shown:
|
| 467 |
+
handles.append(mpatches.Patch(color=col_map[c], label=f'Chr {c}'))
|
|
|
|
| 468 |
shown.add(c)
|
| 469 |
+
ax.legend(handles=handles + [plt.Line2D([0],[0], color=RED_C, ls='--',
|
| 470 |
+
lw=1.5, label='Bonferroni')],
|
| 471 |
+
fontsize=8, facecolor=BG, edgecolor=GRID_C, loc='lower right')
|
| 472 |
|
| 473 |
+
plt.tight_layout(pad=2)
|
| 474 |
+
plt.savefig(save_path, dpi=200, bbox_inches='tight', facecolor=BG)
|
| 475 |
plt.close(fig)
|
| 476 |
|
| 477 |
|
| 478 |
+
# ══════════════════════════════════════════════════════════════
|
| 479 |
+
# MAIN ANALYSIS (GWAS only — no GEBV)
|
| 480 |
+
# ══════════════════════════════════════════════════════════════
|
| 481 |
def run_mta_analysis(input_file, target_markers):
|
| 482 |
try:
|
| 483 |
if input_file is None:
|
|
|
|
| 489 |
for d in [results_dir, plots_dir]:
|
| 490 |
os.makedirs(d, exist_ok=True)
|
| 491 |
|
| 492 |
+
# ── LOAD ──────────────────────────────────
|
| 493 |
df = pd.read_csv(input_file, sep=',', header=0)
|
| 494 |
+
# Col 0=ID, Col 1=Chromosome, Col 2=Phenotype, Col 3+=Markers
|
| 495 |
+
# Row 0 = marker chromosome assignments, Row 1+ = samples
|
| 496 |
+
|
| 497 |
+
marker_cols = df.columns[3:].tolist()
|
| 498 |
+
chrom_info_row = df.iloc[0, 3:].values.astype(str)
|
| 499 |
chromosome_dict = {m: c for m, c in zip(marker_cols, chrom_info_row)}
|
| 500 |
|
| 501 |
+
df_data = df.iloc[1:].reset_index(drop=True)
|
| 502 |
+
sample_ids = df_data.iloc[:, 0].astype(str).values
|
| 503 |
+
phenotypes = pd.to_numeric(df_data.iloc[:, 2], errors='coerce').values
|
| 504 |
+
genotypes = df_data.iloc[:, 3:].apply(pd.to_numeric, errors='coerce').values
|
| 505 |
marker_names = marker_cols
|
| 506 |
|
| 507 |
+
unique_chroms = sorted(set(chrom_info_row),
|
| 508 |
+
key=lambda x: (int(x) if x.isdigit() else 999, x))
|
| 509 |
n_samples = len(sample_ids)
|
| 510 |
n_markers = len(marker_names)
|
| 511 |
|
| 512 |
+
# ── QC ────────────────────────────────────
|
| 513 |
miss_m = np.isnan(genotypes).sum(axis=0) / n_samples
|
| 514 |
miss_s = np.isnan(genotypes).sum(axis=1) / n_markers
|
| 515 |
maf = np.array([
|
|
|
|
| 526 |
mnames_qc = [marker_names[i] for i in range(n_markers) if qc_m[i]]
|
| 527 |
chrom_qc = [chromosome_dict[m] for m in mnames_qc]
|
| 528 |
|
| 529 |
+
n_rm_m = n_markers - len(mnames_qc)
|
| 530 |
+
n_rm_s = n_samples - len(ids_qc)
|
| 531 |
+
|
| 532 |
+
# Impute
|
| 533 |
for i in range(geno_qc.shape[1]):
|
| 534 |
col = geno_qc[:, i]
|
| 535 |
mask = np.isnan(col)
|
|
|
|
| 538 |
|
| 539 |
TARGET = min(int(target_markers), len(mnames_qc))
|
| 540 |
|
| 541 |
+
# ── GWAS ──────────────────────────────────
|
| 542 |
pvals = np.ones(len(mnames_qc))
|
| 543 |
effects = np.zeros(len(mnames_qc))
|
| 544 |
gse = np.zeros(len(mnames_qc))
|
| 545 |
+
r2_vals = np.zeros(len(mnames_qc))
|
| 546 |
+
|
| 547 |
for i in range(len(mnames_qc)):
|
| 548 |
mk = geno_qc[:, i]
|
| 549 |
if np.std(mk) > 0:
|
| 550 |
try:
|
| 551 |
+
res = stats.linregress(mk, pheno_qc)
|
| 552 |
+
pvals[i] = res.pvalue
|
| 553 |
+
effects[i] = res.slope
|
| 554 |
+
gse[i] = res.stderr
|
| 555 |
+
r2_vals[i] = res.rvalue**2
|
| 556 |
+
except:
|
| 557 |
+
pass
|
| 558 |
|
| 559 |
bonf = -np.log10(0.05 / len(mnames_qc))
|
| 560 |
n_sig = int((pvals < 0.05/len(mnames_qc)).sum())
|
| 561 |
n_sugg = int((pvals < 1e-5).sum())
|
| 562 |
+
sig_set = set(np.where(pvals < 0.05/len(mnames_qc))[0])
|
| 563 |
+
|
| 564 |
+
# ── ML marker selection (for annotation) ──
|
| 565 |
+
from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor
|
| 566 |
+
from sklearn.linear_model import ElasticNetCV
|
| 567 |
+
from sklearn.feature_selection import mutual_info_regression, f_regression
|
| 568 |
+
from sklearn.preprocessing import StandardScaler
|
| 569 |
|
|
|
|
| 570 |
scaler = StandardScaler()
|
| 571 |
X = scaler.fit_transform(geno_qc)
|
| 572 |
y = pheno_qc
|
| 573 |
|
| 574 |
+
rf_fs = RandomForestRegressor(n_estimators=100, max_depth=10,
|
| 575 |
+
random_state=42, n_jobs=-1)
|
| 576 |
rf_fs.fit(X, y)
|
| 577 |
+
|
| 578 |
+
gb_fs = GradientBoostingRegressor(n_estimators=100, max_depth=5,
|
| 579 |
+
random_state=42)
|
| 580 |
gb_fs.fit(X, y)
|
| 581 |
+
|
| 582 |
en_fs = ElasticNetCV(cv=5, random_state=42, max_iter=5000)
|
| 583 |
en_fs.fit(X, y)
|
| 584 |
+
|
| 585 |
+
mi = mutual_info_regression(X, y, random_state=42)
|
| 586 |
+
fsc, _ = f_regression(X, y)
|
| 587 |
|
| 588 |
votes = np.zeros(len(mnames_qc))
|
| 589 |
for arr in [rf_fs.feature_importances_, gb_fs.feature_importances_,
|
|
|
|
| 591 |
top = np.argsort(arr)[-TARGET:]
|
| 592 |
votes[top] += 1
|
| 593 |
|
| 594 |
+
ml_top_set = set(np.argsort(votes)[-TARGET:])
|
| 595 |
+
|
| 596 |
+
# ── SAVE CSVs ─────────────────────────────
|
| 597 |
+
gwas_df = pd.DataFrame({
|
| 598 |
+
'Rank' : 0,
|
| 599 |
+
'Marker' : mnames_qc,
|
| 600 |
+
'Chromosome' : chrom_qc,
|
| 601 |
+
'Effect_beta' : effects,
|
| 602 |
+
'StdError' : gse,
|
| 603 |
+
'R2' : r2_vals,
|
| 604 |
+
'P_value' : pvals,
|
| 605 |
+
'neglog10_P' : -np.log10(pvals + 1e-300),
|
| 606 |
+
'ML_votes' : votes.astype(int),
|
| 607 |
+
'Significant' : (pvals < 0.05/len(mnames_qc)).astype(int),
|
| 608 |
+
'Suggestive' : ((pvals < 1e-5) & (pvals >= 0.05/len(mnames_qc))).astype(int),
|
| 609 |
+
})
|
| 610 |
+
gwas_df = gwas_df.sort_values('P_value')
|
| 611 |
+
gwas_df['Rank'] = range(1, len(gwas_df)+1)
|
| 612 |
+
gwas_df.to_csv(os.path.join(results_dir, 'gwas_results.csv'), index=False)
|
| 613 |
+
|
| 614 |
+
# Per-chromosome summary
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 615 |
chr_rows = []
|
| 616 |
+
for ch in unique_chroms:
|
| 617 |
+
ci = [i for i,c in enumerate(chrom_qc) if c == ch]
|
| 618 |
if not ci: continue
|
| 619 |
cp = pvals[ci]
|
| 620 |
chr_rows.append({
|
| 621 |
+
'Chromosome' : ch,
|
| 622 |
+
'N_Markers' : len(ci),
|
| 623 |
+
'N_Significant' : int((cp < 0.05/len(mnames_qc)).sum()),
|
| 624 |
+
'N_Suggestive' : int((cp < 1e-5).sum()),
|
| 625 |
+
'Min_Pvalue' : cp.min(),
|
| 626 |
+
'Best_logP' : float(-np.log10(cp.min()+1e-300)),
|
| 627 |
+
'Mean_Effect' : float(np.mean(np.abs(effects[ci]))),
|
| 628 |
+
'Top_Marker' : mnames_qc[ci[int(np.argmin(cp))]],
|
| 629 |
})
|
| 630 |
pd.DataFrame(chr_rows).to_csv(
|
| 631 |
+
os.path.join(results_dir, 'chromosome_summary.csv'), index=False)
|
| 632 |
|
| 633 |
+
# QC summary
|
| 634 |
pd.DataFrame({
|
| 635 |
'Metric': ['Samples_raw','Samples_QC','Markers_raw','Markers_QC',
|
| 636 |
+
'Target_Selected','Chromosomes',
|
| 637 |
+
'Bonferroni_threshold_logP','N_Significant','N_Suggestive'],
|
| 638 |
+
'Value' : [n_samples, len(ids_qc), n_markers, len(mnames_qc),
|
| 639 |
+
TARGET, len(unique_chroms),
|
| 640 |
+
round(bonf,4), n_sig, n_sugg]
|
| 641 |
}).to_csv(os.path.join(results_dir,'qc_summary.csv'), index=False)
|
| 642 |
|
| 643 |
+
# ── PLOTS ─────────────────────────────────
|
| 644 |
+
man_path = os.path.join(plots_dir, 'manhattan_plot.png')
|
| 645 |
+
qq_path = os.path.join(plots_dir, 'qq_plot.png')
|
| 646 |
+
ld_path = os.path.join(plots_dir, 'ld_decay.png')
|
| 647 |
+
vol_path = os.path.join(plots_dir, 'volcano_plot.png')
|
| 648 |
+
top_path = os.path.join(plots_dir, 'top_gwas_hits.png')
|
|
|
|
| 649 |
|
| 650 |
+
plot_manhattan(mnames_qc, chrom_qc, pvals, sig_set, bonf, man_path)
|
| 651 |
lam = plot_qq(pvals, qq_path)
|
| 652 |
ld_summary = plot_ld_decay(geno_qc, chrom_qc, ld_path)
|
| 653 |
+
plot_volcano(mnames_qc, effects, pvals, bonf, vol_path)
|
| 654 |
+
plot_top_hits(mnames_qc, chrom_qc, pvals, effects, bonf, top_path)
|
|
|
|
| 655 |
|
| 656 |
+
# ── ZIP (all results + plots) ──────────────
|
| 657 |
+
zip_path = os.path.join(temp_dir, 'GWAS_Analysis_Results.zip')
|
| 658 |
with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf:
|
| 659 |
for root, _, files in os.walk(results_dir):
|
| 660 |
for f in files:
|
|
|
|
| 662 |
arc = os.path.relpath(fp, temp_dir)
|
| 663 |
zf.write(fp, arc)
|
| 664 |
|
| 665 |
+
# ── SUMMARY ───────────────────────────────
|
| 666 |
+
lam_txt = ("✅ Well-calibrated (λ ≈ 1)" if lam < 1.05
|
| 667 |
else "⚠️ Minor inflation — consider PCA correction" if lam < 1.10
|
| 668 |
else "❌ Significant inflation — use mixed model (GEMMA/EMMAX)")
|
| 669 |
|
| 670 |
gm_r2 = np.mean(list(ld_summary.values())) if ld_summary else 0
|
| 671 |
ld_txt = ("Low LD — high marker density needed" if gm_r2 < 0.1
|
| 672 |
else "Moderate LD — typical for diverse panels" if gm_r2 < 0.3
|
| 673 |
+
else "High LD — consider LD pruning before analysis")
|
| 674 |
+
|
| 675 |
+
# Top 8 hits table
|
| 676 |
+
top8 = gwas_df.head(8)
|
| 677 |
+
top8_rows = "\n".join(
|
| 678 |
+
f"| {int(r['Rank'])} | `{r['Marker']}` | Chr {r['Chromosome']} | "
|
| 679 |
+
f"{r['Effect_beta']:+.5f} | {r['P_value']:.3e} | {r['neglog10_P']:.3f} |"
|
| 680 |
+
for _, r in top8.iterrows())
|
| 681 |
+
|
| 682 |
+
# Top chromosomes
|
| 683 |
+
chr_df = pd.DataFrame(chr_rows).sort_values('Best_logP', ascending=False)
|
| 684 |
+
chr_rows_txt = "\n".join(
|
| 685 |
+
f"| Chr {r['Chromosome']} | {int(r['N_Markers'])} | "
|
| 686 |
+
f"{int(r['N_Significant'])} | {r['Best_logP']:.3f} | {r['Top_Marker']} |"
|
| 687 |
+
for _, r in chr_df.head(5).iterrows())
|
|
|
|
|
|
|
|
|
|
| 688 |
|
| 689 |
summary = f"""
|
| 690 |
+
## 📋 QC Summary
|
| 691 |
| Metric | Value |
|
| 692 |
|--------|-------|
|
| 693 |
+
| Samples (raw → QC) | {n_samples} → **{len(ids_qc)}** ({n_rm_s} removed) |
|
| 694 |
+
| Markers (raw → QC) | {n_markers} → **{len(mnames_qc)}** ({n_rm_m} removed) |
|
| 695 |
+
| Chromosomes | **{len(unique_chroms)}** |
|
| 696 |
+
| MAF filter | > 1% |
|
| 697 |
+
| Missing rate filter | < 10% |
|
| 698 |
|
| 699 |
+
## 🔬 GWAS Results
|
| 700 |
| Metric | Value |
|
| 701 |
|--------|-------|
|
| 702 |
+
| Total markers tested | **{len(mnames_qc)}** |
|
| 703 |
+
| Bonferroni threshold | −log₁₀p = **{bonf:.3f}** |
|
| 704 |
+
| **Significant markers** | 🔴 **{n_sig}** |
|
| 705 |
+
| Suggestive markers | 🟡 {n_sugg} |
|
| 706 |
| Genomic inflation λ | **{lam:.4f}** — {lam_txt} |
|
| 707 |
|
| 708 |
+
## 🔗 LD Summary
|
| 709 |
Global mean r² = **{gm_r2:.4f}** — {ld_txt}
|
| 710 |
|
| 711 |
+
## 🏆 Top 8 GWAS Hits
|
| 712 |
+
| Rank | Marker | Chr | Effect β | P-value | −log₁₀P |
|
| 713 |
+
|------|--------|-----|----------|---------|---------|
|
| 714 |
+
{top8_rows}
|
| 715 |
|
| 716 |
+
## 🗺️ Top Chromosomes (by significance)
|
| 717 |
+
| Chr | Markers | Significant | Best −log₁₀P | Top Marker |
|
| 718 |
+
|-----|---------|-------------|--------------|------------|
|
| 719 |
+
{chr_rows_txt}
|
| 720 |
|
| 721 |
+
## 📁 ZIP Contains
|
| 722 |
+
- `results/gwas_results.csv` — full GWAS with effects, p-values, ML votes
|
| 723 |
+
- `results/chromosome_summary.csv` — per-chromosome statistics
|
| 724 |
+
- `results/qc_summary.csv` — QC metrics
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 725 |
- `results/plots/manhattan_plot.png`
|
| 726 |
- `results/plots/qq_plot.png`
|
| 727 |
- `results/plots/ld_decay.png`
|
| 728 |
+
- `results/plots/volcano_plot.png`
|
| 729 |
+
- `results/plots/top_gwas_hits.png`
|
|
|
|
| 730 |
"""
|
| 731 |
+
return summary, man_path, qq_path, ld_path, vol_path, top_path, zip_path
|
| 732 |
|
| 733 |
except Exception as e:
|
| 734 |
import traceback
|
| 735 |
+
return (f"## ❌ Error\n```\n{e}\n\n{traceback.format_exc()}\n```",
|
| 736 |
+
None, None, None, None, None, None)
|
| 737 |
|
| 738 |
|
| 739 |
+
# ══════════════════════════════════════════════════════════════
|
| 740 |
+
# HTML / CSS — white background, dark-blue text
|
| 741 |
+
# ══════════════════════════════════════════════════════════════
|
| 742 |
+
THEME_CSS = """
|
| 743 |
<style>
|
| 744 |
+
@import url('https://fonts.googleapis.com/css2?family=DM+Sans:wght@300;400;500;600;700&family=DM+Mono:wght@400;500&display=swap');
|
| 745 |
+
|
| 746 |
+
:root {
|
| 747 |
+
--navy: #0D2B5E;
|
| 748 |
+
--blue: #1A56DB;
|
| 749 |
+
--blue2: #2563EB;
|
| 750 |
+
--sky: #EBF2FF;
|
| 751 |
+
--skymed: #C7D9F8;
|
| 752 |
+
--teal: #0D9488;
|
| 753 |
+
--red: #E53E3E;
|
| 754 |
+
--amber: #D97706;
|
| 755 |
+
--white: #FFFFFF;
|
| 756 |
+
--offwhite:#F8FAFD;
|
| 757 |
+
--border: #D1DEF0;
|
| 758 |
+
--muted: #5A7599;
|
| 759 |
+
--radius: 14px;
|
| 760 |
+
--shadow: 0 2px 16px rgba(13,43,94,0.08);
|
| 761 |
+
}
|
| 762 |
+
|
| 763 |
+
body, .gradio-container {
|
| 764 |
+
background: var(--white) !important;
|
| 765 |
+
color: var(--navy) !important;
|
| 766 |
+
font-family: 'DM Sans', sans-serif !important;
|
| 767 |
+
}
|
| 768 |
+
|
| 769 |
+
/* ── Hero ── */
|
| 770 |
+
.hero {
|
| 771 |
+
background: linear-gradient(135deg, #0D2B5E 0%, #1A56DB 55%, #2563EB 100%);
|
| 772 |
+
border-radius: 20px;
|
| 773 |
+
padding: 52px 60px 44px;
|
| 774 |
+
margin-bottom: 30px;
|
| 775 |
+
position: relative;
|
| 776 |
+
overflow: hidden;
|
| 777 |
+
box-shadow: 0 8px 40px rgba(13,43,94,0.20);
|
| 778 |
+
}
|
| 779 |
+
.hero::before {
|
| 780 |
+
content:'';
|
| 781 |
+
position:absolute; top:-100px; right:-80px;
|
| 782 |
+
width:350px; height:350px; border-radius:50%;
|
| 783 |
+
background:radial-gradient(circle,rgba(255,255,255,0.10) 0%,transparent 70%);
|
| 784 |
+
}
|
| 785 |
+
.hero::after {
|
| 786 |
+
content:'';
|
| 787 |
+
position:absolute; bottom:-80px; left:60px;
|
| 788 |
+
width:260px; height:260px; border-radius:50%;
|
| 789 |
+
background:radial-gradient(circle,rgba(255,255,255,0.07) 0%,transparent 70%);
|
| 790 |
+
}
|
| 791 |
+
.hero-badge {
|
| 792 |
+
display:inline-flex; align-items:center; gap:8px;
|
| 793 |
+
background:rgba(255,255,255,0.15);
|
| 794 |
+
border:1px solid rgba(255,255,255,0.25);
|
| 795 |
+
color:#fff;
|
| 796 |
+
font-family:'DM Mono',monospace;
|
| 797 |
+
font-size:11px; letter-spacing:2px;
|
| 798 |
+
padding:5px 16px; border-radius:30px;
|
| 799 |
+
margin-bottom:20px;
|
| 800 |
+
}
|
| 801 |
+
.hero-badge::before {
|
| 802 |
+
content:''; width:7px; height:7px; border-radius:50%;
|
| 803 |
+
background:#3fb950; animation:pulse 2s infinite;
|
| 804 |
+
}
|
| 805 |
+
@keyframes pulse {
|
| 806 |
+
0%,100%{opacity:1;transform:scale(1)}
|
| 807 |
+
50%{opacity:0.6;transform:scale(1.3)}
|
| 808 |
+
}
|
| 809 |
+
.hero-title {
|
| 810 |
+
font-family:'DM Sans',sans-serif;
|
| 811 |
+
font-weight:700; font-size:42px; color:#fff;
|
| 812 |
+
line-height:1.1; margin:0 0 12px;
|
| 813 |
+
letter-spacing:-0.8px;
|
| 814 |
+
}
|
| 815 |
+
.hero-title em { color:#93C5FD; font-style:normal; }
|
| 816 |
+
.hero-sub {
|
| 817 |
+
color:rgba(255,255,255,0.72);
|
| 818 |
+
font-family:'DM Mono',monospace;
|
| 819 |
+
font-size:13px; margin:0 0 24px;
|
| 820 |
+
}
|
| 821 |
+
.hero-pills {
|
| 822 |
+
display:flex; gap:8px; flex-wrap:wrap;
|
| 823 |
+
}
|
| 824 |
+
.hero-pill {
|
| 825 |
+
background:rgba(255,255,255,0.14);
|
| 826 |
+
border:1px solid rgba(255,255,255,0.22);
|
| 827 |
+
color:#fff; border-radius:20px;
|
| 828 |
+
padding:4px 14px; font-size:12px;
|
| 829 |
+
}
|
| 830 |
+
|
| 831 |
+
/* ── Section header ── */
|
| 832 |
+
.sec-head {
|
| 833 |
+
display:flex; align-items:center; gap:12px;
|
| 834 |
+
font-family:'DM Mono',monospace;
|
| 835 |
+
font-size:10px; letter-spacing:2.5px;
|
| 836 |
+
color:var(--blue); text-transform:uppercase;
|
| 837 |
+
margin:28px 0 14px;
|
| 838 |
+
}
|
| 839 |
+
.sec-head::after {
|
| 840 |
+
content:''; flex:1; height:1px;
|
| 841 |
+
background:linear-gradient(90deg,var(--border),transparent);
|
| 842 |
+
}
|
| 843 |
+
|
| 844 |
+
/* ── Left panel card ── */
|
| 845 |
+
.left-card {
|
| 846 |
+
background:var(--offwhite);
|
| 847 |
+
border:1px solid var(--border);
|
| 848 |
+
border-radius:var(--radius);
|
| 849 |
+
padding:24px;
|
| 850 |
+
}
|
| 851 |
+
|
| 852 |
+
/* ── Format box ── */
|
| 853 |
+
.fmt-box {
|
| 854 |
+
background:var(--white);
|
| 855 |
+
border:1px solid var(--border);
|
| 856 |
+
border-left:4px solid var(--blue);
|
| 857 |
+
border-radius:10px;
|
| 858 |
+
padding:18px 20px;
|
| 859 |
+
font-family:'DM Mono',monospace;
|
| 860 |
+
font-size:11.5px;
|
| 861 |
+
color:var(--muted);
|
| 862 |
+
line-height:2.0;
|
| 863 |
+
margin-bottom:20px;
|
| 864 |
+
}
|
| 865 |
+
.fmt-box .col { color:var(--blue); font-weight:600; }
|
| 866 |
+
.fmt-box .val { color:var(--teal); }
|
| 867 |
+
.fmt-box .cmt { color:var(--border); }
|
| 868 |
+
|
| 869 |
+
/* ── Run button ── */
|
| 870 |
+
.run-btn button {
|
| 871 |
+
background:linear-gradient(135deg,#1A56DB,#2563EB) !important;
|
| 872 |
+
border:none !important;
|
| 873 |
+
border-radius:12px !important;
|
| 874 |
+
color:#fff !important;
|
| 875 |
+
font-family:'DM Sans',sans-serif !important;
|
| 876 |
+
font-weight:600 !important;
|
| 877 |
+
font-size:16px !important;
|
| 878 |
+
padding:15px 0 !important;
|
| 879 |
+
width:100% !important;
|
| 880 |
+
box-shadow:0 4px 20px rgba(26,86,219,0.35) !important;
|
| 881 |
+
transition:all 0.2s !important;
|
| 882 |
+
cursor:pointer !important;
|
| 883 |
+
}
|
| 884 |
+
.run-btn button:hover {
|
| 885 |
+
transform:translateY(-2px) !important;
|
| 886 |
+
box-shadow:0 8px 30px rgba(26,86,219,0.45) !important;
|
| 887 |
+
}
|
| 888 |
+
|
| 889 |
+
/* ── Pipeline ── */
|
| 890 |
+
.pipeline {
|
| 891 |
+
display:flex; margin-top:20px;
|
| 892 |
+
}
|
| 893 |
+
.pipe-step {
|
| 894 |
+
flex:1;
|
| 895 |
+
background:var(--white);
|
| 896 |
+
border:1px solid var(--border);
|
| 897 |
+
padding:14px 8px;
|
| 898 |
+
text-align:center;
|
| 899 |
+
position:relative;
|
| 900 |
+
}
|
| 901 |
+
.pipe-step:not(:last-child)::after {
|
| 902 |
+
content:'›'; position:absolute;
|
| 903 |
+
right:-10px; top:50%; transform:translateY(-50%);
|
| 904 |
+
color:var(--blue); font-size:18px; font-weight:700;
|
| 905 |
+
background:var(--white); padding:0 2px; z-index:1;
|
| 906 |
+
}
|
| 907 |
+
.pipe-step:first-child { border-radius:10px 0 0 10px; }
|
| 908 |
+
.pipe-step:last-child { border-radius:0 10px 10px 0; }
|
| 909 |
+
.pipe-num {
|
| 910 |
+
font-family:'DM Mono',monospace;
|
| 911 |
+
font-size:17px; font-weight:500;
|
| 912 |
+
color:var(--blue); display:block;
|
| 913 |
+
}
|
| 914 |
+
.pipe-name {
|
| 915 |
+
font-size:10px; color:var(--muted);
|
| 916 |
+
margin-top:3px; display:block;
|
| 917 |
+
}
|
| 918 |
+
|
| 919 |
+
/* ── Summary card ── */
|
| 920 |
+
.sum-card {
|
| 921 |
+
background:var(--white);
|
| 922 |
+
border:1px solid var(--border);
|
| 923 |
+
border-radius:var(--radius);
|
| 924 |
+
padding:24px 28px;
|
| 925 |
+
box-shadow:var(--shadow);
|
| 926 |
+
}
|
| 927 |
+
.sum-card h2 {
|
| 928 |
+
color:var(--blue) !important;
|
| 929 |
+
font-family:'DM Sans',sans-serif !important;
|
| 930 |
+
font-size:15px !important;
|
| 931 |
+
font-weight:600 !important;
|
| 932 |
+
margin-top:22px !important;
|
| 933 |
+
padding-bottom:6px;
|
| 934 |
+
border-bottom:1px solid var(--border);
|
| 935 |
+
}
|
| 936 |
+
.sum-card table {
|
| 937 |
+
width:100%; border-collapse:collapse; margin:10px 0;
|
| 938 |
+
}
|
| 939 |
+
.sum-card th {
|
| 940 |
+
background:var(--sky) !important;
|
| 941 |
+
color:var(--navy) !important;
|
| 942 |
+
font-family:'DM Mono',monospace !important;
|
| 943 |
+
font-size:11px !important;
|
| 944 |
+
padding:8px 12px !important;
|
| 945 |
+
border:1px solid var(--border) !important;
|
| 946 |
+
text-align:left;
|
| 947 |
+
}
|
| 948 |
+
.sum-card td {
|
| 949 |
+
color:var(--navy) !important;
|
| 950 |
+
font-size:12.5px !important;
|
| 951 |
+
padding:7px 12px !important;
|
| 952 |
+
border:1px solid var(--border) !important;
|
| 953 |
+
font-family:'DM Mono',monospace !important;
|
| 954 |
+
}
|
| 955 |
+
.sum-card td code, .sum-card p code {
|
| 956 |
+
background:var(--sky); color:var(--blue);
|
| 957 |
+
border-radius:4px; padding:1px 5px;
|
| 958 |
+
font-family:'DM Mono',monospace;
|
| 959 |
+
font-size:11.5px;
|
| 960 |
+
}
|
| 961 |
+
.sum-card p { color:var(--navy) !important; font-size:13px !important; }
|
| 962 |
+
|
| 963 |
+
/* ── Plot card ── */
|
| 964 |
+
.plot-wrap {
|
| 965 |
+
background:var(--white);
|
| 966 |
+
border:1px solid var(--border);
|
| 967 |
+
border-radius:var(--radius);
|
| 968 |
+
overflow:hidden;
|
| 969 |
+
box-shadow:var(--shadow);
|
| 970 |
+
margin-bottom:16px;
|
| 971 |
+
}
|
| 972 |
+
.plot-label {
|
| 973 |
+
padding:12px 18px;
|
| 974 |
+
font-family:'DM Mono',monospace;
|
| 975 |
+
font-size:10px; letter-spacing:2px;
|
| 976 |
+
text-transform:uppercase;
|
| 977 |
+
color:var(--muted);
|
| 978 |
+
border-bottom:1px solid var(--border);
|
| 979 |
+
background:var(--offwhite);
|
| 980 |
+
}
|
| 981 |
+
|
| 982 |
+
/* ── Download box ── */
|
| 983 |
+
.dl-box {
|
| 984 |
+
background:var(--sky);
|
| 985 |
+
border:1px solid var(--skymed);
|
| 986 |
+
border-radius:var(--radius);
|
| 987 |
+
padding:20px 24px;
|
| 988 |
+
}
|
| 989 |
+
.dl-box-title {
|
| 990 |
+
font-family:'DM Mono',monospace;
|
| 991 |
+
font-size:10px; letter-spacing:2px;
|
| 992 |
+
color:var(--blue); text-transform:uppercase;
|
| 993 |
+
margin-bottom:10px;
|
| 994 |
+
}
|
| 995 |
+
.dl-box-list {
|
| 996 |
+
font-family:'DM Mono',monospace;
|
| 997 |
+
font-size:12px; color:var(--navy);
|
| 998 |
+
line-height:2.0;
|
| 999 |
+
}
|
| 1000 |
+
.dl-box-list span { color:var(--blue); font-weight:500; }
|
| 1001 |
+
|
| 1002 |
+
/* ── Gradio overrides ── */
|
| 1003 |
+
.gradio-container .block,
|
| 1004 |
+
.gradio-container .wrap,
|
| 1005 |
+
.gradio-container .gap {
|
| 1006 |
+
background:transparent !important;
|
| 1007 |
+
border:none !important;
|
| 1008 |
+
box-shadow:none !important;
|
| 1009 |
+
}
|
| 1010 |
+
.gradio-container label {
|
| 1011 |
+
color:var(--navy) !important;
|
| 1012 |
+
font-family:'DM Sans',sans-serif !important;
|
| 1013 |
+
font-weight:500 !important;
|
| 1014 |
+
}
|
| 1015 |
+
.gradio-container input,
|
| 1016 |
+
.gradio-container textarea {
|
| 1017 |
+
background:var(--white) !important;
|
| 1018 |
+
border:1px solid var(--border) !important;
|
| 1019 |
+
color:var(--navy) !important;
|
| 1020 |
+
border-radius:8px !important;
|
| 1021 |
+
font-family:'DM Sans',sans-serif !important;
|
| 1022 |
+
}
|
| 1023 |
+
.gradio-container input[type=range] {
|
| 1024 |
+
accent-color:var(--blue) !important;
|
| 1025 |
+
}
|
| 1026 |
+
.gradio-container .output-markdown {
|
| 1027 |
+
background:transparent !important;
|
| 1028 |
+
color:var(--navy) !important;
|
| 1029 |
+
}
|
| 1030 |
+
footer, .gradio-container .built-with,
|
| 1031 |
+
.gradio-container .svelte-1ipelgc { display:none !important; }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1032 |
</style>
|
| 1033 |
"""
|
| 1034 |
|
| 1035 |
HERO_HTML = """
|
| 1036 |
+
<div class="hero">
|
| 1037 |
+
<div class="hero-badge">GWAS · QQ · LD DECAY · ML SELECTION</div>
|
| 1038 |
+
<h1 class="hero-title">Multi-Trait <em>Association</em><br>Analysis Platform</h1>
|
| 1039 |
+
<p class="hero-sub">Genome-Wide Association · Quality Control · LD Analysis · Marker Discovery</p>
|
| 1040 |
+
<div class="hero-pills">
|
| 1041 |
+
<span class="hero-pill">Manhattan Plot</span>
|
| 1042 |
+
<span class="hero-pill">QQ Plot + λ</span>
|
| 1043 |
+
<span class="hero-pill">LD Decay</span>
|
| 1044 |
+
<span class="hero-pill">Volcano Plot</span>
|
| 1045 |
+
<span class="hero-pill">Top Hits</span>
|
| 1046 |
+
<span class="hero-pill">ZIP Export</span>
|
| 1047 |
</div>
|
| 1048 |
</div>
|
| 1049 |
"""
|
| 1050 |
|
| 1051 |
+
FMT_HTML = """
|
| 1052 |
+
<div class="sec-head">Input Format</div>
|
| 1053 |
+
<div class="fmt-box">
|
| 1054 |
+
<span class="col">Col 1</span> Sample ID
|
| 1055 |
+
<span class="col">Col 2</span> Chromosome
|
| 1056 |
+
<span class="col">Col 3</span> Phenotype
|
| 1057 |
+
<span class="col">Col 4+</span> Markers<br><br>
|
| 1058 |
+
<span class="col">ID</span>, <span class="col">Chr</span>, <span class="col">Pheno</span>,
|
| 1059 |
+
<span class="val">M0001</span>, <span class="val">M0002</span>, ...<br>
|
| 1060 |
+
<span class="cmt">- , - , - ,</span>
|
| 1061 |
+
<span class="val">1</span> ,
|
| 1062 |
+
<span class="val">1</span> , ...
|
| 1063 |
+
<span class="cmt"> ← marker chr row</span><br>
|
| 1064 |
+
S1 , 1 , <span class="val">45.2</span> ,
|
| 1065 |
+
<span class="val">0</span> ,
|
| 1066 |
+
<span class="val">1</span> , ...
|
| 1067 |
</div>
|
| 1068 |
"""
|
| 1069 |
|
| 1070 |
+
PIPE_HTML = """
|
| 1071 |
+
<div class="sec-head" style="margin-top:24px">Pipeline</div>
|
| 1072 |
<div class="pipeline">
|
| 1073 |
+
<div class="pipe-step"><span class="pipe-num">01</span><span class="pipe-name">QC</span></div>
|
| 1074 |
<div class="pipe-step"><span class="pipe-num">02</span><span class="pipe-name">GWAS</span></div>
|
| 1075 |
<div class="pipe-step"><span class="pipe-num">03</span><span class="pipe-name">QQ / LD</span></div>
|
| 1076 |
+
<div class="pipe-step"><span class="pipe-num">04</span><span class="pipe-name">Volcano</span></div>
|
| 1077 |
+
<div class="pipe-step"><span class="pipe-num">05</span><span class="pipe-name">Export</span></div>
|
| 1078 |
+
</div>
|
| 1079 |
+
"""
|
| 1080 |
+
|
| 1081 |
+
DL_HTML = """
|
| 1082 |
+
<div class="dl-box">
|
| 1083 |
+
<div class="dl-box-title">ZIP Contents</div>
|
| 1084 |
+
<div class="dl-box-list">
|
| 1085 |
+
<span>📊</span> gwas_results.csv — full marker statistics<br>
|
| 1086 |
+
<span>🗺️</span> chromosome_summary.csv<br>
|
| 1087 |
+
<span>🔬</span> qc_summary.csv<br>
|
| 1088 |
+
<span>🖼️</span> manhattan_plot.png<br>
|
| 1089 |
+
<span>🖼️</span> qq_plot.png<br>
|
| 1090 |
+
<span>🖼️</span> ld_decay.png<br>
|
| 1091 |
+
<span>🖼️</span> volcano_plot.png<br>
|
| 1092 |
+
<span>🖼️</span> top_gwas_hits.png
|
| 1093 |
+
</div>
|
| 1094 |
</div>
|
| 1095 |
"""
|
| 1096 |
|
| 1097 |
+
# ══════════════════════════════════════════════════════════════
|
| 1098 |
# GRADIO APP
|
| 1099 |
+
# ══════════════════════════════════════════════════════════════
|
| 1100 |
+
with gr.Blocks(css=THEME_CSS, title="MTA Analysis") as app:
|
| 1101 |
|
| 1102 |
gr.HTML(HERO_HTML)
|
| 1103 |
|
| 1104 |
with gr.Row():
|
| 1105 |
+
# ── LEFT ──
|
| 1106 |
+
with gr.Column(scale=1, min_width=300):
|
| 1107 |
+
gr.HTML(FMT_HTML)
|
| 1108 |
+
gr.HTML('<div class="sec-head">Configure</div>')
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1109 |
|
| 1110 |
+
input_file = gr.File(label="Upload CSV File", file_types=[".csv"])
|
| 1111 |
target_markers = gr.Slider(
|
| 1112 |
+
100, 5000, value=3000, step=100,
|
| 1113 |
+
label="Target Markers for ML Selection",
|
| 1114 |
+
info="Used for feature voting; does not affect GWAS p-values")
|
| 1115 |
|
| 1116 |
with gr.Row(elem_classes=["run-btn"]):
|
| 1117 |
+
run_btn = gr.Button("⚡ Run GWAS Analysis", variant="primary", size="lg")
|
| 1118 |
|
| 1119 |
+
gr.HTML(PIPE_HTML)
|
| 1120 |
|
| 1121 |
+
# ── RIGHT ──
|
| 1122 |
with gr.Column(scale=2):
|
| 1123 |
+
gr.HTML('<div class="sec-head">Results Summary</div>')
|
| 1124 |
+
with gr.Column(elem_classes=["sum-card"]):
|
| 1125 |
+
summary_out = gr.Markdown(value="*Upload a CSV and click Run to begin.*")
|
|
|
|
| 1126 |
|
| 1127 |
# ── PLOTS ──
|
| 1128 |
+
gr.HTML('<div class="sec-head" style="margin-top:10px">Visualizations</div>')
|
| 1129 |
|
| 1130 |
+
with gr.Column(elem_classes=["plot-wrap"]):
|
| 1131 |
+
gr.HTML('<div class="plot-label">Manhattan Plot — Genome-Wide Significance</div>')
|
| 1132 |
+
manhattan_out = gr.Image(show_label=False)
|
| 1133 |
|
| 1134 |
with gr.Row():
|
| 1135 |
+
with gr.Column(elem_classes=["plot-wrap"]):
|
| 1136 |
+
gr.HTML('<div class="plot-label">QQ Plot — Genomic Inflation Factor</div>')
|
| 1137 |
+
qq_out = gr.Image(show_label=False)
|
| 1138 |
+
with gr.Column(elem_classes=["plot-wrap"]):
|
| 1139 |
+
gr.HTML('<div class="plot-label">LD Decay — Linkage Disequilibrium</div>')
|
| 1140 |
+
ld_out = gr.Image(show_label=False)
|
| 1141 |
|
| 1142 |
with gr.Row():
|
| 1143 |
+
with gr.Column(elem_classes=["plot-wrap"]):
|
| 1144 |
+
gr.HTML('<div class="plot-label">Volcano Plot — Effect vs Significance</div>')
|
| 1145 |
+
vol_out = gr.Image(show_label=False)
|
| 1146 |
+
with gr.Column(elem_classes=["plot-wrap"]):
|
| 1147 |
+
gr.HTML('<div class="plot-label">Top GWAS Hits — Ranked by −log₁₀(P)</div>')
|
| 1148 |
+
top_out = gr.Image(show_label=False)
|
| 1149 |
|
| 1150 |
# ── DOWNLOAD ──
|
| 1151 |
+
gr.HTML('<div class="sec-head" style="margin-top:10px">Export</div>')
|
| 1152 |
with gr.Row():
|
| 1153 |
with gr.Column(scale=1):
|
| 1154 |
+
gr.HTML(DL_HTML)
|
| 1155 |
+
with gr.Column(scale=1):
|
| 1156 |
+
download_out = gr.File(label="⬇ Download All Results (ZIP)")
|
| 1157 |
+
with gr.Column(scale=1):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1158 |
pass
|
| 1159 |
|
| 1160 |
+
run_btn.click(
|
|
|
|
| 1161 |
fn=run_mta_analysis,
|
| 1162 |
inputs=[input_file, target_markers],
|
| 1163 |
+
outputs=[summary_out, manhattan_out, qq_out, ld_out,
|
| 1164 |
+
vol_out, top_out, download_out])
|
| 1165 |
|
| 1166 |
if __name__ == "__main__":
|
| 1167 |
app.launch(share=True, show_error=True)
|