Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,24 +1,13 @@
|
|
| 1 |
# -*- coding: utf-8 -*-
|
| 2 |
"""
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
=========================================================
|
| 12 |
-
FIXES APPLIED:
|
| 13 |
-
β
LD Decay: Proper Hill-Weir (1988) model with population size estimation
|
| 14 |
-
β
Model selection: All models work correctly (GLM, MLM, CMLM, BSLMM, FarmCPU)
|
| 15 |
-
β
Manhattan plot model switching: Dropdown properly updates plots
|
| 16 |
-
β
Matrix dimensionality: Fixed all linear algebra operations
|
| 17 |
-
β
BSLMM: Fixed cross-validation and bootstrapping
|
| 18 |
-
β
FarmCPU: Fixed iterative conditioning
|
| 19 |
-
β
Kinship matrix: Now positive definite
|
| 20 |
-
β
ALL plots: White background, black/dark text for publication quality
|
| 21 |
-
β
Fixed tabulate dependency issue
|
| 22 |
"""
|
| 23 |
|
| 24 |
import gradio as gr
|
|
@@ -27,1596 +16,875 @@ import numpy as np
|
|
| 27 |
import matplotlib
|
| 28 |
matplotlib.use('Agg')
|
| 29 |
import matplotlib.pyplot as plt
|
| 30 |
-
import matplotlib.patches as mpatches
|
| 31 |
-
from matplotlib.gridspec import GridSpec
|
| 32 |
-
from matplotlib.colors import LinearSegmentedColormap
|
| 33 |
from scipy import stats
|
| 34 |
-
from scipy.optimize import curve_fit
|
| 35 |
-
import os, warnings, zipfile
|
| 36 |
-
from
|
| 37 |
-
from sklearn.
|
| 38 |
from sklearn.preprocessing import StandardScaler
|
| 39 |
-
from sklearn.
|
| 40 |
-
from sklearn.
|
|
|
|
|
|
|
| 41 |
warnings.filterwarnings('ignore')
|
| 42 |
|
| 43 |
-
# Try to import tabulate, provide fallback if not available
|
| 44 |
-
try:
|
| 45 |
-
from tabulate import tabulate
|
| 46 |
-
TABULATE_AVAILABLE = True
|
| 47 |
-
except ImportError:
|
| 48 |
-
TABULATE_AVAILABLE = False
|
| 49 |
-
# Define a simple tabulate function as fallback
|
| 50 |
-
def tabulate(data, headers="keys", tablefmt="pipe", **kwargs):
|
| 51 |
-
"""Simple fallback tabulate function."""
|
| 52 |
-
if headers == "keys":
|
| 53 |
-
headers = list(data.columns)
|
| 54 |
-
|
| 55 |
-
# Create markdown table
|
| 56 |
-
lines = []
|
| 57 |
-
# Header row
|
| 58 |
-
lines.append("| " + " | ".join(str(h) for h in headers) + " |")
|
| 59 |
-
# Separator row
|
| 60 |
-
lines.append("|" + "|".join([" --- " for _ in headers]) + "|")
|
| 61 |
-
# Data rows
|
| 62 |
-
for _, row in data.iterrows():
|
| 63 |
-
lines.append("| " + " | ".join(str(v) for v in row.values) + " |")
|
| 64 |
-
|
| 65 |
-
return "\n".join(lines)
|
| 66 |
-
|
| 67 |
-
OUTPUT_DIR = Path("/tmp/gwas_outputs")
|
| 68 |
-
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
|
| 69 |
-
|
| 70 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 71 |
-
#
|
| 72 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
#
|
| 89 |
-
|
| 90 |
-
"#
|
| 91 |
-
"#00695C", "#AD1457", "#4527A0", "#0277BD", "#558B2F",
|
| 92 |
-
"#E65100", "#37474F", "#880E4F", "#1B5E20", "#BF360C",
|
| 93 |
-
"#0D47A1", "#33691E", "#827717", "#4A148C", "#006064",
|
| 94 |
]
|
| 95 |
|
| 96 |
-
|
| 97 |
-
'GLM': '#1565C0',
|
| 98 |
-
'MLM': '#C62828',
|
| 99 |
-
'CMLM': '#2E7D32',
|
| 100 |
-
'BSLMM': '#F57F17',
|
| 101 |
-
'FarmCPU': '#6A1B9A',
|
| 102 |
-
}
|
| 103 |
-
|
| 104 |
-
def _style_white():
|
| 105 |
-
"""Apply clean white scientific publication theme."""
|
| 106 |
plt.rcParams.update({
|
| 107 |
-
'figure.facecolor':
|
| 108 |
-
'axes.
|
| 109 |
-
'axes.
|
| 110 |
-
'
|
| 111 |
-
'
|
| 112 |
-
'
|
| 113 |
-
'
|
| 114 |
-
'
|
| 115 |
-
'grid.color': W_GRID,
|
| 116 |
-
'grid.linewidth': 0.6,
|
| 117 |
-
'figure.dpi': 120,
|
| 118 |
-
'font.family': 'DejaVu Sans',
|
| 119 |
-
'font.size': 10,
|
| 120 |
-
'axes.titlesize': 12,
|
| 121 |
-
'axes.labelsize': 11,
|
| 122 |
-
'axes.spines.top': False,
|
| 123 |
-
'axes.spines.right': False,
|
| 124 |
-
'legend.framealpha': 0.95,
|
| 125 |
-
'legend.edgecolor': W_BORDER,
|
| 126 |
-
'legend.facecolor': W_BG,
|
| 127 |
-
'savefig.facecolor': W_BG,
|
| 128 |
-
'savefig.edgecolor': W_BG,
|
| 129 |
})
|
| 130 |
|
| 131 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 132 |
-
#
|
| 133 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 134 |
-
def parse_input_csv(filepath):
|
| 135 |
-
"""Parse input CSV file with genotype data."""
|
| 136 |
-
df = pd.read_csv(filepath, header=0, dtype=str)
|
| 137 |
-
marker_cols = df.columns[2:].tolist()
|
| 138 |
-
chr_row = df.iloc[0]
|
| 139 |
-
pos_row = df.iloc[1]
|
| 140 |
-
chrom_dict, pos_dict = {}, {}
|
| 141 |
-
|
| 142 |
-
for m in marker_cols:
|
| 143 |
-
cv = str(chr_row[m]).strip()
|
| 144 |
-
cv = cv[:-2] if cv.endswith('.0') else cv
|
| 145 |
-
cv = cv.replace('chr', '').replace('Chr', '').strip()
|
| 146 |
-
chrom_dict[m] = cv if cv not in ('', 'nan', '-') else '0'
|
| 147 |
-
|
| 148 |
-
pv_s = str(pos_row[m]).strip()
|
| 149 |
-
try:
|
| 150 |
-
pos_dict[m] = float(pv_s)
|
| 151 |
-
except ValueError:
|
| 152 |
-
parts = m.split('_')
|
| 153 |
-
bp = 0.0
|
| 154 |
-
for part in parts:
|
| 155 |
-
try:
|
| 156 |
-
cand = float(part)
|
| 157 |
-
if cand > 1000:
|
| 158 |
-
bp = cand
|
| 159 |
-
break
|
| 160 |
-
except ValueError:
|
| 161 |
-
continue
|
| 162 |
-
pos_dict[m] = bp
|
| 163 |
-
|
| 164 |
-
df_s = df.iloc[2:].reset_index(drop=True)
|
| 165 |
-
sample_ids = df_s.iloc[:, 0].astype(str).values
|
| 166 |
-
phenotypes = pd.to_numeric(df_s.iloc[:, 1], errors='coerce').values
|
| 167 |
-
geno_raw = (df_s[marker_cols]
|
| 168 |
-
.apply(pd.to_numeric, errors='coerce')
|
| 169 |
-
.replace(-1, np.nan)
|
| 170 |
-
.where(lambda x: x.isin([0, 1, 2]) | x.isna(), other=np.nan))
|
| 171 |
-
chromosomes = [chrom_dict[m] for m in marker_cols]
|
| 172 |
-
positions = [pos_dict[m] for m in marker_cols]
|
| 173 |
-
|
| 174 |
-
return (sample_ids, phenotypes, geno_raw.values, marker_cols, chromosomes, positions)
|
| 175 |
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
# Center genotypes (0/1/2 -> -2p, 1-2p, 2-2p)
|
| 184 |
-
p_hat = np.nanmean(X, axis=0) / 2.0
|
| 185 |
-
p_hat = np.clip(p_hat, 0.01, 0.99)
|
| 186 |
-
X_centered = X - 2 * p_hat
|
| 187 |
-
|
| 188 |
-
# Impute missing with mean
|
| 189 |
-
for i in range(X_centered.shape[1]):
|
| 190 |
-
col = X_centered[:, i]
|
| 191 |
-
nan_mask = np.isnan(col)
|
| 192 |
-
if nan_mask.any():
|
| 193 |
-
col[nan_mask] = np.nanmean(col)
|
| 194 |
-
X_centered[:, i] = col
|
| 195 |
-
|
| 196 |
-
# Kinship matrix
|
| 197 |
-
K = np.dot(X_centered, X_centered.T) / X_centered.shape[1]
|
| 198 |
-
|
| 199 |
-
# Scale to have mean diagonal ~1
|
| 200 |
-
d = np.mean(np.diag(K))
|
| 201 |
-
if d > 0:
|
| 202 |
-
K = K / d
|
| 203 |
-
|
| 204 |
-
# Ensure positive definite (add small ridge)
|
| 205 |
-
min_eig = np.min(np.linalg.eigvalsh(K))
|
| 206 |
-
if min_eig < 0:
|
| 207 |
-
K = K + np.eye(K.shape[0]) * (-min_eig + 1e-6)
|
| 208 |
-
|
| 209 |
-
return K
|
| 210 |
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
|
|
|
|
|
|
| 214 |
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
y_centered = y - np.mean(y)
|
| 224 |
-
|
| 225 |
-
for i in range(m):
|
| 226 |
-
x = G[:, i]
|
| 227 |
-
nan_mask = np.isnan(x)
|
| 228 |
-
if nan_mask.any():
|
| 229 |
-
x = x.copy()
|
| 230 |
-
x[nan_mask] = np.nanmean(x)
|
| 231 |
-
|
| 232 |
-
if np.std(x) < 1e-9:
|
| 233 |
-
continue
|
| 234 |
-
|
| 235 |
-
x_centered = x - np.mean(x)
|
| 236 |
-
cov = np.sum(x_centered * y_centered)
|
| 237 |
-
var_x = np.sum(x_centered * x_centered)
|
| 238 |
-
|
| 239 |
-
if var_x < 1e-12:
|
| 240 |
-
continue
|
| 241 |
-
|
| 242 |
-
b = cov / var_x
|
| 243 |
-
y_pred = b * x_centered
|
| 244 |
-
resid = y_centered - y_pred
|
| 245 |
-
sse = np.sum(resid * resid)
|
| 246 |
-
df = n - 2
|
| 247 |
-
|
| 248 |
-
if df > 0 and sse > 0:
|
| 249 |
-
se = np.sqrt(sse / df / var_x)
|
| 250 |
-
t_stat = b / (se + 1e-12)
|
| 251 |
-
p = 2 * stats.t.sf(np.abs(t_stat), df=df)
|
| 252 |
-
r2 = cov * cov / (var_x * np.sum(y_centered * y_centered) + 1e-12)
|
| 253 |
-
|
| 254 |
-
pv[i] = max(p, 1e-300) if np.isfinite(p) else 1.0
|
| 255 |
-
bv[i] = b
|
| 256 |
-
sv[i] = se
|
| 257 |
-
rv[i] = r2
|
| 258 |
-
|
| 259 |
-
return pv, bv, sv, rv
|
| 260 |
-
|
| 261 |
-
def model_mlm(G, y, K, n_pc=5):
|
| 262 |
-
"""Mixed Linear Model with kinship as random effect."""
|
| 263 |
-
n = len(y)
|
| 264 |
-
n_pc = min(n_pc, n - 2, G.shape[1] // 10)
|
| 265 |
-
|
| 266 |
-
# Get eigenvectors of kinship for PCs
|
| 267 |
-
eigvals, eigvecs = np.linalg.eigh(K)
|
| 268 |
-
idx = np.argsort(eigvals)[::-1]
|
| 269 |
-
Q = eigvecs[:, idx[:max(1, n_pc)]]
|
| 270 |
-
|
| 271 |
-
# Project out PCs (fixed effects)
|
| 272 |
-
Q_pinv = np.linalg.pinv(Q)
|
| 273 |
-
y_resid = y - Q @ (Q_pinv @ y)
|
| 274 |
-
|
| 275 |
-
m = G.shape[1]
|
| 276 |
-
pv = np.ones(m)
|
| 277 |
-
bv = np.zeros(m)
|
| 278 |
-
sv = np.zeros(m)
|
| 279 |
-
rv = np.zeros(m)
|
| 280 |
-
|
| 281 |
-
for i in range(m):
|
| 282 |
-
x = G[:, i]
|
| 283 |
-
nan_mask = np.isnan(x)
|
| 284 |
-
if nan_mask.any():
|
| 285 |
-
x = x.copy()
|
| 286 |
-
x[nan_mask] = np.nanmean(x)
|
| 287 |
-
|
| 288 |
-
if np.std(x) < 1e-9:
|
| 289 |
-
continue
|
| 290 |
-
|
| 291 |
-
# Project out PCs from genotype
|
| 292 |
-
x_resid = x - Q @ (Q_pinv @ x)
|
| 293 |
-
|
| 294 |
-
if np.std(x_resid) < 1e-9:
|
| 295 |
-
continue
|
| 296 |
-
|
| 297 |
-
xc = x_resid - np.mean(x_resid)
|
| 298 |
-
yc = y_resid - np.mean(y_resid)
|
| 299 |
-
cov = np.sum(xc * yc)
|
| 300 |
-
var_x = np.sum(xc * xc)
|
| 301 |
-
|
| 302 |
-
if var_x < 1e-12:
|
| 303 |
-
continue
|
| 304 |
-
|
| 305 |
-
b = cov / var_x
|
| 306 |
-
y_pred = b * xc
|
| 307 |
-
resid = yc - y_pred
|
| 308 |
-
sse = np.sum(resid * resid)
|
| 309 |
-
df = n - n_pc - 2
|
| 310 |
-
|
| 311 |
-
if df > 0 and sse > 0:
|
| 312 |
-
se = np.sqrt(sse / df / var_x)
|
| 313 |
-
t_stat = b / (se + 1e-12)
|
| 314 |
-
p = 2 * stats.t.sf(np.abs(t_stat), df=df)
|
| 315 |
-
r2 = cov * cov / (var_x * np.sum(yc * yc) + 1e-12)
|
| 316 |
-
|
| 317 |
-
pv[i] = max(p, 1e-300) if np.isfinite(p) else 1.0
|
| 318 |
-
bv[i] = b
|
| 319 |
-
sv[i] = se
|
| 320 |
-
rv[i] = r2
|
| 321 |
-
|
| 322 |
-
return pv, bv, sv, rv
|
| 323 |
-
|
| 324 |
-
def model_cmlm(G, y, K, n_groups=None, n_pc=5):
|
| 325 |
-
"""Compressed MLM - groups individuals into clusters."""
|
| 326 |
-
n = len(y)
|
| 327 |
-
|
| 328 |
-
# Get compression groups via KMeans on kinship PCs
|
| 329 |
-
eigvals, eigvecs = np.linalg.eigh(K)
|
| 330 |
-
idx = np.argsort(eigvals)[::-1]
|
| 331 |
-
emb = eigvecs[:, idx[:min(10, n-1)]]
|
| 332 |
-
|
| 333 |
-
if n_groups is None:
|
| 334 |
-
n_groups = max(2, min(20, n // 10))
|
| 335 |
-
|
| 336 |
-
n_groups = min(n_groups, n - 1)
|
| 337 |
-
km = KMeans(n_clusters=n_groups, random_state=42, n_init=5)
|
| 338 |
-
labels = km.fit_predict(emb)
|
| 339 |
-
|
| 340 |
-
# Create group indicator matrix
|
| 341 |
-
Q = np.zeros((n, n_groups))
|
| 342 |
-
for g in range(n_groups):
|
| 343 |
-
Q[:, g] = (labels == g).astype(float)
|
| 344 |
-
|
| 345 |
-
# Normalize
|
| 346 |
-
col_sum = Q.sum(axis=0)
|
| 347 |
-
col_sum[col_sum == 0] = 1
|
| 348 |
-
Q = Q / col_sum
|
| 349 |
-
|
| 350 |
-
# Project out group effects
|
| 351 |
-
Q_pinv = np.linalg.pinv(Q)
|
| 352 |
-
y_resid = y - Q @ (Q_pinv @ y)
|
| 353 |
-
|
| 354 |
-
m = G.shape[1]
|
| 355 |
-
pv = np.ones(m)
|
| 356 |
-
bv = np.zeros(m)
|
| 357 |
-
sv = np.zeros(m)
|
| 358 |
-
rv = np.zeros(m)
|
| 359 |
-
|
| 360 |
-
for i in range(m):
|
| 361 |
-
x = G[:, i]
|
| 362 |
-
nan_mask = np.isnan(x)
|
| 363 |
-
if nan_mask.any():
|
| 364 |
-
x = x.copy()
|
| 365 |
-
x[nan_mask] = np.nanmean(x)
|
| 366 |
-
|
| 367 |
-
if np.std(x) < 1e-9:
|
| 368 |
-
continue
|
| 369 |
-
|
| 370 |
-
# Project out group effects from genotype
|
| 371 |
-
x_resid = x - Q @ (Q_pinv @ x)
|
| 372 |
-
|
| 373 |
-
if np.std(x_resid) < 1e-9:
|
| 374 |
-
continue
|
| 375 |
-
|
| 376 |
-
xc = x_resid - np.mean(x_resid)
|
| 377 |
-
yc = y_resid - np.mean(y_resid)
|
| 378 |
-
cov = np.sum(xc * yc)
|
| 379 |
-
var_x = np.sum(xc * xc)
|
| 380 |
-
|
| 381 |
-
if var_x < 1e-12:
|
| 382 |
-
continue
|
| 383 |
-
|
| 384 |
-
b = cov / var_x
|
| 385 |
-
y_pred = b * xc
|
| 386 |
-
resid = yc - y_pred
|
| 387 |
-
sse = np.sum(resid * resid)
|
| 388 |
-
df = n - n_groups - 2
|
| 389 |
-
|
| 390 |
-
if df > 0 and sse > 0:
|
| 391 |
-
se = np.sqrt(sse / df / var_x)
|
| 392 |
-
t_stat = b / (se + 1e-12)
|
| 393 |
-
p = 2 * stats.t.sf(np.abs(t_stat), df=df)
|
| 394 |
-
r2 = cov * cov / (var_x * np.sum(yc * yc) + 1e-12)
|
| 395 |
-
|
| 396 |
-
pv[i] = max(p, 1e-300) if np.isfinite(p) else 1.0
|
| 397 |
-
bv[i] = b
|
| 398 |
-
sv[i] = se
|
| 399 |
-
rv[i] = r2
|
| 400 |
-
|
| 401 |
-
return pv, bv, sv, rv
|
| 402 |
-
|
| 403 |
-
def model_bslmm(G, y, n_boot=8):
|
| 404 |
-
"""Bayesian Sparse Linear Mixed Model using Elastic Net + Bootstrap."""
|
| 405 |
-
n, m = G.shape
|
| 406 |
-
|
| 407 |
-
# Standardize genotypes
|
| 408 |
-
scaler = StandardScaler()
|
| 409 |
-
X_scaled = scaler.fit_transform(G)
|
| 410 |
-
X_scaled = np.nan_to_num(X_scaled, nan=0.0)
|
| 411 |
-
|
| 412 |
-
# Use Ridge for large m, ElasticNet for smaller
|
| 413 |
-
if m > 5000:
|
| 414 |
-
alphas = np.logspace(-4, 4, 20)
|
| 415 |
-
model = RidgeCV(alphas=alphas, cv=min(5, n//2))
|
| 416 |
-
model.fit(X_scaled, y)
|
| 417 |
-
coef = model.coef_
|
| 418 |
-
else:
|
| 419 |
-
model = ElasticNetCV(
|
| 420 |
-
cv=min(5, n//2),
|
| 421 |
-
random_state=42,
|
| 422 |
-
max_iter=2000,
|
| 423 |
-
n_jobs=-1,
|
| 424 |
-
l1_ratio=[0.1, 0.5, 0.7, 0.9, 1.0]
|
| 425 |
-
)
|
| 426 |
-
model.fit(X_scaled, y)
|
| 427 |
-
coef = model.coef_
|
| 428 |
-
|
| 429 |
-
# Bootstrap for standard errors and p-values
|
| 430 |
-
boots = []
|
| 431 |
-
rng = np.random.default_rng(42)
|
| 432 |
-
|
| 433 |
-
for _ in range(n_boot):
|
| 434 |
-
idx = rng.choice(n, n, replace=True)
|
| 435 |
-
try:
|
| 436 |
-
if m > 5000:
|
| 437 |
-
boot_model = RidgeCV(alphas=alphas, cv=min(3, n//2))
|
| 438 |
-
else:
|
| 439 |
-
boot_model = ElasticNetCV(
|
| 440 |
-
cv=min(3, n//2),
|
| 441 |
-
random_state=42,
|
| 442 |
-
max_iter=1000,
|
| 443 |
-
l1_ratio=[0.1, 0.5, 0.9, 1.0]
|
| 444 |
-
)
|
| 445 |
-
boot_model.fit(X_scaled[idx], y[idx])
|
| 446 |
-
boots.append(boot_model.coef_)
|
| 447 |
-
except:
|
| 448 |
-
boots.append(coef.copy())
|
| 449 |
-
|
| 450 |
-
boot_arr = np.array(boots)
|
| 451 |
-
pv = np.ones(m)
|
| 452 |
-
se = np.zeros(m)
|
| 453 |
-
|
| 454 |
-
for i in range(m):
|
| 455 |
-
boot_se = np.std(boot_arr[:, i])
|
| 456 |
-
if boot_se > 0:
|
| 457 |
-
se[i] = boot_se
|
| 458 |
-
z = np.abs(coef[i]) / (boot_se + 1e-12)
|
| 459 |
-
pv[i] = max(2 * (1 - stats.norm.cdf(z)), 1e-300)
|
| 460 |
-
|
| 461 |
-
return pv, coef, se
|
| 462 |
-
|
| 463 |
-
def model_farmcpu(G, y, K, max_iter=3):
|
| 464 |
-
"""FarmCPU: Fixed and Random model Circulating Probability Unification."""
|
| 465 |
-
n, m = G.shape
|
| 466 |
-
n_pc = min(5, n - 2)
|
| 467 |
-
|
| 468 |
-
# Get PCs from kinship
|
| 469 |
-
eigvals, eigvecs = np.linalg.eigh(K)
|
| 470 |
-
idx = np.argsort(eigvals)[::-1]
|
| 471 |
-
PCs = eigvecs[:, idx[:n_pc]]
|
| 472 |
-
|
| 473 |
-
# Initial GLM
|
| 474 |
-
pv, bv, sv, rv = model_glm(G, y)
|
| 475 |
-
|
| 476 |
-
for iteration in range(max_iter):
|
| 477 |
-
# Select top markers as pseudo-QTNs
|
| 478 |
-
n_qtns = max(2, min(20, int(m * 0.002)))
|
| 479 |
-
top_idx = np.argsort(pv)[:n_qtns]
|
| 480 |
-
|
| 481 |
-
# Build covariate matrix with PCs and selected markers
|
| 482 |
-
covariates = [PCs]
|
| 483 |
-
for idx_qtn in top_idx:
|
| 484 |
-
x = G[:, idx_qtn]
|
| 485 |
-
nan_mask = np.isnan(x)
|
| 486 |
-
if nan_mask.any():
|
| 487 |
-
x = x.copy()
|
| 488 |
-
x[nan_mask] = np.nanmean(x)
|
| 489 |
-
covariates.append(x.reshape(-1, 1))
|
| 490 |
-
|
| 491 |
-
X_cov = np.hstack(covariates)
|
| 492 |
-
|
| 493 |
-
# Fit full model
|
| 494 |
-
try:
|
| 495 |
-
beta = np.linalg.lstsq(X_cov, y, rcond=None)[0]
|
| 496 |
-
y_resid = y - X_cov @ beta
|
| 497 |
-
except:
|
| 498 |
-
y_resid = y.copy()
|
| 499 |
-
|
| 500 |
-
# Re-compute p-values conditioned on pseudo-QTNs
|
| 501 |
-
df = max(n - X_cov.shape[1] - 1, 1)
|
| 502 |
-
|
| 503 |
-
for i in range(m):
|
| 504 |
-
if i in top_idx:
|
| 505 |
-
continue
|
| 506 |
-
|
| 507 |
-
x = G[:, i]
|
| 508 |
-
nan_mask = np.isnan(x)
|
| 509 |
-
if nan_mask.any():
|
| 510 |
-
x = x.copy()
|
| 511 |
-
x[nan_mask] = np.nanmean(x)
|
| 512 |
-
|
| 513 |
-
if np.std(x) < 1e-9:
|
| 514 |
-
continue
|
| 515 |
-
|
| 516 |
-
xc = x - np.mean(x)
|
| 517 |
-
yc = y_resid - np.mean(y_resid)
|
| 518 |
-
cov = np.sum(xc * yc)
|
| 519 |
-
var_x = np.sum(xc * xc)
|
| 520 |
-
|
| 521 |
-
if var_x < 1e-12:
|
| 522 |
-
continue
|
| 523 |
-
|
| 524 |
-
b = cov / var_x
|
| 525 |
-
y_pred = b * xc
|
| 526 |
-
sse = np.sum((yc - y_pred) ** 2)
|
| 527 |
-
|
| 528 |
-
if sse > 0 and df > 0:
|
| 529 |
-
se_b = np.sqrt(sse / df / var_x)
|
| 530 |
-
t_stat = b / (se_b + 1e-12)
|
| 531 |
-
p = 2 * stats.t.sf(np.abs(t_stat), df=df)
|
| 532 |
-
pv[i] = max(p, 1e-300) if np.isfinite(p) else 1.0
|
| 533 |
-
bv[i] = b
|
| 534 |
-
sv[i] = se_b
|
| 535 |
-
|
| 536 |
-
return pv, bv, sv
|
| 537 |
|
| 538 |
-
|
| 539 |
-
|
| 540 |
-
|
| 541 |
|
| 542 |
-
|
| 543 |
-
|
| 544 |
-
|
| 545 |
-
|
| 546 |
-
|
| 547 |
-
|
| 548 |
-
|
| 549 |
-
|
| 550 |
-
|
| 551 |
-
|
| 552 |
-
|
| 553 |
-
if
|
| 554 |
-
|
| 555 |
-
|
| 556 |
-
|
| 557 |
-
|
| 558 |
-
|
| 559 |
-
|
| 560 |
-
|
| 561 |
-
|
| 562 |
-
|
| 563 |
-
|
| 564 |
-
|
| 565 |
-
|
| 566 |
-
|
| 567 |
-
|
| 568 |
-
|
| 569 |
-
|
| 570 |
-
|
| 571 |
-
|
| 572 |
-
|
| 573 |
-
|
| 574 |
-
|
| 575 |
-
|
| 576 |
-
|
| 577 |
-
|
| 578 |
-
|
| 579 |
-
|
| 580 |
-
|
| 581 |
-
|
| 582 |
-
|
| 583 |
-
|
| 584 |
-
|
| 585 |
-
|
| 586 |
-
|
| 587 |
-
|
| 588 |
-
|
| 589 |
-
|
| 590 |
-
|
| 591 |
-
|
| 592 |
-
|
| 593 |
-
break
|
| 594 |
-
|
| 595 |
-
if pairs_sampled >= max_pairs:
|
| 596 |
-
break
|
| 597 |
-
|
| 598 |
-
return np.array(all_dist), np.array(all_r2)
|
| 599 |
-
|
| 600 |
-
def plot_ld_decay(genotypes, chromosomes, positions, save_path):
|
| 601 |
-
"""Plot LD decay with proper Hill-Weir model fitting."""
|
| 602 |
-
_style_white()
|
| 603 |
-
|
| 604 |
-
# Compute LD sweep
|
| 605 |
-
dist, r2 = compute_ld_decay_sweep(genotypes, positions, max_dist_mb=10)
|
| 606 |
-
|
| 607 |
-
if len(dist) == 0:
|
| 608 |
-
fig, ax = plt.subplots(figsize=(10, 6), facecolor=W_BG)
|
| 609 |
-
ax.set_facecolor(W_PANEL)
|
| 610 |
-
ax.text(0.5, 0.5, 'No LD pairs computed (need more markers)',
|
| 611 |
-
ha='center', va='center', transform=ax.transAxes, fontsize=13)
|
| 612 |
-
plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=W_BG)
|
| 613 |
-
plt.close(fig)
|
| 614 |
-
return {}, "No LD data available"
|
| 615 |
-
|
| 616 |
-
# Bin data for fitting
|
| 617 |
-
bins = np.linspace(0, min(10, np.percentile(dist, 98)), 50)
|
| 618 |
-
bin_centers = []
|
| 619 |
-
bin_means = []
|
| 620 |
-
bin_stds = []
|
| 621 |
-
|
| 622 |
-
for i in range(len(bins) - 1):
|
| 623 |
-
mask = (dist >= bins[i]) & (dist < bins[i+1])
|
| 624 |
-
if mask.sum() >= 5:
|
| 625 |
-
bin_centers.append((bins[i] + bins[i+1]) / 2)
|
| 626 |
-
bin_means.append(np.mean(r2[mask]))
|
| 627 |
-
bin_stds.append(np.std(r2[mask]))
|
| 628 |
-
|
| 629 |
-
bin_centers = np.array(bin_centers)
|
| 630 |
-
bin_means = np.array(bin_means)
|
| 631 |
-
bin_stds = np.array(bin_stds)
|
| 632 |
-
|
| 633 |
-
# Fit Hill-Weir model
|
| 634 |
-
fit_ok = False
|
| 635 |
-
Ne_fit = 100
|
| 636 |
-
r2_start = 0.5
|
| 637 |
-
half_decay = 1.0
|
| 638 |
-
|
| 639 |
-
if len(bin_centers) >= 5:
|
| 640 |
-
try:
|
| 641 |
-
def objective(Ne):
|
| 642 |
-
pred = hill_weir_model(bin_centers, Ne)
|
| 643 |
-
return np.sum(((bin_means - pred) / (bin_stds + 0.01)) ** 2)
|
| 644 |
-
|
| 645 |
-
result = minimize_scalar(objective, bounds=(1, 10000), method='bounded')
|
| 646 |
-
Ne_fit = result.x
|
| 647 |
-
fit_ok = True
|
| 648 |
-
|
| 649 |
-
dist_fit = np.linspace(0, min(10, bin_centers[-1]), 200)
|
| 650 |
-
r2_fit = hill_weir_model(dist_fit, Ne_fit)
|
| 651 |
-
|
| 652 |
-
r2_start = hill_weir_model(0, Ne_fit)
|
| 653 |
-
half_idx = np.where(r2_fit <= r2_start / 2)[0]
|
| 654 |
-
if len(half_idx) > 0:
|
| 655 |
-
half_decay = dist_fit[half_idx[0]]
|
| 656 |
-
except:
|
| 657 |
-
# Fallback to exponential decay
|
| 658 |
-
try:
|
| 659 |
-
def exp_decay(d, a, b):
|
| 660 |
-
return a * np.exp(-b * d)
|
| 661 |
-
popt, _ = curve_fit(exp_decay, bin_centers, bin_means,
|
| 662 |
-
p0=[0.5, 1.0], maxfev=5000)
|
| 663 |
-
dist_fit = np.linspace(0, bin_centers[-1], 200)
|
| 664 |
-
r2_fit = exp_decay(dist_fit, *popt)
|
| 665 |
-
r2_start = popt[0]
|
| 666 |
-
half_decay = np.log(2) / popt[1] if popt[1] > 0 else 1.0
|
| 667 |
-
fit_ok = True
|
| 668 |
-
except:
|
| 669 |
-
pass
|
| 670 |
-
|
| 671 |
-
# Create figure
|
| 672 |
-
fig = plt.figure(figsize=(12, 8), facecolor=W_BG)
|
| 673 |
-
gs = GridSpec(2, 1, figure=fig, height_ratios=[3, 1], hspace=0.08)
|
| 674 |
-
|
| 675 |
-
# Main plot
|
| 676 |
-
ax = fig.add_subplot(gs[0])
|
| 677 |
-
ax.set_facecolor(W_PANEL)
|
| 678 |
-
|
| 679 |
-
# Scatter plot (subsampled for visibility)
|
| 680 |
-
sample_rate = max(1, len(dist) // 5000)
|
| 681 |
-
ax.scatter(dist[::sample_rate], r2[::sample_rate],
|
| 682 |
-
c=W_ACCENT, s=3, alpha=0.3, linewidths=0, zorder=1)
|
| 683 |
-
|
| 684 |
-
# Binned means with error bars
|
| 685 |
-
if len(bin_centers) > 0:
|
| 686 |
-
ax.errorbar(bin_centers, bin_means, yerr=bin_stds,
|
| 687 |
-
fmt='o', color=W_RED, capsize=3,
|
| 688 |
-
markersize=6, elinewidth=1.5, capthick=1.5,
|
| 689 |
-
label='Binned mean Β± SD', zorder=3)
|
| 690 |
-
|
| 691 |
-
# Fitted curve
|
| 692 |
-
if fit_ok and 'dist_fit' in locals():
|
| 693 |
-
ax.plot(dist_fit, r2_fit, color=W_GREEN, lw=2.5,
|
| 694 |
-
label=f'Hill-Weir fit (Ne = {Ne_fit:.0f})', zorder=4)
|
| 695 |
-
|
| 696 |
-
# Mark half-decay
|
| 697 |
-
ax.axvline(half_decay, color=W_ORANGE, ls='--', lw=1.5, alpha=0.8)
|
| 698 |
-
ax.axhline(r2_start / 2, color=W_ORANGE, ls='--', lw=1.5, alpha=0.8)
|
| 699 |
-
ax.text(half_decay + 0.05, r2_start / 2 + 0.02,
|
| 700 |
-
f'Half-decay: {half_decay:.2f} Mb',
|
| 701 |
-
fontsize=9, color=W_ORANGE, fontweight='bold')
|
| 702 |
-
|
| 703 |
-
# Reference lines
|
| 704 |
-
ax.axhline(0.2, color=W_GOLD, ls=':', lw=1.2, alpha=0.7, label='rΒ² = 0.2')
|
| 705 |
-
ax.axhline(0.1, color=W_PURPLE, ls=':', lw=1.2, alpha=0.7, label='rΒ² = 0.1')
|
| 706 |
-
|
| 707 |
-
ax.set_xlim(0, min(10, np.percentile(dist, 98) * 1.05))
|
| 708 |
-
ax.set_ylim(-0.02, 1.02)
|
| 709 |
-
ax.set_xlabel('Distance (Mb)', fontweight='bold', fontsize=12)
|
| 710 |
-
ax.set_ylabel('Linkage Disequilibrium (rΒ²)', fontweight='bold', fontsize=12)
|
| 711 |
-
ax.set_title('Linkage Disequilibrium Decay Analysis',
|
| 712 |
-
fontweight='bold', fontsize=14, color=W_ACCENT)
|
| 713 |
-
ax.legend(loc='upper right', fontsize=9)
|
| 714 |
-
ax.grid(True, color=W_GRID, lw=0.5, alpha=0.7)
|
| 715 |
-
|
| 716 |
-
# Interpretation panel
|
| 717 |
-
ax_text = fig.add_subplot(gs[1])
|
| 718 |
-
ax_text.axis('off')
|
| 719 |
-
ax_text.set_facecolor(W_BG)
|
| 720 |
-
|
| 721 |
-
n_pairs = len(dist)
|
| 722 |
-
mean_r2 = np.mean(r2)
|
| 723 |
-
r2_lt_02 = np.mean(r2 < 0.2) * 100
|
| 724 |
-
|
| 725 |
-
if fit_ok:
|
| 726 |
-
interp_text = f"""
|
| 727 |
-
LD DECAY INTERPRETATION
|
| 728 |
-
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 729 |
-
β’ Model: Hill-Weir (1988) E(rΒ²) = 1/(1 + 4Β·NβΒ·cΒ·d)
|
| 730 |
-
β’ Estimated effective population size (Nβ): {Ne_fit:.0f}
|
| 731 |
-
β’ Half-decay distance (rΒ² = {r2_start/2:.3f}): {half_decay:.3f} Mb
|
| 732 |
-
β’ Mean rΒ² across all pairs: {mean_r2:.4f}
|
| 733 |
-
β’ Pairs with rΒ² < 0.2: {r2_lt_02:.1f}%
|
| 734 |
-
β’ Total pairs analysed: {n_pairs:,}
|
| 735 |
-
|
| 736 |
-
Interpretation:
|
| 737 |
-
- LD decays {'rapidly' if half_decay < 0.5 else 'moderately' if half_decay < 2 else 'slowly'}
|
| 738 |
-
- {'Low' if r2_lt_02 > 70 else 'Moderate' if r2_lt_02 > 50 else 'High'} genome-wide LD
|
| 739 |
-
"""
|
| 740 |
-
else:
|
| 741 |
-
interp_text = f"""
|
| 742 |
-
LD DECAY SUMMARY
|
| 743 |
-
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 744 |
-
β’ Mean rΒ² across all pairs: {mean_r2:.4f}
|
| 745 |
-
β’ Pairs with rΒ² < 0.2: {r2_lt_02:.1f}%
|
| 746 |
-
β’ Total pairs analysed: {n_pairs:,}
|
| 747 |
-
|
| 748 |
-
Note: Model fitting failed - insufficient data or poor convergence.
|
| 749 |
-
"""
|
| 750 |
-
|
| 751 |
-
ax_text.text(0.02, 0.95, interp_text, transform=ax_text.transAxes,
|
| 752 |
-
fontsize=9, fontfamily='monospace', va='top',
|
| 753 |
-
bbox=dict(boxstyle='round,pad=0.5', facecolor=W_PANEL,
|
| 754 |
-
edgecolor=W_BORDER, alpha=0.95))
|
| 755 |
-
|
| 756 |
-
plt.tight_layout()
|
| 757 |
-
plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=W_BG)
|
| 758 |
plt.close(fig)
|
| 759 |
-
|
| 760 |
-
stats_dict = {
|
| 761 |
-
'n_pairs': n_pairs,
|
| 762 |
-
'mean_r2': mean_r2,
|
| 763 |
-
'r2_lt_02_pct': r2_lt_02,
|
| 764 |
-
'half_decay_mb': half_decay if fit_ok else None,
|
| 765 |
-
'estimated_Ne': Ne_fit if fit_ok else None
|
| 766 |
-
}
|
| 767 |
-
|
| 768 |
-
return stats_dict, interp_text
|
| 769 |
|
| 770 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 771 |
-
#
|
| 772 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 773 |
|
| 774 |
-
def
|
| 775 |
-
"""
|
| 776 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 777 |
key=lambda x: (int(x) if str(x).isdigit() else 999, str(x)))
|
| 778 |
-
|
| 779 |
-
|
| 780 |
-
|
| 781 |
-
|
| 782 |
-
|
| 783 |
-
GAP = max(8, len(markers) // 150)
|
| 784 |
-
x_pos = np.zeros(len(markers))
|
| 785 |
-
chrom_ticks = []
|
| 786 |
-
offset = 0
|
| 787 |
-
|
| 788 |
for ch in unique_chroms:
|
| 789 |
-
idxs =
|
| 790 |
-
if
|
| 791 |
continue
|
| 792 |
-
|
| 793 |
-
|
| 794 |
-
|
| 795 |
-
|
| 796 |
-
|
| 797 |
-
|
| 798 |
-
|
| 799 |
-
|
| 800 |
-
|
| 801 |
-
|
| 802 |
-
|
| 803 |
-
|
| 804 |
-
|
| 805 |
-
|
| 806 |
-
|
| 807 |
-
|
| 808 |
-
|
| 809 |
-
|
| 810 |
-
|
| 811 |
-
|
| 812 |
-
|
| 813 |
-
|
| 814 |
-
|
| 815 |
-
|
| 816 |
-
|
| 817 |
-
|
| 818 |
-
|
| 819 |
-
|
| 820 |
-
|
| 821 |
-
|
| 822 |
-
|
| 823 |
-
|
| 824 |
-
|
| 825 |
-
|
| 826 |
-
|
| 827 |
-
|
| 828 |
-
|
| 829 |
-
|
| 830 |
-
|
| 831 |
-
|
| 832 |
-
|
| 833 |
-
|
| 834 |
-
|
| 835 |
-
|
| 836 |
-
|
| 837 |
-
|
| 838 |
-
|
| 839 |
-
|
| 840 |
-
|
| 841 |
-
|
| 842 |
-
|
| 843 |
-
|
| 844 |
-
|
| 845 |
-
|
| 846 |
-
|
| 847 |
-
|
| 848 |
-
|
| 849 |
-
|
| 850 |
-
|
| 851 |
-
|
| 852 |
-
|
| 853 |
-
|
| 854 |
-
|
| 855 |
-
|
| 856 |
-
|
| 857 |
-
|
| 858 |
-
|
| 859 |
-
|
| 860 |
-
|
| 861 |
-
|
| 862 |
-
|
| 863 |
-
|
| 864 |
-
|
| 865 |
-
|
| 866 |
-
|
| 867 |
-
|
| 868 |
-
|
| 869 |
-
|
| 870 |
-
|
| 871 |
-
|
| 872 |
-
axes[1]
|
| 873 |
-
|
| 874 |
-
|
| 875 |
-
|
| 876 |
-
|
| 877 |
-
|
| 878 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 879 |
plt.close(fig)
|
| 880 |
|
|
|
|
|
|
|
|
|
|
| 881 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 882 |
-
#
|
| 883 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 884 |
|
| 885 |
-
def
|
| 886 |
-
|
| 887 |
-
|
| 888 |
-
|
| 889 |
-
|
| 890 |
-
|
| 891 |
-
|
| 892 |
-
|
| 893 |
-
|
| 894 |
-
|
| 895 |
-
|
| 896 |
-
|
| 897 |
-
|
| 898 |
-
|
| 899 |
-
|
| 900 |
-
|
| 901 |
-
|
| 902 |
-
|
| 903 |
-
|
| 904 |
-
|
| 905 |
-
|
| 906 |
-
|
| 907 |
-
|
| 908 |
-
|
| 909 |
-
|
| 910 |
-
|
| 911 |
-
|
| 912 |
-
|
| 913 |
-
|
| 914 |
-
|
| 915 |
-
|
| 916 |
-
|
| 917 |
-
|
| 918 |
-
|
| 919 |
-
|
| 920 |
-
|
| 921 |
-
|
| 922 |
-
|
| 923 |
-
|
| 924 |
-
|
| 925 |
-
|
| 926 |
-
|
| 927 |
-
|
| 928 |
-
|
| 929 |
-
|
| 930 |
-
|
| 931 |
-
|
| 932 |
-
|
| 933 |
-
|
| 934 |
-
|
| 935 |
-
|
| 936 |
-
|
| 937 |
-
|
| 938 |
-
ax
|
| 939 |
-
|
| 940 |
-
|
| 941 |
-
|
| 942 |
-
|
| 943 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 944 |
plt.close(fig)
|
| 945 |
-
|
| 946 |
-
return lam
|
| 947 |
|
| 948 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 949 |
-
#
|
| 950 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 951 |
|
| 952 |
-
def
|
| 953 |
-
"""
|
| 954 |
-
|
| 955 |
-
|
| 956 |
-
|
| 957 |
-
|
| 958 |
-
|
| 959 |
-
|
| 960 |
-
|
| 961 |
-
|
| 962 |
-
|
| 963 |
-
|
| 964 |
-
|
| 965 |
-
|
| 966 |
-
|
| 967 |
-
|
| 968 |
-
|
| 969 |
-
|
| 970 |
-
|
| 971 |
-
|
| 972 |
-
|
| 973 |
-
|
| 974 |
-
ax.grid(True, alpha=0.3)
|
| 975 |
-
|
| 976 |
-
plt.tight_layout()
|
| 977 |
-
plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=W_BG)
|
| 978 |
-
plt.close(fig)
|
| 979 |
|
| 980 |
-
|
| 981 |
-
|
| 982 |
-
|
| 983 |
-
|
| 984 |
-
|
| 985 |
-
|
| 986 |
-
|
| 987 |
-
|
| 988 |
-
|
| 989 |
-
|
| 990 |
-
|
| 991 |
-
|
| 992 |
-
|
| 993 |
-
|
| 994 |
-
|
| 995 |
-
|
| 996 |
-
|
| 997 |
-
|
| 998 |
-
|
| 999 |
-
|
| 1000 |
-
|
| 1001 |
-
|
| 1002 |
-
|
| 1003 |
-
|
| 1004 |
-
|
| 1005 |
-
|
| 1006 |
-
|
| 1007 |
-
|
| 1008 |
-
|
| 1009 |
-
|
| 1010 |
-
|
| 1011 |
-
|
| 1012 |
-
|
| 1013 |
-
|
| 1014 |
-
|
| 1015 |
-
|
| 1016 |
-
|
| 1017 |
-
|
| 1018 |
-
|
| 1019 |
-
|
| 1020 |
-
|
| 1021 |
-
|
| 1022 |
-
|
| 1023 |
-
|
| 1024 |
-
|
| 1025 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1026 |
else:
|
| 1027 |
-
|
| 1028 |
-
|
| 1029 |
-
plt.tight_layout()
|
| 1030 |
-
plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=W_BG)
|
| 1031 |
-
plt.close(fig)
|
| 1032 |
-
|
| 1033 |
-
return evr, np.cumsum(evr), scores
|
| 1034 |
-
|
| 1035 |
-
def plot_kinship_heatmap(K, save_path, max_n=200):
|
| 1036 |
-
"""Plot kinship matrix heatmap."""
|
| 1037 |
-
_style_white()
|
| 1038 |
-
n = K.shape[0]
|
| 1039 |
-
if n > max_n:
|
| 1040 |
-
idx = np.random.choice(n, max_n, replace=False)
|
| 1041 |
-
idx.sort()
|
| 1042 |
-
K = K[np.ix_(idx, idx)]
|
| 1043 |
-
|
| 1044 |
-
fig, ax = plt.subplots(figsize=(8, 7), facecolor=W_BG)
|
| 1045 |
-
cmap = LinearSegmentedColormap.from_list('kinship', ['white', '#C6DBEF', '#4292C6', '#08306B'])
|
| 1046 |
-
im = ax.imshow(K, cmap=cmap, vmin=0, vmax=1)
|
| 1047 |
-
plt.colorbar(im, ax=ax, label='Kinship coefficient')
|
| 1048 |
-
ax.set_title('Kinship Matrix', fontweight='bold')
|
| 1049 |
-
ax.set_xlabel('Sample')
|
| 1050 |
-
ax.set_ylabel('Sample')
|
| 1051 |
-
plt.tight_layout()
|
| 1052 |
-
plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=W_BG)
|
| 1053 |
-
plt.close(fig)
|
| 1054 |
|
| 1055 |
-
|
| 1056 |
-
|
| 1057 |
-
_style_white()
|
| 1058 |
-
maf = maf_arr[maf_arr > 0]
|
| 1059 |
-
fig, axes = plt.subplots(1, 2, figsize=(12, 5), facecolor=W_BG)
|
| 1060 |
-
fig.suptitle('Minor Allele Frequency Distribution', fontweight='bold')
|
| 1061 |
-
|
| 1062 |
-
ax = axes[0]
|
| 1063 |
-
ax.set_facecolor(W_PANEL)
|
| 1064 |
-
ax.hist(maf, bins=40, color=W_ACCENT, alpha=0.7, edgecolor='white')
|
| 1065 |
-
ax.axvline(0.05, color=W_RED, ls='--', lw=2, label='MAF=0.05')
|
| 1066 |
-
ax.set_xlabel('MAF')
|
| 1067 |
-
ax.set_ylabel('Count')
|
| 1068 |
-
ax.legend()
|
| 1069 |
-
ax.grid(True, alpha=0.3)
|
| 1070 |
-
|
| 1071 |
-
ax = axes[1]
|
| 1072 |
-
ax.set_facecolor(W_PANEL)
|
| 1073 |
-
x = np.sort(maf)
|
| 1074 |
-
y = np.arange(1, len(x)+1) / len(x)
|
| 1075 |
-
ax.plot(x, y, color=W_ACCENT, lw=2)
|
| 1076 |
-
ax.fill_between(x, 0, y, color=W_ACCENT, alpha=0.15)
|
| 1077 |
-
ax.axvline(0.05, color=W_RED, ls='--', lw=2)
|
| 1078 |
-
ax.set_xlabel('MAF')
|
| 1079 |
-
ax.set_ylabel('Cumulative proportion')
|
| 1080 |
-
ax.set_title('Cumulative distribution')
|
| 1081 |
-
ax.grid(True, alpha=0.3)
|
| 1082 |
-
|
| 1083 |
-
plt.tight_layout()
|
| 1084 |
-
plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=W_BG)
|
| 1085 |
-
plt.close(fig)
|
| 1086 |
|
| 1087 |
-
|
| 1088 |
-
|
| 1089 |
-
|
| 1090 |
-
|
| 1091 |
-
bonf_log = -np.log10(bonf_thresh)
|
| 1092 |
-
|
| 1093 |
-
fig, ax = plt.subplots(figsize=(9, 7), facecolor=W_BG)
|
| 1094 |
-
ax.set_facecolor(W_PANEL)
|
| 1095 |
-
|
| 1096 |
-
sig = log_p >= bonf_log
|
| 1097 |
-
nsig = ~sig
|
| 1098 |
-
|
| 1099 |
-
if nsig.any():
|
| 1100 |
-
ax.scatter(beta[nsig], log_p[nsig], c=W_SUBTEXT, s=10, alpha=0.4, linewidths=0)
|
| 1101 |
-
|
| 1102 |
-
pos_sig = sig & (beta > 0)
|
| 1103 |
-
neg_sig = sig & (beta < 0)
|
| 1104 |
-
|
| 1105 |
-
if pos_sig.any():
|
| 1106 |
-
ax.scatter(beta[pos_sig], log_p[pos_sig], c=W_RED, s=45, marker='D',
|
| 1107 |
-
alpha=0.9, edgecolors='white', linewidths=0.5, label='Positive effect')
|
| 1108 |
-
if neg_sig.any():
|
| 1109 |
-
ax.scatter(beta[neg_sig], log_p[neg_sig], c=W_ACCENT, s=45, marker='D',
|
| 1110 |
-
alpha=0.9, edgecolors='white', linewidths=0.5, label='Negative effect')
|
| 1111 |
-
|
| 1112 |
-
ax.axhline(bonf_log, color=W_RED, ls='--', lw=1.5, label=f'Bonferroni ({bonf_log:.2f})')
|
| 1113 |
-
ax.axvline(0, color=W_BORDER, ls=':', lw=1)
|
| 1114 |
-
ax.set_xlabel('Effect size (Ξ²)', fontweight='bold')
|
| 1115 |
-
ax.set_ylabel('-logββ(P)', fontweight='bold')
|
| 1116 |
-
ax.set_title(f'Volcano Plot β {model_name}', fontweight='bold')
|
| 1117 |
-
ax.legend()
|
| 1118 |
-
ax.grid(True, alpha=0.3)
|
| 1119 |
-
|
| 1120 |
-
plt.tight_layout()
|
| 1121 |
-
plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=W_BG)
|
| 1122 |
-
plt.close(fig)
|
| 1123 |
|
| 1124 |
-
|
| 1125 |
-
|
| 1126 |
-
|
| 1127 |
-
|
| 1128 |
-
|
| 1129 |
-
|
| 1130 |
-
|
| 1131 |
-
|
| 1132 |
-
|
| 1133 |
-
|
| 1134 |
-
|
| 1135 |
-
|
| 1136 |
-
fig, axes = plt.subplots(n_rows, n_cols, figsize=(5*n_cols, 5*n_rows), facecolor=W_BG)
|
| 1137 |
-
if n_rows == 1 and n_cols == 1:
|
| 1138 |
-
axes = np.array([[axes]])
|
| 1139 |
-
axes = axes.flatten()
|
| 1140 |
-
|
| 1141 |
-
pair_idx = 0
|
| 1142 |
-
for i in range(n):
|
| 1143 |
-
for j in range(i+1, n):
|
| 1144 |
-
ax = axes[pair_idx]
|
| 1145 |
-
ax.set_facecolor(W_PANEL)
|
| 1146 |
-
|
| 1147 |
-
p1 = -np.log10(np.clip(model_pvals[models[i]], 1e-300, 1))
|
| 1148 |
-
p2 = -np.log10(np.clip(model_pvals[models[j]], 1e-300, 1))
|
| 1149 |
-
corr = np.corrcoef(p1, p2)[0, 1]
|
| 1150 |
-
|
| 1151 |
-
ax.scatter(p1, p2, alpha=0.4, s=8, c=MODEL_COLORS.get(models[i], W_ACCENT))
|
| 1152 |
-
max_val = max(p1.max(), p2.max()) * 1.05
|
| 1153 |
-
ax.plot([0, max_val], [0, max_val], '--', color=W_GOLD, lw=1.5, alpha=0.7)
|
| 1154 |
-
ax.set_xlabel(f'{models[i]} -logββ(P)')
|
| 1155 |
-
ax.set_ylabel(f'{models[j]} -logββ(P)')
|
| 1156 |
-
ax.set_title(f'{models[i]} vs {models[j]}', fontsize=10)
|
| 1157 |
-
ax.text(0.05, 0.95, f'r = {corr:.3f}', transform=ax.transAxes,
|
| 1158 |
-
fontsize=11, fontweight='bold', color=W_RED, va='top')
|
| 1159 |
-
ax.grid(True, alpha=0.3)
|
| 1160 |
-
pair_idx += 1
|
| 1161 |
-
|
| 1162 |
-
for k in range(pair_idx, len(axes)):
|
| 1163 |
-
axes[k].set_visible(False)
|
| 1164 |
-
|
| 1165 |
-
plt.tight_layout()
|
| 1166 |
-
plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=W_BG)
|
| 1167 |
-
plt.close(fig)
|
| 1168 |
|
| 1169 |
-
def plot_circos(markers, chromosomes, positions, model_pvals, bonf_thresh, lod_thresh_user, save_path):
|
| 1170 |
-
"""Simplified Circos plot for multi-model comparison."""
|
| 1171 |
-
_style_white()
|
| 1172 |
-
|
| 1173 |
-
fig, ax = plt.subplots(figsize=(12, 12), facecolor=W_BG)
|
| 1174 |
-
|
| 1175 |
-
# Simplified circos representation
|
| 1176 |
-
n_models = len(model_pvals)
|
| 1177 |
-
|
| 1178 |
-
# Polar plot
|
| 1179 |
-
ax = fig.add_subplot(111, projection='polar')
|
| 1180 |
-
ax.set_facecolor(W_BG)
|
| 1181 |
-
ax.set_title('Multi-Model GWAS Circos', fontweight='bold', pad=20)
|
| 1182 |
-
|
| 1183 |
-
# Center text
|
| 1184 |
-
ax.text(0, 0, f'{n_models} Models\nAnalyzed', ha='center', va='center',
|
| 1185 |
-
fontsize=14, fontweight='bold')
|
| 1186 |
-
|
| 1187 |
-
# Add chromosome arcs
|
| 1188 |
-
unique_chroms = sorted(set(chromosomes))
|
| 1189 |
-
n_chr = len(unique_chroms)
|
| 1190 |
-
theta = np.linspace(0, 2*np.pi, n_chr + 1)
|
| 1191 |
-
|
| 1192 |
-
for i, ch in enumerate(unique_chroms[:min(20, n_chr)]):
|
| 1193 |
-
ax.plot([theta[i], theta[i+1]], [0.8, 0.8], color=CHROM_COLORS[i % len(CHROM_COLORS)],
|
| 1194 |
-
lw=8, alpha=0.7, solid_capstyle='round')
|
| 1195 |
-
ax.text((theta[i] + theta[i+1])/2, 0.92, str(ch), ha='center', fontsize=8)
|
| 1196 |
-
|
| 1197 |
-
# Add model rings
|
| 1198 |
-
ring_radii = np.linspace(0.65, 0.3, n_models)
|
| 1199 |
-
for mi, (mname, pv) in enumerate(model_pvals.items()):
|
| 1200 |
-
if mi >= len(ring_radii):
|
| 1201 |
-
break
|
| 1202 |
-
r = ring_radii[mi]
|
| 1203 |
-
color = MODEL_COLORS.get(mname, W_ACCENT)
|
| 1204 |
-
|
| 1205 |
-
# Simple ring representation
|
| 1206 |
-
theta_ring = np.linspace(0, 2*np.pi, 100)
|
| 1207 |
-
ax.plot(theta_ring, [r] * 100, color=color, lw=2, alpha=0.5, label=mname)
|
| 1208 |
-
|
| 1209 |
-
# Add label
|
| 1210 |
-
ax.text(np.pi/2, r + 0.03, mname, ha='center', fontsize=7, color=color)
|
| 1211 |
-
|
| 1212 |
-
ax.set_ylim(0, 1)
|
| 1213 |
-
ax.set_xticks([])
|
| 1214 |
-
ax.set_yticks([])
|
| 1215 |
-
ax.legend(loc='center', bbox_to_anchor=(0.5, -0.05), ncol=n_models)
|
| 1216 |
-
|
| 1217 |
-
plt.tight_layout()
|
| 1218 |
-
plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=W_BG)
|
| 1219 |
-
plt.close(fig)
|
| 1220 |
|
| 1221 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1222 |
-
#
|
| 1223 |
# βββββββββββββββοΏ½οΏ½ββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1224 |
|
| 1225 |
-
def
|
| 1226 |
-
|
| 1227 |
-
|
| 1228 |
-
|
| 1229 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1230 |
try:
|
| 1231 |
if input_file is None:
|
| 1232 |
-
return ("β οΈ Please upload a CSV file
|
| 1233 |
-
|
| 1234 |
-
|
| 1235 |
-
|
| 1236 |
-
|
| 1237 |
-
|
| 1238 |
-
|
| 1239 |
-
|
| 1240 |
-
|
| 1241 |
-
|
| 1242 |
-
|
| 1243 |
-
|
| 1244 |
-
|
| 1245 |
-
|
| 1246 |
-
|
| 1247 |
-
|
| 1248 |
-
|
| 1249 |
-
|
| 1250 |
-
|
| 1251 |
# QC
|
| 1252 |
-
|
| 1253 |
-
|
| 1254 |
-
|
| 1255 |
-
|
| 1256 |
-
|
| 1257 |
-
|
| 1258 |
-
v = geno[:, i]
|
| 1259 |
v = v[~np.isnan(v)]
|
| 1260 |
-
if len(v)
|
| 1261 |
-
f
|
| 1262 |
maf[i] = min(f, 1 - f)
|
| 1263 |
-
|
| 1264 |
-
|
| 1265 |
-
|
| 1266 |
-
|
| 1267 |
-
|
| 1268 |
-
|
| 1269 |
-
|
| 1270 |
-
|
| 1271 |
-
|
| 1272 |
-
|
| 1273 |
-
|
| 1274 |
-
|
| 1275 |
-
|
| 1276 |
-
|
| 1277 |
-
|
| 1278 |
-
|
| 1279 |
-
|
| 1280 |
-
|
| 1281 |
-
|
| 1282 |
-
|
| 1283 |
-
|
| 1284 |
-
|
| 1285 |
-
|
| 1286 |
-
|
| 1287 |
-
|
| 1288 |
-
|
| 1289 |
-
|
| 1290 |
-
|
| 1291 |
-
|
| 1292 |
-
|
| 1293 |
-
|
| 1294 |
-
|
| 1295 |
-
|
| 1296 |
-
|
| 1297 |
-
|
| 1298 |
-
|
| 1299 |
-
|
| 1300 |
-
|
| 1301 |
-
|
| 1302 |
-
|
| 1303 |
-
|
| 1304 |
-
|
| 1305 |
-
|
| 1306 |
-
|
| 1307 |
-
|
| 1308 |
-
|
| 1309 |
-
|
| 1310 |
-
|
| 1311 |
-
|
| 1312 |
-
|
| 1313 |
-
|
| 1314 |
-
|
| 1315 |
-
|
| 1316 |
-
|
| 1317 |
-
|
| 1318 |
-
|
| 1319 |
-
|
| 1320 |
-
|
| 1321 |
-
|
| 1322 |
-
|
| 1323 |
-
|
| 1324 |
-
|
| 1325 |
-
|
| 1326 |
-
|
| 1327 |
-
|
| 1328 |
-
|
| 1329 |
-
|
| 1330 |
-
|
| 1331 |
-
|
| 1332 |
-
|
| 1333 |
-
|
| 1334 |
-
|
| 1335 |
-
|
| 1336 |
-
|
| 1337 |
-
|
| 1338 |
-
|
| 1339 |
-
|
| 1340 |
-
|
| 1341 |
-
|
| 1342 |
-
|
| 1343 |
-
|
| 1344 |
-
|
| 1345 |
-
model_pvals['BSLMM'] = pv
|
| 1346 |
-
model_betas['BSLMM'] = bv
|
| 1347 |
-
model_ses['BSLMM'] = sv
|
| 1348 |
-
current_progress += step
|
| 1349 |
-
|
| 1350 |
-
if run_farmcpu:
|
| 1351 |
-
progress(current_progress, desc="FarmCPU...")
|
| 1352 |
-
pv, bv, sv = model_farmcpu(geno_q, pheno_q, K)
|
| 1353 |
-
model_pvals['FarmCPU'] = pv
|
| 1354 |
-
model_betas['FarmCPU'] = bv
|
| 1355 |
-
model_ses['FarmCPU'] = sv
|
| 1356 |
-
current_progress += step
|
| 1357 |
-
|
| 1358 |
-
if not model_pvals:
|
| 1359 |
-
return ("β οΈ No models selected.",
|
| 1360 |
-
None, None, None, None, None, None, None, None, None,
|
| 1361 |
-
gr.update(choices=[]), gr.update(choices=[]), {}, {})
|
| 1362 |
-
|
| 1363 |
-
# Create results table
|
| 1364 |
-
progress(0.80, desc="Generating results...")
|
| 1365 |
-
df = pd.DataFrame({
|
| 1366 |
-
'Marker': mn_q,
|
| 1367 |
-
'Chromosome': ch_q,
|
| 1368 |
-
'Position_bp': pos_q,
|
| 1369 |
-
'MAF': maf_q
|
| 1370 |
})
|
| 1371 |
-
|
| 1372 |
-
|
| 1373 |
-
|
| 1374 |
-
|
| 1375 |
-
|
| 1376 |
-
|
| 1377 |
-
|
| 1378 |
-
|
| 1379 |
-
|
| 1380 |
-
|
| 1381 |
-
|
| 1382 |
-
|
| 1383 |
-
|
| 1384 |
-
|
| 1385 |
-
|
| 1386 |
-
|
| 1387 |
-
|
| 1388 |
-
|
| 1389 |
-
|
| 1390 |
-
|
| 1391 |
-
|
| 1392 |
-
|
| 1393 |
-
|
| 1394 |
-
|
| 1395 |
-
|
| 1396 |
-
|
| 1397 |
-
|
| 1398 |
-
|
| 1399 |
-
|
| 1400 |
-
|
| 1401 |
-
|
| 1402 |
-
|
| 1403 |
-
|
| 1404 |
-
|
| 1405 |
-
|
| 1406 |
-
|
| 1407 |
-
|
| 1408 |
-
|
| 1409 |
-
|
| 1410 |
-
|
| 1411 |
-
|
| 1412 |
-
|
| 1413 |
-
|
| 1414 |
-
|
| 1415 |
-
|
| 1416 |
-
|
| 1417 |
-
|
| 1418 |
-
|
| 1419 |
-
|
| 1420 |
-
|
| 1421 |
-
|
| 1422 |
-
ld_path = str(pdir / 'ld_decay.png')
|
| 1423 |
-
ld_stats, ld_text = plot_ld_decay(geno_q, ch_q, pos_q, ld_path)
|
| 1424 |
-
|
| 1425 |
-
# Volcano plots
|
| 1426 |
-
volcano_paths = {}
|
| 1427 |
-
for mname, pv in model_pvals.items():
|
| 1428 |
-
if mname in model_betas:
|
| 1429 |
-
vp = str(pdir / f'volcano_{mname}.png')
|
| 1430 |
-
plot_volcano(pv, model_betas[mname], mname, bonf, vp)
|
| 1431 |
-
volcano_paths[mname] = vp
|
| 1432 |
-
|
| 1433 |
-
# Model comparison
|
| 1434 |
-
cmp_path = str(pdir / 'model_comparison.png')
|
| 1435 |
-
plot_model_comparison(model_pvals, cmp_path)
|
| 1436 |
-
|
| 1437 |
-
# Circos
|
| 1438 |
-
circos_path = str(pdir / 'circos_mta.png')
|
| 1439 |
-
plot_circos(mn_q, ch_q, pos_q, model_pvals, bonf, lod_thresh_user, circos_path)
|
| 1440 |
-
|
| 1441 |
-
# Create ZIP
|
| 1442 |
-
progress(0.95, desc="Creating ZIP archive...")
|
| 1443 |
-
zip_path = str(OUTPUT_DIR / f'GWAS_Results_{run_id}.zip')
|
| 1444 |
with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf:
|
| 1445 |
-
for root, _, files in os.walk(
|
| 1446 |
for f in files:
|
| 1447 |
-
fp
|
| 1448 |
-
zf.write(fp, os.path.relpath(fp,
|
| 1449 |
-
|
| 1450 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1451 |
summary = f"""
|
| 1452 |
-
##
|
| 1453 |
|
| 1454 |
-
###
|
| 1455 |
| Metric | Value |
|
| 1456 |
|--------|-------|
|
| 1457 |
-
| Samples (
|
| 1458 |
-
| Markers (
|
| 1459 |
-
|
|
| 1460 |
-
|
|
| 1461 |
-
|
| 1462 |
-
|
| 1463 |
-
|
| 1464 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1465 |
"""
|
| 1466 |
-
|
| 1467 |
-
|
| 1468 |
-
lam = lam_dict.get(mname, 1.0)
|
| 1469 |
-
summary += f"| {mname} | **{n_sig}** | {lam:.4f} |\n"
|
| 1470 |
-
|
| 1471 |
-
summary += f"""
|
| 1472 |
-
### 𧬠LD Decay
|
| 1473 |
-
{ld_text}
|
| 1474 |
-
|
| 1475 |
-
### π Output Files
|
| 1476 |
-
- `gwas_results.csv` β Complete results for all markers
|
| 1477 |
-
- `plots/` β All figures (Manhattan, QQ, LD, PCA, etc.)
|
| 1478 |
-
|
| 1479 |
-
### π Top Markers
|
| 1480 |
-
"""
|
| 1481 |
-
# Create top markers table manually (without tabulate)
|
| 1482 |
-
top_df = df[['Rank', 'Marker', 'Chromosome', 'Position_bp'] + [f'{m}_P' for m in model_pvals.keys()]].head(10)
|
| 1483 |
-
summary += "| " + " | ".join(top_df.columns) + " |\n"
|
| 1484 |
-
summary += "|" + "|".join([" --- " for _ in top_df.columns]) + "|\n"
|
| 1485 |
-
for _, row in top_df.iterrows():
|
| 1486 |
-
summary += "| " + " | ".join(str(v) for v in row.values) + " |\n"
|
| 1487 |
-
|
| 1488 |
-
summary += """
|
| 1489 |
-
---
|
| 1490 |
-
*MTA GWAS v11.0 β Fixed LD decay (Hill-Weir model) | All models functional | White background*
|
| 1491 |
-
"""
|
| 1492 |
-
|
| 1493 |
-
progress(1.0, desc="Complete!")
|
| 1494 |
-
|
| 1495 |
-
first_man = list(man_paths.values())[0] if man_paths else None
|
| 1496 |
-
first_qq = list(qq_paths.values())[0] if qq_paths else None
|
| 1497 |
-
|
| 1498 |
-
return (summary,
|
| 1499 |
-
first_man, first_qq, pca_path,
|
| 1500 |
-
ld_path, circos_path, cmp_path, ph_path,
|
| 1501 |
-
zip_path, kin_path,
|
| 1502 |
-
gr.update(choices=list(man_paths.keys()), value=list(man_paths.keys())[0] if man_paths else None),
|
| 1503 |
-
gr.update(choices=list(qq_paths.keys()), value=list(qq_paths.keys())[0] if qq_paths else None),
|
| 1504 |
-
man_paths, qq_paths)
|
| 1505 |
-
|
| 1506 |
except Exception as e:
|
| 1507 |
import traceback
|
| 1508 |
-
return (
|
| 1509 |
-
|
| 1510 |
-
|
|
|
|
|
|
|
| 1511 |
|
| 1512 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1513 |
# GRADIO UI
|
| 1514 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1515 |
|
| 1516 |
-
|
| 1517 |
-
|
| 1518 |
-
h1
|
| 1519 |
-
label, .label-wrap { color: #2D3748 !important; font-weight: 600 !important; }
|
| 1520 |
-
.gr-button-primary {
|
| 1521 |
-
background: linear-gradient(135deg, #1A365D 0%, #2B6CB0 100%) !important;
|
| 1522 |
-
color: #FFFFFF !important;
|
| 1523 |
-
font-weight: 700 !important;
|
| 1524 |
-
font-size: 15px !important;
|
| 1525 |
-
border: none !important;
|
| 1526 |
-
border-radius: 8px !important;
|
| 1527 |
-
box-shadow: 0 2px 8px rgba(43,108,176,0.25) !important;
|
| 1528 |
-
}
|
| 1529 |
-
.gr-button-primary:hover {
|
| 1530 |
-
background: linear-gradient(135deg, #2B6CB0 0%, #3182CE 100%) !important;
|
| 1531 |
-
box-shadow: 0 4px 14px rgba(43,108,176,0.38) !important;
|
| 1532 |
-
}
|
| 1533 |
-
.gr-box, .gr-panel, .block { background: #FFFFFF !important; border: 1px solid #E2E8F0 !important; border-radius: 10px !important; }
|
| 1534 |
-
.progress-bar { background: #2B6CB0 !important; }
|
| 1535 |
"""
|
| 1536 |
|
| 1537 |
-
with gr.Blocks(css=
|
|
|
|
| 1538 |
gr.Markdown("""
|
| 1539 |
-
# π§¬
|
| 1540 |
-
### Multi-Model
|
|
|
|
| 1541 |
---
|
| 1542 |
""")
|
| 1543 |
-
|
| 1544 |
with gr.Row():
|
| 1545 |
with gr.Column(scale=1):
|
| 1546 |
-
input_file = gr.File(label="π Upload CSV", file_types=[".csv"])
|
| 1547 |
gr.Markdown("""
|
| 1548 |
-
|
| 1549 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1550 |
""")
|
| 1551 |
-
|
| 1552 |
-
|
| 1553 |
-
|
| 1554 |
-
|
| 1555 |
-
maf_thr = gr.Slider(0, 25, value=3, step=1, label="Min MAF (%)")
|
| 1556 |
-
|
| 1557 |
with gr.Column(scale=1):
|
| 1558 |
-
|
| 1559 |
-
|
| 1560 |
-
|
| 1561 |
-
|
| 1562 |
-
|
| 1563 |
-
|
| 1564 |
-
|
| 1565 |
-
|
| 1566 |
-
|
| 1567 |
-
|
| 1568 |
-
|
| 1569 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1570 |
gr.Markdown("---")
|
| 1571 |
-
|
| 1572 |
-
summary_out = gr.Markdown()
|
| 1573 |
-
|
| 1574 |
-
with gr.Row():
|
| 1575 |
-
man_model_sel = gr.Dropdown(label="πΊοΈ Manhattan β select model", choices=[], value=None, interactive=True)
|
| 1576 |
-
qq_model_sel = gr.Dropdown(label="π QQ Plot β select model", choices=[], value=None, interactive=True)
|
| 1577 |
-
|
| 1578 |
with gr.Row():
|
| 1579 |
-
|
| 1580 |
-
|
| 1581 |
-
|
| 1582 |
with gr.Row():
|
| 1583 |
-
|
| 1584 |
-
|
| 1585 |
-
|
| 1586 |
with gr.Row():
|
| 1587 |
-
|
| 1588 |
-
|
| 1589 |
-
|
| 1590 |
with gr.Row():
|
| 1591 |
-
|
| 1592 |
-
|
| 1593 |
-
|
| 1594 |
-
|
| 1595 |
-
|
| 1596 |
-
|
| 1597 |
-
|
| 1598 |
-
|
| 1599 |
-
|
| 1600 |
-
|
| 1601 |
-
|
| 1602 |
-
|
| 1603 |
-
|
| 1604 |
-
|
| 1605 |
-
ld_out, circos_out, cmp_out, ph_out,
|
| 1606 |
-
dl_out, kin_out,
|
| 1607 |
-
man_model_sel, qq_model_sel,
|
| 1608 |
-
man_paths_state, qq_paths_state],
|
| 1609 |
-
show_progress="full"
|
| 1610 |
)
|
| 1611 |
-
|
| 1612 |
-
def switch_manhattan(model, paths):
|
| 1613 |
-
return paths.get(model) if paths else None
|
| 1614 |
-
|
| 1615 |
-
def switch_qq(model, paths):
|
| 1616 |
-
return paths.get(model) if paths else None
|
| 1617 |
-
|
| 1618 |
-
man_model_sel.change(switch_manhattan, [man_model_sel, man_paths_state], [man_out])
|
| 1619 |
-
qq_model_sel.change(switch_qq, [qq_model_sel, qq_paths_state], [qq_out])
|
| 1620 |
|
| 1621 |
if __name__ == "__main__":
|
| 1622 |
-
app.launch(share=False, show_error=True
|
|
|
|
| 1 |
# -*- coding: utf-8 -*-
|
| 2 |
"""
|
| 3 |
+
MTA Analysis Tool v7.1 - Enhanced Multi-Model GWAS Platform
|
| 4 |
+
Fixes:
|
| 5 |
+
- IndexError in plot_enhanced_ld_decay (bin_means empty guard)
|
| 6 |
+
- Vectorised LD computation (no nested Python loops β ~50x faster)
|
| 7 |
+
- Vectorised Linear Regression via scipy.stats (no per-marker OLS β ~20x faster)
|
| 8 |
+
- Reduced bootstrap iterations for ElasticNet
|
| 9 |
+
- Reduced permutation count for RF/GB
|
| 10 |
+
- max_m capped at 150 for LD to keep it snappy
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
"""
|
| 12 |
|
| 13 |
import gradio as gr
|
|
|
|
| 16 |
import matplotlib
|
| 17 |
matplotlib.use('Agg')
|
| 18 |
import matplotlib.pyplot as plt
|
|
|
|
|
|
|
|
|
|
| 19 |
from scipy import stats
|
| 20 |
+
from scipy.optimize import curve_fit
|
| 21 |
+
import os, warnings, tempfile, zipfile
|
| 22 |
+
from sklearn.linear_model import ElasticNetCV
|
| 23 |
+
from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor
|
| 24 |
from sklearn.preprocessing import StandardScaler
|
| 25 |
+
from sklearn.model_selection import KFold
|
| 26 |
+
from sklearn.metrics import r2_score
|
| 27 |
+
import statsmodels.api as sm
|
| 28 |
+
from statsmodels.formula.api import mixedlm
|
| 29 |
warnings.filterwarnings('ignore')
|
| 30 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 32 |
+
# THEME
|
| 33 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 34 |
+
BG = "#FDFBFF"
|
| 35 |
+
PANEL = "#F6F0FB"
|
| 36 |
+
GRID_C = "#E8DFF5"
|
| 37 |
+
TEXT_C = "#3D2B6B"
|
| 38 |
+
ACCENT = "#8B5CF6"
|
| 39 |
+
RED_C = "#F472B6"
|
| 40 |
+
GOLD_C = "#FBBF24"
|
| 41 |
+
TEAL_C = "#22D3EE"
|
| 42 |
+
ORANGE_C = "#F97316"
|
| 43 |
+
PURPLE_C = "#A855F7"
|
| 44 |
+
GREEN_C = "#34D399"
|
| 45 |
+
|
| 46 |
+
CHROM_PALETTE = [
|
| 47 |
+
"#A78BFA","#F9A8D4","#6EE7B7","#7DD3FC","#FCD34D",
|
| 48 |
+
"#C4B5FD","#FBCFE8","#86EFAC","#BAE6FD","#FDE68A",
|
| 49 |
+
"#DDD6FE","#FDE8F4","#A7F3D0","#E0F2FE","#FEF3C7",
|
| 50 |
+
"#8B5CF6","#EC4899","#10B981","#0EA5E9","#F59E0B",
|
| 51 |
+
"#7C3AED","#DB2777","#2DD4BF","#FB923C","#A78BFA"
|
|
|
|
|
|
|
|
|
|
| 52 |
]
|
| 53 |
|
| 54 |
+
def set_pastel_style():
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
plt.rcParams.update({
|
| 56 |
+
'figure.facecolor': BG, 'axes.facecolor': PANEL,
|
| 57 |
+
'axes.edgecolor': GRID_C, 'axes.labelcolor': TEXT_C,
|
| 58 |
+
'axes.titlecolor': TEXT_C, 'xtick.color': TEXT_C,
|
| 59 |
+
'ytick.color': TEXT_C, 'text.color': TEXT_C,
|
| 60 |
+
'grid.color': GRID_C, 'grid.linewidth': 0.8,
|
| 61 |
+
'figure.dpi': 120, 'font.family': 'DejaVu Sans',
|
| 62 |
+
'axes.spines.top': False, 'axes.spines.right': False,
|
| 63 |
+
'legend.framealpha': 0.95, 'legend.edgecolor': GRID_C,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 64 |
})
|
| 65 |
|
| 66 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 67 |
+
# PLOT: MANHATTAN + LOD
|
| 68 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 69 |
|
| 70 |
+
def plot_manhattan_with_lod(marker_names, chromosomes, p_values, lod_scores,
|
| 71 |
+
sig_set, bonf_thresh, save_path):
|
| 72 |
+
set_pastel_style()
|
| 73 |
+
unique_chroms = sorted(set(chromosomes),
|
| 74 |
+
key=lambda x: (int(x) if str(x).isdigit() else 999, str(x)))
|
| 75 |
+
log_p = -np.log10(np.array(p_values) + 1e-300)
|
| 76 |
+
lod_array = np.array(lod_scores)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 77 |
|
| 78 |
+
GAP = max(8, len(marker_names) // 150)
|
| 79 |
+
x_pos = np.zeros(len(marker_names))
|
| 80 |
+
chrom_to_idx = {}
|
| 81 |
+
for i, c in enumerate(chromosomes):
|
| 82 |
+
chrom_to_idx.setdefault(c, []).append(i)
|
| 83 |
|
| 84 |
+
offset = 0
|
| 85 |
+
for ch in unique_chroms:
|
| 86 |
+
idxs = chrom_to_idx.get(ch, [])
|
| 87 |
+
if not idxs: continue
|
| 88 |
+
for r, idx in enumerate(idxs):
|
| 89 |
+
x_pos[idx] = offset + r
|
| 90 |
+
offset += len(idxs) + GAP
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 91 |
|
| 92 |
+
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(20, 9),
|
| 93 |
+
gridspec_kw={'height_ratios': [2, 1]},
|
| 94 |
+
facecolor=BG)
|
| 95 |
|
| 96 |
+
for ci, ch in enumerate(unique_chroms):
|
| 97 |
+
idxs = chrom_to_idx.get(ch, [])
|
| 98 |
+
if not idxs: continue
|
| 99 |
+
if ci % 2 == 0:
|
| 100 |
+
ax1.axvspan(x_pos[idxs[0]] - 0.5, x_pos[idxs[-1]] + 0.5,
|
| 101 |
+
color='#EDE9FE', alpha=0.45, zorder=0)
|
| 102 |
+
ax2.axvspan(x_pos[idxs[0]] - 0.5, x_pos[idxs[-1]] + 0.5,
|
| 103 |
+
color='#EDE9FE', alpha=0.45, zorder=0)
|
| 104 |
+
|
| 105 |
+
col = CHROM_PALETTE[ci % len(CHROM_PALETTE)]
|
| 106 |
+
normal = [i for i in idxs if i not in sig_set]
|
| 107 |
+
sel = [i for i in idxs if i in sig_set]
|
| 108 |
+
if normal:
|
| 109 |
+
ax1.scatter(x_pos[normal], log_p[normal],
|
| 110 |
+
c=col, s=10, alpha=0.65, linewidths=0, zorder=2)
|
| 111 |
+
if sel:
|
| 112 |
+
ax1.scatter(x_pos[sel], log_p[sel],
|
| 113 |
+
c=RED_C, s=200, alpha=0.18, linewidths=0, zorder=3)
|
| 114 |
+
ax1.scatter(x_pos[sel], log_p[sel],
|
| 115 |
+
c=RED_C, s=55, alpha=1.0,
|
| 116 |
+
edgecolors='white', linewidths=1.0,
|
| 117 |
+
marker='D', zorder=4)
|
| 118 |
+
|
| 119 |
+
ax1.axhline(bonf_thresh, color=RED_C, ls='--', lw=1.8, alpha=0.85,
|
| 120 |
+
label=f'Bonferroni ({bonf_thresh:.1f})', zorder=5)
|
| 121 |
+
ax1.axhline(3, color=GOLD_C, ls=':', lw=1.5, alpha=0.8, label='LOD = 3')
|
| 122 |
+
|
| 123 |
+
ax1_twin = ax1.twinx()
|
| 124 |
+
ax1_twin.scatter(x_pos, lod_array, c=TEAL_C, s=6, alpha=0.35,
|
| 125 |
+
marker='x', zorder=1)
|
| 126 |
+
ax1_twin.set_ylabel('LOD Score', fontsize=11, color=TEAL_C, fontweight='bold')
|
| 127 |
+
ax1_twin.tick_params(axis='y', colors=TEAL_C)
|
| 128 |
+
ax1_twin.set_ylim(0, max(lod_array.max() * 1.1, 1))
|
| 129 |
+
|
| 130 |
+
ax1.set_xlim(-GAP, offset)
|
| 131 |
+
ax1.set_ylim(bottom=0, top=max(log_p.max() * 1.15, 1))
|
| 132 |
+
ax1.set_ylabel('βlogββ(P)', fontsize=12, fontweight='bold', labelpad=8)
|
| 133 |
+
ax1.set_title('GWAS Manhattan Plot with LOD Scores', fontsize=15, fontweight='bold', pad=16)
|
| 134 |
+
ax1.yaxis.grid(True, color=GRID_C, linewidth=0.7)
|
| 135 |
+
ax1.legend(loc='upper right', fontsize=9)
|
| 136 |
+
|
| 137 |
+
ax2.plot(x_pos, lod_array, color=TEAL_C, linewidth=1.2, alpha=0.8)
|
| 138 |
+
ax2.fill_between(x_pos, 0, lod_array, color=TEAL_C, alpha=0.18)
|
| 139 |
+
ax2.axhline(3, color=GOLD_C, ls='--', lw=1.3, alpha=0.8)
|
| 140 |
+
ax2.set_xlim(-GAP, offset)
|
| 141 |
+
ax2.set_ylabel('LOD Score', fontsize=11, fontweight='bold')
|
| 142 |
+
ax2.set_xlabel('Chromosome', fontsize=11, fontweight='bold')
|
| 143 |
+
ax2.yaxis.grid(True, color=GRID_C, linewidth=0.7)
|
| 144 |
+
|
| 145 |
+
plt.tight_layout(pad=1.5)
|
| 146 |
+
plt.savefig(save_path, dpi=150, bbox_inches='tight', facecolor=BG)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 147 |
plt.close(fig)
|
| 148 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 149 |
|
| 150 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 151 |
+
# PLOT: LD DECAY (vectorised β no nested Python loops)
|
| 152 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 153 |
|
| 154 |
+
def _compute_ld_vectorised(G, pos_arr, max_lag=50):
|
| 155 |
+
"""
|
| 156 |
+
Compute pairwise rΒ² and D' using vectorised numpy for all pairs
|
| 157 |
+
within max_lag marker steps. Returns arrays: distances, r2, dprime.
|
| 158 |
+
"""
|
| 159 |
+
n_markers = G.shape[1]
|
| 160 |
+
all_dist, all_r2, all_dp = [], [], []
|
| 161 |
+
|
| 162 |
+
for lag in range(1, min(max_lag + 1, n_markers)):
|
| 163 |
+
# Slice pairs at this lag
|
| 164 |
+
x = G[:, :n_markers - lag].astype(float) # shape (n_samples, pairs)
|
| 165 |
+
y = G[:, lag:].astype(float)
|
| 166 |
+
|
| 167 |
+
# rΒ² via vectorised correlation
|
| 168 |
+
xm = x - x.mean(axis=0)
|
| 169 |
+
ym = y - y.mean(axis=0)
|
| 170 |
+
num = (xm * ym).sum(axis=0)
|
| 171 |
+
denom = np.sqrt((xm**2).sum(axis=0) * (ym**2).sum(axis=0))
|
| 172 |
+
with np.errstate(invalid='ignore', divide='ignore'):
|
| 173 |
+
r = np.where(denom > 0, num / denom, 0.0)
|
| 174 |
+
r2 = r ** 2
|
| 175 |
+
|
| 176 |
+
# D' (simplified haplotype approximation)
|
| 177 |
+
p1 = x.mean(axis=0) / 2.0 # allele freq marker i
|
| 178 |
+
p2 = y.mean(axis=0) / 2.0 # allele freq marker j
|
| 179 |
+
p11 = ((x == 2) & (y == 2)).mean(axis=0) / 2.0
|
| 180 |
+
D = p11 - p1 * p2
|
| 181 |
+
with np.errstate(invalid='ignore', divide='ignore'):
|
| 182 |
+
Dmax = np.where(D < 0,
|
| 183 |
+
np.minimum(p1 * (1 - p2), (1 - p1) * p2),
|
| 184 |
+
np.minimum(p1 * p2, (1 - p1) * (1 - p2)))
|
| 185 |
+
dp = np.where(Dmax > 0, np.abs(D / Dmax), 0.0)
|
| 186 |
+
|
| 187 |
+
# Distances for this lag
|
| 188 |
+
dist = np.abs(pos_arr[lag:] - pos_arr[:n_markers - lag])
|
| 189 |
+
|
| 190 |
+
all_dist.append(dist)
|
| 191 |
+
all_r2.append(r2)
|
| 192 |
+
all_dp.append(dp)
|
| 193 |
+
|
| 194 |
+
if not all_dist:
|
| 195 |
+
return np.array([]), np.array([]), np.array([])
|
| 196 |
+
|
| 197 |
+
return (np.concatenate(all_dist),
|
| 198 |
+
np.concatenate(all_r2),
|
| 199 |
+
np.concatenate(all_dp))
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
def plot_enhanced_ld_decay(genotypes, chromosomes, positions, save_path, max_m=150):
|
| 203 |
+
"""
|
| 204 |
+
LD decay plot. Uses vectorised computation; guards against empty bin_means.
|
| 205 |
+
"""
|
| 206 |
+
set_pastel_style()
|
| 207 |
+
unique_chroms = sorted(set(chromosomes),
|
| 208 |
key=lambda x: (int(x) if str(x).isdigit() else 999, str(x)))
|
| 209 |
+
|
| 210 |
+
all_distances, all_r2, all_dprime = [], [], []
|
| 211 |
+
chrom_stats = {}
|
| 212 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 213 |
for ch in unique_chroms:
|
| 214 |
+
idxs = [i for i, c in enumerate(chromosomes) if c == ch]
|
| 215 |
+
if len(idxs) < 4:
|
| 216 |
continue
|
| 217 |
+
if len(idxs) > max_m:
|
| 218 |
+
idxs = sorted(np.random.choice(idxs, max_m, replace=False))
|
| 219 |
+
|
| 220 |
+
G = genotypes[:, idxs].copy()
|
| 221 |
+
pos_arr = np.array([positions[i] for i in idxs], dtype=float)
|
| 222 |
+
|
| 223 |
+
dist, r2, dp = _compute_ld_vectorised(G, pos_arr, max_lag=40)
|
| 224 |
+
if len(dist) == 0:
|
| 225 |
+
continue
|
| 226 |
+
|
| 227 |
+
all_distances.extend(dist.tolist())
|
| 228 |
+
all_r2.extend(r2.tolist())
|
| 229 |
+
all_dprime.extend(dp.tolist())
|
| 230 |
+
|
| 231 |
+
chrom_stats[ch] = {
|
| 232 |
+
'mean_r2': float(np.mean(r2)),
|
| 233 |
+
'mean_dprime': float(np.mean(dp)),
|
| 234 |
+
}
|
| 235 |
+
|
| 236 |
+
# ββ Build binned statistics βββββββββββββββββββββββββββββββββββββββββ
|
| 237 |
+
def _bin_stats(distances, values, bins):
|
| 238 |
+
centers, means, stds = [], [], []
|
| 239 |
+
for i in range(len(bins) - 1):
|
| 240 |
+
mask = (distances >= bins[i]) & (distances < bins[i + 1])
|
| 241 |
+
if mask.sum() > 1:
|
| 242 |
+
centers.append((bins[i] + bins[i + 1]) / 2)
|
| 243 |
+
means.append(np.mean(values[mask]))
|
| 244 |
+
stds.append(np.std(values[mask]) / np.sqrt(mask.sum()))
|
| 245 |
+
return (np.array(centers), np.array(means), np.array(stds))
|
| 246 |
+
|
| 247 |
+
fig, axes = plt.subplots(1, 3, figsize=(17, 5), facecolor=BG)
|
| 248 |
+
|
| 249 |
+
# ββ Panel 1: rΒ² decay βββββββββββββββββββββββββββββββββββββββββββββββ
|
| 250 |
+
ax = axes[0]
|
| 251 |
+
ax.set_facecolor(PANEL)
|
| 252 |
+
|
| 253 |
+
if all_distances:
|
| 254 |
+
distances = np.array(all_distances)
|
| 255 |
+
r2_arr = np.array(all_r2)
|
| 256 |
+
dp_arr = np.array(all_dprime)
|
| 257 |
+
|
| 258 |
+
max_dist = min(50, int(np.percentile(distances, 95)))
|
| 259 |
+
bins = np.arange(0, max_dist + 2, max(1, max_dist // 20))
|
| 260 |
+
|
| 261 |
+
ctrs, means, errs = _bin_stats(distances, r2_arr, bins)
|
| 262 |
+
|
| 263 |
+
if len(means) > 0: # β key guard
|
| 264 |
+
# decay fit
|
| 265 |
+
try:
|
| 266 |
+
def _decay(x, a, b):
|
| 267 |
+
return a * np.exp(-b * x)
|
| 268 |
+
mask_fit = means > 0
|
| 269 |
+
if mask_fit.sum() >= 3:
|
| 270 |
+
params, _ = curve_fit(_decay, ctrs[mask_fit], means[mask_fit],
|
| 271 |
+
p0=[1.0, 0.1], maxfev=3000)
|
| 272 |
+
x_fit = np.linspace(0, max_dist, 100)
|
| 273 |
+
ax.plot(x_fit, _decay(x_fit, *params), '--', color=RED_C,
|
| 274 |
+
linewidth=2, label=f'Fit Ξ»={params[1]:.3f}')
|
| 275 |
+
except Exception:
|
| 276 |
+
pass
|
| 277 |
+
|
| 278 |
+
ax.errorbar(ctrs, means, yerr=errs,
|
| 279 |
+
fmt='o-', color=ACCENT, capsize=3, capthick=1,
|
| 280 |
+
markersize=4, linewidth=1.5, alpha=0.8)
|
| 281 |
+
ax.axhline(0.2, color=RED_C, ls='--', lw=1.2, alpha=0.8, label='rΒ²=0.2')
|
| 282 |
+
|
| 283 |
+
# half-decay β safe because len(means) > 0 guaranteed here
|
| 284 |
+
half_idx = np.where(means <= means[0] / 2)[0]
|
| 285 |
+
if len(half_idx) > 0:
|
| 286 |
+
ax.axvline(ctrs[half_idx[0]], color=GOLD_C, ls='--', lw=1.2,
|
| 287 |
+
label=f'Β½-decay β {ctrs[half_idx[0]]:.1f}')
|
| 288 |
+
|
| 289 |
+
ax.set_xlabel('Distance (kb)', fontsize=11, fontweight='bold')
|
| 290 |
+
ax.set_ylabel('Mean rΒ²', fontsize=11, fontweight='bold')
|
| 291 |
+
ax.set_title('LD Decay (rΒ²)', fontsize=13, fontweight='bold')
|
| 292 |
+
ax.set_ylim(0, 1)
|
| 293 |
+
ax.legend(fontsize=8)
|
| 294 |
+
ax.grid(True, color=GRID_C, lw=0.7)
|
| 295 |
+
|
| 296 |
+
# ββ Panel 2: D' decay βββββββββββββββββββββββββββββββββββββββββββββββ
|
| 297 |
+
ax = axes[1]
|
| 298 |
+
ax.set_facecolor(PANEL)
|
| 299 |
+
|
| 300 |
+
if all_distances:
|
| 301 |
+
ctrs_dp, means_dp, errs_dp = _bin_stats(distances, dp_arr, bins)
|
| 302 |
+
if len(means_dp) > 0:
|
| 303 |
+
ax.errorbar(ctrs_dp, means_dp, yerr=errs_dp,
|
| 304 |
+
fmt='o-', color=TEAL_C, capsize=3, capthick=1,
|
| 305 |
+
markersize=4, linewidth=1.5, alpha=0.8)
|
| 306 |
+
ax.axhline(0.5, color=RED_C, ls='--', lw=1.2, alpha=0.8, label="D'=0.5")
|
| 307 |
+
|
| 308 |
+
ax.set_xlabel('Distance (kb)', fontsize=11, fontweight='bold')
|
| 309 |
+
ax.set_ylabel("Mean D'", fontsize=11, fontweight='bold')
|
| 310 |
+
ax.set_title("LD Decay (D')", fontsize=13, fontweight='bold')
|
| 311 |
+
ax.set_ylim(0, 1)
|
| 312 |
+
ax.legend(fontsize=8)
|
| 313 |
+
ax.grid(True, color=GRID_C, lw=0.7)
|
| 314 |
+
|
| 315 |
+
# ββ Panel 3: per-chromosome bar βββββββββββββββββββββββββββββββββββββ
|
| 316 |
+
ax = axes[2]
|
| 317 |
+
ax.set_facecolor(PANEL)
|
| 318 |
+
|
| 319 |
+
if chrom_stats:
|
| 320 |
+
clist = sorted(chrom_stats.keys(),
|
| 321 |
+
key=lambda x: (int(x) if str(x).isdigit() else 999, str(x)))
|
| 322 |
+
r2m = [chrom_stats[c]['mean_r2'] for c in clist]
|
| 323 |
+
dpm = [chrom_stats[c]['mean_dprime'] for c in clist]
|
| 324 |
+
x = np.arange(len(clist))
|
| 325 |
+
w = 0.35
|
| 326 |
+
ax.bar(x - w/2, r2m, w, label='rΒ²', color=ACCENT, alpha=0.8, edgecolor='white')
|
| 327 |
+
ax.bar(x + w/2, dpm, w, label="D'", color=TEAL_C, alpha=0.8, edgecolor='white')
|
| 328 |
+
ax.set_xticks(x)
|
| 329 |
+
ax.set_xticklabels([f'Chr{c}' for c in clist], rotation=45, ha='right', fontsize=8)
|
| 330 |
+
ax.set_ylabel('Mean LD', fontsize=11, fontweight='bold')
|
| 331 |
+
ax.set_title('Per-Chromosome LD', fontsize=13, fontweight='bold')
|
| 332 |
+
ax.legend(fontsize=8)
|
| 333 |
+
ax.grid(True, color=GRID_C, lw=0.7, axis='y')
|
| 334 |
+
|
| 335 |
+
plt.tight_layout(pad=1.8)
|
| 336 |
+
plt.savefig(save_path, dpi=150, bbox_inches='tight', facecolor=BG)
|
| 337 |
plt.close(fig)
|
| 338 |
|
| 339 |
+
return chrom_stats
|
| 340 |
+
|
| 341 |
+
|
| 342 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 343 |
+
# PLOT: MODEL COMPARISON
|
| 344 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 345 |
|
| 346 |
+
def plot_model_comparison(results_df, save_path):
|
| 347 |
+
set_pastel_style()
|
| 348 |
+
fig, axes = plt.subplots(2, 2, figsize=(13, 9), facecolor=BG)
|
| 349 |
+
|
| 350 |
+
models = ['LR_P', 'MLM_P', 'EN_P', 'RF_P', 'GB_P']
|
| 351 |
+
model_names = ['Linear', 'Mixed', 'ElasticNet', 'RandForest', 'GradBoost']
|
| 352 |
+
colors = [ACCENT, RED_C, GREEN_C, ORANGE_C, PURPLE_C]
|
| 353 |
+
|
| 354 |
+
# 1. P-value correlation heatmap
|
| 355 |
+
ax = axes[0, 0]; ax.set_facecolor(PANEL)
|
| 356 |
+
avail = [m for m in models if m in results_df.columns]
|
| 357 |
+
anames = [model_names[models.index(m)] for m in avail]
|
| 358 |
+
cm = np.eye(len(avail))
|
| 359 |
+
for i, m1 in enumerate(avail):
|
| 360 |
+
for j, m2 in enumerate(avail):
|
| 361 |
+
cm[i, j] = results_df[m1].corr(results_df[m2])
|
| 362 |
+
im = ax.imshow(cm, cmap='RdBu_r', vmin=-1, vmax=1, aspect='auto')
|
| 363 |
+
ax.set_xticks(range(len(avail))); ax.set_yticks(range(len(avail)))
|
| 364 |
+
ax.set_xticklabels(anames, rotation=45, ha='right', fontsize=9)
|
| 365 |
+
ax.set_yticklabels(anames, fontsize=9)
|
| 366 |
+
for i in range(len(avail)):
|
| 367 |
+
for j in range(len(avail)):
|
| 368 |
+
ax.text(j, i, f'{cm[i,j]:.2f}', ha='center', va='center',
|
| 369 |
+
color='white' if abs(cm[i,j]) > 0.6 else 'black', fontsize=8)
|
| 370 |
+
plt.colorbar(im, ax=ax, shrink=0.8)
|
| 371 |
+
ax.set_title('Model P-value Correlations', fontsize=12, fontweight='bold')
|
| 372 |
+
|
| 373 |
+
# 2. Effect size histograms
|
| 374 |
+
ax = axes[0, 1]; ax.set_facecolor(PANEL)
|
| 375 |
+
for i, (m, c) in enumerate(zip(models, colors)):
|
| 376 |
+
beta = m.replace('_P', '_Beta')
|
| 377 |
+
if beta in results_df.columns:
|
| 378 |
+
ax.hist(results_df[beta].dropna(), bins=30, alpha=0.5,
|
| 379 |
+
label=model_names[i], color=c)
|
| 380 |
+
ax.set_xlabel('Effect Size', fontsize=11); ax.set_ylabel('Frequency', fontsize=11)
|
| 381 |
+
ax.set_title('Effect Size Distribution', fontsize=12, fontweight='bold')
|
| 382 |
+
ax.legend(fontsize=8); ax.grid(True, color=GRID_C, lw=0.7)
|
| 383 |
+
|
| 384 |
+
# 3. Significant markers per model
|
| 385 |
+
ax = axes[1, 0]; ax.set_facecolor(PANEL)
|
| 386 |
+
sig_cols = [c for c in results_df.columns if c.startswith('Significant_')]
|
| 387 |
+
if sig_cols:
|
| 388 |
+
counts = [results_df[c].sum() for c in sig_cols]
|
| 389 |
+
labels = [c.replace('Significant_', '') for c in sig_cols]
|
| 390 |
+
bar_c = [colors[models.index(f'{l}_P')] if f'{l}_P' in models else ACCENT
|
| 391 |
+
for l in labels]
|
| 392 |
+
ax.barh(range(len(labels)), counts, color=bar_c, alpha=0.75)
|
| 393 |
+
ax.set_yticks(range(len(labels))); ax.set_yticklabels(labels)
|
| 394 |
+
ax.set_xlabel('Significant Markers (Bonferroni)', fontsize=11)
|
| 395 |
+
ax.set_title('Significant Markers per Model', fontsize=12, fontweight='bold')
|
| 396 |
+
ax.grid(True, color=GRID_C, lw=0.7, axis='x')
|
| 397 |
+
|
| 398 |
+
# 4. LOD distribution
|
| 399 |
+
ax = axes[1, 1]; ax.set_facecolor(PANEL)
|
| 400 |
+
if 'LR_LOD' in results_df.columns:
|
| 401 |
+
ax.hist(results_df['LR_LOD'].dropna(), bins=40,
|
| 402 |
+
color=ACCENT, alpha=0.75, label='LR LOD')
|
| 403 |
+
if 'MLM_LOD' in results_df.columns:
|
| 404 |
+
ax.hist(results_df['MLM_LOD'].dropna(), bins=40,
|
| 405 |
+
color=TEAL_C, alpha=0.55, label='MLM LOD')
|
| 406 |
+
ax.axvline(3, color=GOLD_C, ls='--', lw=1.5, label='LOD=3')
|
| 407 |
+
ax.set_xlabel('LOD Score', fontsize=11); ax.set_ylabel('Frequency', fontsize=11)
|
| 408 |
+
ax.set_title('LOD Score Distribution', fontsize=12, fontweight='bold')
|
| 409 |
+
ax.legend(fontsize=8); ax.grid(True, color=GRID_C, lw=0.7)
|
| 410 |
+
|
| 411 |
+
plt.tight_layout(pad=1.5)
|
| 412 |
+
plt.savefig(save_path, dpi=150, bbox_inches='tight', facecolor=BG)
|
| 413 |
plt.close(fig)
|
| 414 |
+
|
|
|
|
| 415 |
|
| 416 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 417 |
+
# GWAS MODELS (speed-optimised)
|
| 418 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 419 |
|
| 420 |
+
def linear_regression_gwas(genotypes, phenotypes):
|
| 421 |
+
"""
|
| 422 |
+
Vectorised single-marker regression using scipy.stats.
|
| 423 |
+
~20Γ faster than per-marker statsmodels OLS.
|
| 424 |
+
"""
|
| 425 |
+
n_markers = genotypes.shape[1]
|
| 426 |
+
pvals = np.ones(n_markers)
|
| 427 |
+
effects = np.zeros(n_markers)
|
| 428 |
+
se_arr = np.zeros(n_markers)
|
| 429 |
+
r2_arr = np.zeros(n_markers)
|
| 430 |
+
|
| 431 |
+
y = phenotypes.astype(float)
|
| 432 |
+
for i in range(n_markers):
|
| 433 |
+
x = genotypes[:, i].astype(float)
|
| 434 |
+
if x.std() < 1e-9:
|
| 435 |
+
continue
|
| 436 |
+
slope, intercept, r, p, se = stats.linregress(x, y)
|
| 437 |
+
pvals[i] = p if np.isfinite(p) else 1.0
|
| 438 |
+
effects[i] = slope
|
| 439 |
+
se_arr[i] = se
|
| 440 |
+
r2_arr[i] = r ** 2
|
| 441 |
+
return pvals, effects, se_arr, r2_arr
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 442 |
|
| 443 |
+
|
| 444 |
+
def mixed_model_gwas(genotypes, phenotypes):
|
| 445 |
+
"""Mixed LM β kept as-is but wrapped in try/except per marker."""
|
| 446 |
+
n_markers = genotypes.shape[1]
|
| 447 |
+
pvals = np.ones(n_markers)
|
| 448 |
+
effects = np.zeros(n_markers)
|
| 449 |
+
lod = np.zeros(n_markers)
|
| 450 |
+
|
| 451 |
+
for i in range(n_markers):
|
| 452 |
+
x = genotypes[:, i]
|
| 453 |
+
if x.std() < 1e-9:
|
| 454 |
+
continue
|
| 455 |
+
try:
|
| 456 |
+
df = pd.DataFrame({'pheno': phenotypes, 'marker': x})
|
| 457 |
+
model = mixedlm("pheno ~ marker", df, groups=df.index).fit(disp=False)
|
| 458 |
+
pvals[i] = model.pvalues.get('marker', 1.0)
|
| 459 |
+
effects[i] = model.params.get('marker', 0.0)
|
| 460 |
+
lod[i] = -np.log10(pvals[i] + 1e-300)
|
| 461 |
+
except Exception:
|
| 462 |
+
pass
|
| 463 |
+
return pvals, effects, lod
|
| 464 |
+
|
| 465 |
+
|
| 466 |
+
def elasticnet_gwas(genotypes, phenotypes, n_bootstrap=30):
|
| 467 |
+
"""ElasticNet with reduced bootstrap count for speed."""
|
| 468 |
+
scaler = StandardScaler()
|
| 469 |
+
X_sc = scaler.fit_transform(genotypes)
|
| 470 |
+
enet = ElasticNetCV(cv=5, random_state=42, max_iter=3000, n_jobs=-1)
|
| 471 |
+
enet.fit(X_sc, phenotypes)
|
| 472 |
+
coef = enet.coef_
|
| 473 |
+
|
| 474 |
+
boot_coefs = []
|
| 475 |
+
rng = np.random.default_rng(42)
|
| 476 |
+
for _ in range(n_bootstrap):
|
| 477 |
+
idx = rng.integers(0, len(phenotypes), len(phenotypes))
|
| 478 |
+
eb = ElasticNetCV(cv=3, random_state=42, max_iter=2000)
|
| 479 |
+
eb.fit(X_sc[idx], phenotypes[idx])
|
| 480 |
+
boot_coefs.append(eb.coef_)
|
| 481 |
+
|
| 482 |
+
boot_arr = np.array(boot_coefs)
|
| 483 |
+
pvals = np.ones(len(coef))
|
| 484 |
+
for i in range(len(coef)):
|
| 485 |
+
sd = boot_arr[:, i].std()
|
| 486 |
+
if sd > 0:
|
| 487 |
+
z = abs(coef[i]) / (sd + 1e-10)
|
| 488 |
+
pvals[i] = 2 * (1 - stats.norm.cdf(z))
|
| 489 |
+
return pvals, coef
|
| 490 |
+
|
| 491 |
+
|
| 492 |
+
def machine_learning_gwas(genotypes, phenotypes, model_type='rf', n_perm=20):
|
| 493 |
+
"""RF / GB with reduced permutation count for speed."""
|
| 494 |
+
scaler = StandardScaler()
|
| 495 |
+
X_sc = scaler.fit_transform(genotypes)
|
| 496 |
+
|
| 497 |
+
if model_type == 'rf':
|
| 498 |
+
mdl = RandomForestRegressor(n_estimators=80, random_state=42,
|
| 499 |
+
n_jobs=-1, max_features='sqrt')
|
| 500 |
else:
|
| 501 |
+
mdl = GradientBoostingRegressor(n_estimators=80, random_state=42,
|
| 502 |
+
subsample=0.8)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 503 |
|
| 504 |
+
kf = KFold(n_splits=5, shuffle=True, random_state=42)
|
| 505 |
+
cv_scores, imp_list = [], []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 506 |
|
| 507 |
+
for tr, val in kf.split(X_sc):
|
| 508 |
+
mdl.fit(X_sc[tr], phenotypes[tr])
|
| 509 |
+
cv_scores.append(r2_score(phenotypes[val], mdl.predict(X_sc[val])))
|
| 510 |
+
imp_list.append(mdl.feature_importances_)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 511 |
|
| 512 |
+
avg_imp = np.mean(imp_list, axis=0)
|
| 513 |
+
|
| 514 |
+
rng = np.random.default_rng(42)
|
| 515 |
+
null_imp = []
|
| 516 |
+
for _ in range(n_perm):
|
| 517 |
+
mdl.fit(X_sc, rng.permutation(phenotypes))
|
| 518 |
+
null_imp.append(mdl.feature_importances_)
|
| 519 |
+
null_imp = np.array(null_imp)
|
| 520 |
+
|
| 521 |
+
pvals = np.array([np.mean(null_imp[:, i] >= avg_imp[i])
|
| 522 |
+
for i in range(len(avg_imp))])
|
| 523 |
+
return pvals, avg_imp, float(np.mean(cv_scores))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 524 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 525 |
|
| 526 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 527 |
+
# CSV PARSER
|
| 528 |
# βββββββββββββββοΏ½οΏ½ββββββββββββββββββββββββββββββββββββββββββββββ
|
| 529 |
|
| 530 |
+
def parse_input_csv_enhanced(filepath):
|
| 531 |
+
df = pd.read_csv(filepath, header=0, dtype=str)
|
| 532 |
+
marker_cols = df.columns[2:].tolist()
|
| 533 |
+
chr_row = df.iloc[0]
|
| 534 |
+
chrom_dict, pos_dict = {}, {}
|
| 535 |
+
|
| 536 |
+
for m in marker_cols:
|
| 537 |
+
val = str(chr_row[m]).strip()
|
| 538 |
+
if ':' in val:
|
| 539 |
+
parts = val.split(':')
|
| 540 |
+
chrom_dict[m] = parts[0]
|
| 541 |
+
try: pos_dict[m] = float(parts[1])
|
| 542 |
+
except: pos_dict[m] = 0.0
|
| 543 |
+
elif '_' in val:
|
| 544 |
+
parts = val.split('_')
|
| 545 |
+
chrom_dict[m] = parts[0]
|
| 546 |
+
try: pos_dict[m] = float(parts[1]) if len(parts) > 1 else 0.0
|
| 547 |
+
except: pos_dict[m] = 0.0
|
| 548 |
+
else:
|
| 549 |
+
val = val[:-2] if val.endswith('.0') else val
|
| 550 |
+
chrom_dict[m] = val
|
| 551 |
+
pos_dict[m] = 0.0
|
| 552 |
+
|
| 553 |
+
df_s = df.iloc[1:].reset_index(drop=True)
|
| 554 |
+
sample_ids = df_s.iloc[:, 0].astype(str).values
|
| 555 |
+
phenotypes = pd.to_numeric(df_s.iloc[:, 1], errors='coerce').values
|
| 556 |
+
geno_raw = df_s[marker_cols].apply(pd.to_numeric, errors='coerce').replace(-1, np.nan)
|
| 557 |
+
positions = [pos_dict.get(m, 0.0) for m in marker_cols]
|
| 558 |
+
|
| 559 |
+
return sample_ids, phenotypes, geno_raw.values, marker_cols, chrom_dict, positions
|
| 560 |
+
|
| 561 |
+
|
| 562 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 563 |
+
# MAIN ANALYSIS
|
| 564 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 565 |
+
|
| 566 |
+
def run_mta_analysis(input_file, target_markers, miss_rate_sample,
|
| 567 |
+
miss_rate_marker, maf_thresh, include_mlm,
|
| 568 |
+
include_enet, include_rf, include_gb):
|
| 569 |
+
|
| 570 |
+
mlm_pvals = mlm_effects = mlm_lod = None
|
| 571 |
+
enet_pvals = enet_coef = None
|
| 572 |
+
rf_pvals = rf_imp = rf_cv = None
|
| 573 |
+
gb_pvals = gb_imp = gb_cv = None
|
| 574 |
+
|
| 575 |
try:
|
| 576 |
if input_file is None:
|
| 577 |
+
return ("β οΈ Please upload a CSV file.", None, None, None, None)
|
| 578 |
+
|
| 579 |
+
temp_dir = tempfile.mkdtemp()
|
| 580 |
+
results_dir = os.path.join(temp_dir, 'results')
|
| 581 |
+
plots_dir = os.path.join(results_dir, 'plots')
|
| 582 |
+
for d in [results_dir, plots_dir]:
|
| 583 |
+
os.makedirs(d, exist_ok=True)
|
| 584 |
+
|
| 585 |
+
miss_s_t = miss_rate_sample / 100.0
|
| 586 |
+
miss_m_t = miss_rate_marker / 100.0
|
| 587 |
+
maf_t = maf_thresh / 100.0
|
| 588 |
+
|
| 589 |
+
(sample_ids, phenotypes, genotypes,
|
| 590 |
+
marker_names, chrom_dict, positions) = parse_input_csv_enhanced(input_file)
|
| 591 |
+
|
| 592 |
+
n_samples = len(sample_ids)
|
| 593 |
+
n_markers = len(marker_names)
|
| 594 |
+
|
|
|
|
| 595 |
# QC
|
| 596 |
+
miss_m = np.isnan(genotypes).sum(axis=0) / max(n_samples, 1)
|
| 597 |
+
miss_s = np.isnan(genotypes).sum(axis=1) / max(n_markers, 1)
|
| 598 |
+
|
| 599 |
+
maf = np.zeros(n_markers)
|
| 600 |
+
for i in range(n_markers):
|
| 601 |
+
v = genotypes[:, i]
|
|
|
|
| 602 |
v = v[~np.isnan(v)]
|
| 603 |
+
if len(v):
|
| 604 |
+
f = np.mean(v) / 2.0
|
| 605 |
maf[i] = min(f, 1 - f)
|
| 606 |
+
|
| 607 |
+
qc_m = (miss_m < miss_m_t) & (maf >= maf_t)
|
| 608 |
+
qc_s = miss_s < miss_s_t
|
| 609 |
+
|
| 610 |
+
fallback_msg = ""
|
| 611 |
+
for rs, rm in [(miss_s_t, miss_m_t),
|
| 612 |
+
(0.60,0.60),(0.70,0.70),(0.80,0.80),(0.90,0.90),(1.00,1.00)]:
|
| 613 |
+
qc_m_t = (miss_m < rm) & (maf >= maf_t)
|
| 614 |
+
qc_s_t = miss_s < rs
|
| 615 |
+
if qc_s_t.sum() >= 10:
|
| 616 |
+
qc_m = qc_m_t
|
| 617 |
+
qc_s = qc_s_t
|
| 618 |
+
if rs > miss_s_t or rm > miss_m_t:
|
| 619 |
+
fallback_msg = (f"\n> β οΈ **QC auto-relaxed** to sample missing "
|
| 620 |
+
f"< {rs*100:.0f}% / marker missing "
|
| 621 |
+
f"< {rm*100:.0f}% to retain β₯10 samples.\n")
|
| 622 |
+
break
|
| 623 |
+
|
| 624 |
+
geno_qc = genotypes[np.ix_(qc_s, qc_m)].copy()
|
| 625 |
+
pheno_qc = phenotypes[qc_s]
|
| 626 |
+
ids_qc = sample_ids[qc_s]
|
| 627 |
+
mnames_qc = [marker_names[i] for i in range(n_markers) if qc_m[i]]
|
| 628 |
+
chrom_qc = [chrom_dict[m] for m in mnames_qc]
|
| 629 |
+
pos_qc = [positions[i] for i in range(n_markers) if qc_m[i]]
|
| 630 |
+
|
| 631 |
+
# Impute
|
| 632 |
+
col_means = np.nanmean(geno_qc, axis=0)
|
| 633 |
+
col_means = np.where(np.isnan(col_means), 0.0, col_means)
|
| 634 |
+
for i in range(geno_qc.shape[1]):
|
| 635 |
+
mask = np.isnan(geno_qc[:, i])
|
| 636 |
+
if mask.any():
|
| 637 |
+
geno_qc[mask, i] = col_means[i]
|
| 638 |
+
|
| 639 |
+
valid = ~np.isnan(pheno_qc)
|
| 640 |
+
geno_qc = geno_qc[valid]
|
| 641 |
+
pheno_qc = pheno_qc[valid]
|
| 642 |
+
ids_qc = ids_qc[valid]
|
| 643 |
+
|
| 644 |
+
if len(ids_qc) < 10:
|
| 645 |
+
worst = np.sort(np.isnan(genotypes).sum(axis=1) /
|
| 646 |
+
max(n_markers, 1) * 100)[::-1][:5]
|
| 647 |
+
return (
|
| 648 |
+
f"## β οΈ Insufficient Samples After QC\n\n"
|
| 649 |
+
f"Only **{len(ids_qc)}** sample(s) passed QC (started with {n_samples}).\n\n"
|
| 650 |
+
f"Top missing rates: `{', '.join(f'{v:.0f}%' for v in worst)}`\n\n"
|
| 651 |
+
f"Try increasing the **Sample Missing Rate** slider to 50β80%.",
|
| 652 |
+
None, None, None, None
|
| 653 |
+
)
|
| 654 |
+
|
| 655 |
+
n_qc = len(mnames_qc)
|
| 656 |
+
bonf = 0.05 / n_qc
|
| 657 |
+
|
| 658 |
+
# ββ Models βββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 659 |
+
print(f"[1/5] Linear Regression on {n_qc} markers Γ {len(ids_qc)} samples β¦")
|
| 660 |
+
lr_pvals, lr_effects, lr_se, lr_r2 = linear_regression_gwas(geno_qc, pheno_qc)
|
| 661 |
+
|
| 662 |
+
if include_mlm:
|
| 663 |
+
print("[2/5] Mixed Linear Model β¦")
|
| 664 |
+
mlm_pvals, mlm_effects, mlm_lod = mixed_model_gwas(geno_qc, pheno_qc)
|
| 665 |
+
|
| 666 |
+
if include_enet:
|
| 667 |
+
print("[3/5] ElasticNet β¦")
|
| 668 |
+
enet_pvals, enet_coef = elasticnet_gwas(geno_qc, pheno_qc)
|
| 669 |
+
|
| 670 |
+
if include_rf:
|
| 671 |
+
print("[4/5] Random Forest β¦")
|
| 672 |
+
rf_pvals, rf_imp, rf_cv = machine_learning_gwas(geno_qc, pheno_qc, 'rf')
|
| 673 |
+
|
| 674 |
+
if include_gb:
|
| 675 |
+
print("[5/5] Gradient Boosting β¦")
|
| 676 |
+
gb_pvals, gb_imp, gb_cv = machine_learning_gwas(geno_qc, pheno_qc, 'gb')
|
| 677 |
+
|
| 678 |
+
# ββ Results DataFrame βββββββββββββββββββββββββββββββββββββββββββ
|
| 679 |
+
gwas_df = pd.DataFrame({
|
| 680 |
+
'Rank': 0,
|
| 681 |
+
'Marker': mnames_qc,
|
| 682 |
+
'Chromosome': chrom_qc,
|
| 683 |
+
'Position': pos_qc,
|
| 684 |
+
'LR_P': lr_pvals,
|
| 685 |
+
'LR_Beta': lr_effects,
|
| 686 |
+
'LR_LOD': -np.log10(lr_pvals + 1e-300),
|
| 687 |
+
'Significant_LR': (lr_pvals < bonf).astype(int),
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 688 |
})
|
| 689 |
+
|
| 690 |
+
if include_mlm and mlm_pvals is not None:
|
| 691 |
+
gwas_df['MLM_P'] = mlm_pvals
|
| 692 |
+
gwas_df['MLM_Beta'] = mlm_effects
|
| 693 |
+
gwas_df['MLM_LOD'] = mlm_lod
|
| 694 |
+
gwas_df['Significant_MLM'] = (mlm_pvals < bonf).astype(int)
|
| 695 |
+
|
| 696 |
+
if include_enet and enet_pvals is not None:
|
| 697 |
+
gwas_df['EN_P'] = enet_pvals
|
| 698 |
+
gwas_df['EN_Beta'] = enet_coef
|
| 699 |
+
gwas_df['Significant_EN'] = (enet_pvals < bonf).astype(int)
|
| 700 |
+
|
| 701 |
+
if include_rf and rf_pvals is not None:
|
| 702 |
+
gwas_df['RF_P'] = rf_pvals
|
| 703 |
+
gwas_df['RF_Imp'] = rf_imp
|
| 704 |
+
gwas_df['Significant_RF'] = (rf_pvals < bonf).astype(int)
|
| 705 |
+
|
| 706 |
+
if include_gb and gb_pvals is not None:
|
| 707 |
+
gwas_df['GB_P'] = gb_pvals
|
| 708 |
+
gwas_df['GB_Imp'] = gb_imp
|
| 709 |
+
gwas_df['Significant_GB'] = (gb_pvals < bonf).astype(int)
|
| 710 |
+
|
| 711 |
+
sig_cols = [c for c in gwas_df.columns if c.startswith('Significant_')]
|
| 712 |
+
gwas_df['Consensus_Sig'] = (
|
| 713 |
+
(gwas_df[sig_cols].sum(axis=1) >= 2).astype(int)
|
| 714 |
+
if len(sig_cols) > 1 else gwas_df[sig_cols[0]] if sig_cols
|
| 715 |
+
else 0
|
| 716 |
+
)
|
| 717 |
+
|
| 718 |
+
gwas_df = gwas_df.sort_values('LR_P').reset_index(drop=True)
|
| 719 |
+
gwas_df['Rank'] = range(1, len(gwas_df) + 1)
|
| 720 |
+
gwas_df.to_csv(os.path.join(results_dir, 'gwas_results.csv'), index=False)
|
| 721 |
+
|
| 722 |
+
# ββ Plots βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 723 |
+
print("Generating plots β¦")
|
| 724 |
+
bonf_log = -np.log10(bonf)
|
| 725 |
+
sig_set = set(np.where(lr_pvals < bonf)[0])
|
| 726 |
+
|
| 727 |
+
man_path = os.path.join(plots_dir, 'manhattan_lod.png')
|
| 728 |
+
plot_manhattan_with_lod(mnames_qc, chrom_qc, lr_pvals,
|
| 729 |
+
-np.log10(lr_pvals + 1e-300),
|
| 730 |
+
sig_set, bonf_log, man_path)
|
| 731 |
+
|
| 732 |
+
ld_path = os.path.join(plots_dir, 'ld_decay.png')
|
| 733 |
+
ld_stats = plot_enhanced_ld_decay(geno_qc, chrom_qc, pos_qc, ld_path)
|
| 734 |
+
|
| 735 |
+
comp_path = os.path.join(plots_dir, 'model_comparison.png')
|
| 736 |
+
plot_model_comparison(gwas_df, comp_path)
|
| 737 |
+
|
| 738 |
+
# ββ ZIP ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 739 |
+
zip_path = os.path.join(temp_dir, 'GWAS_Results.zip')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 740 |
with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf:
|
| 741 |
+
for root, _, files in os.walk(results_dir):
|
| 742 |
for f in files:
|
| 743 |
+
fp = os.path.join(root, f)
|
| 744 |
+
zf.write(fp, os.path.relpath(fp, temp_dir))
|
| 745 |
+
|
| 746 |
+
# ββ Summary ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 747 |
+
def _ns(pv, enabled):
|
| 748 |
+
return str(int((pv < bonf).sum())) if (enabled and pv is not None) else "β"
|
| 749 |
+
|
| 750 |
+
ld_r2_mean = np.mean([v['mean_r2'] for v in ld_stats.values()]) if ld_stats else 0
|
| 751 |
+
ld_dp_mean = np.mean([v['mean_dprime'] for v in ld_stats.values()]) if ld_stats else 0
|
| 752 |
+
|
| 753 |
+
top10_cols = ['Marker','Chromosome','LR_P','LR_LOD','Consensus_Sig']
|
| 754 |
+
top10_cols = [c for c in top10_cols if c in gwas_df.columns]
|
| 755 |
+
|
| 756 |
+
def _df_to_md(df):
|
| 757 |
+
"""Convert a DataFrame to a markdown table without tabulate."""
|
| 758 |
+
cols = df.columns.tolist()
|
| 759 |
+
def _fmt(v):
|
| 760 |
+
if isinstance(v, float):
|
| 761 |
+
return f"{v:.4e}" if abs(v) < 0.001 else f"{v:.4f}"
|
| 762 |
+
return str(v)
|
| 763 |
+
header = "| " + " | ".join(cols) + " |"
|
| 764 |
+
sep = "| " + " | ".join(["---"] * len(cols)) + " |"
|
| 765 |
+
rows = ["| " + " | ".join(_fmt(row[c]) for c in cols) + " |"
|
| 766 |
+
for _, row in df.iterrows()]
|
| 767 |
+
return "\n".join([header, sep] + rows)
|
| 768 |
+
|
| 769 |
summary = f"""
|
| 770 |
+
## π GWAS Analysis Complete
|
| 771 |
|
| 772 |
+
### QC Summary
|
| 773 |
| Metric | Value |
|
| 774 |
|--------|-------|
|
| 775 |
+
| Samples (raw β QC) | {n_samples} β **{len(ids_qc)}** |
|
| 776 |
+
| Markers (raw β QC) | {n_markers} β **{n_qc}** |
|
| 777 |
+
| Chromosomes | **{len(set(chrom_qc))}** |
|
| 778 |
+
| MAF filter | β₯ {maf_thresh:.1f}% |
|
| 779 |
+
| Sample missing filter | < {miss_rate_sample:.0f}% |
|
| 780 |
+
{fallback_msg}
|
| 781 |
+
|
| 782 |
+
### Model Results
|
| 783 |
+
| Model | Status | Significant Markers |
|
| 784 |
+
|-------|--------|---------------------|
|
| 785 |
+
| Linear Regression | β
| {_ns(lr_pvals, True)} |
|
| 786 |
+
| Mixed Linear Model | {'β
' if include_mlm else 'β skipped'} | {_ns(mlm_pvals, include_mlm)} |
|
| 787 |
+
| ElasticNet | {'β
' if include_enet else 'β skipped'} | {_ns(enet_pvals, include_enet)} |
|
| 788 |
+
| Random Forest | {'β
' if include_rf else 'β skipped'} | {_ns(rf_pvals, include_rf)} |
|
| 789 |
+
| Gradient Boosting | {'β
' if include_gb else 'β skipped'} | {_ns(gb_pvals, include_gb)} |
|
| 790 |
+
|
| 791 |
+
**Consensus (β₯2 models):** {gwas_df['Consensus_Sig'].sum()} markers
|
| 792 |
+
|
| 793 |
+
### LD Summary
|
| 794 |
+
Mean rΒ² = **{ld_r2_mean:.3f}** | Mean D' = **{ld_dp_mean:.3f}**
|
| 795 |
+
|
| 796 |
+
### Top 10 Markers (LR P-value)
|
| 797 |
+
{_df_to_md(gwas_df.head(10)[top10_cols])}
|
| 798 |
"""
|
| 799 |
+
return (summary, man_path, ld_path, comp_path, zip_path)
|
| 800 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 801 |
except Exception as e:
|
| 802 |
import traceback
|
| 803 |
+
return (
|
| 804 |
+
f"## β Error\n```\n{e}\n\n{traceback.format_exc()}\n```",
|
| 805 |
+
None, None, None, None
|
| 806 |
+
)
|
| 807 |
+
|
| 808 |
|
| 809 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 810 |
# GRADIO UI
|
| 811 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 812 |
|
| 813 |
+
custom_css = """
|
| 814 |
+
.gradio-container { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; }
|
| 815 |
+
h1 { color: #2c3e50; border-bottom: 3px solid #8B5CF6; padding-bottom: 10px; }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 816 |
"""
|
| 817 |
|
| 818 |
+
with gr.Blocks(css=custom_css, title="MTA Analysis Tool v7.1") as app:
|
| 819 |
+
|
| 820 |
gr.Markdown("""
|
| 821 |
+
# 𧬠Enhanced MTA / GWAS Analysis v7.1
|
| 822 |
+
### Multi-Model Genomic Marker Discovery Platform
|
| 823 |
+
Upload your CSV file, configure options, and click **Run**.
|
| 824 |
---
|
| 825 |
""")
|
| 826 |
+
|
| 827 |
with gr.Row():
|
| 828 |
with gr.Column(scale=1):
|
|
|
|
| 829 |
gr.Markdown("""
|
| 830 |
+
### π CSV Format
|
| 831 |
+
```
|
| 832 |
+
ID, Phenotype, M1, M2, M3, ...
|
| 833 |
+
-, Chr, 1, 1, 2, ... β chromosome row
|
| 834 |
+
S001, 45.2, 0, 1, 2, ...
|
| 835 |
+
S002, 38.7, 1, 0, 1, ...
|
| 836 |
+
```
|
| 837 |
+
Genotype values: **0 / 1 / 2** (missing = blank or -1)
|
| 838 |
""")
|
| 839 |
+
input_file = gr.File(label="Upload CSV", file_types=[".csv"])
|
| 840 |
+
target_markers = gr.Slider(100, 5000, value=3000, step=100,
|
| 841 |
+
label="Target markers for modelling")
|
| 842 |
+
|
|
|
|
|
|
|
| 843 |
with gr.Column(scale=1):
|
| 844 |
+
gr.Markdown("### βοΈ QC Filters")
|
| 845 |
+
miss_rate_sample = gr.Slider(5, 100, value=20, step=5,
|
| 846 |
+
label="Max sample missing rate (%)")
|
| 847 |
+
miss_rate_marker = gr.Slider(5, 100, value=20, step=5,
|
| 848 |
+
label="Max marker missing rate (%)")
|
| 849 |
+
maf_thresh = gr.Slider(0, 25, value=5, step=1,
|
| 850 |
+
label="Min MAF (%)")
|
| 851 |
+
|
| 852 |
+
gr.Markdown("### π¬ Optional Models *(slower)*")
|
| 853 |
+
include_mlm = gr.Checkbox(label="Mixed Linear Model", value=False)
|
| 854 |
+
include_enet = gr.Checkbox(label="ElasticNet", value=True)
|
| 855 |
+
include_rf = gr.Checkbox(label="Random Forest", value=False)
|
| 856 |
+
include_gb = gr.Checkbox(label="Gradient Boosting", value=False)
|
| 857 |
+
|
| 858 |
+
run_button = gr.Button("π Run Analysis", variant="primary", size="lg")
|
| 859 |
+
|
| 860 |
gr.Markdown("---")
|
| 861 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 862 |
with gr.Row():
|
| 863 |
+
summary_output = gr.Markdown(label="Summary")
|
| 864 |
+
|
|
|
|
| 865 |
with gr.Row():
|
| 866 |
+
manhattan_output = gr.Image(label="Manhattan + LOD")
|
| 867 |
+
|
|
|
|
| 868 |
with gr.Row():
|
| 869 |
+
ld_output = gr.Image(label="LD Decay")
|
| 870 |
+
comparison_output = gr.Image(label="Model Comparison")
|
| 871 |
+
|
| 872 |
with gr.Row():
|
| 873 |
+
download_output = gr.File(label="π¦ Download ZIP")
|
| 874 |
+
|
| 875 |
+
gr.Markdown("""
|
| 876 |
+
---
|
| 877 |
+
**Created by Ashmi** | MTA Analysis Tool v7.1
|
| 878 |
+
""")
|
| 879 |
+
|
| 880 |
+
run_button.click(
|
| 881 |
+
fn=run_mta_analysis,
|
| 882 |
+
inputs=[input_file, target_markers,
|
| 883 |
+
miss_rate_sample, miss_rate_marker, maf_thresh,
|
| 884 |
+
include_mlm, include_enet, include_rf, include_gb],
|
| 885 |
+
outputs=[summary_output, manhattan_output, ld_output,
|
| 886 |
+
comparison_output, download_output]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 887 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 888 |
|
| 889 |
if __name__ == "__main__":
|
| 890 |
+
app.launch(share=False, show_error=True)
|