Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,24 +1,31 @@
|
|
| 1 |
# -*- coding: utf-8 -*-
|
| 2 |
"""
|
| 3 |
-
MTA Analysis Tool v7.
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
"""
|
| 23 |
|
| 24 |
import gradio as gr
|
|
@@ -27,501 +34,711 @@ import numpy as np
|
|
| 27 |
import matplotlib
|
| 28 |
matplotlib.use('Agg')
|
| 29 |
import matplotlib.pyplot as plt
|
|
|
|
| 30 |
from scipy import stats
|
| 31 |
-
from scipy.optimize import curve_fit
|
| 32 |
from scipy.interpolate import make_interp_spline
|
| 33 |
import os, warnings, tempfile, zipfile
|
| 34 |
from sklearn.linear_model import ElasticNetCV
|
| 35 |
from sklearn.preprocessing import StandardScaler
|
| 36 |
-
from sklearn.metrics import r2_score
|
| 37 |
warnings.filterwarnings('ignore')
|
| 38 |
|
| 39 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 40 |
# THEME
|
| 41 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 42 |
BG = "#FDFBFF"
|
| 43 |
-
PANEL = "#
|
| 44 |
-
GRID_C = "#
|
| 45 |
-
TEXT_C = "#
|
| 46 |
-
ACCENT = "#
|
| 47 |
-
RED_C = "#
|
| 48 |
-
GOLD_C = "#
|
| 49 |
-
TEAL_C = "#
|
| 50 |
-
|
|
|
|
| 51 |
|
| 52 |
CHROM_PALETTE = [
|
| 53 |
-
"#
|
| 54 |
-
"#
|
| 55 |
-
"#
|
| 56 |
-
"#
|
| 57 |
-
"#6366F1","#
|
| 58 |
]
|
| 59 |
|
| 60 |
-
def
|
| 61 |
plt.rcParams.update({
|
| 62 |
-
'figure.facecolor': BG,
|
| 63 |
-
'axes.edgecolor':
|
| 64 |
-
'axes.titlecolor':
|
| 65 |
-
'ytick.color':
|
| 66 |
-
'grid.color':
|
| 67 |
-
'figure.dpi':
|
| 68 |
-
'axes.spines.top':
|
| 69 |
-
'legend.framealpha':
|
| 70 |
})
|
| 71 |
|
|
|
|
| 72 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 73 |
-
#
|
| 74 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 75 |
|
| 76 |
-
def
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
for i, c in enumerate(chromosomes):
|
| 89 |
-
chrom_to_idx.setdefault(c, []).append(i)
|
| 90 |
-
|
| 91 |
-
offset = 0
|
| 92 |
-
for ch in unique_chroms:
|
| 93 |
-
idxs = chrom_to_idx.get(ch, [])
|
| 94 |
-
if not idxs: continue
|
| 95 |
-
for r, idx in enumerate(idxs):
|
| 96 |
-
x_pos[idx] = offset + r
|
| 97 |
-
offset += len(idxs) + GAP
|
| 98 |
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 102 |
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
ax2.axvspan(x_pos[idxs[0]] - 0.5, x_pos[idxs[-1]] + 0.5,
|
| 111 |
-
color='#EDE9FE', alpha=0.45, zorder=0)
|
| 112 |
|
| 113 |
-
|
| 114 |
-
normal = [i for i in idxs if i not in sig_set]
|
| 115 |
-
sel = [i for i in idxs if i in sig_set]
|
| 116 |
|
| 117 |
-
if normal:
|
| 118 |
-
ax1.scatter(x_pos[normal], log_p[normal],
|
| 119 |
-
c=col, s=10, alpha=0.65, linewidths=0, zorder=2)
|
| 120 |
-
if sel:
|
| 121 |
-
ax1.scatter(x_pos[sel], log_p[sel],
|
| 122 |
-
c=RED_C, s=200, alpha=0.18, linewidths=0, zorder=3)
|
| 123 |
-
ax1.scatter(x_pos[sel], log_p[sel],
|
| 124 |
-
c=RED_C, s=55, alpha=1.0,
|
| 125 |
-
edgecolors='white', linewidths=1.0,
|
| 126 |
-
marker='D', zorder=4)
|
| 127 |
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
|
|
|
|
|
|
|
|
|
| 139 |
|
| 140 |
-
ax1.set_xlim(-GAP, offset)
|
| 141 |
-
ax1.set_ylim(bottom=0, top=max(log_p.max() * 1.15, 1))
|
| 142 |
-
ax1.set_ylabel('βlogββ(P)', fontsize=12, fontweight='bold', labelpad=8)
|
| 143 |
-
ax1.set_title('GWAS Manhattan Plot with LOD Scores', fontsize=14, fontweight='bold', pad=12)
|
| 144 |
-
ax1.yaxis.grid(True, color=GRID_C, linewidth=0.7)
|
| 145 |
-
ax1.legend(loc='upper right', fontsize=9)
|
| 146 |
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
ax2.yaxis.grid(True, color=GRID_C, linewidth=0.7)
|
| 155 |
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 159 |
|
| 160 |
|
| 161 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 162 |
-
# LD COMPUTATION (vectorised)
|
| 163 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 164 |
|
| 165 |
-
def
|
| 166 |
-
"""
|
| 167 |
-
|
| 168 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 169 |
|
| 170 |
-
for lag in range(1, min(max_lag + 1,
|
| 171 |
-
x = G[:, :
|
| 172 |
-
y = G[:, lag:].astype(float)
|
| 173 |
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
num = (xm * ym).sum(axis=0)
|
| 178 |
-
denom = np.sqrt((xm**2).sum(axis=0) * (ym**2).sum(axis=0))
|
| 179 |
with np.errstate(invalid='ignore', divide='ignore'):
|
| 180 |
-
r
|
| 181 |
-
r2 = r
|
| 182 |
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
p11 = ((x == 2) & (y == 2)).mean(axis=0) / 2.0
|
| 187 |
D = p11 - p1 * p2
|
| 188 |
with np.errstate(invalid='ignore', divide='ignore'):
|
| 189 |
Dmax = np.where(D < 0,
|
| 190 |
-
np.minimum(p1
|
| 191 |
-
np.minimum(p1
|
| 192 |
dp = np.where(Dmax > 0, np.abs(D / Dmax), 0.0)
|
| 193 |
|
| 194 |
-
dist = np.abs(
|
| 195 |
|
| 196 |
-
|
| 197 |
-
all_r2.append(r2)
|
| 198 |
-
all_dp.append(dp)
|
| 199 |
|
| 200 |
-
if not
|
| 201 |
return np.array([]), np.array([]), np.array([])
|
| 202 |
-
|
| 203 |
-
return (np.concatenate(all_dist),
|
| 204 |
-
np.concatenate(all_r2),
|
| 205 |
-
np.concatenate(all_dp))
|
| 206 |
|
| 207 |
|
| 208 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 209 |
-
# PLOT: LD DECAY
|
| 210 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 211 |
|
| 212 |
-
def
|
| 213 |
"""
|
| 214 |
-
LD decay
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
|
|
|
| 221 |
"""
|
| 222 |
-
|
| 223 |
|
| 224 |
unique_chroms = sorted(set(chromosomes),
|
| 225 |
key=lambda x: (int(x) if str(x).isdigit() else 999, str(x)))
|
| 226 |
|
| 227 |
-
# ββ
|
| 228 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 229 |
chrom_stats = {}
|
| 230 |
|
| 231 |
for ch in unique_chroms:
|
| 232 |
-
idxs = [
|
| 233 |
if len(idxs) < 4:
|
| 234 |
continue
|
| 235 |
if len(idxs) > max_m:
|
| 236 |
idxs = sorted(np.random.choice(idxs, max_m, replace=False))
|
| 237 |
|
| 238 |
-
G
|
| 239 |
-
|
| 240 |
|
| 241 |
-
dist, r2, dp =
|
| 242 |
if len(dist) == 0:
|
| 243 |
continue
|
| 244 |
|
| 245 |
all_dist.extend(dist.tolist())
|
| 246 |
all_r2.extend(r2.tolist())
|
| 247 |
-
|
|
|
|
| 248 |
|
| 249 |
-
chrom_stats[ch] = {
|
|
|
|
|
|
|
| 250 |
'mean_r2': float(np.mean(r2)),
|
| 251 |
'mean_dprime': float(np.mean(dp)),
|
|
|
|
| 252 |
}
|
| 253 |
|
| 254 |
-
# ββ handle empty data ββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 255 |
if not all_dist:
|
| 256 |
fig, ax = plt.subplots(figsize=(10, 6), facecolor=BG)
|
| 257 |
-
ax.
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=BG)
|
| 261 |
plt.close(fig)
|
| 262 |
-
return chrom_stats
|
| 263 |
-
|
| 264 |
-
dist_arr = np.array(all_dist,
|
| 265 |
-
r2_arr = np.array(all_r2,
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
# clip
|
| 269 |
-
max_dist =
|
| 270 |
-
|
| 271 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 272 |
chrom_color = {str(ch): CHROM_PALETTE[i % len(CHROM_PALETTE)]
|
| 273 |
for i, ch in enumerate(unique_chroms)}
|
| 274 |
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 278 |
|
| 279 |
-
# ββ scatter
|
| 280 |
-
scatter_handles = []
|
| 281 |
for ch in unique_chroms:
|
| 282 |
key = str(ch)
|
| 283 |
-
|
| 284 |
-
if not
|
| 285 |
continue
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
| 318 |
-
|
| 319 |
-
|
| 320 |
-
except Exception:
|
| 321 |
-
decay_line = None
|
| 322 |
-
|
| 323 |
-
# ββ rΒ² = 0.2 reference dashed line ββββββββββββββββββββββββββββββββββββββ
|
| 324 |
-
ref_line = ax.axhline(0.2, color='#1E293B', ls='--', lw=1.5,
|
| 325 |
-
alpha=0.75, zorder=5, label='rΒ² = 0.2')
|
| 326 |
-
|
| 327 |
-
# ββ axes formatting ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 328 |
-
ax.set_xlim(0, max_dist)
|
| 329 |
-
ax.set_ylim(0, 1.04)
|
| 330 |
|
|
|
|
|
|
|
|
|
|
| 331 |
ax.set_xlabel('Genetic distance (cM)', fontsize=12, fontweight='bold',
|
| 332 |
-
color=TEXT_C, labelpad=
|
| 333 |
ax.set_ylabel('LD estimate (RΒ²)', fontsize=12, fontweight='bold',
|
| 334 |
-
color=TEXT_C, labelpad=
|
| 335 |
ax.set_title('LD Decay by Chromosome', fontsize=14, fontweight='bold',
|
| 336 |
-
color=TEXT_C, pad=
|
| 337 |
-
|
| 338 |
-
ax.
|
| 339 |
-
ax.yaxis.grid(True, color=GRID_C, linewidth=0.6, alpha=0.8)
|
| 340 |
ax.set_axisbelow(True)
|
| 341 |
|
| 342 |
-
#
|
| 343 |
-
for spine in ax.spines.values():
|
| 344 |
-
spine.set_edgecolor(GRID_C)
|
| 345 |
-
spine.set_linewidth(1.0)
|
| 346 |
-
|
| 347 |
-
# ββ legend βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 348 |
handles, labels = ax.get_legend_handles_labels()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 349 |
|
| 350 |
-
#
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
# build final legend: special entries first, then chromosomes
|
| 357 |
-
leg_handles = [h for h, _ in special_entries] + [h for h, _ in chrom_entries]
|
| 358 |
-
leg_labels = [l for _, l in special_entries] + [f'Chr {l}' for _, l in chrom_entries]
|
| 359 |
-
|
| 360 |
-
n_chr_cols = max(1, (len(chrom_entries) + 11) // 12) # β€12 rows per col
|
| 361 |
-
|
| 362 |
-
legend = ax.legend(
|
| 363 |
-
leg_handles, leg_labels,
|
| 364 |
-
title='Chr',
|
| 365 |
-
title_fontsize=9,
|
| 366 |
-
fontsize=7.5,
|
| 367 |
-
loc='upper right',
|
| 368 |
-
ncol=n_chr_cols,
|
| 369 |
-
framealpha=0.93,
|
| 370 |
-
edgecolor=GRID_C,
|
| 371 |
-
markerscale=2.0,
|
| 372 |
-
handlelength=1.4,
|
| 373 |
-
borderpad=0.8,
|
| 374 |
-
labelspacing=0.45,
|
| 375 |
)
|
| 376 |
-
|
| 377 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 378 |
|
| 379 |
-
plt.tight_layout(pad=1.8)
|
| 380 |
plt.savefig(save_path, dpi=130, bbox_inches='tight', facecolor=BG)
|
| 381 |
plt.close(fig)
|
| 382 |
|
| 383 |
-
return chrom_stats
|
| 384 |
|
| 385 |
|
| 386 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 387 |
-
# PLOT:
|
| 388 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 389 |
|
| 390 |
-
def
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
|
|
|
|
|
|
|
|
|
|
| 394 |
|
| 395 |
-
|
| 396 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 397 |
ax.set_facecolor(PANEL)
|
| 398 |
|
| 399 |
-
|
| 400 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 401 |
|
| 402 |
-
if len(avail) >= 2:
|
| 403 |
-
corr = results_df[avail[0]].corr(results_df[avail[1]])
|
| 404 |
-
ax.scatter(results_df[avail[0]], results_df[avail[1]],
|
| 405 |
-
alpha=0.5, s=20, color=ACCENT, edgecolors='white', linewidth=0.5)
|
| 406 |
-
ax.text(0.05, 0.95, f'r = {corr:.3f}', transform=ax.transAxes,
|
| 407 |
-
fontsize=11, fontweight='bold', va='top',
|
| 408 |
-
bbox=dict(boxstyle='round', facecolor=PANEL, alpha=0.8))
|
| 409 |
|
| 410 |
-
|
| 411 |
-
|
| 412 |
-
|
| 413 |
-
|
| 414 |
-
|
| 415 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 416 |
|
| 417 |
-
# Effect size histogram
|
| 418 |
ax = axes[1]
|
| 419 |
ax.set_facecolor(PANEL)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 420 |
|
| 421 |
-
|
| 422 |
-
|
| 423 |
-
|
| 424 |
-
|
| 425 |
-
|
| 426 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 427 |
|
| 428 |
-
|
| 429 |
-
ax
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 430 |
ax.set_title('Effect Size Distribution', fontsize=11, fontweight='bold')
|
| 431 |
ax.legend(fontsize=9)
|
| 432 |
ax.grid(True, color=GRID_C, lw=0.7)
|
| 433 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 434 |
plt.tight_layout(pad=1.5)
|
| 435 |
plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=BG)
|
| 436 |
plt.close(fig)
|
| 437 |
|
| 438 |
|
| 439 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 440 |
-
# GWAS MODELS
|
| 441 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 442 |
|
| 443 |
def linear_regression_gwas(genotypes, phenotypes):
|
| 444 |
-
|
| 445 |
-
|
| 446 |
-
|
| 447 |
-
|
| 448 |
-
|
| 449 |
-
r2_arr = np.zeros(n_markers)
|
| 450 |
-
|
| 451 |
-
y = phenotypes.astype(float)
|
| 452 |
-
for i in range(n_markers):
|
| 453 |
x = genotypes[:, i].astype(float)
|
| 454 |
-
if x.std() < 1e-9:
|
| 455 |
-
|
| 456 |
-
|
| 457 |
-
|
| 458 |
-
|
| 459 |
-
|
| 460 |
-
|
| 461 |
-
|
| 462 |
-
|
| 463 |
-
|
| 464 |
-
|
| 465 |
-
|
| 466 |
-
|
| 467 |
-
|
| 468 |
-
|
| 469 |
-
enet.fit(X_sc, phenotypes)
|
| 470 |
-
coef = enet.coef_
|
| 471 |
-
|
| 472 |
-
boot_coefs = []
|
| 473 |
rng = np.random.default_rng(42)
|
| 474 |
-
for _ in range(
|
| 475 |
idx = rng.integers(0, len(phenotypes), len(phenotypes))
|
| 476 |
eb = ElasticNetCV(cv=3, random_state=42, max_iter=1500)
|
| 477 |
-
eb.fit(
|
| 478 |
-
|
| 479 |
|
| 480 |
-
boot_arr = np.array(
|
| 481 |
-
|
| 482 |
for i in range(len(coef)):
|
| 483 |
sd = boot_arr[:, i].std()
|
| 484 |
if sd > 0:
|
| 485 |
-
z
|
| 486 |
-
|
| 487 |
-
return
|
| 488 |
-
|
| 489 |
-
|
| 490 |
-
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 491 |
-
# CSV PARSER
|
| 492 |
-
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 493 |
-
|
| 494 |
-
def parse_input_csv_enhanced(filepath):
|
| 495 |
-
"""Parse CSV input with chromosome and position info."""
|
| 496 |
-
df = pd.read_csv(filepath, header=0, dtype=str)
|
| 497 |
-
marker_cols = df.columns[2:].tolist()
|
| 498 |
-
chr_row = df.iloc[0]
|
| 499 |
-
chrom_dict, pos_dict = {}, {}
|
| 500 |
-
|
| 501 |
-
for m in marker_cols:
|
| 502 |
-
val = str(chr_row[m]).strip()
|
| 503 |
-
if ':' in val:
|
| 504 |
-
parts = val.split(':')
|
| 505 |
-
chrom_dict[m] = parts[0]
|
| 506 |
-
try: pos_dict[m] = float(parts[1])
|
| 507 |
-
except: pos_dict[m] = 0.0
|
| 508 |
-
elif '_' in val:
|
| 509 |
-
parts = val.split('_')
|
| 510 |
-
chrom_dict[m] = parts[0]
|
| 511 |
-
try: pos_dict[m] = float(parts[1]) if len(parts) > 1 else 0.0
|
| 512 |
-
except: pos_dict[m] = 0.0
|
| 513 |
-
else:
|
| 514 |
-
val = val[:-2] if val.endswith('.0') else val
|
| 515 |
-
chrom_dict[m] = val
|
| 516 |
-
pos_dict[m] = 0.0
|
| 517 |
-
|
| 518 |
-
df_s = df.iloc[1:].reset_index(drop=True)
|
| 519 |
-
sample_ids = df_s.iloc[:, 0].astype(str).values
|
| 520 |
-
phenotypes = pd.to_numeric(df_s.iloc[:, 1], errors='coerce').values
|
| 521 |
-
geno_raw = df_s[marker_cols].apply(pd.to_numeric, errors='coerce').replace(-1, np.nan)
|
| 522 |
-
positions = [pos_dict.get(m, 0.0) for m in marker_cols]
|
| 523 |
-
|
| 524 |
-
return sample_ids, phenotypes, geno_raw.values, marker_cols, chrom_dict, positions
|
| 525 |
|
| 526 |
|
| 527 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
|
@@ -529,234 +746,238 @@ def parse_input_csv_enhanced(filepath):
|
|
| 529 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 530 |
|
| 531 |
def run_mta_analysis(input_file, miss_rate_sample, miss_rate_marker, maf_thresh):
|
| 532 |
-
"""Fast GWAS analysis with only Linear Regression + ElasticNet."""
|
| 533 |
-
|
| 534 |
try:
|
| 535 |
if input_file is None:
|
| 536 |
-
return ("β οΈ Please upload a CSV file.",
|
|
|
|
| 537 |
|
| 538 |
-
|
| 539 |
-
|
| 540 |
-
|
| 541 |
-
for d in [
|
| 542 |
-
os.makedirs(d, exist_ok=True)
|
| 543 |
|
| 544 |
-
|
| 545 |
-
|
| 546 |
-
|
| 547 |
|
| 548 |
print("[Parse] Reading CSVβ¦")
|
| 549 |
-
(
|
| 550 |
-
|
| 551 |
-
|
| 552 |
-
|
| 553 |
-
|
| 554 |
-
|
| 555 |
-
|
| 556 |
-
|
| 557 |
-
|
| 558 |
-
|
| 559 |
-
|
| 560 |
-
|
| 561 |
-
|
| 562 |
-
for i in range(n_markers):
|
| 563 |
-
v = genotypes[:, i]
|
| 564 |
-
v = v[~np.isnan(v)]
|
| 565 |
if len(v):
|
| 566 |
-
f
|
| 567 |
maf[i] = min(f, 1 - f)
|
| 568 |
|
| 569 |
-
qc_m = (miss_m <
|
| 570 |
-
qc_s = miss_s <
|
| 571 |
-
|
| 572 |
-
|
| 573 |
-
for rs, rm in [(
|
| 574 |
-
(
|
| 575 |
-
|
| 576 |
-
|
| 577 |
-
if
|
| 578 |
-
qc_m =
|
| 579 |
-
|
| 580 |
-
|
| 581 |
-
|
| 582 |
-
f"< {rs*100:.0f}% / marker missing "
|
| 583 |
-
f"< {rm*100:.0f}%\n")
|
| 584 |
break
|
| 585 |
|
| 586 |
-
|
| 587 |
-
|
| 588 |
-
|
| 589 |
-
|
| 590 |
-
|
| 591 |
-
|
|
|
|
| 592 |
|
| 593 |
-
print(f"[QC] {len(
|
| 594 |
|
| 595 |
# Impute
|
| 596 |
-
|
| 597 |
-
|
| 598 |
-
|
| 599 |
-
|
| 600 |
-
|
| 601 |
-
|
| 602 |
-
|
| 603 |
-
|
| 604 |
-
|
| 605 |
-
|
| 606 |
-
|
| 607 |
-
|
| 608 |
-
|
| 609 |
-
|
| 610 |
-
|
| 611 |
-
|
| 612 |
-
|
| 613 |
-
f"Try increasing **Sample Missing Rate** slider to 50β80%.",
|
| 614 |
-
None, None, None, None
|
| 615 |
-
)
|
| 616 |
-
|
| 617 |
-
n_qc = len(mnames_qc)
|
| 618 |
-
bonf = 0.05 / n_qc
|
| 619 |
|
| 620 |
-
# ββ
|
| 621 |
print("[1/2] Linear Regressionβ¦")
|
| 622 |
-
|
| 623 |
|
| 624 |
print("[2/2] ElasticNetβ¦")
|
| 625 |
-
|
| 626 |
-
|
| 627 |
-
# ββ Results
|
| 628 |
-
|
| 629 |
-
'
|
| 630 |
-
'
|
| 631 |
-
'
|
| 632 |
-
'
|
| 633 |
-
'
|
| 634 |
-
'
|
| 635 |
-
'LR_LOD': -np.log10(
|
| 636 |
-
'Significant_LR': (
|
| 637 |
-
'EN_P':
|
| 638 |
-
'EN_Beta':
|
| 639 |
-
'Significant_EN': (
|
| 640 |
})
|
|
|
|
|
|
|
|
|
|
|
|
|
| 641 |
|
| 642 |
-
|
| 643 |
-
(gwas_df[['Significant_LR', 'Significant_EN']].sum(axis=1) >= 2).astype(int)
|
| 644 |
-
)
|
| 645 |
|
| 646 |
-
|
| 647 |
-
|
| 648 |
-
|
| 649 |
-
print("[Save] Writing results CSVβ¦")
|
| 650 |
-
gwas_df.to_csv(os.path.join(results_dir, 'gwas_results.csv'), index=False)
|
| 651 |
|
| 652 |
# ββ Plots βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 653 |
-
print("[
|
| 654 |
-
|
| 655 |
-
|
| 656 |
-
|
| 657 |
-
|
| 658 |
-
|
| 659 |
-
|
| 660 |
-
|
| 661 |
-
|
| 662 |
-
|
| 663 |
-
|
| 664 |
-
|
| 665 |
-
|
| 666 |
-
|
| 667 |
-
|
| 668 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 669 |
|
| 670 |
# ββ ZIP βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 671 |
-
|
| 672 |
-
zip_path = os.path.join(temp_dir, 'GWAS_Results.zip')
|
| 673 |
with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf:
|
| 674 |
-
for root, _, files in os.walk(
|
| 675 |
for f in files:
|
| 676 |
-
fp
|
| 677 |
-
zf.write(fp, os.path.relpath(fp,
|
| 678 |
-
|
| 679 |
-
# ββ Summary βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 680 |
-
ld_r2_mean = np.mean([v['mean_r2'] for v in ld_stats.values()]) if ld_stats else 0
|
| 681 |
-
ld_dp_mean = np.mean([v['mean_dprime'] for v in ld_stats.values()]) if ld_stats else 0
|
| 682 |
-
|
| 683 |
-
top10_cols = ['Rank', 'Marker', 'Chromosome', 'LR_P', 'LR_LOD', 'EN_P', 'Consensus_Sig']
|
| 684 |
-
top10_cols = [c for c in top10_cols if c in gwas_df.columns]
|
| 685 |
|
| 686 |
-
|
| 687 |
-
|
| 688 |
-
|
|
|
|
| 689 |
if isinstance(v, float):
|
| 690 |
-
return f"{v:.4e}" if (v
|
| 691 |
return str(v)
|
| 692 |
-
|
| 693 |
-
|
| 694 |
-
|
| 695 |
-
|
| 696 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 697 |
|
| 698 |
summary = f"""
|
| 699 |
-
## β
GWAS Analysis Complete
|
| 700 |
|
| 701 |
### π QC Summary
|
| 702 |
| Metric | Value |
|
| 703 |
|--------|-------|
|
| 704 |
-
| Samples (raw β QC) | {
|
| 705 |
-
| Markers (raw β QC) | {
|
| 706 |
-
| Chromosomes | **{len(set(
|
| 707 |
-
| MAF
|
| 708 |
-
| Sample missing
|
| 709 |
-
{
|
| 710 |
-
|
| 711 |
-
|
| 712 |
-
|
| 713 |
-
|
|
| 714 |
-
|
|
| 715 |
-
|
|
| 716 |
-
|
|
| 717 |
-
|
| 718 |
-
|
| 719 |
-
**
|
| 720 |
-
|
| 721 |
-
###
|
| 722 |
-
{
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 723 |
|
| 724 |
---
|
| 725 |
-
**
|
| 726 |
-
- `gwas_results.csv` β
|
| 727 |
-
- `
|
| 728 |
-
- `
|
| 729 |
-
- `
|
|
|
|
|
|
|
|
|
|
|
|
|
| 730 |
"""
|
| 731 |
-
print("[Done]
|
| 732 |
-
return (summary, man_path, ld_path,
|
|
|
|
| 733 |
|
| 734 |
except Exception as e:
|
| 735 |
import traceback
|
| 736 |
-
|
| 737 |
-
|
| 738 |
-
f"## β Error\n```\n{e}\n\n{traceback.format_exc()}\n```",
|
| 739 |
-
None, None, None, None
|
| 740 |
-
)
|
| 741 |
|
| 742 |
|
| 743 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 744 |
# GRADIO UI
|
| 745 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 746 |
|
| 747 |
-
|
| 748 |
-
.gradio-container
|
| 749 |
-
h1
|
| 750 |
-
.gr-button-primary { background: #8B5CF6 !important; }
|
| 751 |
"""
|
| 752 |
|
| 753 |
-
with gr.Blocks(css=
|
| 754 |
|
| 755 |
gr.Markdown("""
|
| 756 |
-
# π§¬
|
| 757 |
-
###
|
| 758 |
-
|
| 759 |
-
|
| 760 |
---
|
| 761 |
""")
|
| 762 |
|
|
@@ -765,61 +986,61 @@ with gr.Blocks(css=custom_css, title="MTA GWAS v7.3") as app:
|
|
| 765 |
gr.Markdown("""
|
| 766 |
### π CSV Format
|
| 767 |
```
|
| 768 |
-
ID,
|
| 769 |
-
-,
|
| 770 |
-
|
| 771 |
-
|
| 772 |
```
|
| 773 |
-
**Genotypes:** 0/1/
|
| 774 |
""")
|
| 775 |
input_file = gr.File(label="π Upload CSV", file_types=[".csv"])
|
| 776 |
|
| 777 |
with gr.Column(scale=1):
|
| 778 |
-
gr.Markdown("### βοΈ QC
|
| 779 |
-
|
| 780 |
-
|
| 781 |
-
|
| 782 |
-
|
| 783 |
-
|
| 784 |
-
|
| 785 |
-
|
| 786 |
gr.Markdown("""
|
| 787 |
-
###
|
| 788 |
-
-
|
| 789 |
-
-
|
| 790 |
-
-
|
|
|
|
|
|
|
|
|
|
| 791 |
""")
|
| 792 |
|
| 793 |
-
|
| 794 |
-
|
| 795 |
gr.Markdown("---")
|
| 796 |
|
| 797 |
-
|
| 798 |
-
summary_output = gr.Markdown(label="Summary")
|
| 799 |
|
| 800 |
with gr.Row():
|
| 801 |
-
|
| 802 |
-
|
| 803 |
-
with gr.Column():
|
| 804 |
-
ld_output = gr.Image(label="LD Decay (Scatter by Chromosome)")
|
| 805 |
|
| 806 |
with gr.Row():
|
| 807 |
-
|
|
|
|
| 808 |
|
| 809 |
with gr.Row():
|
| 810 |
-
|
|
|
|
| 811 |
|
| 812 |
gr.Markdown("""
|
| 813 |
---
|
| 814 |
-
**MTA GWAS v7.
|
| 815 |
""")
|
| 816 |
|
| 817 |
-
|
| 818 |
fn=run_mta_analysis,
|
| 819 |
-
inputs=[input_file,
|
| 820 |
-
outputs=[
|
| 821 |
-
|
| 822 |
-
show_progress=True
|
| 823 |
)
|
| 824 |
|
| 825 |
if __name__ == "__main__":
|
|
|
|
| 1 |
# -*- coding: utf-8 -*-
|
| 2 |
"""
|
| 3 |
+
MTA Analysis Tool v7.5 β Complete GWAS Platform
|
| 4 |
+
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 5 |
+
NEW in v7.5:
|
| 6 |
+
LD DECAY (fully reworked):
|
| 7 |
+
β’ Uses marker-rank distance (0,1,2β¦) converted to cM via Haldane's
|
| 8 |
+
mapping function so X-axis always has real spread
|
| 9 |
+
β’ Chromosome-coloured scatter dots (one dot per marker pair)
|
| 10 |
+
β’ Green filled cubic-spline median decay curve
|
| 11 |
+
β’ Annotates: half-decay distance, rΒ²=0.2 crossing, rΒ²=0.1 crossing
|
| 12 |
+
β’ Vertical lines + text labels showing EXACT decay positions
|
| 13 |
+
β’ Interpretation panel below plot (text summary)
|
| 14 |
+
β’ No raw bp/position shown β only cM distances
|
| 15 |
+
|
| 16 |
+
GWAS OUTPUTS (comprehensive):
|
| 17 |
+
β’ gwas_results.csv β full per-marker table
|
| 18 |
+
β’ top_significant.csv β Bonferroni-significant markers only
|
| 19 |
+
β’ ld_decay_stats.csv β per-chromosome LD decay statistics
|
| 20 |
+
β’ manhattan_lod.png β Manhattan + LOD panel
|
| 21 |
+
β’ ld_decay.png β LD decay scatter with annotations
|
| 22 |
+
β’ qq_plot.png β QQ plot (inflation Ξ»)
|
| 23 |
+
β’ model_comparison.png β LR vs EN comparison
|
| 24 |
+
β’ phenotype_dist.png β Phenotype distribution
|
| 25 |
+
β’ GWAS_Results.zip β all of the above
|
| 26 |
+
|
| 27 |
+
SPEED: Linear Regression (vectorised) + ElasticNet
|
| 28 |
+
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 29 |
"""
|
| 30 |
|
| 31 |
import gradio as gr
|
|
|
|
| 34 |
import matplotlib
|
| 35 |
matplotlib.use('Agg')
|
| 36 |
import matplotlib.pyplot as plt
|
| 37 |
+
import matplotlib.patches as mpatches
|
| 38 |
from scipy import stats
|
|
|
|
| 39 |
from scipy.interpolate import make_interp_spline
|
| 40 |
import os, warnings, tempfile, zipfile
|
| 41 |
from sklearn.linear_model import ElasticNetCV
|
| 42 |
from sklearn.preprocessing import StandardScaler
|
|
|
|
| 43 |
warnings.filterwarnings('ignore')
|
| 44 |
|
| 45 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 46 |
# THEME
|
| 47 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 48 |
BG = "#FDFBFF"
|
| 49 |
+
PANEL = "#F4EFFE"
|
| 50 |
+
GRID_C = "#E2D9F3"
|
| 51 |
+
TEXT_C = "#2D1B5E"
|
| 52 |
+
ACCENT = "#7C3AED"
|
| 53 |
+
RED_C = "#E11D48"
|
| 54 |
+
GOLD_C = "#D97706"
|
| 55 |
+
TEAL_C = "#0891B2"
|
| 56 |
+
GREEN_C = "#15803D"
|
| 57 |
+
PINK_C = "#DB2777"
|
| 58 |
|
| 59 |
CHROM_PALETTE = [
|
| 60 |
+
"#7C3AED","#DB2777","#059669","#0284C7","#D97706",
|
| 61 |
+
"#6D28D9","#BE185D","#047857","#0369A1","#B45309",
|
| 62 |
+
"#4F46E5","#9D174D","#065F46","#075985","#92400E",
|
| 63 |
+
"#7C3AED","#C026D3","#0F766E","#1D4ED8","#B45309",
|
| 64 |
+
"#6366F1","#EC4899","#10B981","#3B82F6","#F59E0B",
|
| 65 |
]
|
| 66 |
|
| 67 |
+
def _style():
|
| 68 |
plt.rcParams.update({
|
| 69 |
+
'figure.facecolor': BG, 'axes.facecolor': PANEL,
|
| 70 |
+
'axes.edgecolor': GRID_C,'axes.labelcolor': TEXT_C,
|
| 71 |
+
'axes.titlecolor': TEXT_C,'xtick.color': TEXT_C,
|
| 72 |
+
'ytick.color': TEXT_C,'text.color': TEXT_C,
|
| 73 |
+
'grid.color': GRID_C,'grid.linewidth': 0.7,
|
| 74 |
+
'figure.dpi': 120, 'font.family': 'DejaVu Sans',
|
| 75 |
+
'axes.spines.top': False, 'axes.spines.right': False,
|
| 76 |
+
'legend.framealpha':0.95, 'legend.edgecolor': GRID_C,
|
| 77 |
})
|
| 78 |
|
| 79 |
+
|
| 80 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 81 |
+
# CSV PARSER
|
| 82 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 83 |
|
| 84 |
+
def parse_input_csv(filepath):
|
| 85 |
+
"""
|
| 86 |
+
Expected format:
|
| 87 |
+
ID, Phenotype, M1, M2, ...
|
| 88 |
+
-, Chr, 1, 2, ... β chromosome row
|
| 89 |
+
Samp1, 45.2, 0, 1, ...
|
| 90 |
+
Chromosome cell may be: '1', '1:1234567', '1_1234567'
|
| 91 |
+
Genotypes: 0/1/2 (blank or -1 = missing)
|
| 92 |
+
"""
|
| 93 |
+
df = pd.read_csv(filepath, header=0, dtype=str)
|
| 94 |
+
marker_cols = df.columns[2:].tolist()
|
| 95 |
+
chr_row = df.iloc[0]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 96 |
|
| 97 |
+
chrom_dict, pos_dict = {}, {}
|
| 98 |
+
for m in marker_cols:
|
| 99 |
+
val = str(chr_row[m]).strip()
|
| 100 |
+
if ':' in val:
|
| 101 |
+
p = val.split(':')
|
| 102 |
+
chrom_dict[m] = p[0]
|
| 103 |
+
try: pos_dict[m] = float(p[1])
|
| 104 |
+
except: pos_dict[m] = 0.0
|
| 105 |
+
elif '_' in val:
|
| 106 |
+
p = val.split('_')
|
| 107 |
+
chrom_dict[m] = p[0]
|
| 108 |
+
try: pos_dict[m] = float(p[1]) if len(p) > 1 else 0.0
|
| 109 |
+
except: pos_dict[m] = 0.0
|
| 110 |
+
else:
|
| 111 |
+
val = val[:-2] if val.endswith('.0') else val
|
| 112 |
+
chrom_dict[m] = val
|
| 113 |
+
pos_dict[m] = 0.0
|
| 114 |
|
| 115 |
+
df_s = df.iloc[1:].reset_index(drop=True)
|
| 116 |
+
sample_ids = df_s.iloc[:, 0].astype(str).values
|
| 117 |
+
phenotypes = pd.to_numeric(df_s.iloc[:, 1], errors='coerce').values
|
| 118 |
+
geno_raw = (df_s[marker_cols]
|
| 119 |
+
.apply(pd.to_numeric, errors='coerce')
|
| 120 |
+
.replace(-1, np.nan))
|
| 121 |
+
positions = [pos_dict.get(m, 0.0) for m in marker_cols]
|
|
|
|
|
|
|
| 122 |
|
| 123 |
+
return sample_ids, phenotypes, geno_raw.values, marker_cols, chrom_dict, positions
|
|
|
|
|
|
|
| 124 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 125 |
|
| 126 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 127 |
+
# HALDANE cM CONVERSION
|
| 128 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββοΏ½οΏ½οΏ½βββ
|
| 129 |
|
| 130 |
+
def _marker_rank_to_cM(n_markers, avg_genome_cM=1500.0):
|
| 131 |
+
"""
|
| 132 |
+
Convert marker rank indices (0, 1, 2 β¦ n-1) to approximate cM positions.
|
| 133 |
+
Assumes markers are evenly spread across a genome of avg_genome_cM cM.
|
| 134 |
+
Returns an array of cM positions of length n_markers.
|
| 135 |
+
"""
|
| 136 |
+
if n_markers <= 1:
|
| 137 |
+
return np.array([0.0])
|
| 138 |
+
spacing = avg_genome_cM / (n_markers - 1) # cM per marker interval
|
| 139 |
+
return np.arange(n_markers, dtype=float) * spacing
|
| 140 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 141 |
|
| 142 |
+
def _positions_to_cM(positions):
|
| 143 |
+
"""
|
| 144 |
+
Convert raw positions (bp / kb / cM / unknown) to cM.
|
| 145 |
+
Falls back to marker-rank cM if positions are all zero or identical.
|
| 146 |
+
"""
|
| 147 |
+
pos = np.array(positions, dtype=float)
|
| 148 |
+
mx = np.nanmax(np.abs(pos))
|
|
|
|
| 149 |
|
| 150 |
+
if mx == 0 or np.all(pos == pos[0]):
|
| 151 |
+
# No usable position data β use marker rank
|
| 152 |
+
return _marker_rank_to_cM(len(pos)), "marker-rankβcM"
|
| 153 |
+
elif mx > 1_000_000:
|
| 154 |
+
return pos / 1_000_000.0, "bpΓ·1e6βcM"
|
| 155 |
+
elif mx > 1_000:
|
| 156 |
+
return pos / 1_000.0, "kbΓ·1e3βcM"
|
| 157 |
+
else:
|
| 158 |
+
return pos, "cM (raw)"
|
| 159 |
|
| 160 |
|
| 161 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 162 |
+
# LD COMPUTATION (vectorised, per-chromosome)
|
| 163 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 164 |
|
| 165 |
+
def _compute_ld_pairs(G, cM_pos, max_lag=50):
|
| 166 |
+
"""
|
| 167 |
+
Return arrays (dist_cM, r2, dp) for all lagged pairs within a chromosome.
|
| 168 |
+
G : (n_samples, n_markers) int/float genotype matrix
|
| 169 |
+
cM_pos : (n_markers,) cM positions
|
| 170 |
+
"""
|
| 171 |
+
n = G.shape[1]
|
| 172 |
+
dists, r2s, dps = [], [], []
|
| 173 |
|
| 174 |
+
for lag in range(1, min(max_lag + 1, n)):
|
| 175 |
+
x = G[:, :n - lag].astype(float)
|
| 176 |
+
y = G[:, lag: ].astype(float)
|
| 177 |
|
| 178 |
+
xm, ym = x - x.mean(0), y - y.mean(0)
|
| 179 |
+
num = (xm * ym).sum(0)
|
| 180 |
+
denom = np.sqrt((xm**2).sum(0) * (ym**2).sum(0))
|
|
|
|
|
|
|
| 181 |
with np.errstate(invalid='ignore', divide='ignore'):
|
| 182 |
+
r = np.where(denom > 0, num / denom, 0.0)
|
| 183 |
+
r2 = np.clip(r**2, 0, 1)
|
| 184 |
|
| 185 |
+
p1 = x.mean(0) / 2.0
|
| 186 |
+
p2 = y.mean(0) / 2.0
|
| 187 |
+
p11 = ((x == 2) & (y == 2)).mean(0) / 2.0
|
|
|
|
| 188 |
D = p11 - p1 * p2
|
| 189 |
with np.errstate(invalid='ignore', divide='ignore'):
|
| 190 |
Dmax = np.where(D < 0,
|
| 191 |
+
np.minimum(p1*(1-p2), (1-p1)*p2),
|
| 192 |
+
np.minimum(p1*p2, (1-p1)*(1-p2)))
|
| 193 |
dp = np.where(Dmax > 0, np.abs(D / Dmax), 0.0)
|
| 194 |
|
| 195 |
+
dist = np.abs(cM_pos[lag:] - cM_pos[:n - lag])
|
| 196 |
|
| 197 |
+
dists.append(dist); r2s.append(r2); dps.append(dp)
|
|
|
|
|
|
|
| 198 |
|
| 199 |
+
if not dists:
|
| 200 |
return np.array([]), np.array([]), np.array([])
|
| 201 |
+
return np.concatenate(dists), np.concatenate(r2s), np.concatenate(dps)
|
|
|
|
|
|
|
|
|
|
| 202 |
|
| 203 |
|
| 204 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 205 |
+
# PLOT: LD DECAY SCATTER (v7.5 β fully reworked)
|
| 206 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 207 |
|
| 208 |
+
def plot_ld_decay(genotypes, chromosomes, positions, save_path, max_m=120):
|
| 209 |
"""
|
| 210 |
+
Scatter-style LD decay plot:
|
| 211 |
+
β’ X-axis: cM distance between marker pairs (always has real spread)
|
| 212 |
+
β’ Y-axis: rΒ² (LD estimate)
|
| 213 |
+
β’ One dot per pair, coloured by chromosome
|
| 214 |
+
β’ Green filled cubic-spline median decay curve
|
| 215 |
+
β’ Vertical annotation lines: half-decay, rΒ²=0.2, rΒ²=0.1 crossings
|
| 216 |
+
β’ Interpretation panel below figure
|
| 217 |
+
Returns (chrom_stats dict, ld_interpretation str)
|
| 218 |
"""
|
| 219 |
+
_style()
|
| 220 |
|
| 221 |
unique_chroms = sorted(set(chromosomes),
|
| 222 |
key=lambda x: (int(x) if str(x).isdigit() else 999, str(x)))
|
| 223 |
|
| 224 |
+
# ββ convert positions to cM (per-chromosome marker-rank) βββββββββββββββββ
|
| 225 |
+
# We assign cM positions per chromosome independently so within-chrom
|
| 226 |
+
# distances are meaningful regardless of raw position values.
|
| 227 |
+
chrom_to_global_idx = {}
|
| 228 |
+
for gi, ch in enumerate(chromosomes):
|
| 229 |
+
chrom_to_global_idx.setdefault(str(ch), []).append(gi)
|
| 230 |
+
|
| 231 |
+
# Build a global cM array: within each chrom, markers get rank-based cM
|
| 232 |
+
# spacing = (chrom_total_cM_share) / (n_markers_in_chrom - 1)
|
| 233 |
+
# We assume mean genome = 1500 cM split proportionally by marker count
|
| 234 |
+
total_markers = len(chromosomes)
|
| 235 |
+
global_cM = np.zeros(total_markers, dtype=float)
|
| 236 |
+
GENOME_cM = 1500.0
|
| 237 |
+
|
| 238 |
+
for ch in unique_chroms:
|
| 239 |
+
idxs = chrom_to_global_idx[str(ch)]
|
| 240 |
+
n_ch = len(idxs)
|
| 241 |
+
share = GENOME_cM * n_ch / total_markers # cM allocated to this chrom
|
| 242 |
+
if n_ch > 1:
|
| 243 |
+
spacing = share / (n_ch - 1)
|
| 244 |
+
else:
|
| 245 |
+
spacing = share
|
| 246 |
+
for rank, gi in enumerate(idxs):
|
| 247 |
+
global_cM[gi] = rank * spacing
|
| 248 |
+
|
| 249 |
+
# ββ collect pairwise (dist_cM, rΒ², chrom) ββββββββββββββββββββββββββββββββ
|
| 250 |
+
all_dist, all_r2, all_dp, all_ch = [], [], [], []
|
| 251 |
chrom_stats = {}
|
| 252 |
|
| 253 |
for ch in unique_chroms:
|
| 254 |
+
idxs = chrom_to_global_idx[str(ch)]
|
| 255 |
if len(idxs) < 4:
|
| 256 |
continue
|
| 257 |
if len(idxs) > max_m:
|
| 258 |
idxs = sorted(np.random.choice(idxs, max_m, replace=False))
|
| 259 |
|
| 260 |
+
G = genotypes[:, idxs].copy().astype(float)
|
| 261 |
+
cM_pos = global_cM[idxs]
|
| 262 |
|
| 263 |
+
dist, r2, dp = _compute_ld_pairs(G, cM_pos, max_lag=50)
|
| 264 |
if len(dist) == 0:
|
| 265 |
continue
|
| 266 |
|
| 267 |
all_dist.extend(dist.tolist())
|
| 268 |
all_r2.extend(r2.tolist())
|
| 269 |
+
all_dp.extend(dp.tolist())
|
| 270 |
+
all_ch.extend([str(ch)] * len(dist))
|
| 271 |
|
| 272 |
+
chrom_stats[str(ch)] = {
|
| 273 |
+
'n_markers': len(idxs),
|
| 274 |
+
'n_pairs': len(dist),
|
| 275 |
'mean_r2': float(np.mean(r2)),
|
| 276 |
'mean_dprime': float(np.mean(dp)),
|
| 277 |
+
'max_r2': float(np.max(r2)),
|
| 278 |
}
|
| 279 |
|
|
|
|
| 280 |
if not all_dist:
|
| 281 |
fig, ax = plt.subplots(figsize=(10, 6), facecolor=BG)
|
| 282 |
+
ax.text(0.5, 0.5, 'No LD data', ha='center', va='center',
|
| 283 |
+
transform=ax.transAxes, fontsize=14, color=TEXT_C)
|
| 284 |
+
plt.savefig(save_path, dpi=120, bbox_inches='tight')
|
|
|
|
| 285 |
plt.close(fig)
|
| 286 |
+
return chrom_stats, "No LD data available."
|
| 287 |
+
|
| 288 |
+
dist_arr = np.array(all_dist, dtype=float)
|
| 289 |
+
r2_arr = np.array(all_r2, dtype=float)
|
| 290 |
+
ch_arr = np.array(all_ch, dtype=str)
|
| 291 |
+
|
| 292 |
+
# clip extreme tail
|
| 293 |
+
max_dist = float(np.percentile(dist_arr, 99))
|
| 294 |
+
if max_dist < 0.5:
|
| 295 |
+
max_dist = dist_arr.max()
|
| 296 |
+
|
| 297 |
+
mask = dist_arr <= max_dist
|
| 298 |
+
dv, rv = dist_arr[mask], r2_arr[mask]
|
| 299 |
+
|
| 300 |
+
# ββ binned medians for smooth curve ββββββββββββββββββββββββββββββββββββββ
|
| 301 |
+
N_BINS = 80
|
| 302 |
+
bins = np.linspace(0, max_dist, N_BINS + 1)
|
| 303 |
+
ctrs, meds = [], []
|
| 304 |
+
for i in range(N_BINS):
|
| 305 |
+
m = (dv >= bins[i]) & (dv < bins[i + 1])
|
| 306 |
+
if m.sum() >= 3:
|
| 307 |
+
ctrs.append((bins[i] + bins[i + 1]) / 2.0)
|
| 308 |
+
meds.append(np.median(rv[m]))
|
| 309 |
+
|
| 310 |
+
ctrs = np.array(ctrs, dtype=float)
|
| 311 |
+
meds = np.array(meds, dtype=float)
|
| 312 |
+
|
| 313 |
+
# ββ decay annotations βββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 314 |
+
# Find where smooth curve crosses rΒ²=0.5 (half of max), 0.2, 0.1
|
| 315 |
+
ann = {} # key β cM position
|
| 316 |
+
if len(ctrs) >= 5:
|
| 317 |
+
k = min(3, len(ctrs) - 1)
|
| 318 |
+
xs = np.linspace(ctrs[0], ctrs[-1], 2000)
|
| 319 |
+
spl = make_interp_spline(ctrs, meds, k=k)
|
| 320 |
+
ys = np.clip(spl(xs), 0, 1)
|
| 321 |
+
|
| 322 |
+
r2_start = ys[0]
|
| 323 |
+
for thr_name, thr_val in [('half', r2_start / 2.0),
|
| 324 |
+
('r2_02', 0.2),
|
| 325 |
+
('r2_01', 0.1)]:
|
| 326 |
+
idx_cross = np.where(ys <= thr_val)[0]
|
| 327 |
+
if len(idx_cross):
|
| 328 |
+
ann[thr_name] = float(xs[idx_cross[0]])
|
| 329 |
+
else:
|
| 330 |
+
xs, ys = ctrs, meds
|
| 331 |
+
|
| 332 |
+
# ββ LD interpretation string ββββββββββββββββββββββββββββββββββββββββββββββ
|
| 333 |
+
overall_mean_r2 = float(np.mean(r2_arr))
|
| 334 |
+
overall_mean_dp = float(np.mean(all_dp))
|
| 335 |
+
|
| 336 |
+
if 'half' in ann:
|
| 337 |
+
ld_level = ("rapid" if ann['half'] < 5 else
|
| 338 |
+
"moderate" if ann['half'] < 20 else "slow")
|
| 339 |
+
interp_lines = [
|
| 340 |
+
f"β’ **LD half-decay** (rΒ² drops to 50% of starting value): **{ann['half']:.1f} cM**",
|
| 341 |
+
f" β LD decays {ld_level}ly in this population.",
|
| 342 |
+
]
|
| 343 |
+
else:
|
| 344 |
+
interp_lines = ["β’ Half-decay point not reached within plotted range (LD persists strongly)."]
|
| 345 |
+
|
| 346 |
+
if 'r2_02' in ann:
|
| 347 |
+
interp_lines.append(
|
| 348 |
+
f"β’ **rΒ² < 0.2** (useful LD threshold for GWAS tag-SNP coverage): **{ann['r2_02']:.1f} cM**")
|
| 349 |
+
interp_lines.append(
|
| 350 |
+
f" β Markers within {ann['r2_02']:.1f} cM share enough LD to capture the same signal.")
|
| 351 |
+
else:
|
| 352 |
+
interp_lines.append("β’ rΒ² does not drop below 0.2 within plotted range β very high background LD.")
|
| 353 |
+
|
| 354 |
+
if 'r2_01' in ann:
|
| 355 |
+
interp_lines.append(
|
| 356 |
+
f"β’ **rΒ² < 0.1** (independent marker threshold): **{ann['r2_01']:.1f} cM**")
|
| 357 |
+
interp_lines += [
|
| 358 |
+
f"β’ Overall mean rΒ² = {overall_mean_r2:.3f} | mean D' = {overall_mean_dp:.3f}",
|
| 359 |
+
f"β’ Total marker pairs analysed: {len(dist_arr):,}",
|
| 360 |
+
]
|
| 361 |
+
ld_interpretation = "\n".join(interp_lines)
|
| 362 |
+
|
| 363 |
+
# ββ FIGURE ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 364 |
chrom_color = {str(ch): CHROM_PALETTE[i % len(CHROM_PALETTE)]
|
| 365 |
for i, ch in enumerate(unique_chroms)}
|
| 366 |
|
| 367 |
+
fig = plt.figure(figsize=(13, 8), facecolor=BG)
|
| 368 |
+
# Main scatter (top 75%) + interpretation text (bottom 25%)
|
| 369 |
+
gs = fig.add_gridspec(2, 1, height_ratios=[4, 1], hspace=0.05)
|
| 370 |
+
ax = fig.add_subplot(gs[0])
|
| 371 |
+
axt = fig.add_subplot(gs[1])
|
| 372 |
+
axt.axis('off')
|
| 373 |
+
|
| 374 |
+
ax.set_facecolor('#EEE8FA')
|
| 375 |
|
| 376 |
+
# ββ scatter per chromosome ββββββββββββββββββββββββββββββββββββββββββββββββ
|
|
|
|
| 377 |
for ch in unique_chroms:
|
| 378 |
key = str(ch)
|
| 379 |
+
cmsk = (ch_arr == key) & mask
|
| 380 |
+
if not cmsk.any():
|
| 381 |
continue
|
| 382 |
+
ax.scatter(dist_arr[cmsk], r2_arr[cmsk],
|
| 383 |
+
c=chrom_color[key], s=6, alpha=0.35,
|
| 384 |
+
linewidths=0, zorder=2, label=key)
|
| 385 |
+
|
| 386 |
+
# ββ median decay curve + fill βββββββββββββββββββββββββββββββββββββββββββββ
|
| 387 |
+
if len(ctrs) >= 5:
|
| 388 |
+
ax.fill_between(xs, 0, ys, color='#22C55E', alpha=0.22, zorder=3)
|
| 389 |
+
ax.plot(xs, ys, color=GREEN_C, linewidth=2.4, zorder=4,
|
| 390 |
+
label='Median rΒ² decay')
|
| 391 |
+
|
| 392 |
+
# ββ reference line rΒ²=0.2 ββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 393 |
+
ax.axhline(0.2, color='#111827', ls='--', lw=1.6, alpha=0.75,
|
| 394 |
+
zorder=5, label='rΒ² = 0.2')
|
| 395 |
+
|
| 396 |
+
# ββ annotation vertical lines βββββββββββββββββββββββββββββββββββββββββββββ
|
| 397 |
+
ann_styles = {
|
| 398 |
+
'half': (GOLD_C, 'Β½ decay', 0.50),
|
| 399 |
+
'r2_02': (RED_C, 'rΒ²=0.2', 0.20),
|
| 400 |
+
'r2_01': (TEAL_C, 'rΒ²=0.1', 0.10),
|
| 401 |
+
}
|
| 402 |
+
for key, (col, label, r2_ref) in ann_styles.items():
|
| 403 |
+
if key in ann:
|
| 404 |
+
xv = ann[key]
|
| 405 |
+
ax.axvline(xv, color=col, ls=':', lw=1.8, alpha=0.85, zorder=6)
|
| 406 |
+
ax.annotate(
|
| 407 |
+
f'{label}\n{xv:.1f} cM',
|
| 408 |
+
xy=(xv, r2_ref),
|
| 409 |
+
xytext=(xv + max_dist * 0.01, r2_ref + 0.06),
|
| 410 |
+
fontsize=8.5, fontweight='bold', color=col,
|
| 411 |
+
arrowprops=dict(arrowstyle='->', color=col, lw=1.2),
|
| 412 |
+
bbox=dict(boxstyle='round,pad=0.3', fc=BG, ec=col,
|
| 413 |
+
alpha=0.9, lw=1.0),
|
| 414 |
+
zorder=7,
|
| 415 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 416 |
|
| 417 |
+
# ββ axes ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 418 |
+
ax.set_xlim(0, max_dist)
|
| 419 |
+
ax.set_ylim(0, 1.05)
|
| 420 |
ax.set_xlabel('Genetic distance (cM)', fontsize=12, fontweight='bold',
|
| 421 |
+
color=TEXT_C, labelpad=6)
|
| 422 |
ax.set_ylabel('LD estimate (RΒ²)', fontsize=12, fontweight='bold',
|
| 423 |
+
color=TEXT_C, labelpad=6)
|
| 424 |
ax.set_title('LD Decay by Chromosome', fontsize=14, fontweight='bold',
|
| 425 |
+
color=TEXT_C, pad=10)
|
| 426 |
+
ax.xaxis.grid(True, color=GRID_C, lw=0.6, alpha=0.9)
|
| 427 |
+
ax.yaxis.grid(True, color=GRID_C, lw=0.6, alpha=0.9)
|
|
|
|
| 428 |
ax.set_axisbelow(True)
|
| 429 |
|
| 430 |
+
# ββ legend ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 431 |
handles, labels = ax.get_legend_handles_labels()
|
| 432 |
+
special = [(h, l) for h, l in zip(handles, labels)
|
| 433 |
+
if l in ('Median rΒ² decay', 'rΒ² = 0.2')]
|
| 434 |
+
chrs = [(h, l) for h, l in zip(handles, labels)
|
| 435 |
+
if l not in ('Median rΒ² decay', 'rΒ² = 0.2')]
|
| 436 |
+
leg_h = [h for h, _ in special] + [h for h, _ in chrs]
|
| 437 |
+
leg_l = [l for _, l in special] + [f'Chr {l}' for _, l in chrs]
|
| 438 |
+
|
| 439 |
+
ncols = max(1, (len(chrs) + 9) // 10)
|
| 440 |
+
legend = ax.legend(leg_h, leg_l, title='Chr', title_fontsize=9,
|
| 441 |
+
fontsize=7.5, loc='upper right', ncol=ncols,
|
| 442 |
+
framealpha=0.93, edgecolor=GRID_C,
|
| 443 |
+
markerscale=2.2, handlelength=1.4,
|
| 444 |
+
borderpad=0.7, labelspacing=0.4)
|
| 445 |
+
legend.get_title().set_fontweight('bold')
|
| 446 |
|
| 447 |
+
# ββ interpretation text panel βββββββββββββββββββββββββββββββββββββββββββββ
|
| 448 |
+
interp_display = (
|
| 449 |
+
"LD DECAY INTERPRETATION\n"
|
| 450 |
+
+ "β" * 72 + "\n"
|
| 451 |
+
+ ld_interpretation.replace('**', '') # strip markdown bold for plain text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 452 |
)
|
| 453 |
+
axt.text(0.01, 0.98, interp_display,
|
| 454 |
+
transform=axt.transAxes,
|
| 455 |
+
va='top', ha='left',
|
| 456 |
+
fontsize=8.5, color=TEXT_C,
|
| 457 |
+
fontfamily='monospace',
|
| 458 |
+
bbox=dict(boxstyle='round,pad=0.5',
|
| 459 |
+
facecolor='#EDE9FE', edgecolor=GRID_C,
|
| 460 |
+
alpha=0.95))
|
| 461 |
|
|
|
|
| 462 |
plt.savefig(save_path, dpi=130, bbox_inches='tight', facecolor=BG)
|
| 463 |
plt.close(fig)
|
| 464 |
|
| 465 |
+
return chrom_stats, ld_interpretation
|
| 466 |
|
| 467 |
|
| 468 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 469 |
+
# PLOT: MANHATTAN + LOD
|
| 470 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 471 |
|
| 472 |
+
def plot_manhattan_lod(marker_names, chromosomes, p_values, lod_scores,
|
| 473 |
+
sig_set, bonf_thresh, save_path):
|
| 474 |
+
_style()
|
| 475 |
+
unique_chroms = sorted(set(chromosomes),
|
| 476 |
+
key=lambda x: (int(x) if str(x).isdigit() else 999, str(x)))
|
| 477 |
+
log_p = -np.log10(np.array(p_values) + 1e-300)
|
| 478 |
+
lod_array = np.array(lod_scores)
|
| 479 |
|
| 480 |
+
GAP = max(8, len(marker_names) // 150)
|
| 481 |
+
x_pos = np.zeros(len(marker_names))
|
| 482 |
+
chrom_to_idx = {}
|
| 483 |
+
for i, c in enumerate(chromosomes):
|
| 484 |
+
chrom_to_idx.setdefault(c, []).append(i)
|
| 485 |
+
|
| 486 |
+
chrom_xticks, offset = [], 0
|
| 487 |
+
for ch in unique_chroms:
|
| 488 |
+
idxs = chrom_to_idx.get(ch, [])
|
| 489 |
+
if not idxs: continue
|
| 490 |
+
for r, idx in enumerate(idxs):
|
| 491 |
+
x_pos[idx] = offset + r
|
| 492 |
+
chrom_xticks.append((offset + len(idxs) / 2, str(ch)))
|
| 493 |
+
offset += len(idxs) + GAP
|
| 494 |
+
|
| 495 |
+
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(18, 9),
|
| 496 |
+
gridspec_kw={'height_ratios': [2.2, 1]},
|
| 497 |
+
facecolor=BG)
|
| 498 |
+
|
| 499 |
+
for ci, ch in enumerate(unique_chroms):
|
| 500 |
+
idxs = chrom_to_idx.get(ch, [])
|
| 501 |
+
if not idxs: continue
|
| 502 |
+
if ci % 2 == 0:
|
| 503 |
+
for axx in [ax1, ax2]:
|
| 504 |
+
axx.axvspan(x_pos[idxs[0]] - 0.5, x_pos[idxs[-1]] + 0.5,
|
| 505 |
+
color='#EDE9FE', alpha=0.40, zorder=0)
|
| 506 |
+
col = CHROM_PALETTE[ci % len(CHROM_PALETTE)]
|
| 507 |
+
normal = [i for i in idxs if i not in sig_set]
|
| 508 |
+
sel = [i for i in idxs if i in sig_set]
|
| 509 |
+
if normal:
|
| 510 |
+
ax1.scatter(x_pos[normal], log_p[normal],
|
| 511 |
+
c=col, s=9, alpha=0.60, linewidths=0, zorder=2)
|
| 512 |
+
if sel:
|
| 513 |
+
ax1.scatter(x_pos[sel], log_p[sel],
|
| 514 |
+
c=RED_C, s=220, alpha=0.15, linewidths=0, zorder=3)
|
| 515 |
+
ax1.scatter(x_pos[sel], log_p[sel],
|
| 516 |
+
c=RED_C, s=60, alpha=1.0,
|
| 517 |
+
edgecolors='white', linewidths=0.9,
|
| 518 |
+
marker='D', zorder=4, label='Significant')
|
| 519 |
+
|
| 520 |
+
ax1.axhline(bonf_thresh, color=RED_C, ls='--', lw=1.8, alpha=0.85,
|
| 521 |
+
label=f'Bonferroni ({bonf_thresh:.1f})', zorder=5)
|
| 522 |
+
ax1.axhline(3.0, color=GOLD_C, ls=':', lw=1.5, alpha=0.8,
|
| 523 |
+
label='Suggestive (LOD=3)', zorder=5)
|
| 524 |
+
|
| 525 |
+
ax1_t = ax1.twinx()
|
| 526 |
+
ax1_t.scatter(x_pos, lod_array, c=TEAL_C, s=5, alpha=0.30,
|
| 527 |
+
marker='x', zorder=1)
|
| 528 |
+
ax1_t.set_ylabel('LOD Score', fontsize=10, color=TEAL_C, fontweight='bold')
|
| 529 |
+
ax1_t.tick_params(axis='y', colors=TEAL_C)
|
| 530 |
+
ax1_t.set_ylim(0, max(lod_array.max() * 1.15, 1))
|
| 531 |
+
|
| 532 |
+
ax1.set_xlim(-GAP, offset)
|
| 533 |
+
ax1.set_ylim(bottom=0, top=max(log_p.max() * 1.15, 1))
|
| 534 |
+
ax1.set_ylabel('βlogββ(P)', fontsize=12, fontweight='bold', labelpad=8)
|
| 535 |
+
ax1.set_title('GWAS Manhattan Plot with LOD Scores', fontsize=14,
|
| 536 |
+
fontweight='bold', pad=12)
|
| 537 |
+
ax1.set_xticks([x for x, _ in chrom_xticks])
|
| 538 |
+
ax1.set_xticklabels([l for _, l in chrom_xticks], fontsize=7)
|
| 539 |
+
ax1.yaxis.grid(True, color=GRID_C, lw=0.7)
|
| 540 |
+
ax1.legend(loc='upper right', fontsize=9, framealpha=0.9)
|
| 541 |
+
|
| 542 |
+
ax2.plot(x_pos, lod_array, color=TEAL_C, lw=1.2, alpha=0.8)
|
| 543 |
+
ax2.fill_between(x_pos, 0, lod_array, color=TEAL_C, alpha=0.18)
|
| 544 |
+
ax2.axhline(3, color=GOLD_C, ls='--', lw=1.2, alpha=0.8)
|
| 545 |
+
ax2.set_xlim(-GAP, offset)
|
| 546 |
+
ax2.set_ylabel('LOD', fontsize=10, fontweight='bold')
|
| 547 |
+
ax2.set_xlabel('Chromosome', fontsize=11, fontweight='bold')
|
| 548 |
+
ax2.set_xticks([x for x, _ in chrom_xticks])
|
| 549 |
+
ax2.set_xticklabels([l for _, l in chrom_xticks], fontsize=7)
|
| 550 |
+
ax2.yaxis.grid(True, color=GRID_C, lw=0.7)
|
| 551 |
+
|
| 552 |
+
plt.tight_layout(pad=1.5)
|
| 553 |
+
plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=BG)
|
| 554 |
+
plt.close(fig)
|
| 555 |
+
|
| 556 |
+
|
| 557 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 558 |
+
# PLOT: QQ PLOT
|
| 559 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 560 |
+
|
| 561 |
+
def plot_qq(p_values, save_path):
|
| 562 |
+
_style()
|
| 563 |
+
pv = np.array(p_values, dtype=float)
|
| 564 |
+
pv = pv[np.isfinite(pv) & (pv > 0)]
|
| 565 |
+
n = len(pv)
|
| 566 |
+
obs = -np.log10(np.sort(pv))
|
| 567 |
+
exp = -np.log10(np.arange(1, n + 1) / (n + 1))
|
| 568 |
+
|
| 569 |
+
# Genomic inflation Ξ»
|
| 570 |
+
chi2_obs = stats.chi2.ppf(1 - pv, df=1)
|
| 571 |
+
lam = np.median(chi2_obs) / stats.chi2.ppf(0.5, df=1)
|
| 572 |
+
|
| 573 |
+
fig, ax = plt.subplots(figsize=(7, 7), facecolor=BG)
|
| 574 |
ax.set_facecolor(PANEL)
|
| 575 |
|
| 576 |
+
ax.scatter(exp, obs, c=ACCENT, s=12, alpha=0.65,
|
| 577 |
+
linewidths=0, zorder=2, label='Observed')
|
| 578 |
+
maxv = max(obs.max(), exp.max()) * 1.05
|
| 579 |
+
ax.plot([0, maxv], [0, maxv], color=RED_C, lw=1.5,
|
| 580 |
+
ls='--', zorder=3, label='Expected (null)')
|
| 581 |
+
|
| 582 |
+
ax.set_xlim(0, maxv); ax.set_ylim(0, maxv)
|
| 583 |
+
ax.set_xlabel('Expected βlogββ(P)', fontsize=12, fontweight='bold')
|
| 584 |
+
ax.set_ylabel('Observed βlogββ(P)', fontsize=12, fontweight='bold')
|
| 585 |
+
ax.set_title('QQ Plot', fontsize=14, fontweight='bold', pad=10)
|
| 586 |
+
ax.text(0.05, 0.93,
|
| 587 |
+
f'Ξ» (genomic inflation) = {lam:.3f}',
|
| 588 |
+
transform=ax.transAxes, fontsize=11, fontweight='bold',
|
| 589 |
+
color=ACCENT,
|
| 590 |
+
bbox=dict(boxstyle='round', facecolor=BG, edgecolor=ACCENT,
|
| 591 |
+
alpha=0.9))
|
| 592 |
+
ax.legend(fontsize=9)
|
| 593 |
+
ax.grid(True, color=GRID_C, lw=0.7)
|
| 594 |
+
|
| 595 |
+
plt.tight_layout()
|
| 596 |
+
plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=BG)
|
| 597 |
+
plt.close(fig)
|
| 598 |
+
return float(lam)
|
| 599 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 600 |
|
| 601 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 602 |
+
# PLOT: PHENOTYPE DISTRIBUTION
|
| 603 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 604 |
+
|
| 605 |
+
def plot_phenotype_dist(phenotypes, save_path):
|
| 606 |
+
_style()
|
| 607 |
+
pv = phenotypes[~np.isnan(phenotypes)]
|
| 608 |
+
fig, axes = plt.subplots(1, 2, figsize=(11, 4.5), facecolor=BG)
|
| 609 |
+
|
| 610 |
+
ax = axes[0]
|
| 611 |
+
ax.set_facecolor(PANEL)
|
| 612 |
+
ax.hist(pv, bins=30, color=ACCENT, alpha=0.75, edgecolor='white',
|
| 613 |
+
linewidth=0.6)
|
| 614 |
+
ax.axvline(np.mean(pv), color=RED_C, ls='--', lw=1.6,
|
| 615 |
+
label=f'Mean={np.mean(pv):.2f}')
|
| 616 |
+
ax.axvline(np.median(pv), color=GOLD_C, ls=':', lw=1.6,
|
| 617 |
+
label=f'Median={np.median(pv):.2f}')
|
| 618 |
+
ax.set_xlabel('Phenotype Value', fontsize=11, fontweight='bold')
|
| 619 |
+
ax.set_ylabel('Frequency', fontsize=11, fontweight='bold')
|
| 620 |
+
ax.set_title('Phenotype Distribution', fontsize=12, fontweight='bold')
|
| 621 |
+
ax.legend(fontsize=9)
|
| 622 |
+
ax.grid(True, color=GRID_C, lw=0.7)
|
| 623 |
|
|
|
|
| 624 |
ax = axes[1]
|
| 625 |
ax.set_facecolor(PANEL)
|
| 626 |
+
stats.probplot(pv, dist='norm', plot=ax)
|
| 627 |
+
ax.get_lines()[0].set(color=ACCENT, markersize=3, alpha=0.6)
|
| 628 |
+
ax.get_lines()[1].set(color=RED_C, lw=1.5)
|
| 629 |
+
ax.set_title('Normal Q-Q Plot (Phenotype)', fontsize=12, fontweight='bold')
|
| 630 |
+
ax.grid(True, color=GRID_C, lw=0.7)
|
| 631 |
+
|
| 632 |
+
sw_stat, sw_p = stats.shapiro(pv[:5000])
|
| 633 |
+
axes[0].text(0.97, 0.95,
|
| 634 |
+
f'Shapiro-Wilk p={sw_p:.3e}',
|
| 635 |
+
transform=axes[0].transAxes,
|
| 636 |
+
ha='right', va='top', fontsize=8.5, color=TEXT_C,
|
| 637 |
+
bbox=dict(boxstyle='round', facecolor=BG,
|
| 638 |
+
edgecolor=GRID_C, alpha=0.9))
|
| 639 |
+
plt.tight_layout(pad=1.5)
|
| 640 |
+
plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=BG)
|
| 641 |
+
plt.close(fig)
|
| 642 |
+
|
| 643 |
+
|
| 644 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 645 |
+
# PLOT: MODEL COMPARISON
|
| 646 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 647 |
|
| 648 |
+
def plot_model_comparison(results_df, save_path):
|
| 649 |
+
_style()
|
| 650 |
+
fig, axes = plt.subplots(1, 3, figsize=(16, 5), facecolor=BG)
|
| 651 |
+
|
| 652 |
+
# 1. P-value correlation
|
| 653 |
+
ax = axes[0]; ax.set_facecolor(PANEL)
|
| 654 |
+
if 'LR_P' in results_df and 'EN_P' in results_df:
|
| 655 |
+
corr = results_df['LR_P'].corr(results_df['EN_P'])
|
| 656 |
+
ax.scatter(results_df['LR_P'], results_df['EN_P'],
|
| 657 |
+
alpha=0.45, s=15, color=ACCENT,
|
| 658 |
+
edgecolors='white', linewidth=0.4)
|
| 659 |
+
ax.text(0.05, 0.95, f'r = {corr:.3f}', transform=ax.transAxes,
|
| 660 |
+
fontsize=11, fontweight='bold', va='top',
|
| 661 |
+
bbox=dict(boxstyle='round', facecolor=BG, alpha=0.85))
|
| 662 |
+
ax.set_xlabel('LR P-value', fontsize=10, fontweight='bold')
|
| 663 |
+
ax.set_ylabel('ElasticNet P-value', fontsize=10, fontweight='bold')
|
| 664 |
+
ax.set_title('P-value Correlation', fontsize=11, fontweight='bold')
|
| 665 |
+
ax.set_xscale('log'); ax.set_yscale('log')
|
| 666 |
+
ax.grid(True, color=GRID_C, lw=0.7, alpha=0.5)
|
| 667 |
|
| 668 |
+
# 2. Effect size distribution
|
| 669 |
+
ax = axes[1]; ax.set_facecolor(PANEL)
|
| 670 |
+
if 'LR_Beta' in results_df:
|
| 671 |
+
ax.hist(results_df['LR_Beta'].dropna(), bins=45, alpha=0.60,
|
| 672 |
+
label='LR Ξ²', color=ACCENT, edgecolor='white')
|
| 673 |
+
if 'EN_Beta' in results_df:
|
| 674 |
+
ax.hist(results_df['EN_Beta'].dropna(), bins=45, alpha=0.55,
|
| 675 |
+
label='EN Ξ²', color=TEAL_C, edgecolor='white')
|
| 676 |
+
ax.set_xlabel('Effect Size (Ξ²)', fontsize=10, fontweight='bold')
|
| 677 |
+
ax.set_ylabel('Count', fontsize=10, fontweight='bold')
|
| 678 |
ax.set_title('Effect Size Distribution', fontsize=11, fontweight='bold')
|
| 679 |
ax.legend(fontsize=9)
|
| 680 |
ax.grid(True, color=GRID_C, lw=0.7)
|
| 681 |
|
| 682 |
+
# 3. -log10(P) scatter
|
| 683 |
+
ax = axes[2]; ax.set_facecolor(PANEL)
|
| 684 |
+
if 'LR_P' in results_df and 'EN_P' in results_df:
|
| 685 |
+
lp_lr = -np.log10(results_df['LR_P'].clip(1e-300))
|
| 686 |
+
lp_en = -np.log10(results_df['EN_P'].clip(1e-300))
|
| 687 |
+
ax.scatter(lp_lr, lp_en, alpha=0.40, s=12, color=PINK_C,
|
| 688 |
+
edgecolors='white', linewidth=0.3)
|
| 689 |
+
maxv = max(lp_lr.max(), lp_en.max()) * 1.05
|
| 690 |
+
ax.plot([0, maxv], [0, maxv], color=GOLD_C, ls='--', lw=1.2)
|
| 691 |
+
ax.set_xlabel('LR βlogββ(P)', fontsize=10, fontweight='bold')
|
| 692 |
+
ax.set_ylabel('EN βlogββ(P)', fontsize=10, fontweight='bold')
|
| 693 |
+
ax.set_title('Signal Concordance', fontsize=11, fontweight='bold')
|
| 694 |
+
ax.grid(True, color=GRID_C, lw=0.7, alpha=0.5)
|
| 695 |
+
|
| 696 |
plt.tight_layout(pad=1.5)
|
| 697 |
plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=BG)
|
| 698 |
plt.close(fig)
|
| 699 |
|
| 700 |
|
| 701 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 702 |
+
# GWAS MODELS
|
| 703 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 704 |
|
| 705 |
def linear_regression_gwas(genotypes, phenotypes):
|
| 706 |
+
n = genotypes.shape[1]
|
| 707 |
+
pv = np.ones(n); ef = np.zeros(n)
|
| 708 |
+
se = np.zeros(n); r2 = np.zeros(n)
|
| 709 |
+
y = phenotypes.astype(float)
|
| 710 |
+
for i in range(n):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 711 |
x = genotypes[:, i].astype(float)
|
| 712 |
+
if x.std() < 1e-9: continue
|
| 713 |
+
sl, _, r, p, s = stats.linregress(x, y)
|
| 714 |
+
pv[i] = p if np.isfinite(p) else 1.0
|
| 715 |
+
ef[i] = sl; se[i] = s; r2[i] = r**2
|
| 716 |
+
return pv, ef, se, r2
|
| 717 |
+
|
| 718 |
+
|
| 719 |
+
def elasticnet_gwas(genotypes, phenotypes, n_boot=15):
|
| 720 |
+
sc = StandardScaler()
|
| 721 |
+
Xs = sc.fit_transform(genotypes)
|
| 722 |
+
en = ElasticNetCV(cv=3, random_state=42, max_iter=2000, n_jobs=-1)
|
| 723 |
+
en.fit(Xs, phenotypes)
|
| 724 |
+
coef = en.coef_
|
| 725 |
+
|
| 726 |
+
boots = []
|
|
|
|
|
|
|
|
|
|
|
|
|
| 727 |
rng = np.random.default_rng(42)
|
| 728 |
+
for _ in range(n_boot):
|
| 729 |
idx = rng.integers(0, len(phenotypes), len(phenotypes))
|
| 730 |
eb = ElasticNetCV(cv=3, random_state=42, max_iter=1500)
|
| 731 |
+
eb.fit(Xs[idx], phenotypes[idx])
|
| 732 |
+
boots.append(eb.coef_)
|
| 733 |
|
| 734 |
+
boot_arr = np.array(boots)
|
| 735 |
+
pv = np.ones(len(coef))
|
| 736 |
for i in range(len(coef)):
|
| 737 |
sd = boot_arr[:, i].std()
|
| 738 |
if sd > 0:
|
| 739 |
+
z = abs(coef[i]) / (sd + 1e-10)
|
| 740 |
+
pv[i] = 2 * (1 - stats.norm.cdf(z))
|
| 741 |
+
return pv, coef
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 742 |
|
| 743 |
|
| 744 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
|
|
|
| 746 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 747 |
|
| 748 |
def run_mta_analysis(input_file, miss_rate_sample, miss_rate_marker, maf_thresh):
|
|
|
|
|
|
|
| 749 |
try:
|
| 750 |
if input_file is None:
|
| 751 |
+
return ("β οΈ Please upload a CSV file.",
|
| 752 |
+
None, None, None, None, None, None)
|
| 753 |
|
| 754 |
+
tmp = tempfile.mkdtemp()
|
| 755 |
+
rdir = os.path.join(tmp, 'results')
|
| 756 |
+
pdir = os.path.join(rdir, 'plots')
|
| 757 |
+
for d in [rdir, pdir]: os.makedirs(d, exist_ok=True)
|
|
|
|
| 758 |
|
| 759 |
+
ms_t = miss_rate_sample / 100.0
|
| 760 |
+
mm_t = miss_rate_marker / 100.0
|
| 761 |
+
mf_t = maf_thresh / 100.0
|
| 762 |
|
| 763 |
print("[Parse] Reading CSVβ¦")
|
| 764 |
+
(sids, pheno, geno,
|
| 765 |
+
mnames, chrom_dict, positions) = parse_input_csv(input_file)
|
| 766 |
+
|
| 767 |
+
n_s, n_m = len(sids), len(mnames)
|
| 768 |
+
print(f"[Parse] {n_s} samples Γ {n_m} markers")
|
| 769 |
+
|
| 770 |
+
# ββ QC βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 771 |
+
miss_m = np.isnan(geno).sum(0) / max(n_s, 1)
|
| 772 |
+
miss_s = np.isnan(geno).sum(1) / max(n_m, 1)
|
| 773 |
+
|
| 774 |
+
maf = np.zeros(n_m)
|
| 775 |
+
for i in range(n_m):
|
| 776 |
+
v = geno[:, i]; v = v[~np.isnan(v)]
|
|
|
|
|
|
|
|
|
|
| 777 |
if len(v):
|
| 778 |
+
f = np.mean(v) / 2.0
|
| 779 |
maf[i] = min(f, 1 - f)
|
| 780 |
|
| 781 |
+
qc_m = (miss_m < mm_t) & (maf >= mf_t)
|
| 782 |
+
qc_s = miss_s < ms_t
|
| 783 |
+
fallback = ""
|
| 784 |
+
|
| 785 |
+
for rs, rm in [(ms_t, mm_t),
|
| 786 |
+
(.6,.6),(.7,.7),(.8,.8),(.9,.9),(1.,1.)]:
|
| 787 |
+
qm = (miss_m < rm) & (maf >= mf_t)
|
| 788 |
+
qs = miss_s < rs
|
| 789 |
+
if qs.sum() >= 10:
|
| 790 |
+
qc_m, qc_s = qm, qs
|
| 791 |
+
if rs > ms_t or rm > mm_t:
|
| 792 |
+
fallback = (f"\nβ οΈ **QC relaxed** β sample<{rs*100:.0f}% "
|
| 793 |
+
f"/ marker<{rm*100:.0f}%\n")
|
|
|
|
|
|
|
| 794 |
break
|
| 795 |
|
| 796 |
+
geno_q = geno[np.ix_(qc_s, qc_m)].copy()
|
| 797 |
+
pheno_q = pheno[qc_s]
|
| 798 |
+
sids_q = sids[qc_s]
|
| 799 |
+
mn_q = [mnames[i] for i in range(n_m) if qc_m[i]]
|
| 800 |
+
ch_q = [chrom_dict[m] for m in mn_q]
|
| 801 |
+
pos_q = [positions[i] for i in range(n_m) if qc_m[i]]
|
| 802 |
+
n_q = len(mn_q)
|
| 803 |
|
| 804 |
+
print(f"[QC] {len(sids_q)} samples Γ {n_q} markers")
|
| 805 |
|
| 806 |
# Impute
|
| 807 |
+
col_mu = np.nanmean(geno_q, 0)
|
| 808 |
+
col_mu = np.where(np.isnan(col_mu), 0, col_mu)
|
| 809 |
+
for i in range(geno_q.shape[1]):
|
| 810 |
+
mk = np.isnan(geno_q[:, i])
|
| 811 |
+
if mk.any(): geno_q[mk, i] = col_mu[i]
|
| 812 |
+
|
| 813 |
+
valid = ~np.isnan(pheno_q)
|
| 814 |
+
geno_q = geno_q[valid]; pheno_q = pheno_q[valid]
|
| 815 |
+
sids_q = sids_q[valid]
|
| 816 |
+
|
| 817 |
+
if len(sids_q) < 10:
|
| 818 |
+
return (f"## β οΈ Only {len(sids_q)} samples passed QC. "
|
| 819 |
+
"Increase missing-rate sliders.",
|
| 820 |
+
None, None, None, None, None, None)
|
| 821 |
+
|
| 822 |
+
bonf = 0.05 / n_q
|
| 823 |
+
bonf_log = -np.log10(bonf)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 824 |
|
| 825 |
+
# ββ Models βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 826 |
print("[1/2] Linear Regressionβ¦")
|
| 827 |
+
lr_p, lr_b, lr_se, lr_r2 = linear_regression_gwas(geno_q, pheno_q)
|
| 828 |
|
| 829 |
print("[2/2] ElasticNetβ¦")
|
| 830 |
+
en_p, en_b = elasticnet_gwas(geno_q, pheno_q)
|
| 831 |
+
|
| 832 |
+
# ββ Results table ββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 833 |
+
df = pd.DataFrame({
|
| 834 |
+
'Marker': mn_q,
|
| 835 |
+
'Chromosome': ch_q,
|
| 836 |
+
'LR_P': lr_p,
|
| 837 |
+
'LR_Beta': lr_b,
|
| 838 |
+
'LR_SE': lr_se,
|
| 839 |
+
'LR_R2': lr_r2,
|
| 840 |
+
'LR_LOD': -np.log10(lr_p + 1e-300),
|
| 841 |
+
'Significant_LR': (lr_p < bonf).astype(int),
|
| 842 |
+
'EN_P': en_p,
|
| 843 |
+
'EN_Beta': en_b,
|
| 844 |
+
'Significant_EN': (en_p < bonf).astype(int),
|
| 845 |
})
|
| 846 |
+
df['Consensus_Sig'] = ((df[['Significant_LR','Significant_EN']]
|
| 847 |
+
.sum(1) >= 2).astype(int))
|
| 848 |
+
df = df.sort_values('LR_P').reset_index(drop=True)
|
| 849 |
+
df.insert(0, 'Rank', range(1, len(df)+1))
|
| 850 |
|
| 851 |
+
df.to_csv(os.path.join(rdir, 'gwas_results.csv'), index=False)
|
|
|
|
|
|
|
| 852 |
|
| 853 |
+
# Significant only
|
| 854 |
+
sig_df = df[df['Significant_LR'] == 1].copy()
|
| 855 |
+
sig_df.to_csv(os.path.join(rdir, 'top_significant.csv'), index=False)
|
|
|
|
|
|
|
| 856 |
|
| 857 |
# ββ Plots βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 858 |
+
print("[Plot 1/5] Phenotype distributionβ¦")
|
| 859 |
+
ph_path = os.path.join(pdir, 'phenotype_dist.png')
|
| 860 |
+
plot_phenotype_dist(pheno_q, ph_path)
|
| 861 |
+
|
| 862 |
+
print("[Plot 2/5] Manhattan + LODβ¦")
|
| 863 |
+
man_path = os.path.join(pdir, 'manhattan_lod.png')
|
| 864 |
+
sig_set = set(np.where(lr_p < bonf)[0])
|
| 865 |
+
plot_manhattan_lod(mn_q, ch_q, lr_p,
|
| 866 |
+
-np.log10(lr_p + 1e-300),
|
| 867 |
+
sig_set, bonf_log, man_path)
|
| 868 |
+
|
| 869 |
+
print("[Plot 3/5] QQ plotβ¦")
|
| 870 |
+
qq_path = os.path.join(pdir, 'qq_plot.png')
|
| 871 |
+
lam = plot_qq(lr_p, qq_path)
|
| 872 |
+
|
| 873 |
+
print("[Plot 4/5] LD decayβ¦")
|
| 874 |
+
ld_path = os.path.join(pdir, 'ld_decay.png')
|
| 875 |
+
ld_stats, ld_interp = plot_ld_decay(geno_q, ch_q, pos_q, ld_path)
|
| 876 |
+
|
| 877 |
+
# Save LD stats CSV
|
| 878 |
+
ld_df = pd.DataFrame([
|
| 879 |
+
{'Chromosome': k, **v} for k, v in ld_stats.items()
|
| 880 |
+
])
|
| 881 |
+
ld_df.to_csv(os.path.join(rdir, 'ld_decay_stats.csv'), index=False)
|
| 882 |
+
|
| 883 |
+
print("[Plot 5/5] Model comparisonβ¦")
|
| 884 |
+
cmp_path = os.path.join(pdir, 'model_comparison.png')
|
| 885 |
+
plot_model_comparison(df, cmp_path)
|
| 886 |
|
| 887 |
# ββ ZIP βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 888 |
+
zip_path = os.path.join(tmp, 'GWAS_Results.zip')
|
|
|
|
| 889 |
with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf:
|
| 890 |
+
for root, _, files in os.walk(rdir):
|
| 891 |
for f in files:
|
| 892 |
+
fp = os.path.join(root, f)
|
| 893 |
+
zf.write(fp, os.path.relpath(fp, tmp))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 894 |
|
| 895 |
+
# ββ Summary markdown ββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 896 |
+
def _md_table(d):
|
| 897 |
+
cols = d.columns.tolist()
|
| 898 |
+
def _f(v):
|
| 899 |
if isinstance(v, float):
|
| 900 |
+
return f"{v:.4e}" if (v!=0 and abs(v)<0.001) else f"{v:.4f}"
|
| 901 |
return str(v)
|
| 902 |
+
sep = "| " + " | ".join(["---"]*len(cols)) + " |"
|
| 903 |
+
rows = ["| "+" | ".join(_f(row[c]) for c in cols)+" |"
|
| 904 |
+
for _, row in d.iterrows()]
|
| 905 |
+
return "\n".join(["| "+" | ".join(cols)+" |", sep]+rows)
|
| 906 |
+
|
| 907 |
+
top_cols = [c for c in
|
| 908 |
+
['Rank','Marker','Chromosome','LR_P','LR_Beta',
|
| 909 |
+
'LR_R2','LR_LOD','EN_P','Consensus_Sig']
|
| 910 |
+
if c in df.columns]
|
| 911 |
|
| 912 |
summary = f"""
|
| 913 |
+
## β
GWAS Analysis Complete β v7.5
|
| 914 |
|
| 915 |
### π QC Summary
|
| 916 |
| Metric | Value |
|
| 917 |
|--------|-------|
|
| 918 |
+
| Samples (raw β QC) | {n_s} β **{len(sids_q)}** |
|
| 919 |
+
| Markers (raw β QC) | {n_m} β **{n_q}** |
|
| 920 |
+
| Chromosomes | **{len(set(ch_q))}** |
|
| 921 |
+
| MAF threshold | β₯ {maf_thresh:.1f}% |
|
| 922 |
+
| Sample missing rate | < {miss_rate_sample:.0f}% |
|
| 923 |
+
| Marker missing rate | < {miss_rate_marker:.0f}% |
|
| 924 |
+
{fallback}
|
| 925 |
+
|
| 926 |
+
### π¬ Association Results
|
| 927 |
+
| Model | Significant Markers (Bonferroni) |
|
| 928 |
+
|-------|----------------------------------|
|
| 929 |
+
| Linear Regression | **{int((lr_p < bonf).sum())}** |
|
| 930 |
+
| ElasticNet | **{int((en_p < bonf).sum())}** |
|
| 931 |
+
| Consensus (both) | **{int(df['Consensus_Sig'].sum())}** |
|
| 932 |
+
|
| 933 |
+
**Bonferroni threshold:** P < {bonf:.3e} (βlogββP > {bonf_log:.2f})
|
| 934 |
+
|
| 935 |
+
### π QQ / Inflation
|
| 936 |
+
**Genomic inflation Ξ» = {lam:.3f}**
|
| 937 |
+
{"β οΈ Ξ» > 1.05 β possible population stratification or many true signals." if lam > 1.05 else "β
Ξ» β 1.0 β no substantial inflation."}
|
| 938 |
+
|
| 939 |
+
### 𧬠LD Decay Interpretation
|
| 940 |
+
{ld_interp}
|
| 941 |
+
|
| 942 |
+
### π Top 15 Markers (by LR P-value)
|
| 943 |
+
{_md_table(df.head(15)[top_cols])}
|
| 944 |
|
| 945 |
---
|
| 946 |
+
**Output files:**
|
| 947 |
+
- `gwas_results.csv` β all markers, all statistics
|
| 948 |
+
- `top_significant.csv` β Bonferroni-significant markers
|
| 949 |
+
- `ld_decay_stats.csv` β per-chromosome LD statistics
|
| 950 |
+
- `plots/manhattan_lod.png` β Manhattan + LOD
|
| 951 |
+
- `plots/ld_decay.png` β LD decay scatter with decay annotations
|
| 952 |
+
- `plots/qq_plot.png` β QQ plot (genomic inflation)
|
| 953 |
+
- `plots/model_comparison.png` β LR vs ElasticNet comparison
|
| 954 |
+
- `plots/phenotype_dist.png` β Phenotype distribution & normality
|
| 955 |
"""
|
| 956 |
+
print("[Done] β
")
|
| 957 |
+
return (summary, man_path, ld_path, qq_path,
|
| 958 |
+
cmp_path, ph_path, zip_path)
|
| 959 |
|
| 960 |
except Exception as e:
|
| 961 |
import traceback
|
| 962 |
+
return (f"## β Error\n```\n{e}\n\n{traceback.format_exc()}\n```",
|
| 963 |
+
None, None, None, None, None, None)
|
|
|
|
|
|
|
|
|
|
| 964 |
|
| 965 |
|
| 966 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 967 |
# GRADIO UI
|
| 968 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 969 |
|
| 970 |
+
CSS = """
|
| 971 |
+
.gradio-container{font-family:'Segoe UI',Tahoma,sans-serif}
|
| 972 |
+
h1{color:#2D1B5E;border-bottom:3px solid #7C3AED;padding-bottom:8px}
|
|
|
|
| 973 |
"""
|
| 974 |
|
| 975 |
+
with gr.Blocks(css=CSS, title="MTA GWAS v7.5") as app:
|
| 976 |
|
| 977 |
gr.Markdown("""
|
| 978 |
+
# 𧬠GWAS Analysis Platform v7.5
|
| 979 |
+
### Complete Genomic Association Study with LD Decay Analysis
|
| 980 |
+
Linear Regression + ElasticNet | LD Decay Scatter | QQ Plot | Full Outputs
|
|
|
|
| 981 |
---
|
| 982 |
""")
|
| 983 |
|
|
|
|
| 986 |
gr.Markdown("""
|
| 987 |
### π CSV Format
|
| 988 |
```
|
| 989 |
+
ID, Phenotype, M1, M2, M3, ...
|
| 990 |
+
-, Chr, 1, 1, 2, ...
|
| 991 |
+
Sample1, 45.2, 0, 1, 2, ...
|
| 992 |
+
Sample2, 38.7, 1, 0, 1, ...
|
| 993 |
```
|
| 994 |
+
**Genotypes:** 0 / 1 / 2 (blank or β1 = missing)
|
| 995 |
""")
|
| 996 |
input_file = gr.File(label="π Upload CSV", file_types=[".csv"])
|
| 997 |
|
| 998 |
with gr.Column(scale=1):
|
| 999 |
+
gr.Markdown("### βοΈ QC Parameters")
|
| 1000 |
+
miss_sample = gr.Slider(5, 100, value=30, step=5,
|
| 1001 |
+
label="Max sample missing rate (%)")
|
| 1002 |
+
miss_marker = gr.Slider(5, 100, value=30, step=5,
|
| 1003 |
+
label="Max marker missing rate (%)")
|
| 1004 |
+
maf_thr = gr.Slider(0, 25, value=3, step=1,
|
| 1005 |
+
label="Min MAF (%)")
|
|
|
|
| 1006 |
gr.Markdown("""
|
| 1007 |
+
### π¦ Outputs
|
| 1008 |
+
- Manhattan + LOD plot
|
| 1009 |
+
- **LD Decay scatter** (cM, annotated)
|
| 1010 |
+
- QQ plot (Ξ» inflation)
|
| 1011 |
+
- Model comparison
|
| 1012 |
+
- Phenotype distribution
|
| 1013 |
+
- Full CSV results + ZIP
|
| 1014 |
""")
|
| 1015 |
|
| 1016 |
+
run_btn = gr.Button("π Run GWAS Analysis", variant="primary", size="lg")
|
|
|
|
| 1017 |
gr.Markdown("---")
|
| 1018 |
|
| 1019 |
+
summary_out = gr.Markdown()
|
|
|
|
| 1020 |
|
| 1021 |
with gr.Row():
|
| 1022 |
+
man_out = gr.Image(label="πΊοΈ Manhattan + LOD")
|
| 1023 |
+
ld_out = gr.Image(label="𧬠LD Decay (cM, annotated)")
|
|
|
|
|
|
|
| 1024 |
|
| 1025 |
with gr.Row():
|
| 1026 |
+
qq_out = gr.Image(label="π QQ Plot")
|
| 1027 |
+
cmp_out = gr.Image(label="βοΈ Model Comparison")
|
| 1028 |
|
| 1029 |
with gr.Row():
|
| 1030 |
+
ph_out = gr.Image(label="π Phenotype Distribution")
|
| 1031 |
+
dl_out = gr.File(label="π¦ Download All Results (ZIP)")
|
| 1032 |
|
| 1033 |
gr.Markdown("""
|
| 1034 |
---
|
| 1035 |
+
**MTA GWAS v7.5** | Linear Regression + ElasticNet | LD decay uses marker-rank cM positions
|
| 1036 |
""")
|
| 1037 |
|
| 1038 |
+
run_btn.click(
|
| 1039 |
fn=run_mta_analysis,
|
| 1040 |
+
inputs=[input_file, miss_sample, miss_marker, maf_thr],
|
| 1041 |
+
outputs=[summary_out, man_out, ld_out, qq_out,
|
| 1042 |
+
cmp_out, ph_out, dl_out],
|
| 1043 |
+
show_progress=True,
|
| 1044 |
)
|
| 1045 |
|
| 1046 |
if __name__ == "__main__":
|