Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,33 +1,13 @@
|
|
| 1 |
# -*- coding: utf-8 -*-
|
| 2 |
"""
|
| 3 |
-
MTA Analysis Tool v8.
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 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 |
|
| 33 |
import gradio as gr
|
|
@@ -38,12 +18,16 @@ 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,
|
| 42 |
-
from
|
|
|
|
| 43 |
from sklearn.preprocessing import StandardScaler
|
| 44 |
-
from sklearn.decomposition import PCA
|
| 45 |
warnings.filterwarnings('ignore')
|
| 46 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 48 |
# THEME
|
| 49 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
|
@@ -56,8 +40,6 @@ 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",
|
|
@@ -82,51 +64,39 @@ def _style():
|
|
| 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':
|
| 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
|
| 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 |
-
|
| 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 |
-
|
| 123 |
-
name_parts = m.split('_')
|
| 124 |
bp = 0.0
|
| 125 |
-
for part in
|
| 126 |
try:
|
| 127 |
-
|
| 128 |
-
if
|
| 129 |
-
break
|
| 130 |
except ValueError:
|
| 131 |
continue
|
| 132 |
pos_dict[m] = bp
|
|
@@ -134,54 +104,39 @@ def parse_input_csv(filepath):
|
|
| 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 |
-
|
| 139 |
-
|
| 140 |
-
|
| 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
|
| 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 |
-
|
| 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
|
| 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);
|
| 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
|
|
@@ -192,32 +147,22 @@ def model_glm(G, y):
|
|
| 192 |
|
| 193 |
|
| 194 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 195 |
-
# MODEL 2: MLM
|
| 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]]
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
Qy = Q @ np.linalg.lstsq(Q, y, rcond=None)[0]
|
| 212 |
-
y_r = y - Qy
|
| 213 |
|
| 214 |
-
m
|
| 215 |
-
pv = np.ones(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
|
|
@@ -228,42 +173,30 @@ def model_mlm(G, y, K):
|
|
| 228 |
|
| 229 |
|
| 230 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 231 |
-
# MODEL 3: CMLM
|
| 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 |
-
|
| 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
|
| 265 |
-
pv = np.ones(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
|
|
@@ -277,36 +210,52 @@ def model_cmlm(G, y, K, n_groups=None):
|
|
| 277 |
|
| 278 |
|
| 279 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 280 |
-
# MODEL 4: BSLMM
|
| 281 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 282 |
-
|
| 283 |
-
def model_bslmm(G, y, n_boot=20):
|
| 284 |
"""
|
| 285 |
-
|
| 286 |
-
|
|
|
|
|
|
|
| 287 |
"""
|
| 288 |
sc = StandardScaler()
|
| 289 |
Xs = sc.fit_transform(G)
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 294 |
|
| 295 |
boots = []
|
| 296 |
rng = np.random.default_rng(42)
|
| 297 |
for _ in range(n_boot):
|
| 298 |
-
idx = rng.integers(0,
|
| 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(
|
| 309 |
-
for i in range(
|
| 310 |
sd = boot_arr[:, i].std()
|
| 311 |
if sd > 0:
|
| 312 |
z = abs(coef[i]) / (sd + 1e-12)
|
|
@@ -315,70 +264,50 @@ def model_bslmm(G, y, n_boot=20):
|
|
| 315 |
|
| 316 |
|
| 317 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 318 |
-
# MODEL 5: FarmCPU
|
| 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 |
-
|
| 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 |
-
#
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 353 |
for i in range(m):
|
| 354 |
-
x =
|
| 355 |
if x.std() < 1e-9: continue
|
| 356 |
-
|
| 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 |
-
|
| 368 |
-
pv_cur = pv_new.copy()
|
| 369 |
|
| 370 |
return pv_cur, bv_new, sv_new
|
| 371 |
|
| 372 |
|
| 373 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 374 |
-
# PLOT: MANHATTAN
|
| 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)))
|
|
@@ -400,202 +329,157 @@ def plot_manhattan_multi(mn, chroms, model_pvals, bonf_thresh, save_path):
|
|
| 400 |
offset += len(idxs) + GAP
|
| 401 |
|
| 402 |
fig, axes = plt.subplots(n_models, 1,
|
| 403 |
-
figsize=(18, 3.2
|
| 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
|
| 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]]
|
| 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 |
-
|
| 428 |
if sel:
|
| 429 |
-
ax.scatter(x_pos[sel], log_p[sel],
|
| 430 |
-
|
| 431 |
-
ax.scatter(x_pos[sel], log_p[sel],
|
| 432 |
-
|
| 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(
|
| 439 |
label='Suggestive (3)')
|
| 440 |
ax.set_xlim(-GAP, offset)
|
| 441 |
-
ax.set_ylim(0, max(log_p.max()
|
| 442 |
ax.set_ylabel('βlogββ(P)', fontsize=10, fontweight='bold')
|
| 443 |
ax.set_title(f'Model: {mname}', fontsize=11, fontweight='bold',
|
| 444 |
-
color=
|
| 445 |
ax.yaxis.grid(True, color=GRID_C, lw=0.6)
|
| 446 |
-
ax.legend(loc='upper right', fontsize=7.5
|
| 447 |
-
|
| 448 |
-
# count sig
|
| 449 |
n_sig = int((pv < bonf_thresh).sum())
|
| 450 |
-
ax.text(0.01, 0.92, f'{n_sig} significant',
|
| 451 |
-
fontsize=8, color=RED_C,
|
|
|
|
| 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=
|
| 461 |
plt.close(fig)
|
| 462 |
|
| 463 |
|
| 464 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 465 |
-
# PLOT: QQ
|
| 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
|
| 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)
|
| 494 |
ax.text(0.5, 0.5, 'No valid p-values',
|
| 495 |
-
ha='center', va='center', transform=ax.transAxes)
|
| 496 |
-
|
| 497 |
-
|
| 498 |
-
|
| 499 |
-
|
| 500 |
-
|
| 501 |
-
|
| 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)
|
| 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,
|
| 522 |
-
|
| 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 |
-
|
| 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
|
| 542 |
-
|
| 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 |
-
|
| 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 β
|
| 558 |
fontsize=13, fontweight='bold', color=TEXT_C)
|
| 559 |
plt.tight_layout(pad=1.5)
|
| 560 |
-
plt.savefig(save_path, dpi=
|
| 561 |
plt.close(fig)
|
| 562 |
return lam_dict
|
| 563 |
|
| 564 |
|
| 565 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 566 |
-
# LD COMPUTATION
|
| 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 = [], [], []
|
| 576 |
-
|
| 577 |
-
|
| 578 |
-
|
| 579 |
-
y = G[:, lag: ].astype(float)
|
| 580 |
-
|
| 581 |
xm, ym = x - x.mean(0), y - y.mean(0)
|
| 582 |
-
num
|
| 583 |
-
|
| 584 |
with np.errstate(invalid='ignore', divide='ignore'):
|
| 585 |
-
r
|
| 586 |
r2 = np.clip(r**2, 0, 1)
|
| 587 |
|
| 588 |
-
p1 = x.mean(0)
|
| 589 |
-
|
| 590 |
-
|
| 591 |
-
D = p11 - p1 * p2
|
| 592 |
with np.errstate(invalid='ignore', divide='ignore'):
|
| 593 |
-
Dmax = np.where(D
|
| 594 |
-
np.minimum(p1*(1-p2),
|
| 595 |
-
np.minimum(p1*p2,
|
| 596 |
-
dp = np.where(Dmax
|
| 597 |
|
| 598 |
-
dist = np.abs(bp_pos[lag:] - bp_pos[:n
|
| 599 |
dists.append(dist); r2s.append(r2); dps.append(dp)
|
| 600 |
|
| 601 |
if not dists:
|
|
@@ -604,75 +488,53 @@ def _compute_ld_pairs_bp(G, bp_pos, max_lag=60):
|
|
| 604 |
|
| 605 |
|
| 606 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 607 |
-
# PLOT: LD DECAY
|
| 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 |
-
|
| 628 |
-
|
| 629 |
-
|
| 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(
|
| 643 |
|
| 644 |
G_ch = genotypes[:, idxs].copy().astype(float)
|
| 645 |
-
bp_ch =
|
| 646 |
-
|
| 647 |
-
|
| 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=
|
| 653 |
-
if len(dist)
|
| 654 |
-
continue
|
| 655 |
-
|
| 656 |
-
all_dist.extend(dist.tolist())
|
| 657 |
-
all_r2.extend(r2.tolist())
|
| 658 |
-
all_dp.extend(dp.tolist())
|
| 659 |
-
all_ch.extend([str(ch)] * len(dist))
|
| 660 |
|
|
|
|
|
|
|
| 661 |
chrom_stats[str(ch)] = {
|
| 662 |
-
'n_markers':
|
| 663 |
-
'
|
| 664 |
-
'
|
| 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,
|
| 672 |
-
ax.text(0.5, 0.5, 'No LD data available
|
| 673 |
ha='center', va='center', transform=ax.transAxes,
|
| 674 |
fontsize=13, color=TEXT_C)
|
| 675 |
-
plt.savefig(save_path, dpi=
|
| 676 |
plt.close(fig)
|
| 677 |
return chrom_stats, "No LD data available."
|
| 678 |
|
|
@@ -680,183 +542,109 @@ def plot_ld_decay_bp(genotypes, chromosomes, positions, save_path, max_m=120):
|
|
| 680 |
r2_arr = np.array(all_r2, dtype=float)
|
| 681 |
ch_arr = np.array(all_ch, dtype=str)
|
| 682 |
|
| 683 |
-
|
| 684 |
-
|
| 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
|
| 701 |
-
|
| 702 |
-
|
| 703 |
-
N_BINS = 80
|
| 704 |
-
bins = np.linspace(0, max_scaled, N_BINS + 1)
|
| 705 |
ctrs, meds = [], []
|
| 706 |
-
for i in range(
|
| 707 |
-
m = (dv
|
| 708 |
-
if m.sum()
|
| 709 |
-
ctrs.append((bins[i]
|
| 710 |
meds.append(np.median(rv[m]))
|
| 711 |
|
| 712 |
-
ctrs = np.array(ctrs
|
| 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
|
| 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 |
-
|
| 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 =
|
| 743 |
-
|
| 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
|
| 750 |
-
|
| 751 |
if 'r2_02' in ann:
|
| 752 |
-
ilines
|
| 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
|
| 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 |
-
|
| 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,
|
| 771 |
-
gs = fig.add_gridspec(2,
|
| 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 |
-
|
| 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 |
-
|
| 788 |
-
|
| 789 |
-
ax.
|
| 790 |
-
|
| 791 |
-
|
| 792 |
-
|
| 793 |
-
|
| 794 |
-
|
| 795 |
-
|
| 796 |
-
|
| 797 |
-
|
| 798 |
-
|
| 799 |
-
|
| 800 |
-
|
| 801 |
-
|
| 802 |
-
|
| 803 |
-
|
| 804 |
-
|
| 805 |
-
|
| 806 |
-
|
| 807 |
-
|
| 808 |
-
|
| 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,
|
| 835 |
-
|
| 836 |
-
|
| 837 |
-
|
| 838 |
-
|
| 839 |
-
|
| 840 |
-
|
| 841 |
-
|
| 842 |
-
|
| 843 |
-
|
| 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 |
-
|
| 857 |
-
alpha=0.95))
|
| 858 |
|
| 859 |
-
plt.savefig(save_path, dpi=
|
| 860 |
plt.close(fig)
|
| 861 |
return chrom_stats, ld_interp
|
| 862 |
|
|
@@ -864,155 +652,129 @@ def plot_ld_decay_bp(genotypes, chromosomes, positions, save_path, max_m=120):
|
|
| 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
|
| 872 |
-
|
| 873 |
-
|
| 874 |
-
|
| 875 |
-
nrows
|
| 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 |
-
|
| 884 |
-
|
| 885 |
-
|
| 886 |
-
|
| 887 |
-
pa
|
| 888 |
-
|
| 889 |
-
|
| 890 |
-
ax.
|
| 891 |
-
|
| 892 |
-
|
| 893 |
-
|
| 894 |
-
|
| 895 |
-
|
| 896 |
-
|
| 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,
|
| 909 |
plt.close(fig)
|
| 910 |
|
| 911 |
|
| 912 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 913 |
-
# PLOT: PHENOTYPE
|
| 914 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 915 |
-
|
| 916 |
def plot_phenotype(phenotypes, save_path):
|
| 917 |
_style()
|
| 918 |
pv = phenotypes[~np.isnan(phenotypes)]
|
| 919 |
-
fig, axes = plt.subplots(1,
|
| 920 |
-
|
| 921 |
ax = axes[0]; ax.set_facecolor(PANEL)
|
| 922 |
-
ax.hist(pv,
|
| 923 |
-
ax.axvline(np.mean(pv),
|
| 924 |
label=f'Mean={np.mean(pv):.2f}')
|
| 925 |
-
ax.axvline(np.median(pv),
|
| 926 |
label=f'Median={np.median(pv):.2f}')
|
| 927 |
-
ax.set_xlabel('Phenotype Value',
|
| 928 |
-
ax.set_ylabel('Frequency',
|
| 929 |
-
ax.set_title('Phenotype Distribution',
|
| 930 |
-
ax.legend(fontsize=9)
|
| 931 |
-
|
| 932 |
-
|
| 933 |
-
|
| 934 |
-
|
| 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,
|
| 940 |
-
ax.get_lines()[0].set(color=ACCENT,
|
| 941 |
-
ax.get_lines()[1].set(color=RED_C,
|
| 942 |
-
ax.set_title('Normal Q-Q (Phenotype)',
|
| 943 |
-
ax.grid(True,
|
| 944 |
-
|
| 945 |
plt.tight_layout(pad=1.5)
|
| 946 |
-
plt.savefig(save_path,
|
| 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,
|
| 960 |
|
| 961 |
-
|
| 962 |
-
|
| 963 |
-
|
| 964 |
-
|
|
|
|
| 965 |
|
| 966 |
-
ms_t = miss_sample
|
| 967 |
-
mm_t = miss_marker
|
| 968 |
-
mf_t = maf_thresh
|
| 969 |
|
| 970 |
-
|
| 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 |
-
|
| 979 |
-
|
|
|
|
| 980 |
maf_arr = np.zeros(n_m)
|
| 981 |
for i in range(n_m):
|
| 982 |
-
v = geno[:,
|
| 983 |
if len(v):
|
| 984 |
-
f = np.mean(v)
|
| 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,
|
| 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,
|
| 996 |
-
if rs
|
| 997 |
-
fallback
|
| 998 |
-
|
| 999 |
break
|
| 1000 |
|
| 1001 |
-
geno_q = geno[np.ix_(qc_s,
|
| 1002 |
-
pheno_q = pheno[qc_s]
|
| 1003 |
-
|
| 1004 |
-
|
| 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 |
-
|
| 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]):
|
| 1014 |
-
mk = np.isnan(geno_q[:,
|
| 1015 |
-
if mk.any(): geno_q[mk,
|
| 1016 |
|
| 1017 |
valid = ~np.isnan(pheno_q)
|
| 1018 |
geno_q = geno_q[valid]; pheno_q = pheno_q[valid]; sids_q = sids_q[valid]
|
|
@@ -1020,127 +782,122 @@ def run_analysis(input_file, miss_sample, miss_marker, maf_thresh,
|
|
| 1020 |
if len(sids_q) < 10:
|
| 1021 |
return (f"## β οΈ Only {len(sids_q)} samples passed QC. "
|
| 1022 |
"Try increasing missing-rate sliders.",
|
| 1023 |
-
None,
|
| 1024 |
|
| 1025 |
-
bonf
|
| 1026 |
-
bonf_log = -np.log10(bonf)
|
| 1027 |
|
| 1028 |
-
|
| 1029 |
-
print("[Kinship] Computing K matrixβ¦")
|
| 1030 |
K = compute_kinship(geno_q)
|
| 1031 |
|
| 1032 |
-
# ββ
|
| 1033 |
-
model_pvals = {}
|
| 1034 |
-
|
| 1035 |
-
|
| 1036 |
|
| 1037 |
if run_glm:
|
| 1038 |
-
|
| 1039 |
-
pv,
|
| 1040 |
-
model_pvals['GLM']
|
| 1041 |
|
| 1042 |
if run_mlm:
|
| 1043 |
-
|
| 1044 |
-
pv,
|
| 1045 |
-
model_pvals['MLM']
|
| 1046 |
|
| 1047 |
if run_cmlm:
|
| 1048 |
-
|
| 1049 |
-
pv,
|
| 1050 |
-
model_pvals['CMLM']
|
| 1051 |
|
| 1052 |
if run_bslmm:
|
| 1053 |
-
|
| 1054 |
-
|
| 1055 |
-
|
|
|
|
| 1056 |
|
| 1057 |
if run_farmcpu:
|
| 1058 |
-
|
| 1059 |
-
pv,
|
| 1060 |
-
model_pvals['FarmCPU']
|
| 1061 |
|
| 1062 |
if not model_pvals:
|
| 1063 |
-
return ("## β οΈ No models selected.
|
| 1064 |
-
None, None, None, None, None, None)
|
| 1065 |
|
| 1066 |
-
# ββ
|
| 1067 |
-
|
| 1068 |
-
|
| 1069 |
-
for mname,
|
| 1070 |
df[f'{mname}_P'] = pv
|
| 1071 |
-
df[f'{mname}_LOD'] = -np.log10(np.clip(pv,
|
| 1072 |
-
df[f'{mname}_Sig'] = (pv
|
| 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)
|
| 1079 |
df = df.sort_values(f"{list(model_pvals.keys())[0]}_P").reset_index(drop=True)
|
| 1080 |
-
df.insert(0,
|
| 1081 |
-
df.to_csv(os.path.join(rdir, 'gwas_results.csv'), index=False)
|
| 1082 |
|
| 1083 |
-
|
| 1084 |
-
|
| 1085 |
-
df
|
|
|
|
|
|
|
| 1086 |
|
| 1087 |
-
# ββ Plots ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1088 |
-
|
| 1089 |
-
ph_path
|
| 1090 |
plot_phenotype(pheno_q, ph_path)
|
| 1091 |
|
| 1092 |
-
|
| 1093 |
-
man_path =
|
| 1094 |
plot_manhattan_multi(mn_q, ch_q, model_pvals, bonf, man_path)
|
| 1095 |
|
| 1096 |
-
|
| 1097 |
-
qq_path
|
| 1098 |
lam_dict = plot_qq_multi(model_pvals, bonf, qq_path)
|
| 1099 |
|
| 1100 |
-
|
| 1101 |
-
ld_path
|
| 1102 |
ld_stats, ld_interp = plot_ld_decay_bp(geno_q, ch_q, pos_q, ld_path)
|
| 1103 |
-
ld_df = pd.DataFrame([{'Chromosome':
|
| 1104 |
-
ld_df.to_csv(
|
| 1105 |
|
| 1106 |
-
|
| 1107 |
-
cmp_path =
|
| 1108 |
plot_model_comparison(model_pvals, cmp_path)
|
| 1109 |
|
| 1110 |
-
# ββ ZIP ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1111 |
-
|
| 1112 |
-
|
| 1113 |
-
|
|
|
|
| 1114 |
for f in files:
|
| 1115 |
-
fp = os.path.join(root,
|
| 1116 |
-
zf.write(fp, os.path.relpath(fp,
|
| 1117 |
|
| 1118 |
-
# ββ Summary βββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1119 |
def _mdt(d, n=15):
|
| 1120 |
-
sub
|
| 1121 |
-
cols = sub.columns.tolist()
|
| 1122 |
def _f(v):
|
| 1123 |
-
if isinstance(v,
|
| 1124 |
return f"{v:.3e}" if (v!=0 and abs(v)<0.001) else f"{v:.4f}"
|
| 1125 |
return str(v)
|
| 1126 |
-
sep = "| "
|
| 1127 |
rows = ["| "+" | ".join(_f(row[c]) for c in cols)+" |"
|
| 1128 |
-
for _,
|
| 1129 |
-
return "\n".join(["| "+" | ".join(cols)+" |",
|
| 1130 |
|
| 1131 |
model_summary_rows = "\n".join(
|
| 1132 |
-
f"| {m} | **{int((pv
|
| 1133 |
f"{'β οΈ inflation' if lam_dict.get(m,1)>1.05 else 'β
ok'} |"
|
| 1134 |
-
for m,
|
| 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.
|
| 1144 |
|
| 1145 |
### π QC Summary
|
| 1146 |
| Metric | Value |
|
|
@@ -1160,47 +917,41 @@ def run_analysis(input_file, miss_sample, miss_marker, maf_thresh,
|
|
| 1160 |
|
| 1161 |
**Bonferroni threshold:** P < {bonf:.3e} | βlogββP > {bonf_log:.2f}
|
| 1162 |
|
| 1163 |
-
### 𧬠LD Decay
|
| 1164 |
{ld_interp}
|
| 1165 |
|
| 1166 |
### π Top 15 Markers
|
| 1167 |
{_mdt(df[top_cols])}
|
| 1168 |
|
| 1169 |
---
|
| 1170 |
-
**Output
|
| 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 |
-
|
| 1181 |
-
|
|
|
|
|
|
|
| 1182 |
cmp_path, ph_path, zip_path)
|
| 1183 |
|
| 1184 |
except Exception as e:
|
| 1185 |
import traceback
|
| 1186 |
return (f"## β Error\n```\n{e}\n\n{traceback.format_exc()}\n```",
|
| 1187 |
-
None,
|
| 1188 |
|
| 1189 |
|
| 1190 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1191 |
# GRADIO UI
|
| 1192 |
# βββββββββββββββββββββββββββββββββββββββββββββββοΏ½οΏ½ββββββββββββββ
|
| 1193 |
-
|
| 1194 |
CSS = """
|
| 1195 |
.gradio-container{font-family:'Segoe UI',Tahoma,sans-serif}
|
| 1196 |
h1{color:#2D1B5E;border-bottom:3px solid #7C3AED;padding-bottom:8px}
|
|
|
|
| 1197 |
"""
|
| 1198 |
|
| 1199 |
-
with gr.Blocks(css=CSS, title="MTA GWAS v8.
|
| 1200 |
|
| 1201 |
gr.Markdown("""
|
| 1202 |
-
# 𧬠GWAS Analysis Platform v8.
|
| 1203 |
-
### 5-Model MRmlm Suite | LD Decay in bp |
|
| 1204 |
---
|
| 1205 |
""")
|
| 1206 |
|
|
@@ -1209,11 +960,10 @@ with gr.Blocks(css=CSS, title="MTA GWAS v8.0") as app:
|
|
| 1209 |
gr.Markdown("""
|
| 1210 |
### π CSV Format (3-row header)
|
| 1211 |
```
|
| 1212 |
-
ID, Phenotype,
|
| 1213 |
-
-, Chr, 1,
|
| 1214 |
-
-, Pos, 134521,
|
| 1215 |
-
IRRI-1, 25.34, 0,
|
| 1216 |
-
IRRI-75, 23.34, 0, 0, ...
|
| 1217 |
```
|
| 1218 |
**Genotypes:** 0/1/2 (β1 or blank = missing)
|
| 1219 |
""")
|
|
@@ -1221,11 +971,11 @@ with gr.Blocks(css=CSS, title="MTA GWAS v8.0") as app:
|
|
| 1221 |
|
| 1222 |
with gr.Column(scale=1):
|
| 1223 |
gr.Markdown("### βοΈ QC Parameters")
|
| 1224 |
-
miss_sample = gr.Slider(5,
|
| 1225 |
label="Max sample missing rate (%)")
|
| 1226 |
-
miss_marker = gr.Slider(5,
|
| 1227 |
label="Max marker missing rate (%)")
|
| 1228 |
-
maf_thr = gr.Slider(0,
|
| 1229 |
label="Min MAF (%)")
|
| 1230 |
|
| 1231 |
with gr.Column(scale=1):
|
|
@@ -1233,30 +983,32 @@ with gr.Blocks(css=CSS, title="MTA GWAS v8.0") as app:
|
|
| 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=
|
| 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("---")
|
| 1241 |
|
| 1242 |
summary_out = gr.Markdown()
|
| 1243 |
|
| 1244 |
with gr.Row():
|
| 1245 |
-
man_out = gr.Image(label="πΊοΈ Manhattan Plots
|
| 1246 |
-
ld_out = gr.Image(label="𧬠LD Decay
|
| 1247 |
|
| 1248 |
with gr.Row():
|
| 1249 |
-
qq_out = gr.Image(label="π QQ Plots + Ξ»
|
| 1250 |
cmp_out = gr.Image(label="βοΈ Model Concordance")
|
| 1251 |
|
| 1252 |
with gr.Row():
|
| 1253 |
ph_out = gr.Image(label="π Phenotype Distribution")
|
| 1254 |
dl_out = gr.File(label="π¦ Download All Results (ZIP)")
|
| 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,
|
|
@@ -1264,8 +1016,9 @@ with gr.Blocks(css=CSS, title="MTA GWAS v8.0") as app:
|
|
| 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=
|
| 1268 |
)
|
| 1269 |
|
| 1270 |
if __name__ == "__main__":
|
| 1271 |
-
app.launch(share=False, show_error=True
|
|
|
|
|
|
| 1 |
# -*- coding: utf-8 -*-
|
| 2 |
"""
|
| 3 |
+
MTA Analysis Tool v8.1 β FIXES:
|
| 4 |
+
β
Persistent output directory (no tempfile cleanup race)
|
| 5 |
+
β
BSLMM: n_boot reduced + Ridge fallback for speed
|
| 6 |
+
β
FarmCPU: vectorised inner loop
|
| 7 |
+
β
LD decay: max_m cap per chromosome
|
| 8 |
+
β
Gradio: gr.File returns actual path (not None race)
|
| 9 |
+
β
Progress status updates in UI
|
| 10 |
+
β
Timeout-safe: all heavy loops have max-iteration caps
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
"""
|
| 12 |
|
| 13 |
import gradio as gr
|
|
|
|
| 18 |
import matplotlib.pyplot as plt
|
| 19 |
from scipy import stats
|
| 20 |
from scipy.interpolate import make_interp_spline
|
| 21 |
+
import os, warnings, zipfile, shutil
|
| 22 |
+
from pathlib import Path
|
| 23 |
+
from sklearn.linear_model import ElasticNetCV, Ridge
|
| 24 |
from sklearn.preprocessing import StandardScaler
|
|
|
|
| 25 |
warnings.filterwarnings('ignore')
|
| 26 |
|
| 27 |
+
# ββ Persistent output directory (survives Gradio's file-serving lifecycle) ββ
|
| 28 |
+
OUTPUT_DIR = Path(os.path.expanduser("~")) / "gwas_outputs"
|
| 29 |
+
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
|
| 30 |
+
|
| 31 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 32 |
# THEME
|
| 33 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
|
|
|
| 40 |
GOLD_C = "#D97706"
|
| 41 |
TEAL_C = "#0891B2"
|
| 42 |
GREEN_C = "#15803D"
|
|
|
|
|
|
|
| 43 |
|
| 44 |
CHROM_PALETTE = [
|
| 45 |
"#7C3AED","#DB2777","#059669","#0284C7","#D97706",
|
|
|
|
| 64 |
'axes.titlecolor': TEXT_C,'xtick.color': TEXT_C,
|
| 65 |
'ytick.color': TEXT_C,'text.color': TEXT_C,
|
| 66 |
'grid.color': GRID_C,'grid.linewidth': 0.7,
|
| 67 |
+
'figure.dpi': 100, 'font.family': 'DejaVu Sans',
|
| 68 |
'axes.spines.top': False, 'axes.spines.right': False,
|
| 69 |
'legend.framealpha':0.95, 'legend.edgecolor': GRID_C,
|
| 70 |
})
|
| 71 |
|
| 72 |
|
| 73 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 74 |
+
# CSV PARSER
|
| 75 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
|
|
|
| 76 |
def parse_input_csv(filepath):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 77 |
df = pd.read_csv(filepath, header=0, dtype=str)
|
| 78 |
marker_cols = df.columns[2:].tolist()
|
| 79 |
+
chr_row = df.iloc[0]
|
| 80 |
+
pos_row = df.iloc[1]
|
|
|
|
| 81 |
|
| 82 |
chrom_dict, pos_dict = {}, {}
|
| 83 |
for m in marker_cols:
|
|
|
|
| 84 |
cv = str(chr_row[m]).strip()
|
| 85 |
cv = cv[:-2] if cv.endswith('.0') else cv
|
| 86 |
cv = cv.replace('chr','').replace('Chr','').strip()
|
| 87 |
chrom_dict[m] = cv if cv not in ('', 'nan', '-') else '0'
|
| 88 |
|
|
|
|
| 89 |
pv = str(pos_row[m]).strip()
|
| 90 |
try:
|
| 91 |
pos_dict[m] = float(pv)
|
| 92 |
except ValueError:
|
| 93 |
+
parts = m.split('_')
|
|
|
|
| 94 |
bp = 0.0
|
| 95 |
+
for part in parts:
|
| 96 |
try:
|
| 97 |
+
cand = float(part)
|
| 98 |
+
if cand > 1000:
|
| 99 |
+
bp = cand; break
|
| 100 |
except ValueError:
|
| 101 |
continue
|
| 102 |
pos_dict[m] = bp
|
|
|
|
| 104 |
df_s = df.iloc[2:].reset_index(drop=True)
|
| 105 |
sample_ids = df_s.iloc[:, 0].astype(str).values
|
| 106 |
phenotypes = pd.to_numeric(df_s.iloc[:, 1], errors='coerce').values
|
| 107 |
+
geno_raw = (df_s[marker_cols]
|
| 108 |
+
.apply(pd.to_numeric, errors='coerce')
|
| 109 |
+
.replace(-1, np.nan)
|
| 110 |
+
.where(lambda x: x.isin([0,1,2]) | x.isna(), other=np.nan))
|
|
|
|
| 111 |
|
| 112 |
chromosomes = [chrom_dict[m] for m in marker_cols]
|
| 113 |
positions = [pos_dict[m] for m in marker_cols]
|
|
|
|
| 114 |
return (sample_ids, phenotypes,
|
| 115 |
geno_raw.values, marker_cols,
|
| 116 |
chromosomes, positions)
|
| 117 |
|
| 118 |
|
| 119 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 120 |
+
# KINSHIP
|
| 121 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
|
|
|
| 122 |
def compute_kinship(G):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 123 |
X = G.astype(float).copy()
|
| 124 |
+
mu = np.nanmean(X, 0); std = np.nanstd(X, 0)
|
|
|
|
|
|
|
| 125 |
std[std < 1e-9] = 1.0
|
| 126 |
X = (X - mu) / std
|
| 127 |
X = np.nan_to_num(X, 0)
|
|
|
|
| 128 |
K = (X @ X.T) / X.shape[1]
|
|
|
|
| 129 |
d = np.diag(K).mean()
|
| 130 |
+
if d > 0: K /= d
|
|
|
|
| 131 |
return K
|
| 132 |
|
| 133 |
|
| 134 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 135 |
+
# MODEL 1: GLM
|
| 136 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
|
|
|
| 137 |
def model_glm(G, y):
|
|
|
|
| 138 |
n, m = G.shape
|
| 139 |
+
pv = np.ones(m); bv = np.zeros(m); sv = np.zeros(m); rv = np.zeros(m)
|
|
|
|
| 140 |
for i in range(m):
|
| 141 |
x = G[:, i]
|
| 142 |
if x.std() < 1e-9: continue
|
|
|
|
| 147 |
|
| 148 |
|
| 149 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 150 |
+
# MODEL 2: MLM
|
| 151 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
|
|
|
| 152 |
def model_mlm(G, y, K):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 153 |
n = len(y)
|
| 154 |
n_pc = min(5, n - 2)
|
| 155 |
eigvals, eigvecs = np.linalg.eigh(K)
|
| 156 |
idx = np.argsort(eigvals)[::-1]
|
| 157 |
+
Q = eigvecs[:, idx[:n_pc]]
|
| 158 |
+
Qy = Q @ np.linalg.lstsq(Q, y, rcond=None)[0]
|
| 159 |
+
y_r = y - Qy
|
|
|
|
|
|
|
| 160 |
|
| 161 |
+
m = G.shape[1]
|
| 162 |
+
pv = np.ones(m); bv = np.zeros(m); sv = np.zeros(m); rv = np.zeros(m)
|
|
|
|
| 163 |
for i in range(m):
|
| 164 |
x = G[:, i]
|
| 165 |
if x.std() < 1e-9: continue
|
|
|
|
| 166 |
Qx = Q @ np.linalg.lstsq(Q, x, rcond=None)[0]
|
| 167 |
xr = x - Qx
|
| 168 |
if xr.std() < 1e-9: continue
|
|
|
|
| 173 |
|
| 174 |
|
| 175 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 176 |
+
# MODEL 3: CMLM
|
| 177 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
|
|
|
| 178 |
def model_cmlm(G, y, K, n_groups=None):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 179 |
from sklearn.cluster import KMeans
|
| 180 |
n = len(y)
|
| 181 |
if n_groups is None:
|
| 182 |
n_groups = max(2, min(20, n // 10))
|
|
|
|
|
|
|
| 183 |
eigvals, eigvecs = np.linalg.eigh(K)
|
| 184 |
idx = np.argsort(eigvals)[::-1]
|
| 185 |
emb = eigvecs[:, idx[:min(10, n-1)]]
|
| 186 |
+
km = KMeans(n_clusters=n_groups, random_state=42, n_init=5)
|
| 187 |
+
labs = km.fit_predict(emb)
|
| 188 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 189 |
Q = np.zeros((n, n_groups))
|
| 190 |
for g in range(n_groups):
|
| 191 |
Q[:, g] = (labs == g).astype(float)
|
| 192 |
+
col_sum = Q.sum(0); col_sum[col_sum==0] = 1
|
|
|
|
|
|
|
| 193 |
Q = Q / col_sum
|
| 194 |
|
| 195 |
Qy = Q @ np.linalg.lstsq(Q, y, rcond=None)[0]
|
| 196 |
y_r = y - Qy
|
| 197 |
|
| 198 |
+
m = G.shape[1]
|
| 199 |
+
pv = np.ones(m); bv = np.zeros(m); sv = np.zeros(m); rv = np.zeros(m)
|
|
|
|
| 200 |
for i in range(m):
|
| 201 |
x = G[:, i]
|
| 202 |
if x.std() < 1e-9: continue
|
|
|
|
| 210 |
|
| 211 |
|
| 212 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 213 |
+
# MODEL 4: BSLMM β FIXED: faster with Ridge fallback + fewer boots
|
| 214 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 215 |
+
def model_bslmm(G, y, n_boot=8): # β was 20, now 8
|
|
|
|
| 216 |
"""
|
| 217 |
+
Speed fix:
|
| 218 |
+
- Reduced bootstrap iterations to 8 (was 20).
|
| 219 |
+
- Ridge fallback if ElasticNet is slow (n_markers > 2000).
|
| 220 |
+
- max_iter capped at 1000.
|
| 221 |
"""
|
| 222 |
sc = StandardScaler()
|
| 223 |
Xs = sc.fit_transform(G)
|
| 224 |
+
n, m = Xs.shape
|
| 225 |
+
|
| 226 |
+
# Use Ridge for large marker sets β much faster, still regularised
|
| 227 |
+
if m > 2000:
|
| 228 |
+
alphas = np.logspace(-3, 3, 20)
|
| 229 |
+
mdl = Ridge(alpha=1.0, fit_intercept=True)
|
| 230 |
+
from sklearn.linear_model import RidgeCV as _RCV
|
| 231 |
+
mdl = _RCV(alphas=alphas, cv=3)
|
| 232 |
+
mdl.fit(Xs, y)
|
| 233 |
+
coef = mdl.coef_
|
| 234 |
+
else:
|
| 235 |
+
en = ElasticNetCV(cv=3, random_state=42, max_iter=1000, n_jobs=-1,
|
| 236 |
+
l1_ratio=[.1,.5,.9,1])
|
| 237 |
+
en.fit(Xs, y)
|
| 238 |
+
coef = en.coef_
|
| 239 |
|
| 240 |
boots = []
|
| 241 |
rng = np.random.default_rng(42)
|
| 242 |
for _ in range(n_boot):
|
| 243 |
+
idx = rng.integers(0, n, n)
|
|
|
|
|
|
|
| 244 |
try:
|
| 245 |
+
if m > 2000:
|
| 246 |
+
from sklearn.linear_model import RidgeCV as _RCV2
|
| 247 |
+
eb = _RCV2(alphas=[0.1,1,10], cv=3)
|
| 248 |
+
else:
|
| 249 |
+
eb = ElasticNetCV(cv=3, random_state=42,
|
| 250 |
+
max_iter=500, l1_ratio=[.1,.5,.9,1])
|
| 251 |
eb.fit(Xs[idx], y[idx])
|
| 252 |
boots.append(eb.coef_)
|
| 253 |
except Exception:
|
| 254 |
boots.append(coef.copy())
|
| 255 |
|
| 256 |
boot_arr = np.array(boots)
|
| 257 |
+
pv = np.ones(m)
|
| 258 |
+
for i in range(m):
|
| 259 |
sd = boot_arr[:, i].std()
|
| 260 |
if sd > 0:
|
| 261 |
z = abs(coef[i]) / (sd + 1e-12)
|
|
|
|
| 264 |
|
| 265 |
|
| 266 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 267 |
+
# MODEL 5: FarmCPU β FIXED: vectorised scan
|
| 268 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
|
|
|
| 269 |
def model_farmcpu(G, y, K, max_iter=3):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 270 |
n, m = G.shape
|
|
|
|
|
|
|
|
|
|
| 271 |
pv_cur, bv, sv, rv = model_glm(G, y)
|
| 272 |
|
| 273 |
for iteration in range(max_iter):
|
| 274 |
+
n_qtns = max(1, min(10, int(m * 0.001)))
|
|
|
|
| 275 |
top_idx = np.argsort(pv_cur)[:n_qtns]
|
| 276 |
+
covs = G[:, top_idx]
|
| 277 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 278 |
try:
|
| 279 |
coef_c, _, _, _ = np.linalg.lstsq(covs, y, rcond=None)
|
| 280 |
y_cond = y - covs @ coef_c
|
| 281 |
except Exception:
|
| 282 |
y_cond = y.copy()
|
| 283 |
|
| 284 |
+
# ββ vectorised residualise covs from all markers ββββββββββββββββββ
|
| 285 |
+
# covs: nΓq, G: nΓm β project out covs
|
| 286 |
+
try:
|
| 287 |
+
CtC_inv = np.linalg.pinv(covs.T @ covs)
|
| 288 |
+
proj = covs @ CtC_inv @ covs.T # nΓn projector
|
| 289 |
+
G_res = G - proj @ G # nΓm (residualised)
|
| 290 |
+
except Exception:
|
| 291 |
+
G_res = G.copy()
|
| 292 |
+
|
| 293 |
+
# scan residualised markers against y_cond
|
| 294 |
+
pv_new = np.ones(m); bv_new = np.zeros(m); sv_new = np.zeros(m)
|
| 295 |
for i in range(m):
|
| 296 |
+
x = G_res[:, i]
|
| 297 |
if x.std() < 1e-9: continue
|
| 298 |
+
sl, _, r, p, se = stats.linregress(x, y_cond)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 299 |
pv_new[i] = max(p, 1e-300) if np.isfinite(p) else 1.0
|
| 300 |
bv_new[i] = sl; sv_new[i] = se
|
| 301 |
|
| 302 |
+
pv_cur = pv_new.copy()
|
|
|
|
| 303 |
|
| 304 |
return pv_cur, bv_new, sv_new
|
| 305 |
|
| 306 |
|
| 307 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 308 |
+
# PLOT: MANHATTAN
|
| 309 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
|
|
|
| 310 |
def plot_manhattan_multi(mn, chroms, model_pvals, bonf_thresh, save_path):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 311 |
_style()
|
| 312 |
unique_chroms = sorted(set(chroms),
|
| 313 |
key=lambda x: (int(x) if str(x).isdigit() else 999, str(x)))
|
|
|
|
| 329 |
offset += len(idxs) + GAP
|
| 330 |
|
| 331 |
fig, axes = plt.subplots(n_models, 1,
|
| 332 |
+
figsize=(18, 3.2*n_models),
|
| 333 |
facecolor=BG, sharex=True)
|
| 334 |
if n_models == 1:
|
| 335 |
axes = [axes]
|
| 336 |
|
| 337 |
bonf_log = -np.log10(bonf_thresh)
|
|
|
|
|
|
|
| 338 |
for ax, (mname, pv) in zip(axes, model_pvals.items()):
|
| 339 |
+
log_p = -np.log10(np.clip(pv, 1e-300, 1))
|
| 340 |
sig_set = set(np.where(pv < bonf_thresh)[0])
|
|
|
|
|
|
|
| 341 |
for ci, ch in enumerate(unique_chroms):
|
| 342 |
idxs = chrom_to_idx.get(ch, [])
|
| 343 |
if not idxs: continue
|
| 344 |
if ci % 2 == 0:
|
| 345 |
+
ax.axvspan(x_pos[idxs[0]]-.5, x_pos[idxs[-1]]+.5,
|
| 346 |
color='#EDE9FE', alpha=0.35, zorder=0)
|
| 347 |
shade = CHROM_PALETTE[ci % len(CHROM_PALETTE)]
|
| 348 |
norm = [i for i in idxs if i not in sig_set]
|
| 349 |
sel = [i for i in idxs if i in sig_set]
|
| 350 |
if norm:
|
| 351 |
+
ax.scatter(x_pos[norm], log_p[norm], c=shade,
|
| 352 |
+
s=8, alpha=0.55, linewidths=0, zorder=2)
|
| 353 |
if sel:
|
| 354 |
+
ax.scatter(x_pos[sel], log_p[sel], c=RED_C, s=220,
|
| 355 |
+
alpha=0.12, linewidths=0, zorder=3)
|
| 356 |
+
ax.scatter(x_pos[sel], log_p[sel], c=RED_C, s=55,
|
| 357 |
+
alpha=1.0, edgecolors='white', linewidths=0.8,
|
|
|
|
| 358 |
marker='D', zorder=4)
|
| 359 |
+
ax.axhline(bonf_log, color=RED_C, ls='--', lw=1.6, alpha=0.85,
|
|
|
|
| 360 |
label=f'Bonferroni ({bonf_log:.1f})')
|
| 361 |
+
ax.axhline(3.0, color=GOLD_C, ls=':', lw=1.4, alpha=0.8,
|
| 362 |
label='Suggestive (3)')
|
| 363 |
ax.set_xlim(-GAP, offset)
|
| 364 |
+
ax.set_ylim(0, max(log_p.max()*1.15, bonf_log*1.1, 1))
|
| 365 |
ax.set_ylabel('βlogββ(P)', fontsize=10, fontweight='bold')
|
| 366 |
ax.set_title(f'Model: {mname}', fontsize=11, fontweight='bold',
|
| 367 |
+
color=MODEL_COLORS.get(mname, ACCENT), pad=4)
|
| 368 |
ax.yaxis.grid(True, color=GRID_C, lw=0.6)
|
| 369 |
+
ax.legend(loc='upper right', fontsize=7.5)
|
|
|
|
|
|
|
| 370 |
n_sig = int((pv < bonf_thresh).sum())
|
| 371 |
+
ax.text(0.01, 0.92, f'{n_sig} significant',
|
| 372 |
+
transform=ax.transAxes, fontsize=8, color=RED_C,
|
| 373 |
+
fontweight='bold')
|
| 374 |
|
| 375 |
axes[-1].set_xticks([x for x, _ in chrom_xticks])
|
| 376 |
axes[-1].set_xticklabels([l for _, l in chrom_xticks], fontsize=7)
|
| 377 |
axes[-1].set_xlabel('Chromosome', fontsize=11, fontweight='bold')
|
| 378 |
+
plt.suptitle('GWAS Manhattan Plots β Multi-Model',
|
|
|
|
| 379 |
fontsize=13, fontweight='bold', y=1.01, color=TEXT_C)
|
| 380 |
plt.tight_layout(pad=1.2)
|
| 381 |
+
plt.savefig(save_path, dpi=100, bbox_inches='tight', facecolor=BG)
|
| 382 |
plt.close(fig)
|
| 383 |
|
| 384 |
|
| 385 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 386 |
+
# PLOT: QQ
|
| 387 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
|
|
|
| 388 |
def plot_qq_multi(model_pvals, bonf_thresh, save_path):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 389 |
_style()
|
| 390 |
n_models = len(model_pvals)
|
| 391 |
ncols = min(3, n_models)
|
| 392 |
nrows = (n_models + ncols - 1) // ncols
|
|
|
|
| 393 |
fig, axes = plt.subplots(nrows, ncols,
|
| 394 |
+
figsize=(5.5*ncols, 5*nrows),
|
| 395 |
facecolor=BG, squeeze=False)
|
|
|
|
| 396 |
bonf_log = -np.log10(bonf_thresh)
|
| 397 |
lam_dict = {}
|
| 398 |
|
| 399 |
for idx, (mname, pv_raw) in enumerate(model_pvals.items()):
|
| 400 |
row, col = divmod(idx, ncols)
|
| 401 |
+
ax = axes[row][col]; ax.set_facecolor(PANEL)
|
|
|
|
| 402 |
|
|
|
|
| 403 |
pv = np.array(pv_raw, dtype=float)
|
| 404 |
pv = pv[np.isfinite(pv) & (pv > 0) & (pv <= 1)]
|
| 405 |
+
if not len(pv):
|
| 406 |
ax.text(0.5, 0.5, 'No valid p-values',
|
| 407 |
+
ha='center', va='center', transform=ax.transAxes); continue
|
| 408 |
+
|
| 409 |
+
n = len(pv)
|
| 410 |
+
obs_log = -np.log10(np.sort(pv))[::-1]
|
| 411 |
+
exp_log = -np.log10(np.arange(1, n+1) / (n+1))[::-1]
|
| 412 |
+
|
| 413 |
+
chi2_obs = stats.chi2.ppf(1-pv, df=1)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 414 |
chi2_obs = chi2_obs[np.isfinite(chi2_obs) & (chi2_obs > 0)]
|
| 415 |
lam = (np.median(chi2_obs) / stats.chi2.ppf(0.5, df=1)
|
| 416 |
+
if len(chi2_obs) else 1.0)
|
| 417 |
lam_dict[mname] = lam
|
| 418 |
|
| 419 |
mcol = MODEL_COLORS.get(mname, ACCENT)
|
|
|
|
|
|
|
| 420 |
colors_dot = np.where(obs_log >= bonf_log, RED_C, mcol)
|
| 421 |
ax.scatter(exp_log, obs_log, c=colors_dot, s=10,
|
| 422 |
alpha=0.65, linewidths=0, zorder=2)
|
| 423 |
|
| 424 |
maxv = max(obs_log.max(), exp_log.max()) * 1.08
|
| 425 |
+
ax.plot([0,maxv],[0,maxv], color='#374151', lw=1.5, ls='--', zorder=3)
|
| 426 |
+
ax.axhline(bonf_log, color=RED_C, ls=':', lw=1.3, alpha=0.8)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 427 |
|
|
|
|
| 428 |
ci_up = -np.log10(stats.beta.ppf(0.025, np.arange(1,n+1),
|
| 429 |
+
np.arange(n,0,-1)) + 1e-300)[::-1]
|
| 430 |
ci_lo = -np.log10(stats.beta.ppf(0.975, np.arange(1,n+1),
|
| 431 |
+
np.arange(n,0,-1)) + 1e-300)[::-1]
|
| 432 |
+
ax.fill_between(exp_log, ci_lo, ci_up, color=mcol, alpha=0.12, zorder=1)
|
|
|
|
|
|
|
|
|
|
| 433 |
|
| 434 |
ax.set_xlim(0, maxv); ax.set_ylim(0, maxv)
|
| 435 |
ax.set_xlabel('Expected βlogββ(P)', fontsize=10, fontweight='bold')
|
| 436 |
ax.set_ylabel('Observed βlogββ(P)', fontsize=10, fontweight='bold')
|
| 437 |
+
ax.set_title(f'{mname} QQ', fontsize=11, fontweight='bold', color=mcol)
|
| 438 |
+
ax.text(0.05, 0.92, f'Ξ» = {lam:.3f}',
|
|
|
|
|
|
|
| 439 |
transform=ax.transAxes, fontsize=11, fontweight='bold',
|
| 440 |
color=mcol,
|
| 441 |
bbox=dict(boxstyle='round', facecolor=BG,
|
| 442 |
edgecolor=mcol, alpha=0.9, lw=1.2))
|
|
|
|
| 443 |
ax.grid(True, color=GRID_C, lw=0.6)
|
| 444 |
|
| 445 |
+
for extra in range(n_models, nrows*ncols):
|
|
|
|
| 446 |
r, c = divmod(extra, ncols)
|
| 447 |
axes[r][c].set_visible(False)
|
| 448 |
|
| 449 |
+
plt.suptitle('QQ Plots β Ξ» = genomic inflation',
|
| 450 |
fontsize=13, fontweight='bold', color=TEXT_C)
|
| 451 |
plt.tight_layout(pad=1.5)
|
| 452 |
+
plt.savefig(save_path, dpi=100, bbox_inches='tight', facecolor=BG)
|
| 453 |
plt.close(fig)
|
| 454 |
return lam_dict
|
| 455 |
|
| 456 |
|
| 457 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 458 |
+
# LD COMPUTATION
|
| 459 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 460 |
+
def _compute_ld_pairs_bp(G, bp_pos, max_lag=50):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 461 |
n = G.shape[1]
|
| 462 |
dists, r2s, dps = [], [], []
|
| 463 |
+
for lag in range(1, min(max_lag+1, n)):
|
| 464 |
+
x = G[:, :n-lag].astype(float)
|
| 465 |
+
y = G[:, lag: ].astype(float)
|
|
|
|
|
|
|
| 466 |
xm, ym = x - x.mean(0), y - y.mean(0)
|
| 467 |
+
num = (xm*ym).sum(0)
|
| 468 |
+
den = np.sqrt((xm**2).sum(0) * (ym**2).sum(0))
|
| 469 |
with np.errstate(invalid='ignore', divide='ignore'):
|
| 470 |
+
r = np.where(den > 0, num/den, 0.0)
|
| 471 |
r2 = np.clip(r**2, 0, 1)
|
| 472 |
|
| 473 |
+
p1 = x.mean(0)/2.0; p2 = y.mean(0)/2.0
|
| 474 |
+
p11 = ((x==2)&(y==2)).mean(0)/2.0
|
| 475 |
+
D = p11 - p1*p2
|
|
|
|
| 476 |
with np.errstate(invalid='ignore', divide='ignore'):
|
| 477 |
+
Dmax = np.where(D<0,
|
| 478 |
+
np.minimum(p1*(1-p2),(1-p1)*p2),
|
| 479 |
+
np.minimum(p1*p2,(1-p1)*(1-p2)))
|
| 480 |
+
dp = np.where(Dmax>0, np.abs(D/Dmax), 0.0)
|
| 481 |
|
| 482 |
+
dist = np.abs(bp_pos[lag:] - bp_pos[:n-lag])
|
| 483 |
dists.append(dist); r2s.append(r2); dps.append(dp)
|
| 484 |
|
| 485 |
if not dists:
|
|
|
|
| 488 |
|
| 489 |
|
| 490 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 491 |
+
# PLOT: LD DECAY β FIXED: per-chrom cap = 80 markers (was 120)
|
| 492 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 493 |
+
def plot_ld_decay_bp(genotypes, chromosomes, positions, save_path, max_m=80):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 494 |
_style()
|
| 495 |
unique_chroms = sorted(set(chromosomes),
|
| 496 |
key=lambda x: (int(x) if str(x).isdigit() else 999, str(x)))
|
|
|
|
| 497 |
chrom_to_idx = {}
|
| 498 |
for gi, ch in enumerate(chromosomes):
|
| 499 |
chrom_to_idx.setdefault(str(ch), []).append(gi)
|
| 500 |
|
| 501 |
+
bp_arr = np.array(positions, dtype=float)
|
| 502 |
+
if bp_arr.max() == 0:
|
| 503 |
+
bp_arr = np.arange(len(positions), dtype=float) * 1000
|
|
|
|
|
|
|
|
|
|
| 504 |
|
| 505 |
all_dist, all_r2, all_dp, all_ch = [], [], [], []
|
| 506 |
chrom_stats = {}
|
| 507 |
+
rng = np.random.default_rng(0)
|
| 508 |
|
| 509 |
for ch in unique_chroms:
|
| 510 |
idxs = chrom_to_idx.get(str(ch), [])
|
| 511 |
+
if len(idxs) < 4: continue
|
|
|
|
| 512 |
if len(idxs) > max_m:
|
| 513 |
+
idxs = sorted(rng.choice(idxs, max_m, replace=False).tolist())
|
| 514 |
|
| 515 |
G_ch = genotypes[:, idxs].copy().astype(float)
|
| 516 |
+
bp_ch = bp_arr[idxs]
|
| 517 |
+
srt = np.argsort(bp_ch)
|
| 518 |
+
G_ch = G_ch[:, srt]; bp_ch = bp_ch[srt]
|
|
|
|
|
|
|
|
|
|
| 519 |
|
| 520 |
+
dist, r2, dp = _compute_ld_pairs_bp(G_ch, bp_ch, max_lag=50)
|
| 521 |
+
if not len(dist): continue
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 522 |
|
| 523 |
+
all_dist.extend(dist.tolist()); all_r2.extend(r2.tolist())
|
| 524 |
+
all_dp.extend(dp.tolist()); all_ch.extend([str(ch)]*len(dist))
|
| 525 |
chrom_stats[str(ch)] = {
|
| 526 |
+
'n_markers': len(idxs), 'n_pairs': len(dist),
|
| 527 |
+
'mean_r2': float(np.mean(r2)), 'mean_dprime': float(np.mean(dp)),
|
| 528 |
+
'max_r2': float(np.max(r2)),
|
|
|
|
|
|
|
| 529 |
'max_dist_bp': float(dist.max()) if len(dist) else 0,
|
| 530 |
}
|
| 531 |
|
| 532 |
if not all_dist:
|
| 533 |
+
fig, ax = plt.subplots(figsize=(10,6), facecolor=BG)
|
| 534 |
+
ax.text(0.5, 0.5, 'No LD data available (need β₯4 markers/chr)',
|
| 535 |
ha='center', va='center', transform=ax.transAxes,
|
| 536 |
fontsize=13, color=TEXT_C)
|
| 537 |
+
plt.savefig(save_path, dpi=100, bbox_inches='tight')
|
| 538 |
plt.close(fig)
|
| 539 |
return chrom_stats, "No LD data available."
|
| 540 |
|
|
|
|
| 542 |
r2_arr = np.array(all_r2, dtype=float)
|
| 543 |
ch_arr = np.array(all_ch, dtype=str)
|
| 544 |
|
| 545 |
+
max_bp = float(np.percentile(dist_arr, 99)) or dist_arr.max()
|
| 546 |
+
scale, unit_label = (1_000_000,'Mb') if max_bp>=1e6 else (1_000,'kb') if max_bp>=1000 else (1,'bp')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 547 |
dist_scaled = dist_arr / scale
|
| 548 |
max_scaled = max_bp / scale
|
| 549 |
|
|
|
|
| 550 |
mask = dist_arr <= max_bp
|
| 551 |
+
dv, rv = dist_scaled[mask], r2_arr[mask]
|
| 552 |
+
bins = np.linspace(0, max_scaled, 81)
|
|
|
|
|
|
|
|
|
|
| 553 |
ctrs, meds = [], []
|
| 554 |
+
for i in range(80):
|
| 555 |
+
m = (dv>=bins[i]) & (dv<bins[i+1])
|
| 556 |
+
if m.sum()>=3:
|
| 557 |
+
ctrs.append((bins[i]+bins[i+1])/2.)
|
| 558 |
meds.append(np.median(rv[m]))
|
| 559 |
|
| 560 |
+
ctrs = np.array(ctrs); meds = np.array(meds)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 561 |
xs_smooth = ys_smooth = None
|
| 562 |
+
ann = {}
|
| 563 |
if len(ctrs) >= 5:
|
| 564 |
+
k = min(3, len(ctrs)-1)
|
| 565 |
xs_smooth = np.linspace(ctrs[0], ctrs[-1], 2000)
|
| 566 |
spl = make_interp_spline(ctrs, meds, k=k)
|
| 567 |
ys_smooth = np.clip(spl(xs_smooth), 0, 1)
|
| 568 |
+
r2_start = ys_smooth[0] if ys_smooth[0]>0 else (meds[0] if len(meds) else 0.5)
|
| 569 |
+
for thr_name, thr_val in [('half',r2_start/2.),('r2_02',0.2),('r2_01',0.1)]:
|
| 570 |
+
ix = np.where(ys_smooth<=thr_val)[0]
|
| 571 |
+
if len(ix): ann[thr_name] = float(xs_smooth[ix[0]])
|
| 572 |
|
| 573 |
+
def _fmt(v): return f"{v:.2f} {unit_label}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 574 |
ilines = []
|
| 575 |
if 'half' in ann:
|
| 576 |
+
speed = "rapid" if ann['half']<0.5 else "moderate" if ann['half']<5 else "slow"
|
| 577 |
+
ilines.append(f"β’ LD half-decay: {_fmt(ann['half'])} [{speed}]")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 578 |
else:
|
| 579 |
+
ilines.append("β’ Half-decay not reached β LD persists across full range")
|
|
|
|
| 580 |
if 'r2_02' in ann:
|
| 581 |
+
ilines.append(f"β’ rΒ²<0.2 (GWAS tagging): {_fmt(ann['r2_02'])}")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 582 |
if 'r2_01' in ann:
|
| 583 |
+
ilines.append(f"β’ rΒ²<0.1 (independence): {_fmt(ann['r2_01'])}")
|
| 584 |
+
ilines.append(f"β’ Mean rΒ²={np.mean(r2_arr):.3f} | Mean D'={np.mean(all_dp):.3f}")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 585 |
ld_interp = "\n".join(ilines)
|
| 586 |
|
| 587 |
+
chrom_color = {str(ch): CHROM_PALETTE[i%len(CHROM_PALETTE)]
|
|
|
|
| 588 |
for i, ch in enumerate(unique_chroms)}
|
| 589 |
|
| 590 |
+
fig = plt.figure(figsize=(14,9), facecolor=BG)
|
| 591 |
+
gs = fig.add_gridspec(2,1, height_ratios=[3.8,1], hspace=0.08)
|
| 592 |
ax = fig.add_subplot(gs[0])
|
| 593 |
+
axt = fig.add_subplot(gs[1]); axt.axis('off')
|
|
|
|
| 594 |
ax.set_facecolor('#EEE8FA')
|
| 595 |
|
|
|
|
| 596 |
for ch in unique_chroms:
|
| 597 |
+
key = str(ch); cmsk = (ch_arr==key) & mask
|
| 598 |
+
if not cmsk.any(): continue
|
|
|
|
|
|
|
| 599 |
ax.scatter(dist_scaled[cmsk], r2_arr[cmsk],
|
| 600 |
c=chrom_color[key], s=6, alpha=0.38,
|
| 601 |
linewidths=0, zorder=2, label=key)
|
| 602 |
|
| 603 |
+
if xs_smooth is not None:
|
| 604 |
+
ax.fill_between(xs_smooth, 0, ys_smooth, color='#22C55E', alpha=0.22, zorder=3)
|
| 605 |
+
ax.plot(xs_smooth, ys_smooth, color=GREEN_C, lw=2.4, zorder=4, label='Median rΒ²')
|
| 606 |
+
|
| 607 |
+
ax.axhline(0.2, color='#111827', ls='--', lw=1.6, alpha=0.75, zorder=5, label='rΒ²=0.2')
|
| 608 |
+
ann_styles = {'half':(GOLD_C,'Β½ decay',0.50,0.10),
|
| 609 |
+
'r2_02':(RED_C,'rΒ²=0.2',0.20,0.08),
|
| 610 |
+
'r2_01':(TEAL_C,'rΒ²=0.1',0.10,0.06)}
|
| 611 |
+
for akey,(col,lbl,r2ref,offy) in ann_styles.items():
|
| 612 |
+
if akey not in ann: continue
|
| 613 |
+
xv = ann[akey]
|
| 614 |
+
ax.axvline(xv, color=col, ls=':', lw=1.9, alpha=0.88, zorder=6)
|
| 615 |
+
ax.annotate(f'{lbl}\n{_fmt(xv)}', xy=(xv,r2ref),
|
| 616 |
+
xytext=(xv+max_scaled*0.012, r2ref+offy),
|
| 617 |
+
fontsize=8.5, fontweight='bold', color=col,
|
| 618 |
+
arrowprops=dict(arrowstyle='->', color=col, lw=1.2),
|
| 619 |
+
bbox=dict(boxstyle='round,pad=0.3', fc=BG, ec=col, alpha=0.92, lw=1.1),
|
| 620 |
+
zorder=7)
|
| 621 |
+
|
| 622 |
+
ax.set_xlim(0, max_scaled); ax.set_ylim(0, 1.05)
|
| 623 |
+
ax.set_xlabel(f'Physical distance ({unit_label})', fontsize=12, fontweight='bold')
|
| 624 |
+
ax.set_ylabel('LD estimate (RΒ²)', fontsize=12, fontweight='bold')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 625 |
ax.set_title('LD Decay by Chromosome (Physical Distance)',
|
| 626 |
fontsize=14, fontweight='bold', color=TEXT_C, pad=10)
|
| 627 |
ax.xaxis.grid(True, color=GRID_C, lw=0.6, alpha=0.9)
|
| 628 |
ax.yaxis.grid(True, color=GRID_C, lw=0.6, alpha=0.9)
|
| 629 |
ax.set_axisbelow(True)
|
| 630 |
|
|
|
|
| 631 |
handles, labels = ax.get_legend_handles_labels()
|
| 632 |
+
special = [(h,l) for h,l in zip(handles,labels) if l in ('Median rΒ²','rΒ²=0.2')]
|
| 633 |
+
chrs = [(h,l) for h,l in zip(handles,labels) if l not in ('Median rΒ²','rΒ²=0.2')]
|
| 634 |
+
ncols_l = max(1,(len(chrs)+9)//10)
|
| 635 |
+
leg_h = [h for h,_ in special]+[h for h,_ in chrs]
|
| 636 |
+
leg_l = [l for _,l in special]+[f'Chr {l}' for _,l in chrs]
|
| 637 |
+
ax.legend(leg_h, leg_l, title='Chr', title_fontsize=9, fontsize=7.5,
|
| 638 |
+
loc='upper right', ncol=ncols_l, framealpha=0.93,
|
| 639 |
+
markerscale=2.2, handlelength=1.3)
|
| 640 |
+
|
| 641 |
+
axt.text(0.005, 0.98, "LD DECAY INTERPRETATION\n"+"β"*70+"\n"+ld_interp,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 642 |
transform=axt.transAxes, va='top', ha='left',
|
| 643 |
fontsize=8.5, color=TEXT_C, fontfamily='monospace',
|
| 644 |
+
bbox=dict(boxstyle='round,pad=0.5', facecolor='#EDE9FE',
|
| 645 |
+
edgecolor=GRID_C, alpha=0.95))
|
|
|
|
| 646 |
|
| 647 |
+
plt.savefig(save_path, dpi=110, bbox_inches='tight', facecolor=BG)
|
| 648 |
plt.close(fig)
|
| 649 |
return chrom_stats, ld_interp
|
| 650 |
|
|
|
|
| 652 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 653 |
# PLOT: MODEL COMPARISON
|
| 654 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
|
|
|
| 655 |
def plot_model_comparison(model_pvals, save_path):
|
| 656 |
_style()
|
| 657 |
models = list(model_pvals.keys())
|
| 658 |
+
n = len(models)
|
| 659 |
+
pairs = [(models[i],models[j]) for i in range(n) for j in range(i+1,n)]
|
| 660 |
+
if not pairs: return
|
| 661 |
+
ncols = min(3, len(pairs))
|
| 662 |
+
nrows = (len(pairs)+ncols-1)//ncols
|
|
|
|
|
|
|
|
|
|
| 663 |
fig, axes = plt.subplots(nrows, ncols,
|
| 664 |
figsize=(5.5*ncols, 5*nrows),
|
| 665 |
facecolor=BG, squeeze=False)
|
| 666 |
+
for idx,(ma,mb) in enumerate(pairs):
|
| 667 |
+
r,c = divmod(idx, ncols); ax = axes[r][c]; ax.set_facecolor(PANEL)
|
| 668 |
+
pa = -np.log10(np.clip(model_pvals[ma],1e-300,1))
|
| 669 |
+
pb = -np.log10(np.clip(model_pvals[mb],1e-300,1))
|
| 670 |
+
corr = np.corrcoef(pa,pb)[0,1]
|
| 671 |
+
ax.scatter(pa,pb,alpha=0.40,s=12,color=MODEL_COLORS.get(ma,ACCENT),edgecolors='none')
|
| 672 |
+
mx = max(pa.max(),pb.max())*1.05
|
| 673 |
+
ax.plot([0,mx],[0,mx],color=GOLD_C,ls='--',lw=1.2)
|
| 674 |
+
ax.set_xlabel(f'{ma} βlogββ(P)',fontsize=9,fontweight='bold')
|
| 675 |
+
ax.set_ylabel(f'{mb} βlogββ(P)',fontsize=9,fontweight='bold')
|
| 676 |
+
ax.set_title(f'{ma} vs {mb} (r={corr:.3f})',fontsize=10,fontweight='bold')
|
| 677 |
+
ax.grid(True,color=GRID_C,lw=0.6,alpha=0.5)
|
| 678 |
+
for extra in range(len(pairs),nrows*ncols):
|
| 679 |
+
r,c = divmod(extra,ncols); axes[r][c].set_visible(False)
|
| 680 |
+
plt.suptitle('Model P-value Concordance',fontsize=12,fontweight='bold',color=TEXT_C)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 681 |
plt.tight_layout(pad=1.5)
|
| 682 |
+
plt.savefig(save_path,dpi=100,bbox_inches='tight',facecolor=BG)
|
| 683 |
plt.close(fig)
|
| 684 |
|
| 685 |
|
| 686 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 687 |
+
# PLOT: PHENOTYPE
|
| 688 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
|
|
|
| 689 |
def plot_phenotype(phenotypes, save_path):
|
| 690 |
_style()
|
| 691 |
pv = phenotypes[~np.isnan(phenotypes)]
|
| 692 |
+
fig, axes = plt.subplots(1,2,figsize=(11,4.5),facecolor=BG)
|
|
|
|
| 693 |
ax = axes[0]; ax.set_facecolor(PANEL)
|
| 694 |
+
ax.hist(pv,bins=30,color=ACCENT,alpha=0.72,edgecolor='white',lw=0.5)
|
| 695 |
+
ax.axvline(np.mean(pv),color=RED_C,ls='--',lw=1.6,
|
| 696 |
label=f'Mean={np.mean(pv):.2f}')
|
| 697 |
+
ax.axvline(np.median(pv),color=GOLD_C,ls=':',lw=1.6,
|
| 698 |
label=f'Median={np.median(pv):.2f}')
|
| 699 |
+
ax.set_xlabel('Phenotype Value',fontsize=11,fontweight='bold')
|
| 700 |
+
ax.set_ylabel('Frequency',fontsize=11,fontweight='bold')
|
| 701 |
+
ax.set_title('Phenotype Distribution',fontsize=12,fontweight='bold')
|
| 702 |
+
ax.legend(fontsize=9); ax.grid(True,color=GRID_C,lw=0.7)
|
| 703 |
+
sw_s,sw_p = stats.shapiro(pv[:5000])
|
| 704 |
+
ax.text(0.97,0.95,f'Shapiro-Wilk p={sw_p:.3e}',
|
| 705 |
+
transform=ax.transAxes,ha='right',va='top',fontsize=8.5,
|
| 706 |
+
bbox=dict(boxstyle='round',facecolor=BG,edgecolor=GRID_C,alpha=0.9))
|
|
|
|
|
|
|
|
|
|
| 707 |
ax = axes[1]; ax.set_facecolor(PANEL)
|
| 708 |
+
stats.probplot(pv,dist='norm',plot=ax)
|
| 709 |
+
ax.get_lines()[0].set(color=ACCENT,markersize=3,alpha=0.6)
|
| 710 |
+
ax.get_lines()[1].set(color=RED_C,lw=1.5)
|
| 711 |
+
ax.set_title('Normal Q-Q (Phenotype)',fontsize=12,fontweight='bold')
|
| 712 |
+
ax.grid(True,color=GRID_C,lw=0.7)
|
|
|
|
| 713 |
plt.tight_layout(pad=1.5)
|
| 714 |
+
plt.savefig(save_path,dpi=100,bbox_inches='tight',facecolor=BG)
|
| 715 |
plt.close(fig)
|
| 716 |
|
| 717 |
|
| 718 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 719 |
+
# MAIN ANALYSIS β FIXED: persistent paths, progress yields
|
| 720 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
|
|
|
| 721 |
def run_analysis(input_file, miss_sample, miss_marker, maf_thresh,
|
| 722 |
+
run_glm, run_mlm, run_cmlm, run_bslmm, run_farmcpu,
|
| 723 |
+
progress=gr.Progress(track_tqdm=True)):
|
| 724 |
try:
|
| 725 |
if input_file is None:
|
| 726 |
return ("β οΈ Upload a CSV file first.",
|
| 727 |
+
None,None,None,None,None,None)
|
| 728 |
|
| 729 |
+
# ββ FIXED: use a persistent, named output folder ββββββββββββββββββββββ
|
| 730 |
+
run_id = pd.Timestamp.now().strftime("%Y%m%d_%H%M%S")
|
| 731 |
+
rdir = OUTPUT_DIR / run_id
|
| 732 |
+
pdir = rdir / 'plots'
|
| 733 |
+
for d in [rdir, pdir]: d.mkdir(parents=True, exist_ok=True)
|
| 734 |
|
| 735 |
+
ms_t = miss_sample/100.0
|
| 736 |
+
mm_t = miss_marker/100.0
|
| 737 |
+
mf_t = maf_thresh /100.0
|
| 738 |
|
| 739 |
+
progress(0.05, desc="Parsing CSVβ¦")
|
|
|
|
| 740 |
(sids, pheno, geno,
|
| 741 |
mnames, chroms, positions) = parse_input_csv(input_file)
|
| 742 |
n_s, n_m = len(sids), len(mnames)
|
|
|
|
| 743 |
|
| 744 |
+
# ββ QC βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 745 |
+
progress(0.10, desc="Quality controlβ¦")
|
| 746 |
+
miss_m_r = np.isnan(geno).sum(0) / max(n_s,1)
|
| 747 |
+
miss_s_r = np.isnan(geno).sum(1) / max(n_m,1)
|
| 748 |
maf_arr = np.zeros(n_m)
|
| 749 |
for i in range(n_m):
|
| 750 |
+
v = geno[:,i]; v = v[~np.isnan(v)]
|
| 751 |
if len(v):
|
| 752 |
+
f = np.mean(v)/2.0; maf_arr[i] = min(f,1-f)
|
|
|
|
| 753 |
|
| 754 |
qc_m = (miss_m_r < mm_t) & (maf_arr >= mf_t)
|
| 755 |
qc_s = miss_s_r < ms_t
|
| 756 |
fallback = ""
|
| 757 |
+
for rs,rm in [(ms_t,mm_t),(.6,.6),(.7,.7),(.8,.8),(.9,.9),(1.,1.)]:
|
|
|
|
| 758 |
qm = (miss_m_r < rm) & (maf_arr >= mf_t)
|
| 759 |
qs = miss_s_r < rs
|
| 760 |
if qs.sum() >= 10:
|
| 761 |
+
qc_m,qc_s = qm,qs
|
| 762 |
+
if rs>ms_t or rm>mm_t:
|
| 763 |
+
fallback=(f"\nβ οΈ QC relaxed β sample<{rs*100:.0f}% / "
|
| 764 |
+
f"marker<{rm*100:.0f}%\n")
|
| 765 |
break
|
| 766 |
|
| 767 |
+
geno_q = geno[np.ix_(qc_s,qc_m)].copy()
|
| 768 |
+
pheno_q = pheno[qc_s]; sids_q = sids[qc_s]
|
| 769 |
+
mn_q = [mnames[i] for i in range(n_m) if qc_m[i]]
|
| 770 |
+
ch_q = [chroms[i] for i in range(n_m) if qc_m[i]]
|
|
|
|
| 771 |
pos_q = [positions[i] for i in range(n_m) if qc_m[i]]
|
| 772 |
n_q = len(mn_q)
|
|
|
|
| 773 |
|
| 774 |
+
col_mu = np.nanmean(geno_q,0); col_mu = np.where(np.isnan(col_mu),0,col_mu)
|
|
|
|
|
|
|
| 775 |
for i in range(geno_q.shape[1]):
|
| 776 |
+
mk = np.isnan(geno_q[:,i])
|
| 777 |
+
if mk.any(): geno_q[mk,i] = col_mu[i]
|
| 778 |
|
| 779 |
valid = ~np.isnan(pheno_q)
|
| 780 |
geno_q = geno_q[valid]; pheno_q = pheno_q[valid]; sids_q = sids_q[valid]
|
|
|
|
| 782 |
if len(sids_q) < 10:
|
| 783 |
return (f"## β οΈ Only {len(sids_q)} samples passed QC. "
|
| 784 |
"Try increasing missing-rate sliders.",
|
| 785 |
+
None,None,None,None,None,None)
|
| 786 |
|
| 787 |
+
bonf = 0.05 / n_q; bonf_log = -np.log10(bonf)
|
|
|
|
| 788 |
|
| 789 |
+
progress(0.18, desc="Computing kinship matrixβ¦")
|
|
|
|
| 790 |
K = compute_kinship(geno_q)
|
| 791 |
|
| 792 |
+
# ββ Models βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 793 |
+
model_pvals, model_betas, model_ses = {}, {}, {}
|
| 794 |
+
step_base = 0.20; n_models = sum([run_glm,run_mlm,run_cmlm,run_bslmm,run_farmcpu])
|
| 795 |
+
step_size = 0.40 / max(n_models,1); step_i = 0
|
| 796 |
|
| 797 |
if run_glm:
|
| 798 |
+
progress(step_base+step_i*step_size, desc="GLMβ¦")
|
| 799 |
+
pv,bv,sv,rv = model_glm(geno_q,pheno_q)
|
| 800 |
+
model_pvals['GLM']=pv; model_betas['GLM']=bv; model_ses['GLM']=sv; step_i+=1
|
| 801 |
|
| 802 |
if run_mlm:
|
| 803 |
+
progress(step_base+step_i*step_size, desc="MLM (kinship PCs)β¦")
|
| 804 |
+
pv,bv,sv,rv = model_mlm(geno_q,pheno_q,K)
|
| 805 |
+
model_pvals['MLM']=pv; model_betas['MLM']=bv; model_ses['MLM']=sv; step_i+=1
|
| 806 |
|
| 807 |
if run_cmlm:
|
| 808 |
+
progress(step_base+step_i*step_size, desc="CMLM (compressed kinship)β¦")
|
| 809 |
+
pv,bv,sv,rv = model_cmlm(geno_q,pheno_q,K)
|
| 810 |
+
model_pvals['CMLM']=pv; model_betas['CMLM']=bv; model_ses['CMLM']=sv; step_i+=1
|
| 811 |
|
| 812 |
if run_bslmm:
|
| 813 |
+
progress(step_base+step_i*step_size,
|
| 814 |
+
desc="BSLMM (ElasticNet/Ridge + bootstrap)β¦ [may take 1-2 min]")
|
| 815 |
+
pv,bv = model_bslmm(geno_q,pheno_q)
|
| 816 |
+
model_pvals['BSLMM']=pv; model_betas['BSLMM']=bv; step_i+=1
|
| 817 |
|
| 818 |
if run_farmcpu:
|
| 819 |
+
progress(step_base+step_i*step_size, desc="FarmCPU (iterative QTN control)β¦")
|
| 820 |
+
pv,bv,sv = model_farmcpu(geno_q,pheno_q,K)
|
| 821 |
+
model_pvals['FarmCPU']=pv; model_betas['FarmCPU']=bv; model_ses['FarmCPU']=sv
|
| 822 |
|
| 823 |
if not model_pvals:
|
| 824 |
+
return ("## β οΈ No models selected.",None,None,None,None,None,None)
|
|
|
|
| 825 |
|
| 826 |
+
# ββ Results CSV βββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 827 |
+
progress(0.62, desc="Building results tableβ¦")
|
| 828 |
+
df = pd.DataFrame({'Marker':mn_q,'Chromosome':ch_q,'Position_bp':pos_q})
|
| 829 |
+
for mname,pv in model_pvals.items():
|
| 830 |
df[f'{mname}_P'] = pv
|
| 831 |
+
df[f'{mname}_LOD'] = -np.log10(np.clip(pv,1e-300,1))
|
| 832 |
+
df[f'{mname}_Sig'] = (pv<bonf).astype(int)
|
| 833 |
+
if mname in model_betas: df[f'{mname}_Beta'] = model_betas[mname]
|
|
|
|
| 834 |
|
|
|
|
| 835 |
sig_cols = [f'{m}_Sig' for m in model_pvals]
|
| 836 |
+
df['Consensus_Sig'] = (df[sig_cols].sum(1)>=max(1,len(sig_cols)//2)).astype(int)
|
| 837 |
df = df.sort_values(f"{list(model_pvals.keys())[0]}_P").reset_index(drop=True)
|
| 838 |
+
df.insert(0,'Rank',range(1,len(df)+1))
|
|
|
|
| 839 |
|
| 840 |
+
csv_path = str(rdir/'gwas_results.csv')
|
| 841 |
+
top_path = str(rdir/'top_significant.csv')
|
| 842 |
+
df.to_csv(csv_path, index=False)
|
| 843 |
+
any_sig = df[sig_cols].sum(1)>0
|
| 844 |
+
df[any_sig].to_csv(top_path, index=False)
|
| 845 |
|
| 846 |
+
# ββ Plots ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 847 |
+
progress(0.65, desc="Phenotype distribution plotβ¦")
|
| 848 |
+
ph_path = str(pdir/'phenotype_dist.png')
|
| 849 |
plot_phenotype(pheno_q, ph_path)
|
| 850 |
|
| 851 |
+
progress(0.72, desc="Manhattan plotsβ¦")
|
| 852 |
+
man_path = str(pdir/'manhattan_lod.png')
|
| 853 |
plot_manhattan_multi(mn_q, ch_q, model_pvals, bonf, man_path)
|
| 854 |
|
| 855 |
+
progress(0.80, desc="QQ plotsβ¦")
|
| 856 |
+
qq_path = str(pdir/'qq_plot.png')
|
| 857 |
lam_dict = plot_qq_multi(model_pvals, bonf, qq_path)
|
| 858 |
|
| 859 |
+
progress(0.87, desc="LD decay (bp)β¦")
|
| 860 |
+
ld_path = str(pdir/'ld_decay_bp.png')
|
| 861 |
ld_stats, ld_interp = plot_ld_decay_bp(geno_q, ch_q, pos_q, ld_path)
|
| 862 |
+
ld_df = pd.DataFrame([{'Chromosome':k,**v} for k,v in ld_stats.items()])
|
| 863 |
+
ld_df.to_csv(str(rdir/'ld_decay_stats.csv'), index=False)
|
| 864 |
|
| 865 |
+
progress(0.93, desc="Model comparison plotβ¦")
|
| 866 |
+
cmp_path = str(pdir/'model_comparison.png')
|
| 867 |
plot_model_comparison(model_pvals, cmp_path)
|
| 868 |
|
| 869 |
+
# ββ ZIP ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 870 |
+
progress(0.96, desc="Packaging ZIPβ¦")
|
| 871 |
+
zip_path = str(OUTPUT_DIR / f'GWAS_Results_{run_id}.zip')
|
| 872 |
+
with zipfile.ZipFile(zip_path,'w',zipfile.ZIP_DEFLATED) as zf:
|
| 873 |
+
for root,_,files in os.walk(str(rdir)):
|
| 874 |
for f in files:
|
| 875 |
+
fp = os.path.join(root,f)
|
| 876 |
+
zf.write(fp, os.path.relpath(fp, str(rdir)))
|
| 877 |
|
| 878 |
+
# ββ Summary markdown βββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 879 |
def _mdt(d, n=15):
|
| 880 |
+
sub = d.head(n); cols = sub.columns.tolist()
|
|
|
|
| 881 |
def _f(v):
|
| 882 |
+
if isinstance(v,float):
|
| 883 |
return f"{v:.3e}" if (v!=0 and abs(v)<0.001) else f"{v:.4f}"
|
| 884 |
return str(v)
|
| 885 |
+
sep = "| "+" | ".join(["---"]*len(cols))+" |"
|
| 886 |
rows = ["| "+" | ".join(_f(row[c]) for c in cols)+" |"
|
| 887 |
+
for _,row in sub.iterrows()]
|
| 888 |
+
return "\n".join(["| "+" | ".join(cols)+" |",sep]+rows)
|
| 889 |
|
| 890 |
model_summary_rows = "\n".join(
|
| 891 |
+
f"| {m} | **{int((pv<bonf).sum())}** | Ξ»={lam_dict.get(m,0):.3f} | "
|
| 892 |
f"{'β οΈ inflation' if lam_dict.get(m,1)>1.05 else 'β
ok'} |"
|
| 893 |
+
for m,pv in model_pvals.items())
|
|
|
|
| 894 |
|
| 895 |
+
top_cols = (['Rank','Marker','Chromosome','Position_bp']+
|
| 896 |
+
[f'{m}_P' for m in model_pvals]+['Consensus_Sig'])
|
|
|
|
| 897 |
top_cols = [c for c in top_cols if c in df.columns]
|
| 898 |
|
| 899 |
summary = f"""
|
| 900 |
+
## β
GWAS Analysis Complete β v8.1
|
| 901 |
|
| 902 |
### π QC Summary
|
| 903 |
| Metric | Value |
|
|
|
|
| 917 |
|
| 918 |
**Bonferroni threshold:** P < {bonf:.3e} | βlogββP > {bonf_log:.2f}
|
| 919 |
|
| 920 |
+
### 𧬠LD Decay
|
| 921 |
{ld_interp}
|
| 922 |
|
| 923 |
### π Top 15 Markers
|
| 924 |
{_mdt(df[top_cols])}
|
| 925 |
|
| 926 |
---
|
| 927 |
+
**Output saved to:** `{rdir}`
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 928 |
"""
|
| 929 |
+
progress(1.0, desc="Done! β
")
|
| 930 |
+
# Return all actual file paths (not None) so Gradio can serve them
|
| 931 |
+
return (summary,
|
| 932 |
+
man_path, ld_path, qq_path,
|
| 933 |
cmp_path, ph_path, zip_path)
|
| 934 |
|
| 935 |
except Exception as e:
|
| 936 |
import traceback
|
| 937 |
return (f"## β Error\n```\n{e}\n\n{traceback.format_exc()}\n```",
|
| 938 |
+
None,None,None,None,None,None)
|
| 939 |
|
| 940 |
|
| 941 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 942 |
# GRADIO UI
|
| 943 |
# βββββββββββββββββββββββββββββββββββββββββββββββοΏ½οΏ½ββββββββββββββ
|
|
|
|
| 944 |
CSS = """
|
| 945 |
.gradio-container{font-family:'Segoe UI',Tahoma,sans-serif}
|
| 946 |
h1{color:#2D1B5E;border-bottom:3px solid #7C3AED;padding-bottom:8px}
|
| 947 |
+
.progress-bar{background:#7C3AED!important}
|
| 948 |
"""
|
| 949 |
|
| 950 |
+
with gr.Blocks(css=CSS, title="MTA GWAS v8.1") as app:
|
| 951 |
|
| 952 |
gr.Markdown("""
|
| 953 |
+
# 𧬠GWAS Analysis Platform v8.1
|
| 954 |
+
### 5-Model MRmlm Suite | LD Decay in bp | Persistent Outputs | Progress Tracking
|
| 955 |
---
|
| 956 |
""")
|
| 957 |
|
|
|
|
| 960 |
gr.Markdown("""
|
| 961 |
### π CSV Format (3-row header)
|
| 962 |
```
|
| 963 |
+
ID, Phenotype, M1, M2, ...
|
| 964 |
+
-, Chr, 1, 1, ...
|
| 965 |
+
-, Pos, 134521, ..., ...
|
| 966 |
+
IRRI-1, 25.34, 0, 2, ...
|
|
|
|
| 967 |
```
|
| 968 |
**Genotypes:** 0/1/2 (β1 or blank = missing)
|
| 969 |
""")
|
|
|
|
| 971 |
|
| 972 |
with gr.Column(scale=1):
|
| 973 |
gr.Markdown("### βοΈ QC Parameters")
|
| 974 |
+
miss_sample = gr.Slider(5,100,value=30,step=5,
|
| 975 |
label="Max sample missing rate (%)")
|
| 976 |
+
miss_marker = gr.Slider(5,100,value=30,step=5,
|
| 977 |
label="Max marker missing rate (%)")
|
| 978 |
+
maf_thr = gr.Slider(0,25,value=3,step=1,
|
| 979 |
label="Min MAF (%)")
|
| 980 |
|
| 981 |
with gr.Column(scale=1):
|
|
|
|
| 983 |
chk_glm = gr.Checkbox(value=True, label="GLM β General Linear Model")
|
| 984 |
chk_mlm = gr.Checkbox(value=True, label="MLM β Mixed Linear Model")
|
| 985 |
chk_cmlm = gr.Checkbox(value=True, label="CMLM β Compressed MLM")
|
| 986 |
+
chk_bslmm = gr.Checkbox(value=False, label="BSLMM β Bayesian Sparse LMM β οΈ slow")
|
| 987 |
chk_farmcpu = gr.Checkbox(value=True, label="FarmCPU β Fixed & Random")
|
| 988 |
|
| 989 |
+
gr.Markdown("""
|
| 990 |
+
> **β±οΈ Speed guide:** GLM/MLM/CMLM/FarmCPU take ~1β3 min for 3000 markers.
|
| 991 |
+
> BSLMM adds ~2β4 min extra. Disable it for quick runs.
|
| 992 |
+
""")
|
| 993 |
+
|
| 994 |
run_btn = gr.Button("π Run GWAS Analysis", variant="primary", size="lg")
|
| 995 |
gr.Markdown("---")
|
| 996 |
|
| 997 |
summary_out = gr.Markdown()
|
| 998 |
|
| 999 |
with gr.Row():
|
| 1000 |
+
man_out = gr.Image(label="πΊοΈ Manhattan Plots")
|
| 1001 |
+
ld_out = gr.Image(label="𧬠LD Decay (bp/kb/Mb)")
|
| 1002 |
|
| 1003 |
with gr.Row():
|
| 1004 |
+
qq_out = gr.Image(label="π QQ Plots + Ξ»")
|
| 1005 |
cmp_out = gr.Image(label="βοΈ Model Concordance")
|
| 1006 |
|
| 1007 |
with gr.Row():
|
| 1008 |
ph_out = gr.Image(label="π Phenotype Distribution")
|
| 1009 |
dl_out = gr.File(label="π¦ Download All Results (ZIP)")
|
| 1010 |
|
| 1011 |
+
gr.Markdown("---\n**MTA GWAS v8.1** | Persistent output paths | Progress tracking")
|
|
|
|
|
|
|
|
|
|
| 1012 |
|
| 1013 |
run_btn.click(
|
| 1014 |
fn=run_analysis,
|
|
|
|
| 1016 |
chk_glm, chk_mlm, chk_cmlm, chk_bslmm, chk_farmcpu],
|
| 1017 |
outputs=[summary_out, man_out, ld_out, qq_out,
|
| 1018 |
cmp_out, ph_out, dl_out],
|
| 1019 |
+
show_progress="full",
|
| 1020 |
)
|
| 1021 |
|
| 1022 |
if __name__ == "__main__":
|
| 1023 |
+
app.launch(share=False, show_error=True,
|
| 1024 |
+
max_threads=4) # prevent thread exhaustion
|