Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,30 +1,32 @@
|
|
| 1 |
# -*- coding: utf-8 -*-
|
| 2 |
"""
|
| 3 |
-
MTA Analysis Tool
|
| 4 |
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
|
|
|
|
|
|
| 28 |
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 29 |
"""
|
| 30 |
|
|
@@ -34,139 +36,540 @@ import numpy as np
|
|
| 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
|
| 49 |
-
PANEL
|
| 50 |
-
GRID_C
|
| 51 |
-
TEXT_C
|
| 52 |
-
ACCENT
|
| 53 |
-
RED_C
|
| 54 |
-
GOLD_C
|
| 55 |
-
TEAL_C
|
| 56 |
-
GREEN_C
|
| 57 |
-
PINK_C
|
|
|
|
| 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","#
|
| 64 |
"#6366F1","#EC4899","#10B981","#3B82F6","#F59E0B",
|
| 65 |
]
|
| 66 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
def _style():
|
| 68 |
plt.rcParams.update({
|
| 69 |
-
'figure.facecolor': BG,
|
| 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':
|
| 77 |
})
|
| 78 |
|
| 79 |
|
| 80 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 81 |
-
# CSV PARSER
|
| 82 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 83 |
|
| 84 |
def parse_input_csv(filepath):
|
| 85 |
"""
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
Genotypes: 0/1/2 (blank or -1 = missing)
|
| 92 |
"""
|
| 93 |
-
df
|
| 94 |
marker_cols = df.columns[2:].tolist()
|
| 95 |
-
|
|
|
|
|
|
|
| 96 |
|
| 97 |
chrom_dict, pos_dict = {}, {}
|
| 98 |
for m in marker_cols:
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 124 |
|
| 125 |
|
| 126 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 127 |
-
#
|
| 128 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 129 |
|
| 130 |
-
def
|
| 131 |
"""
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
Returns an array of cM positions of length n_markers.
|
| 135 |
"""
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 140 |
|
| 141 |
|
| 142 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 143 |
"""
|
| 144 |
-
|
| 145 |
-
|
| 146 |
"""
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 159 |
|
| 160 |
|
| 161 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 162 |
-
#
|
| 163 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 164 |
|
| 165 |
-
def
|
| 166 |
"""
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 170 |
"""
|
| 171 |
n = G.shape[1]
|
| 172 |
dists, r2s, dps = [], [], []
|
|
@@ -192,8 +595,7 @@ def _compute_ld_pairs(G, cM_pos, max_lag=50):
|
|
| 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(
|
| 196 |
-
|
| 197 |
dists.append(dist); r2s.append(r2); dps.append(dp)
|
| 198 |
|
| 199 |
if not dists:
|
|
@@ -202,65 +604,52 @@ def _compute_ld_pairs(G, cM_pos, max_lag=50):
|
|
| 202 |
|
| 203 |
|
| 204 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 205 |
-
# PLOT: LD DECAY
|
| 206 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 207 |
|
| 208 |
-
def
|
| 209 |
"""
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 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 |
-
|
| 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 |
-
|
| 230 |
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
#
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 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 =
|
| 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 |
-
|
| 261 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 262 |
|
| 263 |
-
dist, r2, dp =
|
| 264 |
if len(dist) == 0:
|
| 265 |
continue
|
| 266 |
|
|
@@ -275,12 +664,14 @@ def plot_ld_decay(genotypes, chromosomes, positions, save_path, max_m=120):
|
|
| 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
|
| 283 |
-
|
|
|
|
| 284 |
plt.savefig(save_path, dpi=120, bbox_inches='tight')
|
| 285 |
plt.close(fig)
|
| 286 |
return chrom_stats, "No LD data available."
|
|
@@ -289,145 +680,156 @@ def plot_ld_decay(genotypes, chromosomes, positions, save_path, max_m=120):
|
|
| 289 |
r2_arr = np.array(all_r2, dtype=float)
|
| 290 |
ch_arr = np.array(all_ch, dtype=str)
|
| 291 |
|
| 292 |
-
#
|
| 293 |
-
|
| 294 |
-
if
|
| 295 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 296 |
|
| 297 |
-
|
| 298 |
-
|
| 299 |
|
| 300 |
-
# ββ binned
|
| 301 |
-
|
| 302 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 303 |
ctrs, meds = [], []
|
| 304 |
for i in range(N_BINS):
|
| 305 |
-
m = (dv >= bins[i]) & (dv < bins[i
|
| 306 |
if m.sum() >= 3:
|
| 307 |
-
ctrs.append((bins[i] + bins[i
|
| 308 |
meds.append(np.median(rv[m]))
|
| 309 |
|
| 310 |
ctrs = np.array(ctrs, dtype=float)
|
| 311 |
meds = np.array(meds, dtype=float)
|
| 312 |
|
| 313 |
-
# ββ
|
| 314 |
-
|
| 315 |
-
|
| 316 |
if len(ctrs) >= 5:
|
| 317 |
-
k
|
| 318 |
-
|
| 319 |
-
spl
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
r2_start =
|
| 323 |
-
for thr_name, thr_val in [('half',
|
| 324 |
-
('r2_02', 0.
|
| 325 |
-
('r2_01', 0.
|
| 326 |
-
idx_cross = np.where(
|
| 327 |
if len(idx_cross):
|
| 328 |
-
ann[thr_name] = float(
|
| 329 |
-
|
| 330 |
-
|
|
|
|
|
|
|
|
|
|
| 331 |
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
overall_mean_dp = float(np.mean(all_dp))
|
| 335 |
|
|
|
|
| 336 |
if 'half' in ann:
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
f"
|
| 342 |
]
|
| 343 |
else:
|
| 344 |
-
|
| 345 |
|
| 346 |
if 'r2_02' in ann:
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
interp_lines.append(
|
| 350 |
-
f" β Markers within {ann['r2_02']:.1f} cM share enough LD to capture the same signal.")
|
| 351 |
else:
|
| 352 |
-
|
| 353 |
|
| 354 |
if 'r2_01' in ann:
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
f"β’ Overall mean rΒ²
|
| 359 |
-
f"β’ Total
|
| 360 |
]
|
| 361 |
-
|
| 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=(
|
| 368 |
-
|
| 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 |
-
#
|
| 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(
|
| 383 |
-
c=chrom_color[key], s=6, alpha=0.
|
| 384 |
linewidths=0, zorder=2, label=key)
|
| 385 |
|
| 386 |
-
#
|
| 387 |
-
if len(
|
| 388 |
-
ax.fill_between(
|
| 389 |
-
|
| 390 |
-
|
|
|
|
| 391 |
|
| 392 |
-
#
|
| 393 |
-
ax.axhline(0.2, color='#111827', ls='--', lw=1.6,
|
| 394 |
-
zorder=5, label='rΒ² = 0.2')
|
| 395 |
|
| 396 |
-
#
|
| 397 |
ann_styles = {
|
| 398 |
-
'half': (GOLD_C,
|
| 399 |
-
'r2_02': (RED_C,
|
| 400 |
-
'r2_01': (TEAL_C,
|
| 401 |
}
|
| 402 |
-
for
|
| 403 |
-
if
|
| 404 |
-
xv = ann[
|
| 405 |
-
ax.axvline(xv, color=col, ls=':', lw=1.
|
| 406 |
ax.annotate(
|
| 407 |
-
f'{
|
| 408 |
-
xy=(xv,
|
| 409 |
-
xytext=(xv +
|
| 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,
|
| 413 |
-
alpha=0.
|
| 414 |
zorder=7,
|
| 415 |
)
|
| 416 |
|
| 417 |
-
#
|
| 418 |
-
ax.set_xlim(0,
|
| 419 |
ax.set_ylim(0, 1.05)
|
| 420 |
-
ax.set_xlabel('
|
| 421 |
-
color=TEXT_C, labelpad=6)
|
| 422 |
-
ax.set_ylabel('LD estimate (RΒ²)',
|
| 423 |
-
color=TEXT_C, labelpad=6)
|
| 424 |
-
ax.set_title('LD Decay by Chromosome
|
| 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 |
-
#
|
| 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')]
|
|
@@ -435,320 +837,125 @@ def plot_ld_decay(genotypes, chromosomes, positions, save_path, max_m=120):
|
|
| 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 |
-
|
| 440 |
-
|
| 441 |
-
|
| 442 |
-
|
| 443 |
-
|
| 444 |
-
borderpad=0.7, labelspacing=0.4)
|
| 445 |
legend.get_title().set_fontweight('bold')
|
| 446 |
|
| 447 |
-
#
|
| 448 |
-
|
| 449 |
-
|
| 450 |
-
|
| 451 |
-
|
| 452 |
-
|
| 453 |
-
|
| 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:
|
| 470 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 471 |
|
| 472 |
-
def
|
| 473 |
-
sig_set, bonf_thresh, save_path):
|
| 474 |
_style()
|
| 475 |
-
|
| 476 |
-
|
| 477 |
-
|
| 478 |
-
|
| 479 |
-
|
| 480 |
-
|
| 481 |
-
|
| 482 |
-
|
| 483 |
-
|
| 484 |
-
|
| 485 |
-
|
| 486 |
-
|
| 487 |
-
|
| 488 |
-
|
| 489 |
-
|
| 490 |
-
|
| 491 |
-
|
| 492 |
-
|
| 493 |
-
|
| 494 |
-
|
| 495 |
-
|
| 496 |
-
|
| 497 |
-
|
| 498 |
-
|
| 499 |
-
|
| 500 |
-
|
| 501 |
-
|
| 502 |
-
|
| 503 |
-
|
| 504 |
-
|
| 505 |
-
|
| 506 |
-
|
| 507 |
-
|
| 508 |
-
|
| 509 |
-
|
| 510 |
-
|
| 511 |
-
|
| 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
|
| 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.
|
| 612 |
-
ax.
|
| 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=':',
|
| 617 |
label=f'Median={np.median(pv):.2f}')
|
| 618 |
ax.set_xlabel('Phenotype Value', fontsize=11, fontweight='bold')
|
| 619 |
-
ax.set_ylabel('Frequency',
|
| 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,
|
| 629 |
-
ax.set_title('Normal Q-Q
|
| 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 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 745 |
# MAIN ANALYSIS
|
| 746 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 747 |
|
| 748 |
-
def
|
|
|
|
| 749 |
try:
|
| 750 |
if input_file is None:
|
| 751 |
-
return ("β οΈ
|
| 752 |
None, None, None, None, None, None)
|
| 753 |
|
| 754 |
tmp = tempfile.mkdtemp()
|
|
@@ -756,54 +963,51 @@ def run_mta_analysis(input_file, miss_rate_sample, miss_rate_marker, maf_thresh)
|
|
| 756 |
pdir = os.path.join(rdir, 'plots')
|
| 757 |
for d in [rdir, pdir]: os.makedirs(d, exist_ok=True)
|
| 758 |
|
| 759 |
-
ms_t =
|
| 760 |
-
mm_t =
|
| 761 |
-
mf_t = maf_thresh
|
| 762 |
|
|
|
|
| 763 |
print("[Parse] Reading CSVβ¦")
|
| 764 |
(sids, pheno, geno,
|
| 765 |
-
mnames,
|
| 766 |
-
|
| 767 |
n_s, n_m = len(sids), len(mnames)
|
| 768 |
print(f"[Parse] {n_s} samples Γ {n_m} markers")
|
| 769 |
|
| 770 |
# ββ QC βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 771 |
-
|
| 772 |
-
|
| 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 |
-
|
| 780 |
|
| 781 |
-
qc_m = (
|
| 782 |
-
qc_s =
|
| 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 = (
|
| 788 |
-
qs =
|
| 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β οΈ
|
| 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]
|
| 800 |
-
ch_q = [
|
| 801 |
-
pos_q = [positions[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]):
|
|
@@ -811,78 +1015,97 @@ def run_mta_analysis(input_file, miss_rate_sample, miss_rate_marker, maf_thresh)
|
|
| 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 |
-
"
|
| 820 |
None, None, None, None, None, None)
|
| 821 |
|
| 822 |
-
bonf
|
| 823 |
bonf_log = -np.log10(bonf)
|
| 824 |
|
| 825 |
-
# ββ
|
| 826 |
-
print("[
|
| 827 |
-
|
| 828 |
-
|
| 829 |
-
|
| 830 |
-
|
| 831 |
-
|
| 832 |
-
|
| 833 |
-
|
| 834 |
-
|
| 835 |
-
|
| 836 |
-
|
| 837 |
-
'
|
| 838 |
-
|
| 839 |
-
|
| 840 |
-
|
| 841 |
-
|
| 842 |
-
'
|
| 843 |
-
|
| 844 |
-
|
| 845 |
-
|
| 846 |
-
|
| 847 |
-
|
| 848 |
-
|
| 849 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 850 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 851 |
df.to_csv(os.path.join(rdir, 'gwas_results.csv'), index=False)
|
| 852 |
|
| 853 |
-
# Significant only
|
| 854 |
-
|
| 855 |
-
|
| 856 |
|
| 857 |
# ββ Plots βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 858 |
print("[Plot 1/5] Phenotype distributionβ¦")
|
| 859 |
ph_path = os.path.join(pdir, 'phenotype_dist.png')
|
| 860 |
-
|
| 861 |
|
| 862 |
-
print("[Plot 2/5] Manhattan
|
| 863 |
man_path = os.path.join(pdir, 'manhattan_lod.png')
|
| 864 |
-
|
| 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
|
| 870 |
qq_path = os.path.join(pdir, 'qq_plot.png')
|
| 871 |
-
|
| 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 |
-
|
| 878 |
-
|
| 879 |
-
|
| 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(
|
| 886 |
|
| 887 |
# ββ ZIP βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 888 |
zip_path = os.path.join(tmp, 'GWAS_Results.zip')
|
|
@@ -892,66 +1115,67 @@ def run_mta_analysis(input_file, miss_rate_sample, miss_rate_marker, maf_thresh)
|
|
| 892 |
fp = os.path.join(root, f)
|
| 893 |
zf.write(fp, os.path.relpath(fp, tmp))
|
| 894 |
|
| 895 |
-
# ββ Summary
|
| 896 |
-
def
|
| 897 |
-
|
|
|
|
| 898 |
def _f(v):
|
| 899 |
if isinstance(v, float):
|
| 900 |
-
return f"{v:.
|
| 901 |
return str(v)
|
| 902 |
sep = "| " + " | ".join(["---"]*len(cols)) + " |"
|
| 903 |
rows = ["| "+" | ".join(_f(row[c]) for c in cols)+" |"
|
| 904 |
-
for _, row in
|
| 905 |
return "\n".join(["| "+" | ".join(cols)+" |", sep]+rows)
|
| 906 |
|
| 907 |
-
|
| 908 |
-
|
| 909 |
-
|
| 910 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 911 |
|
| 912 |
summary = f"""
|
| 913 |
-
## β
GWAS Analysis Complete β
|
| 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
|
| 922 |
-
| Sample missing
|
| 923 |
-
| Marker missing
|
| 924 |
{fallback}
|
| 925 |
|
| 926 |
-
### π¬
|
| 927 |
-
| Model |
|
| 928 |
-
|------
|
| 929 |
-
|
| 930 |
-
| ElasticNet | **{int((en_p < bonf).sum())}** |
|
| 931 |
-
| Consensus (both) | **{int(df['Consensus_Sig'].sum())}** |
|
| 932 |
|
| 933 |
-
**Bonferroni threshold:** P < {bonf:.3e}
|
| 934 |
|
| 935 |
-
###
|
| 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
|
| 943 |
-
{
|
| 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 |
-
- `
|
| 951 |
-
- `
|
| 952 |
-
- `
|
| 953 |
-
- `
|
| 954 |
-
- `
|
| 955 |
"""
|
| 956 |
print("[Done] β
")
|
| 957 |
return (summary, man_path, ld_path, qq_path,
|
|
@@ -972,26 +1196,26 @@ CSS = """
|
|
| 972 |
h1{color:#2D1B5E;border-bottom:3px solid #7C3AED;padding-bottom:8px}
|
| 973 |
"""
|
| 974 |
|
| 975 |
-
with gr.Blocks(css=CSS, title="MTA GWAS
|
| 976 |
|
| 977 |
gr.Markdown("""
|
| 978 |
-
# 𧬠GWAS Analysis Platform
|
| 979 |
-
###
|
| 980 |
-
Linear Regression + ElasticNet | LD Decay Scatter | QQ Plot | Full Outputs
|
| 981 |
---
|
| 982 |
""")
|
| 983 |
|
| 984 |
with gr.Row():
|
| 985 |
with gr.Column(scale=1):
|
| 986 |
gr.Markdown("""
|
| 987 |
-
### π CSV Format
|
| 988 |
```
|
| 989 |
-
ID, Phenotype,
|
| 990 |
-
-, Chr, 1,
|
| 991 |
-
|
| 992 |
-
|
|
|
|
| 993 |
```
|
| 994 |
-
**Genotypes:** 0
|
| 995 |
""")
|
| 996 |
input_file = gr.File(label="π Upload CSV", file_types=[".csv"])
|
| 997 |
|
|
@@ -1003,15 +1227,14 @@ with gr.Blocks(css=CSS, title="MTA GWAS v7.5") as app:
|
|
| 1003 |
label="Max marker missing rate (%)")
|
| 1004 |
maf_thr = gr.Slider(0, 25, value=3, step=1,
|
| 1005 |
label="Min MAF (%)")
|
| 1006 |
-
|
| 1007 |
-
|
| 1008 |
-
|
| 1009 |
-
|
| 1010 |
-
|
| 1011 |
-
|
| 1012 |
-
|
| 1013 |
-
|
| 1014 |
-
""")
|
| 1015 |
|
| 1016 |
run_btn = gr.Button("π Run GWAS Analysis", variant="primary", size="lg")
|
| 1017 |
gr.Markdown("---")
|
|
@@ -1019,12 +1242,12 @@ with gr.Blocks(css=CSS, title="MTA GWAS v7.5") as app:
|
|
| 1019 |
summary_out = gr.Markdown()
|
| 1020 |
|
| 1021 |
with gr.Row():
|
| 1022 |
-
man_out = gr.Image(label="πΊοΈ Manhattan
|
| 1023 |
-
ld_out = gr.Image(label="𧬠LD Decay
|
| 1024 |
|
| 1025 |
with gr.Row():
|
| 1026 |
-
qq_out = gr.Image(label="π QQ
|
| 1027 |
-
cmp_out = gr.Image(label="βοΈ Model
|
| 1028 |
|
| 1029 |
with gr.Row():
|
| 1030 |
ph_out = gr.Image(label="π Phenotype Distribution")
|
|
@@ -1032,12 +1255,13 @@ with gr.Blocks(css=CSS, title="MTA GWAS v7.5") as app:
|
|
| 1032 |
|
| 1033 |
gr.Markdown("""
|
| 1034 |
---
|
| 1035 |
-
**MTA GWAS
|
| 1036 |
""")
|
| 1037 |
|
| 1038 |
run_btn.click(
|
| 1039 |
-
fn=
|
| 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,
|
|
|
|
| 1 |
# -*- coding: utf-8 -*-
|
| 2 |
"""
|
| 3 |
+
MTA Analysis Tool v8.0 β Complete GWAS Platform
|
| 4 |
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 5 |
+
INPUT FORMAT (3-header-row CSV):
|
| 6 |
+
Row 1 : ID | Phenotype | marker_name ...
|
| 7 |
+
Row 2 : - | Chr | chromosome ... (e.g. 1,2,3β¦)
|
| 8 |
+
Row 3 : - | Pos | bp_position ... (e.g. 134521β¦)
|
| 9 |
+
Row 4+: sample data | 0/1/2 genotypes (-1 or blank = missing)
|
| 10 |
+
|
| 11 |
+
MODELS (5 MRmlm-style):
|
| 12 |
+
1. GLM β General Linear Model (single-marker OLS)
|
| 13 |
+
2. MLM β Mixed Linear Model (kinship K as random effect via ridge)
|
| 14 |
+
3. CMLM β Compressed MLM (group-mean kinship)
|
| 15 |
+
4. BSLMM β Bayesian Sparse LMM (ElasticNet + bootstrap p-values)
|
| 16 |
+
5. FarmCPU β Fixed & Random (iterative pseudo-QTN control)
|
| 17 |
+
|
| 18 |
+
PLOTS:
|
| 19 |
+
β’ Manhattan + LOD (all 5 models)
|
| 20 |
+
β’ QQ plot with correct βlogββ(P) observed vs expected, Ξ» annotation
|
| 21 |
+
β’ LD Decay scatter in bp (physical distance), chromosome-coloured,
|
| 22 |
+
green median decay curve, annotated decay positions in kb/Mb
|
| 23 |
+
β’ Model comparison (P-value correlations)
|
| 24 |
+
β’ Phenotype distribution + normality
|
| 25 |
+
|
| 26 |
+
OUTPUTS (ZIP):
|
| 27 |
+
gwas_results.csv | top_significant.csv | ld_decay_stats.csv
|
| 28 |
+
manhattan_lod.png | qq_plot.png | ld_decay_bp.png
|
| 29 |
+
model_comparison.png | phenotype_dist.png
|
| 30 |
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 31 |
"""
|
| 32 |
|
|
|
|
| 36 |
import matplotlib
|
| 37 |
matplotlib.use('Agg')
|
| 38 |
import matplotlib.pyplot as plt
|
|
|
|
| 39 |
from scipy import stats
|
| 40 |
from scipy.interpolate import make_interp_spline
|
| 41 |
import os, warnings, tempfile, zipfile
|
| 42 |
+
from sklearn.linear_model import ElasticNetCV, RidgeCV
|
| 43 |
from sklearn.preprocessing import StandardScaler
|
| 44 |
+
from sklearn.decomposition import PCA
|
| 45 |
warnings.filterwarnings('ignore')
|
| 46 |
|
| 47 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 48 |
# THEME
|
| 49 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 50 |
+
BG = "#FDFBFF"
|
| 51 |
+
PANEL = "#F4EFFE"
|
| 52 |
+
GRID_C = "#E2D9F3"
|
| 53 |
+
TEXT_C = "#2D1B5E"
|
| 54 |
+
ACCENT = "#7C3AED"
|
| 55 |
+
RED_C = "#E11D48"
|
| 56 |
+
GOLD_C = "#D97706"
|
| 57 |
+
TEAL_C = "#0891B2"
|
| 58 |
+
GREEN_C = "#15803D"
|
| 59 |
+
PINK_C = "#DB2777"
|
| 60 |
+
ORANGE_C= "#EA580C"
|
| 61 |
|
| 62 |
CHROM_PALETTE = [
|
| 63 |
"#7C3AED","#DB2777","#059669","#0284C7","#D97706",
|
| 64 |
"#6D28D9","#BE185D","#047857","#0369A1","#B45309",
|
| 65 |
"#4F46E5","#9D174D","#065F46","#075985","#92400E",
|
| 66 |
+
"#7C3AED","#C026D3","#0F766E","#1D4ED8","#CA8A04",
|
| 67 |
"#6366F1","#EC4899","#10B981","#3B82F6","#F59E0B",
|
| 68 |
]
|
| 69 |
|
| 70 |
+
MODEL_COLORS = {
|
| 71 |
+
'GLM': '#7C3AED',
|
| 72 |
+
'MLM': '#DB2777',
|
| 73 |
+
'CMLM': '#059669',
|
| 74 |
+
'BSLMM': '#D97706',
|
| 75 |
+
'FarmCPU': '#0284C7',
|
| 76 |
+
}
|
| 77 |
+
|
| 78 |
def _style():
|
| 79 |
plt.rcParams.update({
|
| 80 |
+
'figure.facecolor': BG, 'axes.facecolor': PANEL,
|
| 81 |
'axes.edgecolor': GRID_C,'axes.labelcolor': TEXT_C,
|
| 82 |
'axes.titlecolor': TEXT_C,'xtick.color': TEXT_C,
|
| 83 |
'ytick.color': TEXT_C,'text.color': TEXT_C,
|
| 84 |
'grid.color': GRID_C,'grid.linewidth': 0.7,
|
| 85 |
'figure.dpi': 120, 'font.family': 'DejaVu Sans',
|
| 86 |
'axes.spines.top': False, 'axes.spines.right': False,
|
| 87 |
+
'legend.framealpha':0.95, 'legend.edgecolor': GRID_C,
|
| 88 |
})
|
| 89 |
|
| 90 |
|
| 91 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 92 |
+
# CSV PARSER (3-row header format)
|
| 93 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 94 |
|
| 95 |
def parse_input_csv(filepath):
|
| 96 |
"""
|
| 97 |
+
Row 0 : column headers β ID | Phenotype | M1 | M2 β¦
|
| 98 |
+
Row 1 : chromosome row β - | Chr/1/2β¦ | 1 | 1 β¦
|
| 99 |
+
Row 2 : position row β - | pos/4345β¦ | bp1| bp2β¦
|
| 100 |
+
Row 3+: sample data
|
| 101 |
+
Genotypes: 0/1/2 (-1 or blank β missing)
|
|
|
|
| 102 |
"""
|
| 103 |
+
df = pd.read_csv(filepath, header=0, dtype=str)
|
| 104 |
marker_cols = df.columns[2:].tolist()
|
| 105 |
+
|
| 106 |
+
chr_row = df.iloc[0] # chromosome numbers
|
| 107 |
+
pos_row = df.iloc[1] # physical positions (bp)
|
| 108 |
|
| 109 |
chrom_dict, pos_dict = {}, {}
|
| 110 |
for m in marker_cols:
|
| 111 |
+
# chromosome
|
| 112 |
+
cv = str(chr_row[m]).strip()
|
| 113 |
+
cv = cv[:-2] if cv.endswith('.0') else cv
|
| 114 |
+
cv = cv.replace('chr','').replace('Chr','').strip()
|
| 115 |
+
chrom_dict[m] = cv if cv not in ('', 'nan', '-') else '0'
|
| 116 |
+
|
| 117 |
+
# physical position
|
| 118 |
+
pv = str(pos_row[m]).strip()
|
| 119 |
+
try:
|
| 120 |
+
pos_dict[m] = float(pv)
|
| 121 |
+
except ValueError:
|
| 122 |
+
# fall back to position encoded in marker name: chr1_134521_β¦
|
| 123 |
+
name_parts = m.split('_')
|
| 124 |
+
bp = 0.0
|
| 125 |
+
for part in name_parts:
|
| 126 |
+
try:
|
| 127 |
+
bp = float(part)
|
| 128 |
+
if bp > 1000: # looks like a bp value
|
| 129 |
+
break
|
| 130 |
+
except ValueError:
|
| 131 |
+
continue
|
| 132 |
+
pos_dict[m] = bp
|
| 133 |
+
|
| 134 |
+
df_s = df.iloc[2:].reset_index(drop=True)
|
| 135 |
sample_ids = df_s.iloc[:, 0].astype(str).values
|
| 136 |
phenotypes = pd.to_numeric(df_s.iloc[:, 1], errors='coerce').values
|
|
|
|
|
|
|
|
|
|
|
|
|
| 137 |
|
| 138 |
+
geno_raw = (df_s[marker_cols]
|
| 139 |
+
.apply(pd.to_numeric, errors='coerce')
|
| 140 |
+
.replace(-1, np.nan) # -1 β NaN
|
| 141 |
+
.where(lambda x: x.isin([0, 1, 2]) | x.isna(), other=np.nan))
|
| 142 |
+
|
| 143 |
+
chromosomes = [chrom_dict[m] for m in marker_cols]
|
| 144 |
+
positions = [pos_dict[m] for m in marker_cols]
|
| 145 |
+
|
| 146 |
+
return (sample_ids, phenotypes,
|
| 147 |
+
geno_raw.values, marker_cols,
|
| 148 |
+
chromosomes, positions)
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 152 |
+
# KINSHIP MATRIX
|
| 153 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 154 |
+
|
| 155 |
+
def compute_kinship(G):
|
| 156 |
+
"""
|
| 157 |
+
Centered IBS kinship matrix K = X X' / p
|
| 158 |
+
where X is mean-centred, standardised genotype matrix.
|
| 159 |
+
"""
|
| 160 |
+
X = G.astype(float).copy()
|
| 161 |
+
# standardise each marker
|
| 162 |
+
mu = np.nanmean(X, 0)
|
| 163 |
+
std = np.nanstd(X, 0)
|
| 164 |
+
std[std < 1e-9] = 1.0
|
| 165 |
+
X = (X - mu) / std
|
| 166 |
+
X = np.nan_to_num(X, 0)
|
| 167 |
+
n = X.shape[0]
|
| 168 |
+
K = (X @ X.T) / X.shape[1]
|
| 169 |
+
# normalize so diagonal mean = 1
|
| 170 |
+
d = np.diag(K).mean()
|
| 171 |
+
if d > 0:
|
| 172 |
+
K /= d
|
| 173 |
+
return K
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 177 |
+
# MODEL 1: GLM (standard single-marker OLS)
|
| 178 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 179 |
+
|
| 180 |
+
def model_glm(G, y):
|
| 181 |
+
"""Single-marker OLS regression. Returns (p_values, betas, ses, r2s)."""
|
| 182 |
+
n, m = G.shape
|
| 183 |
+
pv = np.ones(m); bv = np.zeros(m)
|
| 184 |
+
sv = np.zeros(m); rv = np.zeros(m)
|
| 185 |
+
for i in range(m):
|
| 186 |
+
x = G[:, i]
|
| 187 |
+
if x.std() < 1e-9: continue
|
| 188 |
+
sl, _, r, p, se = stats.linregress(x, y)
|
| 189 |
+
pv[i] = max(p, 1e-300) if np.isfinite(p) else 1.0
|
| 190 |
+
bv[i] = sl; sv[i] = se; rv[i] = r**2
|
| 191 |
+
return pv, bv, sv, rv
|
| 192 |
|
| 193 |
|
| 194 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 195 |
+
# MODEL 2: MLM (Mixed Linear Model via EMMA-lite)
|
| 196 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 197 |
|
| 198 |
+
def model_mlm(G, y, K):
|
| 199 |
"""
|
| 200 |
+
Approximate MLM: decorrelate y using PCA of K (top PCs as covariates),
|
| 201 |
+
then run per-marker OLS on residuals. Fast EMMA-lite approach.
|
|
|
|
| 202 |
"""
|
| 203 |
+
# Use top PCs of K as population-structure covariates
|
| 204 |
+
n = len(y)
|
| 205 |
+
n_pc = min(5, n - 2)
|
| 206 |
+
eigvals, eigvecs = np.linalg.eigh(K)
|
| 207 |
+
idx = np.argsort(eigvals)[::-1]
|
| 208 |
+
Q = eigvecs[:, idx[:n_pc]] # n Γ n_pc
|
| 209 |
+
|
| 210 |
+
# partial out Q from y
|
| 211 |
+
Qy = Q @ np.linalg.lstsq(Q, y, rcond=None)[0]
|
| 212 |
+
y_r = y - Qy
|
| 213 |
+
|
| 214 |
+
m = G.shape[1]
|
| 215 |
+
pv = np.ones(m); bv = np.zeros(m)
|
| 216 |
+
sv = np.zeros(m); rv = np.zeros(m)
|
| 217 |
+
for i in range(m):
|
| 218 |
+
x = G[:, i]
|
| 219 |
+
if x.std() < 1e-9: continue
|
| 220 |
+
# partial out Q from x too
|
| 221 |
+
Qx = Q @ np.linalg.lstsq(Q, x, rcond=None)[0]
|
| 222 |
+
xr = x - Qx
|
| 223 |
+
if xr.std() < 1e-9: continue
|
| 224 |
+
sl, _, r, p, se = stats.linregress(xr, y_r)
|
| 225 |
+
pv[i] = max(p, 1e-300) if np.isfinite(p) else 1.0
|
| 226 |
+
bv[i] = sl; sv[i] = se; rv[i] = r**2
|
| 227 |
+
return pv, bv, sv, rv
|
| 228 |
|
| 229 |
|
| 230 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 231 |
+
# MODEL 3: CMLM (Compressed MLM)
|
| 232 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 233 |
+
|
| 234 |
+
def model_cmlm(G, y, K, n_groups=None):
|
| 235 |
"""
|
| 236 |
+
CMLM: cluster individuals into groups using K, use group means
|
| 237 |
+
as kinship covariates instead of full K.
|
| 238 |
"""
|
| 239 |
+
from sklearn.cluster import KMeans
|
| 240 |
+
n = len(y)
|
| 241 |
+
if n_groups is None:
|
| 242 |
+
n_groups = max(2, min(20, n // 10))
|
| 243 |
+
|
| 244 |
+
# Spectral embedding of K for clustering
|
| 245 |
+
eigvals, eigvecs = np.linalg.eigh(K)
|
| 246 |
+
idx = np.argsort(eigvals)[::-1]
|
| 247 |
+
emb = eigvecs[:, idx[:min(10, n-1)]]
|
| 248 |
+
|
| 249 |
+
km = KMeans(n_clusters=n_groups, random_state=42, n_init=5)
|
| 250 |
+
labs = km.fit_predict(emb)
|
| 251 |
+
|
| 252 |
+
# group-mean compressed kinship covariates
|
| 253 |
+
Q = np.zeros((n, n_groups))
|
| 254 |
+
for g in range(n_groups):
|
| 255 |
+
Q[:, g] = (labs == g).astype(float)
|
| 256 |
+
# normalize columns
|
| 257 |
+
col_sum = Q.sum(0)
|
| 258 |
+
col_sum[col_sum == 0] = 1
|
| 259 |
+
Q = Q / col_sum
|
| 260 |
+
|
| 261 |
+
Qy = Q @ np.linalg.lstsq(Q, y, rcond=None)[0]
|
| 262 |
+
y_r = y - Qy
|
| 263 |
+
|
| 264 |
+
m = G.shape[1]
|
| 265 |
+
pv = np.ones(m); bv = np.zeros(m)
|
| 266 |
+
sv = np.zeros(m); rv = np.zeros(m)
|
| 267 |
+
for i in range(m):
|
| 268 |
+
x = G[:, i]
|
| 269 |
+
if x.std() < 1e-9: continue
|
| 270 |
+
Qx = Q @ np.linalg.lstsq(Q, x, rcond=None)[0]
|
| 271 |
+
xr = x - Qx
|
| 272 |
+
if xr.std() < 1e-9: continue
|
| 273 |
+
sl, _, r, p, se = stats.linregress(xr, y_r)
|
| 274 |
+
pv[i] = max(p, 1e-300) if np.isfinite(p) else 1.0
|
| 275 |
+
bv[i] = sl; sv[i] = se; rv[i] = r**2
|
| 276 |
+
return pv, bv, sv, rv
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 280 |
+
# MODEL 4: BSLMM (Bayesian Sparse LMM via ElasticNet)
|
| 281 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 282 |
+
|
| 283 |
+
def model_bslmm(G, y, n_boot=20):
|
| 284 |
+
"""
|
| 285 |
+
BSLMM approximation: ElasticNet sparse selection + bootstrap
|
| 286 |
+
p-values from coefficient stability across bootstrap samples.
|
| 287 |
+
"""
|
| 288 |
+
sc = StandardScaler()
|
| 289 |
+
Xs = sc.fit_transform(G)
|
| 290 |
+
en = ElasticNetCV(cv=3, random_state=42, max_iter=3000, n_jobs=-1,
|
| 291 |
+
l1_ratio=[.1,.5,.7,.9,.95,1])
|
| 292 |
+
en.fit(Xs, y)
|
| 293 |
+
coef = en.coef_
|
| 294 |
+
|
| 295 |
+
boots = []
|
| 296 |
+
rng = np.random.default_rng(42)
|
| 297 |
+
for _ in range(n_boot):
|
| 298 |
+
idx = rng.integers(0, len(y), len(y))
|
| 299 |
+
eb = ElasticNetCV(cv=3, random_state=42, max_iter=2000,
|
| 300 |
+
l1_ratio=[.1,.5,.9,1])
|
| 301 |
+
try:
|
| 302 |
+
eb.fit(Xs[idx], y[idx])
|
| 303 |
+
boots.append(eb.coef_)
|
| 304 |
+
except Exception:
|
| 305 |
+
boots.append(coef.copy())
|
| 306 |
+
|
| 307 |
+
boot_arr = np.array(boots)
|
| 308 |
+
pv = np.ones(len(coef))
|
| 309 |
+
for i in range(len(coef)):
|
| 310 |
+
sd = boot_arr[:, i].std()
|
| 311 |
+
if sd > 0:
|
| 312 |
+
z = abs(coef[i]) / (sd + 1e-12)
|
| 313 |
+
pv[i] = max(2*(1 - stats.norm.cdf(z)), 1e-300)
|
| 314 |
+
return pv, coef
|
| 315 |
+
|
| 316 |
+
|
| 317 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 318 |
+
# MODEL 5: FarmCPU (Fixed & Random Circulating Probability)
|
| 319 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 320 |
+
|
| 321 |
+
def model_farmcpu(G, y, K, max_iter=3):
|
| 322 |
+
"""
|
| 323 |
+
FarmCPU approximation:
|
| 324 |
+
- Iteratively selects pseudo-QTNs (top significant markers from previous iter)
|
| 325 |
+
- Conditions each marker test on pseudo-QTNs as fixed covariates
|
| 326 |
+
- Controls false positives better than MLM alone
|
| 327 |
+
"""
|
| 328 |
+
n, m = G.shape
|
| 329 |
+
pv_prev = np.ones(m)
|
| 330 |
+
|
| 331 |
+
# Step 0: initial GLM scan
|
| 332 |
+
pv_cur, bv, sv, rv = model_glm(G, y)
|
| 333 |
+
|
| 334 |
+
for iteration in range(max_iter):
|
| 335 |
+
# select top pseudo-QTNs (top 10 or top 0.01%)
|
| 336 |
+
n_qtns = max(1, min(10, int(m * 0.001)))
|
| 337 |
+
top_idx = np.argsort(pv_cur)[:n_qtns]
|
| 338 |
+
|
| 339 |
+
# Build covariate matrix from pseudo-QTNs
|
| 340 |
+
covs = G[:, top_idx] # n Γ n_qtns
|
| 341 |
+
|
| 342 |
+
# Condition y on pseudo-QTNs
|
| 343 |
+
try:
|
| 344 |
+
coef_c, _, _, _ = np.linalg.lstsq(covs, y, rcond=None)
|
| 345 |
+
y_cond = y - covs @ coef_c
|
| 346 |
+
except Exception:
|
| 347 |
+
y_cond = y.copy()
|
| 348 |
+
|
| 349 |
+
# Re-scan
|
| 350 |
+
pv_new = np.ones(m)
|
| 351 |
+
bv_new = np.zeros(m)
|
| 352 |
+
sv_new = np.zeros(m)
|
| 353 |
+
for i in range(m):
|
| 354 |
+
x = G[:, i]
|
| 355 |
+
if x.std() < 1e-9: continue
|
| 356 |
+
# remove pseudo-QTN effect from marker too
|
| 357 |
+
try:
|
| 358 |
+
c2 = np.linalg.lstsq(covs, x, rcond=None)[0]
|
| 359 |
+
xc = x - covs @ c2
|
| 360 |
+
except Exception:
|
| 361 |
+
xc = x
|
| 362 |
+
if xc.std() < 1e-9: continue
|
| 363 |
+
sl, _, r, p, se = stats.linregress(xc, y_cond)
|
| 364 |
+
pv_new[i] = max(p, 1e-300) if np.isfinite(p) else 1.0
|
| 365 |
+
bv_new[i] = sl; sv_new[i] = se
|
| 366 |
+
|
| 367 |
+
pv_prev = pv_cur.copy()
|
| 368 |
+
pv_cur = pv_new.copy()
|
| 369 |
+
|
| 370 |
+
return pv_cur, bv_new, sv_new
|
| 371 |
|
| 372 |
|
| 373 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 374 |
+
# PLOT: MANHATTAN (multi-model)
|
| 375 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 376 |
|
| 377 |
+
def plot_manhattan_multi(mn, chroms, model_pvals, bonf_thresh, save_path):
|
| 378 |
"""
|
| 379 |
+
One subplot per model, stacked vertically.
|
| 380 |
+
model_pvals: dict {model_name: p_array}
|
| 381 |
+
"""
|
| 382 |
+
_style()
|
| 383 |
+
unique_chroms = sorted(set(chroms),
|
| 384 |
+
key=lambda x: (int(x) if str(x).isdigit() else 999, str(x)))
|
| 385 |
+
n_models = len(model_pvals)
|
| 386 |
+
GAP = max(8, len(mn) // 150)
|
| 387 |
+
|
| 388 |
+
chrom_to_idx = {}
|
| 389 |
+
for i, c in enumerate(chroms):
|
| 390 |
+
chrom_to_idx.setdefault(c, []).append(i)
|
| 391 |
+
|
| 392 |
+
x_pos = np.zeros(len(mn))
|
| 393 |
+
chrom_xticks, offset = [], 0
|
| 394 |
+
for ch in unique_chroms:
|
| 395 |
+
idxs = chrom_to_idx.get(ch, [])
|
| 396 |
+
if not idxs: continue
|
| 397 |
+
for r, idx in enumerate(idxs):
|
| 398 |
+
x_pos[idx] = offset + r
|
| 399 |
+
chrom_xticks.append((offset + len(idxs)/2, str(ch)))
|
| 400 |
+
offset += len(idxs) + GAP
|
| 401 |
+
|
| 402 |
+
fig, axes = plt.subplots(n_models, 1,
|
| 403 |
+
figsize=(18, 3.2 * n_models),
|
| 404 |
+
facecolor=BG, sharex=True)
|
| 405 |
+
if n_models == 1:
|
| 406 |
+
axes = [axes]
|
| 407 |
+
|
| 408 |
+
bonf_log = -np.log10(bonf_thresh)
|
| 409 |
+
sug_log = 3.0
|
| 410 |
+
|
| 411 |
+
for ax, (mname, pv) in zip(axes, model_pvals.items()):
|
| 412 |
+
log_p = -np.log10(np.clip(pv, 1e-300, 1))
|
| 413 |
+
sig_set = set(np.where(pv < bonf_thresh)[0])
|
| 414 |
+
mcol = MODEL_COLORS.get(mname, ACCENT)
|
| 415 |
+
|
| 416 |
+
for ci, ch in enumerate(unique_chroms):
|
| 417 |
+
idxs = chrom_to_idx.get(ch, [])
|
| 418 |
+
if not idxs: continue
|
| 419 |
+
if ci % 2 == 0:
|
| 420 |
+
ax.axvspan(x_pos[idxs[0]] - 0.5, x_pos[idxs[-1]] + 0.5,
|
| 421 |
+
color='#EDE9FE', alpha=0.35, zorder=0)
|
| 422 |
+
shade = CHROM_PALETTE[ci % len(CHROM_PALETTE)]
|
| 423 |
+
norm = [i for i in idxs if i not in sig_set]
|
| 424 |
+
sel = [i for i in idxs if i in sig_set]
|
| 425 |
+
if norm:
|
| 426 |
+
ax.scatter(x_pos[norm], log_p[norm],
|
| 427 |
+
c=shade, s=8, alpha=0.55, linewidths=0, zorder=2)
|
| 428 |
+
if sel:
|
| 429 |
+
ax.scatter(x_pos[sel], log_p[sel],
|
| 430 |
+
c=RED_C, s=220, alpha=0.12, linewidths=0, zorder=3)
|
| 431 |
+
ax.scatter(x_pos[sel], log_p[sel],
|
| 432 |
+
c=RED_C, s=55, alpha=1.0,
|
| 433 |
+
edgecolors='white', linewidths=0.8,
|
| 434 |
+
marker='D', zorder=4)
|
| 435 |
+
|
| 436 |
+
ax.axhline(bonf_log, color=RED_C, ls='--', lw=1.6, alpha=0.85,
|
| 437 |
+
label=f'Bonferroni ({bonf_log:.1f})')
|
| 438 |
+
ax.axhline(sug_log, color=GOLD_C, ls=':', lw=1.4, alpha=0.8,
|
| 439 |
+
label='Suggestive (3)')
|
| 440 |
+
ax.set_xlim(-GAP, offset)
|
| 441 |
+
ax.set_ylim(0, max(log_p.max() * 1.15, bonf_log * 1.1, 1))
|
| 442 |
+
ax.set_ylabel('βlogββ(P)', fontsize=10, fontweight='bold')
|
| 443 |
+
ax.set_title(f'Model: {mname}', fontsize=11, fontweight='bold',
|
| 444 |
+
color=mcol, pad=4)
|
| 445 |
+
ax.yaxis.grid(True, color=GRID_C, lw=0.6)
|
| 446 |
+
ax.legend(loc='upper right', fontsize=7.5, framealpha=0.9)
|
| 447 |
+
|
| 448 |
+
# count sig
|
| 449 |
+
n_sig = int((pv < bonf_thresh).sum())
|
| 450 |
+
ax.text(0.01, 0.92, f'{n_sig} significant', transform=ax.transAxes,
|
| 451 |
+
fontsize=8, color=RED_C, fontweight='bold')
|
| 452 |
+
|
| 453 |
+
axes[-1].set_xticks([x for x, _ in chrom_xticks])
|
| 454 |
+
axes[-1].set_xticklabels([l for _, l in chrom_xticks], fontsize=7)
|
| 455 |
+
axes[-1].set_xlabel('Chromosome', fontsize=11, fontweight='bold')
|
| 456 |
+
|
| 457 |
+
plt.suptitle('GWAS Manhattan Plots β Multi-Model Comparison',
|
| 458 |
+
fontsize=13, fontweight='bold', y=1.01, color=TEXT_C)
|
| 459 |
+
plt.tight_layout(pad=1.2)
|
| 460 |
+
plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=BG)
|
| 461 |
+
plt.close(fig)
|
| 462 |
+
|
| 463 |
+
|
| 464 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 465 |
+
# PLOT: QQ (fixed βlogββ calculation)
|
| 466 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 467 |
+
|
| 468 |
+
def plot_qq_multi(model_pvals, bonf_thresh, save_path):
|
| 469 |
+
"""
|
| 470 |
+
One QQ panel per model in a grid.
|
| 471 |
+
Correct βlogββ(P) observed vs expected uniform.
|
| 472 |
+
"""
|
| 473 |
+
_style()
|
| 474 |
+
n_models = len(model_pvals)
|
| 475 |
+
ncols = min(3, n_models)
|
| 476 |
+
nrows = (n_models + ncols - 1) // ncols
|
| 477 |
+
|
| 478 |
+
fig, axes = plt.subplots(nrows, ncols,
|
| 479 |
+
figsize=(5.5 * ncols, 5 * nrows),
|
| 480 |
+
facecolor=BG, squeeze=False)
|
| 481 |
+
|
| 482 |
+
bonf_log = -np.log10(bonf_thresh)
|
| 483 |
+
lam_dict = {}
|
| 484 |
+
|
| 485 |
+
for idx, (mname, pv_raw) in enumerate(model_pvals.items()):
|
| 486 |
+
row, col = divmod(idx, ncols)
|
| 487 |
+
ax = axes[row][col]
|
| 488 |
+
ax.set_facecolor(PANEL)
|
| 489 |
+
|
| 490 |
+
# ββ correct observed βlogββ(P) ββββββββββββββββββββββββββββββββββββββ
|
| 491 |
+
pv = np.array(pv_raw, dtype=float)
|
| 492 |
+
pv = pv[np.isfinite(pv) & (pv > 0) & (pv <= 1)]
|
| 493 |
+
if len(pv) == 0:
|
| 494 |
+
ax.text(0.5, 0.5, 'No valid p-values',
|
| 495 |
+
ha='center', va='center', transform=ax.transAxes)
|
| 496 |
+
continue
|
| 497 |
+
|
| 498 |
+
n = len(pv)
|
| 499 |
+
obs_log = -np.log10(np.sort(pv)) # largest first after sort
|
| 500 |
+
# expected quantiles of Uniform(0,1)
|
| 501 |
+
exp_log = -np.log10(np.arange(1, n + 1) / (n + 1))
|
| 502 |
+
# sort both descending (largest first β plot top-right)
|
| 503 |
+
obs_log = obs_log[::-1] # ascending now (smallest p β rightmost)
|
| 504 |
+
exp_log = exp_log[::-1]
|
| 505 |
+
|
| 506 |
+
# genomic inflation Ξ» from median chiΒ²
|
| 507 |
+
chi2_obs = stats.chi2.ppf(1 - pv, df=1)
|
| 508 |
+
chi2_obs = chi2_obs[np.isfinite(chi2_obs) & (chi2_obs > 0)]
|
| 509 |
+
lam = (np.median(chi2_obs) / stats.chi2.ppf(0.5, df=1)
|
| 510 |
+
if len(chi2_obs) > 0 else 1.0)
|
| 511 |
+
lam_dict[mname] = lam
|
| 512 |
+
|
| 513 |
+
mcol = MODEL_COLORS.get(mname, ACCENT)
|
| 514 |
+
|
| 515 |
+
# colour dots by significance
|
| 516 |
+
colors_dot = np.where(obs_log >= bonf_log, RED_C, mcol)
|
| 517 |
+
ax.scatter(exp_log, obs_log, c=colors_dot, s=10,
|
| 518 |
+
alpha=0.65, linewidths=0, zorder=2)
|
| 519 |
+
|
| 520 |
+
maxv = max(obs_log.max(), exp_log.max()) * 1.08
|
| 521 |
+
ax.plot([0, maxv], [0, maxv], color='#374151',
|
| 522 |
+
lw=1.5, ls='--', zorder=3, label='Expected (y=x)')
|
| 523 |
+
|
| 524 |
+
# Bonferroni line
|
| 525 |
+
ax.axhline(bonf_log, color=RED_C, ls=':', lw=1.3, alpha=0.8,
|
| 526 |
+
label=f'Bonferroni ({bonf_log:.1f})')
|
| 527 |
+
|
| 528 |
+
# 95% confidence band
|
| 529 |
+
ci_up = -np.log10(stats.beta.ppf(0.025, np.arange(1,n+1),
|
| 530 |
+
np.arange(n,0,-1)) + 1e-300)
|
| 531 |
+
ci_lo = -np.log10(stats.beta.ppf(0.975, np.arange(1,n+1),
|
| 532 |
+
np.arange(n,0,-1)) + 1e-300)
|
| 533 |
+
ci_up = ci_up[::-1]; ci_lo = ci_lo[::-1]
|
| 534 |
+
ax.fill_between(exp_log, ci_lo, ci_up,
|
| 535 |
+
color=mcol, alpha=0.12, zorder=1,
|
| 536 |
+
label='95% CI')
|
| 537 |
+
|
| 538 |
+
ax.set_xlim(0, maxv); ax.set_ylim(0, maxv)
|
| 539 |
+
ax.set_xlabel('Expected βlogββ(P)', fontsize=10, fontweight='bold')
|
| 540 |
+
ax.set_ylabel('Observed βlogββ(P)', fontsize=10, fontweight='bold')
|
| 541 |
+
ax.set_title(f'{mname} QQ Plot', fontsize=11, fontweight='bold',
|
| 542 |
+
color=mcol)
|
| 543 |
+
ax.text(0.05, 0.92,
|
| 544 |
+
f'Ξ» = {lam:.3f}',
|
| 545 |
+
transform=ax.transAxes, fontsize=11, fontweight='bold',
|
| 546 |
+
color=mcol,
|
| 547 |
+
bbox=dict(boxstyle='round', facecolor=BG,
|
| 548 |
+
edgecolor=mcol, alpha=0.9, lw=1.2))
|
| 549 |
+
ax.legend(fontsize=7.5, loc='upper left')
|
| 550 |
+
ax.grid(True, color=GRID_C, lw=0.6)
|
| 551 |
+
|
| 552 |
+
# hide unused panels
|
| 553 |
+
for extra in range(n_models, nrows * ncols):
|
| 554 |
+
r, c = divmod(extra, ncols)
|
| 555 |
+
axes[r][c].set_visible(False)
|
| 556 |
+
|
| 557 |
+
plt.suptitle('QQ Plots β Multi-Model (Ξ» = genomic inflation factor)',
|
| 558 |
+
fontsize=13, fontweight='bold', color=TEXT_C)
|
| 559 |
+
plt.tight_layout(pad=1.5)
|
| 560 |
+
plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=BG)
|
| 561 |
+
plt.close(fig)
|
| 562 |
+
return lam_dict
|
| 563 |
+
|
| 564 |
+
|
| 565 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 566 |
+
# LD COMPUTATION (vectorised)
|
| 567 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 568 |
+
|
| 569 |
+
def _compute_ld_pairs_bp(G, bp_pos, max_lag=60):
|
| 570 |
+
"""
|
| 571 |
+
Return (dist_bp, r2, dp) for all lagged pairs.
|
| 572 |
+
bp_pos: physical positions in bp (integers).
|
| 573 |
"""
|
| 574 |
n = G.shape[1]
|
| 575 |
dists, r2s, dps = [], [], []
|
|
|
|
| 595 |
np.minimum(p1*p2, (1-p1)*(1-p2)))
|
| 596 |
dp = np.where(Dmax > 0, np.abs(D / Dmax), 0.0)
|
| 597 |
|
| 598 |
+
dist = np.abs(bp_pos[lag:] - bp_pos[:n - lag])
|
|
|
|
| 599 |
dists.append(dist); r2s.append(r2); dps.append(dp)
|
| 600 |
|
| 601 |
if not dists:
|
|
|
|
| 604 |
|
| 605 |
|
| 606 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 607 |
+
# PLOT: LD DECAY (bp-based scatter)
|
| 608 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 609 |
|
| 610 |
+
def plot_ld_decay_bp(genotypes, chromosomes, positions, save_path, max_m=120):
|
| 611 |
"""
|
| 612 |
+
LD decay scatter in bp:
|
| 613 |
+
- X-axis: physical distance in bp (shown as kb/Mb labels)
|
| 614 |
+
- Chromosome-coloured scatter dots
|
| 615 |
+
- Green filled cubic-spline median decay curve
|
| 616 |
+
- Annotated: half-decay, rΒ²=0.2, rΒ²=0.1 positions in kb or Mb
|
| 617 |
+
- Interpretation text panel below
|
|
|
|
|
|
|
| 618 |
"""
|
| 619 |
_style()
|
|
|
|
| 620 |
unique_chroms = sorted(set(chromosomes),
|
| 621 |
key=lambda x: (int(x) if str(x).isdigit() else 999, str(x)))
|
| 622 |
|
| 623 |
+
chrom_to_idx = {}
|
|
|
|
|
|
|
|
|
|
| 624 |
for gi, ch in enumerate(chromosomes):
|
| 625 |
+
chrom_to_idx.setdefault(str(ch), []).append(gi)
|
| 626 |
|
| 627 |
+
bp_arr_global = np.array(positions, dtype=float)
|
| 628 |
+
|
| 629 |
+
# If all positions are 0 or identical β extract from marker names
|
| 630 |
+
# (already handled by parser, but double-check)
|
| 631 |
+
if bp_arr_global.max() == 0:
|
| 632 |
+
bp_arr_global = np.arange(len(positions), dtype=float) * 1000
|
| 633 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 634 |
all_dist, all_r2, all_dp, all_ch = [], [], [], []
|
| 635 |
chrom_stats = {}
|
| 636 |
|
| 637 |
for ch in unique_chroms:
|
| 638 |
+
idxs = chrom_to_idx.get(str(ch), [])
|
| 639 |
if len(idxs) < 4:
|
| 640 |
continue
|
| 641 |
if len(idxs) > max_m:
|
| 642 |
idxs = sorted(np.random.choice(idxs, max_m, replace=False))
|
| 643 |
|
| 644 |
+
G_ch = genotypes[:, idxs].copy().astype(float)
|
| 645 |
+
bp_ch = bp_arr_global[idxs]
|
| 646 |
+
|
| 647 |
+
# Sort by position within chromosome
|
| 648 |
+
sort_order = np.argsort(bp_ch)
|
| 649 |
+
G_ch = G_ch[:, sort_order]
|
| 650 |
+
bp_ch = bp_ch[sort_order]
|
| 651 |
|
| 652 |
+
dist, r2, dp = _compute_ld_pairs_bp(G_ch, bp_ch, max_lag=60)
|
| 653 |
if len(dist) == 0:
|
| 654 |
continue
|
| 655 |
|
|
|
|
| 664 |
'mean_r2': float(np.mean(r2)),
|
| 665 |
'mean_dprime': float(np.mean(dp)),
|
| 666 |
'max_r2': float(np.max(r2)),
|
| 667 |
+
'max_dist_bp': float(dist.max()) if len(dist) else 0,
|
| 668 |
}
|
| 669 |
|
| 670 |
if not all_dist:
|
| 671 |
fig, ax = plt.subplots(figsize=(10, 6), facecolor=BG)
|
| 672 |
+
ax.text(0.5, 0.5, 'No LD data available\n(need β₯4 markers per chromosome)',
|
| 673 |
+
ha='center', va='center', transform=ax.transAxes,
|
| 674 |
+
fontsize=13, color=TEXT_C)
|
| 675 |
plt.savefig(save_path, dpi=120, bbox_inches='tight')
|
| 676 |
plt.close(fig)
|
| 677 |
return chrom_stats, "No LD data available."
|
|
|
|
| 680 |
r2_arr = np.array(all_r2, dtype=float)
|
| 681 |
ch_arr = np.array(all_ch, dtype=str)
|
| 682 |
|
| 683 |
+
# Determine display unit (bp / kb / Mb)
|
| 684 |
+
max_bp = float(np.percentile(dist_arr, 99))
|
| 685 |
+
if max_bp == 0:
|
| 686 |
+
max_bp = dist_arr.max()
|
| 687 |
+
|
| 688 |
+
if max_bp >= 1_000_000:
|
| 689 |
+
scale, unit_label = 1_000_000, 'Mb'
|
| 690 |
+
elif max_bp >= 1_000:
|
| 691 |
+
scale, unit_label = 1_000, 'kb'
|
| 692 |
+
else:
|
| 693 |
+
scale, unit_label = 1, 'bp'
|
| 694 |
|
| 695 |
+
dist_scaled = dist_arr / scale
|
| 696 |
+
max_scaled = max_bp / scale
|
| 697 |
|
| 698 |
+
# ββ binned median curve βββββββββββββββββββββββββββββββββββββββββββββββ
|
| 699 |
+
mask = dist_arr <= max_bp
|
| 700 |
+
dv = dist_scaled[mask]
|
| 701 |
+
rv = r2_arr[mask]
|
| 702 |
+
|
| 703 |
+
N_BINS = 80
|
| 704 |
+
bins = np.linspace(0, max_scaled, N_BINS + 1)
|
| 705 |
ctrs, meds = [], []
|
| 706 |
for i in range(N_BINS):
|
| 707 |
+
m = (dv >= bins[i]) & (dv < bins[i+1])
|
| 708 |
if m.sum() >= 3:
|
| 709 |
+
ctrs.append((bins[i] + bins[i+1]) / 2.0)
|
| 710 |
meds.append(np.median(rv[m]))
|
| 711 |
|
| 712 |
ctrs = np.array(ctrs, dtype=float)
|
| 713 |
meds = np.array(meds, dtype=float)
|
| 714 |
|
| 715 |
+
# ββ spline ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 716 |
+
ann = {}
|
| 717 |
+
xs_smooth = ys_smooth = None
|
| 718 |
if len(ctrs) >= 5:
|
| 719 |
+
k = min(3, len(ctrs) - 1)
|
| 720 |
+
xs_smooth = np.linspace(ctrs[0], ctrs[-1], 2000)
|
| 721 |
+
spl = make_interp_spline(ctrs, meds, k=k)
|
| 722 |
+
ys_smooth = np.clip(spl(xs_smooth), 0, 1)
|
| 723 |
+
|
| 724 |
+
r2_start = ys_smooth[0] if ys_smooth[0] > 0 else meds[0]
|
| 725 |
+
for thr_name, thr_val in [('half', r2_start / 2.0),
|
| 726 |
+
('r2_02', 0.20),
|
| 727 |
+
('r2_01', 0.10)]:
|
| 728 |
+
idx_cross = np.where(ys_smooth <= thr_val)[0]
|
| 729 |
if len(idx_cross):
|
| 730 |
+
ann[thr_name] = float(xs_smooth[idx_cross[0]])
|
| 731 |
+
|
| 732 |
+
# ββ LD interpretation βββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 733 |
+
overall_r2 = float(np.mean(r2_arr))
|
| 734 |
+
overall_dp = float(np.mean(all_dp))
|
| 735 |
+
n_pairs = len(dist_arr)
|
| 736 |
|
| 737 |
+
def _fmt_dist(v):
|
| 738 |
+
return f"{v:.2f} {unit_label}"
|
|
|
|
| 739 |
|
| 740 |
+
ilines = []
|
| 741 |
if 'half' in ann:
|
| 742 |
+
speed = ("rapid" if ann['half'] < (500/scale if scale==1 else 0.5)
|
| 743 |
+
else "moderate" if ann['half'] < (5000/scale if scale==1 else 5)
|
| 744 |
+
else "slow")
|
| 745 |
+
ilines += [
|
| 746 |
+
f"β’ LD half-decay (rΒ² β 50% of peak): {_fmt_dist(ann['half'])} [{speed} decay]",
|
| 747 |
]
|
| 748 |
else:
|
| 749 |
+
ilines += ["β’ Half-decay not reached β strong LD persists across entire range."]
|
| 750 |
|
| 751 |
if 'r2_02' in ann:
|
| 752 |
+
ilines += [f"β’ rΒ² drops below 0.2 (GWAS tagging threshold): {_fmt_dist(ann['r2_02'])}"]
|
| 753 |
+
ilines += [f" β Tag-SNPs spaced every {_fmt_dist(ann['r2_02'])} capture most variation."]
|
|
|
|
|
|
|
| 754 |
else:
|
| 755 |
+
ilines += ["β’ rΒ² stays above 0.2 throughout β very high LD / small genome window."]
|
| 756 |
|
| 757 |
if 'r2_01' in ann:
|
| 758 |
+
ilines += [f"β’ rΒ² drops below 0.1 (statistical independence): {_fmt_dist(ann['r2_01'])}"]
|
| 759 |
+
|
| 760 |
+
ilines += [
|
| 761 |
+
f"β’ Overall mean rΒ² = {overall_r2:.3f} | mean D' = {overall_dp:.3f}",
|
| 762 |
+
f"β’ Total pairs analysed: {n_pairs:,} | Chromosomes: {len(set(all_ch))}",
|
| 763 |
]
|
| 764 |
+
ld_interp = "\n".join(ilines)
|
| 765 |
|
| 766 |
+
# ββ FIGURE βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 767 |
chrom_color = {str(ch): CHROM_PALETTE[i % len(CHROM_PALETTE)]
|
| 768 |
for i, ch in enumerate(unique_chroms)}
|
| 769 |
|
| 770 |
+
fig = plt.figure(figsize=(14, 9), facecolor=BG)
|
| 771 |
+
gs = fig.add_gridspec(2, 1, height_ratios=[3.8, 1], hspace=0.08)
|
|
|
|
| 772 |
ax = fig.add_subplot(gs[0])
|
| 773 |
axt = fig.add_subplot(gs[1])
|
| 774 |
axt.axis('off')
|
|
|
|
| 775 |
ax.set_facecolor('#EEE8FA')
|
| 776 |
|
| 777 |
+
# scatter per chromosome
|
| 778 |
for ch in unique_chroms:
|
| 779 |
key = str(ch)
|
| 780 |
cmsk = (ch_arr == key) & mask
|
| 781 |
if not cmsk.any():
|
| 782 |
continue
|
| 783 |
+
ax.scatter(dist_scaled[cmsk], r2_arr[cmsk],
|
| 784 |
+
c=chrom_color[key], s=6, alpha=0.38,
|
| 785 |
linewidths=0, zorder=2, label=key)
|
| 786 |
|
| 787 |
+
# smooth decay curve + fill
|
| 788 |
+
if xs_smooth is not None and len(xs_smooth) > 0:
|
| 789 |
+
ax.fill_between(xs_smooth, 0, ys_smooth,
|
| 790 |
+
color='#22C55E', alpha=0.22, zorder=3)
|
| 791 |
+
ax.plot(xs_smooth, ys_smooth, color=GREEN_C,
|
| 792 |
+
linewidth=2.4, zorder=4, label='Median rΒ² decay')
|
| 793 |
|
| 794 |
+
# rΒ²=0.2 dashed reference
|
| 795 |
+
ax.axhline(0.2, color='#111827', ls='--', lw=1.6,
|
| 796 |
+
alpha=0.75, zorder=5, label='rΒ² = 0.2')
|
| 797 |
|
| 798 |
+
# annotation vertical lines
|
| 799 |
ann_styles = {
|
| 800 |
+
'half': (GOLD_C, f'Β½ decay', 0.50, 0.10),
|
| 801 |
+
'r2_02': (RED_C, f'rΒ²=0.2', 0.20, 0.08),
|
| 802 |
+
'r2_01': (TEAL_C, f'rΒ²=0.1', 0.10, 0.06),
|
| 803 |
}
|
| 804 |
+
for akey, (col, lbl, r2ref, offset_y) in ann_styles.items():
|
| 805 |
+
if akey in ann:
|
| 806 |
+
xv = ann[akey]
|
| 807 |
+
ax.axvline(xv, color=col, ls=':', lw=1.9, alpha=0.88, zorder=6)
|
| 808 |
ax.annotate(
|
| 809 |
+
f'{lbl}\n{_fmt_dist(xv)}',
|
| 810 |
+
xy=(xv, r2ref),
|
| 811 |
+
xytext=(xv + max_scaled * 0.012, r2ref + offset_y),
|
| 812 |
fontsize=8.5, fontweight='bold', color=col,
|
| 813 |
arrowprops=dict(arrowstyle='->', color=col, lw=1.2),
|
| 814 |
+
bbox=dict(boxstyle='round,pad=0.3', fc=BG,
|
| 815 |
+
ec=col, alpha=0.92, lw=1.1),
|
| 816 |
zorder=7,
|
| 817 |
)
|
| 818 |
|
| 819 |
+
# axes
|
| 820 |
+
ax.set_xlim(0, max_scaled)
|
| 821 |
ax.set_ylim(0, 1.05)
|
| 822 |
+
ax.set_xlabel(f'Physical distance ({unit_label})',
|
| 823 |
+
fontsize=12, fontweight='bold', color=TEXT_C, labelpad=6)
|
| 824 |
+
ax.set_ylabel('LD estimate (RΒ²)',
|
| 825 |
+
fontsize=12, fontweight='bold', color=TEXT_C, labelpad=6)
|
| 826 |
+
ax.set_title('LD Decay by Chromosome (Physical Distance)',
|
| 827 |
+
fontsize=14, fontweight='bold', color=TEXT_C, pad=10)
|
| 828 |
ax.xaxis.grid(True, color=GRID_C, lw=0.6, alpha=0.9)
|
| 829 |
ax.yaxis.grid(True, color=GRID_C, lw=0.6, alpha=0.9)
|
| 830 |
ax.set_axisbelow(True)
|
| 831 |
|
| 832 |
+
# legend
|
| 833 |
handles, labels = ax.get_legend_handles_labels()
|
| 834 |
special = [(h, l) for h, l in zip(handles, labels)
|
| 835 |
if l in ('Median rΒ² decay', 'rΒ² = 0.2')]
|
|
|
|
| 837 |
if l not in ('Median rΒ² decay', 'rΒ² = 0.2')]
|
| 838 |
leg_h = [h for h, _ in special] + [h for h, _ in chrs]
|
| 839 |
leg_l = [l for _, l in special] + [f'Chr {l}' for _, l in chrs]
|
| 840 |
+
ncols = max(1, (len(chrs) + 9) // 10)
|
| 841 |
+
legend = ax.legend(leg_h, leg_l, title='Chr', title_fontsize=9,
|
| 842 |
+
fontsize=7.5, loc='upper right', ncol=ncols,
|
| 843 |
+
framealpha=0.93, edgecolor=GRID_C,
|
| 844 |
+
markerscale=2.2, handlelength=1.3,
|
| 845 |
+
borderpad=0.7, labelspacing=0.4)
|
|
|
|
| 846 |
legend.get_title().set_fontweight('bold')
|
| 847 |
|
| 848 |
+
# interpretation text panel
|
| 849 |
+
interp_text = ("LD DECAY INTERPRETATION\n"
|
| 850 |
+
+ "β" * 78 + "\n"
|
| 851 |
+
+ ld_interp)
|
| 852 |
+
axt.text(0.005, 0.98, interp_text,
|
| 853 |
+
transform=axt.transAxes, va='top', ha='left',
|
| 854 |
+
fontsize=8.5, color=TEXT_C, fontfamily='monospace',
|
|
|
|
|
|
|
|
|
|
|
|
|
| 855 |
bbox=dict(boxstyle='round,pad=0.5',
|
| 856 |
facecolor='#EDE9FE', edgecolor=GRID_C,
|
| 857 |
alpha=0.95))
|
| 858 |
|
| 859 |
plt.savefig(save_path, dpi=130, bbox_inches='tight', facecolor=BG)
|
| 860 |
plt.close(fig)
|
| 861 |
+
return chrom_stats, ld_interp
|
|
|
|
| 862 |
|
| 863 |
|
| 864 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 865 |
+
# PLOT: MODEL COMPARISON
|
| 866 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 867 |
|
| 868 |
+
def plot_model_comparison(model_pvals, save_path):
|
|
|
|
| 869 |
_style()
|
| 870 |
+
models = list(model_pvals.keys())
|
| 871 |
+
n = len(models)
|
| 872 |
+
ncols = min(3, n*(n-1)//2 if n > 1 else 1)
|
| 873 |
+
pairs = [(models[i], models[j])
|
| 874 |
+
for i in range(n) for j in range(i+1, n)]
|
| 875 |
+
nrows = (len(pairs) + ncols - 1) // ncols
|
| 876 |
+
if not pairs:
|
| 877 |
+
return
|
| 878 |
+
|
| 879 |
+
fig, axes = plt.subplots(nrows, ncols,
|
| 880 |
+
figsize=(5.5*ncols, 5*nrows),
|
| 881 |
+
facecolor=BG, squeeze=False)
|
| 882 |
+
|
| 883 |
+
for idx, (ma, mb) in enumerate(pairs):
|
| 884 |
+
r, c = divmod(idx, ncols)
|
| 885 |
+
ax = axes[r][c]
|
| 886 |
+
ax.set_facecolor(PANEL)
|
| 887 |
+
pa = -np.log10(np.clip(model_pvals[ma], 1e-300, 1))
|
| 888 |
+
pb = -np.log10(np.clip(model_pvals[mb], 1e-300, 1))
|
| 889 |
+
corr = np.corrcoef(pa, pb)[0, 1]
|
| 890 |
+
ax.scatter(pa, pb, alpha=0.40, s=12,
|
| 891 |
+
color=MODEL_COLORS.get(ma, ACCENT),
|
| 892 |
+
edgecolors='none')
|
| 893 |
+
mx = max(pa.max(), pb.max()) * 1.05
|
| 894 |
+
ax.plot([0, mx], [0, mx], color=GOLD_C, ls='--', lw=1.2)
|
| 895 |
+
ax.set_xlabel(f'{ma} βlogββ(P)', fontsize=9, fontweight='bold')
|
| 896 |
+
ax.set_ylabel(f'{mb} βlogββ(P)', fontsize=9, fontweight='bold')
|
| 897 |
+
ax.set_title(f'{ma} vs {mb} (r={corr:.3f})',
|
| 898 |
+
fontsize=10, fontweight='bold')
|
| 899 |
+
ax.grid(True, color=GRID_C, lw=0.6, alpha=0.5)
|
| 900 |
+
|
| 901 |
+
for extra in range(len(pairs), nrows * ncols):
|
| 902 |
+
r, c = divmod(extra, ncols)
|
| 903 |
+
axes[r][c].set_visible(False)
|
| 904 |
+
|
| 905 |
+
plt.suptitle('Model P-value Concordance (βlogββ scale)',
|
| 906 |
+
fontsize=12, fontweight='bold', color=TEXT_C)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 907 |
plt.tight_layout(pad=1.5)
|
| 908 |
plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=BG)
|
| 909 |
plt.close(fig)
|
| 910 |
|
| 911 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 912 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 913 |
# PLOT: PHENOTYPE DISTRIBUTION
|
| 914 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 915 |
|
| 916 |
+
def plot_phenotype(phenotypes, save_path):
|
| 917 |
_style()
|
| 918 |
pv = phenotypes[~np.isnan(phenotypes)]
|
| 919 |
fig, axes = plt.subplots(1, 2, figsize=(11, 4.5), facecolor=BG)
|
| 920 |
|
| 921 |
+
ax = axes[0]; ax.set_facecolor(PANEL)
|
| 922 |
+
ax.hist(pv, bins=30, color=ACCENT, alpha=0.72, edgecolor='white', lw=0.5)
|
| 923 |
+
ax.axvline(np.mean(pv), color=RED_C, ls='--', lw=1.6,
|
|
|
|
|
|
|
| 924 |
label=f'Mean={np.mean(pv):.2f}')
|
| 925 |
+
ax.axvline(np.median(pv), color=GOLD_C, ls=':', lw=1.6,
|
| 926 |
label=f'Median={np.median(pv):.2f}')
|
| 927 |
ax.set_xlabel('Phenotype Value', fontsize=11, fontweight='bold')
|
| 928 |
+
ax.set_ylabel('Frequency', fontsize=11, fontweight='bold')
|
| 929 |
ax.set_title('Phenotype Distribution', fontsize=12, fontweight='bold')
|
| 930 |
ax.legend(fontsize=9)
|
| 931 |
ax.grid(True, color=GRID_C, lw=0.7)
|
| 932 |
+
sw_s, sw_p = stats.shapiro(pv[:5000])
|
| 933 |
+
ax.text(0.97, 0.95, f'Shapiro-Wilk p={sw_p:.3e}',
|
| 934 |
+
transform=ax.transAxes, ha='right', va='top', fontsize=8.5,
|
| 935 |
+
bbox=dict(boxstyle='round', facecolor=BG,
|
| 936 |
+
edgecolor=GRID_C, alpha=0.9))
|
| 937 |
|
| 938 |
+
ax = axes[1]; ax.set_facecolor(PANEL)
|
|
|
|
| 939 |
stats.probplot(pv, dist='norm', plot=ax)
|
| 940 |
ax.get_lines()[0].set(color=ACCENT, markersize=3, alpha=0.6)
|
| 941 |
+
ax.get_lines()[1].set(color=RED_C, lw=1.5)
|
| 942 |
+
ax.set_title('Normal Q-Q (Phenotype)', fontsize=12, fontweight='bold')
|
| 943 |
ax.grid(True, color=GRID_C, lw=0.7)
|
| 944 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 945 |
plt.tight_layout(pad=1.5)
|
| 946 |
plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=BG)
|
| 947 |
plt.close(fig)
|
| 948 |
|
| 949 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 950 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 951 |
# MAIN ANALYSIS
|
| 952 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 953 |
|
| 954 |
+
def run_analysis(input_file, miss_sample, miss_marker, maf_thresh,
|
| 955 |
+
run_glm, run_mlm, run_cmlm, run_bslmm, run_farmcpu):
|
| 956 |
try:
|
| 957 |
if input_file is None:
|
| 958 |
+
return ("β οΈ Upload a CSV file first.",
|
| 959 |
None, None, None, None, None, None)
|
| 960 |
|
| 961 |
tmp = tempfile.mkdtemp()
|
|
|
|
| 963 |
pdir = os.path.join(rdir, 'plots')
|
| 964 |
for d in [rdir, pdir]: os.makedirs(d, exist_ok=True)
|
| 965 |
|
| 966 |
+
ms_t = miss_sample / 100.0
|
| 967 |
+
mm_t = miss_marker / 100.0
|
| 968 |
+
mf_t = maf_thresh / 100.0
|
| 969 |
|
| 970 |
+
# ββ Parse ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 971 |
print("[Parse] Reading CSVβ¦")
|
| 972 |
(sids, pheno, geno,
|
| 973 |
+
mnames, chroms, positions) = parse_input_csv(input_file)
|
|
|
|
| 974 |
n_s, n_m = len(sids), len(mnames)
|
| 975 |
print(f"[Parse] {n_s} samples Γ {n_m} markers")
|
| 976 |
|
| 977 |
# ββ QC βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 978 |
+
miss_m_r = np.isnan(geno).sum(0) / max(n_s, 1)
|
| 979 |
+
miss_s_r = np.isnan(geno).sum(1) / max(n_m, 1)
|
| 980 |
+
maf_arr = np.zeros(n_m)
|
|
|
|
| 981 |
for i in range(n_m):
|
| 982 |
v = geno[:, i]; v = v[~np.isnan(v)]
|
| 983 |
if len(v):
|
| 984 |
f = np.mean(v) / 2.0
|
| 985 |
+
maf_arr[i] = min(f, 1 - f)
|
| 986 |
|
| 987 |
+
qc_m = (miss_m_r < mm_t) & (maf_arr >= mf_t)
|
| 988 |
+
qc_s = miss_s_r < ms_t
|
| 989 |
fallback = ""
|
|
|
|
| 990 |
for rs, rm in [(ms_t, mm_t),
|
| 991 |
(.6,.6),(.7,.7),(.8,.8),(.9,.9),(1.,1.)]:
|
| 992 |
+
qm = (miss_m_r < rm) & (maf_arr >= mf_t)
|
| 993 |
+
qs = miss_s_r < rs
|
| 994 |
if qs.sum() >= 10:
|
| 995 |
qc_m, qc_s = qm, qs
|
| 996 |
if rs > ms_t or rm > mm_t:
|
| 997 |
+
fallback = (f"\nβ οΈ QC relaxed β sample<{rs*100:.0f}%"
|
| 998 |
+
f" / marker<{rm*100:.0f}%\n")
|
| 999 |
break
|
| 1000 |
|
| 1001 |
geno_q = geno[np.ix_(qc_s, qc_m)].copy()
|
| 1002 |
pheno_q = pheno[qc_s]
|
| 1003 |
sids_q = sids[qc_s]
|
| 1004 |
+
mn_q = [mnames[i] for i in range(n_m) if qc_m[i]]
|
| 1005 |
+
ch_q = [chroms[i] for i in range(n_m) if qc_m[i]]
|
| 1006 |
+
pos_q = [positions[i] for i in range(n_m) if qc_m[i]]
|
| 1007 |
n_q = len(mn_q)
|
|
|
|
| 1008 |
print(f"[QC] {len(sids_q)} samples Γ {n_q} markers")
|
| 1009 |
|
| 1010 |
+
# Impute missing genotypes with column mean
|
| 1011 |
col_mu = np.nanmean(geno_q, 0)
|
| 1012 |
col_mu = np.where(np.isnan(col_mu), 0, col_mu)
|
| 1013 |
for i in range(geno_q.shape[1]):
|
|
|
|
| 1015 |
if mk.any(): geno_q[mk, i] = col_mu[i]
|
| 1016 |
|
| 1017 |
valid = ~np.isnan(pheno_q)
|
| 1018 |
+
geno_q = geno_q[valid]; pheno_q = pheno_q[valid]; sids_q = sids_q[valid]
|
|
|
|
| 1019 |
|
| 1020 |
if len(sids_q) < 10:
|
| 1021 |
return (f"## β οΈ Only {len(sids_q)} samples passed QC. "
|
| 1022 |
+
"Try increasing missing-rate sliders.",
|
| 1023 |
None, None, None, None, None, None)
|
| 1024 |
|
| 1025 |
+
bonf = 0.05 / n_q
|
| 1026 |
bonf_log = -np.log10(bonf)
|
| 1027 |
|
| 1028 |
+
# ββ Kinship (needed for MLM, CMLM, FarmCPU) ββββββββββββββββββββββββββ
|
| 1029 |
+
print("[Kinship] Computing K matrixβ¦")
|
| 1030 |
+
K = compute_kinship(geno_q)
|
| 1031 |
+
|
| 1032 |
+
# ββ Run selected models βββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1033 |
+
model_pvals = {}
|
| 1034 |
+
model_betas = {}
|
| 1035 |
+
model_ses = {}
|
| 1036 |
+
|
| 1037 |
+
if run_glm:
|
| 1038 |
+
print("[Model 1/5] GLMβ¦")
|
| 1039 |
+
pv, bv, sv, rv = model_glm(geno_q, pheno_q)
|
| 1040 |
+
model_pvals['GLM'] = pv; model_betas['GLM'] = bv; model_ses['GLM'] = sv
|
| 1041 |
+
|
| 1042 |
+
if run_mlm:
|
| 1043 |
+
print("[Model 2/5] MLMβ¦")
|
| 1044 |
+
pv, bv, sv, rv = model_mlm(geno_q, pheno_q, K)
|
| 1045 |
+
model_pvals['MLM'] = pv; model_betas['MLM'] = bv; model_ses['MLM'] = sv
|
| 1046 |
+
|
| 1047 |
+
if run_cmlm:
|
| 1048 |
+
print("[Model 3/5] CMLMβ¦")
|
| 1049 |
+
pv, bv, sv, rv = model_cmlm(geno_q, pheno_q, K)
|
| 1050 |
+
model_pvals['CMLM'] = pv; model_betas['CMLM'] = bv; model_ses['CMLM'] = sv
|
| 1051 |
+
|
| 1052 |
+
if run_bslmm:
|
| 1053 |
+
print("[Model 4/5] BSLMMβ¦")
|
| 1054 |
+
pv, bv = model_bslmm(geno_q, pheno_q)
|
| 1055 |
+
model_pvals['BSLMM'] = pv; model_betas['BSLMM'] = bv
|
| 1056 |
+
|
| 1057 |
+
if run_farmcpu:
|
| 1058 |
+
print("[Model 5/5] FarmCPUβ¦")
|
| 1059 |
+
pv, bv, sv = model_farmcpu(geno_q, pheno_q, K)
|
| 1060 |
+
model_pvals['FarmCPU'] = pv; model_betas['FarmCPU'] = bv; model_ses['FarmCPU'] = sv
|
| 1061 |
+
|
| 1062 |
+
if not model_pvals:
|
| 1063 |
+
return ("## β οΈ No models selected. Please enable at least one.",
|
| 1064 |
+
None, None, None, None, None, None)
|
| 1065 |
|
| 1066 |
+
# ββ Build results CSV βββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1067 |
+
df = pd.DataFrame({'Marker': mn_q, 'Chromosome': ch_q,
|
| 1068 |
+
'Position_bp': pos_q})
|
| 1069 |
+
for mname, pv in model_pvals.items():
|
| 1070 |
+
df[f'{mname}_P'] = pv
|
| 1071 |
+
df[f'{mname}_LOD'] = -np.log10(np.clip(pv, 1e-300, 1))
|
| 1072 |
+
df[f'{mname}_Sig'] = (pv < bonf).astype(int)
|
| 1073 |
+
if mname in model_betas:
|
| 1074 |
+
df[f'{mname}_Beta'] = model_betas[mname]
|
| 1075 |
+
|
| 1076 |
+
# Consensus: significant in β₯ half of run models
|
| 1077 |
+
sig_cols = [f'{m}_Sig' for m in model_pvals]
|
| 1078 |
+
df['Consensus_Sig'] = (df[sig_cols].sum(1) >= max(1, len(sig_cols)//2)).astype(int)
|
| 1079 |
+
df = df.sort_values(f"{list(model_pvals.keys())[0]}_P").reset_index(drop=True)
|
| 1080 |
+
df.insert(0, 'Rank', range(1, len(df)+1))
|
| 1081 |
df.to_csv(os.path.join(rdir, 'gwas_results.csv'), index=False)
|
| 1082 |
|
| 1083 |
+
# Significant only (any model)
|
| 1084 |
+
any_sig = df[sig_cols].sum(1) > 0
|
| 1085 |
+
df[any_sig].to_csv(os.path.join(rdir, 'top_significant.csv'), index=False)
|
| 1086 |
|
| 1087 |
# ββ Plots βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1088 |
print("[Plot 1/5] Phenotype distributionβ¦")
|
| 1089 |
ph_path = os.path.join(pdir, 'phenotype_dist.png')
|
| 1090 |
+
plot_phenotype(pheno_q, ph_path)
|
| 1091 |
|
| 1092 |
+
print("[Plot 2/5] Manhattan (multi-model)β¦")
|
| 1093 |
man_path = os.path.join(pdir, 'manhattan_lod.png')
|
| 1094 |
+
plot_manhattan_multi(mn_q, ch_q, model_pvals, bonf, man_path)
|
|
|
|
|
|
|
|
|
|
| 1095 |
|
| 1096 |
+
print("[Plot 3/5] QQ plotsβ¦")
|
| 1097 |
qq_path = os.path.join(pdir, 'qq_plot.png')
|
| 1098 |
+
lam_dict = plot_qq_multi(model_pvals, bonf, qq_path)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1099 |
|
| 1100 |
+
print("[Plot 4/5] LD decay (bp)β¦")
|
| 1101 |
+
ld_path = os.path.join(pdir, 'ld_decay_bp.png')
|
| 1102 |
+
ld_stats, ld_interp = plot_ld_decay_bp(geno_q, ch_q, pos_q, ld_path)
|
| 1103 |
+
ld_df = pd.DataFrame([{'Chromosome': k, **v} for k, v in ld_stats.items()])
|
| 1104 |
ld_df.to_csv(os.path.join(rdir, 'ld_decay_stats.csv'), index=False)
|
| 1105 |
|
| 1106 |
print("[Plot 5/5] Model comparisonβ¦")
|
| 1107 |
cmp_path = os.path.join(pdir, 'model_comparison.png')
|
| 1108 |
+
plot_model_comparison(model_pvals, cmp_path)
|
| 1109 |
|
| 1110 |
# ββ ZIP βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1111 |
zip_path = os.path.join(tmp, 'GWAS_Results.zip')
|
|
|
|
| 1115 |
fp = os.path.join(root, f)
|
| 1116 |
zf.write(fp, os.path.relpath(fp, tmp))
|
| 1117 |
|
| 1118 |
+
# ββ Summary βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1119 |
+
def _mdt(d, n=15):
|
| 1120 |
+
sub = d.head(n)
|
| 1121 |
+
cols = sub.columns.tolist()
|
| 1122 |
def _f(v):
|
| 1123 |
if isinstance(v, float):
|
| 1124 |
+
return f"{v:.3e}" if (v!=0 and abs(v)<0.001) else f"{v:.4f}"
|
| 1125 |
return str(v)
|
| 1126 |
sep = "| " + " | ".join(["---"]*len(cols)) + " |"
|
| 1127 |
rows = ["| "+" | ".join(_f(row[c]) for c in cols)+" |"
|
| 1128 |
+
for _, row in sub.iterrows()]
|
| 1129 |
return "\n".join(["| "+" | ".join(cols)+" |", sep]+rows)
|
| 1130 |
|
| 1131 |
+
model_summary_rows = "\n".join(
|
| 1132 |
+
f"| {m} | **{int((pv < bonf).sum())}** | Ξ»={lam_dict.get(m,0):.3f} | "
|
| 1133 |
+
f"{'β οΈ inflation' if lam_dict.get(m,1)>1.05 else 'β
ok'} |"
|
| 1134 |
+
for m, pv in model_pvals.items()
|
| 1135 |
+
)
|
| 1136 |
+
|
| 1137 |
+
top_cols = (['Rank','Marker','Chromosome','Position_bp'] +
|
| 1138 |
+
[f'{m}_P' for m in model_pvals] +
|
| 1139 |
+
['Consensus_Sig'])
|
| 1140 |
+
top_cols = [c for c in top_cols if c in df.columns]
|
| 1141 |
|
| 1142 |
summary = f"""
|
| 1143 |
+
## β
GWAS Analysis Complete β v8.0
|
| 1144 |
|
| 1145 |
### π QC Summary
|
| 1146 |
| Metric | Value |
|
| 1147 |
+
|---|---|
|
| 1148 |
| Samples (raw β QC) | {n_s} β **{len(sids_q)}** |
|
| 1149 |
| Markers (raw β QC) | {n_m} β **{n_q}** |
|
| 1150 |
| Chromosomes | **{len(set(ch_q))}** |
|
| 1151 |
+
| MAF β₯ | {maf_thresh:.1f}% |
|
| 1152 |
+
| Sample missing < | {miss_sample:.0f}% |
|
| 1153 |
+
| Marker missing < | {miss_marker:.0f}% |
|
| 1154 |
{fallback}
|
| 1155 |
|
| 1156 |
+
### π¬ Model Results
|
| 1157 |
+
| Model | Sig. Markers (Bonferroni) | Ξ» | Status |
|
| 1158 |
+
|---|---|---|---|
|
| 1159 |
+
{model_summary_rows}
|
|
|
|
|
|
|
| 1160 |
|
| 1161 |
+
**Bonferroni threshold:** P < {bonf:.3e} | βlogββP > {bonf_log:.2f}
|
| 1162 |
|
| 1163 |
+
### 𧬠LD Decay (Physical Distance)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1164 |
{ld_interp}
|
| 1165 |
|
| 1166 |
+
### π Top 15 Markers
|
| 1167 |
+
{_mdt(df[top_cols])}
|
| 1168 |
|
| 1169 |
---
|
| 1170 |
**Output files:**
|
| 1171 |
+
- `gwas_results.csv` β all markers, all model statistics
|
| 1172 |
+
- `top_significant.csv` β any-model Bonferroni-significant markers
|
| 1173 |
- `ld_decay_stats.csv` β per-chromosome LD statistics
|
| 1174 |
+
- `manhattan_lod.png` β per-model Manhattan plots
|
| 1175 |
+
- `qq_plot.png` β QQ + Ξ» for each model
|
| 1176 |
+
- `ld_decay_bp.png` β LD decay scatter (bp/kb/Mb) with annotations
|
| 1177 |
+
- `model_comparison.png` β pairwise model concordance
|
| 1178 |
+
- `phenotype_dist.png` β phenotype distribution & normality
|
| 1179 |
"""
|
| 1180 |
print("[Done] β
")
|
| 1181 |
return (summary, man_path, ld_path, qq_path,
|
|
|
|
| 1196 |
h1{color:#2D1B5E;border-bottom:3px solid #7C3AED;padding-bottom:8px}
|
| 1197 |
"""
|
| 1198 |
|
| 1199 |
+
with gr.Blocks(css=CSS, title="MTA GWAS v8.0") as app:
|
| 1200 |
|
| 1201 |
gr.Markdown("""
|
| 1202 |
+
# 𧬠GWAS Analysis Platform v8.0
|
| 1203 |
+
### 5-Model MRmlm Suite | LD Decay in bp | Fixed QQ Plot | Complete Outputs
|
|
|
|
| 1204 |
---
|
| 1205 |
""")
|
| 1206 |
|
| 1207 |
with gr.Row():
|
| 1208 |
with gr.Column(scale=1):
|
| 1209 |
gr.Markdown("""
|
| 1210 |
+
### π CSV Format (3-row header)
|
| 1211 |
```
|
| 1212 |
+
ID, Phenotype, M1_bp_gene, M2_bp_gene, ...
|
| 1213 |
+
-, Chr, 1, 1, ... β chromosome
|
| 1214 |
+
-, Pos, 134521, 134810, ... β bp position
|
| 1215 |
+
IRRI-1, 25.34, 0, 2, ...
|
| 1216 |
+
IRRI-75, 23.34, 0, 0, ...
|
| 1217 |
```
|
| 1218 |
+
**Genotypes:** 0/1/2 (β1 or blank = missing)
|
| 1219 |
""")
|
| 1220 |
input_file = gr.File(label="π Upload CSV", file_types=[".csv"])
|
| 1221 |
|
|
|
|
| 1227 |
label="Max marker missing rate (%)")
|
| 1228 |
maf_thr = gr.Slider(0, 25, value=3, step=1,
|
| 1229 |
label="Min MAF (%)")
|
| 1230 |
+
|
| 1231 |
+
with gr.Column(scale=1):
|
| 1232 |
+
gr.Markdown("### π¬ Select Models")
|
| 1233 |
+
chk_glm = gr.Checkbox(value=True, label="GLM β General Linear Model")
|
| 1234 |
+
chk_mlm = gr.Checkbox(value=True, label="MLM β Mixed Linear Model")
|
| 1235 |
+
chk_cmlm = gr.Checkbox(value=True, label="CMLM β Compressed MLM")
|
| 1236 |
+
chk_bslmm = gr.Checkbox(value=True, label="BSLMM β Bayesian Sparse LMM")
|
| 1237 |
+
chk_farmcpu = gr.Checkbox(value=True, label="FarmCPU β Fixed & Random")
|
|
|
|
| 1238 |
|
| 1239 |
run_btn = gr.Button("π Run GWAS Analysis", variant="primary", size="lg")
|
| 1240 |
gr.Markdown("---")
|
|
|
|
| 1242 |
summary_out = gr.Markdown()
|
| 1243 |
|
| 1244 |
with gr.Row():
|
| 1245 |
+
man_out = gr.Image(label="πΊοΈ Manhattan Plots (all models)")
|
| 1246 |
+
ld_out = gr.Image(label="𧬠LD Decay β bp / kb / Mb (annotated)")
|
| 1247 |
|
| 1248 |
with gr.Row():
|
| 1249 |
+
qq_out = gr.Image(label="π QQ Plots + Ξ» (all models)")
|
| 1250 |
+
cmp_out = gr.Image(label="βοΈ Model Concordance")
|
| 1251 |
|
| 1252 |
with gr.Row():
|
| 1253 |
ph_out = gr.Image(label="π Phenotype Distribution")
|
|
|
|
| 1255 |
|
| 1256 |
gr.Markdown("""
|
| 1257 |
---
|
| 1258 |
+
**MTA GWAS v8.0** | GLM Β· MLM Β· CMLM Β· BSLMM Β· FarmCPU | bp LD decay | Correct QQ
|
| 1259 |
""")
|
| 1260 |
|
| 1261 |
run_btn.click(
|
| 1262 |
+
fn=run_analysis,
|
| 1263 |
+
inputs=[input_file, miss_sample, miss_marker, maf_thr,
|
| 1264 |
+
chk_glm, chk_mlm, chk_cmlm, chk_bslmm, chk_farmcpu],
|
| 1265 |
outputs=[summary_out, man_out, ld_out, qq_out,
|
| 1266 |
cmp_out, ph_out, dl_out],
|
| 1267 |
show_progress=True,
|