diff --git "a/app.py" "b/app.py" --- "a/app.py" +++ "b/app.py" @@ -6,7 +6,6 @@ matplotlib.use("Agg") import matplotlib.pyplot as plt import matplotlib.patches as mpatches from matplotlib.colors import LinearSegmentedColormap -from matplotlib.patches import FancyArrowPatch import matplotlib.gridspec as gridspec import warnings warnings.filterwarnings("ignore") @@ -15,14 +14,16 @@ from scipy import stats from scipy.cluster.hierarchy import dendrogram, linkage from sklearn.decomposition import PCA from sklearn.preprocessing import StandardScaler -from sklearn.linear_model import LinearRegression, Ridge, Lasso +from sklearn.linear_model import LinearRegression from sklearn.manifold import MDS, TSNE -from scipy.spatial.distance import pdist -import io, re, itertools -from io import StringIO from statsmodels.stats.multitest import multipletests +import io, re, os, zipfile, tempfile +from io import StringIO +from openpyxl import Workbook +from openpyxl.styles import Font, PatternFill, Alignment, Border, Side +from openpyxl.utils import get_column_letter -# ─────────────────────────── REFINED DARK-SCIENCE THEME ────────────────────────── +# ─────────────────────── PLOT COLORS (unchanged dark-science theme) ─────────────── BG_DARK = "#0D1117" PANEL_DARK = "#161B22" PANEL_MID = "#21262D" @@ -38,19 +39,19 @@ ACCENT_ORG = "#FB923C" TEXT_MAIN = "#E6EDF3" TEXT_DIM = "#8B949E" GRID_LINE = "#30363D" -SIG_COLOR = "#F59E0B" # Gold dot for significant MTAs +SIG_COLOR = "#F59E0B" MODEL_COLORS = { - "OLS": "#60A5FA", - "MLM": "#2DD4BF", - "GLM": "#F87171", - "CMLM": "#A78BFA", - "BLINK": "#F59E0B", - "FarmCPU": "#84CC16", - "EMMAX": "#F472B6", - "PLINK": "#22D3EE", - "GAPIT3": "#FB923C", - "GEMMA": "#E879F9", + "OLS": "#60A5FA", + "MLM": "#2DD4BF", + "GLM": "#F87171", + "CMLM": "#A78BFA", + "BLINK": "#F59E0B", + "FarmCPU": "#84CC16", + "EMMAX": "#F472B6", + "PLINK": "#22D3EE", + "GAPIT3": "#FB923C", + "GEMMA": "#E879F9", } CHR_PALETTE = [ @@ -72,8 +73,7 @@ def style_fig(fig): ax.grid(color=GRID_LINE, linewidth=0.4, linestyle="--", alpha=0.5) return fig -# ─────────────────────────── DATA PARSING ───────────────────────────── - +# ─────────────────────── DATA PARSING ──────────────────────────────────────────── def parse_data(file_obj=None, text_input=None): raw = None if file_obj is not None: @@ -89,38 +89,34 @@ def parse_data(file_obj=None, text_input=None): else: raise ValueError("No data provided.") - has_chrom_row = False chrom_info = {} - if len(raw) > 1: second_row = raw.iloc[1].astype(str) chrom_vals = second_row.iloc[2:].astype(str) if len(chrom_vals) > 0 and chrom_vals.str.match(r'^\d+$').all(): - has_chrom_row = True for i, col in enumerate(raw.columns[2:]): try: chrom_info[col] = int(second_row.iloc[2 + i]) except: chrom_info[col] = 1 raw = raw.drop(index=1).reset_index(drop=True) - + cols = list(raw.columns) id_col = cols[0] phen_col = cols[1] snp_cols = cols[2:] - + raw = raw[pd.to_numeric(raw[phen_col], errors="coerce").notna()].copy() raw[phen_col] = raw[phen_col].astype(float) - geno = raw[snp_cols].apply(pd.to_numeric, errors="coerce") geno = geno.where(~geno.isin([-1, -9, -99, -999]), np.nan) - + df = pd.DataFrame() df["ID"] = raw[id_col].values df["Phenotype"] = raw[phen_col].values for c in snp_cols: df[c] = geno[c].values - + chroms, positions = [], [] for m in snp_cols: if m in chrom_info: @@ -136,11 +132,10 @@ def parse_data(file_obj=None, text_input=None): num = re.findall(r"\d+", m_clean) chroms.append(int(num[0]) if num else 1) positions.append(int(num[1]) if len(num) > 1 else len(positions) + 1) - - return df, snp_cols, np.array(chroms), np.array(positions) -# ─────────────────────────── UTILITY FUNCTIONS ─────────────────────────────────── + return df, snp_cols, np.array(chroms), np.array(positions) +# ─────────────────────── UTILITY ───────────────────────────────────────────────── def impute_genotypes(geno_matrix): mat = geno_matrix.copy().astype(float) for j in range(mat.shape[1]): @@ -152,8 +147,7 @@ def impute_genotypes(geno_matrix): def compute_maf(G): freqs = np.nanmean(G, axis=0) / 2 - maf = np.where(freqs > 0.5, 1 - freqs, freqs) - return maf + return np.where(freqs > 0.5, 1 - freqs, freqs) def compute_heterozygosity(G): return np.mean(G == 1, axis=1) if G.shape[1] > 0 else np.zeros(G.shape[0]) @@ -167,8 +161,29 @@ def build_kinship(G): denom = 2 * np.sum(p * (1 - p)) if denom == 0: denom = 1 - K = Z @ Z.T / denom - return K + return Z @ Z.T / denom + +def compute_pve(y, G, pvals, betas, threshold=0.05): + """Compute Phenotypic Variance Explained (PVE) for significant SNPs""" + bonf = threshold / len(pvals) + sig_idx = np.where(pvals < bonf)[0] + pve_dict = {} + total_var = np.var(y) + for idx in sig_idx: + x = G[:, idx] + mask = ~np.isnan(x) + if mask.sum() < 4: + pve_dict[idx] = 0.0 + continue + corr = np.corrcoef(x[mask], y[mask])[0, 1] + pve_dict[idx] = corr**2 * 100 # as percentage + return pve_dict, total_var + +def fig_to_png_bytes(fig): + buf = io.BytesIO() + fig.savefig(buf, format="png", dpi=150, bbox_inches="tight", facecolor=fig.get_facecolor()) + buf.seek(0) + return buf.read() def fig_to_pil(fig): buf = io.BytesIO() @@ -177,24 +192,20 @@ def fig_to_pil(fig): from PIL import Image return Image.open(buf).copy() -# ─────────────────────────── 10 STATISTICAL MODELS ─────────────────────────────── - -# Model 1: OLS +# ─────────────────────── 10 STATISTICAL MODELS ─────────────────────────────────── def ols_gwas(y, G): n, m = G.shape - pvals = np.ones(m) - betas = np.zeros(m) + pvals = np.ones(m); betas = np.zeros(m); ses = np.zeros(m) for j in range(m): x = G[:, j] - G[:, j].mean() if x.std() < 1e-8: continue - slope, _, _, p, _ = stats.linregress(x, y) - pvals[j] = p; betas[j] = slope - return pvals, betas + slope, _, _, p, se = stats.linregress(x, y) + pvals[j] = p; betas[j] = slope; ses[j] = se + return pvals, betas, ses -# Model 2: MLM def mlm_gwas(y, G, K): n, m = G.shape - pvals = np.ones(m); betas = np.zeros(m) + pvals = np.ones(m); betas = np.zeros(m); ses = np.zeros(m) eigvals, eigvecs = np.linalg.eigh(K + np.eye(n) * 1e-6) n_pcs = min(3, n - 2) Q = eigvecs[:, np.argsort(eigvals)[::-1][:n_pcs]] @@ -203,14 +214,13 @@ def mlm_gwas(y, G, K): x = G[:, j] x_res = x - LinearRegression().fit(Q, x).predict(Q) if x_res.std() < 1e-8: continue - slope, _, _, p, _ = stats.linregress(x_res, y_res) - pvals[j] = p; betas[j] = slope - return pvals, betas + slope, _, _, p, se = stats.linregress(x_res, y_res) + pvals[j] = p; betas[j] = slope; ses[j] = se + return pvals, betas, ses -# Model 3: GLM (PCA-corrected) def glm_gwas(y, G): n, m = G.shape - pvals = np.ones(m); betas = np.zeros(m) + pvals = np.ones(m); betas = np.zeros(m); ses = np.zeros(m) n_pcs = min(3, n - 2) PCs = PCA(n_components=n_pcs).fit_transform(StandardScaler().fit_transform(G)) y_adj = y - LinearRegression().fit(PCs, y).predict(PCs) @@ -218,14 +228,13 @@ def glm_gwas(y, G): x = G[:, j] if x.std() < 1e-8: continue x_adj = x - LinearRegression().fit(PCs, x).predict(PCs) - slope, _, _, p, _ = stats.linregress(x_adj, y_adj) - pvals[j] = p; betas[j] = slope - return pvals, betas + slope, _, _, p, se = stats.linregress(x_adj, y_adj) + pvals[j] = p; betas[j] = slope; ses[j] = se + return pvals, betas, ses -# Model 4: CMLM def cmlm_gwas(y, G, K): n, m = G.shape - pvals = np.ones(m); betas = np.zeros(m) + pvals = np.ones(m); betas = np.zeros(m); ses = np.zeros(m) n_groups = min(3, n) groups = np.array([i % n_groups for i in range(n)]) group_means = np.column_stack([K[:, np.where(groups == g)[0]].mean(axis=1) for g in range(n_groups)]) @@ -234,46 +243,41 @@ def cmlm_gwas(y, G, K): x = G[:, j] x_res = x - LinearRegression().fit(group_means, x).predict(group_means) if x_res.std() < 1e-8: continue - slope, _, _, p, _ = stats.linregress(x_res, y_res) - pvals[j] = p; betas[j] = slope - return pvals, betas + slope, _, _, p, se = stats.linregress(x_res, y_res) + pvals[j] = p; betas[j] = slope; ses[j] = se + return pvals, betas, ses -# Model 5: BLINK def blink_gwas(y, G): n, m = G.shape - pvals = np.ones(m); betas = np.zeros(m) - ols_p, _ = ols_gwas(y, G) + pvals = np.ones(m); betas = np.zeros(m); ses = np.zeros(m) + ols_p, _, _ = ols_gwas(y, G) top_idx = np.argsort(ols_p)[:min(3, m)] covars = G[:, top_idx] y_adj = y - LinearRegression().fit(covars, y).predict(covars) for j in range(m): x = G[:, j] if x.std() < 1e-8: continue - slope, _, _, p, _ = stats.linregress(x, y_adj) - pvals[j] = p; betas[j] = slope - return pvals, betas + slope, _, _, p, se = stats.linregress(x, y_adj) + pvals[j] = p; betas[j] = slope; ses[j] = se + return pvals, betas, ses -# Model 6: FarmCPU def farmcpu_gwas(y, G, K): n, m = G.shape - pvals = np.ones(m); betas = np.zeros(m) - mlm_p, _ = mlm_gwas(y, G, K) + pvals = np.ones(m); betas = np.zeros(m); ses = np.zeros(m) + mlm_p, _, _ = mlm_gwas(y, G, K) qtn_idx = np.argsort(mlm_p)[:min(3, m)] qtns = G[:, qtn_idx] y_adj = y - LinearRegression().fit(qtns, y).predict(qtns) for j in range(m): x = G[:, j] if x.std() < 1e-8: continue - slope, _, _, p, _ = stats.linregress(x, y_adj) - pvals[j] = p; betas[j] = slope - return pvals, betas + slope, _, _, p, se = stats.linregress(x, y_adj) + pvals[j] = p; betas[j] = slope; ses[j] = se + return pvals, betas, ses -# Model 7: EMMAX (Efficient Mixed-Model Association eXpedited) def emmax_gwas(y, G, K): - """EMMAX: uses variance components estimation with kinship""" n, m = G.shape - pvals = np.ones(m); betas = np.zeros(m) - # Estimate variance components via REML approximation + pvals = np.ones(m); betas = np.zeros(m); ses = np.zeros(m) tau = np.var(y) * 0.5 sigma = np.var(y) * 0.5 V = tau * K + sigma * np.eye(n) @@ -289,15 +293,14 @@ def emmax_gwas(y, G, K): resid = y - float(beta) * x.flatten() sigma_e = (resid @ V_inv @ resid) / (n - 2 + 1e-10) se = np.sqrt(float(sigma_e / (x.T @ Px @ x + 1e-10))) + ses[j] = se t_stat = float(beta) / (se + 1e-10) pvals[j] = float(2 * stats.t.sf(abs(t_stat), df=n-2)) - return pvals, betas + return pvals, betas, ses -# Model 8: PLINK-style (chi-square allelic test) def plink_gwas(y, G): - """PLINK-style: allelic chi-square test, dichotomizes phenotype""" n, m = G.shape - pvals = np.ones(m); betas = np.zeros(m) + pvals = np.ones(m); betas = np.zeros(m); ses = np.zeros(m) y_bin = (y > np.median(y)).astype(float) for j in range(m): x = G[:, j] @@ -311,24 +314,20 @@ def plink_gwas(y, G): if ct.sum() > 4: chi2, p, _, _ = stats.chi2_contingency(ct + 0.5) pvals[j] = p - slope, _, _, p2, _ = stats.linregress(x, y_bin) - betas[j] = slope + slope, _, _, p2, se = stats.linregress(x, y_bin) + betas[j] = slope; ses[j] = se except: pass - return pvals, betas + return pvals, betas, ses -# Model 9: GAPIT3-style (Genomic Association and Prediction Integrated Tool) def gapit3_gwas(y, G, K): - """GAPIT3-style: PC + kinship compression with Bonferroni iteration""" n, m = G.shape - pvals = np.ones(m); betas = np.zeros(m) + pvals = np.ones(m); betas = np.zeros(m); ses = np.zeros(m) n_pcs = min(3, n - 2) PCs = PCA(n_components=n_pcs).fit_transform(StandardScaler().fit_transform(G)) eigvals, eigvecs = np.linalg.eigh(K + np.eye(n) * 1e-6) Q = eigvecs[:, np.argsort(eigvals)[::-1][:n_pcs]] covars = np.hstack([PCs, Q]) - y_adj = y - LinearRegression().fit(covars, y).predict(covars) - # Iterative QTN inclusion qtns = [] for iteration in range(2): for j in range(m): @@ -340,21 +339,18 @@ def gapit3_gwas(y, G, K): cov = covars x_res = x - LinearRegression().fit(cov, x).predict(cov) y_res = y - LinearRegression().fit(cov, y).predict(cov) - slope, _, _, p, _ = stats.linregress(x_res, y_res) - pvals[j] = p; betas[j] = slope + slope, _, _, p, se = stats.linregress(x_res, y_res) + pvals[j] = p; betas[j] = slope; ses[j] = se new_qtns = list(np.where(pvals < 0.05 / m)[0][:2]) if new_qtns and new_qtns != qtns: qtns = new_qtns else: break - return pvals, betas + return pvals, betas, ses -# Model 10: GEMMA-style (Genome-wide Efficient Mixed Model Association) def gemma_gwas(y, G, K): - """GEMMA-style: LMM with centered kinship matrix""" n, m = G.shape - pvals = np.ones(m); betas = np.zeros(m) - # Center kinship matrix + pvals = np.ones(m); betas = np.zeros(m); ses = np.zeros(m) row_mean = K.mean(axis=1, keepdims=True) col_mean = K.mean(axis=0, keepdims=True) grand_mean = K.mean() @@ -364,38 +360,29 @@ def gemma_gwas(y, G, K): n_pcs = min(4, n - 2) Q = eigvecs[:, idx[:n_pcs]] y_res = y - LinearRegression().fit(Q, y).predict(Q) - # Wald test approximation for j in range(m): x = G[:, j] x_res = x - LinearRegression().fit(Q, x).predict(Q) if x_res.std() < 1e-8: continue - slope, intercept, r, p, se = stats.linregress(x_res, y_res) - # Apply genomic control correction - pvals[j] = p; betas[j] = slope + slope, _, _, p, se = stats.linregress(x_res, y_res) + pvals[j] = p; betas[j] = slope; ses[j] = se lam = np.median(stats.chi2.ppf(1 - np.clip(pvals, 1e-10, 1), df=1)) / stats.chi2.ppf(0.5, df=1) if lam > 1.05: chi2_vals = stats.chi2.ppf(1 - pvals, df=1) / lam pvals = 1 - stats.chi2.cdf(np.clip(chi2_vals, 0, 1e10), df=1) - return pvals, betas - -# ─────────────────────────── ENHANCED MANHATTAN PLOT (GOLDEN DOTS) ────────────── + return pvals, betas, ses +# ─────────────────────── PLOTS ─────────────────────────────────────────────────── def plot_manhattan(pvals, chroms, positions, title="Manhattan Plot", model_name=""): fig, ax = plt.subplots(figsize=(16, 5)) style_fig(fig) - fig.patch.set_facecolor(BG_DARK) - ax.set_facecolor(PANEL_DARK) - log_p = -np.log10(np.clip(pvals, 1e-300, 1)) sig_line = -np.log10(5e-8) sug_line = -np.log10(1e-5) - chrom_list = sorted(set(chroms)) chrom_colors = {c: CHR_PALETTE[i % len(CHR_PALETTE)] for i, c in enumerate(chrom_list)} - x_offset = 0 tick_pos, tick_lab, x_coords = [], [], np.zeros(len(pvals)) - for ch in chrom_list: mask = chroms == ch pos = positions[mask] @@ -405,90 +392,93 @@ def plot_manhattan(pvals, chroms, positions, title="Manhattan Plot", model_name= x_coords[np.where(mask)[0][order]] = x_vals tick_pos.append(x_vals.mean()) tick_lab.append(f"Chr{ch}") - ax.scatter(x_coords[mask], log_p[mask], - c=chrom_colors[ch], s=12, alpha=0.75, linewidths=0) + ax.scatter(x_coords[mask], log_p[mask], c=chrom_colors[ch], s=12, alpha=0.75, linewidths=0) x_offset += (pos.max() - pos.min()) + max(positions) * 0.015 + 1 - - # Suggestive line ax.axhline(sug_line, color=ACCENT_TEAL, ls=":", lw=1, alpha=0.7, label=f"Suggestive (1e-5)") - # Genome-wide significance line ax.axhline(sig_line, color=ACCENT_CORAL, ls="--", lw=1.5, label=f"GW sig. (5e-8)") - - # ── GOLDEN DOTS for significant MTAs ── sig_mask = log_p >= sig_line if sig_mask.any(): - ax.scatter(x_coords[sig_mask], log_p[sig_mask], - c=SIG_COLOR, s=80, marker="o", zorder=10, - edgecolors="#FFFBEB", linewidth=1.2, + ax.scatter(x_coords[sig_mask], log_p[sig_mask], c=SIG_COLOR, s=80, marker="o", + zorder=10, edgecolors="#FFFBEB", linewidth=1.2, label=f"Sig. MTA ({sig_mask.sum()} SNPs)") - ax.set_xticks(tick_pos) ax.set_xticklabels(tick_lab, rotation=45, fontsize=7, color=TEXT_DIM) ax.set_ylabel("-log₁₀(p)", color=TEXT_DIM) ax.set_title(f"{title}{' — ' + model_name if model_name else ''}", color=TEXT_MAIN, fontsize=11, pad=8) - ax.legend(fontsize=7, framealpha=0.2, facecolor=PANEL_MID, edgecolor=GRID_LINE, - labelcolor=TEXT_MAIN, loc="upper right") + ax.legend(fontsize=7, framealpha=0.2, facecolor=PANEL_MID, edgecolor=GRID_LINE, labelcolor=TEXT_MAIN) ax.set_xlim(-x_offset * 0.01, x_offset * 1.01) fig.tight_layout() return fig -# ─────────────────────────── PER-MODEL QQ PLOTS (ALL MODELS) ──────────────────── +def plot_qq_single(pvals, title="QQ Plot", model_name="", color=None): + """High-quality standalone QQ plot for a single model""" + if color is None: + color = ACCENT_PURP + fig, ax = plt.subplots(figsize=(7, 7)) + style_fig(fig) + n = len(pvals) + obs = np.sort(-np.log10(np.clip(pvals, 1e-300, 1)))[::-1] + exp = -np.log10(np.linspace(1/n, 1, n)[::-1]) + ci_lower = -np.log10(stats.beta.ppf(0.975, np.arange(1, n+1), np.arange(n, 0, -1))) + ci_upper = -np.log10(stats.beta.ppf(0.025, np.arange(1, n+1), np.arange(n, 0, -1))) + ax.fill_between(exp, ci_lower, ci_upper, alpha=0.25, color=color, label="95% CI") + ax.scatter(exp, obs, c=color, s=22, alpha=0.85, linewidths=0, zorder=5) + ax.plot([0, max(exp)], [0, max(exp)], color=ACCENT_CORAL, ls="--", lw=1.8, label="Expected", zorder=6) + lam = np.median(stats.chi2.ppf(1 - np.clip(pvals, 1e-10, 1), df=1)) / stats.chi2.ppf(0.5, df=1) + ax.text(0.05, 0.93, f"λ = {lam:.4f}", transform=ax.transAxes, fontsize=12, + color=ACCENT_GOLD, fontweight='bold') + ax.set_xlabel("Expected -log₁₀(p)", fontsize=10) + ax.set_ylabel("Observed -log₁₀(p)", fontsize=10) + ax.set_title(f"{title}{' — ' + model_name if model_name else ''}", color=TEXT_MAIN, fontsize=12) + ax.legend(fontsize=9, framealpha=0.2, facecolor=PANEL_MID, edgecolor=GRID_LINE, labelcolor=TEXT_MAIN) + fig.tight_layout() + return fig def plot_qq_all_models(all_results): - """QQ plot for each model individually + overlay comparison""" n_models = len(all_results) ncols = min(3, n_models) nrows = (n_models + ncols - 1) // ncols - - fig, axes = plt.subplots(nrows, ncols, figsize=(6 * ncols, 5 * nrows)) + fig, axes = plt.subplots(nrows, ncols, figsize=(7 * ncols, 6 * nrows)) style_fig(fig) if n_models == 1: axes = np.array([axes]) axes = np.array(axes).flatten() - - for idx, (mname, (pvals, _)) in enumerate(all_results.items()): + for idx, (mname, (pvals, _, _)) in enumerate(all_results.items()): ax = axes[idx] n = len(pvals) obs = np.sort(-np.log10(np.clip(pvals, 1e-300, 1)))[::-1] exp = -np.log10(np.linspace(1/n, 1, n)[::-1]) - - # 95% CI band ci_lo = -np.log10(stats.beta.ppf(0.975, np.arange(1, n+1), np.arange(n, 0, -1))) ci_hi = -np.log10(stats.beta.ppf(0.025, np.arange(1, n+1), np.arange(n, 0, -1))) - ax.fill_between(exp, ci_lo, ci_hi, alpha=0.2, color=MODEL_COLORS.get(mname, ACCENT_BLUE)) - - ax.scatter(exp, obs, c=MODEL_COLORS.get(mname, ACCENT_BLUE), s=18, alpha=0.8, linewidths=0) + col = MODEL_COLORS.get(mname, ACCENT_BLUE) + ax.fill_between(exp, ci_lo, ci_hi, alpha=0.22, color=col) + ax.scatter(exp, obs, c=col, s=18, alpha=0.8, linewidths=0) ax.plot([0, max(exp)], [0, max(exp)], color=ACCENT_CORAL, ls="--", lw=1.5, alpha=0.8) - lam = np.median(stats.chi2.ppf(1 - np.clip(pvals, 1e-10, 1), df=1)) / stats.chi2.ppf(0.5, df=1) - ax.text(0.05, 0.92, f"λ = {lam:.4f}", transform=ax.transAxes, - fontsize=9, color=ACCENT_GOLD, fontweight='bold') + ax.text(0.05, 0.92, f"λ = {lam:.4f}", transform=ax.transAxes, fontsize=9, + color=ACCENT_GOLD, fontweight='bold') ax.set_xlabel("Expected -log₁₀(p)", fontsize=8) ax.set_ylabel("Observed -log₁₀(p)", fontsize=8) - ax.set_title(f"QQ — {mname}", color=MODEL_COLORS.get(mname, TEXT_MAIN), fontsize=10) - + ax.set_title(f"QQ — {mname}", color=col, fontsize=10) for idx in range(n_models, len(axes)): axes[idx].set_visible(False) - fig.suptitle("QQ Plots — All Models", color=TEXT_MAIN, fontsize=13, y=1.01) fig.tight_layout() return fig -# ─────────────────────────── QQ OVERLAY (ALL MODELS) ──────────────────────────── - def plot_qq_overlay(all_results): - fig, ax = plt.subplots(figsize=(8, 8)) + fig, ax = plt.subplots(figsize=(9, 9)) style_fig(fig) - - for mname, (pvals, _) in all_results.items(): + exp_max = 0 + for mname, (pvals, _, _) in all_results.items(): n = len(pvals) obs = np.sort(-np.log10(np.clip(pvals, 1e-300, 1)))[::-1] exp = -np.log10(np.linspace(1/n, 1, n)[::-1]) + exp_max = max(exp_max, max(exp)) lam = np.median(stats.chi2.ppf(1 - np.clip(pvals, 1e-10, 1), df=1)) / stats.chi2.ppf(0.5, df=1) ax.plot(exp, obs, color=MODEL_COLORS.get(mname, ACCENT_BLUE), lw=1.8, label=f"{mname} (λ={lam:.3f})", alpha=0.85) - - ax.plot([0, max(exp)], [0, max(exp)], color=ACCENT_CORAL, ls="--", lw=1.5, label="Expected") + ax.plot([0, exp_max], [0, exp_max], color=ACCENT_CORAL, ls="--", lw=1.5, label="Expected") ax.set_xlabel("Expected -log₁₀(p)") ax.set_ylabel("Observed -log₁₀(p)") ax.set_title("QQ Plot — All Models Overlay", color=TEXT_MAIN, fontsize=12) @@ -496,14 +486,7 @@ def plot_qq_overlay(all_results): fig.tight_layout() return fig -# ─────────────────────────── CIRCOS PLOT ───────────────────────────────────────── - def plot_circos(all_results, chroms, positions): - """ - Circos-style circular plot comparing all models. - Each ring = one model. Radius encodes -log10(p). - Significant MTAs shown as golden dots. - """ fig, ax = plt.subplots(figsize=(14, 14), subplot_kw=dict(projection='polar')) fig.patch.set_facecolor(BG_DARK) ax.set_facecolor(BG_DARK) @@ -511,109 +494,59 @@ def plot_circos(all_results, chroms, positions): ax.set_yticks([]) ax.set_xticks([]) ax.spines['polar'].set_visible(False) - chrom_list = sorted(set(chroms)) total_snps = len(chroms) - - # Compute cumulative SNP indices for angular positions snp_angles = np.linspace(0, 2 * np.pi, total_snps, endpoint=False) - # Sort SNPs by chromosome then position sort_idx = np.lexsort((positions, chroms)) angles_sorted = snp_angles.copy() - - # Draw chromosome arc bands (outermost ring) outer_r = 1.0 - chrom_gap = 0.02 - chrom_starts = {} - chrom_ends = {} for ch in chrom_list: mask = chroms[sort_idx] == ch idxs = np.where(mask)[0] if len(idxs) == 0: continue - chrom_starts[ch] = angles_sorted[idxs[0]] - chrom_ends[ch] = angles_sorted[idxs[-1]] theta = angles_sorted[idxs] col = CHR_PALETTE[chrom_list.index(ch) % len(CHR_PALETTE)] - # Draw thick arc for chromosome ax.bar(theta, [0.04]*len(theta), width=2*np.pi/total_snps*1.1, bottom=outer_r, color=col, alpha=0.85, linewidth=0) - # Chromosome label mid_angle = (theta[0] + theta[-1]) / 2 - ax.text(mid_angle, outer_r + 0.075, f"Chr{ch}", - ha='center', va='center', fontsize=6, - color=col, fontweight='bold', - rotation=np.degrees(mid_angle) - 90 if mid_angle < np.pi else np.degrees(mid_angle) + 90) - - # Draw model rings (inner to outer) + ax.text(mid_angle, outer_r + 0.075, f"Chr{ch}", ha='center', va='center', + fontsize=6, color=col, fontweight='bold') model_names = list(all_results.keys()) n_models = len(model_names) ring_inner = 0.25 ring_width = (outer_r - 0.05 - ring_inner) / max(n_models, 1) - sig_line = -np.log10(5e-8) - for midx, mname in enumerate(model_names): - pvals, _ = all_results[mname] + pvals, _, _ = all_results[mname] log_p = -np.log10(np.clip(pvals, 1e-300, 1)) r_base = ring_inner + midx * ring_width r_max_data = ring_width * 0.85 - col = MODEL_COLORS.get(mname, CHR_PALETTE[midx % len(CHR_PALETTE)]) - - # Normalize log_p to ring height max_lp = max(log_p.max(), sig_line, 1) lp_norm = log_p[sort_idx] / max_lp * r_max_data - - # Draw thin baseline arc - ax.plot(angles_sorted, np.full_like(angles_sorted, r_base), - color=col, alpha=0.15, lw=0.5) - - # Scatter points - ax.scatter(angles_sorted, r_base + lp_norm, - c=col, s=4, alpha=0.6, linewidths=0) - - # Golden dots for significant MTAs + ax.plot(angles_sorted, np.full_like(angles_sorted, r_base), color=col, alpha=0.15, lw=0.5) + ax.scatter(angles_sorted, r_base + lp_norm, c=col, s=4, alpha=0.6, linewidths=0) sig_mask = log_p[sort_idx] >= sig_line if sig_mask.any(): ax.scatter(angles_sorted[sig_mask], r_base + lp_norm[sig_mask], - c=SIG_COLOR, s=40, zorder=10, marker='o', - edgecolors='#FFFBEB', linewidth=0.8, alpha=0.95) - - # Ring label - ax.text(0, r_base + r_max_data / 2, mname, - ha='center', va='center', fontsize=7, - color=col, fontweight='bold', alpha=0.9) - - # Center circle decoration - circle = plt.Circle((0, 0), ring_inner - 0.02, transform=ax.transData._b, - color=PANEL_MID, zorder=5) - ax.text(0, 0, "GWAS\nCircos\nComparison", ha='center', va='center', - fontsize=9, color=TEXT_MAIN, fontweight='bold', zorder=6) - - # Legend - legend_elements = [mpatches.Patch(facecolor=MODEL_COLORS.get(m, ACCENT_BLUE), - label=m, alpha=0.8) for m in model_names] + c=SIG_COLOR, s=40, zorder=10, marker='o', edgecolors='#FFFBEB', + linewidth=0.8, alpha=0.95) + ax.text(0, r_base + r_max_data / 2, mname, ha='center', va='center', + fontsize=7, color=col, fontweight='bold', alpha=0.9) + legend_elements = [mpatches.Patch(facecolor=MODEL_COLORS.get(m, ACCENT_BLUE), label=m, alpha=0.8) + for m in model_names] legend_elements.append(mpatches.Patch(facecolor=SIG_COLOR, label="Sig. MTA (●)", alpha=0.9)) - ax.legend(handles=legend_elements, loc='lower center', - bbox_to_anchor=(0.5, -0.08), ncol=min(5, n_models+1), - fontsize=7, framealpha=0.2, facecolor=PANEL_MID, + ax.legend(handles=legend_elements, loc='lower center', bbox_to_anchor=(0.5, -0.08), + ncol=min(5, n_models+1), fontsize=7, framealpha=0.2, facecolor=PANEL_MID, edgecolor=GRID_LINE, labelcolor=TEXT_MAIN) - ax.set_title("Circos Plot — Multi-Model GWAS Comparison\n(Ring height = -log₁₀(p) | ● = Significant MTA)", color=TEXT_MAIN, fontsize=12, pad=20) fig.tight_layout() return fig -# ─────────────────────────── LD DECAY (BP + MB SEPARATE PLOTS) ────────────────── - -def plot_ld_decay_bpMb(G, positions): - """ - Separate LD decay plots in Base Pairs (bp) and Megabases (Mb). - Includes binned mean r² curve and half-decay annotation. - """ +def plot_ld_decay(G, positions): fig, axes = plt.subplots(1, 2, figsize=(16, 6)) style_fig(fig) - m = G.shape[1] dists_bp, r2s = [], [] n_pairs = min(50, m) @@ -624,20 +557,15 @@ def plot_ld_decay_bpMb(G, positions): if mask.sum() < 4: continue r, _ = stats.pearsonr(xi[mask], xj[mask]) d = abs(positions[j] - positions[i]) - dists_bp.append(d) - r2s.append(r**2) - - if len(dists_bp) == 0: + dists_bp.append(d); r2s.append(r**2) + if not dists_bp: for ax in axes: - ax.text(0.5, 0.5, "Insufficient data for LD decay", ha='center', - transform=ax.transAxes, color=TEXT_DIM) + ax.text(0.5, 0.5, "Insufficient data", ha='center', transform=ax.transAxes, color=TEXT_DIM) fig.tight_layout() return fig - dists_bp = np.array(dists_bp) dists_mb = dists_bp / 1_000_000 r2s = np.array(r2s) - def bin_ld(dists, r2s, n_bins=20): bins = np.percentile(dists, np.linspace(0, 100, n_bins + 1)) centers, means, sems = [], [], [] @@ -648,76 +576,34 @@ def plot_ld_decay_bpMb(G, positions): means.append(np.mean(r2s[mask])) sems.append(stats.sem(r2s[mask])) return np.array(centers), np.array(means), np.array(sems) - - # ── Panel 1: Base Pairs ── ax = axes[0] ax.scatter(dists_bp, r2s, c=ACCENT_TEAL, s=12, alpha=0.35, linewidths=0) bc, bm, bs = bin_ld(dists_bp, r2s) - ax.plot(bc, bm, color=ACCENT_CORAL, lw=2.5, marker='o', ms=5, zorder=5, label="Binned mean r²") - ax.fill_between(bc, bm - bs, bm + bs, alpha=0.2, color=ACCENT_CORAL) - ax.axhline(0.5, color=ACCENT_GOLD, ls='--', lw=1.5, alpha=0.8, label="r² = 0.5 (half-decay)") + if len(bc) > 0: + ax.plot(bc, bm, color=ACCENT_CORAL, lw=2.5, marker='o', ms=5, zorder=5, label="Binned mean r²") + ax.fill_between(bc, bm - bs, bm + bs, alpha=0.2, color=ACCENT_CORAL) + ax.axhline(0.5, color=ACCENT_GOLD, ls='--', lw=1.5, alpha=0.8, label="r² = 0.5") ax.axhline(0.2, color=ACCENT_PURP, ls=':', lw=1.2, alpha=0.7, label="r² = 0.2") - # Annotate half-decay distance - if len(bc) > 0 and bm[0] > 0.5: - try: - cross_idx = np.where(bm <= 0.5)[0] - if len(cross_idx) > 0: - half_d = bc[cross_idx[0]] - ax.axvline(half_d, color=ACCENT_GOLD, ls='--', lw=1, alpha=0.6) - ax.text(half_d, 0.55, f"~{half_d:.0f} bp", color=ACCENT_GOLD, fontsize=8, ha='left') - except: pass - ax.set_xlabel("Distance (bp)", fontsize=9) - ax.set_ylabel("r² (LD)", fontsize=9) + ax.set_xlabel("Distance (bp)", fontsize=9); ax.set_ylabel("r² (LD)", fontsize=9) ax.set_title("LD Decay — Base Pairs (bp)", color=TEXT_MAIN, fontsize=11) ax.legend(fontsize=7, framealpha=0.2, facecolor=PANEL_MID, edgecolor=GRID_LINE, labelcolor=TEXT_MAIN) ax.set_ylim(0, 1.05) - - # ── Panel 2: Megabases ── ax2 = axes[1] ax2.scatter(dists_mb, r2s, c=ACCENT_PURP, s=12, alpha=0.35, linewidths=0) bc2, bm2, bs2 = bin_ld(dists_mb, r2s) - ax2.plot(bc2, bm2, color=ACCENT_GOLD, lw=2.5, marker='o', ms=5, zorder=5, label="Binned mean r²") - ax2.fill_between(bc2, bm2 - bs2, bm2 + bs2, alpha=0.2, color=ACCENT_GOLD) - ax2.axhline(0.5, color=ACCENT_CORAL, ls='--', lw=1.5, alpha=0.8, label="r² = 0.5 (half-decay)") + if len(bc2) > 0: + ax2.plot(bc2, bm2, color=ACCENT_GOLD, lw=2.5, marker='o', ms=5, zorder=5, label="Binned mean r²") + ax2.fill_between(bc2, bm2 - bs2, bm2 + bs2, alpha=0.2, color=ACCENT_GOLD) + ax2.axhline(0.5, color=ACCENT_CORAL, ls='--', lw=1.5, alpha=0.8, label="r² = 0.5") ax2.axhline(0.2, color=ACCENT_TEAL, ls=':', lw=1.2, alpha=0.7, label="r² = 0.2") - if len(bc2) > 0 and bm2[0] > 0.5: - try: - cross_idx = np.where(bm2 <= 0.5)[0] - if len(cross_idx) > 0: - half_d = bc2[cross_idx[0]] - ax2.axvline(half_d, color=ACCENT_CORAL, ls='--', lw=1, alpha=0.6) - ax2.text(half_d, 0.55, f"~{half_d:.4f} Mb", color=ACCENT_CORAL, fontsize=8, ha='left') - except: pass - ax2.set_xlabel("Distance (Mb)", fontsize=9) - ax2.set_ylabel("r² (LD)", fontsize=9) + ax2.set_xlabel("Distance (Mb)", fontsize=9); ax2.set_ylabel("r² (LD)", fontsize=9) ax2.set_title("LD Decay — Megabases (Mb)", color=TEXT_MAIN, fontsize=11) ax2.legend(fontsize=7, framealpha=0.2, facecolor=PANEL_MID, edgecolor=GRID_LINE, labelcolor=TEXT_MAIN) ax2.set_ylim(0, 1.05) - fig.suptitle("Linkage Disequilibrium (LD) Decay Analysis", color=TEXT_MAIN, fontsize=13) fig.tight_layout() return fig -# ─────────────────────────── ALL OTHER PLOTS ────────────────────────────────────── - -def plot_qq(pvals, title="QQ Plot"): - fig, ax = plt.subplots(figsize=(6, 6)) - style_fig(fig) - n = len(pvals) - obs = np.sort(-np.log10(np.clip(pvals, 1e-300, 1)))[::-1] - exp = -np.log10(np.linspace(1/n, 1, n)[::-1]) - ci_lower = -np.log10(stats.beta.ppf(0.975, np.arange(1,n+1), np.arange(n,0,-1))) - ci_upper = -np.log10(stats.beta.ppf(0.025, np.arange(1,n+1), np.arange(n,0,-1))) - ax.fill_between(exp, ci_lower, ci_upper, alpha=0.2, color=ACCENT_TEAL, label="95% CI") - ax.scatter(exp, obs, c=ACCENT_PURP, s=20, alpha=0.8) - ax.plot([0, max(exp)], [0, max(exp)], color=ACCENT_CORAL, ls="--", lw=1.5) - lam = np.median(stats.chi2.ppf(1 - pvals, df=1)) / stats.chi2.ppf(0.5, df=1) - ax.text(0.05, 0.92, f"λ = {lam:.4f}", transform=ax.transAxes, fontsize=11, color=ACCENT_GOLD) - ax.set_xlabel("Expected -log₁₀(p)"); ax.set_ylabel("Observed -log₁₀(p)") - ax.set_title(title) - fig.tight_layout() - return fig - def plot_pca(G, y, ids): fig, axes = plt.subplots(2, 2, figsize=(14, 12)) style_fig(fig) @@ -733,264 +619,21 @@ def plot_pca(G, y, ids): axes[0,1].scatter(pcs[:,2], pcs[:,3], c=y, cmap='plasma', s=60, edgecolors='none') axes[0,1].set_xlabel(f"PC3 ({var_exp[2]:.1f}%)"); axes[0,1].set_ylabel(f"PC4 ({var_exp[3]:.1f}%)") axes[0,1].set_title("PCA: PC3 vs PC4") - else: - axes[0,1].text(0.5, 0.5, "< 4 PCs available", ha='center', transform=axes[0,1].transAxes, color=TEXT_DIM) axes[1,0].bar(range(1, n_comp+1), var_exp, color=ACCENT_TEAL, edgecolor='none', alpha=0.8) axes[1,0].plot(range(1, n_comp+1), np.cumsum(var_exp), color=ACCENT_CORAL, marker='o', lw=2) axes[1,0].set_xlabel("Principal Component"); axes[1,0].set_ylabel("Variance Explained (%)") axes[1,0].set_title("Scree Plot") axes[1,1].scatter(pcs[:,0], pcs[:,1], c=y, cmap='plasma', s=60, edgecolors='none') axes[1,1].set_title("Population Structure (PC1 vs PC2)") - fig.tight_layout(); return fig - -def plot_phenotype_distribution(y, ids): - fig, axes = plt.subplots(2, 2, figsize=(14, 10)) - style_fig(fig) - axes[0,0].hist(y, bins=15, color=ACCENT_PURP, edgecolor='none', alpha=0.8) - axes[0,0].axvline(y.mean(), color=ACCENT_CORAL, lw=2, ls='--', label=f"Mean: {y.mean():.2f}") - axes[0,0].axvline(y.mean()+y.std(), color=ACCENT_GOLD, lw=1.5, ls=':', label="±1 SD") - axes[0,0].axvline(y.mean()-y.std(), color=ACCENT_GOLD, lw=1.5, ls=':') - axes[0,0].set_title("Phenotype Distribution"); axes[0,0].legend(fontsize=7) - bp = axes[0,1].boxplot(y, vert=True, patch_artist=True) - for patch in bp['boxes']: patch.set_facecolor(ACCENT_TEAL); patch.set_edgecolor(ACCENT_CORAL) - axes[0,1].set_title("Box Plot") - stats.probplot(y, dist="norm", plot=axes[1,0]) - axes[1,0].set_title("Normal Q-Q Plot") - axes[1,0].get_lines()[0].set_color(ACCENT_PURP) - axes[1,0].get_lines()[1].set_color(ACCENT_CORAL) - axes[1,1].hist(y, bins=15, density=True, color=ACCENT_PURP, alpha=0.7, edgecolor='none') - x_d = np.linspace(y.min(), y.max(), 100) - axes[1,1].plot(x_d, stats.gaussian_kde(y)(x_d), color=ACCENT_CORAL, lw=2) - axes[1,1].set_title("Density Plot") - fig.tight_layout(); return fig - -def plot_maf_analysis(maf, snp_names): - fig, axes = plt.subplots(2, 2, figsize=(14, 10)) - style_fig(fig) - axes[0,0].hist(maf, bins=20, color=ACCENT_TEAL, edgecolor='none') - axes[0,0].axvline(0.05, color=ACCENT_CORAL, ls='--', lw=2, label="MAF=0.05") - axes[0,0].set_title("MAF Distribution"); axes[0,0].legend(fontsize=7) - order = np.argsort(maf)[::-1] - colors = [ACCENT_TEAL if m >= 0.05 else ACCENT_PURP for m in maf[order]] - axes[0,1].bar(range(min(50, len(maf))), maf[order][:50], color=colors[:50]) - axes[0,1].axhline(0.05, color=ACCENT_CORAL, ls='--', lw=1.5) - axes[0,1].set_title("Top 50 SNPs by MAF") - rare_mask = maf < 0.05 - axes[1,0].pie([rare_mask.sum(), (~rare_mask).sum()], - labels=[f"Rare (<0.05): {rare_mask.sum()}", f"Common: {(~rare_mask).sum()}"], - colors=[ACCENT_CORAL, ACCENT_TEAL], autopct='%1.1f%%', textprops={'color': TEXT_MAIN}) - axes[1,0].set_title("Rare vs Common Variants") - axes[1,1].text(0.5, 0.5, - f"MAF Summary\n\nMean: {np.mean(maf):.4f}\nMedian: {np.median(maf):.4f}\nMin: {np.min(maf):.4f}\nMax: {np.max(maf):.4f}", - ha='center', va='center', transform=axes[1,1].transAxes, color=TEXT_MAIN, fontsize=11) - axes[1,1].set_title("MAF Statistics") - fig.tight_layout(); return fig - -def plot_ld_analysis_heatmap(G, positions, chroms): - """LD heatmap + r² histogram + LD scatter""" - fig, axes = plt.subplots(2, 2, figsize=(14, 12)) - style_fig(fig) - m = G.shape[1] - dists, r2s = [], [] - pairs = [(i,j) for i in range(min(50,m)) for j in range(i+1, min(50,m))] - for i, j in pairs: - xi, xj = G[:,i], G[:,j] - mask = ~(np.isnan(xi)|np.isnan(xj)) - if mask.sum() >= 4: - r, _ = stats.pearsonr(xi[mask], xj[mask]) - d = abs(positions[j]-positions[i]) - dists.append(d); r2s.append(r**2) - if dists: - axes[0,0].scatter(np.array(dists)/1000, r2s, alpha=0.4, s=12, color=ACCENT_TEAL, linewidths=0) - axes[0,0].set_xlabel("Distance (kb)"); axes[0,0].set_ylabel("r²") - axes[0,0].set_title("LD Decay (kb)") - m_sub = min(30, m) - R = np.eye(m_sub) - for i in range(m_sub): - for j in range(i+1, m_sub): - xi, xj = G[:,i], G[:,j] - mask = ~(np.isnan(xi)|np.isnan(xj)) - if mask.sum() >= 3: - r, _ = stats.pearsonr(xi[mask], xj[mask]) - R[i,j] = R[j,i] = r**2 - im = axes[0,1].imshow(R, cmap='hot', vmin=0, vmax=1, aspect='auto') - axes[0,1].set_title("LD Heatmap (r², first 30 SNPs)") - plt.colorbar(im, ax=axes[0,1], label="r²") - if r2s: - axes[1,0].hist(r2s, bins=20, color=ACCENT_PURP, edgecolor='none') - axes[1,0].set_xlabel("r²"); axes[1,0].set_ylabel("Frequency") - axes[1,0].set_title("r² Distribution") - if dists: - axes[1,1].scatter(np.array(dists), r2s, alpha=0.3, s=10, color=ACCENT_GOLD, linewidths=0) - axes[1,1].set_xlabel("Distance (bp)"); axes[1,1].set_ylabel("r²") - axes[1,1].set_title("LD vs Distance (bp)") - axes[1,1].set_ylim(0,1) - fig.tight_layout(); return fig - -def plot_effect_sizes(pvals, betas, snp_names): - fig, axes = plt.subplots(2, 2, figsize=(14, 10)) - style_fig(fig) - top_idx = np.argsort(np.abs(betas))[-20:] - top_betas = betas[top_idx] - top_names = [snp_names[i][:15] for i in top_idx] - colors = [ACCENT_CORAL if b < 0 else ACCENT_TEAL for b in top_betas] - axes[0,0].barh(range(len(top_betas)), top_betas, color=colors) - axes[0,0].axvline(0, color=TEXT_DIM, lw=0.7) - axes[0,0].set_yticks(range(len(top_betas))); axes[0,0].set_yticklabels(top_names, fontsize=7) - axes[0,0].set_xlabel("Effect Size (β)"); axes[0,0].set_title("Top 20 Effect Sizes") - log_p = -np.log10(np.clip(pvals, 1e-300, 1)) - sig_thr = -np.log10(0.05/len(pvals)) - colors_v = np.where(log_p >= sig_thr, SIG_COLOR, np.where(betas > 0, ACCENT_TEAL, ACCENT_PURP)) - axes[0,1].scatter(betas, log_p, c=colors_v, s=25, alpha=0.7, linewidths=0) - axes[0,1].axhline(sig_thr, color=ACCENT_CORAL, ls='--', lw=1.5, label="Bonferroni") - axes[0,1].axvline(0, color=TEXT_DIM, lw=0.5) - axes[0,1].set_xlabel("β"); axes[0,1].set_ylabel("-log₁₀(p)") - axes[0,1].set_title("Volcano Plot"); axes[0,1].legend(fontsize=7) - axes[1,0].hist(betas, bins=30, color=ACCENT_TEAL, edgecolor='none') - axes[1,0].axvline(0, color=ACCENT_CORAL, lw=2, ls='--') - axes[1,0].set_xlabel("β"); axes[1,0].set_title("Effect Size Distribution") - axes[1,1].scatter(betas, log_p, c=colors_v, s=20, alpha=0.6, linewidths=0) - axes[1,1].set_xlabel("β"); axes[1,1].set_ylabel("-log₁₀(p)") - axes[1,1].set_title("Effect Size vs Significance") - fig.tight_layout(); return fig - -def plot_heterozygosity(G, y, ids): - fig, axes = plt.subplots(2, 2, figsize=(14, 10)) - style_fig(fig) - het = compute_heterozygosity(G) - axes[0,0].hist(het, bins=20, color=ACCENT_PURP, edgecolor='none') - axes[0,0].set_title("Individual Heterozygosity") - axes[0,1].scatter(het, y, c=ACCENT_TEAL, s=50, alpha=0.7, linewidths=0) - axes[0,1].set_xlabel("Heterozygosity"); axes[0,1].set_ylabel("Phenotype") - axes[0,1].set_title("Heterozygosity vs Phenotype") - top_idx = np.argsort(het)[-10:] - axes[1,0].barh(range(len(top_idx)), het[top_idx], color=ACCENT_CORAL) - axes[1,0].set_yticks(range(len(top_idx))) - axes[1,0].set_yticklabels([ids[i][:10] for i in top_idx], fontsize=8) - axes[1,0].set_title("Top 10 Most Heterozygous") - median_y = np.median(y) - bp = axes[1,1].boxplot([het[y <= median_y], het[y > median_y]], - labels=['Low Pheno', 'High Pheno'], patch_artist=True) - for patch, c in zip(bp['boxes'], [ACCENT_TEAL, ACCENT_CORAL]): - patch.set_facecolor(c) - axes[1,1].set_title("Heterozygosity by Phenotype Group") - fig.tight_layout(); return fig - -def plot_call_rate_analysis(G, snp_names): - fig, axes = plt.subplots(2, 2, figsize=(14, 10)) - style_fig(fig) - cr = compute_call_rate(G) - axes[0,0].hist(cr, bins=20, color=ACCENT_TEAL, edgecolor='none') - axes[0,0].axvline(0.95, color=ACCENT_CORAL, ls='--', lw=2, label="95% threshold") - axes[0,0].set_title("SNP Call Rate Distribution"); axes[0,0].legend(fontsize=7) - order = np.argsort(cr) - axes[0,1].plot(cr[order], color=ACCENT_PURP, lw=1) - axes[0,1].axhline(0.95, color=ACCENT_CORAL, ls='--', lw=1.5) - axes[0,1].fill_between(range(len(cr)), 0, cr[order], alpha=0.2, color=ACCENT_TEAL) - axes[0,1].set_title("Call Rate by SNP (sorted)") - low_cr = cr < 0.95 - axes[1,0].pie([low_cr.sum(), (~low_cr).sum()], - labels=[f"Low CR: {low_cr.sum()}", f"Good CR: {(~low_cr).sum()}"], - colors=[ACCENT_CORAL, ACCENT_TEAL], autopct='%1.1f%%', textprops={'color': TEXT_MAIN}) - axes[1,0].set_title("SNP Quality") - axes[1,1].text(0.5, 0.5, - 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()}", - ha='center', va='center', transform=axes[1,1].transAxes, color=TEXT_MAIN, fontsize=11) - axes[1,1].set_title("Summary Statistics") - fig.tight_layout(); return fig - -def plot_kinship_analysis(K, ids): - fig, axes = plt.subplots(2, 2, figsize=(14, 12)) - style_fig(fig) - im = axes[0,0].imshow(K, cmap='RdYlBu_r', aspect='auto', vmin=-0.5, vmax=1) - axes[0,0].set_title("Kinship Matrix"); plt.colorbar(im, ax=axes[0,0]) - K_flat = K[np.triu_indices_from(K, k=1)] - axes[0,1].hist(K_flat, bins=30, color=ACCENT_PURP, edgecolor='none') - axes[0,1].set_title("Pairwise Kinship Distribution") - try: - lm = linkage(K, method='average') - dendrogram(lm, ax=axes[1,0], labels=ids, leaf_rotation=90, leaf_font_size=7, - color_threshold=0.7, above_threshold_color=ACCENT_TEAL) - except: axes[1,0].text(0.5, 0.5, "Dendrogram failed", ha='center', transform=axes[1,0].transAxes) - axes[1,0].set_title("Sample Clustering Dendrogram") - eigvals, eigvecs = np.linalg.eigh(K) - idx = np.argsort(eigvals)[::-1] - axes[1,1].scatter(eigvecs[:,idx[0]], eigvecs[:,idx[1]], c=ACCENT_TEAL, s=60, edgecolors='none') - axes[1,1].set_title("Kinship PCA") - fig.tight_layout(); return fig - -def plot_mds_analysis(G, y, ids): - fig, axes = plt.subplots(1, 2, figsize=(14, 6)) - style_fig(fig) - try: - mds = MDS(n_components=2, random_state=42, normalized_stress='auto') - mds_c = mds.fit_transform(G) - sc = axes[0].scatter(mds_c[:,0], mds_c[:,1], c=y, cmap='plasma', s=60, edgecolors='none') - axes[0].set_title("MDS"); plt.colorbar(sc, ax=axes[0], label="Phenotype") - perp = min(30, len(G)-1) - tsne_c = TSNE(n_components=2, random_state=42, perplexity=perp).fit_transform(G) - sc2 = axes[1].scatter(tsne_c[:,0], tsne_c[:,1], c=y, cmap='plasma', s=60, edgecolors='none') - axes[1].set_title("t-SNE"); plt.colorbar(sc2, ax=axes[1], label="Phenotype") - except Exception as e: - for ax in axes: ax.text(0.5, 0.5, str(e)[:40], ha='center', transform=ax.transAxes, color=TEXT_DIM) - fig.tight_layout(); return fig - -def plot_manhattan_by_chromosome(pvals, chroms, positions): - fig, axes = plt.subplots(2, 3, figsize=(15, 10)) - style_fig(fig) - axes = axes.flatten() - log_p = -np.log10(np.clip(pvals, 1e-300, 1)) - unique_chroms = sorted(set(chroms)) - for i, ch in enumerate(unique_chroms[:6]): - mask = chroms == ch - if mask.sum() > 0: - col = CHR_PALETTE[unique_chroms.index(ch) % len(CHR_PALETTE)] - axes[i].scatter(positions[mask], log_p[mask], c=col, s=12, alpha=0.7, linewidths=0) - axes[i].axhline(-np.log10(5e-8), color=ACCENT_CORAL, ls='--', lw=1) - sig_m = log_p[mask] >= -np.log10(5e-8) - if sig_m.any(): - axes[i].scatter(positions[mask][sig_m], log_p[mask][sig_m], - c=SIG_COLOR, s=60, zorder=10, linewidths=0) - axes[i].set_title(f"Chr {ch}") - for i in range(len(unique_chroms), 6): - axes[i].set_visible(False) - fig.tight_layout(); return fig - -def plot_manhattan_qq_combined(pvals, chroms, positions): - fig = plt.figure(figsize=(14, 10)) - style_fig(fig) - gs = fig.add_gridspec(2, 2, height_ratios=[2, 1]) - ax1 = fig.add_subplot(gs[0, :]) - log_p = -np.log10(np.clip(pvals, 1e-300, 1)) - ax1.scatter(range(len(pvals)), log_p, c=ACCENT_TEAL, s=8, alpha=0.6, linewidths=0) - ax1.axhline(-np.log10(5e-8), color=ACCENT_CORAL, ls='--', lw=1.5, label="GW sig.") - sig_m = log_p >= -np.log10(5e-8) - if sig_m.any(): - ax1.scatter(np.where(sig_m)[0], log_p[sig_m], c=SIG_COLOR, s=50, zorder=10, linewidths=0) - ax1.set_title("Manhattan Plot"); ax1.legend(fontsize=7) - ax2 = fig.add_subplot(gs[1, 0]) - n = len(pvals) - obs = np.sort(-np.log10(np.clip(pvals, 1e-300, 1)))[::-1] - exp = -np.log10(np.linspace(1/n, 1, n)[::-1]) - ax2.scatter(exp, obs, c=ACCENT_PURP, s=10, alpha=0.6, linewidths=0) - ax2.plot([0, max(exp)], [0, max(exp)], color=ACCENT_CORAL, ls='--', lw=1.5) - ax2.set_title("QQ Plot") - ax3 = fig.add_subplot(gs[1, 1]) - ax3.hist(pvals, bins=50, color=ACCENT_TEAL, edgecolor='none') - ax3.axvline(0.05, color=ACCENT_CORAL, ls='--', lw=1.5) - ax3.set_title("P-value Distribution") - fig.tight_layout(); return fig + fig.tight_layout() + return fig def plot_model_comparison_manhattan(all_results, chroms, positions): - """Side-by-side Manhattan for all models""" n_models = len(all_results) fig, axes = plt.subplots(n_models, 1, figsize=(16, 3.5 * n_models), sharex=True) style_fig(fig) if n_models == 1: axes = [axes] - for ax in fig.get_axes(): - ax.set_facecolor(PANEL_DARK) - chrom_list = sorted(set(chroms)) total_len = 0 chrom_offsets = {} @@ -999,23 +642,20 @@ def plot_model_comparison_manhattan(all_results, chroms, positions): mask = chroms == ch if mask.sum() > 0: total_len += positions[mask].max() - positions[mask].min() + max(positions) * 0.02 + 1 - x_coords = np.zeros(len(chroms)) for ch in chrom_list: mask = chroms == ch if mask.sum() > 0: x_coords[mask] = positions[mask] - positions[mask].min() + chrom_offsets[ch] - - tick_pos = [] - tick_lab = [] + tick_pos, tick_lab = [], [] for ch in chrom_list: mask = chroms == ch if mask.sum() > 0: tick_pos.append(x_coords[mask].mean()) tick_lab.append(f"Chr{ch}") - - for midx, (mname, (pvals, _)) in enumerate(all_results.items()): + for midx, (mname, (pvals, _, _)) in enumerate(all_results.items()): ax = axes[midx] + ax.set_facecolor(PANEL_DARK) log_p = -np.log10(np.clip(pvals, 1e-300, 1)) col = MODEL_COLORS.get(mname, CHR_PALETTE[midx % len(CHR_PALETTE)]) for ch in chrom_list: @@ -1023,99 +663,104 @@ def plot_model_comparison_manhattan(all_results, chroms, positions): ax.scatter(x_coords[mask], log_p[mask], c=col, s=6, alpha=0.65, linewidths=0) sig_m = log_p >= -np.log10(5e-8) if sig_m.any(): - ax.scatter(x_coords[sig_m], log_p[sig_m], c=SIG_COLOR, s=45, - zorder=10, linewidths=0.8, edgecolors='#FFFBEB') + ax.scatter(x_coords[sig_m], log_p[sig_m], c=SIG_COLOR, s=45, zorder=10, + linewidths=0.8, edgecolors='#FFFBEB') ax.axhline(-np.log10(5e-8), color=ACCENT_CORAL, ls='--', lw=1, alpha=0.7) ax.set_ylabel("-log₁₀(p)", fontsize=7, color=TEXT_DIM) ax.set_title(f"Model: {mname}", color=col, fontsize=9, pad=3) ax.set_xticks(tick_pos) ax.set_xticklabels(tick_lab if midx == n_models-1 else [], rotation=40, fontsize=7) ax.tick_params(colors=TEXT_DIM, labelsize=7) - for spine in ax.spines.values(): spine.set_edgecolor(GRID_LINE) + for spine in ax.spines.values(): + spine.set_edgecolor(GRID_LINE) ax.grid(color=GRID_LINE, linewidth=0.3, linestyle="--", alpha=0.4) - fig.suptitle("Manhattan Plots — All Models Comparison", color=TEXT_MAIN, fontsize=13) fig.tight_layout(rect=[0, 0, 1, 0.98]) return fig -def plot_summary_dashboard(y, maf, pvals, betas, G, all_results): +def plot_kinship(K, ids): + fig, axes = plt.subplots(2, 2, figsize=(14, 12)) + style_fig(fig) + im = axes[0,0].imshow(K, cmap='RdYlBu_r', aspect='auto', vmin=-0.5, vmax=1) + axes[0,0].set_title("Kinship Matrix"); plt.colorbar(im, ax=axes[0,0]) + K_flat = K[np.triu_indices_from(K, k=1)] + axes[0,1].hist(K_flat, bins=30, color=ACCENT_PURP, edgecolor='none') + axes[0,1].set_title("Pairwise Kinship Distribution") + try: + lm = linkage(K, method='average') + dendrogram(lm, ax=axes[1,0], labels=ids, leaf_rotation=90, leaf_font_size=7, + color_threshold=0.7, above_threshold_color=ACCENT_TEAL) + except: + axes[1,0].text(0.5, 0.5, "Dendrogram unavailable", ha='center', transform=axes[1,0].transAxes) + axes[1,0].set_title("Clustering Dendrogram") + eigvals, eigvecs = np.linalg.eigh(K) + idx = np.argsort(eigvals)[::-1] + axes[1,1].scatter(eigvecs[:,idx[0]], eigvecs[:,idx[1]], c=ACCENT_TEAL, s=60, edgecolors='none') + axes[1,1].set_title("Kinship PCA") + fig.tight_layout() + return fig + +def plot_effect_sizes(pvals, betas, snp_names): + fig, axes = plt.subplots(2, 2, figsize=(14, 10)) + style_fig(fig) + top_idx = np.argsort(np.abs(betas))[-20:] + top_betas = betas[top_idx] + top_names = [snp_names[i][:15] for i in top_idx] + colors = [ACCENT_CORAL if b < 0 else ACCENT_TEAL for b in top_betas] + axes[0,0].barh(range(len(top_betas)), top_betas, color=colors) + axes[0,0].axvline(0, color=TEXT_DIM, lw=0.7) + axes[0,0].set_yticks(range(len(top_betas))) + axes[0,0].set_yticklabels(top_names, fontsize=7) + axes[0,0].set_xlabel("Effect Size (β)") + axes[0,0].set_title("Top 20 Effect Sizes") + log_p = -np.log10(np.clip(pvals, 1e-300, 1)) + sig_thr = -np.log10(0.05/len(pvals)) + colors_v = np.where(log_p >= sig_thr, SIG_COLOR, np.where(betas > 0, ACCENT_TEAL, ACCENT_PURP)) + axes[0,1].scatter(betas, log_p, c=colors_v, s=25, alpha=0.7, linewidths=0) + axes[0,1].axhline(sig_thr, color=ACCENT_CORAL, ls='--', lw=1.5, label="Bonferroni") + axes[0,1].axvline(0, color=TEXT_DIM, lw=0.5) + axes[0,1].set_xlabel("β"); axes[0,1].set_ylabel("-log₁₀(p)") + axes[0,1].set_title("Volcano Plot"); axes[0,1].legend(fontsize=7) + axes[1,0].hist(betas, bins=30, color=ACCENT_TEAL, edgecolor='none') + axes[1,0].axvline(0, color=ACCENT_CORAL, lw=2, ls='--') + axes[1,0].set_xlabel("β"); axes[1,0].set_title("Effect Size Distribution") + axes[1,1].scatter(betas, log_p, c=colors_v, s=20, alpha=0.6, linewidths=0) + axes[1,1].set_xlabel("β"); axes[1,1].set_ylabel("-log₁₀(p)") + axes[1,1].set_title("Effect Size vs Significance") + fig.tight_layout() + return fig + +def plot_summary_dashboard(y, maf, all_results, G_filt): fig, axes = plt.subplots(2, 3, figsize=(15, 10)) style_fig(fig) axes = axes.flatten() - axes[0].boxplot(y, patch_artist=True, - boxprops={'facecolor': ACCENT_TEAL, 'edgecolor': ACCENT_CORAL}) - axes[0].set_title(f"Phenotype | n={len(y)} | μ={y.mean():.2f}") + axes[0].hist(y, bins=15, color=ACCENT_PURP, edgecolor='none', alpha=0.8) + axes[0].axvline(y.mean(), color=ACCENT_CORAL, lw=2, ls='--', label=f"Mean: {y.mean():.2f}") + axes[0].set_title(f"Phenotype | n={len(y)}") + axes[0].legend(fontsize=7) axes[1].hist(maf, bins=20, color=ACCENT_TEAL, edgecolor='none') axes[1].axvline(0.05, color=ACCENT_CORAL, ls='--') axes[1].set_title(f"MAF | rare={np.sum(maf<0.05)}") - log_p = -np.log10(np.clip(pvals, 1e-300, 1)) - axes[2].hist(log_p, bins=30, color=ACCENT_PURP, edgecolor='none') - axes[2].axvline(-np.log10(0.05/len(pvals)), color=ACCENT_CORAL, ls='--') - axes[2].set_title(f"P-values | sig={np.sum(pvals < 0.05/len(pvals))}") - axes[3].hist(betas, bins=30, color=ACCENT_ORG, edgecolor='none') - axes[3].axvline(0, color=ACCENT_CORAL, ls='--') - axes[3].set_title(f"Effect Sizes | μ={np.mean(betas):.4f}") - # Lambda comparison bar chart lambdas = {} - for mname, (p, _) in all_results.items(): + for mname, (p, _, _) in all_results.items(): lam = np.median(stats.chi2.ppf(1-np.clip(p,1e-10,1), df=1)) / stats.chi2.ppf(0.5, df=1) lambdas[mname] = lam - colors_lam = [ACCENT_TEAL if v <= 1.1 else ACCENT_GOLD if v <= 1.3 else ACCENT_CORAL for v in lambdas.values()] - axes[4].bar(lambdas.keys(), lambdas.values(), color=colors_lam, edgecolor='none') - axes[4].axhline(1.0, color=TEXT_DIM, ls='--', lw=1) - axes[4].set_title("Genomic Inflation λ per Model") - axes[4].tick_params(axis='x', rotation=35, labelsize=7) - lam0 = list(lambdas.values())[0] - miss_r = np.isnan(G).mean() - axes[5].text(0.5, 0.5, - 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))}", - ha='center', va='center', transform=axes[5].transAxes, color=TEXT_MAIN, fontsize=10) - axes[5].set_title("Pipeline Summary") - fig.tight_layout(); return fig - -def plot_gwas_interpretation_panel(all_results, pvals_primary, betas_primary, snp_filt, chroms, positions): - """Comprehensive interpretation: sig SNP table, effect distribution, p-value comparison""" - fig, axes = plt.subplots(2, 2, figsize=(14, 10)) - style_fig(fig) - - # Panel 1: Significant SNP count per model + colors_lam = [ACCENT_TEAL if v <= 1.1 else ACCENT_GOLD if v <= 1.3 else ACCENT_CORAL + for v in lambdas.values()] + axes[2].bar(lambdas.keys(), lambdas.values(), color=colors_lam, edgecolor='none') + axes[2].axhline(1.0, color=TEXT_DIM, ls='--', lw=1) + axes[2].set_title("Genomic Inflation λ per Model") + axes[2].tick_params(axis='x', rotation=35, labelsize=7) sig_counts = {} - bonf = 0.05 / len(pvals_primary) - for mname, (p, _) in all_results.items(): - sig_counts[mname] = (p < bonf).sum() + for mname, (p, _, _) in all_results.items(): + bonf = 0.05 / len(p) + sig_counts[mname] = int((p < bonf).sum()) cols_bar = [MODEL_COLORS.get(m, ACCENT_BLUE) for m in sig_counts.keys()] - axes[0,0].bar(sig_counts.keys(), sig_counts.values(), color=cols_bar, edgecolor='none') - axes[0,0].set_title("Significant SNP Count per Model") - axes[0,0].tick_params(axis='x', rotation=35, labelsize=7) - axes[0,0].set_ylabel("# Significant SNPs") - - # Panel 2: -log10(p) distribution per model (violin-style via hist) - log_ps = {m: -np.log10(np.clip(p, 1e-300, 1)) for m, (p, _) in all_results.items()} - positions_viol = list(range(len(log_ps))) - axes[0,1].violinplot([v for v in log_ps.values()], positions=positions_viol, - showmedians=True, showextrema=True) - axes[0,1].set_xticks(positions_viol) - axes[0,1].set_xticklabels(list(log_ps.keys()), rotation=35, fontsize=7) - axes[0,1].axhline(-np.log10(5e-8), color=ACCENT_CORAL, ls='--', lw=1.5, label="GW sig.") - axes[0,1].set_title("−log₁₀(p) Distribution per Model") - axes[0,1].set_ylabel("−log₁₀(p)"); axes[0,1].legend(fontsize=7) - - # Panel 3: Effect size correlation between models (pairwise) + axes[3].bar(sig_counts.keys(), sig_counts.values(), color=cols_bar, edgecolor='none') + axes[3].set_title("Significant SNPs per Model (Bonferroni)") + axes[3].tick_params(axis='x', rotation=35, labelsize=7) + n_m = len(all_results) model_names = list(all_results.keys()) - if len(model_names) >= 2: - b1 = all_results[model_names[0]][1] - b2 = all_results[model_names[1]][1] - axes[1,0].scatter(b1, b2, c=ACCENT_TEAL, s=15, alpha=0.5, linewidths=0) - m_range = [min(b1.min(), b2.min()), max(b1.max(), b2.max())] - axes[1,0].plot(m_range, m_range, color=ACCENT_CORAL, ls='--', lw=1.5) - r, p_cor = stats.pearsonr(b1, b2) - axes[1,0].set_title(f"Effect Size Correlation\n{model_names[0]} vs {model_names[1]} (r={r:.3f})") - axes[1,0].set_xlabel(f"β ({model_names[0]})"); axes[1,0].set_ylabel(f"β ({model_names[1]})") - else: - axes[1,0].text(0.5, 0.5, "Need ≥2 models", ha='center', transform=axes[1,0].transAxes, color=TEXT_DIM) - - # Panel 4: Concordance heatmap (Spearman r of -log10p across models) - n_m = len(model_names) concordance = np.eye(n_m) for i in range(n_m): for j in range(i+1, n_m): @@ -1123,27 +768,321 @@ def plot_gwas_interpretation_panel(all_results, pvals_primary, betas_primary, sn lp_j = -np.log10(np.clip(all_results[model_names[j]][0], 1e-300, 1)) r, _ = stats.spearmanr(lp_i, lp_j) concordance[i,j] = concordance[j,i] = r - im = axes[1,1].imshow(concordance, cmap='RdYlGn', vmin=-1, vmax=1, aspect='auto') - axes[1,1].set_xticks(range(n_m)); axes[1,1].set_yticks(range(n_m)) - axes[1,1].set_xticklabels(model_names, rotation=35, fontsize=7) - axes[1,1].set_yticklabels(model_names, fontsize=7) + im = axes[4].imshow(concordance, cmap='RdYlGn', vmin=-1, vmax=1, aspect='auto') + axes[4].set_xticks(range(n_m)); axes[4].set_yticks(range(n_m)) + axes[4].set_xticklabels(model_names, rotation=35, fontsize=6) + axes[4].set_yticklabels(model_names, fontsize=6) for i in range(n_m): for j in range(n_m): - axes[1,1].text(j, i, f"{concordance[i,j]:.2f}", ha='center', va='center', - fontsize=6, color='black' if abs(concordance[i,j]) < 0.7 else 'white') - plt.colorbar(im, ax=axes[1,1], label="Spearman ρ") - axes[1,1].set_title("Model Concordance (Spearman ρ of −log₁₀p)") + axes[4].text(j, i, f"{concordance[i,j]:.2f}", ha='center', va='center', + fontsize=5, color='black' if abs(concordance[i,j]) < 0.7 else 'white') + plt.colorbar(im, ax=axes[4], label="Spearman ρ") + axes[4].set_title("Model Concordance") + miss_r = np.isnan(G_filt).mean() + first_model = model_names[0] + axes[5].text(0.5, 0.5, + f"GWAS Summary\n\nSamples: {G_filt.shape[0]}\nSNPs: {G_filt.shape[1]}\n" + f"Models: {n_m}\nMissing: {miss_r:.1%}\n" + f"λ ({first_model}): {lambdas[first_model]:.3f}\n" + f"Sig. ({first_model}): {sig_counts[first_model]}", + ha='center', va='center', transform=axes[5].transAxes, color=TEXT_MAIN, fontsize=10) + axes[5].set_title("Pipeline Summary") + fig.tight_layout() + return fig - fig.suptitle("GWAS Interpretation Panel", color=TEXT_MAIN, fontsize=13) - fig.tight_layout(); return fig +# ─────────────────────── EXCEL RESULTS EXPORT ──────────────────────────────────── +def export_results_excel(all_results, snp_filt, chr_filt, pos_filt, y, G_filt, maf_vals, output_path): + wb = Workbook() + + # Color scheme + header_fill = PatternFill("solid", start_color="4A90D9", end_color="4A90D9") + sig_fill = PatternFill("solid", start_color="FFF3CD", end_color="FFF3CD") + alt_fill = PatternFill("solid", start_color="F8F9FA", end_color="F8F9FA") + header_font = Font(bold=True, color="FFFFFF", name="Calibri", size=11) + title_font = Font(bold=True, color="2C5F8A", name="Calibri", size=13) + thin_border = Border( + left=Side(style='thin', color='CCCCCC'), + right=Side(style='thin', color='CCCCCC'), + top=Side(style='thin', color='CCCCCC'), + bottom=Side(style='thin', color='CCCCCC') + ) -# ─────────────────────────── MAIN PIPELINE ──────────────────────────────────────── + bonf = 0.05 / len(list(all_results.values())[0][0]) + + # ── Sheet 1: Summary ────────────────────────────────────────────────────────── + ws_sum = wb.active + ws_sum.title = "Summary" + ws_sum['A1'] = "GWAS Complete Analysis Summary" + ws_sum['A1'].font = Font(bold=True, color="2C5F8A", name="Calibri", size=16) + ws_sum.merge_cells('A1:H1') + + headers_sum = ["Model", "N_SNPs_Tested", "Bonferroni_Threshold", "Sig_SNPs_Bonferroni", + "Sig_SNPs_5e8", "Genomic_Lambda", "Min_Pvalue", "Max_AbsBeta"] + for col, h in enumerate(headers_sum, 1): + cell = ws_sum.cell(row=3, column=col, value=h) + cell.font = header_font; cell.fill = header_fill + cell.alignment = Alignment(horizontal='center') + cell.border = thin_border + ws_sum.column_dimensions[get_column_letter(col)].width = 22 + + for row_i, (mname, (pvals, betas, ses)) in enumerate(all_results.items(), 4): + lam = np.median(stats.chi2.ppf(1-np.clip(pvals,1e-10,1), df=1)) / stats.chi2.ppf(0.5, df=1) + sig_bonf = int((pvals < bonf).sum()) + sig_5e8 = int((pvals < 5e-8).sum()) + row_data = [mname, len(pvals), f"{bonf:.2e}", sig_bonf, sig_5e8, + round(float(lam), 4), float(np.min(pvals)), round(float(np.max(np.abs(betas))), 5)] + fill = alt_fill if row_i % 2 == 0 else PatternFill("solid", start_color="FFFFFF", end_color="FFFFFF") + for col, val in enumerate(row_data, 1): + cell = ws_sum.cell(row=row_i, column=col, value=val) + cell.fill = fill; cell.border = thin_border + cell.alignment = Alignment(horizontal='center') + + # ── Sheet per model: All SNP results ───────────────────────────────────────── + for mname, (pvals, betas, ses) in all_results.items(): + ws = wb.create_sheet(title=f"{mname}_AllSNPs") + ws['A1'] = f"GWAS Results — {mname} Model — All SNPs" + ws['A1'].font = title_font + ws.merge_cells('A1:K1') + log_p = -np.log10(np.clip(pvals, 1e-300, 1)) + t_stats = np.where(ses > 0, betas / (ses + 1e-10), 0.0) + reject_fdr, pvals_fdr, _, _ = multipletests(pvals, method='fdr_bh') + reject_bonf, _, _, _ = multipletests(pvals, method='bonferroni') + + headers = ["SNP", "Chr", "Position", "MAF", "Beta", "SE", "T_statistic", + "P_value", "neg_log10P", "FDR_BH", "Bonferroni_sig"] + for col, h in enumerate(headers, 1): + cell = ws.cell(row=3, column=col, value=h) + cell.font = header_font; cell.fill = header_fill + cell.alignment = Alignment(horizontal='center') + cell.border = thin_border + + col_widths = [25, 8, 12, 10, 12, 12, 12, 14, 12, 14, 16] + for i, w in enumerate(col_widths, 1): + ws.column_dimensions[get_column_letter(i)].width = w + + sort_order = np.argsort(pvals) + for row_i, idx in enumerate(sort_order, 4): + is_sig = bool(reject_bonf[idx]) or pvals[idx] < 5e-8 + fill = sig_fill if is_sig else (alt_fill if row_i % 2 == 0 else + PatternFill("solid", start_color="FFFFFF", end_color="FFFFFF")) + maf_v = maf_vals[idx] if idx < len(maf_vals) else np.nan + row_data = [ + str(snp_filt[idx]) if idx < len(snp_filt) else "", + int(chr_filt[idx]) if idx < len(chr_filt) else "", + int(pos_filt[idx]) if idx < len(pos_filt) else "", + round(float(maf_v), 4) if not np.isnan(maf_v) else "", + round(float(betas[idx]), 6), + round(float(ses[idx]), 6) if ses is not None else "", + round(float(t_stats[idx]), 4), + float(pvals[idx]), + round(float(log_p[idx]), 4), + round(float(pvals_fdr[idx]), 6), + "YES" if is_sig else "NO" + ] + for col, val in enumerate(row_data, 1): + cell = ws.cell(row=row_i, column=col, value=val) + cell.fill = fill; cell.border = thin_border + cell.alignment = Alignment(horizontal='center') + if col == 8 and isinstance(val, float): + cell.number_format = '0.00E+00' + + # ── Sheet: Significant MTAs (all models combined) ───────────────────────────── + ws_mta = wb.create_sheet(title="Significant_MTAs") + ws_mta['A1'] = "Significant MTAs — All Models Combined (Bonferroni + GW threshold)" + ws_mta['A1'].font = title_font + ws_mta.merge_cells('A1:N1') + + headers_mta = ["Model", "SNP", "Chr", "Position", "MAF", "Beta", "SE", + "T_stat", "P_value", "neg_log10P", "FDR_BH_p", + "Bonferroni_sig", "GW_sig_5e8", "PVE_%"] + for col, h in enumerate(headers_mta, 1): + cell = ws_mta.cell(row=3, column=col, value=h) + cell.font = header_font; cell.fill = header_fill + cell.alignment = Alignment(horizontal='center'); cell.border = thin_border + ws_mta.column_dimensions[get_column_letter(col)].width = 18 + + mta_row = 4 + for mname, (pvals, betas, ses) in all_results.items(): + log_p = -np.log10(np.clip(pvals, 1e-300, 1)) + t_stats = np.where(ses > 0, betas / (ses + 1e-10), 0.0) + _, pvals_fdr, _, _ = multipletests(pvals, method='fdr_bh') + reject_bonf, _, _, _ = multipletests(pvals, method='bonferroni') + sig_idx = np.where((pvals < bonf) | (pvals < 5e-8))[0] + sig_idx = sig_idx[np.argsort(pvals[sig_idx])] + # Compute PVE for significant SNPs + pve_dict, _ = compute_pve(y, G_filt, pvals, betas) + for idx in sig_idx: + pve_val = round(pve_dict.get(int(idx), 0.0), 4) + maf_v = maf_vals[idx] if idx < len(maf_vals) else np.nan + row_data = [ + mname, + str(snp_filt[idx]) if idx < len(snp_filt) else "", + int(chr_filt[idx]) if idx < len(chr_filt) else "", + int(pos_filt[idx]) if idx < len(pos_filt) else "", + round(float(maf_v), 4) if not np.isnan(maf_v) else "", + round(float(betas[idx]), 6), + round(float(ses[idx]), 6), + round(float(t_stats[idx]), 4), + float(pvals[idx]), + round(float(log_p[idx]), 4), + round(float(pvals_fdr[idx]), 6), + "YES" if bool(reject_bonf[idx]) else "NO", + "YES" if pvals[idx] < 5e-8 else "NO", + pve_val + ] + fill = sig_fill if mta_row % 2 == 0 else PatternFill("solid", start_color="FFFDE7", end_color="FFFDE7") + for col, val in enumerate(row_data, 1): + cell = ws_mta.cell(row=mta_row, column=col, value=val) + cell.fill = fill; cell.border = thin_border + cell.alignment = Alignment(horizontal='center') + if col == 9 and isinstance(val, float): + cell.number_format = '0.00E+00' + mta_row += 1 + + # ── Sheet: QTN Effects ──────────────────────────────────────────────────────── + ws_qtn = wb.create_sheet(title="QTN_Effects") + ws_qtn['A1'] = "Quantitative Trait Nucleotides (QTNs) — Effect Analysis" + ws_qtn['A1'].font = title_font + ws_qtn.merge_cells('A1:L1') + + headers_qtn = ["Model", "Rank", "SNP", "Chr", "Position", "MAF", + "QTN_Effect_Beta", "SE", "95%_CI_Lower", "95%_CI_Upper", + "P_value", "PVE_%"] + for col, h in enumerate(headers_qtn, 1): + cell = ws_qtn.cell(row=3, column=col, value=h) + cell.font = header_font; cell.fill = header_fill + cell.alignment = Alignment(horizontal='center'); cell.border = thin_border + ws_qtn.column_dimensions[get_column_letter(col)].width = 17 + + qtn_row = 4 + for mname, (pvals, betas, ses) in all_results.items(): + top_n = min(20, len(pvals)) + top_idx = np.argsort(pvals)[:top_n] + pve_dict, _ = compute_pve(y, G_filt, pvals, betas) + for rank, idx in enumerate(top_idx, 1): + pve_val = round(pve_dict.get(int(idx), 0.0), 4) + maf_v = maf_vals[idx] if idx < len(maf_vals) else np.nan + ci_lower = float(betas[idx]) - 1.96 * float(ses[idx]) + ci_upper = float(betas[idx]) + 1.96 * float(ses[idx]) + fill = alt_fill if qtn_row % 2 == 0 else PatternFill("solid", start_color="FFFFFF", end_color="FFFFFF") + row_data = [ + mname, rank, + str(snp_filt[idx]) if idx < len(snp_filt) else "", + int(chr_filt[idx]) if idx < len(chr_filt) else "", + int(pos_filt[idx]) if idx < len(pos_filt) else "", + round(float(maf_v), 4) if not np.isnan(maf_v) else "", + round(float(betas[idx]), 6), + round(float(ses[idx]), 6), + round(ci_lower, 6), + round(ci_upper, 6), + float(pvals[idx]), + pve_val + ] + for col, val in enumerate(row_data, 1): + cell = ws_qtn.cell(row=qtn_row, column=col, value=val) + cell.fill = fill; cell.border = thin_border + cell.alignment = Alignment(horizontal='center') + if col == 11 and isinstance(val, float): + cell.number_format = '0.00E+00' + qtn_row += 1 + + # ── Sheet: PVE Summary ──────────────────────────────────────────────────────── + ws_pve = wb.create_sheet(title="PVE_Summary") + ws_pve['A1'] = "Phenotypic Variance Explained (PVE) by Significant QTNs" + ws_pve['A1'].font = title_font + ws_pve.merge_cells('A1:I1') + + headers_pve = ["Model", "SNP", "Chr", "Position", "Beta", "P_value", "PVE_%", + "Cumulative_PVE_%", "Significance"] + for col, h in enumerate(headers_pve, 1): + cell = ws_pve.cell(row=3, column=col, value=h) + cell.font = header_font; cell.fill = header_fill + cell.alignment = Alignment(horizontal='center'); cell.border = thin_border + ws_pve.column_dimensions[get_column_letter(col)].width = 20 + + pve_row = 4 + for mname, (pvals, betas, ses) in all_results.items(): + pve_dict, _ = compute_pve(y, G_filt, pvals, betas) + sig_idx_sorted = sorted(pve_dict.keys(), key=lambda i: pve_dict[i], reverse=True) + cumulative = 0.0 + for idx in sig_idx_sorted: + pve_val = pve_dict[idx] + cumulative += pve_val + is_sig_gw = pvals[idx] < 5e-8 + sig_label = "GW-significant" if is_sig_gw else "Bonferroni-significant" + fill = sig_fill if pve_row % 2 == 0 else PatternFill("solid", start_color="FFFFFF", end_color="FFFFFF") + row_data = [ + mname, + str(snp_filt[idx]) if idx < len(snp_filt) else "", + int(chr_filt[idx]) if idx < len(chr_filt) else "", + int(pos_filt[idx]) if idx < len(pos_filt) else "", + round(float(betas[idx]), 6), + float(pvals[idx]), + round(pve_val, 4), + round(cumulative, 4), + sig_label + ] + for col, val in enumerate(row_data, 1): + cell = ws_pve.cell(row=pve_row, column=col, value=val) + cell.fill = fill; cell.border = thin_border + cell.alignment = Alignment(horizontal='center') + if col == 6 and isinstance(val, float): + cell.number_format = '0.00E+00' + pve_row += 1 + + # ── Sheet: MAF & Quality ────────────────────────────────────────────────────── + ws_qc = wb.create_sheet(title="SNP_QC") + ws_qc['A1'] = "SNP Quality Control Statistics" + ws_qc['A1'].font = title_font + ws_qc.merge_cells('A1:F1') + headers_qc = ["SNP", "Chr", "Position", "MAF", "Call_Rate", "Category"] + for col, h in enumerate(headers_qc, 1): + cell = ws_qc.cell(row=3, column=col, value=h) + cell.font = header_font; cell.fill = header_fill + cell.alignment = Alignment(horizontal='center'); cell.border = thin_border + ws_qc.column_dimensions[get_column_letter(col)].width = 20 + call_rates = compute_call_rate(G_filt) + for row_i in range(len(snp_filt)): + maf_v = maf_vals[row_i] if row_i < len(maf_vals) else np.nan + cr_v = call_rates[row_i] if row_i < len(call_rates) else np.nan + cat = "Rare (<0.05)" if not np.isnan(maf_v) and maf_v < 0.05 else "Common" + fill = alt_fill if row_i % 2 == 0 else PatternFill("solid", start_color="FFFFFF", end_color="FFFFFF") + row_data = [ + str(snp_filt[row_i]), + int(chr_filt[row_i]) if row_i < len(chr_filt) else "", + int(pos_filt[row_i]) if row_i < len(pos_filt) else "", + round(float(maf_v), 4) if not np.isnan(maf_v) else "", + round(float(cr_v), 4) if not np.isnan(cr_v) else "", + cat + ] + for col, val in enumerate(row_data, 1): + cell = ws_qc.cell(row=row_i+4, column=col, value=val) + cell.fill = fill; cell.border = thin_border + cell.alignment = Alignment(horizontal='center') + + wb.save(output_path) + return output_path + +def save_all_plots_zip(plot_dict, out_dir): + """Save all plots as PNG files in a temp zip""" + zip_path = os.path.join(out_dir, "gwas_plots.zip") + with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf: + for name, fig in plot_dict.items(): + if fig is not None: + buf = io.BytesIO() + fig.savefig(buf, format="png", dpi=150, bbox_inches="tight", + facecolor=fig.get_facecolor()) + buf.seek(0) + zf.writestr(f"{name}.png", buf.read()) + return zip_path + +# ─────────────────────── MAIN PIPELINE ─────────────────────────────────────────── def run_gwas(file_obj, text_input, selected_models, maf_threshold): try: df, snp_cols, chroms, positions = parse_data(file_obj, text_input) except Exception as e: - return [None] * 24 + [f"❌ Data parsing error: {e}"] + return [None] * 30 + [f"❌ Data parsing error: {e}"] y = df["Phenotype"].values.astype(float) ids = df["ID"].values @@ -1151,15 +1090,17 @@ def run_gwas(file_obj, text_input, selected_models, maf_threshold): G = impute_genotypes(G_raw) n, m = G.shape - maf_vals = compute_maf(G) + maf_vals_all = compute_maf(G) maf_thr = float(maf_threshold) - keep = maf_vals >= maf_thr - if keep.sum() < 2: keep = np.ones(m, dtype=bool) + keep = maf_vals_all >= maf_thr + if keep.sum() < 2: + keep = np.ones(m, dtype=bool) G_filt = G[:, keep] snp_filt = np.array(snp_cols)[keep] chr_filt = chroms[keep] if len(chroms) == m else np.ones(G_filt.shape[1], dtype=int) pos_filt = positions[keep] if len(positions) == m else np.arange(G_filt.shape[1]) + maf_vals = maf_vals_all[keep] K = build_kinship(G_filt) @@ -1178,227 +1119,410 @@ def run_gwas(file_obj, text_input, selected_models, maf_threshold): models_to_run = selected_models if selected_models else list(model_funcs.keys()) all_results = {} - primary_p = primary_b = None + primary_p = primary_b = primary_se = None for mname in models_to_run: if mname in model_funcs: try: - p, b = model_funcs[mname]() - all_results[mname] = (p, b) + p, b, se = model_funcs[mname]() + all_results[mname] = (p, b, se) if primary_p is None: - primary_p, primary_b = p, b + primary_p, primary_b, primary_se = p, b, se except Exception as ex: print(f"Model {mname} failed: {ex}") if primary_p is None: - return [None] * 24 + ["❌ No models succeeded"] - - plots = [] - # 1. Manhattan (primary model, golden dots) - plots.append(plot_manhattan(primary_p, chr_filt, pos_filt, "Manhattan Plot", models_to_run[0])) - # 2. QQ (primary model) - plots.append(plot_qq(primary_p, f"QQ Plot — {models_to_run[0]}")) - # 3. QQ all models (individual panels) - plots.append(plot_qq_all_models(all_results)) - # 4. QQ overlay all models - plots.append(plot_qq_overlay(all_results)) - # 5. Circos comparison - plots.append(plot_circos(all_results, chr_filt, pos_filt)) - # 6. LD decay BP + MB - plots.append(plot_ld_decay_bpMb(G_filt, pos_filt)) - # 7. LD heatmap - plots.append(plot_ld_analysis_heatmap(G_filt, pos_filt, chr_filt)) - # 8. PCA - plots.append(plot_pca(G_filt, y, ids)) - # 9. Phenotype distribution - plots.append(plot_phenotype_distribution(y, ids)) - # 10. MAF - plots.append(plot_maf_analysis(maf_vals, snp_cols)) - # 11. Effect sizes - plots.append(plot_effect_sizes(primary_p, primary_b, snp_filt)) - # 12. Heterozygosity - plots.append(plot_heterozygosity(G_filt, y, ids)) - # 13. Call rate - plots.append(plot_call_rate_analysis(G_filt, snp_filt)) - # 14. Kinship - plots.append(plot_kinship_analysis(K, ids)) - # 15. MDS/t-SNE - plots.append(plot_mds_analysis(G_filt, y, ids)) - # 16. Manhattan by chromosome - plots.append(plot_manhattan_by_chromosome(primary_p, chr_filt, pos_filt)) - # 17. Manhattan + QQ combined panel - plots.append(plot_manhattan_qq_combined(primary_p, chr_filt, pos_filt)) - # 18. All-model Manhattan comparison - plots.append(plot_model_comparison_manhattan(all_results, chr_filt, pos_filt)) - # 19. Interpretation panel - plots.append(plot_gwas_interpretation_panel(all_results, primary_p, primary_b, snp_filt, chr_filt, pos_filt)) - # 20. Summary dashboard - plots.append(plot_summary_dashboard(y, maf_vals, primary_p, primary_b, G_filt, all_results)) - - img_plots = [fig_to_pil(fig) if fig is not None else None for fig in plots] + return [None] * 30 + ["❌ No models succeeded"] + + # ── Build all named plots ────────────────────────────────────────────────────── + plot_dict = {} + plot_dict["01_Manhattan_Primary"] = plot_manhattan( + primary_p, chr_filt, pos_filt, "Manhattan Plot", models_to_run[0]) + plot_dict["02_QQ_Primary"] = plot_qq_single( + primary_p, "QQ Plot", models_to_run[0], MODEL_COLORS.get(models_to_run[0], ACCENT_PURP)) + plot_dict["03_QQ_All_Models"] = plot_qq_all_models(all_results) + plot_dict["04_QQ_Overlay"] = plot_qq_overlay(all_results) + plot_dict["05_Circos"] = plot_circos(all_results, chr_filt, pos_filt) + plot_dict["06_LD_Decay"] = plot_ld_decay(G_filt, pos_filt) + plot_dict["07_PCA"] = plot_pca(G_filt, y, ids) + plot_dict["08_Kinship"] = plot_kinship(K, ids) + plot_dict["09_Effect_Sizes"] = plot_effect_sizes(primary_p, primary_b, snp_filt) + plot_dict["10_All_Models_Manhattan"] = plot_model_comparison_manhattan(all_results, chr_filt, pos_filt) + plot_dict["11_Summary_Dashboard"] = plot_summary_dashboard(y, maf_vals, all_results, G_filt) + + # Per-model individual Manhattan + QQ + for mname, (p, b, se) in all_results.items(): + plot_dict[f"12_{mname}_Manhattan"] = plot_manhattan(p, chr_filt, pos_filt, "Manhattan", mname) + plot_dict[f"13_{mname}_QQ"] = plot_qq_single(p, "QQ Plot", mname, MODEL_COLORS.get(mname, ACCENT_PURP)) + + # PIL images for display + imgs = {} + for k, fig in plot_dict.items(): + imgs[k] = fig_to_pil(fig) if fig is not None else None + + # ── Save all plots as PNG zip ────────────────────────────────────────────────── + tmp_dir = tempfile.mkdtemp() + zip_path = save_all_plots_zip(plot_dict, tmp_dir) + + # ── Export Excel ─────────────────────────────────────────────────────────────── + excel_path = os.path.join(tmp_dir, "gwas_results_complete.xlsx") + export_results_excel(all_results, snp_filt, chr_filt, pos_filt, y, G_filt, maf_vals, excel_path) + plt.close('all') + # ── Summary text ─────────────────────────────────────────────────────────────── bonf = 0.05 / len(primary_p) - res_df = pd.DataFrame({ - "SNP": snp_filt[:50], - "Chr": chr_filt[:50], - "Pos": pos_filt[:50], - "Beta": np.round(primary_b[:50], 5), - "P_value": primary_p[:50], - "-log10P": np.round(-np.log10(np.clip(primary_p[:50], 1e-300, 1)), 4), - }).sort_values("P_value").head(20) - - lam = np.median(stats.chi2.ppf(1 - np.clip(primary_p, 1e-10, 1), df=1)) / stats.chi2.ppf(0.5, df=1) - sig_snps = (primary_p < bonf).sum() - lambdas_str = "\n ".join([ - 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