Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -6,7 +6,8 @@ matplotlib.use("Agg")
|
|
| 6 |
import matplotlib.pyplot as plt
|
| 7 |
import matplotlib.patches as mpatches
|
| 8 |
from matplotlib.colors import LinearSegmentedColormap
|
| 9 |
-
from matplotlib.patches import
|
|
|
|
| 10 |
import warnings
|
| 11 |
warnings.filterwarnings("ignore")
|
| 12 |
|
|
@@ -14,45 +15,66 @@ from scipy import stats
|
|
| 14 |
from scipy.cluster.hierarchy import dendrogram, linkage
|
| 15 |
from sklearn.decomposition import PCA
|
| 16 |
from sklearn.preprocessing import StandardScaler
|
| 17 |
-
from sklearn.linear_model import LinearRegression
|
| 18 |
from sklearn.manifold import MDS, TSNE
|
| 19 |
from scipy.spatial.distance import pdist
|
| 20 |
import io, re, itertools
|
| 21 |
from io import StringIO
|
| 22 |
from statsmodels.stats.multitest import multipletests
|
| 23 |
|
| 24 |
-
# βββββββββββββββββββββββββββ
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
|
| 39 |
def style_fig(fig):
|
| 40 |
-
fig.patch.set_facecolor(
|
| 41 |
for ax in fig.get_axes():
|
| 42 |
-
ax.set_facecolor(
|
| 43 |
-
ax.tick_params(colors=
|
| 44 |
-
ax.xaxis.label.set_color(
|
| 45 |
-
ax.yaxis.label.set_color(
|
| 46 |
-
ax.title.set_color(
|
| 47 |
for spine in ax.spines.values():
|
| 48 |
-
spine.set_edgecolor(
|
| 49 |
-
ax.grid(color=
|
| 50 |
return fig
|
| 51 |
|
| 52 |
# βββββββββββββββββββββββββββ DATA PARSING βββββββββββββββββββββββββββββ
|
| 53 |
|
| 54 |
def parse_data(file_obj=None, text_input=None):
|
| 55 |
-
"""Parse uploaded CSV with optional chromosome row."""
|
| 56 |
raw = None
|
| 57 |
if file_obj is not None:
|
| 58 |
try:
|
|
@@ -67,7 +89,6 @@ def parse_data(file_obj=None, text_input=None):
|
|
| 67 |
else:
|
| 68 |
raise ValueError("No data provided.")
|
| 69 |
|
| 70 |
-
# Check if second row contains chromosome info
|
| 71 |
has_chrom_row = False
|
| 72 |
chrom_info = {}
|
| 73 |
|
|
@@ -88,11 +109,9 @@ def parse_data(file_obj=None, text_input=None):
|
|
| 88 |
phen_col = cols[1]
|
| 89 |
snp_cols = cols[2:]
|
| 90 |
|
| 91 |
-
# Clean data
|
| 92 |
raw = raw[pd.to_numeric(raw[phen_col], errors="coerce").notna()].copy()
|
| 93 |
raw[phen_col] = raw[phen_col].astype(float)
|
| 94 |
|
| 95 |
-
# Replace missing codes
|
| 96 |
geno = raw[snp_cols].apply(pd.to_numeric, errors="coerce")
|
| 97 |
geno = geno.where(~geno.isin([-1, -9, -99, -999]), np.nan)
|
| 98 |
|
|
@@ -102,12 +121,11 @@ def parse_data(file_obj=None, text_input=None):
|
|
| 102 |
for c in snp_cols:
|
| 103 |
df[c] = geno[c].values
|
| 104 |
|
| 105 |
-
# Parse chromosome and position
|
| 106 |
chroms, positions = [], []
|
| 107 |
for m in snp_cols:
|
| 108 |
if m in chrom_info:
|
| 109 |
chroms.append(chrom_info[m])
|
| 110 |
-
positions.append(
|
| 111 |
else:
|
| 112 |
m_clean = str(m).strip()
|
| 113 |
mat = re.match(r"[Cc]hr(\d+)[_\-](\d+)", m_clean)
|
|
@@ -121,7 +139,7 @@ def parse_data(file_obj=None, text_input=None):
|
|
| 121 |
|
| 122 |
return df, snp_cols, np.array(chroms), np.array(positions)
|
| 123 |
|
| 124 |
-
# βββββββββββββββββββββ
|
| 125 |
|
| 126 |
def impute_genotypes(geno_matrix):
|
| 127 |
mat = geno_matrix.copy().astype(float)
|
|
@@ -152,219 +170,535 @@ def build_kinship(G):
|
|
| 152 |
K = Z @ Z.T / denom
|
| 153 |
return K
|
| 154 |
|
| 155 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 156 |
def ols_gwas(y, G):
|
| 157 |
n, m = G.shape
|
| 158 |
pvals = np.ones(m)
|
| 159 |
betas = np.zeros(m)
|
| 160 |
for j in range(m):
|
| 161 |
-
x = G[:, j]
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
slope, intercept, r, p, se = stats.linregress(x, y)
|
| 166 |
-
pvals[j] = p
|
| 167 |
-
betas[j] = slope
|
| 168 |
return pvals, betas
|
| 169 |
|
| 170 |
-
# Model 2: MLM
|
| 171 |
def mlm_gwas(y, G, K):
|
| 172 |
n, m = G.shape
|
| 173 |
-
pvals = np.ones(m)
|
| 174 |
-
betas = np.zeros(m)
|
| 175 |
eigvals, eigvecs = np.linalg.eigh(K + np.eye(n) * 1e-6)
|
| 176 |
-
idx = np.argsort(eigvals)[::-1]
|
| 177 |
n_pcs = min(3, n - 2)
|
| 178 |
-
Q = eigvecs[:,
|
| 179 |
-
|
| 180 |
-
y_res = y - reg.predict(Q)
|
| 181 |
for j in range(m):
|
| 182 |
x = G[:, j]
|
| 183 |
x_res = x - LinearRegression().fit(Q, x).predict(Q)
|
| 184 |
-
if x_res.std() < 1e-8:
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
pvals[j] = p
|
| 188 |
-
betas[j] = slope
|
| 189 |
return pvals, betas
|
| 190 |
|
| 191 |
-
# Model 3: GLM (PCA-corrected
|
| 192 |
def glm_gwas(y, G):
|
| 193 |
n, m = G.shape
|
| 194 |
-
pvals = np.ones(m)
|
| 195 |
-
betas = np.zeros(m)
|
| 196 |
-
scaler = StandardScaler()
|
| 197 |
-
G_sc = scaler.fit_transform(G)
|
| 198 |
n_pcs = min(3, n - 2)
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
reg = LinearRegression().fit(PCs, y)
|
| 202 |
-
y_adj = y - reg.predict(PCs)
|
| 203 |
for j in range(m):
|
| 204 |
x = G[:, j]
|
| 205 |
-
if x.std() < 1e-8:
|
| 206 |
-
continue
|
| 207 |
x_adj = x - LinearRegression().fit(PCs, x).predict(PCs)
|
| 208 |
-
slope,
|
| 209 |
-
pvals[j] = p
|
| 210 |
-
betas[j] = slope
|
| 211 |
return pvals, betas
|
| 212 |
|
| 213 |
-
# Model 4:
|
| 214 |
def cmlm_gwas(y, G, K):
|
| 215 |
n, m = G.shape
|
| 216 |
-
pvals = np.ones(m)
|
| 217 |
-
betas = np.zeros(m)
|
| 218 |
-
# Create groups based on kinship
|
| 219 |
n_groups = min(3, n)
|
| 220 |
groups = np.array([i % n_groups for i in range(n)])
|
| 221 |
-
group_means = np.
|
| 222 |
-
|
| 223 |
-
idx = np.where(groups == g)[0]
|
| 224 |
-
if len(idx) > 0:
|
| 225 |
-
group_means[:, g] = K[:, idx].mean(axis=1)
|
| 226 |
-
reg = LinearRegression().fit(group_means, y)
|
| 227 |
-
y_res = y - reg.predict(group_means)
|
| 228 |
for j in range(m):
|
| 229 |
x = G[:, j]
|
| 230 |
x_res = x - LinearRegression().fit(group_means, x).predict(group_means)
|
| 231 |
-
if x_res.std() < 1e-8:
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
pvals[j] = p
|
| 235 |
-
betas[j] = slope
|
| 236 |
return pvals, betas
|
| 237 |
|
| 238 |
-
# Model 5: BLINK
|
| 239 |
def blink_gwas(y, G):
|
| 240 |
n, m = G.shape
|
| 241 |
-
pvals = np.ones(m)
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
n_cov = min(3, m)
|
| 247 |
-
top_idx = np.argsort(ols_p)[:n_cov]
|
| 248 |
-
if len(top_idx) > 0:
|
| 249 |
-
covars = G[:, top_idx]
|
| 250 |
-
reg = LinearRegression().fit(covars, y)
|
| 251 |
-
y_adj = y - reg.predict(covars)
|
| 252 |
-
else:
|
| 253 |
-
y_adj = y
|
| 254 |
-
# Second pass with covariates
|
| 255 |
for j in range(m):
|
| 256 |
x = G[:, j]
|
| 257 |
-
if x.std() < 1e-8:
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
pvals[j] = p
|
| 261 |
-
betas[j] = slope
|
| 262 |
return pvals, betas
|
| 263 |
|
| 264 |
-
# Model 6: FarmCPU
|
| 265 |
def farmcpu_gwas(y, G, K):
|
| 266 |
n, m = G.shape
|
| 267 |
-
pvals = np.ones(m)
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
n_qtns = min(3, m)
|
| 273 |
-
qtn_idx = np.argsort(mlm_p)[:n_qtns]
|
| 274 |
-
# Step 3: Fixed effect model with QTNs
|
| 275 |
-
if len(qtn_idx) > 0:
|
| 276 |
-
qtns = G[:, qtn_idx]
|
| 277 |
-
reg = LinearRegression().fit(qtns, y)
|
| 278 |
-
y_adj = y - reg.predict(qtns)
|
| 279 |
-
else:
|
| 280 |
-
y_adj = y
|
| 281 |
-
# Step 4: Final association
|
| 282 |
for j in range(m):
|
| 283 |
x = G[:, j]
|
| 284 |
-
if x.std() < 1e-8:
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
pvals[j] = p
|
| 288 |
-
betas[j] = slope
|
| 289 |
return pvals, betas
|
| 290 |
|
| 291 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 292 |
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 299 |
style_fig(fig)
|
|
|
|
|
|
|
|
|
|
| 300 |
log_p = -np.log10(np.clip(pvals, 1e-300, 1))
|
| 301 |
sig_line = -np.log10(5e-8)
|
| 302 |
-
|
| 303 |
-
|
| 304 |
chrom_list = sorted(set(chroms))
|
| 305 |
-
|
| 306 |
-
|
| 307 |
-
'#1B4F72', # Dark Blue
|
| 308 |
-
'#1E8449', # Dark Green
|
| 309 |
-
'#6C3483', # Dark Purple
|
| 310 |
-
'#B7950B', # Dark Gold
|
| 311 |
-
'#C0392B', # Dark Red
|
| 312 |
-
'#117A65', # Dark Teal
|
| 313 |
-
'#D35400', # Dark Orange
|
| 314 |
-
'#21618C', # Navy
|
| 315 |
-
'#7D6608', # Olive
|
| 316 |
-
'#2E4053', # Dark Gray
|
| 317 |
-
'#A93226', # Dark Brick
|
| 318 |
-
'#0E6251', # Dark Cyan
|
| 319 |
-
'#5B2C6F', # Dark Violet
|
| 320 |
-
'#7E5109', # Dark Brown
|
| 321 |
-
'#1A5276' # Deep Blue
|
| 322 |
-
]
|
| 323 |
-
chrom_colors = {c: dark_palette[i % len(dark_palette)] for i, c in enumerate(chrom_list)}
|
| 324 |
-
|
| 325 |
x_offset = 0
|
| 326 |
tick_pos, tick_lab, x_coords = [], [], np.zeros(len(pvals))
|
| 327 |
-
|
| 328 |
for ch in chrom_list:
|
| 329 |
mask = chroms == ch
|
| 330 |
pos = positions[mask]
|
| 331 |
-
if len(pos) == 0:
|
| 332 |
-
continue
|
| 333 |
order = np.argsort(pos)
|
| 334 |
x_vals = pos[order] - pos.min() + x_offset
|
| 335 |
x_coords[np.where(mask)[0][order]] = x_vals
|
| 336 |
tick_pos.append(x_vals.mean())
|
| 337 |
tick_lab.append(f"Chr{ch}")
|
| 338 |
-
ax.
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 344 |
sig_mask = log_p >= sig_line
|
| 345 |
if sig_mask.any():
|
| 346 |
-
ax.scatter(x_coords[sig_mask], log_p[sig_mask],
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
ax.axhline(sig_line, color='#DC3545', ls="--", lw=1.5, label="Bonferroni (5e-8)")
|
| 352 |
ax.set_xticks(tick_pos)
|
| 353 |
-
ax.set_xticklabels(tick_lab, rotation=45)
|
| 354 |
-
ax.set_ylabel("-
|
| 355 |
-
ax.set_title(title)
|
| 356 |
-
ax.legend(
|
|
|
|
|
|
|
| 357 |
fig.tight_layout()
|
| 358 |
return fig
|
| 359 |
|
| 360 |
-
# βββββββββββββββββββββββββββ
|
| 361 |
|
| 362 |
-
def
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 368 |
|
| 369 |
def plot_qq(pvals, title="QQ Plot"):
|
| 370 |
fig, ax = plt.subplots(figsize=(6, 6))
|
|
@@ -372,17 +706,14 @@ def plot_qq(pvals, title="QQ Plot"):
|
|
| 372 |
n = len(pvals)
|
| 373 |
obs = np.sort(-np.log10(np.clip(pvals, 1e-300, 1)))[::-1]
|
| 374 |
exp = -np.log10(np.linspace(1/n, 1, n)[::-1])
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
ax.
|
| 379 |
-
ax.
|
| 380 |
-
ax.plot([0, max(exp)], [0, max(exp)], color=ACCENT_PINK, ls="--", lw=1.5)
|
| 381 |
-
|
| 382 |
lam = np.median(stats.chi2.ppf(1 - pvals, df=1)) / stats.chi2.ppf(0.5, df=1)
|
| 383 |
-
ax.text(0.05, 0.92, f"Ξ» = {lam:.4f}", transform=ax.transAxes, fontsize=11)
|
| 384 |
-
ax.set_xlabel("Expected -
|
| 385 |
-
ax.set_ylabel("Observed -log10(p)")
|
| 386 |
ax.set_title(title)
|
| 387 |
fig.tight_layout()
|
| 388 |
return fig
|
|
@@ -390,598 +721,523 @@ def plot_qq(pvals, title="QQ Plot"):
|
|
| 390 |
def plot_pca(G, y, ids):
|
| 391 |
fig, axes = plt.subplots(2, 2, figsize=(14, 12))
|
| 392 |
style_fig(fig)
|
| 393 |
-
|
| 394 |
-
scaler = StandardScaler()
|
| 395 |
-
G_sc = scaler.fit_transform(G)
|
| 396 |
n_comp = min(5, G_sc.shape[0]-1, G_sc.shape[1])
|
| 397 |
pca = PCA(n_components=n_comp)
|
| 398 |
pcs = pca.fit_transform(G_sc)
|
| 399 |
var_exp = pca.explained_variance_ratio_ * 100
|
| 400 |
-
|
| 401 |
-
|
| 402 |
-
axes[0,0].
|
| 403 |
-
axes[0,0].set_ylabel(f"PC2 ({var_exp[1]:.1f}%)")
|
| 404 |
-
axes[0,0].set_title("PCA: PC1 vs PC2")
|
| 405 |
-
plt.colorbar(sc, ax=axes[0,0], label="Phenotype")
|
| 406 |
-
|
| 407 |
if n_comp >= 4:
|
| 408 |
-
axes[0,1].scatter(pcs[:,2], pcs[:,3], c=y, cmap='
|
| 409 |
-
axes[0,1].set_xlabel(f"PC3 ({var_exp[2]:.1f}%)")
|
| 410 |
-
axes[0,1].set_ylabel(f"PC4 ({var_exp[3]:.1f}%)")
|
| 411 |
axes[0,1].set_title("PCA: PC3 vs PC4")
|
| 412 |
else:
|
| 413 |
-
axes[0,1].text(0.5, 0.5, "
|
| 414 |
-
|
| 415 |
-
axes[1,0].
|
| 416 |
-
axes[1,0].
|
| 417 |
-
axes[1,0].set_xlabel("Principal Component")
|
| 418 |
-
axes[1,0].set_ylabel("Variance Explained (%)")
|
| 419 |
axes[1,0].set_title("Scree Plot")
|
| 420 |
-
axes[1,
|
| 421 |
-
|
| 422 |
-
|
| 423 |
-
axes[1,1].set_xlabel(f"PC1 ({var_exp[0]:.1f}%)")
|
| 424 |
-
axes[1,1].set_ylabel(f"PC2 ({var_exp[1]:.1f}%)")
|
| 425 |
-
axes[1,1].set_title("Population Structure")
|
| 426 |
-
|
| 427 |
-
fig.tight_layout()
|
| 428 |
-
return fig
|
| 429 |
|
| 430 |
def plot_phenotype_distribution(y, ids):
|
| 431 |
fig, axes = plt.subplots(2, 2, figsize=(14, 10))
|
| 432 |
style_fig(fig)
|
| 433 |
-
|
| 434 |
-
axes[0,0].
|
| 435 |
-
axes[0,0].axvline(y.mean(), color=
|
| 436 |
-
axes[0,0].axvline(y.mean()
|
| 437 |
-
axes[0,0].
|
| 438 |
-
axes[0,0].set_xlabel("Phenotype")
|
| 439 |
-
axes[0,0].set_ylabel("Frequency")
|
| 440 |
-
axes[0,0].set_title("Phenotype Distribution")
|
| 441 |
-
axes[0,0].legend()
|
| 442 |
-
|
| 443 |
bp = axes[0,1].boxplot(y, vert=True, patch_artist=True)
|
| 444 |
-
for patch in bp['boxes']:
|
| 445 |
-
patch.set_facecolor(ACCENT_MINT)
|
| 446 |
-
patch.set_edgecolor(ACCENT_PINK)
|
| 447 |
-
axes[0,1].set_xticklabels(['Phenotype'])
|
| 448 |
-
axes[0,1].set_ylabel("Value")
|
| 449 |
axes[0,1].set_title("Box Plot")
|
| 450 |
-
|
| 451 |
stats.probplot(y, dist="norm", plot=axes[1,0])
|
| 452 |
axes[1,0].set_title("Normal Q-Q Plot")
|
| 453 |
-
axes[1,0].get_lines()[0].set_color(
|
| 454 |
-
axes[1,0].get_lines()[1].set_color(
|
| 455 |
-
|
| 456 |
-
|
| 457 |
-
|
| 458 |
-
kde = stats.gaussian_kde(y)
|
| 459 |
-
axes[1,1].plot(x_dense, kde(x_dense), color=ACCENT_PINK, lw=2)
|
| 460 |
-
axes[1,1].set_xlabel("Phenotype")
|
| 461 |
-
axes[1,1].set_ylabel("Density")
|
| 462 |
axes[1,1].set_title("Density Plot")
|
| 463 |
-
|
| 464 |
-
fig.tight_layout()
|
| 465 |
-
return fig
|
| 466 |
|
| 467 |
def plot_maf_analysis(maf, snp_names):
|
| 468 |
fig, axes = plt.subplots(2, 2, figsize=(14, 10))
|
| 469 |
style_fig(fig)
|
| 470 |
-
|
| 471 |
-
axes[0,0].
|
| 472 |
-
axes[0,0].
|
| 473 |
-
axes[0,0].set_xlabel("Minor Allele Frequency")
|
| 474 |
-
axes[0,0].set_ylabel("Count")
|
| 475 |
-
axes[0,0].set_title("MAF Distribution")
|
| 476 |
-
axes[0,0].legend()
|
| 477 |
-
|
| 478 |
order = np.argsort(maf)[::-1]
|
| 479 |
-
colors = [
|
| 480 |
axes[0,1].bar(range(min(50, len(maf))), maf[order][:50], color=colors[:50])
|
| 481 |
-
axes[0,1].axhline(0.05, color=
|
| 482 |
-
axes[0,1].set_xlabel("SNP Index")
|
| 483 |
-
axes[0,1].set_ylabel("MAF")
|
| 484 |
axes[0,1].set_title("Top 50 SNPs by MAF")
|
| 485 |
-
|
| 486 |
rare_mask = maf < 0.05
|
| 487 |
-
axes[1,0].pie([rare_mask.sum(), (~rare_mask).sum()],
|
|
|
|
|
|
|
| 488 |
axes[1,0].set_title("Rare vs Common Variants")
|
| 489 |
-
|
| 490 |
-
|
| 491 |
-
|
| 492 |
-
axes[1,1].set_title("MAF
|
| 493 |
-
|
| 494 |
-
fig.tight_layout()
|
| 495 |
-
return fig
|
| 496 |
|
| 497 |
-
def
|
|
|
|
| 498 |
fig, axes = plt.subplots(2, 2, figsize=(14, 12))
|
| 499 |
style_fig(fig)
|
| 500 |
-
|
| 501 |
m = G.shape[1]
|
| 502 |
dists, r2s = [], []
|
| 503 |
-
|
| 504 |
-
|
| 505 |
-
|
| 506 |
-
|
| 507 |
-
for i in range(min(50, m)):
|
| 508 |
-
for j in range(i+1, min(50, m)):
|
| 509 |
-
sampled_pairs.append((i, j))
|
| 510 |
-
|
| 511 |
-
for i, j in sampled_pairs:
|
| 512 |
-
xi, xj = G[:, i], G[:, j]
|
| 513 |
-
mask = ~(np.isnan(xi) | np.isnan(xj))
|
| 514 |
if mask.sum() >= 4:
|
| 515 |
r, _ = stats.pearsonr(xi[mask], xj[mask])
|
| 516 |
-
d = abs(positions[j]
|
| 517 |
-
dists.append(d)
|
| 518 |
-
|
| 519 |
-
|
| 520 |
-
|
| 521 |
-
axes[0,0].
|
| 522 |
-
axes[0,0].set_xlabel("Distance (kb)")
|
| 523 |
-
axes[0,0].set_ylabel("rΒ²")
|
| 524 |
-
axes[0,0].set_title("LD Decay")
|
| 525 |
-
|
| 526 |
-
bins = np.percentile(dists, np.linspace(0, 100, 11))
|
| 527 |
-
bin_centers, bin_means = [], []
|
| 528 |
-
for k in range(len(bins)-1):
|
| 529 |
-
mask = (dists >= bins[k]) & (dists < bins[k+1])
|
| 530 |
-
if mask.sum() > 0:
|
| 531 |
-
bin_centers.append((bins[k] + bins[k+1])/2/1000)
|
| 532 |
-
bin_means.append(np.mean(np.array(r2s)[mask]))
|
| 533 |
-
axes[0,0].plot(bin_centers, bin_means, color=ACCENT_PINK, lw=2, marker='o')
|
| 534 |
-
|
| 535 |
m_sub = min(30, m)
|
| 536 |
-
R = np.
|
| 537 |
for i in range(m_sub):
|
| 538 |
-
for j in range(m_sub):
|
| 539 |
-
|
| 540 |
-
|
| 541 |
-
|
| 542 |
-
|
| 543 |
-
|
| 544 |
-
|
| 545 |
-
|
| 546 |
-
R[i,j] = r**2
|
| 547 |
-
|
| 548 |
-
im = axes[0,1].imshow(R, cmap='RdYlBu_r', vmin=0, vmax=1, aspect='auto')
|
| 549 |
-
axes[0,1].set_title("LD Heatmap (first 30 SNPs)")
|
| 550 |
plt.colorbar(im, ax=axes[0,1], label="rΒ²")
|
| 551 |
-
|
| 552 |
-
|
| 553 |
-
axes[1,0].
|
| 554 |
-
axes[1,0].
|
| 555 |
-
|
| 556 |
-
axes[1,
|
| 557 |
-
|
| 558 |
-
|
| 559 |
-
|
| 560 |
-
|
| 561 |
-
axes[1,1].scatter(dists_kb, r2s_arr, alpha=0.3, s=15, color=ACCENT_MINT)
|
| 562 |
-
axes[1,1].set_xlabel("Distance (kb)")
|
| 563 |
-
axes[1,1].set_ylabel("rΒ²")
|
| 564 |
-
axes[1,1].set_title("LD Decay Scatter")
|
| 565 |
-
axes[1,1].set_ylim(0, 1)
|
| 566 |
-
|
| 567 |
-
fig.tight_layout()
|
| 568 |
-
return fig
|
| 569 |
|
| 570 |
def plot_effect_sizes(pvals, betas, snp_names):
|
| 571 |
fig, axes = plt.subplots(2, 2, figsize=(14, 10))
|
| 572 |
style_fig(fig)
|
| 573 |
-
|
| 574 |
top_idx = np.argsort(np.abs(betas))[-20:]
|
| 575 |
top_betas = betas[top_idx]
|
| 576 |
top_names = [snp_names[i][:15] for i in top_idx]
|
| 577 |
-
colors = [
|
| 578 |
-
|
| 579 |
axes[0,0].barh(range(len(top_betas)), top_betas, color=colors)
|
| 580 |
-
axes[0,0].axvline(0, color=
|
| 581 |
-
axes[0,0].set_yticks(range(len(top_betas)))
|
| 582 |
-
axes[0,0].
|
| 583 |
-
axes[0,0].set_xlabel("Effect Size (Ξ²)")
|
| 584 |
-
axes[0,0].set_title("Top 20 Effect Sizes")
|
| 585 |
-
|
| 586 |
log_p = -np.log10(np.clip(pvals, 1e-300, 1))
|
| 587 |
sig_thr = -np.log10(0.05/len(pvals))
|
| 588 |
-
colors_v = np.where(log_p >= sig_thr,
|
| 589 |
-
axes[0,1].scatter(betas, log_p, c=colors_v, s=
|
| 590 |
-
axes[0,1].axhline(sig_thr, color=
|
| 591 |
-
axes[0,1].axvline(0, color=
|
| 592 |
-
axes[0,1].set_xlabel("
|
| 593 |
-
axes[0,1].
|
| 594 |
-
axes[
|
| 595 |
-
axes[
|
| 596 |
-
|
| 597 |
-
axes[1,
|
| 598 |
-
axes[1,
|
| 599 |
-
axes[1,0].set_xlabel("Effect Size (Ξ²)")
|
| 600 |
-
axes[1,0].set_ylabel("Frequency")
|
| 601 |
-
axes[1,0].set_title("Effect Size Distribution")
|
| 602 |
-
|
| 603 |
-
axes[1,1].scatter(betas, log_p, c=colors_v, s=25, alpha=0.6)
|
| 604 |
-
axes[1,1].set_xlabel("Effect Size (Ξ²)")
|
| 605 |
-
axes[1,1].set_ylabel("-log10(p)")
|
| 606 |
axes[1,1].set_title("Effect Size vs Significance")
|
| 607 |
-
|
| 608 |
-
fig.tight_layout()
|
| 609 |
-
return fig
|
| 610 |
|
| 611 |
def plot_heterozygosity(G, y, ids):
|
| 612 |
fig, axes = plt.subplots(2, 2, figsize=(14, 10))
|
| 613 |
style_fig(fig)
|
| 614 |
-
|
| 615 |
het = compute_heterozygosity(G)
|
| 616 |
-
|
| 617 |
-
axes[0,0].hist(het, bins=20, color=ACCENT_LAV, edgecolor='white')
|
| 618 |
-
axes[0,0].set_xlabel("Heterozygosity")
|
| 619 |
-
axes[0,0].set_ylabel("Count")
|
| 620 |
axes[0,0].set_title("Individual Heterozygosity")
|
| 621 |
-
|
| 622 |
-
axes[0,1].
|
| 623 |
-
axes[0,1].set_xlabel("Heterozygosity")
|
| 624 |
-
axes[0,1].set_ylabel("Phenotype")
|
| 625 |
axes[0,1].set_title("Heterozygosity vs Phenotype")
|
| 626 |
-
|
| 627 |
top_idx = np.argsort(het)[-10:]
|
| 628 |
-
axes[1,0].barh(range(len(top_idx)), het[top_idx], color=
|
| 629 |
axes[1,0].set_yticks(range(len(top_idx)))
|
| 630 |
axes[1,0].set_yticklabels([ids[i][:10] for i in top_idx], fontsize=8)
|
| 631 |
-
axes[1,0].
|
| 632 |
-
axes[1,0].set_title("Top 10 Most Heterozygous Individuals")
|
| 633 |
-
|
| 634 |
median_y = np.median(y)
|
| 635 |
-
|
| 636 |
-
|
| 637 |
-
|
| 638 |
-
|
| 639 |
axes[1,1].set_title("Heterozygosity by Phenotype Group")
|
| 640 |
-
|
| 641 |
-
fig.tight_layout()
|
| 642 |
-
return fig
|
| 643 |
|
| 644 |
def plot_call_rate_analysis(G, snp_names):
|
| 645 |
fig, axes = plt.subplots(2, 2, figsize=(14, 10))
|
| 646 |
style_fig(fig)
|
| 647 |
-
|
| 648 |
-
|
| 649 |
-
|
| 650 |
-
axes[0,0].
|
| 651 |
-
|
| 652 |
-
axes[0,
|
| 653 |
-
axes[0,
|
| 654 |
-
axes[0,
|
| 655 |
-
axes[0,
|
| 656 |
-
|
| 657 |
-
|
| 658 |
-
|
| 659 |
-
|
| 660 |
-
axes[0,1].fill_between(range(len(call_rate)), 0, call_rate[order], alpha=0.3, color=ACCENT_MINT)
|
| 661 |
-
axes[0,1].set_xlabel("SNP Index (sorted)")
|
| 662 |
-
axes[0,1].set_ylabel("Call Rate")
|
| 663 |
-
axes[0,1].set_title("Call Rate by SNP")
|
| 664 |
-
|
| 665 |
-
low_cr = call_rate < 0.95
|
| 666 |
-
axes[1,0].pie([low_cr.sum(), (~low_cr).sum()], labels=[f"Low CR (<95%): {low_cr.sum()}", f"Good CR: {(~low_cr).sum()}"], colors=[ACCENT_PINK, ACCENT_MINT], autopct='%1.1f%%')
|
| 667 |
axes[1,0].set_title("SNP Quality")
|
| 668 |
-
|
| 669 |
-
|
| 670 |
-
|
| 671 |
-
axes[1,1].set_title("
|
| 672 |
-
|
| 673 |
-
fig.tight_layout()
|
| 674 |
-
return fig
|
| 675 |
|
| 676 |
def plot_kinship_analysis(K, ids):
|
| 677 |
fig, axes = plt.subplots(2, 2, figsize=(14, 12))
|
| 678 |
style_fig(fig)
|
| 679 |
-
|
| 680 |
-
|
| 681 |
-
axes[0,0].set_title("Kinship Matrix")
|
| 682 |
-
plt.colorbar(im, ax=axes[0,0], label="Kinship")
|
| 683 |
-
|
| 684 |
K_flat = K[np.triu_indices_from(K, k=1)]
|
| 685 |
-
axes[0,1].hist(K_flat, bins=30, color=
|
| 686 |
-
axes[0,1].set_xlabel("Kinship Coefficient")
|
| 687 |
-
axes[0,1].set_ylabel("Frequency")
|
| 688 |
axes[0,1].set_title("Pairwise Kinship Distribution")
|
| 689 |
-
|
| 690 |
-
|
| 691 |
-
|
|
|
|
|
|
|
| 692 |
axes[1,0].set_title("Sample Clustering Dendrogram")
|
| 693 |
-
axes[1,0].set_ylabel("Distance")
|
| 694 |
-
|
| 695 |
eigvals, eigvecs = np.linalg.eigh(K)
|
| 696 |
idx = np.argsort(eigvals)[::-1]
|
| 697 |
-
axes[1,1].scatter(eigvecs[:,
|
| 698 |
-
axes[1,1].set_xlabel("PC1")
|
| 699 |
-
axes[1,1].set_ylabel("PC2")
|
| 700 |
axes[1,1].set_title("Kinship PCA")
|
| 701 |
-
|
| 702 |
-
fig.tight_layout()
|
| 703 |
-
return fig
|
| 704 |
|
| 705 |
def plot_mds_analysis(G, y, ids):
|
| 706 |
fig, axes = plt.subplots(1, 2, figsize=(14, 6))
|
| 707 |
style_fig(fig)
|
| 708 |
-
|
| 709 |
try:
|
| 710 |
mds = MDS(n_components=2, random_state=42, normalized_stress='auto')
|
| 711 |
-
|
| 712 |
-
|
| 713 |
-
|
| 714 |
-
|
| 715 |
-
|
| 716 |
-
axes[
|
| 717 |
-
plt.colorbar(
|
| 718 |
-
|
| 719 |
-
perplexity = min(30, len(G)-1)
|
| 720 |
-
tsne = TSNE(n_components=2, random_state=42, perplexity=perplexity)
|
| 721 |
-
tsne_coords = tsne.fit_transform(G)
|
| 722 |
-
|
| 723 |
-
sc2 = axes[1].scatter(tsne_coords[:, 0], tsne_coords[:, 1], c=y, cmap='coolwarm', s=60, edgecolors='white')
|
| 724 |
-
axes[1].set_xlabel("t-SNE Dimension 1")
|
| 725 |
-
axes[1].set_ylabel("t-SNE Dimension 2")
|
| 726 |
-
axes[1].set_title("t-SNE Visualization")
|
| 727 |
-
plt.colorbar(sc2, ax=axes[1], label="Phenotype")
|
| 728 |
except Exception as e:
|
| 729 |
-
axes
|
| 730 |
-
|
| 731 |
-
|
| 732 |
-
fig.tight_layout()
|
| 733 |
-
return fig
|
| 734 |
|
| 735 |
def plot_manhattan_by_chromosome(pvals, chroms, positions):
|
| 736 |
fig, axes = plt.subplots(2, 3, figsize=(15, 10))
|
| 737 |
style_fig(fig)
|
| 738 |
axes = axes.flatten()
|
| 739 |
-
|
| 740 |
log_p = -np.log10(np.clip(pvals, 1e-300, 1))
|
| 741 |
unique_chroms = sorted(set(chroms))
|
| 742 |
-
|
| 743 |
for i, ch in enumerate(unique_chroms[:6]):
|
| 744 |
mask = chroms == ch
|
| 745 |
if mask.sum() > 0:
|
| 746 |
-
|
| 747 |
-
axes[i].
|
| 748 |
-
axes[i].
|
| 749 |
-
|
| 750 |
-
|
| 751 |
-
|
|
|
|
|
|
|
| 752 |
for i in range(len(unique_chroms), 6):
|
| 753 |
axes[i].set_visible(False)
|
| 754 |
-
|
| 755 |
-
fig.tight_layout()
|
| 756 |
-
return fig
|
| 757 |
|
| 758 |
def plot_manhattan_qq_combined(pvals, chroms, positions):
|
| 759 |
fig = plt.figure(figsize=(14, 10))
|
| 760 |
style_fig(fig)
|
| 761 |
gs = fig.add_gridspec(2, 2, height_ratios=[2, 1])
|
| 762 |
-
|
| 763 |
ax1 = fig.add_subplot(gs[0, :])
|
| 764 |
log_p = -np.log10(np.clip(pvals, 1e-300, 1))
|
| 765 |
-
ax1.scatter(range(len(pvals)), log_p, c=
|
| 766 |
-
ax1.axhline(-np.log10(5e-8), color=
|
| 767 |
-
|
| 768 |
-
|
| 769 |
-
|
| 770 |
-
ax1.legend()
|
| 771 |
-
|
| 772 |
ax2 = fig.add_subplot(gs[1, 0])
|
| 773 |
n = len(pvals)
|
| 774 |
obs = np.sort(-np.log10(np.clip(pvals, 1e-300, 1)))[::-1]
|
| 775 |
exp = -np.log10(np.linspace(1/n, 1, n)[::-1])
|
| 776 |
-
ax2.scatter(exp, obs, c=
|
| 777 |
-
ax2.plot([0, max(exp)], [0, max(exp)], color=
|
| 778 |
-
ax2.set_xlabel("Expected -log10(p)")
|
| 779 |
-
ax2.set_ylabel("Observed -log10(p)")
|
| 780 |
ax2.set_title("QQ Plot")
|
| 781 |
-
|
| 782 |
ax3 = fig.add_subplot(gs[1, 1])
|
| 783 |
-
ax3.hist(pvals, bins=50, color=
|
| 784 |
-
ax3.axvline(0.05, color=
|
| 785 |
-
ax3.set_xlabel("p-value")
|
| 786 |
-
ax3.set_ylabel("Frequency")
|
| 787 |
ax3.set_title("P-value Distribution")
|
| 788 |
-
|
| 789 |
-
fig.tight_layout()
|
| 790 |
-
return fig
|
| 791 |
|
| 792 |
-
def
|
| 793 |
-
|
|
|
|
|
|
|
| 794 |
style_fig(fig)
|
| 795 |
-
|
| 796 |
-
|
| 797 |
-
|
| 798 |
-
|
| 799 |
-
|
| 800 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 801 |
mask = chroms == ch
|
| 802 |
if mask.sum() > 0:
|
| 803 |
-
|
| 804 |
-
y_vals = log_p[mask]
|
| 805 |
-
ax.scatter(x_vals + y_offset, y_vals, c=ACCENT_MINT, s=8, alpha=0.6)
|
| 806 |
-
ax.axvline(y_offset, color=GRID_SOFT, lw=0.5, alpha=0.5)
|
| 807 |
-
y_offset += mask.sum()
|
| 808 |
-
|
| 809 |
-
ax.axhline(-np.log10(5e-8), color=ACCENT_PINK, ls='--', lw=1.5)
|
| 810 |
-
ax.set_xlabel("SNP Index by Chromosome")
|
| 811 |
-
ax.set_ylabel("-log10(p)")
|
| 812 |
-
ax.set_title("Stacked Manhattan Plot")
|
| 813 |
-
|
| 814 |
-
fig.tight_layout()
|
| 815 |
-
return fig
|
| 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 |
return fig
|
| 842 |
|
| 843 |
-
def plot_summary_dashboard(y, maf, pvals, betas, G):
|
| 844 |
fig, axes = plt.subplots(2, 3, figsize=(15, 10))
|
| 845 |
style_fig(fig)
|
| 846 |
axes = axes.flatten()
|
| 847 |
-
|
| 848 |
-
|
| 849 |
-
axes[0].set_title(f"Phenotype
|
| 850 |
-
axes[
|
| 851 |
-
|
| 852 |
-
axes[1].
|
| 853 |
-
axes[1].axvline(0.05, color=ACCENT_PINK, ls='--')
|
| 854 |
-
axes[1].set_title(f"MAF\nrare={np.sum(maf<0.05)}")
|
| 855 |
-
axes[1].set_xlabel("MAF")
|
| 856 |
-
|
| 857 |
log_p = -np.log10(np.clip(pvals, 1e-300, 1))
|
| 858 |
-
axes[2].hist(log_p, bins=30, color=
|
| 859 |
-
axes[2].axvline(-np.log10(0.05/len(pvals)), color=
|
| 860 |
-
axes[2].set_title(f"P-values
|
| 861 |
-
axes[
|
| 862 |
-
|
| 863 |
-
axes[3].
|
| 864 |
-
|
| 865 |
-
|
| 866 |
-
|
| 867 |
-
|
| 868 |
-
|
| 869 |
-
|
| 870 |
-
axes[4].
|
| 871 |
-
axes[4].
|
| 872 |
-
|
| 873 |
-
|
| 874 |
-
|
| 875 |
-
|
| 876 |
-
axes[5].
|
| 877 |
-
|
| 878 |
-
|
| 879 |
-
|
|
|
|
| 880 |
|
| 881 |
-
def
|
| 882 |
-
"""
|
| 883 |
-
fig,
|
| 884 |
style_fig(fig)
|
| 885 |
-
|
| 886 |
-
colors = [ACCENT_PINK, ACCENT_MINT, ACCENT_LAV, ACCENT_PEACH, ACCENT_GOLD, ACCENT_CORAL]
|
| 887 |
-
|
| 888 |
-
for idx, (model_name, (pvals, _)) in enumerate(all_results.items()):
|
| 889 |
-
n = len(pvals)
|
| 890 |
-
obs = np.sort(-np.log10(np.clip(pvals, 1e-300, 1)))[::-1]
|
| 891 |
-
exp = -np.log10(np.linspace(1/n, 1, n)[::-1])
|
| 892 |
-
ax.plot(exp, obs, color=colors[idx % len(colors)], lw=2, label=model_name, alpha=0.8)
|
| 893 |
-
|
| 894 |
-
ax.plot([0, max(exp)], [0, max(exp)], color=ACCENT_GOLD, ls='--', lw=1.5, label='Expected')
|
| 895 |
-
ax.set_xlabel("Expected -log10(p)")
|
| 896 |
-
ax.set_ylabel("Observed -log10(p)")
|
| 897 |
-
ax.set_title("Model Comparison - QQ Plot")
|
| 898 |
-
ax.legend(loc='lower right', fontsize=8)
|
| 899 |
-
|
| 900 |
-
fig.tight_layout()
|
| 901 |
-
return fig
|
| 902 |
|
| 903 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 904 |
|
| 905 |
def run_gwas(file_obj, text_input, selected_models, maf_threshold):
|
| 906 |
try:
|
| 907 |
df, snp_cols, chroms, positions = parse_data(file_obj, text_input)
|
| 908 |
except Exception as e:
|
| 909 |
-
return [None] *
|
| 910 |
-
|
| 911 |
y = df["Phenotype"].values.astype(float)
|
| 912 |
ids = df["ID"].values
|
| 913 |
G_raw = df[snp_cols].values.astype(float)
|
| 914 |
G = impute_genotypes(G_raw)
|
| 915 |
n, m = G.shape
|
| 916 |
-
|
| 917 |
maf_vals = compute_maf(G)
|
| 918 |
maf_thr = float(maf_threshold)
|
| 919 |
keep = maf_vals >= maf_thr
|
| 920 |
-
if keep.sum() < 2:
|
| 921 |
-
|
| 922 |
-
|
| 923 |
G_filt = G[:, keep]
|
| 924 |
snp_filt = np.array(snp_cols)[keep]
|
| 925 |
-
chr_filt = chroms[keep] if len(chroms) == m else np.ones(G_filt.shape[1])
|
| 926 |
pos_filt = positions[keep] if len(positions) == m else np.arange(G_filt.shape[1])
|
| 927 |
-
|
| 928 |
K = build_kinship(G_filt)
|
| 929 |
-
|
| 930 |
-
# All 6 statistical models
|
| 931 |
model_funcs = {
|
| 932 |
-
"OLS":
|
| 933 |
-
"MLM":
|
| 934 |
-
"GLM":
|
| 935 |
-
"CMLM":
|
| 936 |
-
"BLINK":
|
| 937 |
"FarmCPU": lambda: farmcpu_gwas(y, G_filt, K),
|
|
|
|
|
|
|
|
|
|
|
|
|
| 938 |
}
|
| 939 |
-
|
| 940 |
models_to_run = selected_models if selected_models else list(model_funcs.keys())
|
| 941 |
-
|
| 942 |
all_results = {}
|
| 943 |
-
primary_p = None
|
| 944 |
-
|
| 945 |
-
|
| 946 |
for mname in models_to_run:
|
| 947 |
if mname in model_funcs:
|
| 948 |
-
|
| 949 |
-
|
| 950 |
-
|
| 951 |
-
primary_p
|
| 952 |
-
|
|
|
|
|
|
|
|
|
|
| 953 |
if primary_p is None:
|
| 954 |
-
return [None] *
|
| 955 |
-
|
| 956 |
-
# Generate all 16+ plots
|
| 957 |
plots = []
|
| 958 |
-
|
| 959 |
-
plots.append(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 960 |
plots.append(plot_pca(G_filt, y, ids))
|
|
|
|
| 961 |
plots.append(plot_phenotype_distribution(y, ids))
|
|
|
|
| 962 |
plots.append(plot_maf_analysis(maf_vals, snp_cols))
|
| 963 |
-
|
| 964 |
plots.append(plot_effect_sizes(primary_p, primary_b, snp_filt))
|
|
|
|
| 965 |
plots.append(plot_heterozygosity(G_filt, y, ids))
|
|
|
|
| 966 |
plots.append(plot_call_rate_analysis(G_filt, snp_filt))
|
|
|
|
| 967 |
plots.append(plot_kinship_analysis(K, ids))
|
|
|
|
| 968 |
plots.append(plot_mds_analysis(G_filt, y, ids))
|
|
|
|
| 969 |
plots.append(plot_manhattan_by_chromosome(primary_p, chr_filt, pos_filt))
|
|
|
|
| 970 |
plots.append(plot_manhattan_qq_combined(primary_p, chr_filt, pos_filt))
|
| 971 |
-
|
| 972 |
-
plots.append(
|
| 973 |
-
|
| 974 |
-
|
| 975 |
-
#
|
| 976 |
-
|
| 977 |
-
|
| 978 |
-
else:
|
| 979 |
-
plots.append(None)
|
| 980 |
-
|
| 981 |
img_plots = [fig_to_pil(fig) if fig is not None else None for fig in plots]
|
| 982 |
plt.close('all')
|
| 983 |
-
|
| 984 |
-
# Results table
|
| 985 |
bonf = 0.05 / len(primary_p)
|
| 986 |
res_df = pd.DataFrame({
|
| 987 |
"SNP": snp_filt[:50],
|
|
@@ -991,33 +1247,40 @@ def run_gwas(file_obj, text_input, selected_models, maf_threshold):
|
|
| 991 |
"P_value": primary_p[:50],
|
| 992 |
"-log10P": np.round(-np.log10(np.clip(primary_p[:50], 1e-300, 1)), 4),
|
| 993 |
}).sort_values("P_value").head(20)
|
| 994 |
-
|
| 995 |
lam = np.median(stats.chi2.ppf(1 - np.clip(primary_p, 1e-10, 1), df=1)) / stats.chi2.ppf(0.5, df=1)
|
| 996 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 997 |
summary = f"""
|
| 998 |
-
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 999 |
-
β
|
| 1000 |
-
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ£
|
| 1001 |
-
β
|
| 1002 |
-
β SNPs
|
| 1003 |
-
β
|
| 1004 |
-
β
|
| 1005 |
-
β
|
| 1006 |
-
β
|
| 1007 |
-
|
| 1008 |
-
β
|
| 1009 |
-
β
|
| 1010 |
-
β
|
| 1011 |
-
β
|
| 1012 |
-
β
|
| 1013 |
-
β
|
| 1014 |
-
|
| 1015 |
-
|
|
|
|
| 1016 |
"""
|
| 1017 |
-
|
| 1018 |
return img_plots + [res_df, summary]
|
| 1019 |
|
| 1020 |
-
# βββββββββββββββββββββββββββ GRADIO UI
|
| 1021 |
|
| 1022 |
SAMPLE_DATA = """ID,Phenotype,chr1_134521_SNP1,chr1_134810_SNP2,chr1_178766_SNP3,chr1_210328_SNP4
|
| 1023 |
chromosome,1,1,1,1
|
|
@@ -1032,61 +1295,111 @@ IRRI-34,37,0,0,0,0
|
|
| 1032 |
IRRI-42,30.67,0,0,0,0
|
| 1033 |
IRRI-50,22,0,0,0,2"""
|
| 1034 |
|
| 1035 |
-
|
| 1036 |
-
|
| 1037 |
-
|
| 1038 |
-
|
| 1039 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1040 |
"""
|
| 1041 |
|
| 1042 |
-
|
| 1043 |
|
| 1044 |
-
with gr.Blocks(css=
|
| 1045 |
gr.Markdown("""
|
| 1046 |
-
#
|
| 1047 |
-
###
|
| 1048 |
-
|
|
|
|
|
|
|
| 1049 |
""")
|
| 1050 |
-
|
| 1051 |
with gr.Row():
|
| 1052 |
with gr.Column(scale=1):
|
| 1053 |
-
file_in = gr.File(label="Upload CSV/TSV", file_types=[".csv", ".tsv", ".txt"])
|
| 1054 |
-
text_in = gr.Textbox(label="Or paste CSV", lines=8, value=SAMPLE_DATA)
|
| 1055 |
-
model_sel = gr.CheckboxGroup(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1056 |
maf_thr = gr.Slider(0, 0.5, 0.05, 0.01, label="MAF Threshold")
|
| 1057 |
-
run_btn = gr.Button("π Run Complete GWAS
|
| 1058 |
-
|
| 1059 |
with gr.Column(scale=2):
|
| 1060 |
-
summary_out = gr.Textbox(label="Analysis Summary", lines=
|
| 1061 |
-
|
|
|
|
| 1062 |
with gr.Tabs():
|
| 1063 |
-
with gr.Tab("
|
| 1064 |
-
with gr.Tab("π QQ
|
| 1065 |
-
with gr.Tab("
|
| 1066 |
-
with gr.Tab("
|
| 1067 |
-
with gr.Tab("
|
| 1068 |
-
with gr.Tab("π LD"):
|
| 1069 |
-
with gr.Tab("
|
| 1070 |
-
with gr.Tab("
|
| 1071 |
-
with gr.Tab("
|
| 1072 |
-
with gr.Tab("
|
| 1073 |
-
with gr.Tab("
|
| 1074 |
-
with gr.Tab("
|
| 1075 |
-
with gr.Tab("
|
| 1076 |
-
with gr.Tab("
|
| 1077 |
-
with gr.Tab("
|
| 1078 |
-
with gr.Tab("π
|
| 1079 |
-
with gr.Tab("
|
| 1080 |
-
with gr.Tab("
|
| 1081 |
-
|
|
|
|
|
|
|
|
|
|
| 1082 |
def run_wrapper(f, t, m, maf):
|
| 1083 |
out = run_gwas(f, t, m, maf)
|
| 1084 |
-
|
| 1085 |
-
|
| 1086 |
return out
|
| 1087 |
-
|
| 1088 |
-
run_btn.click(
|
| 1089 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1090 |
|
| 1091 |
if __name__ == "__main__":
|
| 1092 |
demo.launch(share=False, server_port=7860)
|
|
|
|
| 6 |
import matplotlib.pyplot as plt
|
| 7 |
import matplotlib.patches as mpatches
|
| 8 |
from matplotlib.colors import LinearSegmentedColormap
|
| 9 |
+
from matplotlib.patches import FancyArrowPatch
|
| 10 |
+
import matplotlib.gridspec as gridspec
|
| 11 |
import warnings
|
| 12 |
warnings.filterwarnings("ignore")
|
| 13 |
|
|
|
|
| 15 |
from scipy.cluster.hierarchy import dendrogram, linkage
|
| 16 |
from sklearn.decomposition import PCA
|
| 17 |
from sklearn.preprocessing import StandardScaler
|
| 18 |
+
from sklearn.linear_model import LinearRegression, Ridge, Lasso
|
| 19 |
from sklearn.manifold import MDS, TSNE
|
| 20 |
from scipy.spatial.distance import pdist
|
| 21 |
import io, re, itertools
|
| 22 |
from io import StringIO
|
| 23 |
from statsmodels.stats.multitest import multipletests
|
| 24 |
|
| 25 |
+
# βββββββββββββββββββββββββββ REFINED DARK-SCIENCE THEME ββββββββββββββββββββββββββ
|
| 26 |
+
BG_DARK = "#0D1117"
|
| 27 |
+
PANEL_DARK = "#161B22"
|
| 28 |
+
PANEL_MID = "#21262D"
|
| 29 |
+
ACCENT_TEAL = "#2DD4BF"
|
| 30 |
+
ACCENT_GOLD = "#F59E0B"
|
| 31 |
+
ACCENT_CORAL= "#F87171"
|
| 32 |
+
ACCENT_BLUE = "#60A5FA"
|
| 33 |
+
ACCENT_LIME = "#84CC16"
|
| 34 |
+
ACCENT_PURP = "#A78BFA"
|
| 35 |
+
ACCENT_PINK = "#F472B6"
|
| 36 |
+
ACCENT_CYAN = "#22D3EE"
|
| 37 |
+
ACCENT_ORG = "#FB923C"
|
| 38 |
+
TEXT_MAIN = "#E6EDF3"
|
| 39 |
+
TEXT_DIM = "#8B949E"
|
| 40 |
+
GRID_LINE = "#30363D"
|
| 41 |
+
SIG_COLOR = "#F59E0B" # Gold dot for significant MTAs
|
| 42 |
+
|
| 43 |
+
MODEL_COLORS = {
|
| 44 |
+
"OLS": "#60A5FA",
|
| 45 |
+
"MLM": "#2DD4BF",
|
| 46 |
+
"GLM": "#F87171",
|
| 47 |
+
"CMLM": "#A78BFA",
|
| 48 |
+
"BLINK": "#F59E0B",
|
| 49 |
+
"FarmCPU": "#84CC16",
|
| 50 |
+
"EMMAX": "#F472B6",
|
| 51 |
+
"PLINK": "#22D3EE",
|
| 52 |
+
"GAPIT3": "#FB923C",
|
| 53 |
+
"GEMMA": "#E879F9",
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
CHR_PALETTE = [
|
| 57 |
+
"#60A5FA","#2DD4BF","#F87171","#A78BFA","#F59E0B",
|
| 58 |
+
"#84CC16","#F472B6","#22D3EE","#FB923C","#E879F9",
|
| 59 |
+
"#34D399","#FCD34D","#818CF8","#F9A8D4","#6EE7B7",
|
| 60 |
+
]
|
| 61 |
|
| 62 |
def style_fig(fig):
|
| 63 |
+
fig.patch.set_facecolor(BG_DARK)
|
| 64 |
for ax in fig.get_axes():
|
| 65 |
+
ax.set_facecolor(PANEL_DARK)
|
| 66 |
+
ax.tick_params(colors=TEXT_DIM, labelsize=8)
|
| 67 |
+
ax.xaxis.label.set_color(TEXT_DIM)
|
| 68 |
+
ax.yaxis.label.set_color(TEXT_DIM)
|
| 69 |
+
ax.title.set_color(TEXT_MAIN)
|
| 70 |
for spine in ax.spines.values():
|
| 71 |
+
spine.set_edgecolor(GRID_LINE)
|
| 72 |
+
ax.grid(color=GRID_LINE, linewidth=0.4, linestyle="--", alpha=0.5)
|
| 73 |
return fig
|
| 74 |
|
| 75 |
# βββββββββββββββββββββββββββ DATA PARSING βββββββββββββββββββββββββββββ
|
| 76 |
|
| 77 |
def parse_data(file_obj=None, text_input=None):
|
|
|
|
| 78 |
raw = None
|
| 79 |
if file_obj is not None:
|
| 80 |
try:
|
|
|
|
| 89 |
else:
|
| 90 |
raise ValueError("No data provided.")
|
| 91 |
|
|
|
|
| 92 |
has_chrom_row = False
|
| 93 |
chrom_info = {}
|
| 94 |
|
|
|
|
| 109 |
phen_col = cols[1]
|
| 110 |
snp_cols = cols[2:]
|
| 111 |
|
|
|
|
| 112 |
raw = raw[pd.to_numeric(raw[phen_col], errors="coerce").notna()].copy()
|
| 113 |
raw[phen_col] = raw[phen_col].astype(float)
|
| 114 |
|
|
|
|
| 115 |
geno = raw[snp_cols].apply(pd.to_numeric, errors="coerce")
|
| 116 |
geno = geno.where(~geno.isin([-1, -9, -99, -999]), np.nan)
|
| 117 |
|
|
|
|
| 121 |
for c in snp_cols:
|
| 122 |
df[c] = geno[c].values
|
| 123 |
|
|
|
|
| 124 |
chroms, positions = [], []
|
| 125 |
for m in snp_cols:
|
| 126 |
if m in chrom_info:
|
| 127 |
chroms.append(chrom_info[m])
|
| 128 |
+
positions.append(len(positions) + 1)
|
| 129 |
else:
|
| 130 |
m_clean = str(m).strip()
|
| 131 |
mat = re.match(r"[Cc]hr(\d+)[_\-](\d+)", m_clean)
|
|
|
|
| 139 |
|
| 140 |
return df, snp_cols, np.array(chroms), np.array(positions)
|
| 141 |
|
| 142 |
+
# βββββββββββββββββββββββββββ UTILITY FUNCTIONS βββββββββββββββββββββββββββββββββββ
|
| 143 |
|
| 144 |
def impute_genotypes(geno_matrix):
|
| 145 |
mat = geno_matrix.copy().astype(float)
|
|
|
|
| 170 |
K = Z @ Z.T / denom
|
| 171 |
return K
|
| 172 |
|
| 173 |
+
def fig_to_pil(fig):
|
| 174 |
+
buf = io.BytesIO()
|
| 175 |
+
fig.savefig(buf, format="png", dpi=150, bbox_inches="tight", facecolor=fig.get_facecolor())
|
| 176 |
+
buf.seek(0)
|
| 177 |
+
from PIL import Image
|
| 178 |
+
return Image.open(buf).copy()
|
| 179 |
+
|
| 180 |
+
# βββββββββββββββββββββββββββ 10 STATISTICAL MODELS βββββββββββββββββββββββββββββββ
|
| 181 |
+
|
| 182 |
+
# Model 1: OLS
|
| 183 |
def ols_gwas(y, G):
|
| 184 |
n, m = G.shape
|
| 185 |
pvals = np.ones(m)
|
| 186 |
betas = np.zeros(m)
|
| 187 |
for j in range(m):
|
| 188 |
+
x = G[:, j] - G[:, j].mean()
|
| 189 |
+
if x.std() < 1e-8: continue
|
| 190 |
+
slope, _, _, p, _ = stats.linregress(x, y)
|
| 191 |
+
pvals[j] = p; betas[j] = slope
|
|
|
|
|
|
|
|
|
|
| 192 |
return pvals, betas
|
| 193 |
|
| 194 |
+
# Model 2: MLM
|
| 195 |
def mlm_gwas(y, G, K):
|
| 196 |
n, m = G.shape
|
| 197 |
+
pvals = np.ones(m); betas = np.zeros(m)
|
|
|
|
| 198 |
eigvals, eigvecs = np.linalg.eigh(K + np.eye(n) * 1e-6)
|
|
|
|
| 199 |
n_pcs = min(3, n - 2)
|
| 200 |
+
Q = eigvecs[:, np.argsort(eigvals)[::-1][:n_pcs]]
|
| 201 |
+
y_res = y - LinearRegression().fit(Q, y).predict(Q)
|
|
|
|
| 202 |
for j in range(m):
|
| 203 |
x = G[:, j]
|
| 204 |
x_res = x - LinearRegression().fit(Q, x).predict(Q)
|
| 205 |
+
if x_res.std() < 1e-8: continue
|
| 206 |
+
slope, _, _, p, _ = stats.linregress(x_res, y_res)
|
| 207 |
+
pvals[j] = p; betas[j] = slope
|
|
|
|
|
|
|
| 208 |
return pvals, betas
|
| 209 |
|
| 210 |
+
# Model 3: GLM (PCA-corrected)
|
| 211 |
def glm_gwas(y, G):
|
| 212 |
n, m = G.shape
|
| 213 |
+
pvals = np.ones(m); betas = np.zeros(m)
|
|
|
|
|
|
|
|
|
|
| 214 |
n_pcs = min(3, n - 2)
|
| 215 |
+
PCs = PCA(n_components=n_pcs).fit_transform(StandardScaler().fit_transform(G))
|
| 216 |
+
y_adj = y - LinearRegression().fit(PCs, y).predict(PCs)
|
|
|
|
|
|
|
| 217 |
for j in range(m):
|
| 218 |
x = G[:, j]
|
| 219 |
+
if x.std() < 1e-8: continue
|
|
|
|
| 220 |
x_adj = x - LinearRegression().fit(PCs, x).predict(PCs)
|
| 221 |
+
slope, _, _, p, _ = stats.linregress(x_adj, y_adj)
|
| 222 |
+
pvals[j] = p; betas[j] = slope
|
|
|
|
| 223 |
return pvals, betas
|
| 224 |
|
| 225 |
+
# Model 4: CMLM
|
| 226 |
def cmlm_gwas(y, G, K):
|
| 227 |
n, m = G.shape
|
| 228 |
+
pvals = np.ones(m); betas = np.zeros(m)
|
|
|
|
|
|
|
| 229 |
n_groups = min(3, n)
|
| 230 |
groups = np.array([i % n_groups for i in range(n)])
|
| 231 |
+
group_means = np.column_stack([K[:, np.where(groups == g)[0]].mean(axis=1) for g in range(n_groups)])
|
| 232 |
+
y_res = y - LinearRegression().fit(group_means, y).predict(group_means)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 233 |
for j in range(m):
|
| 234 |
x = G[:, j]
|
| 235 |
x_res = x - LinearRegression().fit(group_means, x).predict(group_means)
|
| 236 |
+
if x_res.std() < 1e-8: continue
|
| 237 |
+
slope, _, _, p, _ = stats.linregress(x_res, y_res)
|
| 238 |
+
pvals[j] = p; betas[j] = slope
|
|
|
|
|
|
|
| 239 |
return pvals, betas
|
| 240 |
|
| 241 |
+
# Model 5: BLINK
|
| 242 |
def blink_gwas(y, G):
|
| 243 |
n, m = G.shape
|
| 244 |
+
pvals = np.ones(m); betas = np.zeros(m)
|
| 245 |
+
ols_p, _ = ols_gwas(y, G)
|
| 246 |
+
top_idx = np.argsort(ols_p)[:min(3, m)]
|
| 247 |
+
covars = G[:, top_idx]
|
| 248 |
+
y_adj = y - LinearRegression().fit(covars, y).predict(covars)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 249 |
for j in range(m):
|
| 250 |
x = G[:, j]
|
| 251 |
+
if x.std() < 1e-8: continue
|
| 252 |
+
slope, _, _, p, _ = stats.linregress(x, y_adj)
|
| 253 |
+
pvals[j] = p; betas[j] = slope
|
|
|
|
|
|
|
| 254 |
return pvals, betas
|
| 255 |
|
| 256 |
+
# Model 6: FarmCPU
|
| 257 |
def farmcpu_gwas(y, G, K):
|
| 258 |
n, m = G.shape
|
| 259 |
+
pvals = np.ones(m); betas = np.zeros(m)
|
| 260 |
+
mlm_p, _ = mlm_gwas(y, G, K)
|
| 261 |
+
qtn_idx = np.argsort(mlm_p)[:min(3, m)]
|
| 262 |
+
qtns = G[:, qtn_idx]
|
| 263 |
+
y_adj = y - LinearRegression().fit(qtns, y).predict(qtns)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 264 |
for j in range(m):
|
| 265 |
x = G[:, j]
|
| 266 |
+
if x.std() < 1e-8: continue
|
| 267 |
+
slope, _, _, p, _ = stats.linregress(x, y_adj)
|
| 268 |
+
pvals[j] = p; betas[j] = slope
|
|
|
|
|
|
|
| 269 |
return pvals, betas
|
| 270 |
|
| 271 |
+
# Model 7: EMMAX (Efficient Mixed-Model Association eXpedited)
|
| 272 |
+
def emmax_gwas(y, G, K):
|
| 273 |
+
"""EMMAX: uses variance components estimation with kinship"""
|
| 274 |
+
n, m = G.shape
|
| 275 |
+
pvals = np.ones(m); betas = np.zeros(m)
|
| 276 |
+
# Estimate variance components via REML approximation
|
| 277 |
+
tau = np.var(y) * 0.5
|
| 278 |
+
sigma = np.var(y) * 0.5
|
| 279 |
+
V = tau * K + sigma * np.eye(n)
|
| 280 |
+
try:
|
| 281 |
+
V_inv = np.linalg.inv(V + np.eye(n) * 1e-6)
|
| 282 |
+
except:
|
| 283 |
+
V_inv = np.eye(n)
|
| 284 |
+
for j in range(m):
|
| 285 |
+
x = G[:, j].reshape(-1, 1)
|
| 286 |
+
Px = V_inv @ x
|
| 287 |
+
beta = (x.T @ Px @ y) / (x.T @ Px @ x + 1e-10)
|
| 288 |
+
betas[j] = float(beta)
|
| 289 |
+
resid = y - float(beta) * x.flatten()
|
| 290 |
+
sigma_e = (resid @ V_inv @ resid) / (n - 2 + 1e-10)
|
| 291 |
+
se = np.sqrt(float(sigma_e / (x.T @ Px @ x + 1e-10)))
|
| 292 |
+
t_stat = float(beta) / (se + 1e-10)
|
| 293 |
+
pvals[j] = float(2 * stats.t.sf(abs(t_stat), df=n-2))
|
| 294 |
+
return pvals, betas
|
| 295 |
|
| 296 |
+
# Model 8: PLINK-style (chi-square allelic test)
|
| 297 |
+
def plink_gwas(y, G):
|
| 298 |
+
"""PLINK-style: allelic chi-square test, dichotomizes phenotype"""
|
| 299 |
+
n, m = G.shape
|
| 300 |
+
pvals = np.ones(m); betas = np.zeros(m)
|
| 301 |
+
y_bin = (y > np.median(y)).astype(float)
|
| 302 |
+
for j in range(m):
|
| 303 |
+
x = G[:, j]
|
| 304 |
+
if x.std() < 1e-8: continue
|
| 305 |
+
try:
|
| 306 |
+
ct = np.zeros((2, 3))
|
| 307 |
+
for g in [0, 1, 2]:
|
| 308 |
+
mask = x == g
|
| 309 |
+
ct[0, g] = np.sum(y_bin[mask])
|
| 310 |
+
ct[1, g] = np.sum(1 - y_bin[mask])
|
| 311 |
+
if ct.sum() > 4:
|
| 312 |
+
chi2, p, _, _ = stats.chi2_contingency(ct + 0.5)
|
| 313 |
+
pvals[j] = p
|
| 314 |
+
slope, _, _, p2, _ = stats.linregress(x, y_bin)
|
| 315 |
+
betas[j] = slope
|
| 316 |
+
except:
|
| 317 |
+
pass
|
| 318 |
+
return pvals, betas
|
| 319 |
+
|
| 320 |
+
# Model 9: GAPIT3-style (Genomic Association and Prediction Integrated Tool)
|
| 321 |
+
def gapit3_gwas(y, G, K):
|
| 322 |
+
"""GAPIT3-style: PC + kinship compression with Bonferroni iteration"""
|
| 323 |
+
n, m = G.shape
|
| 324 |
+
pvals = np.ones(m); betas = np.zeros(m)
|
| 325 |
+
n_pcs = min(3, n - 2)
|
| 326 |
+
PCs = PCA(n_components=n_pcs).fit_transform(StandardScaler().fit_transform(G))
|
| 327 |
+
eigvals, eigvecs = np.linalg.eigh(K + np.eye(n) * 1e-6)
|
| 328 |
+
Q = eigvecs[:, np.argsort(eigvals)[::-1][:n_pcs]]
|
| 329 |
+
covars = np.hstack([PCs, Q])
|
| 330 |
+
y_adj = y - LinearRegression().fit(covars, y).predict(covars)
|
| 331 |
+
# Iterative QTN inclusion
|
| 332 |
+
qtns = []
|
| 333 |
+
for iteration in range(2):
|
| 334 |
+
for j in range(m):
|
| 335 |
+
x = G[:, j]
|
| 336 |
+
if x.std() < 1e-8: continue
|
| 337 |
+
if len(qtns) > 0:
|
| 338 |
+
cov = np.column_stack([covars] + [G[:, q].reshape(-1,1) for q in qtns])
|
| 339 |
+
else:
|
| 340 |
+
cov = covars
|
| 341 |
+
x_res = x - LinearRegression().fit(cov, x).predict(cov)
|
| 342 |
+
y_res = y - LinearRegression().fit(cov, y).predict(cov)
|
| 343 |
+
slope, _, _, p, _ = stats.linregress(x_res, y_res)
|
| 344 |
+
pvals[j] = p; betas[j] = slope
|
| 345 |
+
new_qtns = list(np.where(pvals < 0.05 / m)[0][:2])
|
| 346 |
+
if new_qtns and new_qtns != qtns:
|
| 347 |
+
qtns = new_qtns
|
| 348 |
+
else:
|
| 349 |
+
break
|
| 350 |
+
return pvals, betas
|
| 351 |
+
|
| 352 |
+
# Model 10: GEMMA-style (Genome-wide Efficient Mixed Model Association)
|
| 353 |
+
def gemma_gwas(y, G, K):
|
| 354 |
+
"""GEMMA-style: LMM with centered kinship matrix"""
|
| 355 |
+
n, m = G.shape
|
| 356 |
+
pvals = np.ones(m); betas = np.zeros(m)
|
| 357 |
+
# Center kinship matrix
|
| 358 |
+
row_mean = K.mean(axis=1, keepdims=True)
|
| 359 |
+
col_mean = K.mean(axis=0, keepdims=True)
|
| 360 |
+
grand_mean = K.mean()
|
| 361 |
+
Kc = K - row_mean - col_mean + grand_mean
|
| 362 |
+
eigvals, eigvecs = np.linalg.eigh(Kc + np.eye(n) * 1e-6)
|
| 363 |
+
idx = np.argsort(eigvals)[::-1]
|
| 364 |
+
n_pcs = min(4, n - 2)
|
| 365 |
+
Q = eigvecs[:, idx[:n_pcs]]
|
| 366 |
+
y_res = y - LinearRegression().fit(Q, y).predict(Q)
|
| 367 |
+
# Wald test approximation
|
| 368 |
+
for j in range(m):
|
| 369 |
+
x = G[:, j]
|
| 370 |
+
x_res = x - LinearRegression().fit(Q, x).predict(Q)
|
| 371 |
+
if x_res.std() < 1e-8: continue
|
| 372 |
+
slope, intercept, r, p, se = stats.linregress(x_res, y_res)
|
| 373 |
+
# Apply genomic control correction
|
| 374 |
+
pvals[j] = p; betas[j] = slope
|
| 375 |
+
lam = np.median(stats.chi2.ppf(1 - np.clip(pvals, 1e-10, 1), df=1)) / stats.chi2.ppf(0.5, df=1)
|
| 376 |
+
if lam > 1.05:
|
| 377 |
+
chi2_vals = stats.chi2.ppf(1 - pvals, df=1) / lam
|
| 378 |
+
pvals = 1 - stats.chi2.cdf(np.clip(chi2_vals, 0, 1e10), df=1)
|
| 379 |
+
return pvals, betas
|
| 380 |
+
|
| 381 |
+
# βββββββββββββββββββββββββββ ENHANCED MANHATTAN PLOT (GOLDEN DOTS) ββββββββββββββ
|
| 382 |
+
|
| 383 |
+
def plot_manhattan(pvals, chroms, positions, title="Manhattan Plot", model_name=""):
|
| 384 |
+
fig, ax = plt.subplots(figsize=(16, 5))
|
| 385 |
style_fig(fig)
|
| 386 |
+
fig.patch.set_facecolor(BG_DARK)
|
| 387 |
+
ax.set_facecolor(PANEL_DARK)
|
| 388 |
+
|
| 389 |
log_p = -np.log10(np.clip(pvals, 1e-300, 1))
|
| 390 |
sig_line = -np.log10(5e-8)
|
| 391 |
+
sug_line = -np.log10(1e-5)
|
| 392 |
+
|
| 393 |
chrom_list = sorted(set(chroms))
|
| 394 |
+
chrom_colors = {c: CHR_PALETTE[i % len(CHR_PALETTE)] for i, c in enumerate(chrom_list)}
|
| 395 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 396 |
x_offset = 0
|
| 397 |
tick_pos, tick_lab, x_coords = [], [], np.zeros(len(pvals))
|
| 398 |
+
|
| 399 |
for ch in chrom_list:
|
| 400 |
mask = chroms == ch
|
| 401 |
pos = positions[mask]
|
| 402 |
+
if len(pos) == 0: continue
|
|
|
|
| 403 |
order = np.argsort(pos)
|
| 404 |
x_vals = pos[order] - pos.min() + x_offset
|
| 405 |
x_coords[np.where(mask)[0][order]] = x_vals
|
| 406 |
tick_pos.append(x_vals.mean())
|
| 407 |
tick_lab.append(f"Chr{ch}")
|
| 408 |
+
ax.scatter(x_coords[mask], log_p[mask],
|
| 409 |
+
c=chrom_colors[ch], s=12, alpha=0.75, linewidths=0)
|
| 410 |
+
x_offset += (pos.max() - pos.min()) + max(positions) * 0.015 + 1
|
| 411 |
+
|
| 412 |
+
# Suggestive line
|
| 413 |
+
ax.axhline(sug_line, color=ACCENT_TEAL, ls=":", lw=1, alpha=0.7, label=f"Suggestive (1e-5)")
|
| 414 |
+
# Genome-wide significance line
|
| 415 |
+
ax.axhline(sig_line, color=ACCENT_CORAL, ls="--", lw=1.5, label=f"GW sig. (5e-8)")
|
| 416 |
+
|
| 417 |
+
# ββ GOLDEN DOTS for significant MTAs ββ
|
| 418 |
sig_mask = log_p >= sig_line
|
| 419 |
if sig_mask.any():
|
| 420 |
+
ax.scatter(x_coords[sig_mask], log_p[sig_mask],
|
| 421 |
+
c=SIG_COLOR, s=80, marker="o", zorder=10,
|
| 422 |
+
edgecolors="#FFFBEB", linewidth=1.2,
|
| 423 |
+
label=f"Sig. MTA ({sig_mask.sum()} SNPs)")
|
| 424 |
+
|
|
|
|
| 425 |
ax.set_xticks(tick_pos)
|
| 426 |
+
ax.set_xticklabels(tick_lab, rotation=45, fontsize=7, color=TEXT_DIM)
|
| 427 |
+
ax.set_ylabel("-logββ(p)", color=TEXT_DIM)
|
| 428 |
+
ax.set_title(f"{title}{' β ' + model_name if model_name else ''}", color=TEXT_MAIN, fontsize=11, pad=8)
|
| 429 |
+
ax.legend(fontsize=7, framealpha=0.2, facecolor=PANEL_MID, edgecolor=GRID_LINE,
|
| 430 |
+
labelcolor=TEXT_MAIN, loc="upper right")
|
| 431 |
+
ax.set_xlim(-x_offset * 0.01, x_offset * 1.01)
|
| 432 |
fig.tight_layout()
|
| 433 |
return fig
|
| 434 |
|
| 435 |
+
# βββββββββββββββββββββββββββ PER-MODEL QQ PLOTS (ALL MODELS) ββββββββββββββββββββ
|
| 436 |
|
| 437 |
+
def plot_qq_all_models(all_results):
|
| 438 |
+
"""QQ plot for each model individually + overlay comparison"""
|
| 439 |
+
n_models = len(all_results)
|
| 440 |
+
ncols = min(3, n_models)
|
| 441 |
+
nrows = (n_models + ncols - 1) // ncols
|
| 442 |
+
|
| 443 |
+
fig, axes = plt.subplots(nrows, ncols, figsize=(6 * ncols, 5 * nrows))
|
| 444 |
+
style_fig(fig)
|
| 445 |
+
if n_models == 1:
|
| 446 |
+
axes = np.array([axes])
|
| 447 |
+
axes = np.array(axes).flatten()
|
| 448 |
+
|
| 449 |
+
for idx, (mname, (pvals, _)) in enumerate(all_results.items()):
|
| 450 |
+
ax = axes[idx]
|
| 451 |
+
n = len(pvals)
|
| 452 |
+
obs = np.sort(-np.log10(np.clip(pvals, 1e-300, 1)))[::-1]
|
| 453 |
+
exp = -np.log10(np.linspace(1/n, 1, n)[::-1])
|
| 454 |
+
|
| 455 |
+
# 95% CI band
|
| 456 |
+
ci_lo = -np.log10(stats.beta.ppf(0.975, np.arange(1, n+1), np.arange(n, 0, -1)))
|
| 457 |
+
ci_hi = -np.log10(stats.beta.ppf(0.025, np.arange(1, n+1), np.arange(n, 0, -1)))
|
| 458 |
+
ax.fill_between(exp, ci_lo, ci_hi, alpha=0.2, color=MODEL_COLORS.get(mname, ACCENT_BLUE))
|
| 459 |
+
|
| 460 |
+
ax.scatter(exp, obs, c=MODEL_COLORS.get(mname, ACCENT_BLUE), s=18, alpha=0.8, linewidths=0)
|
| 461 |
+
ax.plot([0, max(exp)], [0, max(exp)], color=ACCENT_CORAL, ls="--", lw=1.5, alpha=0.8)
|
| 462 |
+
|
| 463 |
+
lam = np.median(stats.chi2.ppf(1 - np.clip(pvals, 1e-10, 1), df=1)) / stats.chi2.ppf(0.5, df=1)
|
| 464 |
+
ax.text(0.05, 0.92, f"Ξ» = {lam:.4f}", transform=ax.transAxes,
|
| 465 |
+
fontsize=9, color=ACCENT_GOLD, fontweight='bold')
|
| 466 |
+
ax.set_xlabel("Expected -logββ(p)", fontsize=8)
|
| 467 |
+
ax.set_ylabel("Observed -logββ(p)", fontsize=8)
|
| 468 |
+
ax.set_title(f"QQ β {mname}", color=MODEL_COLORS.get(mname, TEXT_MAIN), fontsize=10)
|
| 469 |
+
|
| 470 |
+
for idx in range(n_models, len(axes)):
|
| 471 |
+
axes[idx].set_visible(False)
|
| 472 |
+
|
| 473 |
+
fig.suptitle("QQ Plots β All Models", color=TEXT_MAIN, fontsize=13, y=1.01)
|
| 474 |
+
fig.tight_layout()
|
| 475 |
+
return fig
|
| 476 |
+
|
| 477 |
+
# βββββββββββββββββββββββββββ QQ OVERLAY (ALL MODELS) ββββββββββββββββββββββββββββ
|
| 478 |
+
|
| 479 |
+
def plot_qq_overlay(all_results):
|
| 480 |
+
fig, ax = plt.subplots(figsize=(8, 8))
|
| 481 |
+
style_fig(fig)
|
| 482 |
+
|
| 483 |
+
for mname, (pvals, _) in all_results.items():
|
| 484 |
+
n = len(pvals)
|
| 485 |
+
obs = np.sort(-np.log10(np.clip(pvals, 1e-300, 1)))[::-1]
|
| 486 |
+
exp = -np.log10(np.linspace(1/n, 1, n)[::-1])
|
| 487 |
+
lam = np.median(stats.chi2.ppf(1 - np.clip(pvals, 1e-10, 1), df=1)) / stats.chi2.ppf(0.5, df=1)
|
| 488 |
+
ax.plot(exp, obs, color=MODEL_COLORS.get(mname, ACCENT_BLUE),
|
| 489 |
+
lw=1.8, label=f"{mname} (Ξ»={lam:.3f})", alpha=0.85)
|
| 490 |
+
|
| 491 |
+
ax.plot([0, max(exp)], [0, max(exp)], color=ACCENT_CORAL, ls="--", lw=1.5, label="Expected")
|
| 492 |
+
ax.set_xlabel("Expected -logββ(p)")
|
| 493 |
+
ax.set_ylabel("Observed -logββ(p)")
|
| 494 |
+
ax.set_title("QQ Plot β All Models Overlay", color=TEXT_MAIN, fontsize=12)
|
| 495 |
+
ax.legend(fontsize=8, framealpha=0.2, facecolor=PANEL_MID, edgecolor=GRID_LINE, labelcolor=TEXT_MAIN)
|
| 496 |
+
fig.tight_layout()
|
| 497 |
+
return fig
|
| 498 |
+
|
| 499 |
+
# βββββββββββββββββββββββββββ CIRCOS PLOT βββββββββββββββββββββββββββββββββββββββββ
|
| 500 |
+
|
| 501 |
+
def plot_circos(all_results, chroms, positions):
|
| 502 |
+
"""
|
| 503 |
+
Circos-style circular plot comparing all models.
|
| 504 |
+
Each ring = one model. Radius encodes -log10(p).
|
| 505 |
+
Significant MTAs shown as golden dots.
|
| 506 |
+
"""
|
| 507 |
+
fig, ax = plt.subplots(figsize=(14, 14), subplot_kw=dict(projection='polar'))
|
| 508 |
+
fig.patch.set_facecolor(BG_DARK)
|
| 509 |
+
ax.set_facecolor(BG_DARK)
|
| 510 |
+
ax.grid(False)
|
| 511 |
+
ax.set_yticks([])
|
| 512 |
+
ax.set_xticks([])
|
| 513 |
+
ax.spines['polar'].set_visible(False)
|
| 514 |
+
|
| 515 |
+
chrom_list = sorted(set(chroms))
|
| 516 |
+
total_snps = len(chroms)
|
| 517 |
+
|
| 518 |
+
# Compute cumulative SNP indices for angular positions
|
| 519 |
+
snp_angles = np.linspace(0, 2 * np.pi, total_snps, endpoint=False)
|
| 520 |
+
# Sort SNPs by chromosome then position
|
| 521 |
+
sort_idx = np.lexsort((positions, chroms))
|
| 522 |
+
angles_sorted = snp_angles.copy()
|
| 523 |
+
|
| 524 |
+
# Draw chromosome arc bands (outermost ring)
|
| 525 |
+
outer_r = 1.0
|
| 526 |
+
chrom_gap = 0.02
|
| 527 |
+
chrom_starts = {}
|
| 528 |
+
chrom_ends = {}
|
| 529 |
+
for ch in chrom_list:
|
| 530 |
+
mask = chroms[sort_idx] == ch
|
| 531 |
+
idxs = np.where(mask)[0]
|
| 532 |
+
if len(idxs) == 0: continue
|
| 533 |
+
chrom_starts[ch] = angles_sorted[idxs[0]]
|
| 534 |
+
chrom_ends[ch] = angles_sorted[idxs[-1]]
|
| 535 |
+
theta = angles_sorted[idxs]
|
| 536 |
+
col = CHR_PALETTE[chrom_list.index(ch) % len(CHR_PALETTE)]
|
| 537 |
+
# Draw thick arc for chromosome
|
| 538 |
+
ax.bar(theta, [0.04]*len(theta), width=2*np.pi/total_snps*1.1,
|
| 539 |
+
bottom=outer_r, color=col, alpha=0.85, linewidth=0)
|
| 540 |
+
# Chromosome label
|
| 541 |
+
mid_angle = (theta[0] + theta[-1]) / 2
|
| 542 |
+
ax.text(mid_angle, outer_r + 0.075, f"Chr{ch}",
|
| 543 |
+
ha='center', va='center', fontsize=6,
|
| 544 |
+
color=col, fontweight='bold',
|
| 545 |
+
rotation=np.degrees(mid_angle) - 90 if mid_angle < np.pi else np.degrees(mid_angle) + 90)
|
| 546 |
+
|
| 547 |
+
# Draw model rings (inner to outer)
|
| 548 |
+
model_names = list(all_results.keys())
|
| 549 |
+
n_models = len(model_names)
|
| 550 |
+
ring_inner = 0.25
|
| 551 |
+
ring_width = (outer_r - 0.05 - ring_inner) / max(n_models, 1)
|
| 552 |
+
|
| 553 |
+
sig_line = -np.log10(5e-8)
|
| 554 |
+
|
| 555 |
+
for midx, mname in enumerate(model_names):
|
| 556 |
+
pvals, _ = all_results[mname]
|
| 557 |
+
log_p = -np.log10(np.clip(pvals, 1e-300, 1))
|
| 558 |
+
r_base = ring_inner + midx * ring_width
|
| 559 |
+
r_max_data = ring_width * 0.85
|
| 560 |
+
|
| 561 |
+
col = MODEL_COLORS.get(mname, CHR_PALETTE[midx % len(CHR_PALETTE)])
|
| 562 |
+
|
| 563 |
+
# Normalize log_p to ring height
|
| 564 |
+
max_lp = max(log_p.max(), sig_line, 1)
|
| 565 |
+
lp_norm = log_p[sort_idx] / max_lp * r_max_data
|
| 566 |
+
|
| 567 |
+
# Draw thin baseline arc
|
| 568 |
+
ax.plot(angles_sorted, np.full_like(angles_sorted, r_base),
|
| 569 |
+
color=col, alpha=0.15, lw=0.5)
|
| 570 |
+
|
| 571 |
+
# Scatter points
|
| 572 |
+
ax.scatter(angles_sorted, r_base + lp_norm,
|
| 573 |
+
c=col, s=4, alpha=0.6, linewidths=0)
|
| 574 |
+
|
| 575 |
+
# Golden dots for significant MTAs
|
| 576 |
+
sig_mask = log_p[sort_idx] >= sig_line
|
| 577 |
+
if sig_mask.any():
|
| 578 |
+
ax.scatter(angles_sorted[sig_mask], r_base + lp_norm[sig_mask],
|
| 579 |
+
c=SIG_COLOR, s=40, zorder=10, marker='o',
|
| 580 |
+
edgecolors='#FFFBEB', linewidth=0.8, alpha=0.95)
|
| 581 |
+
|
| 582 |
+
# Ring label
|
| 583 |
+
ax.text(0, r_base + r_max_data / 2, mname,
|
| 584 |
+
ha='center', va='center', fontsize=7,
|
| 585 |
+
color=col, fontweight='bold', alpha=0.9)
|
| 586 |
+
|
| 587 |
+
# Center circle decoration
|
| 588 |
+
circle = plt.Circle((0, 0), ring_inner - 0.02, transform=ax.transData._b,
|
| 589 |
+
color=PANEL_MID, zorder=5)
|
| 590 |
+
ax.text(0, 0, "GWAS\nCircos\nComparison", ha='center', va='center',
|
| 591 |
+
fontsize=9, color=TEXT_MAIN, fontweight='bold', zorder=6)
|
| 592 |
+
|
| 593 |
+
# Legend
|
| 594 |
+
legend_elements = [mpatches.Patch(facecolor=MODEL_COLORS.get(m, ACCENT_BLUE),
|
| 595 |
+
label=m, alpha=0.8) for m in model_names]
|
| 596 |
+
legend_elements.append(mpatches.Patch(facecolor=SIG_COLOR, label="Sig. MTA (β)", alpha=0.9))
|
| 597 |
+
ax.legend(handles=legend_elements, loc='lower center',
|
| 598 |
+
bbox_to_anchor=(0.5, -0.08), ncol=min(5, n_models+1),
|
| 599 |
+
fontsize=7, framealpha=0.2, facecolor=PANEL_MID,
|
| 600 |
+
edgecolor=GRID_LINE, labelcolor=TEXT_MAIN)
|
| 601 |
+
|
| 602 |
+
ax.set_title("Circos Plot β Multi-Model GWAS Comparison\n(Ring height = -logββ(p) | β = Significant MTA)",
|
| 603 |
+
color=TEXT_MAIN, fontsize=12, pad=20)
|
| 604 |
+
fig.tight_layout()
|
| 605 |
+
return fig
|
| 606 |
+
|
| 607 |
+
# βββββββββββββββββββββββββββ LD DECAY (BP + MB SEPARATE PLOTS) ββββββββββββββββββ
|
| 608 |
+
|
| 609 |
+
def plot_ld_decay_bpMb(G, positions):
|
| 610 |
+
"""
|
| 611 |
+
Separate LD decay plots in Base Pairs (bp) and Megabases (Mb).
|
| 612 |
+
Includes binned mean rΒ² curve and half-decay annotation.
|
| 613 |
+
"""
|
| 614 |
+
fig, axes = plt.subplots(1, 2, figsize=(16, 6))
|
| 615 |
+
style_fig(fig)
|
| 616 |
+
|
| 617 |
+
m = G.shape[1]
|
| 618 |
+
dists_bp, r2s = [], []
|
| 619 |
+
n_pairs = min(50, m)
|
| 620 |
+
for i in range(n_pairs):
|
| 621 |
+
for j in range(i+1, n_pairs):
|
| 622 |
+
xi, xj = G[:, i], G[:, j]
|
| 623 |
+
mask = ~(np.isnan(xi) | np.isnan(xj))
|
| 624 |
+
if mask.sum() < 4: continue
|
| 625 |
+
r, _ = stats.pearsonr(xi[mask], xj[mask])
|
| 626 |
+
d = abs(positions[j] - positions[i])
|
| 627 |
+
dists_bp.append(d)
|
| 628 |
+
r2s.append(r**2)
|
| 629 |
+
|
| 630 |
+
if len(dists_bp) == 0:
|
| 631 |
+
for ax in axes:
|
| 632 |
+
ax.text(0.5, 0.5, "Insufficient data for LD decay", ha='center',
|
| 633 |
+
transform=ax.transAxes, color=TEXT_DIM)
|
| 634 |
+
fig.tight_layout()
|
| 635 |
+
return fig
|
| 636 |
+
|
| 637 |
+
dists_bp = np.array(dists_bp)
|
| 638 |
+
dists_mb = dists_bp / 1_000_000
|
| 639 |
+
r2s = np.array(r2s)
|
| 640 |
+
|
| 641 |
+
def bin_ld(dists, r2s, n_bins=20):
|
| 642 |
+
bins = np.percentile(dists, np.linspace(0, 100, n_bins + 1))
|
| 643 |
+
centers, means, sems = [], [], []
|
| 644 |
+
for k in range(len(bins)-1):
|
| 645 |
+
mask = (dists >= bins[k]) & (dists < bins[k+1])
|
| 646 |
+
if mask.sum() > 2:
|
| 647 |
+
centers.append((bins[k] + bins[k+1]) / 2)
|
| 648 |
+
means.append(np.mean(r2s[mask]))
|
| 649 |
+
sems.append(stats.sem(r2s[mask]))
|
| 650 |
+
return np.array(centers), np.array(means), np.array(sems)
|
| 651 |
+
|
| 652 |
+
# ββ Panel 1: Base Pairs ββ
|
| 653 |
+
ax = axes[0]
|
| 654 |
+
ax.scatter(dists_bp, r2s, c=ACCENT_TEAL, s=12, alpha=0.35, linewidths=0)
|
| 655 |
+
bc, bm, bs = bin_ld(dists_bp, r2s)
|
| 656 |
+
ax.plot(bc, bm, color=ACCENT_CORAL, lw=2.5, marker='o', ms=5, zorder=5, label="Binned mean rΒ²")
|
| 657 |
+
ax.fill_between(bc, bm - bs, bm + bs, alpha=0.2, color=ACCENT_CORAL)
|
| 658 |
+
ax.axhline(0.5, color=ACCENT_GOLD, ls='--', lw=1.5, alpha=0.8, label="rΒ² = 0.5 (half-decay)")
|
| 659 |
+
ax.axhline(0.2, color=ACCENT_PURP, ls=':', lw=1.2, alpha=0.7, label="rΒ² = 0.2")
|
| 660 |
+
# Annotate half-decay distance
|
| 661 |
+
if len(bc) > 0 and bm[0] > 0.5:
|
| 662 |
+
try:
|
| 663 |
+
cross_idx = np.where(bm <= 0.5)[0]
|
| 664 |
+
if len(cross_idx) > 0:
|
| 665 |
+
half_d = bc[cross_idx[0]]
|
| 666 |
+
ax.axvline(half_d, color=ACCENT_GOLD, ls='--', lw=1, alpha=0.6)
|
| 667 |
+
ax.text(half_d, 0.55, f"~{half_d:.0f} bp", color=ACCENT_GOLD, fontsize=8, ha='left')
|
| 668 |
+
except: pass
|
| 669 |
+
ax.set_xlabel("Distance (bp)", fontsize=9)
|
| 670 |
+
ax.set_ylabel("rΒ² (LD)", fontsize=9)
|
| 671 |
+
ax.set_title("LD Decay β Base Pairs (bp)", color=TEXT_MAIN, fontsize=11)
|
| 672 |
+
ax.legend(fontsize=7, framealpha=0.2, facecolor=PANEL_MID, edgecolor=GRID_LINE, labelcolor=TEXT_MAIN)
|
| 673 |
+
ax.set_ylim(0, 1.05)
|
| 674 |
+
|
| 675 |
+
# ββ Panel 2: Megabases ββ
|
| 676 |
+
ax2 = axes[1]
|
| 677 |
+
ax2.scatter(dists_mb, r2s, c=ACCENT_PURP, s=12, alpha=0.35, linewidths=0)
|
| 678 |
+
bc2, bm2, bs2 = bin_ld(dists_mb, r2s)
|
| 679 |
+
ax2.plot(bc2, bm2, color=ACCENT_GOLD, lw=2.5, marker='o', ms=5, zorder=5, label="Binned mean rΒ²")
|
| 680 |
+
ax2.fill_between(bc2, bm2 - bs2, bm2 + bs2, alpha=0.2, color=ACCENT_GOLD)
|
| 681 |
+
ax2.axhline(0.5, color=ACCENT_CORAL, ls='--', lw=1.5, alpha=0.8, label="rΒ² = 0.5 (half-decay)")
|
| 682 |
+
ax2.axhline(0.2, color=ACCENT_TEAL, ls=':', lw=1.2, alpha=0.7, label="rΒ² = 0.2")
|
| 683 |
+
if len(bc2) > 0 and bm2[0] > 0.5:
|
| 684 |
+
try:
|
| 685 |
+
cross_idx = np.where(bm2 <= 0.5)[0]
|
| 686 |
+
if len(cross_idx) > 0:
|
| 687 |
+
half_d = bc2[cross_idx[0]]
|
| 688 |
+
ax2.axvline(half_d, color=ACCENT_CORAL, ls='--', lw=1, alpha=0.6)
|
| 689 |
+
ax2.text(half_d, 0.55, f"~{half_d:.4f} Mb", color=ACCENT_CORAL, fontsize=8, ha='left')
|
| 690 |
+
except: pass
|
| 691 |
+
ax2.set_xlabel("Distance (Mb)", fontsize=9)
|
| 692 |
+
ax2.set_ylabel("rΒ² (LD)", fontsize=9)
|
| 693 |
+
ax2.set_title("LD Decay β Megabases (Mb)", color=TEXT_MAIN, fontsize=11)
|
| 694 |
+
ax2.legend(fontsize=7, framealpha=0.2, facecolor=PANEL_MID, edgecolor=GRID_LINE, labelcolor=TEXT_MAIN)
|
| 695 |
+
ax2.set_ylim(0, 1.05)
|
| 696 |
+
|
| 697 |
+
fig.suptitle("Linkage Disequilibrium (LD) Decay Analysis", color=TEXT_MAIN, fontsize=13)
|
| 698 |
+
fig.tight_layout()
|
| 699 |
+
return fig
|
| 700 |
+
|
| 701 |
+
# βββββββββββββββββββββββββββ ALL OTHER PLOTS ββββββββββββββββββββββββββββββββββββββ
|
| 702 |
|
| 703 |
def plot_qq(pvals, title="QQ Plot"):
|
| 704 |
fig, ax = plt.subplots(figsize=(6, 6))
|
|
|
|
| 706 |
n = len(pvals)
|
| 707 |
obs = np.sort(-np.log10(np.clip(pvals, 1e-300, 1)))[::-1]
|
| 708 |
exp = -np.log10(np.linspace(1/n, 1, n)[::-1])
|
| 709 |
+
ci_lower = -np.log10(stats.beta.ppf(0.975, np.arange(1,n+1), np.arange(n,0,-1)))
|
| 710 |
+
ci_upper = -np.log10(stats.beta.ppf(0.025, np.arange(1,n+1), np.arange(n,0,-1)))
|
| 711 |
+
ax.fill_between(exp, ci_lower, ci_upper, alpha=0.2, color=ACCENT_TEAL, label="95% CI")
|
| 712 |
+
ax.scatter(exp, obs, c=ACCENT_PURP, s=20, alpha=0.8)
|
| 713 |
+
ax.plot([0, max(exp)], [0, max(exp)], color=ACCENT_CORAL, ls="--", lw=1.5)
|
|
|
|
|
|
|
| 714 |
lam = np.median(stats.chi2.ppf(1 - pvals, df=1)) / stats.chi2.ppf(0.5, df=1)
|
| 715 |
+
ax.text(0.05, 0.92, f"Ξ» = {lam:.4f}", transform=ax.transAxes, fontsize=11, color=ACCENT_GOLD)
|
| 716 |
+
ax.set_xlabel("Expected -logββ(p)"); ax.set_ylabel("Observed -logββ(p)")
|
|
|
|
| 717 |
ax.set_title(title)
|
| 718 |
fig.tight_layout()
|
| 719 |
return fig
|
|
|
|
| 721 |
def plot_pca(G, y, ids):
|
| 722 |
fig, axes = plt.subplots(2, 2, figsize=(14, 12))
|
| 723 |
style_fig(fig)
|
| 724 |
+
G_sc = StandardScaler().fit_transform(G)
|
|
|
|
|
|
|
| 725 |
n_comp = min(5, G_sc.shape[0]-1, G_sc.shape[1])
|
| 726 |
pca = PCA(n_components=n_comp)
|
| 727 |
pcs = pca.fit_transform(G_sc)
|
| 728 |
var_exp = pca.explained_variance_ratio_ * 100
|
| 729 |
+
sc = axes[0,0].scatter(pcs[:,0], pcs[:,1], c=y, cmap='plasma', s=60, edgecolors='none')
|
| 730 |
+
axes[0,0].set_xlabel(f"PC1 ({var_exp[0]:.1f}%)"); axes[0,0].set_ylabel(f"PC2 ({var_exp[1]:.1f}%)")
|
| 731 |
+
axes[0,0].set_title("PCA: PC1 vs PC2"); plt.colorbar(sc, ax=axes[0,0], label="Phenotype")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 732 |
if n_comp >= 4:
|
| 733 |
+
axes[0,1].scatter(pcs[:,2], pcs[:,3], c=y, cmap='plasma', s=60, edgecolors='none')
|
| 734 |
+
axes[0,1].set_xlabel(f"PC3 ({var_exp[2]:.1f}%)"); axes[0,1].set_ylabel(f"PC4 ({var_exp[3]:.1f}%)")
|
|
|
|
| 735 |
axes[0,1].set_title("PCA: PC3 vs PC4")
|
| 736 |
else:
|
| 737 |
+
axes[0,1].text(0.5, 0.5, "< 4 PCs available", ha='center', transform=axes[0,1].transAxes, color=TEXT_DIM)
|
| 738 |
+
axes[1,0].bar(range(1, n_comp+1), var_exp, color=ACCENT_TEAL, edgecolor='none', alpha=0.8)
|
| 739 |
+
axes[1,0].plot(range(1, n_comp+1), np.cumsum(var_exp), color=ACCENT_CORAL, marker='o', lw=2)
|
| 740 |
+
axes[1,0].set_xlabel("Principal Component"); axes[1,0].set_ylabel("Variance Explained (%)")
|
|
|
|
|
|
|
| 741 |
axes[1,0].set_title("Scree Plot")
|
| 742 |
+
axes[1,1].scatter(pcs[:,0], pcs[:,1], c=y, cmap='plasma', s=60, edgecolors='none')
|
| 743 |
+
axes[1,1].set_title("Population Structure (PC1 vs PC2)")
|
| 744 |
+
fig.tight_layout(); return fig
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 745 |
|
| 746 |
def plot_phenotype_distribution(y, ids):
|
| 747 |
fig, axes = plt.subplots(2, 2, figsize=(14, 10))
|
| 748 |
style_fig(fig)
|
| 749 |
+
axes[0,0].hist(y, bins=15, color=ACCENT_PURP, edgecolor='none', alpha=0.8)
|
| 750 |
+
axes[0,0].axvline(y.mean(), color=ACCENT_CORAL, lw=2, ls='--', label=f"Mean: {y.mean():.2f}")
|
| 751 |
+
axes[0,0].axvline(y.mean()+y.std(), color=ACCENT_GOLD, lw=1.5, ls=':', label="Β±1 SD")
|
| 752 |
+
axes[0,0].axvline(y.mean()-y.std(), color=ACCENT_GOLD, lw=1.5, ls=':')
|
| 753 |
+
axes[0,0].set_title("Phenotype Distribution"); axes[0,0].legend(fontsize=7)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 754 |
bp = axes[0,1].boxplot(y, vert=True, patch_artist=True)
|
| 755 |
+
for patch in bp['boxes']: patch.set_facecolor(ACCENT_TEAL); patch.set_edgecolor(ACCENT_CORAL)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 756 |
axes[0,1].set_title("Box Plot")
|
|
|
|
| 757 |
stats.probplot(y, dist="norm", plot=axes[1,0])
|
| 758 |
axes[1,0].set_title("Normal Q-Q Plot")
|
| 759 |
+
axes[1,0].get_lines()[0].set_color(ACCENT_PURP)
|
| 760 |
+
axes[1,0].get_lines()[1].set_color(ACCENT_CORAL)
|
| 761 |
+
axes[1,1].hist(y, bins=15, density=True, color=ACCENT_PURP, alpha=0.7, edgecolor='none')
|
| 762 |
+
x_d = np.linspace(y.min(), y.max(), 100)
|
| 763 |
+
axes[1,1].plot(x_d, stats.gaussian_kde(y)(x_d), color=ACCENT_CORAL, lw=2)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 764 |
axes[1,1].set_title("Density Plot")
|
| 765 |
+
fig.tight_layout(); return fig
|
|
|
|
|
|
|
| 766 |
|
| 767 |
def plot_maf_analysis(maf, snp_names):
|
| 768 |
fig, axes = plt.subplots(2, 2, figsize=(14, 10))
|
| 769 |
style_fig(fig)
|
| 770 |
+
axes[0,0].hist(maf, bins=20, color=ACCENT_TEAL, edgecolor='none')
|
| 771 |
+
axes[0,0].axvline(0.05, color=ACCENT_CORAL, ls='--', lw=2, label="MAF=0.05")
|
| 772 |
+
axes[0,0].set_title("MAF Distribution"); axes[0,0].legend(fontsize=7)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 773 |
order = np.argsort(maf)[::-1]
|
| 774 |
+
colors = [ACCENT_TEAL if m >= 0.05 else ACCENT_PURP for m in maf[order]]
|
| 775 |
axes[0,1].bar(range(min(50, len(maf))), maf[order][:50], color=colors[:50])
|
| 776 |
+
axes[0,1].axhline(0.05, color=ACCENT_CORAL, ls='--', lw=1.5)
|
|
|
|
|
|
|
| 777 |
axes[0,1].set_title("Top 50 SNPs by MAF")
|
|
|
|
| 778 |
rare_mask = maf < 0.05
|
| 779 |
+
axes[1,0].pie([rare_mask.sum(), (~rare_mask).sum()],
|
| 780 |
+
labels=[f"Rare (<0.05): {rare_mask.sum()}", f"Common: {(~rare_mask).sum()}"],
|
| 781 |
+
colors=[ACCENT_CORAL, ACCENT_TEAL], autopct='%1.1f%%', textprops={'color': TEXT_MAIN})
|
| 782 |
axes[1,0].set_title("Rare vs Common Variants")
|
| 783 |
+
axes[1,1].text(0.5, 0.5,
|
| 784 |
+
f"MAF Summary\n\nMean: {np.mean(maf):.4f}\nMedian: {np.median(maf):.4f}\nMin: {np.min(maf):.4f}\nMax: {np.max(maf):.4f}",
|
| 785 |
+
ha='center', va='center', transform=axes[1,1].transAxes, color=TEXT_MAIN, fontsize=11)
|
| 786 |
+
axes[1,1].set_title("MAF Statistics")
|
| 787 |
+
fig.tight_layout(); return fig
|
|
|
|
|
|
|
| 788 |
|
| 789 |
+
def plot_ld_analysis_heatmap(G, positions, chroms):
|
| 790 |
+
"""LD heatmap + rΒ² histogram + LD scatter"""
|
| 791 |
fig, axes = plt.subplots(2, 2, figsize=(14, 12))
|
| 792 |
style_fig(fig)
|
|
|
|
| 793 |
m = G.shape[1]
|
| 794 |
dists, r2s = [], []
|
| 795 |
+
pairs = [(i,j) for i in range(min(50,m)) for j in range(i+1, min(50,m))]
|
| 796 |
+
for i, j in pairs:
|
| 797 |
+
xi, xj = G[:,i], G[:,j]
|
| 798 |
+
mask = ~(np.isnan(xi)|np.isnan(xj))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 799 |
if mask.sum() >= 4:
|
| 800 |
r, _ = stats.pearsonr(xi[mask], xj[mask])
|
| 801 |
+
d = abs(positions[j]-positions[i])
|
| 802 |
+
dists.append(d); r2s.append(r**2)
|
| 803 |
+
if dists:
|
| 804 |
+
axes[0,0].scatter(np.array(dists)/1000, r2s, alpha=0.4, s=12, color=ACCENT_TEAL, linewidths=0)
|
| 805 |
+
axes[0,0].set_xlabel("Distance (kb)"); axes[0,0].set_ylabel("rΒ²")
|
| 806 |
+
axes[0,0].set_title("LD Decay (kb)")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 807 |
m_sub = min(30, m)
|
| 808 |
+
R = np.eye(m_sub)
|
| 809 |
for i in range(m_sub):
|
| 810 |
+
for j in range(i+1, m_sub):
|
| 811 |
+
xi, xj = G[:,i], G[:,j]
|
| 812 |
+
mask = ~(np.isnan(xi)|np.isnan(xj))
|
| 813 |
+
if mask.sum() >= 3:
|
| 814 |
+
r, _ = stats.pearsonr(xi[mask], xj[mask])
|
| 815 |
+
R[i,j] = R[j,i] = r**2
|
| 816 |
+
im = axes[0,1].imshow(R, cmap='hot', vmin=0, vmax=1, aspect='auto')
|
| 817 |
+
axes[0,1].set_title("LD Heatmap (rΒ², first 30 SNPs)")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 818 |
plt.colorbar(im, ax=axes[0,1], label="rΒ²")
|
| 819 |
+
if r2s:
|
| 820 |
+
axes[1,0].hist(r2s, bins=20, color=ACCENT_PURP, edgecolor='none')
|
| 821 |
+
axes[1,0].set_xlabel("rΒ²"); axes[1,0].set_ylabel("Frequency")
|
| 822 |
+
axes[1,0].set_title("rΒ² Distribution")
|
| 823 |
+
if dists:
|
| 824 |
+
axes[1,1].scatter(np.array(dists), r2s, alpha=0.3, s=10, color=ACCENT_GOLD, linewidths=0)
|
| 825 |
+
axes[1,1].set_xlabel("Distance (bp)"); axes[1,1].set_ylabel("rΒ²")
|
| 826 |
+
axes[1,1].set_title("LD vs Distance (bp)")
|
| 827 |
+
axes[1,1].set_ylim(0,1)
|
| 828 |
+
fig.tight_layout(); return fig
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 829 |
|
| 830 |
def plot_effect_sizes(pvals, betas, snp_names):
|
| 831 |
fig, axes = plt.subplots(2, 2, figsize=(14, 10))
|
| 832 |
style_fig(fig)
|
|
|
|
| 833 |
top_idx = np.argsort(np.abs(betas))[-20:]
|
| 834 |
top_betas = betas[top_idx]
|
| 835 |
top_names = [snp_names[i][:15] for i in top_idx]
|
| 836 |
+
colors = [ACCENT_CORAL if b < 0 else ACCENT_TEAL for b in top_betas]
|
|
|
|
| 837 |
axes[0,0].barh(range(len(top_betas)), top_betas, color=colors)
|
| 838 |
+
axes[0,0].axvline(0, color=TEXT_DIM, lw=0.7)
|
| 839 |
+
axes[0,0].set_yticks(range(len(top_betas))); axes[0,0].set_yticklabels(top_names, fontsize=7)
|
| 840 |
+
axes[0,0].set_xlabel("Effect Size (Ξ²)"); axes[0,0].set_title("Top 20 Effect Sizes")
|
|
|
|
|
|
|
|
|
|
| 841 |
log_p = -np.log10(np.clip(pvals, 1e-300, 1))
|
| 842 |
sig_thr = -np.log10(0.05/len(pvals))
|
| 843 |
+
colors_v = np.where(log_p >= sig_thr, SIG_COLOR, np.where(betas > 0, ACCENT_TEAL, ACCENT_PURP))
|
| 844 |
+
axes[0,1].scatter(betas, log_p, c=colors_v, s=25, alpha=0.7, linewidths=0)
|
| 845 |
+
axes[0,1].axhline(sig_thr, color=ACCENT_CORAL, ls='--', lw=1.5, label="Bonferroni")
|
| 846 |
+
axes[0,1].axvline(0, color=TEXT_DIM, lw=0.5)
|
| 847 |
+
axes[0,1].set_xlabel("Ξ²"); axes[0,1].set_ylabel("-logββ(p)")
|
| 848 |
+
axes[0,1].set_title("Volcano Plot"); axes[0,1].legend(fontsize=7)
|
| 849 |
+
axes[1,0].hist(betas, bins=30, color=ACCENT_TEAL, edgecolor='none')
|
| 850 |
+
axes[1,0].axvline(0, color=ACCENT_CORAL, lw=2, ls='--')
|
| 851 |
+
axes[1,0].set_xlabel("Ξ²"); axes[1,0].set_title("Effect Size Distribution")
|
| 852 |
+
axes[1,1].scatter(betas, log_p, c=colors_v, s=20, alpha=0.6, linewidths=0)
|
| 853 |
+
axes[1,1].set_xlabel("Ξ²"); axes[1,1].set_ylabel("-logββ(p)")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 854 |
axes[1,1].set_title("Effect Size vs Significance")
|
| 855 |
+
fig.tight_layout(); return fig
|
|
|
|
|
|
|
| 856 |
|
| 857 |
def plot_heterozygosity(G, y, ids):
|
| 858 |
fig, axes = plt.subplots(2, 2, figsize=(14, 10))
|
| 859 |
style_fig(fig)
|
|
|
|
| 860 |
het = compute_heterozygosity(G)
|
| 861 |
+
axes[0,0].hist(het, bins=20, color=ACCENT_PURP, edgecolor='none')
|
|
|
|
|
|
|
|
|
|
| 862 |
axes[0,0].set_title("Individual Heterozygosity")
|
| 863 |
+
axes[0,1].scatter(het, y, c=ACCENT_TEAL, s=50, alpha=0.7, linewidths=0)
|
| 864 |
+
axes[0,1].set_xlabel("Heterozygosity"); axes[0,1].set_ylabel("Phenotype")
|
|
|
|
|
|
|
| 865 |
axes[0,1].set_title("Heterozygosity vs Phenotype")
|
|
|
|
| 866 |
top_idx = np.argsort(het)[-10:]
|
| 867 |
+
axes[1,0].barh(range(len(top_idx)), het[top_idx], color=ACCENT_CORAL)
|
| 868 |
axes[1,0].set_yticks(range(len(top_idx)))
|
| 869 |
axes[1,0].set_yticklabels([ids[i][:10] for i in top_idx], fontsize=8)
|
| 870 |
+
axes[1,0].set_title("Top 10 Most Heterozygous")
|
|
|
|
|
|
|
| 871 |
median_y = np.median(y)
|
| 872 |
+
bp = axes[1,1].boxplot([het[y <= median_y], het[y > median_y]],
|
| 873 |
+
labels=['Low Pheno', 'High Pheno'], patch_artist=True)
|
| 874 |
+
for patch, c in zip(bp['boxes'], [ACCENT_TEAL, ACCENT_CORAL]):
|
| 875 |
+
patch.set_facecolor(c)
|
| 876 |
axes[1,1].set_title("Heterozygosity by Phenotype Group")
|
| 877 |
+
fig.tight_layout(); return fig
|
|
|
|
|
|
|
| 878 |
|
| 879 |
def plot_call_rate_analysis(G, snp_names):
|
| 880 |
fig, axes = plt.subplots(2, 2, figsize=(14, 10))
|
| 881 |
style_fig(fig)
|
| 882 |
+
cr = compute_call_rate(G)
|
| 883 |
+
axes[0,0].hist(cr, bins=20, color=ACCENT_TEAL, edgecolor='none')
|
| 884 |
+
axes[0,0].axvline(0.95, color=ACCENT_CORAL, ls='--', lw=2, label="95% threshold")
|
| 885 |
+
axes[0,0].set_title("SNP Call Rate Distribution"); axes[0,0].legend(fontsize=7)
|
| 886 |
+
order = np.argsort(cr)
|
| 887 |
+
axes[0,1].plot(cr[order], color=ACCENT_PURP, lw=1)
|
| 888 |
+
axes[0,1].axhline(0.95, color=ACCENT_CORAL, ls='--', lw=1.5)
|
| 889 |
+
axes[0,1].fill_between(range(len(cr)), 0, cr[order], alpha=0.2, color=ACCENT_TEAL)
|
| 890 |
+
axes[0,1].set_title("Call Rate by SNP (sorted)")
|
| 891 |
+
low_cr = cr < 0.95
|
| 892 |
+
axes[1,0].pie([low_cr.sum(), (~low_cr).sum()],
|
| 893 |
+
labels=[f"Low CR: {low_cr.sum()}", f"Good CR: {(~low_cr).sum()}"],
|
| 894 |
+
colors=[ACCENT_CORAL, ACCENT_TEAL], autopct='%1.1f%%', textprops={'color': TEXT_MAIN})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 895 |
axes[1,0].set_title("SNP Quality")
|
| 896 |
+
axes[1,1].text(0.5, 0.5,
|
| 897 |
+
f"Call Rate Summary\n\nMean: {np.mean(cr):.4f}\nMedian: {np.median(cr):.4f}\nMin: {np.min(cr):.4f}\nSNPs with CR>95%: {(~low_cr).sum()}",
|
| 898 |
+
ha='center', va='center', transform=axes[1,1].transAxes, color=TEXT_MAIN, fontsize=11)
|
| 899 |
+
axes[1,1].set_title("Summary Statistics")
|
| 900 |
+
fig.tight_layout(); return fig
|
|
|
|
|
|
|
| 901 |
|
| 902 |
def plot_kinship_analysis(K, ids):
|
| 903 |
fig, axes = plt.subplots(2, 2, figsize=(14, 12))
|
| 904 |
style_fig(fig)
|
| 905 |
+
im = axes[0,0].imshow(K, cmap='RdYlBu_r', aspect='auto', vmin=-0.5, vmax=1)
|
| 906 |
+
axes[0,0].set_title("Kinship Matrix"); plt.colorbar(im, ax=axes[0,0])
|
|
|
|
|
|
|
|
|
|
| 907 |
K_flat = K[np.triu_indices_from(K, k=1)]
|
| 908 |
+
axes[0,1].hist(K_flat, bins=30, color=ACCENT_PURP, edgecolor='none')
|
|
|
|
|
|
|
| 909 |
axes[0,1].set_title("Pairwise Kinship Distribution")
|
| 910 |
+
try:
|
| 911 |
+
lm = linkage(K, method='average')
|
| 912 |
+
dendrogram(lm, ax=axes[1,0], labels=ids, leaf_rotation=90, leaf_font_size=7,
|
| 913 |
+
color_threshold=0.7, above_threshold_color=ACCENT_TEAL)
|
| 914 |
+
except: axes[1,0].text(0.5, 0.5, "Dendrogram failed", ha='center', transform=axes[1,0].transAxes)
|
| 915 |
axes[1,0].set_title("Sample Clustering Dendrogram")
|
|
|
|
|
|
|
| 916 |
eigvals, eigvecs = np.linalg.eigh(K)
|
| 917 |
idx = np.argsort(eigvals)[::-1]
|
| 918 |
+
axes[1,1].scatter(eigvecs[:,idx[0]], eigvecs[:,idx[1]], c=ACCENT_TEAL, s=60, edgecolors='none')
|
|
|
|
|
|
|
| 919 |
axes[1,1].set_title("Kinship PCA")
|
| 920 |
+
fig.tight_layout(); return fig
|
|
|
|
|
|
|
| 921 |
|
| 922 |
def plot_mds_analysis(G, y, ids):
|
| 923 |
fig, axes = plt.subplots(1, 2, figsize=(14, 6))
|
| 924 |
style_fig(fig)
|
|
|
|
| 925 |
try:
|
| 926 |
mds = MDS(n_components=2, random_state=42, normalized_stress='auto')
|
| 927 |
+
mds_c = mds.fit_transform(G)
|
| 928 |
+
sc = axes[0].scatter(mds_c[:,0], mds_c[:,1], c=y, cmap='plasma', s=60, edgecolors='none')
|
| 929 |
+
axes[0].set_title("MDS"); plt.colorbar(sc, ax=axes[0], label="Phenotype")
|
| 930 |
+
perp = min(30, len(G)-1)
|
| 931 |
+
tsne_c = TSNE(n_components=2, random_state=42, perplexity=perp).fit_transform(G)
|
| 932 |
+
sc2 = axes[1].scatter(tsne_c[:,0], tsne_c[:,1], c=y, cmap='plasma', s=60, edgecolors='none')
|
| 933 |
+
axes[1].set_title("t-SNE"); plt.colorbar(sc2, ax=axes[1], label="Phenotype")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 934 |
except Exception as e:
|
| 935 |
+
for ax in axes: ax.text(0.5, 0.5, str(e)[:40], ha='center', transform=ax.transAxes, color=TEXT_DIM)
|
| 936 |
+
fig.tight_layout(); return fig
|
|
|
|
|
|
|
|
|
|
| 937 |
|
| 938 |
def plot_manhattan_by_chromosome(pvals, chroms, positions):
|
| 939 |
fig, axes = plt.subplots(2, 3, figsize=(15, 10))
|
| 940 |
style_fig(fig)
|
| 941 |
axes = axes.flatten()
|
|
|
|
| 942 |
log_p = -np.log10(np.clip(pvals, 1e-300, 1))
|
| 943 |
unique_chroms = sorted(set(chroms))
|
|
|
|
| 944 |
for i, ch in enumerate(unique_chroms[:6]):
|
| 945 |
mask = chroms == ch
|
| 946 |
if mask.sum() > 0:
|
| 947 |
+
col = CHR_PALETTE[unique_chroms.index(ch) % len(CHR_PALETTE)]
|
| 948 |
+
axes[i].scatter(positions[mask], log_p[mask], c=col, s=12, alpha=0.7, linewidths=0)
|
| 949 |
+
axes[i].axhline(-np.log10(5e-8), color=ACCENT_CORAL, ls='--', lw=1)
|
| 950 |
+
sig_m = log_p[mask] >= -np.log10(5e-8)
|
| 951 |
+
if sig_m.any():
|
| 952 |
+
axes[i].scatter(positions[mask][sig_m], log_p[mask][sig_m],
|
| 953 |
+
c=SIG_COLOR, s=60, zorder=10, linewidths=0)
|
| 954 |
+
axes[i].set_title(f"Chr {ch}")
|
| 955 |
for i in range(len(unique_chroms), 6):
|
| 956 |
axes[i].set_visible(False)
|
| 957 |
+
fig.tight_layout(); return fig
|
|
|
|
|
|
|
| 958 |
|
| 959 |
def plot_manhattan_qq_combined(pvals, chroms, positions):
|
| 960 |
fig = plt.figure(figsize=(14, 10))
|
| 961 |
style_fig(fig)
|
| 962 |
gs = fig.add_gridspec(2, 2, height_ratios=[2, 1])
|
|
|
|
| 963 |
ax1 = fig.add_subplot(gs[0, :])
|
| 964 |
log_p = -np.log10(np.clip(pvals, 1e-300, 1))
|
| 965 |
+
ax1.scatter(range(len(pvals)), log_p, c=ACCENT_TEAL, s=8, alpha=0.6, linewidths=0)
|
| 966 |
+
ax1.axhline(-np.log10(5e-8), color=ACCENT_CORAL, ls='--', lw=1.5, label="GW sig.")
|
| 967 |
+
sig_m = log_p >= -np.log10(5e-8)
|
| 968 |
+
if sig_m.any():
|
| 969 |
+
ax1.scatter(np.where(sig_m)[0], log_p[sig_m], c=SIG_COLOR, s=50, zorder=10, linewidths=0)
|
| 970 |
+
ax1.set_title("Manhattan Plot"); ax1.legend(fontsize=7)
|
|
|
|
| 971 |
ax2 = fig.add_subplot(gs[1, 0])
|
| 972 |
n = len(pvals)
|
| 973 |
obs = np.sort(-np.log10(np.clip(pvals, 1e-300, 1)))[::-1]
|
| 974 |
exp = -np.log10(np.linspace(1/n, 1, n)[::-1])
|
| 975 |
+
ax2.scatter(exp, obs, c=ACCENT_PURP, s=10, alpha=0.6, linewidths=0)
|
| 976 |
+
ax2.plot([0, max(exp)], [0, max(exp)], color=ACCENT_CORAL, ls='--', lw=1.5)
|
|
|
|
|
|
|
| 977 |
ax2.set_title("QQ Plot")
|
|
|
|
| 978 |
ax3 = fig.add_subplot(gs[1, 1])
|
| 979 |
+
ax3.hist(pvals, bins=50, color=ACCENT_TEAL, edgecolor='none')
|
| 980 |
+
ax3.axvline(0.05, color=ACCENT_CORAL, ls='--', lw=1.5)
|
|
|
|
|
|
|
| 981 |
ax3.set_title("P-value Distribution")
|
| 982 |
+
fig.tight_layout(); return fig
|
|
|
|
|
|
|
| 983 |
|
| 984 |
+
def plot_model_comparison_manhattan(all_results, chroms, positions):
|
| 985 |
+
"""Side-by-side Manhattan for all models"""
|
| 986 |
+
n_models = len(all_results)
|
| 987 |
+
fig, axes = plt.subplots(n_models, 1, figsize=(16, 3.5 * n_models), sharex=True)
|
| 988 |
style_fig(fig)
|
| 989 |
+
if n_models == 1:
|
| 990 |
+
axes = [axes]
|
| 991 |
+
for ax in fig.get_axes():
|
| 992 |
+
ax.set_facecolor(PANEL_DARK)
|
| 993 |
+
|
| 994 |
+
chrom_list = sorted(set(chroms))
|
| 995 |
+
total_len = 0
|
| 996 |
+
chrom_offsets = {}
|
| 997 |
+
for ch in chrom_list:
|
| 998 |
+
chrom_offsets[ch] = total_len
|
| 999 |
mask = chroms == ch
|
| 1000 |
if mask.sum() > 0:
|
| 1001 |
+
total_len += positions[mask].max() - positions[mask].min() + max(positions) * 0.02 + 1
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1002 |
|
| 1003 |
+
x_coords = np.zeros(len(chroms))
|
| 1004 |
+
for ch in chrom_list:
|
| 1005 |
+
mask = chroms == ch
|
| 1006 |
+
if mask.sum() > 0:
|
| 1007 |
+
x_coords[mask] = positions[mask] - positions[mask].min() + chrom_offsets[ch]
|
| 1008 |
+
|
| 1009 |
+
tick_pos = []
|
| 1010 |
+
tick_lab = []
|
| 1011 |
+
for ch in chrom_list:
|
| 1012 |
+
mask = chroms == ch
|
| 1013 |
+
if mask.sum() > 0:
|
| 1014 |
+
tick_pos.append(x_coords[mask].mean())
|
| 1015 |
+
tick_lab.append(f"Chr{ch}")
|
| 1016 |
+
|
| 1017 |
+
for midx, (mname, (pvals, _)) in enumerate(all_results.items()):
|
| 1018 |
+
ax = axes[midx]
|
| 1019 |
+
log_p = -np.log10(np.clip(pvals, 1e-300, 1))
|
| 1020 |
+
col = MODEL_COLORS.get(mname, CHR_PALETTE[midx % len(CHR_PALETTE)])
|
| 1021 |
+
for ch in chrom_list:
|
| 1022 |
+
mask = chroms == ch
|
| 1023 |
+
ax.scatter(x_coords[mask], log_p[mask], c=col, s=6, alpha=0.65, linewidths=0)
|
| 1024 |
+
sig_m = log_p >= -np.log10(5e-8)
|
| 1025 |
+
if sig_m.any():
|
| 1026 |
+
ax.scatter(x_coords[sig_m], log_p[sig_m], c=SIG_COLOR, s=45,
|
| 1027 |
+
zorder=10, linewidths=0.8, edgecolors='#FFFBEB')
|
| 1028 |
+
ax.axhline(-np.log10(5e-8), color=ACCENT_CORAL, ls='--', lw=1, alpha=0.7)
|
| 1029 |
+
ax.set_ylabel("-logββ(p)", fontsize=7, color=TEXT_DIM)
|
| 1030 |
+
ax.set_title(f"Model: {mname}", color=col, fontsize=9, pad=3)
|
| 1031 |
+
ax.set_xticks(tick_pos)
|
| 1032 |
+
ax.set_xticklabels(tick_lab if midx == n_models-1 else [], rotation=40, fontsize=7)
|
| 1033 |
+
ax.tick_params(colors=TEXT_DIM, labelsize=7)
|
| 1034 |
+
for spine in ax.spines.values(): spine.set_edgecolor(GRID_LINE)
|
| 1035 |
+
ax.grid(color=GRID_LINE, linewidth=0.3, linestyle="--", alpha=0.4)
|
| 1036 |
+
|
| 1037 |
+
fig.suptitle("Manhattan Plots β All Models Comparison", color=TEXT_MAIN, fontsize=13)
|
| 1038 |
+
fig.tight_layout(rect=[0, 0, 1, 0.98])
|
| 1039 |
return fig
|
| 1040 |
|
| 1041 |
+
def plot_summary_dashboard(y, maf, pvals, betas, G, all_results):
|
| 1042 |
fig, axes = plt.subplots(2, 3, figsize=(15, 10))
|
| 1043 |
style_fig(fig)
|
| 1044 |
axes = axes.flatten()
|
| 1045 |
+
axes[0].boxplot(y, patch_artist=True,
|
| 1046 |
+
boxprops={'facecolor': ACCENT_TEAL, 'edgecolor': ACCENT_CORAL})
|
| 1047 |
+
axes[0].set_title(f"Phenotype | n={len(y)} | ΞΌ={y.mean():.2f}")
|
| 1048 |
+
axes[1].hist(maf, bins=20, color=ACCENT_TEAL, edgecolor='none')
|
| 1049 |
+
axes[1].axvline(0.05, color=ACCENT_CORAL, ls='--')
|
| 1050 |
+
axes[1].set_title(f"MAF | rare={np.sum(maf<0.05)}")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1051 |
log_p = -np.log10(np.clip(pvals, 1e-300, 1))
|
| 1052 |
+
axes[2].hist(log_p, bins=30, color=ACCENT_PURP, edgecolor='none')
|
| 1053 |
+
axes[2].axvline(-np.log10(0.05/len(pvals)), color=ACCENT_CORAL, ls='--')
|
| 1054 |
+
axes[2].set_title(f"P-values | sig={np.sum(pvals < 0.05/len(pvals))}")
|
| 1055 |
+
axes[3].hist(betas, bins=30, color=ACCENT_ORG, edgecolor='none')
|
| 1056 |
+
axes[3].axvline(0, color=ACCENT_CORAL, ls='--')
|
| 1057 |
+
axes[3].set_title(f"Effect Sizes | ΞΌ={np.mean(betas):.4f}")
|
| 1058 |
+
# Lambda comparison bar chart
|
| 1059 |
+
lambdas = {}
|
| 1060 |
+
for mname, (p, _) in all_results.items():
|
| 1061 |
+
lam = np.median(stats.chi2.ppf(1-np.clip(p,1e-10,1), df=1)) / stats.chi2.ppf(0.5, df=1)
|
| 1062 |
+
lambdas[mname] = lam
|
| 1063 |
+
colors_lam = [ACCENT_TEAL if v <= 1.1 else ACCENT_GOLD if v <= 1.3 else ACCENT_CORAL for v in lambdas.values()]
|
| 1064 |
+
axes[4].bar(lambdas.keys(), lambdas.values(), color=colors_lam, edgecolor='none')
|
| 1065 |
+
axes[4].axhline(1.0, color=TEXT_DIM, ls='--', lw=1)
|
| 1066 |
+
axes[4].set_title("Genomic Inflation Ξ» per Model")
|
| 1067 |
+
axes[4].tick_params(axis='x', rotation=35, labelsize=7)
|
| 1068 |
+
lam0 = list(lambdas.values())[0]
|
| 1069 |
+
miss_r = np.isnan(G).mean()
|
| 1070 |
+
axes[5].text(0.5, 0.5,
|
| 1071 |
+
f"GWAS Summary\n\nSamples: {len(y)}\nSNPs: {G.shape[1]}\nModels: {len(all_results)}\nMissing data: {miss_r:.1%}\nPrimary Ξ»: {lam0:.3f}\nSignificant: {np.sum(pvals < 0.05/len(pvals))}",
|
| 1072 |
+
ha='center', va='center', transform=axes[5].transAxes, color=TEXT_MAIN, fontsize=10)
|
| 1073 |
+
axes[5].set_title("Pipeline Summary")
|
| 1074 |
+
fig.tight_layout(); return fig
|
| 1075 |
|
| 1076 |
+
def plot_gwas_interpretation_panel(all_results, pvals_primary, betas_primary, snp_filt, chroms, positions):
|
| 1077 |
+
"""Comprehensive interpretation: sig SNP table, effect distribution, p-value comparison"""
|
| 1078 |
+
fig, axes = plt.subplots(2, 2, figsize=(14, 10))
|
| 1079 |
style_fig(fig)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1080 |
|
| 1081 |
+
# Panel 1: Significant SNP count per model
|
| 1082 |
+
sig_counts = {}
|
| 1083 |
+
bonf = 0.05 / len(pvals_primary)
|
| 1084 |
+
for mname, (p, _) in all_results.items():
|
| 1085 |
+
sig_counts[mname] = (p < bonf).sum()
|
| 1086 |
+
cols_bar = [MODEL_COLORS.get(m, ACCENT_BLUE) for m in sig_counts.keys()]
|
| 1087 |
+
axes[0,0].bar(sig_counts.keys(), sig_counts.values(), color=cols_bar, edgecolor='none')
|
| 1088 |
+
axes[0,0].set_title("Significant SNP Count per Model")
|
| 1089 |
+
axes[0,0].tick_params(axis='x', rotation=35, labelsize=7)
|
| 1090 |
+
axes[0,0].set_ylabel("# Significant SNPs")
|
| 1091 |
+
|
| 1092 |
+
# Panel 2: -log10(p) distribution per model (violin-style via hist)
|
| 1093 |
+
log_ps = {m: -np.log10(np.clip(p, 1e-300, 1)) for m, (p, _) in all_results.items()}
|
| 1094 |
+
positions_viol = list(range(len(log_ps)))
|
| 1095 |
+
axes[0,1].violinplot([v for v in log_ps.values()], positions=positions_viol,
|
| 1096 |
+
showmedians=True, showextrema=True)
|
| 1097 |
+
axes[0,1].set_xticks(positions_viol)
|
| 1098 |
+
axes[0,1].set_xticklabels(list(log_ps.keys()), rotation=35, fontsize=7)
|
| 1099 |
+
axes[0,1].axhline(-np.log10(5e-8), color=ACCENT_CORAL, ls='--', lw=1.5, label="GW sig.")
|
| 1100 |
+
axes[0,1].set_title("βlogββ(p) Distribution per Model")
|
| 1101 |
+
axes[0,1].set_ylabel("βlogββ(p)"); axes[0,1].legend(fontsize=7)
|
| 1102 |
+
|
| 1103 |
+
# Panel 3: Effect size correlation between models (pairwise)
|
| 1104 |
+
model_names = list(all_results.keys())
|
| 1105 |
+
if len(model_names) >= 2:
|
| 1106 |
+
b1 = all_results[model_names[0]][1]
|
| 1107 |
+
b2 = all_results[model_names[1]][1]
|
| 1108 |
+
axes[1,0].scatter(b1, b2, c=ACCENT_TEAL, s=15, alpha=0.5, linewidths=0)
|
| 1109 |
+
m_range = [min(b1.min(), b2.min()), max(b1.max(), b2.max())]
|
| 1110 |
+
axes[1,0].plot(m_range, m_range, color=ACCENT_CORAL, ls='--', lw=1.5)
|
| 1111 |
+
r, p_cor = stats.pearsonr(b1, b2)
|
| 1112 |
+
axes[1,0].set_title(f"Effect Size Correlation\n{model_names[0]} vs {model_names[1]} (r={r:.3f})")
|
| 1113 |
+
axes[1,0].set_xlabel(f"Ξ² ({model_names[0]})"); axes[1,0].set_ylabel(f"Ξ² ({model_names[1]})")
|
| 1114 |
+
else:
|
| 1115 |
+
axes[1,0].text(0.5, 0.5, "Need β₯2 models", ha='center', transform=axes[1,0].transAxes, color=TEXT_DIM)
|
| 1116 |
+
|
| 1117 |
+
# Panel 4: Concordance heatmap (Spearman r of -log10p across models)
|
| 1118 |
+
n_m = len(model_names)
|
| 1119 |
+
concordance = np.eye(n_m)
|
| 1120 |
+
for i in range(n_m):
|
| 1121 |
+
for j in range(i+1, n_m):
|
| 1122 |
+
lp_i = -np.log10(np.clip(all_results[model_names[i]][0], 1e-300, 1))
|
| 1123 |
+
lp_j = -np.log10(np.clip(all_results[model_names[j]][0], 1e-300, 1))
|
| 1124 |
+
r, _ = stats.spearmanr(lp_i, lp_j)
|
| 1125 |
+
concordance[i,j] = concordance[j,i] = r
|
| 1126 |
+
im = axes[1,1].imshow(concordance, cmap='RdYlGn', vmin=-1, vmax=1, aspect='auto')
|
| 1127 |
+
axes[1,1].set_xticks(range(n_m)); axes[1,1].set_yticks(range(n_m))
|
| 1128 |
+
axes[1,1].set_xticklabels(model_names, rotation=35, fontsize=7)
|
| 1129 |
+
axes[1,1].set_yticklabels(model_names, fontsize=7)
|
| 1130 |
+
for i in range(n_m):
|
| 1131 |
+
for j in range(n_m):
|
| 1132 |
+
axes[1,1].text(j, i, f"{concordance[i,j]:.2f}", ha='center', va='center',
|
| 1133 |
+
fontsize=6, color='black' if abs(concordance[i,j]) < 0.7 else 'white')
|
| 1134 |
+
plt.colorbar(im, ax=axes[1,1], label="Spearman Ο")
|
| 1135 |
+
axes[1,1].set_title("Model Concordance (Spearman Ο of βlogββp)")
|
| 1136 |
+
|
| 1137 |
+
fig.suptitle("GWAS Interpretation Panel", color=TEXT_MAIN, fontsize=13)
|
| 1138 |
+
fig.tight_layout(); return fig
|
| 1139 |
+
|
| 1140 |
+
# βββββββββββββββββββββββββββ MAIN PIPELINE ββββββββββββββββββββββββββββββββββββββββ
|
| 1141 |
|
| 1142 |
def run_gwas(file_obj, text_input, selected_models, maf_threshold):
|
| 1143 |
try:
|
| 1144 |
df, snp_cols, chroms, positions = parse_data(file_obj, text_input)
|
| 1145 |
except Exception as e:
|
| 1146 |
+
return [None] * 24 + [f"β Data parsing error: {e}"]
|
| 1147 |
+
|
| 1148 |
y = df["Phenotype"].values.astype(float)
|
| 1149 |
ids = df["ID"].values
|
| 1150 |
G_raw = df[snp_cols].values.astype(float)
|
| 1151 |
G = impute_genotypes(G_raw)
|
| 1152 |
n, m = G.shape
|
| 1153 |
+
|
| 1154 |
maf_vals = compute_maf(G)
|
| 1155 |
maf_thr = float(maf_threshold)
|
| 1156 |
keep = maf_vals >= maf_thr
|
| 1157 |
+
if keep.sum() < 2: keep = np.ones(m, dtype=bool)
|
| 1158 |
+
|
|
|
|
| 1159 |
G_filt = G[:, keep]
|
| 1160 |
snp_filt = np.array(snp_cols)[keep]
|
| 1161 |
+
chr_filt = chroms[keep] if len(chroms) == m else np.ones(G_filt.shape[1], dtype=int)
|
| 1162 |
pos_filt = positions[keep] if len(positions) == m else np.arange(G_filt.shape[1])
|
| 1163 |
+
|
| 1164 |
K = build_kinship(G_filt)
|
| 1165 |
+
|
|
|
|
| 1166 |
model_funcs = {
|
| 1167 |
+
"OLS": lambda: ols_gwas(y, G_filt),
|
| 1168 |
+
"MLM": lambda: mlm_gwas(y, G_filt, K),
|
| 1169 |
+
"GLM": lambda: glm_gwas(y, G_filt),
|
| 1170 |
+
"CMLM": lambda: cmlm_gwas(y, G_filt, K),
|
| 1171 |
+
"BLINK": lambda: blink_gwas(y, G_filt),
|
| 1172 |
"FarmCPU": lambda: farmcpu_gwas(y, G_filt, K),
|
| 1173 |
+
"EMMAX": lambda: emmax_gwas(y, G_filt, K),
|
| 1174 |
+
"PLINK": lambda: plink_gwas(y, G_filt),
|
| 1175 |
+
"GAPIT3": lambda: gapit3_gwas(y, G_filt, K),
|
| 1176 |
+
"GEMMA": lambda: gemma_gwas(y, G_filt, K),
|
| 1177 |
}
|
| 1178 |
+
|
| 1179 |
models_to_run = selected_models if selected_models else list(model_funcs.keys())
|
|
|
|
| 1180 |
all_results = {}
|
| 1181 |
+
primary_p = primary_b = None
|
| 1182 |
+
|
|
|
|
| 1183 |
for mname in models_to_run:
|
| 1184 |
if mname in model_funcs:
|
| 1185 |
+
try:
|
| 1186 |
+
p, b = model_funcs[mname]()
|
| 1187 |
+
all_results[mname] = (p, b)
|
| 1188 |
+
if primary_p is None:
|
| 1189 |
+
primary_p, primary_b = p, b
|
| 1190 |
+
except Exception as ex:
|
| 1191 |
+
print(f"Model {mname} failed: {ex}")
|
| 1192 |
+
|
| 1193 |
if primary_p is None:
|
| 1194 |
+
return [None] * 24 + ["β No models succeeded"]
|
| 1195 |
+
|
|
|
|
| 1196 |
plots = []
|
| 1197 |
+
# 1. Manhattan (primary model, golden dots)
|
| 1198 |
+
plots.append(plot_manhattan(primary_p, chr_filt, pos_filt, "Manhattan Plot", models_to_run[0]))
|
| 1199 |
+
# 2. QQ (primary model)
|
| 1200 |
+
plots.append(plot_qq(primary_p, f"QQ Plot β {models_to_run[0]}"))
|
| 1201 |
+
# 3. QQ all models (individual panels)
|
| 1202 |
+
plots.append(plot_qq_all_models(all_results))
|
| 1203 |
+
# 4. QQ overlay all models
|
| 1204 |
+
plots.append(plot_qq_overlay(all_results))
|
| 1205 |
+
# 5. Circos comparison
|
| 1206 |
+
plots.append(plot_circos(all_results, chr_filt, pos_filt))
|
| 1207 |
+
# 6. LD decay BP + MB
|
| 1208 |
+
plots.append(plot_ld_decay_bpMb(G_filt, pos_filt))
|
| 1209 |
+
# 7. LD heatmap
|
| 1210 |
+
plots.append(plot_ld_analysis_heatmap(G_filt, pos_filt, chr_filt))
|
| 1211 |
+
# 8. PCA
|
| 1212 |
plots.append(plot_pca(G_filt, y, ids))
|
| 1213 |
+
# 9. Phenotype distribution
|
| 1214 |
plots.append(plot_phenotype_distribution(y, ids))
|
| 1215 |
+
# 10. MAF
|
| 1216 |
plots.append(plot_maf_analysis(maf_vals, snp_cols))
|
| 1217 |
+
# 11. Effect sizes
|
| 1218 |
plots.append(plot_effect_sizes(primary_p, primary_b, snp_filt))
|
| 1219 |
+
# 12. Heterozygosity
|
| 1220 |
plots.append(plot_heterozygosity(G_filt, y, ids))
|
| 1221 |
+
# 13. Call rate
|
| 1222 |
plots.append(plot_call_rate_analysis(G_filt, snp_filt))
|
| 1223 |
+
# 14. Kinship
|
| 1224 |
plots.append(plot_kinship_analysis(K, ids))
|
| 1225 |
+
# 15. MDS/t-SNE
|
| 1226 |
plots.append(plot_mds_analysis(G_filt, y, ids))
|
| 1227 |
+
# 16. Manhattan by chromosome
|
| 1228 |
plots.append(plot_manhattan_by_chromosome(primary_p, chr_filt, pos_filt))
|
| 1229 |
+
# 17. Manhattan + QQ combined panel
|
| 1230 |
plots.append(plot_manhattan_qq_combined(primary_p, chr_filt, pos_filt))
|
| 1231 |
+
# 18. All-model Manhattan comparison
|
| 1232 |
+
plots.append(plot_model_comparison_manhattan(all_results, chr_filt, pos_filt))
|
| 1233 |
+
# 19. Interpretation panel
|
| 1234 |
+
plots.append(plot_gwas_interpretation_panel(all_results, primary_p, primary_b, snp_filt, chr_filt, pos_filt))
|
| 1235 |
+
# 20. Summary dashboard
|
| 1236 |
+
plots.append(plot_summary_dashboard(y, maf_vals, primary_p, primary_b, G_filt, all_results))
|
| 1237 |
+
|
|
|
|
|
|
|
|
|
|
| 1238 |
img_plots = [fig_to_pil(fig) if fig is not None else None for fig in plots]
|
| 1239 |
plt.close('all')
|
| 1240 |
+
|
|
|
|
| 1241 |
bonf = 0.05 / len(primary_p)
|
| 1242 |
res_df = pd.DataFrame({
|
| 1243 |
"SNP": snp_filt[:50],
|
|
|
|
| 1247 |
"P_value": primary_p[:50],
|
| 1248 |
"-log10P": np.round(-np.log10(np.clip(primary_p[:50], 1e-300, 1)), 4),
|
| 1249 |
}).sort_values("P_value").head(20)
|
| 1250 |
+
|
| 1251 |
lam = np.median(stats.chi2.ppf(1 - np.clip(primary_p, 1e-10, 1), df=1)) / stats.chi2.ppf(0.5, df=1)
|
| 1252 |
+
sig_snps = (primary_p < bonf).sum()
|
| 1253 |
+
|
| 1254 |
+
lambdas_str = "\n ".join([
|
| 1255 |
+
f"{m}: Ξ»={np.median(stats.chi2.ppf(1-np.clip(p,1e-10,1),df=1))/stats.chi2.ppf(0.5,df=1):.4f}, sig={int((p<bonf).sum())}"
|
| 1256 |
+
for m, (p, _) in all_results.items()
|
| 1257 |
+
])
|
| 1258 |
+
|
| 1259 |
summary = f"""
|
| 1260 |
+
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1261 |
+
β 𧬠COMPLETE GWAS ANALYSIS SUMMARY 𧬠β
|
| 1262 |
+
β βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ£
|
| 1263 |
+
β Dataset: {n} samples Γ {m} SNPs (raw)
|
| 1264 |
+
β SNPs after MAFβ₯{maf_thr:.2f} filter: {G_filt.shape[1]}
|
| 1265 |
+
β
|
| 1266 |
+
β MODELS RUN ({len(all_results)}): {', '.join(all_results.keys())}
|
| 1267 |
+
β
|
| 1268 |
+
β PER-MODEL RESULTS:
|
| 1269 |
+
{lambdas_str}
|
| 1270 |
+
β
|
| 1271 |
+
β PRIMARY MODEL ({models_to_run[0]}):
|
| 1272 |
+
β Bonferroni threshold: {bonf:.2e}
|
| 1273 |
+
β Significant MTAs: {sig_snps}
|
| 1274 |
+
β Genomic Inflation Ξ»: {lam:.4f}
|
| 1275 |
+
β
|
| 1276 |
+
β TOP 5 ASSOCIATIONS ({models_to_run[0]}):
|
| 1277 |
+
{res_df[['SNP','Chr','Pos','Beta','P_value']].head(5).to_string(index=False)}
|
| 1278 |
+
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1279 |
"""
|
| 1280 |
+
|
| 1281 |
return img_plots + [res_df, summary]
|
| 1282 |
|
| 1283 |
+
# βββββββββββββββββββββββββββ GRADIO UI ββββββββββββββββββββββββββββββββββββββββββββ
|
| 1284 |
|
| 1285 |
SAMPLE_DATA = """ID,Phenotype,chr1_134521_SNP1,chr1_134810_SNP2,chr1_178766_SNP3,chr1_210328_SNP4
|
| 1286 |
chromosome,1,1,1,1
|
|
|
|
| 1295 |
IRRI-42,30.67,0,0,0,0
|
| 1296 |
IRRI-50,22,0,0,0,2"""
|
| 1297 |
|
| 1298 |
+
DARK_CSS = """
|
| 1299 |
+
@import url('https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;600&family=Sora:wght@300;500;700&display=swap');
|
| 1300 |
+
body, .gradio-container {
|
| 1301 |
+
background: #0D1117 !important;
|
| 1302 |
+
font-family: 'Sora', sans-serif !important;
|
| 1303 |
+
color: #E6EDF3 !important;
|
| 1304 |
+
}
|
| 1305 |
+
.gr-panel, .gr-box, .block {
|
| 1306 |
+
background: #161B22 !important;
|
| 1307 |
+
border: 1px solid #30363D !important;
|
| 1308 |
+
border-radius: 12px !important;
|
| 1309 |
+
}
|
| 1310 |
+
h1, h2, h3 { color: #2DD4BF !important; font-family: 'Sora', sans-serif !important; }
|
| 1311 |
+
.gr-button-primary {
|
| 1312 |
+
background: linear-gradient(135deg, #2DD4BF, #60A5FA) !important;
|
| 1313 |
+
border-radius: 8px !important;
|
| 1314 |
+
font-family: 'Sora', sans-serif !important;
|
| 1315 |
+
font-weight: 600 !important;
|
| 1316 |
+
border: none !important;
|
| 1317 |
+
color: #0D1117 !important;
|
| 1318 |
+
}
|
| 1319 |
+
.gr-button-primary:hover {
|
| 1320 |
+
background: linear-gradient(135deg, #60A5FA, #A78BFA) !important;
|
| 1321 |
+
transform: translateY(-1px) !important;
|
| 1322 |
+
box-shadow: 0 4px 15px rgba(45, 212, 191, 0.3) !important;
|
| 1323 |
+
}
|
| 1324 |
+
label { color: #8B949E !important; font-size: 12px !important; }
|
| 1325 |
+
input, textarea, select {
|
| 1326 |
+
background: #21262D !important;
|
| 1327 |
+
color: #E6EDF3 !important;
|
| 1328 |
+
border-color: #30363D !important;
|
| 1329 |
+
font-family: 'JetBrains Mono', monospace !important;
|
| 1330 |
+
font-size: 12px !important;
|
| 1331 |
+
}
|
| 1332 |
+
.tab-nav button {
|
| 1333 |
+
color: #8B949E !important;
|
| 1334 |
+
font-family: 'Sora', sans-serif !important;
|
| 1335 |
+
font-size: 11px !important;
|
| 1336 |
+
}
|
| 1337 |
+
.tab-nav button.selected { color: #2DD4BF !important; border-color: #2DD4BF !important; }
|
| 1338 |
"""
|
| 1339 |
|
| 1340 |
+
ALL_MODELS = ["OLS", "MLM", "GLM", "CMLM", "BLINK", "FarmCPU", "EMMAX", "PLINK", "GAPIT3", "GEMMA"]
|
| 1341 |
|
| 1342 |
+
with gr.Blocks(css=DARK_CSS, title="𧬠GWAS Pipeline β 10 Models", theme=gr.themes.Base()) as demo:
|
| 1343 |
gr.Markdown("""
|
| 1344 |
+
# 𧬠Complete GWAS Analysis Pipeline
|
| 1345 |
+
### 10 Statistical Models Β· Circos Plot Β· Per-Model QQ Β· LD Decay (bp + Mb) Β· Golden Dot MTAs
|
| 1346 |
+
|
| 1347 |
+
**Models:** OLS Β· MLM Β· GLM Β· CMLM Β· BLINK Β· FarmCPU Β· EMMAX Β· PLINK Β· GAPIT3 Β· GEMMA
|
| 1348 |
+
**Significant MTAs** highlighted as **π‘ golden dots** on all Manhattan plots
|
| 1349 |
""")
|
| 1350 |
+
|
| 1351 |
with gr.Row():
|
| 1352 |
with gr.Column(scale=1):
|
| 1353 |
+
file_in = gr.File(label="π Upload CSV/TSV", file_types=[".csv", ".tsv", ".txt"])
|
| 1354 |
+
text_in = gr.Textbox(label="π Or paste CSV data", lines=8, value=SAMPLE_DATA)
|
| 1355 |
+
model_sel = gr.CheckboxGroup(
|
| 1356 |
+
choices=ALL_MODELS,
|
| 1357 |
+
value=["OLS", "MLM", "GLM", "FarmCPU", "EMMAX", "GEMMA"],
|
| 1358 |
+
label="π¬ Select Models (up to 10)"
|
| 1359 |
+
)
|
| 1360 |
maf_thr = gr.Slider(0, 0.5, 0.05, 0.01, label="MAF Threshold")
|
| 1361 |
+
run_btn = gr.Button("π Run Complete GWAS Pipeline", variant="primary", size="lg")
|
| 1362 |
+
|
| 1363 |
with gr.Column(scale=2):
|
| 1364 |
+
summary_out = gr.Textbox(label="π Analysis Summary", lines=22,
|
| 1365 |
+
elem_classes=["monospace"])
|
| 1366 |
+
|
| 1367 |
with gr.Tabs():
|
| 1368 |
+
with gr.Tab("πΊ Manhattan"): img1 = gr.Image(type="pil", label="Manhattan β Primary Model (β = Sig. MTA)")
|
| 1369 |
+
with gr.Tab("π QQ (Primary)"): img2 = gr.Image(type="pil", label="QQ Plot β Primary Model")
|
| 1370 |
+
with gr.Tab("π QQ (All Models)"):img3 = gr.Image(type="pil", label="QQ Plots β All Models (individual)")
|
| 1371 |
+
with gr.Tab("π QQ Overlay"): img4 = gr.Image(type="pil", label="QQ Overlay β All Models")
|
| 1372 |
+
with gr.Tab("π΅ Circos"): img5 = gr.Image(type="pil", label="Circos Plot β Multi-Model Comparison")
|
| 1373 |
+
with gr.Tab("π LD Decay (bp/Mb)"):img6 = gr.Image(type="pil", label="LD Decay β bp and Mb")
|
| 1374 |
+
with gr.Tab("π₯ LD Heatmap"): img7 = gr.Image(type="pil", label="LD Heatmap")
|
| 1375 |
+
with gr.Tab("π¬ PCA"): img8 = gr.Image(type="pil", label="PCA Analysis")
|
| 1376 |
+
with gr.Tab("π Phenotype"): img9 = gr.Image(type="pil", label="Phenotype Distribution")
|
| 1377 |
+
with gr.Tab("𧬠MAF"): img10 = gr.Image(type="pil", label="MAF Analysis")
|
| 1378 |
+
with gr.Tab("β Effect Sizes"): img11 = gr.Image(type="pil", label="Effect Sizes & Volcano")
|
| 1379 |
+
with gr.Tab("𧬠Heterozygosity"): img12 = gr.Image(type="pil", label="Heterozygosity Analysis")
|
| 1380 |
+
with gr.Tab("π Call Rate"): img13 = gr.Image(type="pil", label="Call Rate Analysis")
|
| 1381 |
+
with gr.Tab("π¨βπ©βπ§ Kinship"): img14 = gr.Image(type="pil", label="Kinship Matrix")
|
| 1382 |
+
with gr.Tab("π¨ MDS/t-SNE"): img15 = gr.Image(type="pil", label="MDS & t-SNE")
|
| 1383 |
+
with gr.Tab("π By Chromosome"): img16 = gr.Image(type="pil", label="Manhattan by Chromosome")
|
| 1384 |
+
with gr.Tab("π Combined Panel"): img17 = gr.Image(type="pil", label="Manhattan + QQ Combined")
|
| 1385 |
+
with gr.Tab("π All Models MH"): img18 = gr.Image(type="pil", label="Manhattan β All Models")
|
| 1386 |
+
with gr.Tab("π§ Interpretation"): img19 = gr.Image(type="pil", label="GWAS Interpretation Panel")
|
| 1387 |
+
with gr.Tab("π Dashboard"): img20 = gr.Image(type="pil", label="Summary Dashboard")
|
| 1388 |
+
with gr.Tab("π Results Table"): results_tbl = gr.Dataframe(label="Top Associations Table")
|
| 1389 |
+
|
| 1390 |
def run_wrapper(f, t, m, maf):
|
| 1391 |
out = run_gwas(f, t, m, maf)
|
| 1392 |
+
while len(out) < 22:
|
| 1393 |
+
out.append(None)
|
| 1394 |
return out
|
| 1395 |
+
|
| 1396 |
+
run_btn.click(
|
| 1397 |
+
run_wrapper,
|
| 1398 |
+
[file_in, text_in, model_sel, maf_thr],
|
| 1399 |
+
[img1, img2, img3, img4, img5, img6, img7, img8, img9, img10,
|
| 1400 |
+
img11, img12, img13, img14, img15, img16, img17, img18, img19, img20,
|
| 1401 |
+
results_tbl, summary_out]
|
| 1402 |
+
)
|
| 1403 |
|
| 1404 |
if __name__ == "__main__":
|
| 1405 |
demo.launch(share=False, server_port=7860)
|