softwareDevelopment commited on
Commit
19324ec
·
verified ·
1 Parent(s): dede199

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -2020
app.py DELETED
@@ -1,2020 +0,0 @@
1
- import gradio as gr
2
- import pandas as pd
3
- import numpy as np
4
- import matplotlib
5
- matplotlib.use("Agg")
6
- import matplotlib.pyplot as plt
7
- import matplotlib.patches as mpatches
8
- from matplotlib.colors import LinearSegmentedColormap
9
- import matplotlib.gridspec as gridspec
10
- import warnings
11
- warnings.filterwarnings("ignore")
12
-
13
- 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
19
- from statsmodels.stats.multitest import multipletests
20
- import io, re, os, zipfile, tempfile
21
- from io import StringIO
22
- from openpyxl import Workbook
23
- from openpyxl.styles import Font, PatternFill, Alignment, Border, Side
24
- from openpyxl.utils import get_column_letter
25
-
26
- # ─────────────────────── DEFAULT COLOR PALETTES ──────────────────────────────────
27
- BG_DARK = "#0D1117"
28
- PANEL_DARK = "#161B22"
29
- PANEL_MID = "#21262D"
30
- ACCENT_TEAL = "#2DD4BF"
31
- ACCENT_GOLD = "#F59E0B"
32
- ACCENT_CORAL= "#F87171"
33
- ACCENT_BLUE = "#60A5FA"
34
- ACCENT_LIME = "#84CC16"
35
- ACCENT_PURP = "#A78BFA"
36
- ACCENT_PINK = "#F472B6"
37
- ACCENT_CYAN = "#22D3EE"
38
- ACCENT_ORG = "#FB923C"
39
- TEXT_MAIN = "#E6EDF3"
40
- TEXT_DIM = "#8B949E"
41
- GRID_LINE = "#30363D"
42
- SIG_COLOR = "#F59E0B"
43
-
44
- MODEL_COLORS = {
45
- "OLS": "#60A5FA",
46
- "MLM": "#2DD4BF",
47
- "EMMAX": "#F472B6",
48
- "FarmCPU": "#84CC16",
49
- "GEMMA": "#E879F9",
50
- }
51
-
52
- CHR_PALETTE = [
53
- "#4E79A7","#F28E2B","#E15759","#76B7B2","#59A14F",
54
- "#EDC948","#B07AA1","#FF9DA7","#9C755F","#BAB0AC",
55
- "#499894","#86BCB6","#D4A6C8","#FFBE7D","#8CD17D",
56
- ]
57
-
58
- ALL_MODELS = ["OLS", "MLM", "EMMAX", "FarmCPU", "GEMMA"]
59
-
60
- def style_fig_white(fig, font_size=9, font_color="#2D3142", grid_color="#E8ECF4"):
61
- fig.patch.set_facecolor("#FFFFFF")
62
- for ax in fig.get_axes():
63
- ax.set_facecolor("#FAFBFF")
64
- ax.tick_params(colors=font_color, labelsize=font_size)
65
- ax.xaxis.label.set_color(font_color)
66
- ax.yaxis.label.set_color(font_color)
67
- ax.title.set_color(font_color)
68
- for spine in ax.spines.values():
69
- spine.set_edgecolor("#CCCCCC")
70
- ax.grid(color=grid_color, linewidth=0.5, linestyle="--", alpha=0.7)
71
- return fig
72
-
73
- def apply_custom_style(fig, cfg):
74
- bg = cfg.get("bg_color", "#FFFFFF")
75
- panel = cfg.get("panel_color", "#FAFBFF")
76
- fc = cfg.get("font_color", "#2D3142")
77
- fs = cfg.get("font_size", 9)
78
- gc = cfg.get("grid_color", "#E8ECF4")
79
- fig.patch.set_facecolor(bg)
80
- for ax in fig.get_axes():
81
- ax.set_facecolor(panel)
82
- ax.tick_params(colors=fc, labelsize=fs)
83
- ax.xaxis.label.set_color(fc)
84
- ax.yaxis.label.set_color(fc)
85
- ax.title.set_color(fc)
86
- for spine in ax.spines.values():
87
- spine.set_edgecolor("#CCCCCC")
88
- ax.grid(color=gc, linewidth=0.5, linestyle="--", alpha=0.7)
89
- ax.xaxis.label.set_fontsize(fs)
90
- ax.yaxis.label.set_fontsize(fs)
91
- ax.title.set_fontsize(fs + 2)
92
- return fig
93
-
94
- # ─────────────────────── DATA PARSING ────────────────────────────────────────────
95
- def parse_data(file_obj=None, text_input=None):
96
- raw = None
97
- if file_obj is not None:
98
- try:
99
- raw = pd.read_csv(file_obj.name, sep=None, engine="python")
100
- except Exception:
101
- raw = pd.read_csv(file_obj.name, sep="\t")
102
- elif text_input and text_input.strip():
103
- try:
104
- raw = pd.read_csv(StringIO(text_input), sep=None, engine="python")
105
- except Exception:
106
- raw = pd.read_csv(StringIO(text_input), sep="\t")
107
- else:
108
- raise ValueError("No data provided.")
109
-
110
- chrom_info = {}
111
- if len(raw) > 1:
112
- second_row = raw.iloc[1].astype(str)
113
- chrom_vals = second_row.iloc[2:].astype(str)
114
- if len(chrom_vals) > 0 and chrom_vals.str.match(r'^\d+$').all():
115
- for i, col in enumerate(raw.columns[2:]):
116
- try:
117
- chrom_info[col] = int(second_row.iloc[2 + i])
118
- except:
119
- chrom_info[col] = 1
120
- raw = raw.drop(index=1).reset_index(drop=True)
121
-
122
- cols = list(raw.columns)
123
- id_col = cols[0]
124
- phen_col = cols[1]
125
- snp_cols = cols[2:]
126
-
127
- raw = raw[pd.to_numeric(raw[phen_col], errors="coerce").notna()].copy()
128
- raw[phen_col] = raw[phen_col].astype(float)
129
- geno = raw[snp_cols].apply(pd.to_numeric, errors="coerce")
130
- geno = geno.where(~geno.isin([-1, -9, -99, -999]), np.nan)
131
-
132
- df = pd.DataFrame()
133
- df["ID"] = raw[id_col].values
134
- df["Phenotype"] = raw[phen_col].values
135
- for c in snp_cols:
136
- df[c] = geno[c].values
137
-
138
- chroms, positions = [], []
139
- for m in snp_cols:
140
- if m in chrom_info:
141
- chroms.append(chrom_info[m])
142
- positions.append(len(positions) + 1)
143
- else:
144
- m_clean = str(m).strip()
145
- mat = re.match(r"[Cc]hr(\d+)[_\-](\d+)", m_clean)
146
- if mat:
147
- chroms.append(int(mat.group(1)))
148
- positions.append(int(mat.group(2)))
149
- else:
150
- num = re.findall(r"\d+", m_clean)
151
- chroms.append(int(num[0]) if num else 1)
152
- positions.append(int(num[1]) if len(num) > 1 else len(positions) + 1)
153
-
154
- return df, snp_cols, np.array(chroms), np.array(positions)
155
-
156
- # ─────────────────────── UTILITY ─────────────────────────────────────────────────
157
- def impute_genotypes(geno_matrix):
158
- mat = geno_matrix.copy().astype(float)
159
- for j in range(mat.shape[1]):
160
- col = mat[:, j]
161
- m = np.nanmean(col)
162
- col[np.isnan(col)] = m if not np.isnan(m) else 0
163
- mat[:, j] = col
164
- return mat
165
-
166
- def compute_maf(G):
167
- freqs = np.nanmean(G, axis=0) / 2
168
- return np.where(freqs > 0.5, 1 - freqs, freqs)
169
-
170
- def compute_call_rate(G):
171
- return 1 - np.isnan(G).mean(axis=0)
172
-
173
- def build_kinship(G):
174
- p = np.nanmean(G, axis=0) / 2
175
- Z = G - 2 * p
176
- denom = 2 * np.sum(p * (1 - p))
177
- if denom == 0:
178
- denom = 1
179
- return Z @ Z.T / denom
180
-
181
- def compute_pve(y, G, pvals, betas, threshold=0.05):
182
- bonf = threshold / len(pvals)
183
- sig_idx = np.where(pvals < bonf)[0]
184
- pve_dict = {}
185
- for idx in sig_idx:
186
- x = G[:, idx]
187
- mask = ~np.isnan(x)
188
- if mask.sum() < 4:
189
- pve_dict[idx] = 0.0
190
- continue
191
- corr = np.corrcoef(x[mask], y[mask])[0, 1]
192
- pve_dict[idx] = corr**2 * 100
193
- return pve_dict, np.var(y)
194
-
195
- def fig_to_png_bytes(fig):
196
- buf = io.BytesIO()
197
- fig.savefig(buf, format="png", dpi=150, bbox_inches="tight", facecolor=fig.get_facecolor())
198
- buf.seek(0)
199
- return buf.read()
200
-
201
- def fig_to_pil(fig):
202
- buf = io.BytesIO()
203
- fig.savefig(buf, format="png", dpi=150, bbox_inches="tight", facecolor=fig.get_facecolor())
204
- buf.seek(0)
205
- from PIL import Image
206
- return Image.open(buf).copy()
207
-
208
- def get_top_mta(pvals, n=15):
209
- return np.argsort(pvals)[:min(n, len(pvals))]
210
-
211
- def compute_thresholds(n_snps, model_name=""):
212
- """
213
- Compute and explain Bonferroni and suggestive thresholds.
214
- Returns thresholds and explanation text.
215
- """
216
- bonferroni = 0.05 / n_snps
217
- suggestive = 1.0 / n_snps # 1 expected false positive genome-wide
218
-
219
- model_notes = {
220
- "OLS": "OLS uses no population structure correction; thresholds are standard.",
221
- "MLM": "MLM corrects for kinship (relatedness); mixed model may slightly inflate λ.",
222
- "EMMAX": "EMMAX uses efficient mixed-model; variance components estimated once.",
223
- "FarmCPU": "FarmCPU iteratively controls for pseudo-QTNs; reduces false positives.",
224
- "GEMMA": "GEMMA applies genomic inflation correction (λ); p-values are GC-corrected.",
225
- }
226
- note = model_notes.get(model_name, "")
227
-
228
- explanation = (
229
- f"──────────────────────────────────────────────\n"
230
- f" Threshold Calculations — {model_name}\n"
231
- f"──────────────────────────────────────────────\n"
232
- f" SNPs tested (m) : {n_snps:,}\n\n"
233
- f" 📌 Bonferroni threshold:\n"
234
- f" α / m = 0.05 / {n_snps:,} = {bonferroni:.3e}\n"
235
- f" -log₁₀(p) = {-np.log10(bonferroni):.2f}\n"
236
- f" Controls genome-wide Type-I error at 5%.\n"
237
- f" Assumes all tests are independent.\n\n"
238
- f" 📌 Suggestive threshold:\n"
239
- f" 1 / m = 1 / {n_snps:,} = {suggestive:.3e}\n"
240
- f" -log₁₀(p) = {-np.log10(suggestive):.2f}\n"
241
- f" Expects ~1 false positive per genome scan.\n"
242
- f" Lander & Kruglyak (1995) convention.\n\n"
243
- f" ℹ️ Model note: {note}\n"
244
- f"──────────────────────────────────────────────\n"
245
- )
246
- return bonferroni, suggestive, explanation
247
-
248
- # ─────────────────────── 5 EFFICIENT STATISTICAL MODELS ──────────────────────────
249
- def ols_gwas(y, G):
250
- n, m = G.shape
251
- pvals = np.ones(m); betas = np.zeros(m); ses = np.zeros(m)
252
- for j in range(m):
253
- x = G[:, j] - G[:, j].mean()
254
- if x.std() < 1e-8: continue
255
- slope, _, _, p, se = stats.linregress(x, y)
256
- pvals[j] = p; betas[j] = slope; ses[j] = se
257
- return pvals, betas, ses
258
-
259
- def mlm_gwas(y, G, K):
260
- n, m = G.shape
261
- pvals = np.ones(m); betas = np.zeros(m); ses = np.zeros(m)
262
- eigvals, eigvecs = np.linalg.eigh(K + np.eye(n) * 1e-6)
263
- n_pcs = min(3, n - 2)
264
- Q = eigvecs[:, np.argsort(eigvals)[::-1][:n_pcs]]
265
- y_res = y - LinearRegression().fit(Q, y).predict(Q)
266
- for j in range(m):
267
- x = G[:, j]
268
- x_res = x - LinearRegression().fit(Q, x).predict(Q)
269
- if x_res.std() < 1e-8: continue
270
- slope, _, _, p, se = stats.linregress(x_res, y_res)
271
- pvals[j] = p; betas[j] = slope; ses[j] = se
272
- return pvals, betas, ses
273
-
274
- def emmax_gwas(y, G, K):
275
- """
276
- EMMAX: Efficient Mixed-Model Association eXpedited.
277
- Fixed: proper handling of matrix dimensions for all SNPs.
278
- """
279
- n, m = G.shape
280
- pvals = np.ones(m)
281
- betas = np.zeros(m)
282
- ses = np.zeros(m)
283
-
284
- tau = np.var(y) * 0.5
285
- sigma = np.var(y) * 0.5
286
- V = tau * K + sigma * np.eye(n)
287
- try:
288
- V_inv = np.linalg.inv(V + np.eye(n) * 1e-6)
289
- except np.linalg.LinAlgError:
290
- V_inv = np.eye(n)
291
-
292
- for j in range(m):
293
- x = G[:, j].reshape(-1, 1) # shape (n, 1)
294
-
295
- # P_x = V_inv @ x → shape (n, 1)
296
- Px = V_inv @ x # (n, 1)
297
-
298
- # scalar: x^T Px x
299
- xTPx = float(x.T @ Px) # (1,1) → scalar
300
- if abs(xTPx) < 1e-12:
301
- continue
302
-
303
- # scalar: x^T Px y
304
- xTPy = float(x.T @ (V_inv @ y.reshape(-1, 1)))
305
-
306
- beta = xTPy / xTPx
307
- betas[j] = beta
308
-
309
- resid = y - beta * x.flatten() # shape (n,)
310
- # scalar: resid^T V_inv resid
311
- rVr = float(resid.reshape(1, -1) @ V_inv @ resid.reshape(-1, 1))
312
- sigma_e = rVr / max(n - 2, 1)
313
-
314
- se = float(np.sqrt(abs(sigma_e / xTPx)))
315
- ses[j] = se
316
-
317
- t_stat = beta / (se + 1e-12)
318
- pvals[j] = float(2 * stats.t.sf(abs(t_stat), df=max(n - 2, 1)))
319
-
320
- return pvals, betas, ses
321
-
322
- def farmcpu_gwas(y, G, K):
323
- n, m = G.shape
324
- pvals = np.ones(m); betas = np.zeros(m); ses = np.zeros(m)
325
- mlm_p, _, _ = mlm_gwas(y, G, K)
326
- qtn_idx = np.argsort(mlm_p)[:min(3, m)]
327
- qtns = G[:, qtn_idx]
328
- y_adj = y - LinearRegression().fit(qtns, y).predict(qtns)
329
- for j in range(m):
330
- x = G[:, j]
331
- if x.std() < 1e-8: continue
332
- slope, _, _, p, se = stats.linregress(x, y_adj)
333
- pvals[j] = p; betas[j] = slope; ses[j] = se
334
- return pvals, betas, ses
335
-
336
- def gemma_gwas(y, G, K):
337
- n, m = G.shape
338
- pvals = np.ones(m); betas = np.zeros(m); ses = np.zeros(m)
339
- row_mean = K.mean(axis=1, keepdims=True)
340
- col_mean = K.mean(axis=0, keepdims=True)
341
- grand_mean = K.mean()
342
- Kc = K - row_mean - col_mean + grand_mean
343
- eigvals, eigvecs = np.linalg.eigh(Kc + np.eye(n) * 1e-6)
344
- idx = np.argsort(eigvals)[::-1]
345
- n_pcs = min(4, n - 2)
346
- Q = eigvecs[:, idx[:n_pcs]]
347
- y_res = y - LinearRegression().fit(Q, y).predict(Q)
348
- for j in range(m):
349
- x = G[:, j]
350
- x_res = x - LinearRegression().fit(Q, x).predict(Q)
351
- if x_res.std() < 1e-8: continue
352
- slope, _, _, p, se = stats.linregress(x_res, y_res)
353
- pvals[j] = p; betas[j] = slope; ses[j] = se
354
- lam = np.median(stats.chi2.ppf(1 - np.clip(pvals, 1e-10, 1), df=1)) / stats.chi2.ppf(0.5, df=1)
355
- if lam > 1.05:
356
- chi2_vals = stats.chi2.ppf(1 - pvals, df=1) / lam
357
- pvals = 1 - stats.chi2.cdf(np.clip(chi2_vals, 0, 1e10), df=1)
358
- return pvals, betas, ses
359
-
360
- # ─────────────────────── CONFIG BUILDER ──────────────────────────────────────────
361
- def build_cfg(w, h, fs, fc, gc="#E8ECF4", bg="#FFFFFF", panel="#FAFBFF",
362
- sig_col="#E15759", sug_col="#4E79A7", marker_size=12, alpha=0.75,
363
- font_color=None, dot_col=None, line_col=None, fill_col=None,
364
- axis_col=None):
365
- """
366
- Build a plot configuration dictionary.
367
- 'fc' is the required positional font-color argument.
368
- 'font_color' is an optional alias (takes precedence if provided).
369
- """
370
- effective_fc = font_color if font_color is not None else fc
371
- return {
372
- "width": w,
373
- "height": h,
374
- "font_size": fs,
375
- "font_color": effective_fc,
376
- "grid_color": gc,
377
- "bg_color": bg,
378
- "panel_color": panel,
379
- "sig_color": sig_col,
380
- "sug_color": sug_col,
381
- "marker_size": marker_size,
382
- "alpha": alpha,
383
- "dot_color": dot_col or "#4E79A7",
384
- "line_color": line_col or "#E15759",
385
- "fill_color": fill_col or "#A78BFA",
386
- "axis_color": axis_col or "#2D3142",
387
- }
388
-
389
- # ─────────────────────── MANHATTAN PLOT ──────────────────────────────────────────
390
- def plot_manhattan(pvals, chroms, positions, title="Manhattan Plot", model_name="",
391
- cfg=None, top_n=15):
392
- if cfg is None:
393
- cfg = build_cfg(16, 5, 9, "#2D3142")
394
-
395
- n_snps = len(pvals)
396
- bonf_thresh = 0.05 / n_snps
397
- sug_thresh = 1.0 / n_snps
398
-
399
- sig_line = -np.log10(bonf_thresh)
400
- sug_line = -np.log10(sug_thresh)
401
-
402
- fig, ax = plt.subplots(figsize=(cfg["width"], cfg["height"]))
403
- fig.patch.set_facecolor(cfg["bg_color"])
404
- ax.set_facecolor(cfg["panel_color"])
405
-
406
- log_p = -np.log10(np.clip(pvals, 1e-300, 1))
407
-
408
- chrom_list = sorted(set(chroms))
409
- chrom_colors = {c: CHR_PALETTE[i % len(CHR_PALETTE)] for i, c in enumerate(chrom_list)}
410
- x_offset = 0
411
- tick_pos, tick_lab, x_coords = [], [], np.zeros(len(pvals))
412
- gap = max(positions) * 0.018 + 1
413
-
414
- for ch in chrom_list:
415
- mask = chroms == ch
416
- pos = positions[mask]
417
- if len(pos) == 0: continue
418
- order = np.argsort(pos)
419
- x_vals = pos[order] - pos.min() + x_offset
420
- x_coords[np.where(mask)[0][order]] = x_vals
421
- tick_pos.append(x_vals.mean())
422
- tick_lab.append(f"Chr{ch}")
423
- ax.scatter(x_coords[mask], log_p[mask],
424
- c=chrom_colors[ch], s=cfg["marker_size"],
425
- alpha=cfg["alpha"], linewidths=0)
426
- x_offset += (pos.max() - pos.min()) + gap
427
-
428
- ax.axhline(sug_line, color=cfg["sug_color"], ls=":", lw=1.5, alpha=0.9,
429
- label=f"Suggestive (1/m = {sug_thresh:.1e}, -log₁₀={sug_line:.1f})")
430
- ax.axhline(sig_line, color=cfg["sig_color"], ls="--", lw=2.0,
431
- label=f"Bonferroni (0.05/m = {bonf_thresh:.1e}, -log₁₀={sig_line:.1f})")
432
-
433
- top_idx = get_top_mta(pvals, top_n)
434
- sig_mask = np.zeros(len(pvals), dtype=bool)
435
- sig_mask[top_idx] = True
436
-
437
- if sig_mask.any():
438
- ax.scatter(x_coords[sig_mask], log_p[sig_mask],
439
- c=ACCENT_GOLD, s=max(cfg["marker_size"]*4, 60),
440
- marker="D", zorder=10, edgecolors="#333333", linewidth=0.7,
441
- label=f"Top {sig_mask.sum()} MTAs")
442
-
443
- ax.set_xticks(tick_pos)
444
- ax.set_xticklabels(tick_lab, rotation=45,
445
- fontsize=cfg["font_size"]-1, color=cfg["font_color"])
446
- ax.set_ylabel("-log₁₀(p)", color=cfg["font_color"], fontsize=cfg["font_size"])
447
- ax.set_xlabel("Chromosome", color=cfg["font_color"], fontsize=cfg["font_size"])
448
- ax.set_title(f"{title}{' — ' + model_name if model_name else ''}",
449
- color=cfg["font_color"], fontsize=cfg["font_size"]+2, pad=8)
450
- ax.legend(fontsize=cfg["font_size"]-1, framealpha=0.9,
451
- facecolor=cfg["bg_color"], edgecolor="#CCCCCC",
452
- labelcolor=cfg["font_color"], loc='upper right')
453
- ax.set_xlim(-x_offset * 0.01, x_offset * 1.01)
454
- ax.tick_params(colors=cfg["font_color"])
455
- for spine in ax.spines.values():
456
- spine.set_edgecolor("#CCCCCC")
457
- ax.grid(color=cfg["grid_color"], linewidth=0.4, linestyle="--", alpha=0.6)
458
- fig.tight_layout()
459
- return fig
460
-
461
-
462
- # ─────────────────────── QQ PLOT ─────────────────────────────────────────────────
463
- def plot_qq_single(pvals, title="QQ Plot", model_name="", color=None, cfg=None):
464
- if cfg is None:
465
- cfg = build_cfg(7, 7, 9, "#2D3142")
466
- if color is None:
467
- color = cfg.get("dot_color", "#A78BFA")
468
-
469
- fig, ax = plt.subplots(figsize=(cfg["width"], cfg["height"]))
470
- fig.patch.set_facecolor(cfg["bg_color"])
471
- ax.set_facecolor(cfg["panel_color"])
472
-
473
- n = len(pvals)
474
- obs = np.sort(-np.log10(np.clip(pvals, 1e-300, 1)))[::-1]
475
- exp = -np.log10(np.linspace(1/n, 1, n)[::-1])
476
-
477
- ci_lower = -np.log10(stats.beta.ppf(0.975, np.arange(1, n+1), np.arange(n, 0, -1)))
478
- ci_upper = -np.log10(stats.beta.ppf(0.025, np.arange(1, n+1), np.arange(n, 0, -1)))
479
- ax.fill_between(exp, ci_lower, ci_upper, alpha=0.2, color=color, label="95% CI")
480
-
481
- ax.scatter(exp, obs, c=color, s=cfg["marker_size"], alpha=cfg["alpha"],
482
- linewidths=0, zorder=5, label="Observed")
483
-
484
- ax.plot([0, max(exp)], [0, max(exp)], color="#AAAAAA",
485
- ls="-", lw=1.2, alpha=0.7, label="y = x (null)", zorder=4)
486
-
487
- valid = np.isfinite(exp) & np.isfinite(obs)
488
- if valid.sum() > 2:
489
- slope_reg, intercept_reg, r_val, p_val, _ = stats.linregress(exp[valid], obs[valid])
490
- x_reg = np.linspace(exp[valid].min(), exp[valid].max(), 200)
491
- y_reg = slope_reg * x_reg + intercept_reg
492
- ax.plot(x_reg, y_reg, color=cfg["line_color"], ls="-", lw=2.2, zorder=6,
493
- label=f"Regression (slope={slope_reg:.3f}, R²={r_val**2:.3f})")
494
-
495
- lam = np.median(stats.chi2.ppf(1 - np.clip(pvals, 1e-10, 1), df=1)) / stats.chi2.ppf(0.5, df=1)
496
- ax.text(0.05, 0.93, f"λ = {lam:.4f}", transform=ax.transAxes,
497
- fontsize=cfg["font_size"]+2, color="#E15759", fontweight='bold')
498
-
499
- ax.set_xlabel("Expected -log₁₀(p)", fontsize=cfg["font_size"], color=cfg["font_color"])
500
- ax.set_ylabel("Observed -log₁₀(p)", fontsize=cfg["font_size"], color=cfg["font_color"])
501
- ax.set_title(f"{title}{' — ' + model_name if model_name else ''}",
502
- color=cfg["font_color"], fontsize=cfg["font_size"]+2)
503
- ax.legend(fontsize=cfg["font_size"]-1, framealpha=0.85,
504
- facecolor=cfg["bg_color"], edgecolor="#CCCCCC",
505
- labelcolor=cfg["font_color"])
506
- ax.tick_params(colors=cfg["font_color"], labelsize=cfg["font_size"])
507
- for spine in ax.spines.values():
508
- spine.set_edgecolor("#CCCCCC")
509
- ax.grid(color=cfg["grid_color"], linewidth=0.4, linestyle="--", alpha=0.6)
510
- fig.tight_layout()
511
- return fig
512
-
513
-
514
- def plot_qq_all_models(all_results, cfg=None):
515
- """QQ plots for all models with regression lines."""
516
- if cfg is None:
517
- cfg = build_cfg(7, 6, 9, "#2D3142")
518
- n_models = len(all_results)
519
- ncols = min(3, n_models)
520
- nrows = (n_models + ncols - 1) // ncols
521
- fig, axes = plt.subplots(nrows, ncols,
522
- figsize=(cfg["width"] * ncols, cfg["height"] * nrows))
523
- fig.patch.set_facecolor(cfg["bg_color"])
524
-
525
- if n_models == 1:
526
- axes = np.array([axes])
527
- axes = np.array(axes).flatten()
528
-
529
- for idx, (mname, (pvals, _, _)) in enumerate(all_results.items()):
530
- ax = axes[idx]
531
- ax.set_facecolor(cfg["panel_color"])
532
- n = len(pvals)
533
- obs = np.sort(-np.log10(np.clip(pvals, 1e-300, 1)))[::-1]
534
- exp = -np.log10(np.linspace(1/n, 1, n)[::-1])
535
- ci_lo = -np.log10(stats.beta.ppf(0.975, np.arange(1, n+1), np.arange(n, 0, -1)))
536
- ci_hi = -np.log10(stats.beta.ppf(0.025, np.arange(1, n+1), np.arange(n, 0, -1)))
537
- col = MODEL_COLORS.get(mname, "#7C6FCD")
538
-
539
- ax.fill_between(exp, ci_lo, ci_hi, alpha=0.2, color=col)
540
- ax.scatter(exp, obs, c=col, s=cfg["marker_size"], alpha=cfg["alpha"],
541
- linewidths=0, zorder=5)
542
-
543
- ax.plot([0, max(exp)], [0, max(exp)], color="#AAAAAA",
544
- ls="-", lw=1.0, alpha=0.6, zorder=4)
545
-
546
- valid = np.isfinite(exp) & np.isfinite(obs)
547
- if valid.sum() > 2:
548
- slope_reg, intercept_reg, r_val, _, _ = stats.linregress(exp[valid], obs[valid])
549
- x_reg = np.linspace(exp[valid].min(), exp[valid].max(), 200)
550
- y_reg = slope_reg * x_reg + intercept_reg
551
- ax.plot(x_reg, y_reg, color=cfg["sig_color"], ls="-", lw=2.0, zorder=6,
552
- label=f"Reg slope={slope_reg:.2f}")
553
- ax.legend(fontsize=cfg["font_size"]-2, facecolor=cfg["bg_color"],
554
- edgecolor="#CCCCCC", labelcolor=cfg["font_color"])
555
-
556
- lam = np.median(stats.chi2.ppf(1-np.clip(pvals,1e-10,1),df=1)) / stats.chi2.ppf(0.5, df=1)
557
- ax.text(0.05, 0.92, f"λ = {lam:.4f}", transform=ax.transAxes,
558
- fontsize=cfg["font_size"]+1, color="#E15759", fontweight='bold')
559
- ax.set_xlabel("Expected -log₁₀(p)", fontsize=cfg["font_size"], color=cfg["font_color"])
560
- ax.set_ylabel("Observed -log₁₀(p)", fontsize=cfg["font_size"], color=cfg["font_color"])
561
- ax.set_title(f"QQ — {mname}", color=col, fontsize=cfg["font_size"]+1, fontweight='bold')
562
- ax.tick_params(colors=cfg["font_color"], labelsize=cfg["font_size"]-1)
563
- for spine in ax.spines.values():
564
- spine.set_edgecolor("#CCCCCC")
565
- ax.grid(color=cfg["grid_color"], linewidth=0.4, linestyle="--", alpha=0.6)
566
-
567
- for idx in range(n_models, len(axes)):
568
- axes[idx].set_visible(False)
569
-
570
- fig.suptitle("QQ Plots — All Models (with Regression Lines)", color=cfg["font_color"],
571
- fontsize=cfg["font_size"]+3, y=1.01, fontweight='bold')
572
- fig.tight_layout()
573
- return fig
574
-
575
-
576
- def plot_qq_overlay(all_results, cfg=None):
577
- """QQ overlay with regression lines per model."""
578
- if cfg is None:
579
- cfg = build_cfg(9, 9, 10, "#2D3142")
580
- fig, ax = plt.subplots(figsize=(cfg["width"], cfg["height"]))
581
- fig.patch.set_facecolor(cfg["bg_color"])
582
- ax.set_facecolor(cfg["panel_color"])
583
- exp_max = 0
584
- for mname, (pvals, _, _) in all_results.items():
585
- n = len(pvals)
586
- obs = np.sort(-np.log10(np.clip(pvals, 1e-300, 1)))[::-1]
587
- exp = -np.log10(np.linspace(1/n, 1, n)[::-1])
588
- exp_max = max(exp_max, max(exp))
589
- lam = np.median(stats.chi2.ppf(1-np.clip(pvals,1e-10,1),df=1)) / stats.chi2.ppf(0.5, df=1)
590
- col = MODEL_COLORS.get(mname, "#7C6FCD")
591
- ax.plot(exp, obs, color=col, lw=2, label=f"{mname} (λ={lam:.3f})", alpha=0.85)
592
-
593
- valid = np.isfinite(exp) & np.isfinite(obs)
594
- if valid.sum() > 2:
595
- slope_r, intercept_r, _, _, _ = stats.linregress(exp[valid], obs[valid])
596
- x_r = np.linspace(exp[valid].min(), exp[valid].max(), 100)
597
- ax.plot(x_r, slope_r * x_r + intercept_r, color=col,
598
- ls="--", lw=1.2, alpha=0.55)
599
-
600
- ax.plot([0, exp_max], [0, exp_max], color="#AAAAAA",
601
- ls="-", lw=1.5, label="y = x (null)", alpha=0.6)
602
- ax.set_xlabel("Expected -log₁₀(p)", fontsize=cfg["font_size"], color=cfg["font_color"])
603
- ax.set_ylabel("Observed -log₁₀(p)", fontsize=cfg["font_size"], color=cfg["font_color"])
604
- ax.set_title("QQ Plot — All Models Overlay (solid=observed, dashed=regression)",
605
- color=cfg["font_color"], fontsize=cfg["font_size"]+2, fontweight='bold')
606
- ax.legend(fontsize=cfg["font_size"]-1, framealpha=0.85,
607
- facecolor=cfg["bg_color"], edgecolor="#CCCCCC", labelcolor=cfg["font_color"])
608
- ax.tick_params(colors=cfg["font_color"], labelsize=cfg["font_size"])
609
- for spine in ax.spines.values():
610
- spine.set_edgecolor("#CCCCCC")
611
- ax.grid(color=cfg["grid_color"], linewidth=0.4, linestyle="--", alpha=0.6)
612
- fig.tight_layout()
613
- return fig
614
-
615
-
616
- # ─────────────────────── CIRCOS PLOT ─────────────────────────────────────────────
617
- def plot_circos(all_results, chroms, positions, cfg=None, top_n=15):
618
- if cfg is None:
619
- cfg = build_cfg(14, 14, 8, "#2D3142")
620
-
621
- fig, ax = plt.subplots(figsize=(cfg["width"], cfg["height"]),
622
- subplot_kw=dict(projection='polar'))
623
- fig.patch.set_facecolor(cfg["bg_color"])
624
- ax.set_facecolor(cfg["bg_color"])
625
- ax.grid(False)
626
- ax.set_yticks([])
627
- ax.set_xticks([])
628
- ax.spines['polar'].set_visible(False)
629
-
630
- chrom_list = sorted(set(chroms))
631
- total_snps = len(chroms)
632
- sort_idx = np.lexsort((positions, chroms))
633
-
634
- snp_angles = np.linspace(0, 2 * np.pi, total_snps, endpoint=False)
635
-
636
- outer_r = 1.0
637
- band_h = 0.07
638
- label_r = outer_r + band_h + 0.10
639
-
640
- chrom_bounds = {}
641
- for ch in chrom_list:
642
- mask_sorted = chroms[sort_idx] == ch
643
- idxs_in_sorted = np.where(mask_sorted)[0]
644
- if len(idxs_in_sorted) == 0: continue
645
- theta_start = snp_angles[idxs_in_sorted[0]]
646
- theta_end = snp_angles[idxs_in_sorted[-1]]
647
- theta_mid = (theta_start + theta_end) / 2
648
- chrom_bounds[ch] = (theta_start, theta_end, theta_mid, idxs_in_sorted)
649
- col = CHR_PALETTE[chrom_list.index(ch) % len(CHR_PALETTE)]
650
- span = snp_angles[1] - snp_angles[0] if len(snp_angles) > 1 else 0.01
651
- bar_w = max(span * len(idxs_in_sorted) * 1.05,
652
- 2 * np.pi / total_snps * 1.2)
653
- ax.bar(theta_mid, band_h, width=bar_w,
654
- bottom=outer_r, color=col, alpha=0.88,
655
- linewidth=0.8, edgecolor="white")
656
-
657
- text_angle_deg = np.degrees(theta_mid)
658
- if theta_mid > np.pi:
659
- rotation = text_angle_deg - 90
660
- else:
661
- rotation = text_angle_deg + 90
662
-
663
- ax.text(theta_mid, outer_r + band_h * 0.5,
664
- f"{ch}",
665
- ha='center', va='center',
666
- fontsize=max(cfg["font_size"]-1, 6),
667
- color='white', fontweight='bold',
668
- rotation=rotation)
669
-
670
- used_angles = []
671
- min_sep = 0.20
672
-
673
- def angle_free(a):
674
- for ua in used_angles:
675
- diff = abs(a - ua) % (2 * np.pi)
676
- if min(diff, 2*np.pi - diff) < min_sep:
677
- return False
678
- return True
679
-
680
- for ch in chrom_list:
681
- if ch not in chrom_bounds: continue
682
- _, _, theta_mid, _ = chrom_bounds[ch]
683
- col = CHR_PALETTE[chrom_list.index(ch) % len(CHR_PALETTE)]
684
- candidate = theta_mid
685
- for delta in np.linspace(0, np.pi, 60):
686
- for sign in [1, -1]:
687
- t = (theta_mid + sign * delta) % (2 * np.pi)
688
- if angle_free(t):
689
- candidate = t
690
- break
691
- else:
692
- continue
693
- break
694
- used_angles.append(candidate)
695
-
696
- if candidate > np.pi:
697
- rot = np.degrees(candidate) - 90
698
- else:
699
- rot = np.degrees(candidate) + 90
700
-
701
- ax.text(candidate, label_r,
702
- f"Chr{ch}", ha='center', va='center',
703
- fontsize=cfg["font_size"], color=col,
704
- fontweight='bold', rotation=rot)
705
-
706
- model_names = list(all_results.keys())
707
- n_models = len(model_names)
708
- ring_gap = 0.012
709
- ring_total = outer_r - 0.05 - 0.18
710
- ring_width = (ring_total - ring_gap * n_models) / max(n_models, 1)
711
-
712
- for midx, mname in enumerate(model_names):
713
- pvals, _, _ = all_results[mname]
714
- log_p = -np.log10(np.clip(pvals, 1e-300, 1))
715
- r_base = 0.18 + midx * (ring_width + ring_gap)
716
- r_max_data = ring_width * 0.85
717
- col = MODEL_COLORS.get(mname, CHR_PALETTE[midx % len(CHR_PALETTE)])
718
- max_lp = max(log_p.max(), 1)
719
-
720
- n_snps = len(pvals)
721
- bonf_thresh = 0.05 / n_snps
722
- sug_thresh = 1.0 / n_snps
723
- bonf_lp = -np.log10(bonf_thresh)
724
- sug_lp = -np.log10(sug_thresh)
725
-
726
- theta_arc = np.linspace(0, 2 * np.pi, 500)
727
- ax.plot(theta_arc, np.full_like(theta_arc, r_base),
728
- color=col, alpha=0.15, lw=0.8, zorder=1)
729
-
730
- sug_r = r_base + (sug_lp / max_lp) * r_max_data
731
- ax.plot(theta_arc, np.full_like(theta_arc, min(sug_r, r_base + r_max_data)),
732
- color=cfg["sug_color"], alpha=0.35, lw=0.7, ls=":", zorder=2)
733
-
734
- bonf_r = r_base + (bonf_lp / max_lp) * r_max_data
735
- if bonf_r <= r_base + r_max_data:
736
- ax.plot(theta_arc, np.full_like(theta_arc, bonf_r),
737
- color=cfg["sig_color"], alpha=0.45, lw=1.0, ls="--", zorder=2)
738
-
739
- lp_norm = log_p[sort_idx] / max_lp * r_max_data
740
- ax.scatter(snp_angles, r_base + lp_norm,
741
- c=col, s=cfg["marker_size"]*0.5,
742
- alpha=cfg["alpha"]*0.7, linewidths=0, zorder=3)
743
-
744
- top_idx = get_top_mta(pvals, top_n)
745
- top_sort_pos = [np.where(sort_idx == ti)[0][0] for ti in top_idx
746
- if len(np.where(sort_idx == ti)[0]) > 0]
747
- if top_sort_pos:
748
- top_ang = snp_angles[top_sort_pos]
749
- top_lp = lp_norm[top_sort_pos]
750
- ax.scatter(top_ang, r_base + top_lp,
751
- c=ACCENT_GOLD, s=max(cfg["marker_size"]*3, 30),
752
- zorder=12, marker='D',
753
- edgecolors='#333333', linewidth=0.5, alpha=0.95)
754
-
755
- ax.text(np.pi * 1.5, r_base + r_max_data * 0.35,
756
- mname, ha='center', va='center',
757
- fontsize=cfg["font_size"]-1, color=col,
758
- fontweight='bold', alpha=0.92)
759
-
760
- if len(all_results) > 0:
761
- first_model = model_names[0]
762
- pvals_first, _, _ = all_results[first_model]
763
- top_mta_idx = get_top_mta(pvals_first, min(top_n, 15))
764
- top_chroms = chroms[top_mta_idx]
765
- uniq_top_chr = np.unique(top_chroms)
766
-
767
- if len(uniq_top_chr) > 1:
768
- ribbon_r = 0.16
769
- for i, idx_i in enumerate(top_mta_idx):
770
- for j, idx_j in enumerate(top_mta_idx):
771
- if j <= i: continue
772
- if chroms[idx_i] == chroms[idx_j]: continue
773
- pos_i = np.where(sort_idx == idx_i)[0]
774
- pos_j = np.where(sort_idx == idx_j)[0]
775
- if len(pos_i) == 0 or len(pos_j) == 0: continue
776
- ang_i = snp_angles[pos_i[0]]
777
- ang_j = snp_angles[pos_j[0]]
778
- theta_ribbon = np.linspace(ang_i, ang_j, 30)
779
- col_r = CHR_PALETTE[chrom_list.index(chroms[idx_i]) % len(CHR_PALETTE)]
780
- ax.fill_between(theta_ribbon,
781
- np.full(30, ribbon_r * 0.4),
782
- np.full(30, ribbon_r),
783
- alpha=0.06, color=col_r, zorder=0)
784
- ax.plot(theta_ribbon, np.full(30, ribbon_r * 0.7),
785
- color=col_r, alpha=0.12, lw=0.8, zorder=1)
786
-
787
- legend_elements = [
788
- mpatches.Patch(facecolor=MODEL_COLORS.get(m, "#7C6FCD"), label=m, alpha=0.85)
789
- for m in model_names
790
- ]
791
- legend_elements.append(mpatches.Patch(facecolor=ACCENT_GOLD,
792
- label=f"Top {top_n} MTAs (◆)", alpha=0.9))
793
- legend_elements.append(mpatches.Patch(facecolor=cfg["sig_color"], alpha=0.6,
794
- label="── Bonferroni (dashed ring)"))
795
- legend_elements.append(mpatches.Patch(facecolor=cfg["sug_color"], alpha=0.6,
796
- label="··· Suggestive (dotted ring)"))
797
-
798
- ax.legend(handles=legend_elements,
799
- loc='lower center', bbox_to_anchor=(0.5, -0.07),
800
- ncol=min(4, n_models+3),
801
- fontsize=cfg["font_size"], framealpha=0.9,
802
- facecolor=cfg["bg_color"], edgecolor="#CCCCCC",
803
- labelcolor=cfg["font_color"])
804
-
805
- ax.set_title(
806
- f"Circos — Multi-Model GWAS | Chr numbers on outer band | ◆ = Top {top_n} MTAs",
807
- color=cfg["font_color"], fontsize=cfg["font_size"]+2, pad=28, fontweight='bold'
808
- )
809
- fig.tight_layout()
810
- return fig
811
-
812
-
813
- # ─────────────────────── LD DECAY ────────────────────────────────────────────────
814
- def plot_ld_decay(G, positions, cfg=None):
815
- if cfg is None:
816
- cfg = build_cfg(16, 6, 9, "#2D3142")
817
- fig, axes = plt.subplots(1, 2, figsize=(cfg["width"], cfg["height"]))
818
- fig.patch.set_facecolor(cfg["bg_color"])
819
-
820
- m = G.shape[1]
821
- dists_bp, r2s = [], []
822
- n_pairs = min(80, m)
823
- for i in range(n_pairs):
824
- for j in range(i+1, n_pairs):
825
- xi, xj = G[:, i], G[:, j]
826
- mask = ~(np.isnan(xi) | np.isnan(xj))
827
- if mask.sum() < 4: continue
828
- r, _ = stats.pearsonr(xi[mask], xj[mask])
829
- d = abs(positions[j] - positions[i])
830
- dists_bp.append(d); r2s.append(r**2)
831
-
832
- if not dists_bp:
833
- for ax in axes:
834
- ax.set_facecolor(cfg["panel_color"])
835
- ax.text(0.5, 0.5, "Insufficient data", ha='center',
836
- transform=ax.transAxes, color=cfg["font_color"])
837
- fig.tight_layout()
838
- return fig
839
-
840
- dists_bp = np.array(dists_bp)
841
- dists_mb = dists_bp / 1_000_000
842
- r2s = np.array(r2s)
843
-
844
- def bin_ld(dists, r2s, n_bins=20):
845
- bins = np.percentile(dists, np.linspace(0, 100, n_bins + 1))
846
- centers, means, sems = [], [], []
847
- for k in range(len(bins)-1):
848
- mask = (dists >= bins[k]) & (dists < bins[k+1])
849
- if mask.sum() > 2:
850
- centers.append((bins[k] + bins[k+1]) / 2)
851
- means.append(np.mean(r2s[mask]))
852
- sems.append(stats.sem(r2s[mask]))
853
- return np.array(centers), np.array(means), np.array(sems)
854
-
855
- for i, (dist_arr, xlabel, title_str, dot_col, line_col) in enumerate([
856
- (dists_bp, "Distance (bp)", "LD Decay — Base Pairs (bp)",
857
- cfg.get("dot_color","#4E79A7"), cfg.get("line_color","#E15759")),
858
- (dists_mb, "Distance (Mb)", "LD Decay — Megabases (Mb)", "#59A14F", "#F28E2B"),
859
- ]):
860
- ax = axes[i]
861
- ax.set_facecolor(cfg["panel_color"])
862
- ax.scatter(dist_arr, r2s, c=dot_col, s=cfg["marker_size"],
863
- alpha=cfg["alpha"], linewidths=0)
864
- bc, bm, bs = bin_ld(dist_arr, r2s)
865
- if len(bc) > 0:
866
- ax.plot(bc, bm, color=line_col, lw=2.5, marker='o',
867
- ms=5, zorder=5, label="Binned mean r²")
868
- ax.fill_between(bc, bm - bs, bm + bs, alpha=0.18, color=line_col)
869
- ax.axhline(0.5, color="#EDC948", ls='--', lw=1.5, alpha=0.85, label="r² = 0.5")
870
- ax.axhline(0.2, color="#B07AA1", ls=':', lw=1.2, alpha=0.75, label="r² = 0.2")
871
- ax.set_xlabel(xlabel, fontsize=cfg["font_size"], color=cfg["font_color"])
872
- ax.set_ylabel("r² (LD)", fontsize=cfg["font_size"], color=cfg["font_color"])
873
- ax.set_title(title_str, color=cfg["font_color"], fontsize=cfg["font_size"]+1,
874
- fontweight='bold')
875
- ax.legend(fontsize=cfg["font_size"]-1, framealpha=0.85,
876
- facecolor=cfg["bg_color"], edgecolor="#CCCCCC",
877
- labelcolor=cfg["font_color"])
878
- ax.set_ylim(0, 1.05)
879
- ax.tick_params(colors=cfg["font_color"], labelsize=cfg["font_size"]-1)
880
- for spine in ax.spines.values(): spine.set_edgecolor("#CCCCCC")
881
- ax.grid(color=cfg["grid_color"], linewidth=0.4, linestyle="--", alpha=0.6)
882
-
883
- fig.suptitle("Linkage Disequilibrium (LD) Decay Analysis",
884
- color=cfg["font_color"], fontsize=cfg["font_size"]+3,
885
- fontweight='bold')
886
- fig.tight_layout()
887
- return fig
888
-
889
-
890
- # ─────────────────────── PCA (DARK THEME) ────────────────────────────────────────
891
- def plot_pca(G, y, ids, cfg=None):
892
- if cfg is None:
893
- cfg = build_cfg(14, 10, 9, TEXT_MAIN,
894
- gc=GRID_LINE, bg=BG_DARK, panel=PANEL_DARK,
895
- sig_col=ACCENT_TEAL, sug_col=ACCENT_GOLD,
896
- marker_size=55, alpha=0.80)
897
-
898
- bg_col = cfg.get("bg_color", BG_DARK)
899
- panel_col = cfg.get("panel_color", PANEL_DARK)
900
- fc = cfg.get("font_color", TEXT_MAIN)
901
- gc = cfg.get("grid_color", GRID_LINE)
902
- fs = cfg.get("font_size", 9)
903
-
904
- fig, axes = plt.subplots(1, 3, figsize=(cfg["width"], cfg["height"]))
905
- fig.patch.set_facecolor(bg_col)
906
- axes = axes.flatten()
907
-
908
- G_sc = StandardScaler().fit_transform(G)
909
- n_comp = min(5, G_sc.shape[0]-1, G_sc.shape[1])
910
- pca = PCA(n_components=n_comp)
911
- pcs = pca.fit_transform(G_sc)
912
- var_exp = pca.explained_variance_ratio_ * 100
913
-
914
- for ax in axes:
915
- ax.set_facecolor(panel_col)
916
- for spine in ax.spines.values():
917
- spine.set_edgecolor(GRID_LINE)
918
- ax.grid(color=gc, linewidth=0.4, linestyle="--", alpha=0.5)
919
- ax.tick_params(colors=fc, labelsize=fs-1)
920
-
921
- sc = axes[0].scatter(pcs[:,0], pcs[:,1], c=y, cmap='plasma',
922
- s=cfg["marker_size"], edgecolors='none', alpha=cfg["alpha"])
923
- axes[0].set_xlabel(f"PC1 ({var_exp[0]:.1f}%)", fontsize=fs, color=fc)
924
- axes[0].set_ylabel(f"PC2 ({var_exp[1]:.1f}%)", fontsize=fs, color=fc)
925
- axes[0].set_title("PC1 vs PC2", color=ACCENT_TEAL, fontsize=fs+1, fontweight='bold')
926
- cbar = plt.colorbar(sc, ax=axes[0])
927
- cbar.set_label("Phenotype", color=fc, fontsize=fs-1)
928
- cbar.ax.tick_params(colors=fc)
929
- cbar.ax.yaxis.set_tick_params(color=fc)
930
- plt.setp(cbar.ax.yaxis.get_ticklabels(), color=fc)
931
-
932
- if n_comp >= 3:
933
- sc2 = axes[1].scatter(pcs[:,1], pcs[:,2], c=y, cmap='plasma',
934
- s=cfg["marker_size"], edgecolors='none', alpha=cfg["alpha"])
935
- axes[1].set_xlabel(f"PC2 ({var_exp[1]:.1f}%)", fontsize=fs, color=fc)
936
- axes[1].set_ylabel(f"PC3 ({var_exp[2]:.1f}%)", fontsize=fs, color=fc)
937
- axes[1].set_title("PC2 vs PC3", color=ACCENT_GOLD, fontsize=fs+1, fontweight='bold')
938
- cbar2 = plt.colorbar(sc2, ax=axes[1])
939
- cbar2.set_label("Phenotype", color=fc, fontsize=fs-1)
940
- cbar2.ax.tick_params(colors=fc)
941
- plt.setp(cbar2.ax.yaxis.get_ticklabels(), color=fc)
942
- else:
943
- axes[1].set_visible(False)
944
-
945
- sc3 = axes[2].scatter(pcs[:,0], pcs[:,1], c=y, cmap='cool',
946
- s=cfg["marker_size"], edgecolors='none', alpha=cfg["alpha"])
947
- axes[2].set_title("Population Structure", color=ACCENT_PINK, fontsize=fs+1, fontweight='bold')
948
- axes[2].set_xlabel(f"PC1 ({var_exp[0]:.1f}%)", fontsize=fs, color=fc)
949
- axes[2].set_ylabel(f"PC2 ({var_exp[1]:.1f}%)", fontsize=fs, color=fc)
950
- cbar3 = plt.colorbar(sc3, ax=axes[2])
951
- cbar3.set_label("Phenotype", color=fc, fontsize=fs-1)
952
- cbar3.ax.tick_params(colors=fc)
953
- plt.setp(cbar3.ax.yaxis.get_ticklabels(), color=fc)
954
-
955
- fig.suptitle("Principal Component Analysis", color=TEXT_MAIN,
956
- fontsize=fs+3, fontweight='bold')
957
- fig.tight_layout()
958
- return fig
959
-
960
-
961
- # ─────────────────────── MODEL COMPARISON MANHATTAN ──────────────────────────────
962
- def plot_model_comparison_manhattan(all_results, chroms, positions, cfg=None, top_n=15):
963
- if cfg is None:
964
- cfg = build_cfg(16, 3.5, 7, "#2D3142")
965
- n_models = len(all_results)
966
- fig, axes = plt.subplots(n_models, 1,
967
- figsize=(cfg["width"], cfg["height"] * n_models),
968
- sharex=True)
969
- fig.patch.set_facecolor(cfg["bg_color"])
970
- if n_models == 1:
971
- axes = [axes]
972
-
973
- chrom_list = sorted(set(chroms))
974
- total_len = 0
975
- chrom_offsets = {}
976
- for ch in chrom_list:
977
- chrom_offsets[ch] = total_len
978
- mask = chroms == ch
979
- if mask.sum() > 0:
980
- total_len += positions[mask].max() - positions[mask].min() + max(positions) * 0.02 + 1
981
-
982
- x_coords = np.zeros(len(chroms))
983
- for ch in chrom_list:
984
- mask = chroms == ch
985
- if mask.sum() > 0:
986
- x_coords[mask] = positions[mask] - positions[mask].min() + chrom_offsets[ch]
987
-
988
- tick_pos, tick_lab = [], []
989
- for ch in chrom_list:
990
- mask = chroms == ch
991
- if mask.sum() > 0:
992
- tick_pos.append(x_coords[mask].mean())
993
- tick_lab.append(f"Chr{ch}")
994
-
995
- for midx, (mname, (pvals, _, _)) in enumerate(all_results.items()):
996
- ax = axes[midx]
997
- ax.set_facecolor(cfg["panel_color"])
998
- log_p = -np.log10(np.clip(pvals, 1e-300, 1))
999
- col = MODEL_COLORS.get(mname, CHR_PALETTE[midx % len(CHR_PALETTE)])
1000
-
1001
- n_snps = len(pvals)
1002
- bonf_thresh = 0.05 / n_snps
1003
- sug_thresh = 1.0 / n_snps
1004
-
1005
- for ch in chrom_list:
1006
- mask = chroms == ch
1007
- ax.scatter(x_coords[mask], log_p[mask],
1008
- c=col, s=cfg["marker_size"], alpha=cfg["alpha"], linewidths=0)
1009
-
1010
- top_idx = get_top_mta(pvals, top_n)
1011
- ax.scatter(x_coords[top_idx], log_p[top_idx],
1012
- c=ACCENT_GOLD, s=max(cfg["marker_size"]*4, 35),
1013
- zorder=10, linewidths=0.7, edgecolors='#333333',
1014
- marker='D', label=f"Top {top_n} MTAs")
1015
-
1016
- ax.axhline(-np.log10(sug_thresh), color=cfg["sug_color"],
1017
- ls=':', lw=1.2, alpha=0.9,
1018
- label=f"Sug. (1/m={sug_thresh:.1e})")
1019
- ax.axhline(-np.log10(bonf_thresh), color=cfg["sig_color"],
1020
- ls='--', lw=1.5, alpha=0.9,
1021
- label=f"Bonf. (0.05/m={bonf_thresh:.1e})")
1022
-
1023
- ax.set_ylabel("-log₁₀(p)", fontsize=cfg["font_size"], color=cfg["font_color"])
1024
- ax.set_title(f"Model: {mname}", color=col,
1025
- fontsize=cfg["font_size"]+1, pad=3, fontweight='bold')
1026
- ax.set_xticks(tick_pos)
1027
- ax.set_xticklabels(
1028
- tick_lab if midx == n_models-1 else [],
1029
- rotation=40, fontsize=cfg["font_size"]-1, color=cfg["font_color"]
1030
- )
1031
- ax.tick_params(colors=cfg["font_color"], labelsize=cfg["font_size"]-1)
1032
- ax.legend(fontsize=cfg["font_size"]-2, framealpha=0.85,
1033
- facecolor=cfg["bg_color"], edgecolor="#CCCCCC",
1034
- labelcolor=cfg["font_color"], ncol=3)
1035
- for spine in ax.spines.values(): spine.set_edgecolor("#CCCCCC")
1036
- ax.grid(color=cfg["grid_color"], linewidth=0.3, linestyle="--", alpha=0.5)
1037
-
1038
- fig.suptitle("Manhattan Plots — All Models Comparison",
1039
- color=cfg["font_color"], fontsize=cfg["font_size"]+3,
1040
- fontweight='bold')
1041
- fig.tight_layout(rect=[0, 0, 1, 0.98])
1042
- return fig
1043
-
1044
-
1045
- # ─────────────────────── KINSHIP ─────────────────────────────────────────────────
1046
- def plot_kinship(K, ids, cfg=None):
1047
- if cfg is None:
1048
- cfg = build_cfg(14, 12, 9, "#2D3142")
1049
-
1050
- fig, axes = plt.subplots(2, 2, figsize=(cfg["width"], cfg["height"]))
1051
- fig.patch.set_facecolor(cfg["bg_color"])
1052
- axes = axes.flatten()
1053
- for ax in axes:
1054
- ax.set_facecolor(cfg["panel_color"])
1055
- for spine in ax.spines.values(): spine.set_edgecolor("#CCCCCC")
1056
- ax.tick_params(colors=cfg["font_color"], labelsize=cfg["font_size"]-1)
1057
-
1058
- im = axes[0].imshow(K, cmap='RdYlBu_r', aspect='auto', vmin=-0.5, vmax=1)
1059
- axes[0].set_title("Kinship Matrix", color=cfg["font_color"],
1060
- fontsize=cfg["font_size"]+1, fontweight='bold')
1061
- cbar = plt.colorbar(im, ax=axes[0])
1062
- cbar.ax.tick_params(colors=cfg["font_color"])
1063
-
1064
- K_flat = K[np.triu_indices_from(K, k=1)]
1065
- axes[1].hist(K_flat, bins=30, color=cfg.get("dot_color","#4E79A7"),
1066
- edgecolor='white', alpha=0.85)
1067
- axes[1].set_title("Pairwise Kinship Distribution", color=cfg["font_color"],
1068
- fontsize=cfg["font_size"]+1, fontweight='bold')
1069
- axes[1].set_xlabel("Kinship Coefficient", fontsize=cfg["font_size"],
1070
- color=cfg["font_color"])
1071
- axes[1].set_ylabel("Count", fontsize=cfg["font_size"], color=cfg["font_color"])
1072
- axes[1].grid(color=cfg["grid_color"], linewidth=0.4, linestyle="--", alpha=0.6)
1073
-
1074
- try:
1075
- lm = linkage(K, method='ward')
1076
- n_samples = len(ids)
1077
- leaf_fs = max(3, min(cfg["font_size"]-1, int(200 / max(n_samples, 1))))
1078
- truncate_mode = None
1079
- p_param = None
1080
- if n_samples > 50:
1081
- truncate_mode = 'lastp'
1082
- p_param = 30
1083
- axes[2].set_title(
1084
- f"Dendrogram (truncated, {n_samples} samples)",
1085
- color=cfg["font_color"], fontsize=cfg["font_size"]+1, fontweight='bold'
1086
- )
1087
- else:
1088
- axes[2].set_title("Clustering Dendrogram", color=cfg["font_color"],
1089
- fontsize=cfg["font_size"]+1, fontweight='bold')
1090
-
1091
- dend_kwargs = dict(
1092
- ax=axes[2],
1093
- leaf_rotation=90,
1094
- leaf_font_size=leaf_fs,
1095
- color_threshold=0.7 * max(lm[:, 2]),
1096
- above_threshold_color="#AAAAAA"
1097
- )
1098
- if truncate_mode:
1099
- dend_kwargs["truncate_mode"] = truncate_mode
1100
- dend_kwargs["p"] = p_param
1101
- else:
1102
- short_labels = [str(x)[:10] for x in ids]
1103
- dend_kwargs["labels"] = short_labels
1104
-
1105
- dendrogram(lm, **dend_kwargs)
1106
- axes[2].tick_params(axis='x', labelsize=leaf_fs, colors=cfg["font_color"])
1107
- axes[2].tick_params(axis='y', labelsize=cfg["font_size"]-2,
1108
- colors=cfg["font_color"])
1109
- if n_samples > 50:
1110
- axes[2].set_xticks([])
1111
- axes[2].set_facecolor(cfg["panel_color"])
1112
- for spine in axes[2].spines.values(): spine.set_edgecolor("#CCCCCC")
1113
- except Exception as e:
1114
- axes[2].text(0.5, 0.5, f"Dendrogram\nunavailable:\n{str(e)[:40]}",
1115
- ha='center', va='center', transform=axes[2].transAxes,
1116
- color=cfg["font_color"], fontsize=cfg["font_size"])
1117
-
1118
- eigvals, eigvecs = np.linalg.eigh(K)
1119
- idx = np.argsort(eigvals)[::-1]
1120
- axes[3].scatter(eigvecs[:,idx[0]], eigvecs[:,idx[1]],
1121
- c=cfg.get("dot_color","#4E79A7"), s=cfg["marker_size"],
1122
- edgecolors='none', alpha=cfg["alpha"])
1123
- axes[3].set_title("Kinship PCA", color=cfg["font_color"],
1124
- fontsize=cfg["font_size"]+1, fontweight='bold')
1125
- axes[3].set_xlabel("PC1", fontsize=cfg["font_size"], color=cfg["font_color"])
1126
- axes[3].set_ylabel("PC2", fontsize=cfg["font_size"], color=cfg["font_color"])
1127
- axes[3].grid(color=cfg["grid_color"], linewidth=0.4, linestyle="--", alpha=0.6)
1128
-
1129
- fig.suptitle("Kinship Matrix & Clustering Analysis",
1130
- color=cfg["font_color"], fontsize=cfg["font_size"]+3, fontweight='bold')
1131
- fig.tight_layout()
1132
- return fig
1133
-
1134
-
1135
- # ─────────────────────── EFFECT SIZES ────────────────────────────────────────────
1136
- def plot_effect_sizes(pvals, betas, snp_names, cfg=None, top_n=15):
1137
- if cfg is None:
1138
- cfg = build_cfg(14, 10, 9, "#2D3142")
1139
-
1140
- fig, axes = plt.subplots(2, 2, figsize=(cfg["width"], cfg["height"]))
1141
- fig.patch.set_facecolor(cfg["bg_color"])
1142
- axes = axes.flatten()
1143
- for ax in axes:
1144
- ax.set_facecolor(cfg["panel_color"])
1145
- for spine in ax.spines.values(): spine.set_edgecolor("#CCCCCC")
1146
- ax.tick_params(colors=cfg["font_color"], labelsize=cfg["font_size"]-1)
1147
- ax.grid(color=cfg["grid_color"], linewidth=0.4, linestyle="--", alpha=0.6)
1148
-
1149
- top_idx = get_top_mta(pvals, top_n)
1150
- top_betas = betas[top_idx]
1151
- top_names = [str(snp_names[i])[:18] for i in top_idx]
1152
- pos_col = cfg.get("dot_color", "#4E79A7")
1153
- neg_col = cfg.get("line_color", "#E15759")
1154
- colors = [neg_col if b < 0 else pos_col for b in top_betas]
1155
-
1156
- order = np.argsort(top_betas)
1157
- axes[0].barh([top_names[o] for o in order], [top_betas[o] for o in order],
1158
- color=[colors[o] for o in order], edgecolor='white', linewidth=0.4)
1159
- axes[0].axvline(0, color=cfg["font_color"], lw=0.9, alpha=0.6)
1160
- axes[0].set_xlabel("Effect Size (β)", fontsize=cfg["font_size"],
1161
- color=cfg["font_color"])
1162
- axes[0].set_title(f"Top {top_n} Effect Sizes", color=cfg["font_color"],
1163
- fontsize=cfg["font_size"]+1, fontweight='bold')
1164
- axes[0].tick_params(axis='y', labelsize=max(5, cfg["font_size"]-2))
1165
-
1166
- log_p = -np.log10(np.clip(pvals, 1e-300, 1))
1167
- sig_thr = -np.log10(0.05/len(pvals))
1168
- pt_colors = [neg_col if lp >= sig_thr else (pos_col if b > 0 else "#59A14F")
1169
- for lp, b in zip(log_p, betas)]
1170
- axes[1].scatter(betas, log_p, c=pt_colors, s=cfg["marker_size"],
1171
- alpha=cfg["alpha"], linewidths=0)
1172
- axes[1].axhline(sig_thr, color=cfg["sig_color"], ls='--', lw=1.8, label="Bonferroni")
1173
- axes[1].axvline(0, color=cfg["font_color"], lw=0.6, alpha=0.5)
1174
- axes[1].set_xlabel("β", fontsize=cfg["font_size"], color=cfg["font_color"])
1175
- axes[1].set_ylabel("-log₁₀(p)", fontsize=cfg["font_size"], color=cfg["font_color"])
1176
- axes[1].set_title("Volcano Plot", color=cfg["font_color"],
1177
- fontsize=cfg["font_size"]+1, fontweight='bold')
1178
- axes[1].legend(fontsize=cfg["font_size"]-1, facecolor=cfg["bg_color"],
1179
- edgecolor="#CCCCCC", labelcolor=cfg["font_color"])
1180
-
1181
- axes[2].hist(betas, bins=25, color=cfg.get("fill_color","#A78BFA"),
1182
- edgecolor='white', alpha=0.85)
1183
- axes[2].axvline(0, color=cfg["sig_color"], lw=2, ls='--')
1184
- axes[2].set_xlabel("β", fontsize=cfg["font_size"], color=cfg["font_color"])
1185
- axes[2].set_title("Effect Size Distribution", color=cfg["font_color"],
1186
- fontsize=cfg["font_size"]+1, fontweight='bold')
1187
- axes[2].set_ylabel("Count", fontsize=cfg["font_size"], color=cfg["font_color"])
1188
-
1189
- axes[3].scatter(betas, log_p, c=pt_colors, s=cfg["marker_size"],
1190
- alpha=cfg["alpha"]*0.85, linewidths=0)
1191
- top_idx2 = get_top_mta(pvals, min(5, top_n))
1192
- for ti in top_idx2:
1193
- axes[3].annotate(str(snp_names[ti])[:12],
1194
- (betas[ti], log_p[ti]),
1195
- fontsize=max(5, cfg["font_size"]-3),
1196
- color=cfg["font_color"], alpha=0.8,
1197
- xytext=(5, 3), textcoords='offset points',
1198
- arrowprops=dict(arrowstyle='->', color='gray', lw=0.6))
1199
- axes[3].set_xlabel("β", fontsize=cfg["font_size"], color=cfg["font_color"])
1200
- axes[3].set_ylabel("-log₁₀(p)", fontsize=cfg["font_size"], color=cfg["font_color"])
1201
- axes[3].set_title("Effect Size vs Significance (annotated)",
1202
- color=cfg["font_color"], fontsize=cfg["font_size"]+1, fontweight='bold')
1203
-
1204
- fig.suptitle("Effect Size Analysis", color=cfg["font_color"],
1205
- fontsize=cfg["font_size"]+3, fontweight='bold')
1206
- fig.tight_layout()
1207
- return fig
1208
-
1209
-
1210
- # ─────────────────────── SUMMARY DASHBOARD ───────────────────────────────────────
1211
- def plot_summary_dashboard(y, maf, all_results, G_filt, cfg=None):
1212
- if cfg is None:
1213
- cfg = build_cfg(15, 10, 9, "#2D3142")
1214
-
1215
- fig, axes = plt.subplots(2, 3, figsize=(cfg["width"], cfg["height"]))
1216
- fig.patch.set_facecolor(cfg["bg_color"])
1217
- axes = axes.flatten()
1218
- for ax in axes:
1219
- ax.set_facecolor(cfg["panel_color"])
1220
- for spine in ax.spines.values(): spine.set_edgecolor("#CCCCCC")
1221
- ax.tick_params(colors=cfg["font_color"], labelsize=cfg["font_size"]-1)
1222
- ax.grid(color=cfg["grid_color"], linewidth=0.4, linestyle="--", alpha=0.6)
1223
-
1224
- # Panel 0: Phenotype distribution
1225
- axes[0].hist(y, bins=15, color=cfg.get("dot_color","#4E79A7"),
1226
- edgecolor='white', alpha=0.85)
1227
- axes[0].axvline(y.mean(), color=cfg["sig_color"], lw=2, ls='--',
1228
- label=f"Mean: {y.mean():.2f}")
1229
- axes[0].set_title(f"Phenotype Distribution | n={len(y)}",
1230
- color=cfg["font_color"], fontsize=cfg["font_size"]+1, fontweight='bold')
1231
- axes[0].legend(fontsize=cfg["font_size"]-1, facecolor=cfg["bg_color"],
1232
- edgecolor="#CCCCCC", labelcolor=cfg["font_color"])
1233
- axes[0].set_xlabel("Phenotype Value", fontsize=cfg["font_size"], color=cfg["font_color"])
1234
- axes[0].set_ylabel("Count", fontsize=cfg["font_size"], color=cfg["font_color"])
1235
-
1236
- # Panel 1: MAF distribution
1237
- axes[1].hist(maf, bins=20, color="#59A14F", edgecolor='white', alpha=0.85)
1238
- axes[1].axvline(0.05, color=cfg["sig_color"], ls='--', lw=1.5,
1239
- label=f"MAF=0.05 (rare: {np.sum(maf<0.05)})")
1240
- axes[1].set_title("Minor Allele Frequency",
1241
- color=cfg["font_color"], fontsize=cfg["font_size"]+1, fontweight='bold')
1242
- axes[1].legend(fontsize=cfg["font_size"]-1, facecolor=cfg["bg_color"],
1243
- edgecolor="#CCCCCC", labelcolor=cfg["font_color"])
1244
- axes[1].set_xlabel("MAF", fontsize=cfg["font_size"], color=cfg["font_color"])
1245
- axes[1].set_ylabel("Count", fontsize=cfg["font_size"], color=cfg["font_color"])
1246
-
1247
- # Panel 2: Genomic inflation per model
1248
- lambdas = {}
1249
- for mname, (p, _, _) in all_results.items():
1250
- lam = np.median(stats.chi2.ppf(1-np.clip(p,1e-10,1),df=1)) / stats.chi2.ppf(0.5,df=1)
1251
- lambdas[mname] = lam
1252
- lam_cols = ["#59A14F" if v<=1.1 else "#F28E2B" if v<=1.3 else "#E15759"
1253
- for v in lambdas.values()]
1254
- bars = axes[2].bar(lambdas.keys(), lambdas.values(),
1255
- color=lam_cols, edgecolor='white', linewidth=0.5)
1256
- axes[2].axhline(1.0, color=cfg["font_color"], ls='--', lw=1, alpha=0.5)
1257
- axes[2].set_title("Genomic Inflation λ per Model",
1258
- color=cfg["font_color"], fontsize=cfg["font_size"]+1, fontweight='bold')
1259
- axes[2].tick_params(axis='x', rotation=30, labelsize=cfg["font_size"])
1260
- axes[2].set_ylabel("λ", fontsize=cfg["font_size"], color=cfg["font_color"])
1261
- for bar, lv in zip(bars, lambdas.values()):
1262
- axes[2].text(bar.get_x() + bar.get_width()/2, bar.get_height() + 0.01,
1263
- f"{lv:.3f}", ha='center', fontsize=cfg["font_size"]-2,
1264
- color=cfg["font_color"], va='bottom')
1265
-
1266
- # Panel 3: Significant SNPs (Bonferroni)
1267
- sig_counts = {}
1268
- for mname, (p, _, _) in all_results.items():
1269
- bonf = 0.05 / len(p)
1270
- sig_counts[mname] = int((p < bonf).sum())
1271
- cols_bar = [MODEL_COLORS.get(m, "#4E79A7") for m in sig_counts.keys()]
1272
- axes[3].bar(sig_counts.keys(), sig_counts.values(),
1273
- color=cols_bar, edgecolor='white', linewidth=0.5)
1274
- axes[3].set_title("Significant SNPs (Bonferroni)",
1275
- color=cfg["font_color"], fontsize=cfg["font_size"]+1, fontweight='bold')
1276
- axes[3].tick_params(axis='x', rotation=30, labelsize=cfg["font_size"])
1277
- axes[3].set_ylabel("Count", fontsize=cfg["font_size"], color=cfg["font_color"])
1278
-
1279
- # Panel 4: Model concordance heatmap
1280
- n_m = len(all_results)
1281
- model_names = list(all_results.keys())
1282
- concordance = np.eye(n_m)
1283
- for i in range(n_m):
1284
- for j in range(i+1, n_m):
1285
- lp_i = -np.log10(np.clip(all_results[model_names[i]][0], 1e-300, 1))
1286
- lp_j = -np.log10(np.clip(all_results[model_names[j]][0], 1e-300, 1))
1287
- r, _ = stats.spearmanr(lp_i, lp_j)
1288
- concordance[i,j] = concordance[j,i] = r
1289
- im = axes[4].imshow(concordance, cmap='RdYlGn', vmin=-1, vmax=1, aspect='auto')
1290
- axes[4].set_xticks(range(n_m)); axes[4].set_yticks(range(n_m))
1291
- axes[4].set_xticklabels(model_names, rotation=35,
1292
- fontsize=cfg["font_size"]-1, color=cfg["font_color"])
1293
- axes[4].set_yticklabels(model_names, fontsize=cfg["font_size"]-1,
1294
- color=cfg["font_color"])
1295
- for i in range(n_m):
1296
- for j in range(n_m):
1297
- axes[4].text(j, i, f"{concordance[i,j]:.2f}",
1298
- ha='center', va='center',
1299
- fontsize=cfg["font_size"]-1,
1300
- color='#111111' if abs(concordance[i,j])<0.7 else '#FFFFFF')
1301
- cbar2 = plt.colorbar(im, ax=axes[4])
1302
- cbar2.ax.tick_params(colors=cfg["font_color"])
1303
- axes[4].set_title("Model Concordance (Spearman ρ)",
1304
- color=cfg["font_color"], fontsize=cfg["font_size"]+1, fontweight='bold')
1305
-
1306
- # Panel 5: Threshold table per model (replaces scree plot)
1307
- axes[5].axis('off')
1308
- thresh_lines = [
1309
- f"{'Model':<10} {'Bonferroni':>14} {'Suggestive':>14}",
1310
- "─" * 42,
1311
- ]
1312
- for mname, (p, _, _) in all_results.items():
1313
- n_snps = len(p)
1314
- b_thr = 0.05 / n_snps
1315
- s_thr = 1.0 / n_snps
1316
- thresh_lines.append(
1317
- f"{mname:<10} {b_thr:>14.3e} {s_thr:>14.3e}"
1318
- )
1319
- thresh_lines.append("─" * 42)
1320
- thresh_lines.append(f" (Bonferroni = 0.05 / m)")
1321
- thresh_lines.append(f" (Suggestive = 1.0 / m)")
1322
-
1323
- summary_text = (
1324
- f"GWAS Summary\n\n"
1325
- f"Samples: {G_filt.shape[0]}\n"
1326
- f"SNPs (filt.): {G_filt.shape[1]}\n"
1327
- f"Models run: {n_m}\n"
1328
- f"Missing rate: {np.isnan(G_filt).mean():.1%}\n\n"
1329
- + "\n".join(thresh_lines)
1330
- )
1331
- axes[5].text(0.04, 0.96, summary_text,
1332
- ha='left', va='top', transform=axes[5].transAxes,
1333
- color=cfg["font_color"], fontsize=cfg["font_size"]-1,
1334
- fontfamily='monospace',
1335
- bbox=dict(boxstyle='round,pad=0.8', facecolor=cfg["panel_color"],
1336
- edgecolor="#CCCCCC", alpha=0.9))
1337
- axes[5].set_title("Pipeline Summary + Thresholds", color=cfg["font_color"],
1338
- fontsize=cfg["font_size"]+1, fontweight='bold')
1339
-
1340
- fig.suptitle("GWAS Analysis Dashboard",
1341
- color=cfg["font_color"], fontsize=cfg["font_size"]+4, fontweight='bold')
1342
- fig.tight_layout()
1343
- return fig
1344
-
1345
-
1346
- # ─────────────────────── EXCEL EXPORT ────────────────────────────────────────────
1347
- def export_results_excel(all_results, snp_filt, chr_filt, pos_filt, y,
1348
- G_filt, maf_vals, output_path, top_n=15):
1349
- wb = Workbook()
1350
- header_fill = PatternFill("solid", start_color="4A90D9", end_color="4A90D9")
1351
- sig_fill = PatternFill("solid", start_color="FFF3CD", end_color="FFF3CD")
1352
- alt_fill = PatternFill("solid", start_color="F8F9FA", end_color="F8F9FA")
1353
- header_font = Font(bold=True, color="FFFFFF", name="Calibri", size=11)
1354
- title_font = Font(bold=True, color="2C5F8A", name="Calibri", size=13)
1355
- thin_border = Border(
1356
- left=Side(style='thin', color='CCCCCC'),
1357
- right=Side(style='thin', color='CCCCCC'),
1358
- top=Side(style='thin', color='CCCCCC'),
1359
- bottom=Side(style='thin', color='CCCCCC')
1360
- )
1361
- bonf = 0.05 / len(list(all_results.values())[0][0])
1362
-
1363
- # Sheet 1: Summary
1364
- ws_sum = wb.active
1365
- ws_sum.title = "Summary"
1366
- ws_sum['A1'] = f"GWAS Complete Analysis Summary — Top {top_n} MTAs per Model"
1367
- ws_sum['A1'].font = Font(bold=True, color="2C5F8A", name="Calibri", size=16)
1368
- ws_sum.merge_cells('A1:H1')
1369
- headers_sum = ["Model", "N_SNPs_Tested", "Bonferroni_Threshold",
1370
- "Suggestive_Threshold","Sig_SNPs_Bonferroni",
1371
- "Sig_SNPs_Suggestive", "Genomic_Lambda", "Min_Pvalue"]
1372
- for col, h in enumerate(headers_sum, 1):
1373
- cell = ws_sum.cell(row=3, column=col, value=h)
1374
- cell.font = header_font; cell.fill = header_fill
1375
- cell.alignment = Alignment(horizontal='center'); cell.border = thin_border
1376
- ws_sum.column_dimensions[get_column_letter(col)].width = 24
1377
- for row_i, (mname, (pvals, betas, ses)) in enumerate(all_results.items(), 4):
1378
- lam = np.median(stats.chi2.ppf(1-np.clip(pvals,1e-10,1),df=1)) / stats.chi2.ppf(0.5,df=1)
1379
- n_snps = len(pvals)
1380
- bonf_t = 0.05 / n_snps
1381
- sug_t = 1.0 / n_snps
1382
- sig_bonf = int((pvals < bonf_t).sum())
1383
- sig_sug = int((pvals < sug_t).sum())
1384
- row_data = [mname, n_snps, f"{bonf_t:.2e}", f"{sug_t:.2e}",
1385
- sig_bonf, sig_sug, round(float(lam),4), float(np.min(pvals))]
1386
- fill = alt_fill if row_i%2==0 else PatternFill("solid",start_color="FFFFFF",end_color="FFFFFF")
1387
- for col, val in enumerate(row_data, 1):
1388
- cell = ws_sum.cell(row=row_i, column=col, value=val)
1389
- cell.fill = fill; cell.border = thin_border
1390
- cell.alignment = Alignment(horizontal='center')
1391
-
1392
- # Threshold explanation sheet
1393
- ws_exp = wb.create_sheet(title="Threshold_Explanation")
1394
- ws_exp['A1'] = "Threshold Calculation Explanation"
1395
- ws_exp['A1'].font = title_font
1396
- ws_exp.merge_cells('A1:C1')
1397
- explanation_rows = [
1398
- ("Bonferroni Threshold", "Formula", "0.05 / m where m = number of SNPs tested"),
1399
- ("Bonferroni Threshold", "Rationale", "Controls genome-wide Type I error rate at 5%."),
1400
- ("Bonferroni Threshold", "Assumption", "All SNP tests are independent (conservative)."),
1401
- ("Suggestive Threshold", "Formula", "1 / m where m = number of SNPs tested"),
1402
- ("Suggestive Threshold", "Rationale", "Expects ~1 false positive per genome scan."),
1403
- ("Suggestive Threshold", "Reference", "Lander & Kruglyak (1995) Nature Genetics."),
1404
- ("OLS Note", "Correction", "No population structure correction."),
1405
- ("MLM Note", "Correction", "Kinship matrix controls for relatedness."),
1406
- ("EMMAX Note", "Correction", "Efficient Mixed Model Association with variance components."),
1407
- ("FarmCPU Note", "Correction", "Iterative pseudo-QTN control reduces false positives."),
1408
- ("GEMMA Note", "Correction", "Genomic control (GC correction) applied for inflation."),
1409
- ]
1410
- ws_exp.cell(row=3, column=1, value="Threshold").font = header_font
1411
- ws_exp.cell(row=3, column=1).fill = header_fill
1412
- ws_exp.cell(row=3, column=2, value="Aspect").font = header_font
1413
- ws_exp.cell(row=3, column=2).fill = header_fill
1414
- ws_exp.cell(row=3, column=3, value="Details").font = header_font
1415
- ws_exp.cell(row=3, column=3).fill = header_fill
1416
- ws_exp.column_dimensions['A'].width = 22
1417
- ws_exp.column_dimensions['B'].width = 16
1418
- ws_exp.column_dimensions['C'].width = 60
1419
- for r_i, (t, a, d) in enumerate(explanation_rows, 4):
1420
- ws_exp.cell(row=r_i, column=1, value=t).border = thin_border
1421
- ws_exp.cell(row=r_i, column=2, value=a).border = thin_border
1422
- ws_exp.cell(row=r_i, column=3, value=d).border = thin_border
1423
-
1424
- # Sheet per model: Top N MTAs
1425
- for mname, (pvals, betas, ses) in all_results.items():
1426
- ws = wb.create_sheet(title=f"{mname}_Top{top_n}MTAs")
1427
- ws['A1'] = f"GWAS Results — {mname} Model — Top {top_n} MTAs"
1428
- ws['A1'].font = title_font
1429
- ws.merge_cells('A1:K1')
1430
- log_p = -np.log10(np.clip(pvals, 1e-300, 1))
1431
- t_stats = np.where(ses > 0, betas / (ses + 1e-10), 0.0)
1432
- reject_fdr, pvals_fdr, _, _ = multipletests(pvals, method='fdr_bh')
1433
- reject_bonf, _, _, _ = multipletests(pvals, method='bonferroni')
1434
- headers = ["Rank","SNP","Chr","Position","MAF","Beta","SE",
1435
- "T_statistic","P_value","neg_log10P","FDR_BH","Bonferroni_sig"]
1436
- for col, h in enumerate(headers, 1):
1437
- cell = ws.cell(row=3, column=col, value=h)
1438
- cell.font = header_font; cell.fill = header_fill
1439
- cell.alignment = Alignment(horizontal='center'); cell.border = thin_border
1440
- col_widths = [8, 25, 8, 12, 10, 12, 12, 12, 14, 12, 14, 16]
1441
- for i, w in enumerate(col_widths, 1):
1442
- ws.column_dimensions[get_column_letter(i)].width = w
1443
- top_idx = get_top_mta(pvals, top_n)
1444
- for rank, idx in enumerate(top_idx, 1):
1445
- is_sig = bool(reject_bonf[idx]) or pvals[idx] < 5e-8
1446
- fill = sig_fill if is_sig else (alt_fill if rank%2==0 else
1447
- PatternFill("solid",start_color="FFFFFF",end_color="FFFFFF"))
1448
- maf_v = maf_vals[idx] if idx < len(maf_vals) else np.nan
1449
- row_data = [
1450
- rank,
1451
- str(snp_filt[idx]) if idx < len(snp_filt) else "",
1452
- int(chr_filt[idx]) if idx < len(chr_filt) else "",
1453
- int(pos_filt[idx]) if idx < len(pos_filt) else "",
1454
- round(float(maf_v),4) if not np.isnan(maf_v) else "",
1455
- round(float(betas[idx]),6),
1456
- round(float(ses[idx]),6),
1457
- round(float(t_stats[idx]),4),
1458
- float(pvals[idx]),
1459
- round(float(log_p[idx]),4),
1460
- round(float(pvals_fdr[idx]),6),
1461
- "YES" if is_sig else "NO"
1462
- ]
1463
- for col, val in enumerate(row_data, 1):
1464
- cell = ws.cell(row=rank+3, column=col, value=val)
1465
- cell.fill = fill; cell.border = thin_border
1466
- cell.alignment = Alignment(horizontal='center')
1467
- if col == 9 and isinstance(val, float):
1468
- cell.number_format = '0.00E+00'
1469
-
1470
- # Sheet: Significant MTAs combined
1471
- ws_mta = wb.create_sheet(title="Significant_MTAs")
1472
- ws_mta['A1'] = f"Significant MTAs — All Models Combined — Top {top_n} per Model"
1473
- ws_mta['A1'].font = title_font
1474
- ws_mta.merge_cells('A1:N1')
1475
- headers_mta = ["Model","Rank","SNP","Chr","Position","MAF","Beta","SE",
1476
- "T_stat","P_value","neg_log10P","FDR_BH_p","Bonferroni_sig","PVE_%"]
1477
- for col, h in enumerate(headers_mta, 1):
1478
- cell = ws_mta.cell(row=3, column=col, value=h)
1479
- cell.font = header_font; cell.fill = header_fill
1480
- cell.alignment = Alignment(horizontal='center'); cell.border = thin_border
1481
- ws_mta.column_dimensions[get_column_letter(col)].width = 16
1482
- mta_row = 4
1483
- for mname, (pvals, betas, ses) in all_results.items():
1484
- log_p = -np.log10(np.clip(pvals, 1e-300, 1))
1485
- t_stats = np.where(ses > 0, betas / (ses + 1e-10), 0.0)
1486
- _, pvals_fdr, _, _ = multipletests(pvals, method='fdr_bh')
1487
- reject_bonf, _, _, _ = multipletests(pvals, method='bonferroni')
1488
- top_idx = get_top_mta(pvals, top_n)
1489
- pve_dict, _ = compute_pve(y, G_filt, pvals, betas)
1490
- for rank, idx in enumerate(top_idx, 1):
1491
- pve_val = round(pve_dict.get(int(idx), 0.0), 4)
1492
- maf_v = maf_vals[idx] if idx < len(maf_vals) else np.nan
1493
- row_data = [
1494
- mname, rank,
1495
- str(snp_filt[idx]) if idx < len(snp_filt) else "",
1496
- int(chr_filt[idx]) if idx < len(chr_filt) else "",
1497
- int(pos_filt[idx]) if idx < len(pos_filt) else "",
1498
- round(float(maf_v),4) if not np.isnan(maf_v) else "",
1499
- round(float(betas[idx]),6),
1500
- round(float(ses[idx]),6),
1501
- round(float(t_stats[idx]),4),
1502
- float(pvals[idx]),
1503
- round(float(log_p[idx]),4),
1504
- round(float(pvals_fdr[idx]),6),
1505
- "YES" if bool(reject_bonf[idx]) else "NO",
1506
- pve_val
1507
- ]
1508
- fill = sig_fill if mta_row%2==0 else PatternFill("solid",start_color="FFFDE7",end_color="FFFDE7")
1509
- for col, val in enumerate(row_data, 1):
1510
- cell = ws_mta.cell(row=mta_row, column=col, value=val)
1511
- cell.fill = fill; cell.border = thin_border
1512
- cell.alignment = Alignment(horizontal='center')
1513
- if col == 10 and isinstance(val, float):
1514
- cell.number_format = '0.00E+00'
1515
- mta_row += 1
1516
-
1517
- # Sheet: QTN Effects
1518
- ws_qtn = wb.create_sheet(title="QTN_Effects")
1519
- ws_qtn['A1'] = f"Quantitative Trait Nucleotides (QTNs) — Top {top_n} per Model"
1520
- ws_qtn['A1'].font = title_font
1521
- ws_qtn.merge_cells('A1:L1')
1522
- headers_qtn = ["Model","Rank","SNP","Chr","Position","MAF",
1523
- "QTN_Effect_Beta","SE","95%_CI_Lower","95%_CI_Upper","P_value","PVE_%"]
1524
- for col, h in enumerate(headers_qtn, 1):
1525
- cell = ws_qtn.cell(row=3, column=col, value=h)
1526
- cell.font = header_font; cell.fill = header_fill
1527
- cell.alignment = Alignment(horizontal='center'); cell.border = thin_border
1528
- ws_qtn.column_dimensions[get_column_letter(col)].width = 17
1529
- qtn_row = 4
1530
- for mname, (pvals, betas, ses) in all_results.items():
1531
- top_idx = get_top_mta(pvals, top_n)
1532
- pve_dict, _ = compute_pve(y, G_filt, pvals, betas)
1533
- for rank, idx in enumerate(top_idx, 1):
1534
- pve_val = round(pve_dict.get(int(idx), 0.0), 4)
1535
- maf_v = maf_vals[idx] if idx < len(maf_vals) else np.nan
1536
- ci_lower = float(betas[idx]) - 1.96 * float(ses[idx])
1537
- ci_upper = float(betas[idx]) + 1.96 * float(ses[idx])
1538
- fill = alt_fill if qtn_row%2==0 else PatternFill("solid",start_color="FFFFFF",end_color="FFFFFF")
1539
- row_data = [
1540
- mname, rank,
1541
- str(snp_filt[idx]) if idx < len(snp_filt) else "",
1542
- int(chr_filt[idx]) if idx < len(chr_filt) else "",
1543
- int(pos_filt[idx]) if idx < len(pos_filt) else "",
1544
- round(float(maf_v),4) if not np.isnan(maf_v) else "",
1545
- round(float(betas[idx]),6),
1546
- round(float(ses[idx]),6),
1547
- round(ci_lower,6), round(ci_upper,6),
1548
- float(pvals[idx]), pve_val
1549
- ]
1550
- for col, val in enumerate(row_data, 1):
1551
- cell = ws_qtn.cell(row=qtn_row, column=col, value=val)
1552
- cell.fill = fill; cell.border = thin_border
1553
- cell.alignment = Alignment(horizontal='center')
1554
- if col == 11 and isinstance(val, float):
1555
- cell.number_format = '0.00E+00'
1556
- qtn_row += 1
1557
-
1558
- # Sheet: SNP QC
1559
- ws_qc = wb.create_sheet(title="SNP_QC")
1560
- ws_qc['A1'] = "SNP Quality Control Statistics"
1561
- ws_qc['A1'].font = title_font
1562
- ws_qc.merge_cells('A1:F1')
1563
- headers_qc = ["SNP","Chr","Position","MAF","Call_Rate","Category"]
1564
- for col, h in enumerate(headers_qc, 1):
1565
- cell = ws_qc.cell(row=3, column=col, value=h)
1566
- cell.font = header_font; cell.fill = header_fill
1567
- cell.alignment = Alignment(horizontal='center'); cell.border = thin_border
1568
- ws_qc.column_dimensions[get_column_letter(col)].width = 20
1569
- call_rates = compute_call_rate(G_filt)
1570
- for row_i in range(len(snp_filt)):
1571
- maf_v = maf_vals[row_i] if row_i < len(maf_vals) else np.nan
1572
- cr_v = call_rates[row_i] if row_i < len(call_rates) else np.nan
1573
- cat = "Rare (<0.05)" if not np.isnan(maf_v) and maf_v < 0.05 else "Common"
1574
- fill = alt_fill if row_i%2==0 else PatternFill("solid",start_color="FFFFFF",end_color="FFFFFF")
1575
- row_data = [
1576
- str(snp_filt[row_i]),
1577
- int(chr_filt[row_i]) if row_i < len(chr_filt) else "",
1578
- int(pos_filt[row_i]) if row_i < len(pos_filt) else "",
1579
- round(float(maf_v),4) if not np.isnan(maf_v) else "",
1580
- round(float(cr_v),4) if not np.isnan(cr_v) else "",
1581
- cat
1582
- ]
1583
- for col, val in enumerate(row_data, 1):
1584
- cell = ws_qc.cell(row=row_i+4, column=col, value=val)
1585
- cell.fill = fill; cell.border = thin_border
1586
- cell.alignment = Alignment(horizontal='center')
1587
-
1588
- wb.save(output_path)
1589
- return output_path
1590
-
1591
-
1592
- def save_all_plots_zip(plot_dict, out_dir):
1593
- zip_path = os.path.join(out_dir, "gwas_plots.zip")
1594
- with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf:
1595
- for name, fig in plot_dict.items():
1596
- if fig is not None:
1597
- buf = io.BytesIO()
1598
- fig.savefig(buf, format="png", dpi=150, bbox_inches="tight",
1599
- facecolor=fig.get_facecolor())
1600
- buf.seek(0)
1601
- zf.writestr(f"{name}.png", buf.read())
1602
- return zip_path
1603
-
1604
-
1605
- # ─────────────────────── MAIN PIPELINE ───────────────────────────────────────────
1606
- def run_gwas(file_obj, text_input, selected_models, maf_threshold, top_n,
1607
- # Manhattan cfg
1608
- mh_w, mh_h, mh_fs, mh_fc, mh_ms, mh_alpha, mh_bg, mh_sig, mh_sug,
1609
- mh_dot, mh_panel,
1610
- # QQ cfg
1611
- qq_w, qq_h, qq_fs, qq_fc, qq_ms, qq_dot, qq_line, qq_fill, qq_bg, qq_panel,
1612
- # Circos cfg
1613
- ci_w, ci_h, ci_fs, ci_sig, ci_sug,
1614
- # LD cfg
1615
- ld_w, ld_h, ld_fs, ld_dot, ld_line,
1616
- # PCA cfg (dark)
1617
- pc_w, pc_h, pc_fs,
1618
- # Kinship cfg
1619
- ki_w, ki_h, ki_fs, ki_dot, ki_bg, ki_panel,
1620
- # Effect cfg
1621
- ef_w, ef_h, ef_fs, ef_pos, ef_neg, ef_fill, ef_bg,
1622
- # Comparison cfg
1623
- co_w, co_h, co_sig, co_sug,
1624
- # Dashboard cfg
1625
- db_w, db_h, db_dot):
1626
-
1627
- try:
1628
- df, snp_cols, chroms, positions = parse_data(file_obj, text_input)
1629
- except Exception as e:
1630
- return [None] * 13 + [f"❌ Data parsing error: {e}"]
1631
-
1632
- y = df["Phenotype"].values.astype(float)
1633
- ids = df["ID"].values
1634
- G_raw = df[snp_cols].values.astype(float)
1635
- G = impute_genotypes(G_raw)
1636
- n, m = G.shape
1637
-
1638
- maf_vals_all = compute_maf(G)
1639
- maf_thr = float(maf_threshold)
1640
- keep = maf_vals_all >= maf_thr
1641
- if keep.sum() < 2:
1642
- keep = np.ones(m, dtype=bool)
1643
-
1644
- G_filt = G[:, keep]
1645
- snp_filt = np.array(snp_cols)[keep]
1646
- chr_filt = chroms[keep] if len(chroms)==m else np.ones(G_filt.shape[1],dtype=int)
1647
- pos_filt = positions[keep] if len(positions)==m else np.arange(G_filt.shape[1])
1648
- maf_vals = maf_vals_all[keep]
1649
- K = build_kinship(G_filt)
1650
-
1651
- model_funcs = {
1652
- "OLS": lambda: ols_gwas(y, G_filt),
1653
- "MLM": lambda: mlm_gwas(y, G_filt, K),
1654
- "EMMAX": lambda: emmax_gwas(y, G_filt, K),
1655
- "FarmCPU": lambda: farmcpu_gwas(y, G_filt, K),
1656
- "GEMMA": lambda: gemma_gwas(y, G_filt, K),
1657
- }
1658
-
1659
- models_to_run = [mdl for mdl in (selected_models or list(model_funcs.keys()))
1660
- if mdl in model_funcs]
1661
- if not models_to_run:
1662
- models_to_run = list(model_funcs.keys())
1663
-
1664
- all_results = {}
1665
- primary_p = primary_b = primary_se = None
1666
-
1667
- for mname in models_to_run:
1668
- try:
1669
- p, b, se = model_funcs[mname]()
1670
- all_results[mname] = (p, b, se)
1671
- if primary_p is None:
1672
- primary_p, primary_b, primary_se = p, b, se
1673
- except Exception as ex:
1674
- print(f"Model {mname} failed: {ex}")
1675
-
1676
- if primary_p is None:
1677
- return [None] * 13 + ["❌ No models succeeded"]
1678
-
1679
- top_n = int(top_n)
1680
-
1681
- # ── Build per-plot configs ────────────────────────────────────────────────
1682
- # All build_cfg calls now correctly pass 'fc' as the 4th positional arg
1683
- cfg_mh = build_cfg(mh_w, mh_h, mh_fs, mh_fc,
1684
- bg=mh_bg, panel=mh_panel,
1685
- sig_col=mh_sig, sug_col=mh_sug,
1686
- marker_size=mh_ms, alpha=mh_alpha,
1687
- dot_col=mh_dot)
1688
-
1689
- cfg_qq = build_cfg(qq_w, qq_h, qq_fs, qq_fc,
1690
- bg=qq_bg, panel=qq_panel,
1691
- marker_size=qq_ms,
1692
- dot_col=qq_dot, line_col=qq_line, fill_col=qq_fill)
1693
-
1694
- cfg_ci = build_cfg(ci_w, ci_h, ci_fs, "#2D3142",
1695
- sig_col=ci_sig, sug_col=ci_sug)
1696
-
1697
- cfg_ld = build_cfg(ld_w, ld_h, ld_fs, "#2D3142",
1698
- dot_col=ld_dot, line_col=ld_line)
1699
-
1700
- # PCA — always dark theme; fc = TEXT_MAIN
1701
- cfg_pc = build_cfg(pc_w, pc_h, pc_fs, TEXT_MAIN,
1702
- gc=GRID_LINE, bg=BG_DARK, panel=PANEL_DARK,
1703
- sig_col=ACCENT_TEAL, sug_col=ACCENT_GOLD,
1704
- marker_size=55, alpha=0.80)
1705
-
1706
- cfg_ki = build_cfg(ki_w, ki_h, ki_fs, "#2D3142",
1707
- bg=ki_bg, panel=ki_panel, dot_col=ki_dot)
1708
-
1709
- cfg_ef = build_cfg(ef_w, ef_h, ef_fs, "#2D3142",
1710
- bg=ef_bg,
1711
- dot_col=ef_pos, line_col=ef_neg, fill_col=ef_fill)
1712
-
1713
- cfg_co = build_cfg(co_w, co_h, 7, "#2D3142",
1714
- sig_col=co_sig, sug_col=co_sug)
1715
-
1716
- cfg_db = build_cfg(db_w, db_h, 9, "#2D3142",
1717
- dot_col=db_dot)
1718
-
1719
- # Generate all plots
1720
- plot_dict = {}
1721
- plot_dict["01_Manhattan_Primary"] = plot_manhattan(
1722
- primary_p, chr_filt, pos_filt,
1723
- "Manhattan Plot", models_to_run[0], cfg_mh, top_n)
1724
- plot_dict["02_QQ_Primary"] = plot_qq_single(
1725
- primary_p, "QQ Plot", models_to_run[0],
1726
- MODEL_COLORS.get(models_to_run[0], "#A78BFA"), cfg_qq)
1727
- plot_dict["03_QQ_All_Models"] = plot_qq_all_models(all_results, cfg_qq)
1728
- plot_dict["04_QQ_Overlay"] = plot_qq_overlay(all_results, cfg_qq)
1729
- plot_dict["05_Circos"] = plot_circos(all_results, chr_filt, pos_filt, cfg_ci, top_n)
1730
- plot_dict["06_LD_Decay"] = plot_ld_decay(G_filt, pos_filt, cfg_ld)
1731
- plot_dict["07_PCA"] = plot_pca(G_filt, y, ids, cfg_pc)
1732
- plot_dict["08_Kinship"] = plot_kinship(K, ids, cfg_ki)
1733
- plot_dict["09_Effect_Sizes"] = plot_effect_sizes(primary_p, primary_b, snp_filt, cfg_ef, top_n)
1734
- plot_dict["10_All_Models_MH"] = plot_model_comparison_manhattan(
1735
- all_results, chr_filt, pos_filt, cfg_co, top_n)
1736
- plot_dict["11_Dashboard"] = plot_summary_dashboard(y, maf_vals, all_results, G_filt, cfg_db)
1737
-
1738
- def _pil(fig):
1739
- return fig_to_pil(fig) if fig is not None else None
1740
-
1741
- imgs = [_pil(plot_dict[k]) for k in sorted(plot_dict.keys())]
1742
-
1743
- # Save files
1744
- tmp_dir = tempfile.mkdtemp()
1745
- zip_path = save_all_plots_zip(plot_dict, tmp_dir)
1746
- excel_path = os.path.join(tmp_dir, "gwas_results_top15.xlsx")
1747
- export_results_excel(all_results, snp_filt, chr_filt, pos_filt,
1748
- y, G_filt, maf_vals, excel_path, top_n)
1749
- plt.close('all')
1750
-
1751
- # Build threshold explanation string
1752
- thresh_explanation = ""
1753
- for mname, (p, _, _) in all_results.items():
1754
- _, _, expl = compute_thresholds(len(p), mname)
1755
- thresh_explanation += expl + "\n"
1756
-
1757
- bonf = 0.05 / len(primary_p)
1758
- lambdas_str = "\n ".join([
1759
- f"{mdl}: λ={np.median(stats.chi2.ppf(1-np.clip(p,1e-10,1),df=1))/stats.chi2.ppf(0.5,df=1):.4f} "
1760
- f"sig(Bonf)={int((p<0.05/len(p)).sum())} sig(Sug)={int((p<1.0/len(p)).sum())}"
1761
- for mdl, (p, _, _) in all_results.items()
1762
- ])
1763
- lam = (np.median(stats.chi2.ppf(1-np.clip(primary_p,1e-10,1),df=1)) /
1764
- stats.chi2.ppf(0.5, df=1))
1765
-
1766
- summary = (
1767
- f"{'='*68}\n"
1768
- f" 🧬 GWAS ANALYSIS SUMMARY (Top {top_n} MTAs per Model)\n"
1769
- f"{'='*68}\n"
1770
- f" Samples: {n} | SNPs (raw): {m} | SNPs (filtered): {G_filt.shape[1]}\n"
1771
- f" MAF threshold: ≥{maf_thr:.2f} | Models: {', '.join(all_results.keys())}\n"
1772
- f"{'─'*68}\n"
1773
- f" PER-MODEL RESULTS:\n {lambdas_str}\n"
1774
- f"{'─'*68}\n"
1775
- f" Primary model ({models_to_run[0]}):\n"
1776
- f" Bonferroni threshold : {bonf:.2e} (-log₁₀ = {-np.log10(bonf):.2f})\n"
1777
- f" Suggestive threshold : {1/len(primary_p):.2e} (-log₁₀ = {-np.log10(1/len(primary_p)):.2f})\n"
1778
- f" Significant (Bonf.) : {int((primary_p<bonf).sum())}\n"
1779
- f" Significant (Sug.) : {int((primary_p<1/len(primary_p)).sum())}\n"
1780
- f" Genomic Inflation λ : {lam:.4f}\n"
1781
- f"{'─'*68}\n"
1782
- f" 📌 THRESHOLD EXPLANATIONS (see Excel sheet 'Threshold_Explanation'):\n\n"
1783
- + thresh_explanation +
1784
- f"{'─'*68}\n"
1785
- f" 📥 Excel: gwas_results_top15.xlsx\n"
1786
- f" 🖼 Plots: gwas_plots.zip ({len(plot_dict)} PNG files)\n"
1787
- f"{'='*68}\n"
1788
- )
1789
-
1790
- return imgs[:11] + [excel_path, zip_path, summary]
1791
-
1792
-
1793
- # ─────────────────────── CSS ──────────────────────────────────────────────────────
1794
- CSS = """
1795
- @import url('https://fonts.googleapis.com/css2?family=DM+Sans:wght@300;400;500;600&family=DM+Mono:wght@400;500&display=swap');
1796
- * { box-sizing: border-box; }
1797
- body, .gradio-container { background:#F7F8FC!important; font-family:'DM Sans',sans-serif!important; color:#2D3142!important; }
1798
- .gradio-container { max-width:1500px!important; margin:0 auto!important; }
1799
- .gwas-header { background:linear-gradient(135deg,#E8F4FD 0%,#EDE9F8 50%,#FDF0F8 100%); border:1px solid #D6E8F5; border-radius:18px; padding:24px 32px; margin-bottom:20px; box-shadow:0 2px 20px rgba(100,120,200,0.08); }
1800
- .gwas-header h1 { font-size:22px!important; font-weight:600!important; color:#2C5F8A!important; margin:0 0 4px 0!important; }
1801
- .gwas-header p { color:#6B7A99!important; font-size:13px!important; margin:3px 0!important; }
1802
- .gr-panel, .gr-box, .block, .panel { background:#FFFFFF!important; border:1px solid #E8ECF4!important; border-radius:14px!important; box-shadow:0 1px 8px rgba(60,80,140,0.06)!important; }
1803
- label, .label-wrap span { color:#5A6480!important; font-size:11px!important; font-weight:500!important; text-transform:uppercase!important; letter-spacing:0.5px!important; }
1804
- input, textarea, select { background:#FAFBFF!important; color:#2D3142!important; border:1px solid #DDE2F0!important; border-radius:8px!important; font-size:12px!important; }
1805
- button.primary { background:linear-gradient(135deg,#5BA8E5 0%,#7C6FCD 100%)!important; border:none!important; border-radius:12px!important; color:#FFFFFF!important; font-weight:600!important; font-size:14px!important; padding:12px 24px!important; box-shadow:0 4px 16px rgba(91,168,229,0.35)!important; width:100%!important; }
1806
- .tab-nav { background:#F0F3FB!important; border-radius:10px!important; padding:3px!important; border:1px solid #E4E8F5!important; overflow-x:auto!important; }
1807
- .tab-nav button { color:#6B7A99!important; font-size:11px!important; font-weight:500!important; border-radius:8px!important; padding:6px 12px!important; border:none!important; background:transparent!important; white-space:nowrap!important; }
1808
- .tab-nav button.selected, .tab-nav button:hover { background:#FFFFFF!important; color:#5BA8E5!important; box-shadow:0 1px 6px rgba(91,168,229,0.2)!important; }
1809
- .summary-box textarea { font-family:'DM Mono',monospace!important; font-size:10px!important; background:#F8F9FF!important; }
1810
- ::-webkit-scrollbar { width:5px; height:5px; }
1811
- ::-webkit-scrollbar-thumb { background:#C8D0E7; border-radius:4px; }
1812
- .cfg-panel { background:#F4F6FF!important; border-radius:10px!important; padding:10px!important; border:1px solid #DDE2F0!important; }
1813
- """
1814
-
1815
- SAMPLE_DATA = """ID,Phenotype,chr1_134521_SNP1,chr1_134810_SNP2,chr1_178766_SNP3,chr1_210328_SNP4
1816
- chromosome,1,1,1,1
1817
- IRRI-1,25.34,0,0,0,2
1818
- IRRI-75,23.34,0,0,0,0
1819
- IRRI-84,26.67,2,0,2,0
1820
- IRRI-93,23,0,0,0,1
1821
- IRRI-9,28.34,0,0,0,0
1822
- IRRI-17,18.67,0,0,0,0
1823
- IRRI-25,20,2,0,2,0
1824
- IRRI-34,37,0,0,0,0
1825
- IRRI-42,30.67,0,0,0,0
1826
- IRRI-50,22,0,0,0,2"""
1827
-
1828
- # ─────────────────────── GRADIO INTERFACE ────────────────────────────────────────
1829
- with gr.Blocks(css=CSS, title="🧬 GWAS Pipeline v3", theme=gr.themes.Base()) as demo:
1830
-
1831
- gr.HTML("""
1832
- <div class="gwas-header">
1833
- <h1>🧬 GWAS Analysis Pipeline v3 — Chr Labels · Threshold Explanations · QQ Regression · Dark PCA · No Scree</h1>
1834
- <p>OLS · MLM · EMMAX · FarmCPU · GEMMA &nbsp;|&nbsp; Bonferroni & Suggestive on ALL plots · Full Color Customization</p>
1835
- <p style="font-size:12px;color:#8892B0;">Circos with Chr numbers on bands · QQ with regression line · PCA dark theme · Scree plot removed</p>
1836
- </div>
1837
- """)
1838
-
1839
- with gr.Row(equal_height=False):
1840
- with gr.Column(scale=1, min_width=300):
1841
- gr.HTML('<div style="font-size:11px;font-weight:600;color:#8892B0;text-transform:uppercase;letter-spacing:1px;padding:6px 0 3px;border-bottom:1px solid #E8ECF4;margin-bottom:8px">📂 Data Input</div>')
1842
- file_in = gr.File(label="Upload CSV / TSV / TXT", file_types=[".csv",".tsv",".txt"])
1843
- text_in = gr.Textbox(label="Or paste CSV data", lines=6, value=SAMPLE_DATA)
1844
-
1845
- gr.HTML('<div style="font-size:11px;font-weight:600;color:#8892B0;text-transform:uppercase;letter-spacing:1px;padding:6px 0 3px;border-bottom:1px solid #E8ECF4;margin-bottom:8px;margin-top:12px">⚙️ Models & Filters</div>')
1846
- model_sel = gr.CheckboxGroup(
1847
- choices=ALL_MODELS, value=ALL_MODELS,
1848
- label="Select models (5 efficient)")
1849
- maf_thr = gr.Slider(0, 0.5, 0.05, 0.01, label="MAF Threshold")
1850
- top_n_sl = gr.Slider(5, 50, 15, 1, label="Top N MTAs to report per model")
1851
-
1852
- run_btn = gr.Button("🚀 Run Complete GWAS Pipeline", variant="primary")
1853
-
1854
- gr.HTML('<div style="font-size:11px;font-weight:600;color:#8892B0;text-transform:uppercase;letter-spacing:1px;padding:6px 0 3px;border-bottom:1px solid #E8ECF4;margin-bottom:8px;margin-top:12px">📥 Downloads</div>')
1855
- excel_out = gr.File(label="📊 Excel (MTAs · Thresholds · PVE · QTN · All Models)", interactive=False)
1856
- zip_out = gr.File(label="🖼 All Plots as PNG (ZIP)", interactive=False)
1857
-
1858
- with gr.Column(scale=2):
1859
- gr.HTML('<div style="font-size:11px;font-weight:600;color:#8892B0;text-transform:uppercase;letter-spacing:1px;padding:6px 0 3px;border-bottom:1px solid #E8ECF4;margin-bottom:8px">📊 Analysis Summary + Threshold Explanations</div>')
1860
- summary_out = gr.Textbox(label="", lines=32, show_label=False, elem_classes=["summary-box"])
1861
-
1862
- # ── Plot Customization Panels ──────────────────────────────────────────────
1863
- gr.HTML('<div style="font-size:11px;font-weight:600;color:#8892B0;text-transform:uppercase;letter-spacing:1px;padding:12px 0 4px;border-bottom:1px solid #E8ECF4;margin-bottom:8px">🎨 Plot Customization (Full Color Control)</div>')
1864
-
1865
- with gr.Accordion("🗺 Manhattan Plot Options", open=False):
1866
- gr.HTML('<p style="font-size:11px;color:#8892B0;margin:4px 0">Both Bonferroni (0.05/m) and Suggestive (1/m) thresholds shown on all Manhattan plots.</p>')
1867
- with gr.Row():
1868
- mh_w = gr.Slider(8, 24, 16, 1, label="Width")
1869
- mh_h = gr.Slider(3, 12, 5, 0.5, label="Height")
1870
- mh_fs = gr.Slider(6, 18, 9, 1, label="Font Size")
1871
- with gr.Row():
1872
- mh_fc = gr.ColorPicker(value="#2D3142", label="Font Color")
1873
- mh_sig = gr.ColorPicker(value="#E15759", label="Bonferroni Line Color")
1874
- mh_sug = gr.ColorPicker(value="#4E79A7", label="Suggestive Line Color")
1875
- with gr.Row():
1876
- mh_ms = gr.Slider(2, 60, 12, 1, label="Marker Size")
1877
- mh_alpha= gr.Slider(0.1, 1.0, 0.75, 0.05, label="Marker Alpha")
1878
- with gr.Row():
1879
- mh_bg = gr.ColorPicker(value="#FFFFFF", label="Background Color")
1880
- mh_panel= gr.ColorPicker(value="#FAFBFF", label="Panel Color")
1881
- mh_dot = gr.ColorPicker(value="#4E79A7", label="Dot Color (overridden by chr colors)")
1882
-
1883
- with gr.Accordion("📈 QQ Plot Options", open=False):
1884
- gr.HTML('<p style="font-size:11px;color:#8892B0;margin:4px 0">QQ plots include 95% CI band, regression line (slope + R²), and λ inflation factor.</p>')
1885
- with gr.Row():
1886
- qq_w = gr.Slider(5, 16, 7, 0.5, label="Width")
1887
- qq_h = gr.Slider(5, 16, 7, 0.5, label="Height")
1888
- qq_fs = gr.Slider(6, 18, 10, 1, label="Font Size")
1889
- with gr.Row():
1890
- qq_fc = gr.ColorPicker(value="#2D3142", label="Font Color")
1891
- qq_ms = gr.Slider(5, 80, 22, 1, label="Marker Size")
1892
- with gr.Row():
1893
- qq_dot = gr.ColorPicker(value="#A78BFA", label="Dot Color")
1894
- qq_line = gr.ColorPicker(value="#E15759", label="Regression Line Color")
1895
- qq_fill = gr.ColorPicker(value="#A78BFA", label="CI Fill Color")
1896
- with gr.Row():
1897
- qq_bg = gr.ColorPicker(value="#FFFFFF", label="Background Color")
1898
- qq_panel= gr.ColorPicker(value="#FAFBFF", label="Panel Color")
1899
-
1900
- with gr.Accordion("🔵 Circos Plot Options", open=False):
1901
- gr.HTML('<p style="font-size:11px;color:#8892B0;margin:4px 0">Chr numbers shown on outer bands. Bonferroni (dashed) and Suggestive (dotted) threshold rings shown per model.</p>')
1902
- with gr.Row():
1903
- ci_w = gr.Slider(8, 22, 14, 1, label="Width")
1904
- ci_h = gr.Slider(8, 22, 14, 1, label="Height")
1905
- ci_fs = gr.Slider(5, 16, 8, 1, label="Font Size")
1906
- with gr.Row():
1907
- ci_sig = gr.ColorPicker(value="#E15759", label="Bonferroni Ring Color")
1908
- ci_sug = gr.ColorPicker(value="#4E79A7", label="Suggestive Ring Color")
1909
-
1910
- with gr.Accordion("🔗 LD Decay Options", open=False):
1911
- with gr.Row():
1912
- ld_w = gr.Slider(8, 24, 16, 1, label="Width")
1913
- ld_h = gr.Slider(3, 12, 6, 0.5, label="Height")
1914
- ld_fs = gr.Slider(6, 18, 9, 1, label="Font Size")
1915
- with gr.Row():
1916
- ld_dot = gr.ColorPicker(value="#4E79A7", label="Dot Color")
1917
- ld_line = gr.ColorPicker(value="#E15759", label="Trend Line Color")
1918
-
1919
- with gr.Accordion("🔬 PCA Options (Dark Theme)", open=False):
1920
- gr.HTML('<p style="font-size:11px;color:#8892B0;margin:4px 0">PCA uses a dark background by design. Scree plot removed. Showing PC1v2, PC2v3, Population Structure.</p>')
1921
- with gr.Row():
1922
- pc_w = gr.Slider(8, 22, 14, 1, label="Width")
1923
- pc_h = gr.Slider(4, 14, 10, 1, label="Height")
1924
- pc_fs = gr.Slider(6, 18, 9, 1, label="Font Size")
1925
-
1926
- with gr.Accordion("👨‍👩‍👧 Kinship / Dendrogram Options", open=False):
1927
- gr.HTML('<p style="font-size:11px;color:#8892B0;margin:4px 0">For >50 samples, dendrogram auto-truncates to last 30 nodes.</p>')
1928
- with gr.Row():
1929
- ki_w = gr.Slider(8, 22, 14, 1, label="Width")
1930
- ki_h = gr.Slider(6, 20, 12, 1, label="Height")
1931
- ki_fs = gr.Slider(6, 18, 9, 1, label="Font Size")
1932
- with gr.Row():
1933
- ki_dot = gr.ColorPicker(value="#4E79A7", label="Dot/Bar Color")
1934
- ki_bg = gr.ColorPicker(value="#FFFFFF", label="Background Color")
1935
- ki_panel= gr.ColorPicker(value="#FAFBFF", label="Panel Color")
1936
-
1937
- with gr.Accordion("⚖ Effect Sizes Options", open=False):
1938
- with gr.Row():
1939
- ef_w = gr.Slider(8, 22, 14, 1, label="Width")
1940
- ef_h = gr.Slider(5, 18, 10, 1, label="Height")
1941
- ef_fs = gr.Slider(6, 18, 9, 1, label="Font Size")
1942
- with gr.Row():
1943
- ef_pos = gr.ColorPicker(value="#4E79A7", label="Positive Effect Color")
1944
- ef_neg = gr.ColorPicker(value="#E15759", label="Negative Effect Color")
1945
- ef_fill = gr.ColorPicker(value="#A78BFA", label="Distribution Fill Color")
1946
- ef_bg = gr.ColorPicker(value="#FFFFFF", label="Background Color")
1947
-
1948
- with gr.Accordion("🔄 All-Models Manhattan Options", open=False):
1949
- gr.HTML('<p style="font-size:11px;color:#8892B0;margin:4px 0">Both thresholds shown on each model subplot.</p>')
1950
- with gr.Row():
1951
- co_w = gr.Slider(8, 24, 16, 1, label="Width")
1952
- co_h = gr.Slider(2, 8, 3.5, 0.5, label="Height per model")
1953
- with gr.Row():
1954
- co_sig = gr.ColorPicker(value="#E15759", label="Bonferroni Line Color")
1955
- co_sug = gr.ColorPicker(value="#4E79A7", label="Suggestive Line Color")
1956
-
1957
- with gr.Accordion("📊 Dashboard Options", open=False):
1958
- with gr.Row():
1959
- db_w = gr.Slider(8, 24, 15, 1, label="Width")
1960
- db_h = gr.Slider(5, 18, 10, 1, label="Height")
1961
- db_dot = gr.ColorPicker(value="#4E79A7", label="Bar/Dot Color")
1962
-
1963
- # ── Visualization Tabs ────────────────────────────────────────────────────
1964
- gr.HTML('<div style="font-size:11px;font-weight:600;color:#8892B0;text-transform:uppercase;letter-spacing:1px;padding:12px 0 4px;border-bottom:1px solid #E8ECF4;margin-bottom:8px">🖼 Visualizations</div>')
1965
- with gr.Tabs():
1966
- with gr.Tab("🗺 Manhattan"):
1967
- img1 = gr.Image(type="pil", label="Manhattan — Primary Model (Chr labels · both thresholds · ◆ = Top MTAs)")
1968
- with gr.Tab("📈 QQ Primary"):
1969
- img2 = gr.Image(type="pil", label="QQ Plot — Regression line + CI + λ")
1970
- with gr.Tab("📈 QQ All Models"):
1971
- img3 = gr.Image(type="pil", label="QQ Plots — All Models with Regression")
1972
- with gr.Tab("📊 QQ Overlay"):
1973
- img4 = gr.Image(type="pil", label="QQ Overlay (solid=obs, dashed=regression per model)")
1974
- with gr.Tab("🔵 Circos"):
1975
- img5 = gr.Image(type="pil", label="Circos — Chr numbers on bands · Threshold rings · Ribbons")
1976
- with gr.Tab("🔗 LD Decay"):
1977
- img6 = gr.Image(type="pil", label="LD Decay (bp & Mb)")
1978
- with gr.Tab("🔬 PCA (Dark)"):
1979
- img7 = gr.Image(type="pil", label="PCA — Dark theme (PC1v2, PC2v3, Population Structure)")
1980
- with gr.Tab("👨‍👩‍👧 Kinship"):
1981
- img8 = gr.Image(type="pil", label="Kinship & Dendrogram")
1982
- with gr.Tab("⚖ Effect Sizes"):
1983
- img9 = gr.Image(type="pil", label="Effect Sizes & Volcano Plot")
1984
- with gr.Tab("🔄 All Models MH"):
1985
- img10 = gr.Image(type="pil", label="All-Models Manhattan (Chr labels · both thresholds)")
1986
- with gr.Tab("📊 Dashboard"):
1987
- img11 = gr.Image(type="pil", label="Summary Dashboard (Threshold table replaces Scree plot)")
1988
-
1989
- all_inputs = [
1990
- file_in, text_in, model_sel, maf_thr, top_n_sl,
1991
- # Manhattan
1992
- mh_w, mh_h, mh_fs, mh_fc, mh_ms, mh_alpha, mh_bg, mh_sig, mh_sug,
1993
- mh_dot, mh_panel,
1994
- # QQ
1995
- qq_w, qq_h, qq_fs, qq_fc, qq_ms, qq_dot, qq_line, qq_fill, qq_bg, qq_panel,
1996
- # Circos
1997
- ci_w, ci_h, ci_fs, ci_sig, ci_sug,
1998
- # LD
1999
- ld_w, ld_h, ld_fs, ld_dot, ld_line,
2000
- # PCA
2001
- pc_w, pc_h, pc_fs,
2002
- # Kinship
2003
- ki_w, ki_h, ki_fs, ki_dot, ki_bg, ki_panel,
2004
- # Effect
2005
- ef_w, ef_h, ef_fs, ef_pos, ef_neg, ef_fill, ef_bg,
2006
- # Comparison
2007
- co_w, co_h, co_sig, co_sug,
2008
- # Dashboard
2009
- db_w, db_h, db_dot,
2010
- ]
2011
-
2012
- run_btn.click(
2013
- run_gwas,
2014
- inputs=all_inputs,
2015
- outputs=[img1, img2, img3, img4, img5, img6, img7,
2016
- img8, img9, img10, img11, excel_out, zip_out, summary_out]
2017
- )
2018
-
2019
- if __name__ == "__main__":
2020
- demo.launch(share=False, server_port=7860)