Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,15 +1,7 @@
|
|
| 1 |
# -*- coding: utf-8 -*-
|
| 2 |
"""
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
FIXES:
|
| 7 |
-
- Corrected CSV parsing: Column 2 = Chromosome, Column 3 = Phenotype, Column 4+ = Markers
|
| 8 |
-
- Manhattan plot: proper chromosome coloring, no overlapping labels, correct spacing
|
| 9 |
-
- Added QQ plot with confidence bands
|
| 10 |
-
- Added LD Decay plot and analysis
|
| 11 |
-
- Chromosome info now included in all CSV outputs
|
| 12 |
-
- Improved interpretations and summaries
|
| 13 |
"""
|
| 14 |
|
| 15 |
import gradio as gr
|
|
@@ -19,6 +11,8 @@ import matplotlib
|
|
| 19 |
matplotlib.use('Agg')
|
| 20 |
import matplotlib.pyplot as plt
|
| 21 |
import matplotlib.patches as mpatches
|
|
|
|
|
|
|
| 22 |
import seaborn as sns
|
| 23 |
from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor
|
| 24 |
from sklearn.linear_model import LassoCV, ElasticNetCV, Ridge
|
|
@@ -27,909 +21,1190 @@ from sklearn.model_selection import cross_val_score, KFold
|
|
| 27 |
from sklearn.preprocessing import StandardScaler
|
| 28 |
from sklearn.metrics import r2_score, mean_squared_error
|
| 29 |
from scipy import stats
|
| 30 |
-
import os
|
| 31 |
-
import warnings
|
| 32 |
-
import tempfile
|
| 33 |
-
import zipfile
|
| 34 |
-
|
| 35 |
warnings.filterwarnings('ignore')
|
| 36 |
|
| 37 |
-
# ─────────────────────────────────────────────
|
| 38 |
-
# GLOBAL PLOT
|
| 39 |
-
# ─────────────────────────────────────────────
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
"#
|
| 53 |
-
"#
|
| 54 |
-
"#
|
| 55 |
-
"#
|
| 56 |
-
"#66A61E", "#E6AB02"
|
| 57 |
]
|
| 58 |
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
def plot_manhattan(marker_names, chromosomes, p_values, consensus_set,
|
| 64 |
bonf_thresh, save_path):
|
| 65 |
-
|
| 66 |
-
Draws a publication-quality Manhattan plot.
|
| 67 |
-
- No overlapping x-axis labels
|
| 68 |
-
- Alternating chromosome colors
|
| 69 |
-
- Highlighted selected markers in red
|
| 70 |
-
- Proper spacing between chromosomes
|
| 71 |
-
"""
|
| 72 |
-
unique_chroms = []
|
| 73 |
-
seen = set()
|
| 74 |
-
for c in chromosomes:
|
| 75 |
-
if c not in seen:
|
| 76 |
-
unique_chroms.append(c)
|
| 77 |
-
seen.add(c)
|
| 78 |
-
unique_chroms = sorted(unique_chroms, key=lambda x: (
|
| 79 |
-
int(x) if x.isdigit() else 999, x))
|
| 80 |
|
|
|
|
|
|
|
| 81 |
log_p = -np.log10(np.array(p_values) + 1e-300)
|
| 82 |
|
| 83 |
-
|
| 84 |
-
GAP = max(5, len(marker_names) // 200)
|
| 85 |
x_pos = np.zeros(len(marker_names))
|
| 86 |
-
chrom_centers = {}
|
| 87 |
-
chrom_starts = {}
|
| 88 |
-
offset = 0
|
| 89 |
-
|
| 90 |
-
chrom_to_idx = {}
|
| 91 |
for i, m in enumerate(marker_names):
|
| 92 |
c = chromosomes[i]
|
| 93 |
-
|
| 94 |
-
chrom_to_idx[c] = []
|
| 95 |
-
chrom_to_idx[c].append(i)
|
| 96 |
|
| 97 |
-
|
|
|
|
| 98 |
idxs = chrom_to_idx.get(chrom, [])
|
| 99 |
-
if not idxs:
|
| 100 |
-
continue
|
| 101 |
-
chrom_starts[chrom] = offset
|
| 102 |
for rank, idx in enumerate(idxs):
|
| 103 |
x_pos[idx] = offset + rank
|
| 104 |
chrom_centers[chrom] = offset + (len(idxs) - 1) / 2
|
| 105 |
offset += len(idxs) + GAP
|
| 106 |
|
| 107 |
-
fig
|
|
|
|
| 108 |
|
|
|
|
| 109 |
for ci, chrom in enumerate(unique_chroms):
|
| 110 |
idxs = chrom_to_idx.get(chrom, [])
|
| 111 |
-
if not idxs:
|
| 112 |
-
|
| 113 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 114 |
|
| 115 |
-
# Normal markers
|
| 116 |
normal = [i for i in idxs if i not in consensus_set]
|
|
|
|
|
|
|
| 117 |
if normal:
|
| 118 |
ax.scatter(x_pos[normal], log_p[normal],
|
| 119 |
-
c=
|
| 120 |
-
|
| 121 |
-
# Selected / consensus markers
|
| 122 |
-
sel = [i for i in idxs if i in consensus_set]
|
| 123 |
if sel:
|
|
|
|
|
|
|
|
|
|
| 124 |
ax.scatter(x_pos[sel], log_p[sel],
|
| 125 |
-
c=
|
| 126 |
-
edgecolors='
|
| 127 |
-
marker='D')
|
| 128 |
|
| 129 |
-
#
|
| 130 |
-
ax.axhline(bonf_thresh, color=
|
| 131 |
-
|
|
|
|
| 132 |
|
| 133 |
-
# Suggestive line
|
| 134 |
suggestive = -np.log10(1e-5)
|
| 135 |
if suggestive < bonf_thresh:
|
| 136 |
-
ax.axhline(suggestive, color=
|
| 137 |
-
|
|
|
|
| 138 |
|
| 139 |
-
#
|
| 140 |
xtick_pos = [chrom_centers[c] for c in unique_chroms if c in chrom_centers]
|
| 141 |
-
xtick_lab = [c for c in unique_chroms if c in chrom_centers]
|
| 142 |
-
|
| 143 |
ax.set_xticks(xtick_pos)
|
| 144 |
-
ax.set_xticklabels(xtick_lab,
|
| 145 |
-
|
|
|
|
|
|
|
| 146 |
ax.set_xlim(-GAP, offset)
|
| 147 |
-
ax.set_ylim(bottom=0)
|
| 148 |
|
| 149 |
-
ax.
|
| 150 |
-
ax.
|
| 151 |
-
ax.set_title('Genome-Wide Association Study
|
| 152 |
-
|
| 153 |
-
# Legend
|
| 154 |
-
red_patch = mpatches.Patch(color='red', label='Selected markers (consensus ML)')
|
| 155 |
-
handles = [red_patch]
|
| 156 |
-
line1 = plt.Line2D([0], [0], color='#333333', ls='--', lw=1.8,
|
| 157 |
-
label=f'Bonferroni (α=0.05, –log₁₀p={bonf_thresh:.2f})')
|
| 158 |
-
handles.append(line1)
|
| 159 |
-
if suggestive < bonf_thresh:
|
| 160 |
-
line2 = plt.Line2D([0], [0], color='steelblue', ls=':', lw=1.4,
|
| 161 |
-
label='Suggestive (1×10⁻⁵)')
|
| 162 |
-
handles.append(line2)
|
| 163 |
-
ax.legend(handles=handles, fontsize=10, loc='upper right', framealpha=0.9)
|
| 164 |
|
| 165 |
-
|
| 166 |
-
ax.
|
| 167 |
-
ax.
|
| 168 |
|
| 169 |
-
|
| 170 |
-
plt.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 171 |
plt.close(fig)
|
| 172 |
|
| 173 |
|
| 174 |
-
# ─────────────────────────────────────────────
|
| 175 |
-
#
|
| 176 |
-
# ─────────────────────────────────────────────
|
| 177 |
def plot_qq(p_values, save_path):
|
| 178 |
-
|
| 179 |
-
QQ plot of observed vs expected –log10(p) with 95% confidence band.
|
| 180 |
-
"""
|
| 181 |
-
pv = np.array(p_values)
|
| 182 |
-
pv = pv[~np.isnan(pv)]
|
| 183 |
-
pv = np.clip(pv, 1e-300, 1.0)
|
| 184 |
-
n = len(pv)
|
| 185 |
|
|
|
|
|
|
|
| 186 |
obs = np.sort(pv)
|
| 187 |
-
|
| 188 |
log_obs = -np.log10(obs)
|
| 189 |
-
log_exp = -np.log10(
|
| 190 |
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
np.arange(n, 0, -1)))
|
| 194 |
-
ci_lower = -np.log10(stats.beta.ppf(0.975, np.arange(1, n + 1),
|
| 195 |
-
np.arange(n, 0, -1)))
|
| 196 |
-
ci_lower = np.maximum(ci_lower, 0)
|
| 197 |
|
| 198 |
-
# Genomic inflation factor λ
|
| 199 |
chi2 = stats.chi2.ppf(1 - pv, df=1)
|
| 200 |
-
lam
|
| 201 |
|
| 202 |
-
fig, ax = plt.subplots(figsize=(7, 7))
|
|
|
|
| 203 |
|
| 204 |
-
ax.fill_between(log_exp,
|
| 205 |
-
color=
|
| 206 |
-
ax.scatter(log_exp, log_obs,
|
|
|
|
| 207 |
linewidths=0, zorder=3)
|
| 208 |
-
|
| 209 |
-
ax.plot([0,
|
| 210 |
-
|
| 211 |
-
ax.set_xlabel('Expected −log₁₀(P)', fontsize=
|
| 212 |
-
ax.set_ylabel('Observed −log₁₀(P)', fontsize=
|
| 213 |
-
ax.set_title(f'QQ Plot
|
| 214 |
-
|
| 215 |
-
ax.set_xlim(0,
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
ax.
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
va='top', color='navy',
|
| 231 |
-
bbox=dict(boxstyle='round,pad=0.3', fc='lightyellow', alpha=0.8))
|
| 232 |
-
|
| 233 |
-
plt.tight_layout()
|
| 234 |
-
plt.savefig(save_path, dpi=200, bbox_inches='tight')
|
| 235 |
plt.close(fig)
|
| 236 |
return lam
|
| 237 |
|
| 238 |
|
| 239 |
-
# ─────────────────────────────────────────────
|
| 240 |
-
#
|
| 241 |
-
# ─────────────────────────────────────────────
|
| 242 |
-
def plot_ld_decay(genotypes,
|
| 243 |
-
|
| 244 |
-
Computes pairwise r² within chromosomes and plots LD decay vs physical distance (marker index).
|
| 245 |
-
"""
|
| 246 |
-
unique_chroms = sorted(set(chromosomes), key=lambda x: (int(x) if x.isdigit() else 999, x))
|
| 247 |
-
|
| 248 |
-
all_distances = []
|
| 249 |
-
all_r2 = []
|
| 250 |
|
| 251 |
-
|
|
|
|
|
|
|
|
|
|
| 252 |
|
| 253 |
for chrom in unique_chroms:
|
| 254 |
idxs = [i for i, c in enumerate(chromosomes) if c == chrom]
|
| 255 |
-
if len(idxs) < 4:
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
# Subsample if needed
|
| 259 |
-
if len(idxs) > max_markers_per_chrom:
|
| 260 |
-
idxs = np.random.choice(idxs, max_markers_per_chrom, replace=False)
|
| 261 |
-
idxs = sorted(idxs)
|
| 262 |
-
|
| 263 |
G = genotypes[:, idxs].copy()
|
| 264 |
-
|
| 265 |
-
std = G.std(axis=0)
|
| 266 |
-
std[std == 0] = 1
|
| 267 |
G = (G - G.mean(axis=0)) / std
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 268 |
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
mean_r2_per_bin = []
|
| 302 |
-
se_r2_per_bin = []
|
| 303 |
-
for b in bins:
|
| 304 |
-
mask = all_distances == b
|
| 305 |
-
if mask.sum() > 0:
|
| 306 |
-
mean_r2_per_bin.append(np.mean(all_r2[mask]))
|
| 307 |
-
se_r2_per_bin.append(np.std(all_r2[mask]) / np.sqrt(mask.sum()))
|
| 308 |
-
else:
|
| 309 |
-
mean_r2_per_bin.append(np.nan)
|
| 310 |
-
se_r2_per_bin.append(np.nan)
|
| 311 |
-
|
| 312 |
-
mean_r2_arr = np.array(mean_r2_per_bin)
|
| 313 |
-
se_arr = np.array(se_r2_per_bin)
|
| 314 |
-
|
| 315 |
-
# Find half-decay distance
|
| 316 |
-
start_r2 = mean_r2_arr[~np.isnan(mean_r2_arr)][0] if any(~np.isnan(mean_r2_arr)) else 1.0
|
| 317 |
-
half = start_r2 / 2
|
| 318 |
-
half_decay_dist = None
|
| 319 |
-
for i, r2 in enumerate(mean_r2_arr):
|
| 320 |
-
if not np.isnan(r2) and r2 <= half:
|
| 321 |
-
half_decay_dist = bins[i]
|
| 322 |
-
break
|
| 323 |
-
|
| 324 |
-
fig, axes = plt.subplots(1, 2, figsize=(16, 6))
|
| 325 |
-
|
| 326 |
-
# Left: LD decay curve
|
| 327 |
-
ax = axes[0]
|
| 328 |
-
valid = ~np.isnan(mean_r2_arr)
|
| 329 |
-
ax.fill_between(bins[valid],
|
| 330 |
-
(mean_r2_arr - se_arr)[valid].clip(0),
|
| 331 |
-
(mean_r2_arr + se_arr)[valid].clip(0, 1),
|
| 332 |
-
alpha=0.25, color='steelblue', label='±1 SE')
|
| 333 |
-
ax.plot(bins[valid], mean_r2_arr[valid], 'o-', color='steelblue',
|
| 334 |
-
markersize=5, lw=2, label='Mean r²')
|
| 335 |
-
ax.axhline(0.2, color='red', ls='--', lw=1.4, alpha=0.8, label='r²=0.2 (common LD threshold)')
|
| 336 |
-
if half_decay_dist:
|
| 337 |
-
ax.axvline(half_decay_dist, color='orange', ls='--', lw=1.4,
|
| 338 |
-
label=f'Half-decay at d={half_decay_dist}')
|
| 339 |
-
ax.set_xlabel('Marker Distance (index units)', fontsize=13, fontweight='bold')
|
| 340 |
-
ax.set_ylabel('Mean r²', fontsize=13, fontweight='bold')
|
| 341 |
-
ax.set_title('LD Decay Across All Chromosomes', fontsize=14, fontweight='bold')
|
| 342 |
-
ax.set_ylim(0, 1)
|
| 343 |
-
ax.legend(fontsize=10)
|
| 344 |
-
ax.spines['top'].set_visible(False)
|
| 345 |
-
ax.spines['right'].set_visible(False)
|
| 346 |
-
ax.grid(alpha=0.2)
|
| 347 |
-
|
| 348 |
-
# Right: Per-chromosome mean r²
|
| 349 |
-
ax2 = axes[1]
|
| 350 |
-
chroms_sorted = sorted(chrom_summary.keys(),
|
| 351 |
-
key=lambda x: (int(x) if x.isdigit() else 999, x))
|
| 352 |
-
mean_vals = [chrom_summary[c]['mean_r2'] for c in chroms_sorted]
|
| 353 |
-
colors = [CHROM_COLORS[i % len(CHROM_COLORS)] for i in range(len(chroms_sorted))]
|
| 354 |
-
bars = ax2.bar(range(len(chroms_sorted)), mean_vals, color=colors, edgecolor='black',
|
| 355 |
-
linewidth=0.6, alpha=0.85)
|
| 356 |
-
ax2.set_xticks(range(len(chroms_sorted)))
|
| 357 |
-
ax2.set_xticklabels(chroms_sorted, rotation=45 if len(chroms_sorted) > 10 else 0,
|
| 358 |
-
fontsize=9, ha='right')
|
| 359 |
-
ax2.set_xlabel('Chromosome', fontsize=13, fontweight='bold')
|
| 360 |
-
ax2.set_ylabel('Mean r²', fontsize=13, fontweight='bold')
|
| 361 |
-
ax2.set_title('Mean LD (r²) per Chromosome', fontsize=14, fontweight='bold')
|
| 362 |
-
ax2.set_ylim(0, 1)
|
| 363 |
-
ax2.spines['top'].set_visible(False)
|
| 364 |
-
ax2.spines['right'].set_visible(False)
|
| 365 |
-
ax2.grid(axis='y', alpha=0.25)
|
| 366 |
-
|
| 367 |
-
# Add value labels on bars
|
| 368 |
-
for bar, val in zip(bars, mean_vals):
|
| 369 |
-
ax2.text(bar.get_x() + bar.get_width() / 2, bar.get_height() + 0.01,
|
| 370 |
-
f'{val:.2f}', ha='center', va='bottom', fontsize=8)
|
| 371 |
-
|
| 372 |
-
plt.suptitle('Linkage Disequilibrium (LD) Analysis', fontsize=16, fontweight='bold', y=1.01)
|
| 373 |
-
plt.tight_layout()
|
| 374 |
-
plt.savefig(save_path, dpi=200, bbox_inches='tight')
|
| 375 |
plt.close(fig)
|
| 376 |
|
| 377 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 378 |
|
| 379 |
|
| 380 |
-
# ─────────────────────────────────────────────
|
| 381 |
-
# MAIN ANALYSIS
|
| 382 |
-
# ─────────────────────────────────────────────
|
| 383 |
def run_mta_analysis(input_file, target_markers):
|
| 384 |
try:
|
| 385 |
if input_file is None:
|
| 386 |
-
return ("Please upload a CSV file
|
| 387 |
-
None, None, None, None, None)
|
| 388 |
|
| 389 |
-
|
| 390 |
-
temp_dir = tempfile.mkdtemp()
|
| 391 |
results_dir = os.path.join(temp_dir, 'results')
|
| 392 |
plots_dir = os.path.join(results_dir, 'plots')
|
| 393 |
-
for
|
| 394 |
-
os.makedirs(
|
| 395 |
-
|
| 396 |
-
# ── LOAD DATA ──────────────────────────────
|
| 397 |
-
# Expected format:
|
| 398 |
-
# Col 0 : Sample ID
|
| 399 |
-
# Col 1 : Chromosome (row 0 = header "Chromosome", row 1+ = values)
|
| 400 |
-
# Col 2 : Phenotype (row 0 = header "Phenotype", row 1+ = values)
|
| 401 |
-
# Col 3+: Markers (row 0 = marker names, row 1 = chr info, row 2+ = genotype scores)
|
| 402 |
-
#
|
| 403 |
-
# HOWEVER – original script treats row 1 as chromosome info for markers.
|
| 404 |
-
# We preserve that logic but fix column indexing.
|
| 405 |
|
|
|
|
| 406 |
df = pd.read_csv(input_file, sep=',', header=0)
|
| 407 |
-
|
| 408 |
-
|
| 409 |
-
# Row 1+ = actual sample data
|
| 410 |
-
# Col 0 = ID, Col 1 = Chromosome (sample chrom — skip), Col 2 = Phenotype, Col 3+ = Markers
|
| 411 |
-
|
| 412 |
-
# --- Extract marker chromosome info (first data row) ---
|
| 413 |
-
marker_cols = df.columns[3:].tolist() # marker column names
|
| 414 |
-
chrom_info_row = df.iloc[0, 3:].values.astype(str) # chr per marker
|
| 415 |
chromosome_dict = {m: c for m, c in zip(marker_cols, chrom_info_row)}
|
| 416 |
|
| 417 |
-
|
| 418 |
-
|
| 419 |
-
|
| 420 |
-
|
| 421 |
-
sample_chrom = df_data.iloc[:, 1].astype(str).values # sample-level chrom (if any)
|
| 422 |
-
phenotypes = pd.to_numeric(df_data.iloc[:, 2], errors='coerce').values
|
| 423 |
-
genotypes = df_data.iloc[:, 3:].apply(pd.to_numeric, errors='coerce').values
|
| 424 |
marker_names = marker_cols
|
| 425 |
|
| 426 |
unique_chromosomes = sorted(set(chrom_info_row),
|
| 427 |
key=lambda x: (int(x) if x.isdigit() else 999, x))
|
| 428 |
-
|
| 429 |
n_samples = len(sample_ids)
|
| 430 |
n_markers = len(marker_names)
|
| 431 |
|
| 432 |
-
# ── QC ──
|
| 433 |
-
|
| 434 |
-
|
| 435 |
-
|
| 436 |
maf = np.array([
|
| 437 |
-
min(np.nanmean(genotypes[:,
|
| 438 |
-
|
| 439 |
-
|
| 440 |
-
|
| 441 |
-
|
| 442 |
-
|
| 443 |
-
|
| 444 |
-
|
| 445 |
-
|
| 446 |
-
|
| 447 |
-
|
| 448 |
-
|
| 449 |
-
|
| 450 |
-
|
| 451 |
-
|
| 452 |
-
n_removed_markers = n_markers - len(marker_names_qc)
|
| 453 |
-
n_removed_samples = n_samples - len(sample_ids_qc)
|
| 454 |
-
|
| 455 |
-
# Impute missing
|
| 456 |
-
for i in range(genotypes_qc.shape[1]):
|
| 457 |
-
col = genotypes_qc[:, i]
|
| 458 |
mask = np.isnan(col)
|
| 459 |
if mask.any():
|
| 460 |
-
|
| 461 |
-
|
| 462 |
-
TARGET_MARKERS = min(int(target_markers), len(marker_names_qc))
|
| 463 |
|
| 464 |
-
|
| 465 |
-
p_values = np.ones(len(marker_names_qc))
|
| 466 |
-
gwas_effects = np.zeros(len(marker_names_qc))
|
| 467 |
-
gwas_se = np.zeros(len(marker_names_qc))
|
| 468 |
|
| 469 |
-
|
| 470 |
-
|
| 471 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 472 |
try:
|
| 473 |
-
|
| 474 |
-
|
| 475 |
-
|
| 476 |
-
|
| 477 |
-
except
|
| 478 |
-
pass
|
| 479 |
-
|
| 480 |
-
bonf_thresh = -np.log10(0.05 / len(marker_names_qc))
|
| 481 |
-
n_sig = int(np.sum(p_values < 0.05 / len(marker_names_qc)))
|
| 482 |
-
n_suggestive = int(np.sum(p_values < 1e-5))
|
| 483 |
-
|
| 484 |
-
# ── ML FEATURE SELECTION ───────────────────
|
| 485 |
-
scaler = StandardScaler()
|
| 486 |
-
X = scaler.fit_transform(genotypes_qc)
|
| 487 |
-
y = phenotypes_qc
|
| 488 |
-
|
| 489 |
-
rf_fs = RandomForestRegressor(n_estimators=100, max_depth=10,
|
| 490 |
-
random_state=42, n_jobs=-1)
|
| 491 |
-
rf_fs.fit(X, y)
|
| 492 |
-
rf_top = set(np.argsort(rf_fs.feature_importances_)[-TARGET_MARKERS:])
|
| 493 |
|
| 494 |
-
|
| 495 |
-
|
|
|
|
| 496 |
|
| 497 |
-
|
| 498 |
-
|
|
|
|
|
|
|
| 499 |
|
| 500 |
-
|
|
|
|
|
|
|
| 501 |
gb_fs.fit(X, y)
|
| 502 |
-
|
| 503 |
-
|
| 504 |
-
|
| 505 |
-
|
| 506 |
-
enet_top = set(np.argsort(np.abs(enet_fs.coef_))[-TARGET_MARKERS:])
|
| 507 |
|
| 508 |
-
votes = np.zeros(len(
|
| 509 |
-
for
|
| 510 |
-
|
| 511 |
-
|
|
|
|
| 512 |
|
| 513 |
-
|
| 514 |
-
|
| 515 |
|
| 516 |
-
# ──
|
| 517 |
-
X_sel = X[:,
|
| 518 |
-
|
| 519 |
|
| 520 |
-
|
| 521 |
('LASSO', LassoCV(cv=5, random_state=42, max_iter=10000)),
|
| 522 |
-
('RF', RandomForestRegressor(
|
| 523 |
-
|
| 524 |
-
('GB', GradientBoostingRegressor(n_estimators=200, max_depth=7,
|
| 525 |
-
random_state=42)),
|
| 526 |
('Ridge', Ridge(alpha=1.0)),
|
| 527 |
('ElasticNet', ElasticNetCV(cv=5, random_state=42, max_iter=5000)),
|
| 528 |
]
|
| 529 |
-
|
| 530 |
models = {}
|
| 531 |
-
for
|
| 532 |
obj.fit(X_sel, y)
|
| 533 |
-
pred
|
| 534 |
-
cv_r2 = cross_val_score(obj, X_sel, y, cv=
|
| 535 |
-
|
| 536 |
-
|
| 537 |
-
|
| 538 |
-
|
| 539 |
-
|
| 540 |
-
|
| 541 |
-
eff = np.zeros(X_sel.shape[1])
|
| 542 |
-
|
| 543 |
-
models[name] = {
|
| 544 |
-
'model': obj, 'pred': pred,
|
| 545 |
-
'r2': r2_score(y, pred),
|
| 546 |
-
'rmse': np.sqrt(mean_squared_error(y, pred)),
|
| 547 |
-
'cv': cv_r2,
|
| 548 |
-
'effects': eff,
|
| 549 |
-
}
|
| 550 |
|
| 551 |
best_name = max(models, key=lambda k: models[k]['cv'])
|
| 552 |
-
|
| 553 |
-
|
| 554 |
-
# ──
|
| 555 |
-
|
| 556 |
-
|
| 557 |
-
'
|
| 558 |
-
'
|
| 559 |
-
})
|
| 560 |
-
for nm, data in models.items():
|
| 561 |
-
pred_df[f'GEBV_{nm}'] = data['pred']
|
| 562 |
-
pred_df[f'Residual_{nm}'] = phenotypes_qc - data['pred']
|
| 563 |
pred_df['Best_GEBV'] = pred_df[f'GEBV_{best_name}']
|
| 564 |
pred_df['Rank'] = pred_df['Best_GEBV'].rank(ascending=False).astype(int)
|
| 565 |
-
pred_df
|
| 566 |
-
pred_df.to_csv(os.path.join(results_dir,
|
| 567 |
|
| 568 |
-
# MTA associations — with Chromosome column
|
| 569 |
mta_results = {}
|
| 570 |
-
for nm,
|
| 571 |
rows = []
|
| 572 |
-
for
|
| 573 |
-
|
| 574 |
-
|
| 575 |
-
|
| 576 |
-
|
| 577 |
-
|
| 578 |
-
|
| 579 |
-
|
| 580 |
-
|
| 581 |
-
|
| 582 |
-
|
| 583 |
-
|
| 584 |
-
|
| 585 |
-
|
| 586 |
-
|
| 587 |
-
|
| 588 |
-
|
| 589 |
-
|
| 590 |
-
|
| 591 |
-
|
| 592 |
-
|
| 593 |
-
|
| 594 |
-
|
| 595 |
-
|
| 596 |
-
|
| 597 |
-
|
| 598 |
-
|
| 599 |
-
|
| 600 |
-
|
| 601 |
-
|
| 602 |
-
|
| 603 |
-
'Chromosome': chrom,
|
| 604 |
-
'N_Markers': len(c_idx),
|
| 605 |
-
'N_Selected': c_sel,
|
| 606 |
-
'Min_Pvalue': c_pvals.min(),
|
| 607 |
-
'Best_logP': -np.log10(c_pvals.min() + 1e-300),
|
| 608 |
-
'Mean_logP': float(-np.log10(c_pvals + 1e-300).mean()),
|
| 609 |
-
'N_Significant': int((c_pvals < 0.05 / len(marker_names_qc)).sum()),
|
| 610 |
-
'N_Suggestive': int((c_pvals < 1e-5).sum()),
|
| 611 |
})
|
| 612 |
-
|
| 613 |
-
|
| 614 |
-
|
| 615 |
-
|
| 616 |
-
|
| 617 |
-
|
| 618 |
-
'
|
| 619 |
-
|
| 620 |
-
|
| 621 |
-
|
| 622 |
-
|
| 623 |
-
|
| 624 |
-
|
| 625 |
-
|
| 626 |
-
|
| 627 |
-
|
| 628 |
-
|
| 629 |
-
|
| 630 |
-
|
| 631 |
-
|
| 632 |
-
|
| 633 |
-
|
| 634 |
-
|
| 635 |
-
|
| 636 |
-
|
| 637 |
-
|
| 638 |
-
|
| 639 |
-
|
| 640 |
-
|
| 641 |
-
# 2) QQ plot
|
| 642 |
-
qq_path = os.path.join(plots_dir, 'qq_plot.png')
|
| 643 |
-
lambda_gc = plot_qq(p_values, qq_path)
|
| 644 |
-
|
| 645 |
-
# 3) LD decay
|
| 646 |
-
ld_path = os.path.join(plots_dir, 'ld_decay.png')
|
| 647 |
-
ld_chrom_summary = plot_ld_decay(genotypes_qc, marker_names_qc,
|
| 648 |
-
chromosome_qc, ld_path)
|
| 649 |
-
|
| 650 |
-
# 4) Model comparison
|
| 651 |
-
comp_path = os.path.join(plots_dir, 'model_comparison.png')
|
| 652 |
-
fig, ax = plt.subplots(figsize=(11, 6))
|
| 653 |
-
names_list = list(models.keys())
|
| 654 |
-
cv_r2_list = [models[m]['cv'] for m in names_list]
|
| 655 |
-
train_r2_list = [models[m]['r2'] for m in names_list]
|
| 656 |
-
rmse_list = [models[m]['rmse'] for m in names_list]
|
| 657 |
-
x = np.arange(len(names_list))
|
| 658 |
-
w = 0.30
|
| 659 |
-
b1 = ax.bar(x - w, train_r2_list, w, label='Train R²',
|
| 660 |
-
color='#AED6F1', edgecolor='black', alpha=0.9)
|
| 661 |
-
b2 = ax.bar(x, cv_r2_list, w, label='CV R²',
|
| 662 |
-
color='#A9DFBF', edgecolor='black', alpha=0.9)
|
| 663 |
-
bi = names_list.index(best_name)
|
| 664 |
-
for b in [b1[bi], b2[bi]]:
|
| 665 |
-
b.set_edgecolor('red'); b.set_linewidth(2.5)
|
| 666 |
-
for xi, (tr, cv_r) in enumerate(zip(train_r2_list, cv_r2_list)):
|
| 667 |
-
ax.text(xi - w, tr + 0.01, f'{tr:.3f}', ha='center', va='bottom', fontsize=9)
|
| 668 |
-
ax.text(xi, cv_r + 0.01, f'{cv_r:.3f}', ha='center', va='bottom', fontsize=9)
|
| 669 |
-
ax.set_ylabel('R²', fontsize=13, fontweight='bold')
|
| 670 |
-
ax.set_title('Predictive Model Performance Comparison\n(Red border = Best CV model)',
|
| 671 |
-
fontsize=14, fontweight='bold')
|
| 672 |
-
ax.set_xticks(x); ax.set_xticklabels(names_list, fontsize=11)
|
| 673 |
-
ax.legend(fontsize=11); ax.set_ylim(0, 1.1)
|
| 674 |
-
ax.spines['top'].set_visible(False); ax.spines['right'].set_visible(False)
|
| 675 |
-
ax.grid(axis='y', alpha=0.25)
|
| 676 |
-
plt.tight_layout()
|
| 677 |
-
plt.savefig(comp_path, dpi=200, bbox_inches='tight'); plt.close(fig)
|
| 678 |
-
|
| 679 |
-
# 5) Observed vs Predicted
|
| 680 |
-
pred_path = os.path.join(plots_dir, 'observed_vs_predicted.png')
|
| 681 |
-
fig, ax = plt.subplots(figsize=(8, 7))
|
| 682 |
-
ax.scatter(phenotypes_qc, best_model['pred'],
|
| 683 |
-
alpha=0.65, s=55, edgecolors='black', lw=0.5, c='#7D3C98')
|
| 684 |
-
lims = [min(phenotypes_qc.min(), best_model['pred'].min()),
|
| 685 |
-
max(phenotypes_qc.max(), best_model['pred'].max())]
|
| 686 |
-
ax.plot(lims, lims, 'r--', lw=2)
|
| 687 |
-
corr, _ = stats.pearsonr(phenotypes_qc, best_model['pred'])
|
| 688 |
-
ax.set_xlabel('Observed Phenotype', fontsize=13, fontweight='bold')
|
| 689 |
-
ax.set_ylabel('Predicted GEBV', fontsize=13, fontweight='bold')
|
| 690 |
-
ax.set_title(
|
| 691 |
-
f'Best Model ({best_name}): Observed vs Predicted\n'
|
| 692 |
-
f'CV R² = {best_model["cv"]:.4f} | RMSE = {best_model["rmse"]:.4f} | r = {corr:.4f}',
|
| 693 |
-
fontsize=13, fontweight='bold')
|
| 694 |
-
ax.grid(alpha=0.2); ax.spines['top'].set_visible(False); ax.spines['right'].set_visible(False)
|
| 695 |
-
plt.tight_layout()
|
| 696 |
-
plt.savefig(pred_path, dpi=200, bbox_inches='tight'); plt.close(fig)
|
| 697 |
-
|
| 698 |
-
# 6) Top marker effects (best model)
|
| 699 |
-
top_eff_path = os.path.join(plots_dir, 'top_marker_effects.png')
|
| 700 |
-
top_mta = mta_results[best_name].head(30)
|
| 701 |
-
fig, ax = plt.subplots(figsize=(12, 8))
|
| 702 |
-
colors_bar = [CHROM_COLORS[
|
| 703 |
-
sorted(set(chromosome_qc),
|
| 704 |
-
key=lambda x: (int(x) if x.isdigit() else 999, x)).index(c)
|
| 705 |
-
% len(CHROM_COLORS)]
|
| 706 |
-
for c in top_mta['Chromosome']]
|
| 707 |
-
bars = ax.barh(range(len(top_mta)),
|
| 708 |
-
top_mta[f'Effect_{best_name}'].values,
|
| 709 |
-
color=colors_bar, edgecolor='black', linewidth=0.5, alpha=0.85)
|
| 710 |
-
ax.set_yticks(range(len(top_mta)))
|
| 711 |
-
ax.set_yticklabels(
|
| 712 |
-
[f"{row['Marker']} (Chr {row['Chromosome']})"
|
| 713 |
-
for _, row in top_mta.iterrows()],
|
| 714 |
-
fontsize=9)
|
| 715 |
-
ax.invert_yaxis()
|
| 716 |
-
ax.set_xlabel(f'Effect Size ({best_name})', fontsize=12, fontweight='bold')
|
| 717 |
-
ax.set_title(f'Top 30 Selected Markers — {best_name} Model', fontsize=14, fontweight='bold')
|
| 718 |
-
ax.spines['top'].set_visible(False); ax.spines['right'].set_visible(False)
|
| 719 |
-
ax.grid(axis='x', alpha=0.2)
|
| 720 |
-
plt.tight_layout()
|
| 721 |
-
plt.savefig(top_eff_path, dpi=200, bbox_inches='tight'); plt.close(fig)
|
| 722 |
-
|
| 723 |
-
# ── ZIP ────────────────────────────────────
|
| 724 |
-
zip_path = os.path.join(temp_dir, 'mta_results.zip')
|
| 725 |
-
with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
|
| 726 |
for root, _, files in os.walk(results_dir):
|
| 727 |
-
for
|
| 728 |
-
fp
|
| 729 |
-
|
| 730 |
-
|
| 731 |
-
|
| 732 |
-
#
|
| 733 |
-
if
|
| 734 |
-
|
| 735 |
-
|
| 736 |
-
|
| 737 |
-
else
|
| 738 |
-
|
| 739 |
-
|
| 740 |
-
|
| 741 |
-
|
| 742 |
-
|
| 743 |
-
|
| 744 |
-
|
| 745 |
-
|
| 746 |
-
|
| 747 |
-
else:
|
| 748 |
-
|
| 749 |
-
|
| 750 |
-
|
| 751 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 752 |
|
| 753 |
summary = f"""
|
| 754 |
-
#
|
| 755 |
-
|
| 756 |
-
---
|
| 757 |
-
|
| 758 |
-
## 📊 Dataset & QC Summary
|
| 759 |
-
| Metric | Value |
|
| 760 |
-
|--------|-------|
|
| 761 |
-
| Samples (raw) | {n_samples} |
|
| 762 |
-
| Samples after QC | {len(sample_ids_qc)} ({n_removed_samples} removed) |
|
| 763 |
-
| Markers (raw) | {n_markers} |
|
| 764 |
-
| Markers after QC | {len(marker_names_qc)} ({n_removed_markers} removed) |
|
| 765 |
-
| Markers selected | {TARGET_MARKERS} |
|
| 766 |
-
| Chromosomes | {len(unique_chromosomes)} ({', '.join(unique_chromosomes[:10])}{'...' if len(unique_chromosomes) > 10 else ''}) |
|
| 767 |
-
|
| 768 |
-
---
|
| 769 |
-
|
| 770 |
-
## 🔬 GWAS Results
|
| 771 |
| Metric | Value |
|
| 772 |
|--------|-------|
|
| 773 |
-
|
|
| 774 |
-
|
|
| 775 |
-
|
|
| 776 |
-
|
|
| 777 |
|
| 778 |
-
|
| 779 |
-
|
| 780 |
-
---
|
| 781 |
-
|
| 782 |
-
## 🔗 LD Analysis
|
| 783 |
| Metric | Value |
|
| 784 |
|--------|-------|
|
| 785 |
-
|
|
| 786 |
-
|
| 787 |
-
|
|
|
|
| 788 |
|
| 789 |
-
|
|
|
|
| 790 |
|
| 791 |
-
##
|
| 792 |
| Model | CV R² | Train R² | RMSE |
|
| 793 |
|-------|--------|-----------|------|
|
| 794 |
-
|
| 795 |
-
for nm, data in models.items():
|
| 796 |
-
star = " 🏆" if nm == best_name else ""
|
| 797 |
-
summary += f"| **{nm}{star}** | {data['cv']:.4f} | {data['r2']:.4f} | {data['rmse']:.4f} |\n"
|
| 798 |
-
|
| 799 |
-
summary += f"""
|
| 800 |
-
**Best Model: {best_name}** (highest CV R²)
|
| 801 |
|
| 802 |
-
**
|
| 803 |
|
| 804 |
-
|
| 805 |
-
|
| 806 |
-
## 🎯 Top 5 Selected Markers ({best_name})
|
| 807 |
| Rank | Marker | Chromosome | Effect | Votes | GWAS −log₁₀p |
|
| 808 |
-
|------|--------|------------|--------|-------|--------------
|
| 809 |
-
|
| 810 |
-
|
| 811 |
-
|
| 812 |
-
|
| 813 |
-
|
| 814 |
-
|
| 815 |
-
|
| 816 |
-
|
| 817 |
-
|
| 818 |
-
|
| 819 |
-
|
| 820 |
-
|
| 821 |
-
|
| 822 |
-
|
| 823 |
-
|
| 824 |
-
|
| 825 |
-
|
| 826 |
-
|
| 827 |
-
---
|
| 828 |
-
|
| 829 |
-
## 📁 Output Files
|
| 830 |
-
- `all_model_predictions.csv` — GEBVs and rankings for all samples
|
| 831 |
-
- `mta_associations_<Model>.csv` — Marker associations with **Chromosome column** ✅
|
| 832 |
-
- `chromosome_summary.csv` — Per-chromosome GWAS summary
|
| 833 |
-
- `qc_summary.csv` — Quality control statistics
|
| 834 |
-
- `plots/manhattan_plot.png` — Fixed Manhattan plot (no overlap)
|
| 835 |
-
- `plots/qq_plot.png` — QQ plot with 95% CI and λ
|
| 836 |
-
- `plots/ld_decay.png` — LD decay curve + per-chromosome r²
|
| 837 |
-
- `plots/model_comparison.png` — CV vs Train R² for all models
|
| 838 |
-
- `plots/observed_vs_predicted.png` — Best model prediction scatter
|
| 839 |
-
- `plots/top_marker_effects.png` — Top 30 markers colored by chromosome
|
| 840 |
"""
|
| 841 |
-
return summary,
|
| 842 |
|
| 843 |
except Exception as e:
|
| 844 |
import traceback
|
| 845 |
-
|
| 846 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 847 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 848 |
|
| 849 |
-
|
| 850 |
-
|
| 851 |
-
|
| 852 |
-
|
| 853 |
-
|
| 854 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 855 |
"""
|
| 856 |
|
| 857 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 858 |
|
| 859 |
-
|
| 860 |
-
|
| 861 |
-
|
|
|
|
| 862 |
|
| 863 |
-
|
| 864 |
-
- Col 1: Sample ID | Col 2: Chromosome | Col 3: Phenotype | Col 4+: Marker genotypes
|
| 865 |
-
- Row 1 (after header): Chromosome assignment per marker
|
| 866 |
-
- Rows 2+: Sample genotype data
|
| 867 |
-
---
|
| 868 |
-
""")
|
| 869 |
|
| 870 |
with gr.Row():
|
| 871 |
-
|
| 872 |
-
|
| 873 |
-
|
| 874 |
-
|
| 875 |
-
ID, Chromosome, Phenotype, M1, M2, M3, ...
|
| 876 |
-
-, -, -, 1, 1, 2, ... ← marker chromosome row
|
| 877 |
-
S1, 1, 45.2, 0, 1, 2, ...
|
| 878 |
-
S2, 2, 38.7, 1, 0, 1, ...
|
| 879 |
-
```
|
| 880 |
-
""")
|
| 881 |
-
input_file = gr.File(label="📂 Upload Input CSV", file_types=[".csv"])
|
| 882 |
-
target_markers = gr.Slider(100, 5000, value=3000, step=100,
|
| 883 |
-
label="Target Markers to Select",
|
| 884 |
-
info="Top markers for predictive modeling")
|
| 885 |
-
run_button = gr.Button("🚀 Run MTA Analysis", variant="primary", size="lg")
|
| 886 |
|
| 887 |
-
|
| 888 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 889 |
|
| 890 |
-
|
| 891 |
-
|
|
|
|
|
|
|
|
|
|
| 892 |
|
| 893 |
with gr.Row():
|
| 894 |
with gr.Column():
|
| 895 |
-
gr.
|
| 896 |
-
qq_output = gr.Image(
|
| 897 |
with gr.Column():
|
| 898 |
-
gr.
|
| 899 |
-
ld_output = gr.Image(
|
| 900 |
|
| 901 |
with gr.Row():
|
| 902 |
with gr.Column():
|
| 903 |
-
gr.
|
| 904 |
-
comparison_output = gr.Image(
|
| 905 |
with gr.Column():
|
| 906 |
-
gr.
|
| 907 |
-
prediction_output = gr.Image(
|
| 908 |
-
|
| 909 |
-
|
| 910 |
-
|
| 911 |
-
|
| 912 |
-
|
| 913 |
-
|
| 914 |
-
|
| 915 |
-
|
| 916 |
-
|
| 917 |
-
|
| 918 |
-
|
| 919 |
-
|
| 920 |
-
|
| 921 |
-
|
| 922 |
-
|
| 923 |
-
|
| 924 |
-
|
| 925 |
-
|
|
|
|
|
|
|
|
|
|
| 926 |
|
|
|
|
| 927 |
run_button.click(
|
| 928 |
fn=run_mta_analysis,
|
| 929 |
inputs=[input_file, target_markers],
|
| 930 |
outputs=[summary_output, manhattan_output, qq_output, ld_output,
|
| 931 |
-
comparison_output, prediction_output, download_output]
|
| 932 |
-
)
|
| 933 |
|
| 934 |
if __name__ == "__main__":
|
| 935 |
app.launch(share=True, show_error=True)
|
|
|
|
| 1 |
# -*- coding: utf-8 -*-
|
| 2 |
"""
|
| 3 |
+
MTA Analysis Tool v4.0
|
| 4 |
+
Premium HTML/CSS frontend · Beautiful plots · Full ZIP download
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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.colors import LinearSegmentedColormap
|
| 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
|
|
|
|
| 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 |
+
# GLOBAL PLOT THEME — dark, cinematic, scientific
|
| 29 |
+
# ──────────────────────────────────────────────────────────────
|
| 30 |
+
DARK_BG = "#0d1117"
|
| 31 |
+
PANEL_BG = "#161b22"
|
| 32 |
+
GRID_COL = "#21262d"
|
| 33 |
+
TEXT_COL = "#e6edf3"
|
| 34 |
+
ACCENT1 = "#58a6ff" # blue
|
| 35 |
+
ACCENT2 = "#3fb950" # green
|
| 36 |
+
ACCENT3 = "#f78166" # red/coral
|
| 37 |
+
ACCENT4 = "#d2a8ff" # purple
|
| 38 |
+
GOLD = "#e3b341" # gold
|
| 39 |
+
|
| 40 |
+
CHROM_PALETTE = [
|
| 41 |
+
"#58a6ff","#3fb950","#f78166","#d2a8ff","#e3b341",
|
| 42 |
+
"#79c0ff","#56d364","#ff7b72","#bc8cff","#ffa657",
|
| 43 |
+
"#1f6feb","#238636","#da3633","#8957e5","#d29922",
|
| 44 |
+
"#388bfd","#2ea043","#f85149","#a371f7","#fb8f44",
|
| 45 |
+
"#0d419d","#196c2e",
|
|
|
|
| 46 |
]
|
| 47 |
|
| 48 |
+
def set_dark_style():
|
| 49 |
+
plt.rcParams.update({
|
| 50 |
+
'figure.facecolor': DARK_BG,
|
| 51 |
+
'axes.facecolor': PANEL_BG,
|
| 52 |
+
'axes.edgecolor': GRID_COL,
|
| 53 |
+
'axes.labelcolor': TEXT_COL,
|
| 54 |
+
'axes.titlecolor': TEXT_COL,
|
| 55 |
+
'xtick.color': TEXT_COL,
|
| 56 |
+
'ytick.color': TEXT_COL,
|
| 57 |
+
'text.color': TEXT_COL,
|
| 58 |
+
'grid.color': GRID_COL,
|
| 59 |
+
'grid.linewidth': 0.6,
|
| 60 |
+
'figure.dpi': 150,
|
| 61 |
+
'font.family': 'monospace',
|
| 62 |
+
'axes.spines.top': False,
|
| 63 |
+
'axes.spines.right': False,
|
| 64 |
+
'axes.spines.left': False,
|
| 65 |
+
'axes.spines.bottom':False,
|
| 66 |
+
})
|
| 67 |
+
|
| 68 |
+
# ──────────────────────────────────────────────────────────────
|
| 69 |
+
# PLOT 1 — MANHATTAN (ultra-premium)
|
| 70 |
+
# ──────────────────────────────────────────────────────────────
|
| 71 |
def plot_manhattan(marker_names, chromosomes, p_values, consensus_set,
|
| 72 |
bonf_thresh, save_path):
|
| 73 |
+
set_dark_style()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
|
| 75 |
+
unique_chroms = sorted(set(chromosomes),
|
| 76 |
+
key=lambda x: (int(x) if x.isdigit() else 999, x))
|
| 77 |
log_p = -np.log10(np.array(p_values) + 1e-300)
|
| 78 |
|
| 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, m in enumerate(marker_names):
|
| 83 |
c = chromosomes[i]
|
| 84 |
+
chrom_to_idx.setdefault(c, []).append(i)
|
|
|
|
|
|
|
| 85 |
|
| 86 |
+
offset = 0
|
| 87 |
+
for chrom in unique_chroms:
|
| 88 |
idxs = chrom_to_idx.get(chrom, [])
|
| 89 |
+
if not idxs: continue
|
|
|
|
|
|
|
| 90 |
for rank, idx in enumerate(idxs):
|
| 91 |
x_pos[idx] = offset + rank
|
| 92 |
chrom_centers[chrom] = offset + (len(idxs) - 1) / 2
|
| 93 |
offset += len(idxs) + GAP
|
| 94 |
|
| 95 |
+
fig = plt.figure(figsize=(22, 8), facecolor=DARK_BG)
|
| 96 |
+
ax = fig.add_subplot(111, facecolor=PANEL_BG)
|
| 97 |
|
| 98 |
+
# Subtle alternating band background per chromosome
|
| 99 |
for ci, chrom in enumerate(unique_chroms):
|
| 100 |
idxs = chrom_to_idx.get(chrom, [])
|
| 101 |
+
if not idxs: continue
|
| 102 |
+
x0 = x_pos[idxs[0]] - 0.5
|
| 103 |
+
x1 = x_pos[idxs[-1]] + 0.5
|
| 104 |
+
alpha = 0.06 if ci % 2 == 0 else 0.0
|
| 105 |
+
ax.axvspan(x0, x1, color='white', alpha=alpha, zorder=0)
|
| 106 |
+
|
| 107 |
+
# Plot per chromosome
|
| 108 |
+
for ci, chrom in enumerate(unique_chroms):
|
| 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 consensus_set]
|
| 114 |
+
sel = [i for i in idxs if i in consensus_set]
|
| 115 |
+
|
| 116 |
if normal:
|
| 117 |
ax.scatter(x_pos[normal], log_p[normal],
|
| 118 |
+
c=col, s=10, alpha=0.55, linewidths=0, zorder=2)
|
|
|
|
|
|
|
|
|
|
| 119 |
if sel:
|
| 120 |
+
# Glow effect: large faint circle behind
|
| 121 |
+
ax.scatter(x_pos[sel], log_p[sel],
|
| 122 |
+
c=ACCENT3, s=220, alpha=0.18, linewidths=0, zorder=3)
|
| 123 |
ax.scatter(x_pos[sel], log_p[sel],
|
| 124 |
+
c=ACCENT3, s=70, alpha=1.0,
|
| 125 |
+
edgecolors='white', linewidths=0.8,
|
| 126 |
+
marker='D', zorder=4)
|
| 127 |
|
| 128 |
+
# Threshold lines
|
| 129 |
+
ax.axhline(bonf_thresh, color=ACCENT3, ls='--', lw=1.6, alpha=0.9, zorder=5)
|
| 130 |
+
ax.text(offset * 0.01, bonf_thresh + 0.15,
|
| 131 |
+
f'Bonferroni α=0.05', color=ACCENT3, fontsize=9, va='bottom')
|
| 132 |
|
|
|
|
| 133 |
suggestive = -np.log10(1e-5)
|
| 134 |
if suggestive < bonf_thresh:
|
| 135 |
+
ax.axhline(suggestive, color=GOLD, ls=':', lw=1.2, alpha=0.7, zorder=5)
|
| 136 |
+
ax.text(offset * 0.01, suggestive + 0.15,
|
| 137 |
+
'Suggestive 1×10⁻⁵', color=GOLD, fontsize=9, va='bottom')
|
| 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=TEXT_COL)
|
| 147 |
ax.set_xlim(-GAP, offset)
|
| 148 |
+
ax.set_ylim(bottom=0, top=max(log_p) * 1.12)
|
| 149 |
|
| 150 |
+
ax.set_ylabel('−log₁₀(P-value)', fontsize=12, color=TEXT_COL, labelpad=10)
|
| 151 |
+
ax.set_xlabel('Chromosome', fontsize=12, color=TEXT_COL, labelpad=10)
|
| 152 |
+
ax.set_title('Genome-Wide Association Study · Manhattan Plot',
|
| 153 |
+
fontsize=16, color=TEXT_COL, fontweight='bold', pad=18)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 154 |
|
| 155 |
+
# Y grid lines only
|
| 156 |
+
ax.yaxis.grid(True, color=GRID_COL, linewidth=0.6, alpha=0.8)
|
| 157 |
+
ax.set_axisbelow(True)
|
| 158 |
|
| 159 |
+
# Legend
|
| 160 |
+
h1 = plt.Line2D([0],[0], color=ACCENT3, ls='--', lw=1.6, label='Bonferroni threshold')
|
| 161 |
+
h2 = mpatches.Patch(color=ACCENT3, label='Selected markers (ML consensus)')
|
| 162 |
+
h3 = plt.Line2D([0],[0], color=GOLD, ls=':', lw=1.2, label='Suggestive threshold')
|
| 163 |
+
ax.legend(handles=[h1, h2, h3], fontsize=9,
|
| 164 |
+
facecolor=PANEL_BG, edgecolor=GRID_COL,
|
| 165 |
+
labelcolor=TEXT_COL, loc='upper right')
|
| 166 |
+
|
| 167 |
+
# Tick styling
|
| 168 |
+
ax.tick_params(axis='both', colors=TEXT_COL, length=3)
|
| 169 |
+
|
| 170 |
+
plt.tight_layout(pad=1.5)
|
| 171 |
+
plt.savefig(save_path, dpi=200, bbox_inches='tight', facecolor=DARK_BG)
|
| 172 |
plt.close(fig)
|
| 173 |
|
| 174 |
|
| 175 |
+
# ──────────────────────────────────────────────────────────────
|
| 176 |
+
# PLOT 2 — QQ PLOT
|
| 177 |
+
# ──────────────────────────────────────────────────────────────
|
| 178 |
def plot_qq(p_values, save_path):
|
| 179 |
+
set_dark_style()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 180 |
|
| 181 |
+
pv = np.clip(np.array(p_values)[~np.isnan(p_values)], 1e-300, 1.0)
|
| 182 |
+
n = len(pv)
|
| 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 = -np.log10(stats.beta.ppf(0.025, np.arange(1,n+1), np.arange(n,0,-1)))
|
| 189 |
+
ci_lo = np.maximum(-np.log10(stats.beta.ppf(0.975, np.arange(1,n+1), np.arange(n,0,-1))), 0)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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=DARK_BG)
|
| 195 |
+
ax.set_facecolor(PANEL_BG)
|
| 196 |
|
| 197 |
+
ax.fill_between(log_exp, ci_lo, ci_up,
|
| 198 |
+
color=ACCENT1, alpha=0.15, label='95% CI')
|
| 199 |
+
ax.scatter(log_exp, log_obs,
|
| 200 |
+
c=log_obs, cmap='plasma', s=12, alpha=0.8,
|
| 201 |
linewidths=0, zorder=3)
|
| 202 |
+
maxv = max(log_obs.max(), log_exp.max()) * 1.05
|
| 203 |
+
ax.plot([0, maxv], [0, maxv], color=GRID_COL, lw=1.8, ls='--', zorder=2)
|
| 204 |
+
|
| 205 |
+
ax.set_xlabel('Expected −log₁₀(P)', fontsize=12, color=TEXT_COL)
|
| 206 |
+
ax.set_ylabel('Observed −log₁₀(P)', fontsize=12, color=TEXT_COL)
|
| 207 |
+
ax.set_title(f'QQ Plot · λ = {lam:.4f}', fontsize=15,
|
| 208 |
+
color=TEXT_COL, fontweight='bold', pad=14)
|
| 209 |
+
ax.set_xlim(0, maxv); ax.set_ylim(0, maxv)
|
| 210 |
+
|
| 211 |
+
lam_col = ACCENT2 if lam < 1.05 else (GOLD if lam < 1.10 else ACCENT3)
|
| 212 |
+
lam_txt = "Well-calibrated" if lam < 1.05 else ("Minor inflation" if lam < 1.10 else "Significant inflation")
|
| 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 |
+
set_dark_style()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 chrom in unique_chroms:
|
| 240 |
idxs = [i for i, c in enumerate(chromosomes) if c == chrom]
|
| 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 = genotypes[:, idxs].copy()
|
| 245 |
+
std = G.std(axis=0); std[std == 0] = 1
|
|
|
|
|
|
|
| 246 |
G = (G - G.mean(axis=0)) / std
|
| 247 |
+
nm = G.shape[1]
|
| 248 |
+
dl, rl = [], []
|
| 249 |
+
for i in range(nm - 1):
|
| 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 - i); rl.append(r2)
|
| 254 |
+
if dl:
|
| 255 |
+
all_d.extend(dl); all_r2.extend(rl)
|
| 256 |
+
chrom_mean[chrom] = np.mean(rl)
|
| 257 |
+
|
| 258 |
+
fig, axes = plt.subplots(1, 2, figsize=(16, 6), facecolor=DARK_BG)
|
| 259 |
+
|
| 260 |
+
# ── Left: decay curve ──
|
| 261 |
+
ax = axes[0]; ax.set_facecolor(PANEL_BG)
|
| 262 |
+
if all_d:
|
| 263 |
+
all_d = np.array(all_d); all_r2 = np.array(all_r2)
|
| 264 |
+
max_d = min(int(all_d.max()), 50)
|
| 265 |
+
bins = np.arange(1, max_d + 1)
|
| 266 |
+
mu, se = [], []
|
| 267 |
+
for b in bins:
|
| 268 |
+
m = all_d == b
|
| 269 |
+
if m.sum() > 0:
|
| 270 |
+
mu.append(np.mean(all_r2[m]))
|
| 271 |
+
se.append(np.std(all_r2[m]) / np.sqrt(m.sum()))
|
| 272 |
+
else:
|
| 273 |
+
mu.append(np.nan); se.append(np.nan)
|
| 274 |
+
mu = np.array(mu); se = np.array(se)
|
| 275 |
+
v = ~np.isnan(mu)
|
| 276 |
+
|
| 277 |
+
ax.fill_between(bins[v], np.clip(mu[v]-se[v],0,1), np.clip(mu[v]+se[v],0,1),
|
| 278 |
+
color=ACCENT1, alpha=0.18)
|
| 279 |
+
|
| 280 |
+
# Color gradient on the line
|
| 281 |
+
from matplotlib.collections import LineCollection
|
| 282 |
+
points = np.array([bins[v], mu[v]]).T.reshape(-1, 1, 2)
|
| 283 |
+
segs = np.concatenate([points[:-1], points[1:]], axis=1)
|
| 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='cool', s=20, zorder=5, linewidths=0)
|
| 288 |
+
|
| 289 |
+
ax.axhline(0.2, color=GOLD, ls='--', lw=1.2, alpha=0.8, label='r²=0.2 threshold')
|
| 290 |
+
|
| 291 |
+
# Half-decay
|
| 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 <= start_r2 / 2:
|
| 296 |
+
hd = bins[v][i]; break
|
| 297 |
+
if hd:
|
| 298 |
+
ax.axvline(hd, color=ACCENT3, ls='--', lw=1.2, alpha=0.8,
|
| 299 |
+
label=f'Half-decay d={hd}')
|
| 300 |
+
|
| 301 |
+
ax.set_xlabel('Marker Distance (index)', fontsize=11, color=TEXT_COL)
|
| 302 |
+
ax.set_ylabel('Mean r²', fontsize=11, color=TEXT_COL)
|
| 303 |
+
ax.set_title('LD Decay Curve', fontsize=14, color=TEXT_COL, fontweight='bold', pad=12)
|
| 304 |
+
ax.set_ylim(0, 1); ax.tick_params(colors=TEXT_COL)
|
| 305 |
+
ax.yaxis.grid(True, color=GRID_COL, lw=0.6)
|
| 306 |
+
ax.legend(fontsize=9, facecolor=PANEL_BG, edgecolor=GRID_COL, labelcolor=TEXT_COL)
|
| 307 |
+
|
| 308 |
+
# ── Right: per-chromosome bars ──
|
| 309 |
+
ax2 = axes[1]; ax2.set_facecolor(PANEL_BG)
|
| 310 |
+
if chrom_mean:
|
| 311 |
+
cs = sorted(chrom_mean.keys(), key=lambda x: (int(x) if x.isdigit() else 999, x))
|
| 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=DARK_BG, linewidth=0.8, alpha=0.9, width=0.65)
|
| 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=TEXT_COL)
|
| 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=7, color=TEXT_COL)
|
| 326 |
+
ax2.set_xlabel('Chromosome', fontsize=11, color=TEXT_COL)
|
| 327 |
+
ax2.set_ylabel('Mean r²', fontsize=11, color=TEXT_COL)
|
| 328 |
+
ax2.set_title('Mean LD per Chromosome', fontsize=14, color=TEXT_COL,
|
| 329 |
+
fontweight='bold', pad=12)
|
| 330 |
+
ax2.tick_params(colors=TEXT_COL)
|
| 331 |
+
ax2.yaxis.grid(True, color=GRID_COL, lw=0.6)
|
| 332 |
+
|
| 333 |
+
fig.suptitle('Linkage Disequilibrium Analysis', fontsize=16,
|
| 334 |
+
color=TEXT_COL, fontweight='bold', y=1.02)
|
| 335 |
+
plt.tight_layout(pad=2)
|
| 336 |
+
plt.savefig(save_path, dpi=200, bbox_inches='tight', facecolor=DARK_BG)
|
| 337 |
+
plt.close(fig)
|
| 338 |
+
return chrom_mean
|
| 339 |
+
|
| 340 |
+
|
| 341 |
+
# ──────────────────────────────────────────────────────────────
|
| 342 |
+
# PLOT 4 — MODEL COMPARISON
|
| 343 |
+
# ──────────────────────────────────────────────────────────────
|
| 344 |
+
def plot_model_comparison(models, best_name, save_path):
|
| 345 |
+
set_dark_style()
|
| 346 |
+
names = list(models.keys())
|
| 347 |
+
cv_r2 = [models[m]['cv'] for m in names]
|
| 348 |
+
train_r2 = [models[m]['r2'] for m in names]
|
| 349 |
+
rmse = [models[m]['rmse'] for m in names]
|
| 350 |
+
|
| 351 |
+
fig, axes = plt.subplots(1, 2, figsize=(14, 6), facecolor=DARK_BG)
|
| 352 |
+
|
| 353 |
+
# Bar chart
|
| 354 |
+
ax = axes[0]; ax.set_facecolor(PANEL_BG)
|
| 355 |
+
x = np.arange(len(names)); w = 0.35
|
| 356 |
+
b1 = ax.bar(x - w/2, train_r2, w, label='Train R²',
|
| 357 |
+
color=ACCENT1, alpha=0.8, edgecolor=DARK_BG, linewidth=0.8)
|
| 358 |
+
b2 = ax.bar(x + w/2, cv_r2, w, label='CV R²',
|
| 359 |
+
color=ACCENT2, alpha=0.8, edgecolor=DARK_BG, linewidth=0.8)
|
| 360 |
+
bi = names.index(best_name)
|
| 361 |
+
for b in [b1[bi], b2[bi]]:
|
| 362 |
+
b.set_edgecolor(GOLD); b.set_linewidth(2.5)
|
| 363 |
+
for xi, (tr, cv) in enumerate(zip(train_r2, cv_r2)):
|
| 364 |
+
ax.text(xi - w/2, tr + 0.01, f'{tr:.3f}', ha='center', va='bottom', fontsize=8, color=TEXT_COL)
|
| 365 |
+
ax.text(xi + w/2, cv + 0.01, f'{cv:.3f}', ha='center', va='bottom', fontsize=8, color=TEXT_COL)
|
| 366 |
+
ax.set_xticks(x); ax.set_xticklabels(names, fontsize=11, color=TEXT_COL)
|
| 367 |
+
ax.set_ylabel('R²', fontsize=12, color=TEXT_COL)
|
| 368 |
+
ax.set_title('R² Comparison\n(Gold border = best CV model)', fontsize=13, color=TEXT_COL, fontweight='bold')
|
| 369 |
+
ax.set_ylim(0, 1.15)
|
| 370 |
+
ax.yaxis.grid(True, color=GRID_COL, lw=0.6)
|
| 371 |
+
ax.tick_params(colors=TEXT_COL)
|
| 372 |
+
ax.legend(fontsize=10, facecolor=PANEL_BG, edgecolor=GRID_COL, labelcolor=TEXT_COL)
|
| 373 |
+
|
| 374 |
+
# RMSE radar-style horizontal bar
|
| 375 |
+
ax2 = axes[1]; ax2.set_facecolor(PANEL_BG)
|
| 376 |
+
cols = [GOLD if n == best_name else ACCENT4 for n in names]
|
| 377 |
+
bars = ax2.barh(names, rmse, color=cols, edgecolor=DARK_BG, linewidth=0.8, alpha=0.85)
|
| 378 |
+
for bar, val in zip(bars, rmse):
|
| 379 |
+
ax2.text(bar.get_width() + max(rmse)*0.01, bar.get_y() + bar.get_height()/2,
|
| 380 |
+
f'{val:.4f}', va='center', fontsize=10, color=TEXT_COL)
|
| 381 |
+
ax2.set_xlabel('RMSE', fontsize=12, color=TEXT_COL)
|
| 382 |
+
ax2.set_title('Root Mean Square Error\n(Lower is better)', fontsize=13, color=TEXT_COL, fontweight='bold')
|
| 383 |
+
ax2.tick_params(colors=TEXT_COL)
|
| 384 |
+
ax2.xaxis.grid(True, color=GRID_COL, lw=0.6)
|
| 385 |
+
|
| 386 |
+
plt.tight_layout(pad=2)
|
| 387 |
+
plt.savefig(save_path, dpi=200, bbox_inches='tight', facecolor=DARK_BG)
|
| 388 |
+
plt.close(fig)
|
| 389 |
+
|
| 390 |
+
|
| 391 |
+
# ──────────────────────────────────────────────────────────────
|
| 392 |
+
# PLOT 5 — OBSERVED vs PREDICTED
|
| 393 |
+
# ──────────────────────────────────────────────────────────────
|
| 394 |
+
def plot_obs_pred(obs, pred, best_name, cv_r2, rmse, save_path):
|
| 395 |
+
set_dark_style()
|
| 396 |
+
fig, ax = plt.subplots(figsize=(8, 7), facecolor=DARK_BG)
|
| 397 |
+
ax.set_facecolor(PANEL_BG)
|
| 398 |
|
| 399 |
+
# Density-colored scatter
|
| 400 |
+
from scipy.stats import gaussian_kde
|
| 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, c in enumerate(chrom_list_sorted)}
|
| 445 |
+
colors = [col_map.get(c, ACCENT1) for c in df['Chromosome']]
|
| 446 |
+
|
| 447 |
+
bars = ax.barh(range(len(df)), df[f'Effect_{best_name}'].values,
|
| 448 |
+
color=colors, edgecolor=DARK_BG, linewidth=0.6,
|
| 449 |
+
alpha=0.88, height=0.7)
|
| 450 |
+
|
| 451 |
+
ax.set_yticks(range(len(df)))
|
| 452 |
+
ax.set_yticklabels(
|
| 453 |
+
[f" {row['Marker']} Chr{row['Chromosome']}" for _, row in df.iterrows()],
|
| 454 |
+
fontsize=8.5, color=TEXT_COL)
|
| 455 |
+
ax.invert_yaxis()
|
| 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 |
+
# Chromosome color legend (compact)
|
| 464 |
+
handles = []
|
| 465 |
+
shown = set()
|
| 466 |
+
for _, row in df.iterrows():
|
| 467 |
+
c = row['Chromosome']
|
| 468 |
+
if c not in shown:
|
| 469 |
+
handles.append(mpatches.Patch(color=col_map.get(c, ACCENT1),
|
| 470 |
+
label=f'Chr {c}'))
|
| 471 |
+
shown.add(c)
|
| 472 |
+
ax.legend(handles=handles, fontsize=8, ncol=max(1, len(shown)//6 + 1),
|
| 473 |
+
facecolor=PANEL_BG, edgecolor=GRID_COL, labelcolor=TEXT_COL,
|
| 474 |
+
loc='lower right')
|
| 475 |
+
|
| 476 |
+
plt.tight_layout(pad=1.5)
|
| 477 |
+
plt.savefig(save_path, dpi=200, bbox_inches='tight', facecolor=DARK_BG)
|
| 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:
|
| 487 |
+
return ("⚠️ Please upload a CSV file.", None, None, None, None, None, None)
|
|
|
|
| 488 |
|
| 489 |
+
temp_dir = tempfile.mkdtemp()
|
|
|
|
| 490 |
results_dir = os.path.join(temp_dir, 'results')
|
| 491 |
plots_dir = os.path.join(results_dir, 'plots')
|
| 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 |
+
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_chromosomes = 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([
|
| 516 |
+
min(np.nanmean(genotypes[:,i])/2, 1-np.nanmean(genotypes[:,i])/2)
|
| 517 |
+
if not np.all(np.isnan(genotypes[:,i])) else 0
|
| 518 |
+
for i in range(n_markers)])
|
| 519 |
+
|
| 520 |
+
qc_m = (miss_m < 0.1) & (maf > 0.01)
|
| 521 |
+
qc_s = miss_s < 0.1
|
| 522 |
+
|
| 523 |
+
geno_qc = genotypes[qc_s][:, qc_m].copy()
|
| 524 |
+
pheno_qc = phenotypes[qc_s]
|
| 525 |
+
ids_qc = sample_ids[qc_s]
|
| 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)
|
| 532 |
if mask.any():
|
| 533 |
+
geno_qc[mask, i] = np.nanmean(col)
|
|
|
|
|
|
|
| 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 |
+
r = stats.linregress(mk, pheno_qc)
|
| 546 |
+
pvals[i] = r.pvalue
|
| 547 |
+
effects[i] = r.slope
|
| 548 |
+
gse[i] = r.stderr
|
| 549 |
+
except: pass
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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, random_state=42, n_jobs=-1)
|
| 561 |
+
rf_fs.fit(X, y)
|
| 562 |
+
gb_fs = GradientBoostingRegressor(100, max_depth=5, random_state=42)
|
| 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 |
+
mi = mutual_info_regression(X, y, random_state=42)
|
| 567 |
+
fsc, _ = f_regression(X, y)
|
|
|
|
| 568 |
|
| 569 |
+
votes = np.zeros(len(mnames_qc))
|
| 570 |
+
for arr in [rf_fs.feature_importances_, gb_fs.feature_importances_,
|
| 571 |
+
np.abs(en_fs.coef_), mi, fsc]:
|
| 572 |
+
top = np.argsort(arr)[-TARGET:]
|
| 573 |
+
votes[top] += 1
|
| 574 |
|
| 575 |
+
cons_idx = np.argsort(votes)[-TARGET:]
|
| 576 |
+
cons_set = set(cons_idx)
|
| 577 |
|
| 578 |
+
# ── MODELS ──
|
| 579 |
+
X_sel = X[:, cons_idx]
|
| 580 |
+
cv5 = KFold(n_splits=5, shuffle=True, random_state=42)
|
| 581 |
|
| 582 |
+
specs = [
|
| 583 |
('LASSO', LassoCV(cv=5, random_state=42, max_iter=10000)),
|
| 584 |
+
('RF', RandomForestRegressor(200, max_depth=15, random_state=42, n_jobs=-1)),
|
| 585 |
+
('GB', GradientBoostingRegressor(200, max_depth=7, random_state=42)),
|
|
|
|
|
|
|
| 586 |
('Ridge', Ridge(alpha=1.0)),
|
| 587 |
('ElasticNet', ElasticNetCV(cv=5, random_state=42, max_iter=5000)),
|
| 588 |
]
|
|
|
|
| 589 |
models = {}
|
| 590 |
+
for nm, obj in specs:
|
| 591 |
obj.fit(X_sel, y)
|
| 592 |
+
pred = obj.predict(X_sel)
|
| 593 |
+
cv_r2 = cross_val_score(obj, X_sel, y, cv=cv5, scoring='r2').mean()
|
| 594 |
+
eff = obj.feature_importances_ if hasattr(obj,'feature_importances_') else np.abs(obj.coef_)
|
| 595 |
+
models[nm] = {'pred': pred,
|
| 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 unique_chromosomes:
|
| 637 |
+
ci = [i for i, c in enumerate(chrom_qc) if c == ch]
|
| 638 |
+
if not ci: continue
|
| 639 |
+
cp = pvals[ci]
|
| 640 |
+
chr_rows.append({
|
| 641 |
+
'Chromosome': ch,
|
| 642 |
+
'N_Markers': len(ci),
|
| 643 |
+
'N_Selected': sum(1 for i in ci if i in cons_set),
|
| 644 |
+
'Min_Pvalue': cp.min(),
|
| 645 |
+
'Best_logP': -np.log10(cp.min()+1e-300),
|
| 646 |
+
'N_Significant': int((cp < 0.05/len(mnames_qc)).sum()),
|
| 647 |
+
'N_Suggestive': int((cp < 1e-5).sum()),
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
'Markers_Selected','Chromosomes','N_Significant','N_Suggestive'],
|
| 655 |
+
'Value': [n_samples, len(ids_qc), n_markers, len(mnames_qc),
|
| 656 |
+
TARGET, len(unique_chromosomes), n_sig, n_sugg]
|
| 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 |
+
comp_path = os.path.join(plots_dir,'model_comparison.png')
|
| 664 |
+
pred_path = os.path.join(plots_dir,'observed_vs_predicted.png')
|
| 665 |
+
top_path = os.path.join(plots_dir,'top_marker_effects.png')
|
| 666 |
+
|
| 667 |
+
plot_manhattan(mnames_qc, chrom_qc, pvals, cons_set, bonf, man_path)
|
| 668 |
+
lam = plot_qq(pvals, qq_path)
|
| 669 |
+
ld_summary = plot_ld_decay(geno_qc, chrom_qc, ld_path)
|
| 670 |
+
plot_model_comparison(models, best_name, comp_path)
|
| 671 |
+
plot_obs_pred(pheno_qc, best['pred'], best_name, best['cv'], best['rmse'], pred_path)
|
| 672 |
+
plot_top_markers(mta_results[best_name], best_name, unique_chromosomes, top_path)
|
| 673 |
+
|
| 674 |
+
# ── ZIP (ALL results) ──
|
| 675 |
+
zip_path = os.path.join(temp_dir, 'MTA_Analysis_Results.zip')
|
| 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:
|
| 679 |
+
fp = os.path.join(root, f)
|
| 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 |
+
acc_txt = (f"Excellent ({best['cv']*100:.1f}% variance explained)" if best['cv'] > 0.5
|
| 694 |
+
else f"Moderate ({best['cv']*100:.1f}%) — more samples may help" if best['cv'] > 0.2
|
| 695 |
+
else f"Low ({best['cv']*100:.1f}%) — consider larger dataset or mixed models")
|
| 696 |
+
|
| 697 |
+
model_rows = "\n".join(
|
| 698 |
+
f"| {'🏆 ' if nm==best_name else ''}{nm} | {d['cv']:.4f} | {d['r2']:.4f} | {d['rmse']:.4f} |"
|
| 699 |
+
for nm, d in models.items())
|
| 700 |
+
|
| 701 |
+
top5_rows = "\n".join(
|
| 702 |
+
f"| {int(r['Rank'])} | {r['Marker']} | Chr {r['Chromosome']} | "
|
| 703 |
+
f"{r[f'Effect_{best_name}']:.6f} | {int(r['Vote_Count'])}/5 | {r['GWAS_logP']:.3f} |"
|
| 704 |
+
for _, r in mta_results[best_name].head(5).iterrows())
|
| 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 |
+
## Dataset & QC
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 712 |
| Metric | Value |
|
| 713 |
|--------|-------|
|
| 714 |
+
| Samples (raw → QC) | {n_samples} → {len(ids_qc)} |
|
| 715 |
+
| Markers (raw → QC) | {n_markers} → {len(mnames_qc)} |
|
| 716 |
+
| Markers selected | **{TARGET}** |
|
| 717 |
+
| Chromosomes | {len(unique_chromosomes)} |
|
| 718 |
|
| 719 |
+
## GWAS
|
|
|
|
|
|
|
|
|
|
|
|
|
| 720 |
| Metric | Value |
|
| 721 |
|--------|-------|
|
| 722 |
+
| Bonferroni threshold | −log₁₀p = {bonf:.3f} |
|
| 723 |
+
| Significant markers | **{n_sig}** |
|
| 724 |
+
| Suggestive markers | {n_sugg} |
|
| 725 |
+
| Genomic inflation λ | **{lam:.4f}** — {lam_txt} |
|
| 726 |
|
| 727 |
+
## LD Summary
|
| 728 |
+
Global mean r² = **{gm_r2:.4f}** — {ld_txt}
|
| 729 |
|
| 730 |
+
## Model Performance
|
| 731 |
| Model | CV R² | Train R² | RMSE |
|
| 732 |
|-------|--------|-----------|------|
|
| 733 |
+
{model_rows}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 734 |
|
| 735 |
+
**Best Model:** {best_name} — {acc_txt}
|
| 736 |
|
| 737 |
+
## Top 5 Markers ({best_name})
|
|
|
|
|
|
|
| 738 |
| Rank | Marker | Chromosome | Effect | Votes | GWAS −log₁₀p |
|
| 739 |
+
|------|--------|------------|--------|-------|--------------|
|
| 740 |
+
{top5_rows}
|
| 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/model_comparison.png`
|
| 756 |
+
- `results/plots/observed_vs_predicted.png`
|
| 757 |
+
- `results/plots/top_marker_effects.png`
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 758 |
"""
|
| 759 |
+
return summary, man_path, qq_path, ld_path, comp_path, pred_path, zip_path
|
| 760 |
|
| 761 |
except Exception as e:
|
| 762 |
import traceback
|
| 763 |
+
return f"## Error\n```\n{e}\n\n{traceback.format_exc()}\n```", None,None,None,None,None,None
|
| 764 |
+
|
| 765 |
+
|
| 766 |
+
# ──────────────────────────────────────────────────────────────
|
| 767 |
+
# HTML / CSS THEME
|
| 768 |
+
# ──────────────────────────────────────────────────────────────
|
| 769 |
+
HEAD_HTML = """
|
| 770 |
+
<style>
|
| 771 |
+
@import url('https://fonts.googleapis.com/css2?family=Space+Mono:wght@400;700&family=Syne:wght@400;600;800&display=swap');
|
| 772 |
+
|
| 773 |
+
:root {
|
| 774 |
+
--bg: #0d1117;
|
| 775 |
+
--surface: #161b22;
|
| 776 |
+
--surface2: #21262d;
|
| 777 |
+
--border: #30363d;
|
| 778 |
+
--accent: #58a6ff;
|
| 779 |
+
--green: #3fb950;
|
| 780 |
+
--red: #f78166;
|
| 781 |
+
--gold: #e3b341;
|
| 782 |
+
--purple: #d2a8ff;
|
| 783 |
+
--text: #e6edf3;
|
| 784 |
+
--muted: #8b949e;
|
| 785 |
+
--radius: 12px;
|
| 786 |
+
}
|
| 787 |
+
|
| 788 |
+
/* ── Global ── */
|
| 789 |
+
body, .gradio-container {
|
| 790 |
+
background: var(--bg) !important;
|
| 791 |
+
color: var(--text) !important;
|
| 792 |
+
font-family: 'Syne', sans-serif !important;
|
| 793 |
+
}
|
| 794 |
+
|
| 795 |
+
/* ── Hero Banner ── */
|
| 796 |
+
.mta-hero {
|
| 797 |
+
background: linear-gradient(135deg, #0d1117 0%, #161b22 40%, #0d2137 100%);
|
| 798 |
+
border: 1px solid var(--border);
|
| 799 |
+
border-radius: 18px;
|
| 800 |
+
padding: 48px 56px 40px;
|
| 801 |
+
margin-bottom: 28px;
|
| 802 |
+
position: relative;
|
| 803 |
+
overflow: hidden;
|
| 804 |
+
}
|
| 805 |
+
.mta-hero::before {
|
| 806 |
+
content: '';
|
| 807 |
+
position: absolute;
|
| 808 |
+
top: -80px; right: -80px;
|
| 809 |
+
width: 320px; height: 320px;
|
| 810 |
+
border-radius: 50%;
|
| 811 |
+
background: radial-gradient(circle, rgba(88,166,255,0.10) 0%, transparent 70%);
|
| 812 |
+
pointer-events: none;
|
| 813 |
+
}
|
| 814 |
+
.mta-hero::after {
|
| 815 |
+
content: '';
|
| 816 |
+
position: absolute;
|
| 817 |
+
bottom: -60px; left: 120px;
|
| 818 |
+
width: 240px; height: 240px;
|
| 819 |
+
border-radius: 50%;
|
| 820 |
+
background: radial-gradient(circle, rgba(63,185,80,0.08) 0%, transparent 70%);
|
| 821 |
+
pointer-events: none;
|
| 822 |
+
}
|
| 823 |
+
.mta-badge {
|
| 824 |
+
display: inline-block;
|
| 825 |
+
background: rgba(88,166,255,0.12);
|
| 826 |
+
border: 1px solid rgba(88,166,255,0.30);
|
| 827 |
+
color: var(--accent);
|
| 828 |
+
font-family: 'Space Mono', monospace;
|
| 829 |
+
font-size: 11px;
|
| 830 |
+
letter-spacing: 2px;
|
| 831 |
+
padding: 4px 14px;
|
| 832 |
+
border-radius: 20px;
|
| 833 |
+
margin-bottom: 18px;
|
| 834 |
+
}
|
| 835 |
+
.mta-title {
|
| 836 |
+
font-family: 'Syne', sans-serif;
|
| 837 |
+
font-weight: 800;
|
| 838 |
+
font-size: 38px;
|
| 839 |
+
color: var(--text);
|
| 840 |
+
line-height: 1.15;
|
| 841 |
+
margin: 0 0 12px;
|
| 842 |
+
letter-spacing: -0.5px;
|
| 843 |
+
}
|
| 844 |
+
.mta-title span { color: var(--accent); }
|
| 845 |
+
.mta-subtitle {
|
| 846 |
+
color: var(--muted);
|
| 847 |
+
font-size: 15px;
|
| 848 |
+
font-family: 'Space Mono', monospace;
|
| 849 |
+
letter-spacing: 0.3px;
|
| 850 |
+
margin: 0;
|
| 851 |
+
}
|
| 852 |
+
.mta-pills {
|
| 853 |
+
display: flex; gap: 10px; flex-wrap: wrap;
|
| 854 |
+
margin-top: 22px;
|
| 855 |
+
}
|
| 856 |
+
.mta-pill {
|
| 857 |
+
background: var(--surface2);
|
| 858 |
+
border: 1px solid var(--border);
|
| 859 |
+
border-radius: 20px;
|
| 860 |
+
padding: 5px 14px;
|
| 861 |
+
font-size: 12px;
|
| 862 |
+
color: var(--muted);
|
| 863 |
+
font-family: 'Space Mono', monospace;
|
| 864 |
+
}
|
| 865 |
+
|
| 866 |
+
/* ── Section labels ── */
|
| 867 |
+
.section-label {
|
| 868 |
+
font-family: 'Space Mono', monospace;
|
| 869 |
+
font-size: 10px;
|
| 870 |
+
letter-spacing: 2.5px;
|
| 871 |
+
color: var(--accent);
|
| 872 |
+
text-transform: uppercase;
|
| 873 |
+
margin-bottom: 14px;
|
| 874 |
+
display: flex;
|
| 875 |
+
align-items: center;
|
| 876 |
+
gap: 10px;
|
| 877 |
+
}
|
| 878 |
+
.section-label::after {
|
| 879 |
+
content: '';
|
| 880 |
+
flex: 1;
|
| 881 |
+
height: 1px;
|
| 882 |
+
background: var(--border);
|
| 883 |
+
}
|
| 884 |
+
|
| 885 |
+
/* ── Format box ── */
|
| 886 |
+
.format-box {
|
| 887 |
+
background: var(--surface);
|
| 888 |
+
border: 1px solid var(--border);
|
| 889 |
+
border-left: 3px solid var(--accent);
|
| 890 |
+
border-radius: var(--radius);
|
| 891 |
+
padding: 20px 24px;
|
| 892 |
+
font-family: 'Space Mono', monospace;
|
| 893 |
+
font-size: 12px;
|
| 894 |
+
color: var(--muted);
|
| 895 |
+
line-height: 1.9;
|
| 896 |
+
}
|
| 897 |
+
.format-box .col-tag {
|
| 898 |
+
color: var(--accent);
|
| 899 |
+
font-weight: 700;
|
| 900 |
+
}
|
| 901 |
+
.format-box .val-tag { color: var(--green); }
|
| 902 |
+
.format-box .comment { color: var(--muted); opacity: 0.6; }
|
| 903 |
+
|
| 904 |
+
/* ── Run button ── */
|
| 905 |
+
.run-btn button {
|
| 906 |
+
background: linear-gradient(135deg, #1f6feb, #388bfd) !important;
|
| 907 |
+
border: none !important;
|
| 908 |
+
border-radius: 10px !important;
|
| 909 |
+
color: white !important;
|
| 910 |
+
font-family: 'Syne', sans-serif !important;
|
| 911 |
+
font-weight: 700 !important;
|
| 912 |
+
font-size: 16px !important;
|
| 913 |
+
letter-spacing: 0.5px !important;
|
| 914 |
+
padding: 14px 0 !important;
|
| 915 |
+
width: 100% !important;
|
| 916 |
+
cursor: pointer !important;
|
| 917 |
+
transition: all 0.2s ease !important;
|
| 918 |
+
box-shadow: 0 4px 24px rgba(31,111,235,0.35) !important;
|
| 919 |
+
}
|
| 920 |
+
.run-btn button:hover {
|
| 921 |
+
transform: translateY(-2px) !important;
|
| 922 |
+
box-shadow: 0 8px 32px rgba(31,111,235,0.50) !important;
|
| 923 |
+
}
|
| 924 |
+
|
| 925 |
+
/* ── Download button ── */
|
| 926 |
+
.dl-btn button, .dl-btn a {
|
| 927 |
+
background: linear-gradient(135deg, #238636, #2ea043) !important;
|
| 928 |
+
border: none !important;
|
| 929 |
+
border-radius: 10px !important;
|
| 930 |
+
color: white !important;
|
| 931 |
+
font-family: 'Syne', sans-serif !important;
|
| 932 |
+
font-weight: 700 !important;
|
| 933 |
+
font-size: 15px !important;
|
| 934 |
+
padding: 12px 0 !important;
|
| 935 |
+
width: 100% !important;
|
| 936 |
+
display: block !important;
|
| 937 |
+
text-align: center !important;
|
| 938 |
+
box-shadow: 0 4px 20px rgba(35,134,54,0.35) !important;
|
| 939 |
+
transition: all 0.2s ease !important;
|
| 940 |
+
text-decoration: none !important;
|
| 941 |
+
}
|
| 942 |
+
.dl-btn button:hover { transform: translateY(-2px) !important; }
|
| 943 |
+
|
| 944 |
+
/* ── Slider ── */
|
| 945 |
+
input[type=range] { accent-color: var(--accent) !important; }
|
| 946 |
+
|
| 947 |
+
/* ── Cards ── */
|
| 948 |
+
.stat-grid {
|
| 949 |
+
display: grid;
|
| 950 |
+
grid-template-columns: repeat(4, 1fr);
|
| 951 |
+
gap: 12px;
|
| 952 |
+
margin-bottom: 28px;
|
| 953 |
+
}
|
| 954 |
+
.stat-card {
|
| 955 |
+
background: var(--surface);
|
| 956 |
+
border: 1px solid var(--border);
|
| 957 |
+
border-radius: var(--radius);
|
| 958 |
+
padding: 18px 20px;
|
| 959 |
+
text-align: center;
|
| 960 |
+
}
|
| 961 |
+
.stat-card .stat-val {
|
| 962 |
+
font-family: 'Space Mono', monospace;
|
| 963 |
+
font-size: 28px;
|
| 964 |
+
font-weight: 700;
|
| 965 |
+
color: var(--accent);
|
| 966 |
+
}
|
| 967 |
+
.stat-card .stat-label {
|
| 968 |
+
font-size: 11px;
|
| 969 |
+
color: var(--muted);
|
| 970 |
+
margin-top: 4px;
|
| 971 |
+
text-transform: uppercase;
|
| 972 |
+
letter-spacing: 1px;
|
| 973 |
+
}
|
| 974 |
+
|
| 975 |
+
/* ── Plot containers ── */
|
| 976 |
+
.plot-card {
|
| 977 |
+
background: var(--surface);
|
| 978 |
+
border: 1px solid var(--border);
|
| 979 |
+
border-radius: var(--radius);
|
| 980 |
+
overflow: hidden;
|
| 981 |
+
}
|
| 982 |
+
.plot-title {
|
| 983 |
+
padding: 14px 20px 0;
|
| 984 |
+
font-family: 'Space Mono', monospace;
|
| 985 |
+
font-size: 11px;
|
| 986 |
+
color: var(--muted);
|
| 987 |
+
letter-spacing: 1.5px;
|
| 988 |
+
text-transform: uppercase;
|
| 989 |
+
}
|
| 990 |
+
|
| 991 |
+
/* ── Summary markdown ── */
|
| 992 |
+
.summary-wrap .prose, .summary-wrap p,
|
| 993 |
+
.summary-wrap table, .summary-wrap th, .summary-wrap td {
|
| 994 |
+
color: var(--text) !important;
|
| 995 |
+
font-family: 'Space Mono', monospace !important;
|
| 996 |
+
font-size: 12.5px !important;
|
| 997 |
+
}
|
| 998 |
+
.summary-wrap table {
|
| 999 |
+
width: 100%;
|
| 1000 |
+
border-collapse: collapse;
|
| 1001 |
+
margin: 12px 0;
|
| 1002 |
+
}
|
| 1003 |
+
.summary-wrap th {
|
| 1004 |
+
background: var(--surface2) !important;
|
| 1005 |
+
padding: 8px 12px !important;
|
| 1006 |
+
text-align: left;
|
| 1007 |
+
border: 1px solid var(--border) !important;
|
| 1008 |
+
color: var(--accent) !important;
|
| 1009 |
+
}
|
| 1010 |
+
.summary-wrap td {
|
| 1011 |
+
padding: 7px 12px !important;
|
| 1012 |
+
border: 1px solid var(--border) !important;
|
| 1013 |
+
}
|
| 1014 |
+
.summary-wrap h2 {
|
| 1015 |
+
color: var(--accent) !important;
|
| 1016 |
+
font-family: 'Syne', sans-serif !important;
|
| 1017 |
+
font-size: 15px !important;
|
| 1018 |
+
margin-top: 22px !important;
|
| 1019 |
+
border-bottom: 1px solid var(--border);
|
| 1020 |
+
padding-bottom: 6px;
|
| 1021 |
+
}
|
| 1022 |
+
|
| 1023 |
+
/* ── Pipeline steps ── */
|
| 1024 |
+
.pipeline {
|
| 1025 |
+
display: flex;
|
| 1026 |
+
gap: 0;
|
| 1027 |
+
margin: 28px 0 0;
|
| 1028 |
+
}
|
| 1029 |
+
.pipe-step {
|
| 1030 |
+
flex: 1;
|
| 1031 |
+
background: var(--surface);
|
| 1032 |
+
border: 1px solid var(--border);
|
| 1033 |
+
padding: 16px 14px;
|
| 1034 |
+
text-align: center;
|
| 1035 |
+
position: relative;
|
| 1036 |
+
}
|
| 1037 |
+
.pipe-step:not(:last-child)::after {
|
| 1038 |
+
content: '→';
|
| 1039 |
+
position: absolute;
|
| 1040 |
+
right: -13px;
|
| 1041 |
+
top: 50%;
|
| 1042 |
+
transform: translateY(-50%);
|
| 1043 |
+
color: var(--accent);
|
| 1044 |
+
font-size: 16px;
|
| 1045 |
+
z-index: 1;
|
| 1046 |
+
background: var(--surface);
|
| 1047 |
+
padding: 0 2px;
|
| 1048 |
+
}
|
| 1049 |
+
.pipe-step:first-child { border-radius: var(--radius) 0 0 var(--radius); }
|
| 1050 |
+
.pipe-step:last-child { border-radius: 0 var(--radius) var(--radius) 0; }
|
| 1051 |
+
.pipe-num {
|
| 1052 |
+
font-family: 'Space Mono', monospace;
|
| 1053 |
+
font-size: 18px;
|
| 1054 |
+
font-weight: 700;
|
| 1055 |
+
color: var(--accent);
|
| 1056 |
+
display: block;
|
| 1057 |
+
}
|
| 1058 |
+
.pipe-name {
|
| 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="mta-hero">
|
| 1085 |
+
<div class="mta-badge">GENOMICS · GWAS · ML</div>
|
| 1086 |
+
<h1 class="mta-title">Multi-Trait<br><span>Association Analysis</span></h1>
|
| 1087 |
+
<p class="mta-subtitle">GWAS · Genomic Prediction · LD Decay · ML Feature Selection</p>
|
| 1088 |
+
<div class="mta-pills">
|
| 1089 |
+
<span class="mta-pill">Manhattan Plot</span>
|
| 1090 |
+
<span class="mta-pill">QQ Plot + λ</span>
|
| 1091 |
+
<span class="mta-pill">LD Decay</span>
|
| 1092 |
+
<span class="mta-pill">5 ML Models</span>
|
| 1093 |
+
<span class="mta-pill">GEBV Ranking</span>
|
| 1094 |
+
<span class="mta-pill">ZIP Export</span>
|
| 1095 |
+
</div>
|
| 1096 |
+
</div>
|
| 1097 |
+
"""
|
| 1098 |
|
| 1099 |
+
FORMAT_HTML = """
|
| 1100 |
+
<div class="section-label">Input Format</div>
|
| 1101 |
+
<div class="format-box">
|
| 1102 |
+
<span class="col-tag">Col 1</span> Sample ID
|
| 1103 |
+
<span class="col-tag">Col 2</span> Chromosome
|
| 1104 |
+
<span class="col-tag">Col 3</span> Phenotype
|
| 1105 |
+
<span class="col-tag">Col 4+</span> Markers<br><br>
|
| 1106 |
+
<span class="col-tag">ID</span>, <span class="col-tag">Chr</span>, <span class="col-tag">Pheno</span>, <span class="val-tag">M0001</span>, <span class="val-tag">M0002</span>, ...<br>
|
| 1107 |
+
<span class="comment">- , - , - ,</span> <span class="val-tag">1</span> , <span class="val-tag">1</span> , ... <span class="comment">← marker chromosome row</span><br>
|
| 1108 |
+
S1 , 1 , <span class="val-tag">45.2</span> , <span class="val-tag">0</span> , <span class="val-tag">1</span> , ...<br>
|
| 1109 |
+
S2 , 2 , <span class="val-tag">38.7</span> , <span class="val-tag">1</span> , <span class="val-tag">2</span> , ...
|
| 1110 |
+
</div>
|
| 1111 |
"""
|
| 1112 |
|
| 1113 |
+
PIPELINE_HTML = """
|
| 1114 |
+
<div class="section-label" style="margin-top:32px">Analysis Pipeline</div>
|
| 1115 |
+
<div class="pipeline">
|
| 1116 |
+
<div class="pipe-step"><span class="pipe-num">01</span><span class="pipe-name">QC Filter</span></div>
|
| 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">ML Select</span></div>
|
| 1120 |
+
<div class="pipe-step"><span class="pipe-num">05</span><span class="pipe-name">5 Models</span></div>
|
| 1121 |
+
<div class="pipe-step"><span class="pipe-num">06</span><span class="pipe-name">Export ZIP</span></div>
|
| 1122 |
+
</div>
|
| 1123 |
+
"""
|
| 1124 |
|
| 1125 |
+
# ──────────────────────────────────────────────────────────────
|
| 1126 |
+
# GRADIO APP
|
| 1127 |
+
# ──────────────────────────────────────────────────────────────
|
| 1128 |
+
with gr.Blocks(css=HEAD_HTML, title="MTA Analysis") as app:
|
| 1129 |
|
| 1130 |
+
gr.HTML(HERO_HTML)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1131 |
|
| 1132 |
with gr.Row():
|
| 1133 |
+
# ── LEFT: controls ──
|
| 1134 |
+
with gr.Column(scale=1, min_width=320):
|
| 1135 |
+
gr.HTML(FORMAT_HTML)
|
| 1136 |
+
gr.HTML('<div class="section-label" style="margin-top:24px">Upload & Configure</div>')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1137 |
|
| 1138 |
+
input_file = gr.File(
|
| 1139 |
+
label="CSV Input File",
|
| 1140 |
+
file_types=[".csv"])
|
| 1141 |
+
|
| 1142 |
+
target_markers = gr.Slider(
|
| 1143 |
+
minimum=100, maximum=5000, value=3000, step=100,
|
| 1144 |
+
label="Target Markers to Select",
|
| 1145 |
+
info="Top markers used in predictive models")
|
| 1146 |
+
|
| 1147 |
+
with gr.Row(elem_classes=["run-btn"]):
|
| 1148 |
+
run_button = gr.Button("⚡ Run Analysis", variant="primary", size="lg")
|
| 1149 |
+
|
| 1150 |
+
gr.HTML(PIPELINE_HTML)
|
| 1151 |
+
|
| 1152 |
+
# ── RIGHT: summary ──
|
| 1153 |
+
with gr.Column(scale=2):
|
| 1154 |
+
gr.HTML('<div class="section-label">Results Summary</div>')
|
| 1155 |
+
with gr.Column(elem_classes=["summary-wrap"]):
|
| 1156 |
+
summary_output = gr.Markdown(
|
| 1157 |
+
value="*Results will appear here after analysis…*")
|
| 1158 |
|
| 1159 |
+
# ── PLOTS ──
|
| 1160 |
+
gr.HTML('<div class="section-label" style="margin-top:32px">Visualizations</div>')
|
| 1161 |
+
|
| 1162 |
+
gr.HTML('<div class="plot-title">GWAS — Manhattan Plot</div>')
|
| 1163 |
+
manhattan_output = gr.Image(show_label=False, elem_classes=["plot-card"])
|
| 1164 |
|
| 1165 |
with gr.Row():
|
| 1166 |
with gr.Column():
|
| 1167 |
+
gr.HTML('<div class="plot-title">QQ Plot — Genomic Inflation</div>')
|
| 1168 |
+
qq_output = gr.Image(show_label=False, elem_classes=["plot-card"])
|
| 1169 |
with gr.Column():
|
| 1170 |
+
gr.HTML('<div class="plot-title">Linkage Disequilibrium Decay</div>')
|
| 1171 |
+
ld_output = gr.Image(show_label=False, elem_classes=["plot-card"])
|
| 1172 |
|
| 1173 |
with gr.Row():
|
| 1174 |
with gr.Column():
|
| 1175 |
+
gr.HTML('<div class="plot-title">Model Performance Comparison</div>')
|
| 1176 |
+
comparison_output = gr.Image(show_label=False, elem_classes=["plot-card"])
|
| 1177 |
with gr.Column():
|
| 1178 |
+
gr.HTML('<div class="plot-title">Observed vs Predicted (Best Model)</div>')
|
| 1179 |
+
prediction_output = gr.Image(show_label=False, elem_classes=["plot-card"])
|
| 1180 |
+
|
| 1181 |
+
# ── DOWNLOAD ──
|
| 1182 |
+
gr.HTML('<div class="section-label" style="margin-top:32px">Export</div>')
|
| 1183 |
+
with gr.Row():
|
| 1184 |
+
with gr.Column(scale=1):
|
| 1185 |
+
gr.HTML("""
|
| 1186 |
+
<div style="background:#161b22;border:1px solid #30363d;border-radius:12px;padding:20px 24px;margin-bottom:8px">
|
| 1187 |
+
<div style="font-family:'Space Mono',monospace;font-size:11px;color:#8b949e;letter-spacing:1.5px;text-transform:uppercase;margin-bottom:10px">ZIP Contents</div>
|
| 1188 |
+
<div style="font-family:'Space Mono',monospace;font-size:12px;color:#e6edf3;line-height:2">
|
| 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 |
+
# ── WIRE UP ──
|
| 1203 |
run_button.click(
|
| 1204 |
fn=run_mta_analysis,
|
| 1205 |
inputs=[input_file, target_markers],
|
| 1206 |
outputs=[summary_output, manhattan_output, qq_output, ld_output,
|
| 1207 |
+
comparison_output, prediction_output, download_output])
|
|
|
|
| 1208 |
|
| 1209 |
if __name__ == "__main__":
|
| 1210 |
app.launch(share=True, show_error=True)
|