diff --git "a/app.py" "b/app.py" --- "a/app.py" +++ "b/app.py" @@ -5,22 +5,17 @@ import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt import matplotlib.patches as mpatches -from matplotlib.colors import LinearSegmentedColormap, Normalize -from matplotlib.cm import ScalarMappable +from matplotlib.colors import LinearSegmentedColormap import matplotlib.gridspec as gridspec -import plotly.graph_objects as go -import plotly.express as px -from plotly.subplots import make_subplots import warnings warnings.filterwarnings("ignore") from scipy import stats from scipy.cluster.hierarchy import dendrogram, linkage -from scipy.optimize import minimize_scalar from sklearn.decomposition import PCA from sklearn.preprocessing import StandardScaler from sklearn.linear_model import LinearRegression -from sklearn.cluster import KMeans +from sklearn.manifold import MDS, TSNE from statsmodels.stats.multitest import multipletests import io, re, os, zipfile, tempfile from io import StringIO @@ -28,58 +23,57 @@ from openpyxl import Workbook from openpyxl.styles import Font, PatternFill, Alignment, Border, Side from openpyxl.utils import get_column_letter -# ─────────────────────── PLOT COLORS ────────────────────────────────────────── -BG_WHITE = "#FFFFFF" -PANEL_WHITE = "#FAFAFA" -PANEL_LIGHT = "#F3F6FC" -ACCENT_TEAL = "#00C9A7" -ACCENT_GOLD = "#FFB300" -ACCENT_CORAL= "#FF4560" -ACCENT_BLUE = "#008FFB" -ACCENT_LIME = "#00E396" -ACCENT_PURP = "#775DD0" -ACCENT_PINK = "#FF66C4" -ACCENT_CYAN = "#00D9E9" -ACCENT_ORG = "#FF6B35" -TEXT_MAIN = "#1E293B" -TEXT_DIM = "#475569" -GRID_LINE = "#E2E8F0" -SIG_COLOR = "#FF1744" +# ─────────────────────── PLOT COLORS (unchanged dark-science theme) ─────────────── +BG_DARK = "#0D1117" +PANEL_DARK = "#161B22" +PANEL_MID = "#21262D" +ACCENT_TEAL = "#2DD4BF" +ACCENT_GOLD = "#F59E0B" +ACCENT_CORAL= "#F87171" +ACCENT_BLUE = "#60A5FA" +ACCENT_LIME = "#84CC16" +ACCENT_PURP = "#A78BFA" +ACCENT_PINK = "#F472B6" +ACCENT_CYAN = "#22D3EE" +ACCENT_ORG = "#FB923C" +TEXT_MAIN = "#E6EDF3" +TEXT_DIM = "#8B949E" +GRID_LINE = "#30363D" +SIG_COLOR = "#F59E0B" MODEL_COLORS = { - "MLM": "#00C9A7", - "CMLM": "#775DD0", - "FarmCPU": "#00E396", - "PLINK": "#008FFB", - "GLM": "#FF4560", - "EMMAX": "#FF66C4", - "GEMMA": "#A855F7", - "BLINK": "#FFB300", - "OLS": "#FF6B35", - "GAPIT3": "#00D9E9", + "OLS": "#60A5FA", + "MLM": "#2DD4BF", + "GLM": "#F87171", + "CMLM": "#A78BFA", + "BLINK": "#F59E0B", + "FarmCPU": "#84CC16", + "EMMAX": "#F472B6", + "PLINK": "#22D3EE", + "GAPIT3": "#FB923C", + "GEMMA": "#E879F9", } CHR_PALETTE = [ - "#1f77b4","#ff7f0e","#2ca02c","#d62728","#9467bd", - "#8c564b","#e377c2","#7f7f7f","#bcbd22","#17becf", - "#aec7e8","#ffbb78","#98df8a","#ff9896","#c5b0d5", + "#60A5FA","#2DD4BF","#F87171","#A78BFA","#F59E0B", + "#84CC16","#F472B6","#22D3EE","#FB923C","#E879F9", + "#34D399","#FCD34D","#818CF8","#F9A8D4","#6EE7B7", ] def style_fig(fig): - fig.patch.set_facecolor(BG_WHITE) + fig.patch.set_facecolor(BG_DARK) for ax in fig.get_axes(): - ax.set_facecolor(PANEL_WHITE) + ax.set_facecolor(PANEL_DARK) ax.tick_params(colors=TEXT_DIM, labelsize=8) ax.xaxis.label.set_color(TEXT_DIM) ax.yaxis.label.set_color(TEXT_DIM) ax.title.set_color(TEXT_MAIN) for spine in ax.spines.values(): spine.set_edgecolor(GRID_LINE) - spine.set_linewidth(0.8) - ax.grid(color=GRID_LINE, linewidth=0.5, linestyle="--", alpha=0.7) + 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: @@ -98,18 +92,17 @@ def parse_data(file_obj=None, text_input=None): chrom_info = {} if len(raw) > 1: second_row = raw.iloc[1].astype(str) - for i, col in enumerate(raw.columns[2:]): - val = str(second_row.iloc[2 + i]).strip() - if re.match(r'^\d+$', val): + chrom_vals = second_row.iloc[2:].astype(str) + if len(chrom_vals) > 0 and chrom_vals.str.match(r'^\d+$').all(): + for i, col in enumerate(raw.columns[2:]): try: - chrom_info[col] = int(val) - except Exception: - pass - if len(chrom_info) > 0: + 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] + id_col = cols[0] phen_col = cols[1] snp_cols = cols[2:] @@ -119,16 +112,16 @@ def parse_data(file_obj=None, text_input=None): geno = geno.where(~geno.isin([-1, -9, -99, -999]), np.nan) df = pd.DataFrame() - df["ID"] = raw[id_col].values + 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 idx_m, m in enumerate(snp_cols): + for m in snp_cols: if m in chrom_info: chroms.append(chrom_info[m]) - positions.append(idx_m + 1) + positions.append(len(positions) + 1) else: m_clean = str(m).strip() mat = re.match(r"[Cc]hr(\d+)[_\-](\d+)", m_clean) @@ -136,1719 +129,672 @@ def parse_data(file_obj=None, text_input=None): chroms.append(int(mat.group(1))) positions.append(int(mat.group(2))) else: - nums = re.findall(r"\d+", m_clean) - chroms.append(int(nums[0]) if nums else 1) - positions.append(int(nums[1]) * 1000 if len(nums) > 1 - else (idx_m + 1) * 10_000) + 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 ────────────────────────────────────────────── -def impute_genotypes_mode(geno_matrix): +# ─────────────────────── UTILITY ───────────────────────────────────────────────── +def impute_genotypes(geno_matrix): mat = geno_matrix.copy().astype(float) for j in range(mat.shape[1]): col = mat[:, j] - valid = col[~np.isnan(col)] - if len(valid) == 0: - mat[:, j] = 0 - continue - counts = np.bincount(valid.astype(int), minlength=3) - mode_val = float(np.argmax(counts)) - col[np.isnan(col)] = mode_val + m = np.nanmean(col) + col[np.isnan(col)] = m if not np.isnan(m) else 0 mat[:, j] = col return mat def compute_maf(G): - freqs = np.nanmean(G, axis=0) / 2.0 + freqs = np.nanmean(G, axis=0) / 2 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]) + def compute_call_rate(G): return 1 - np.isnan(G).mean(axis=0) -def build_kinship(G_raw): - G = G_raw.copy().astype(float) - p = np.nanmean(G, axis=0) / 2.0 - p = np.clip(p, 1e-6, 1 - 1e-6) - for j in range(G.shape[1]): - nan_mask = np.isnan(G[:, j]) - G[nan_mask, j] = 2 * p[j] - Z = G - 2 * p +def build_kinship(G): + p = np.nanmean(G, axis=0) / 2 + Z = G - 2 * p denom = 2 * np.sum(p * (1 - p)) - if denom < 1e-8: - denom = 1.0 - K = (Z @ Z.T) / denom - return K - -def reml_variance_components(y, K): - n = len(y) - eigvals, U = np.linalg.eigh(K + np.eye(n) * 1e-6) - eigvals = np.maximum(eigvals, 1e-8) - - Uty = U.T @ y - Ut1 = U.T @ np.ones(n) - Uty = Uty - (np.dot(Uty, Ut1) / np.dot(Ut1, Ut1)) * Ut1 - - def neg_log_reml(log_delta): - delta = np.exp(log_delta) - d = eigvals + delta - ll = -0.5 * np.sum(np.log(d)) - ll -= 0.5 * (n - 1) * np.log(np.maximum(np.sum(Uty**2 / d), 1e-12)) - return -ll - - res = minimize_scalar(neg_log_reml, bounds=(-10, 10), method='bounded') - delta = np.exp(res.x) - d = eigvals + delta - Ve = np.sum(Uty**2 / d) / (n - 1) - Vg = Ve / delta - Ve = max(float(Ve), 1e-8) - Vg = max(float(Vg), 1e-8) - return Vg, Ve, float(delta), eigvals, U - -def gls_test(y, x, V_inv): - x = x.reshape(-1, 1) - one = np.ones((len(y), 1)) - X = np.hstack([one, x]) - XtVX = X.T @ V_inv @ X - XtVy = X.T @ V_inv @ y - try: - coeffs = np.linalg.solve(XtVX + np.eye(2) * 1e-10, XtVy) - except np.linalg.LinAlgError: - return 0.0, 1.0, 1.0 - beta = float(coeffs[1]) - resid = y - X @ coeffs - df = len(y) - 2 - sigma2 = float(resid @ resid) / max(df, 1) - try: - XtVX_inv = np.linalg.inv(XtVX + np.eye(2) * 1e-10) - var_beta = sigma2 * float(XtVX_inv[1, 1]) - except np.linalg.LinAlgError: - return beta, 1.0, 1.0 - se = float(np.sqrt(max(var_beta, 1e-12))) - t_stat = beta / se - p_val = float(2 * stats.t.sf(abs(t_stat), df=max(df, 1))) - return beta, se, p_val - -def ols_linregress(y, x): - if x.std() < 1e-8: - return 0.0, 1.0, 1.0 - slope, intercept, r, p, se = stats.linregress(x, y) - return float(slope), float(se), float(p) - -def precompute_rotation(y, K): - n = len(y) - Vg, Ve, delta, eigvals, U = reml_variance_components(y, K) - d = eigvals + delta - Uty = U.T @ y - Ut1 = U.T @ np.ones(n) - return U, d, Uty, Ut1, Vg, Ve, delta - -def rotated_gls_snp(Utx, Uty, Ut1, d): - n = len(Uty) - df = n - 2 - S11 = np.sum(Ut1**2 / d) - S1x = np.sum(Ut1 * Utx / d) - Sxx = np.sum(Utx**2 / d) - S1y = np.sum(Ut1 * Uty / d) - Sxy = np.sum(Utx * Uty / d) - denom = S11 * Sxx - S1x**2 - if abs(denom) < 1e-12: - return 0.0, 1.0, 1.0 - beta = (S11 * Sxy - S1x * S1y) / denom - intercept= (S1y - S1x * beta) / S11 - resid_rot = Uty - intercept * Ut1 - beta * Utx - sigma2 = np.dot(resid_rot, resid_rot) / max(df, 1) - var_beta = sigma2 * S11 / denom - se = float(np.sqrt(max(var_beta, 1e-12))) - t_stat = beta / se - p_val = float(2 * stats.t.sf(abs(t_stat), df=max(df, 1))) - return float(beta), se, p_val - -def compute_pve(y, G, pvals, betas, ses, threshold=0.05): - bonf = threshold / len(pvals) - sig_idx = list(np.where(pvals < bonf)[0]) - SST = np.sum((y - y.mean())**2) + if denom == 0: + denom = 1 + 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 = {} - if SST < 1e-10 or len(sig_idx) == 0: - return {}, SST - X_parts = [np.ones(len(y))] - valid_idx = [] + total_var = np.var(y) for idx in sig_idx: x = G[:, idx] - if x.std() > 1e-8: - X_parts.append(x) - valid_idx.append(idx) - if len(valid_idx) == 0: - return {}, SST - X_joint = np.column_stack(X_parts) - try: - c_joint = np.linalg.lstsq(X_joint, y, rcond=None)[0] - ss_full = np.sum((y - X_joint @ c_joint)**2) - except Exception: - return {idx: 0.0 for idx in valid_idx}, SST - for k, idx in enumerate(valid_idx): - X_drop = np.delete(X_joint, k + 1, axis=1) - try: - c_drop = np.linalg.lstsq(X_drop, y, rcond=None)[0] - ss_drop = np.sum((y - X_drop @ c_drop)**2) - except Exception: + mask = ~np.isnan(x) + if mask.sum() < 4: pve_dict[idx] = 0.0 continue - partial_ss = ss_drop - ss_full - pve_dict[idx] = max(partial_ss / SST * 100, 0.0) - return pve_dict, SST + 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() -# ─────────────────────── 10 STATISTICAL MODELS ──────────────────────────────── +def fig_to_pil(fig): + buf = io.BytesIO() + fig.savefig(buf, format="png", dpi=150, bbox_inches="tight", facecolor=fig.get_facecolor()) + buf.seek(0) + from PIL import Image + return Image.open(buf).copy() + +# ─────────────────────── 10 STATISTICAL MODELS ─────────────────────────────────── def ols_gwas(y, G): n, m = G.shape pvals = np.ones(m); betas = np.zeros(m); ses = np.zeros(m) for j in range(m): - b, se, p = ols_linregress(y, G[:, j]) - pvals[j] = p; betas[j] = b; ses[j] = se + x = G[:, j] - G[:, j].mean() + if x.std() < 1e-8: continue + slope, _, _, p, se = stats.linregress(x, y) + pvals[j] = p; betas[j] = slope; ses[j] = se return pvals, betas, ses def mlm_gwas(y, G, K): n, m = G.shape pvals = np.ones(m); betas = np.zeros(m); ses = np.zeros(m) - Vg, Ve, delta, eigvals, U = reml_variance_components(y, K) - V = Vg * K + Ve * np.eye(n) - try: - V_inv = np.linalg.inv(V + np.eye(n) * 1e-6) - except np.linalg.LinAlgError: - V_inv = np.eye(n) + 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]] + y_res = y - LinearRegression().fit(Q, y).predict(Q) for j in range(m): x = G[:, j] - if x.std() < 1e-8: - continue - b, se, p = gls_test(y, x, V_inv) - pvals[j] = p; betas[j] = b; ses[j] = se + x_res = x - LinearRegression().fit(Q, x).predict(Q) + if x_res.std() < 1e-8: continue + slope, _, _, p, se = stats.linregress(x_res, y_res) + pvals[j] = p; betas[j] = slope; ses[j] = se return pvals, betas, ses def glm_gwas(y, G): n, m = G.shape pvals = np.ones(m); betas = np.zeros(m); ses = np.zeros(m) - n_pcs = min(3, n - 3, G.shape[1]) - if n_pcs < 1: - return ols_gwas(y, G) - try: - PCs = PCA(n_components=n_pcs).fit_transform( - StandardScaler().fit_transform(G)) - lr = LinearRegression().fit(PCs, y) - y_adj = y - lr.predict(PCs) - except Exception: - y_adj = y - y.mean() - PCs = np.zeros((n, 1)); n_pcs = 1 - df_correct = max(n - n_pcs - 2, 1) + 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) for j in range(m): x = G[:, j] - if x.std() < 1e-8: - continue - try: - x_adj = x - LinearRegression().fit(PCs, x).predict(PCs) - except Exception: - x_adj = x - x.mean() - if x_adj.std() < 1e-8: - continue - slope, _, _, _, se = stats.linregress(x_adj, y_adj) - t_stat = slope / (se + 1e-12) - p = float(2 * stats.t.sf(abs(t_stat), df=df_correct)) + if x.std() < 1e-8: continue + x_adj = x - LinearRegression().fit(PCs, x).predict(PCs) + slope, _, _, p, se = stats.linregress(x_adj, y_adj) pvals[j] = p; betas[j] = slope; ses[j] = se return pvals, betas, ses def cmlm_gwas(y, G, K): n, m = G.shape pvals = np.ones(m); betas = np.zeros(m); ses = np.zeros(m) - eigvals_k, eigvecs_k = np.linalg.eigh(K + np.eye(n) * 1e-6) - idx_sort = np.argsort(eigvals_k)[::-1] - n_pcs_k = min(3, n - 2) - Q_kin = eigvecs_k[:, idx_sort[:n_pcs_k]] - n_groups = min(max(2, n // 10), 8) - try: - km = KMeans(n_clusters=n_groups, n_init=5, random_state=42) - labels = km.fit_predict(Q_kin) - group_mat = np.column_stack([ - K[:, labels == g].mean(axis=1) for g in range(n_groups) - ]) - y_res = y - LinearRegression().fit(group_mat, y).predict(group_mat) - except Exception: - y_res = y - y.mean() - group_mat = np.ones((n, 1)) - df_correct = max(n - n_groups - 2, 1) + 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)]) + y_res = y - LinearRegression().fit(group_means, y).predict(group_means) for j in range(m): x = G[:, j] - if x.std() < 1e-8: - continue - try: - x_res = x - LinearRegression().fit(group_mat, x).predict(group_mat) - except Exception: - x_res = x - x.mean() - if x_res.std() < 1e-8: - continue - slope, _, _, _, se = stats.linregress(x_res, y_res) - t_stat = slope / (se + 1e-12) - p = float(2 * stats.t.sf(abs(t_stat), df=df_correct)) + x_res = x - LinearRegression().fit(group_means, x).predict(group_means) + if x_res.std() < 1e-8: continue + slope, _, _, p, se = stats.linregress(x_res, y_res) pvals[j] = p; betas[j] = slope; ses[j] = se return pvals, betas, ses -def blink_gwas(y, G, K): +def blink_gwas(y, G): n, m = G.shape pvals = np.ones(m); betas = np.zeros(m); ses = np.zeros(m) - U, d, Uty, Ut1, Vg, Ve, delta = precompute_rotation(y, K) - init_p = np.ones(m) - for j in range(m): - Utx = U.T @ G[:, j] - if Utx.std() < 1e-8: - continue - _, _, p = rotated_gls_snp(Utx, Uty, Ut1, d) - init_p[j] = p - qtns = [] - candidates = list(np.argsort(init_p)[:min(20, m)]) - best_bic = np.inf - for cand in candidates: - trial_qtns = qtns + [cand] - X_trial = np.column_stack([np.ones(n)] + [G[:, q] for q in trial_qtns]) - try: - coeffs = np.linalg.lstsq(X_trial, y, rcond=None)[0] - resid = y - X_trial @ coeffs - sigma2 = np.var(resid) - bic = n * np.log(max(sigma2, 1e-12)) + X_trial.shape[1] * np.log(n) - except Exception: - bic = np.inf - if bic < best_bic - 1e-3: - best_bic = bic - qtns = trial_qtns - if len(qtns) >= 5: - break - if qtns: - cov = np.column_stack([np.ones(n)] + [G[:, q] for q in qtns]) - try: - y_adj = y - cov[:, 1:] @ np.linalg.lstsq(cov[:, 1:], y, rcond=None)[0] - except Exception: - y_adj = y - y.mean() - else: - y_adj = y - y.mean() - df_correct = max(n - len(qtns) - 2, 1) + 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 - if qtns: - try: - x_adj = x - cov[:, 1:] @ np.linalg.lstsq(cov[:, 1:], x, rcond=None)[0] - except Exception: - x_adj = x - x.mean() - else: - x_adj = x - x.mean() - if x_adj.std() < 1e-8: - continue - slope, _, _, _, se = stats.linregress(x_adj, y_adj) - t_stat = slope / (se + 1e-12) - p = float(2 * stats.t.sf(abs(t_stat), df=df_correct)) + if x.std() < 1e-8: continue + slope, _, _, p, se = stats.linregress(x, y_adj) pvals[j] = p; betas[j] = slope; ses[j] = se return pvals, betas, ses def farmcpu_gwas(y, G, K): n, m = G.shape pvals = np.ones(m); betas = np.zeros(m); ses = np.zeros(m) - U, d, Uty, Ut1, Vg, Ve, delta = precompute_rotation(y, K) - qtns_prev = [] - for iteration in range(5): - for j in range(m): - x = G[:, j] - if x.std() < 1e-8: - continue - if qtns_prev: - Q_cov = G[:, qtns_prev] - try: - x_res = x - LinearRegression().fit(Q_cov, x).predict(Q_cov) - y_res = y - LinearRegression().fit(Q_cov, y).predict(Q_cov) - except Exception: - x_res = x - x.mean() - y_res = y - y.mean() - else: - x_res = x - x.mean() - y_res = y - y.mean() - if x_res.std() < 1e-8: - continue - slope, _, _, _, se = stats.linregress(x_res, y_res) - df_c = max(n - len(qtns_prev) - 2, 1) - t_stat = slope / (se + 1e-12) - pvals[j] = float(2 * stats.t.sf(abs(t_stat), df=df_c)) - betas[j] = slope; ses[j] = se - candidates = list(np.argsort(pvals)[:min(15, m)]) - best_bic = np.inf - new_qtns = [] - for cand in candidates: - trial = new_qtns + [cand] - X_t = np.column_stack([np.ones(n)] + [G[:, q] for q in trial]) - try: - r = np.linalg.lstsq(X_t, y, rcond=None)[0] - resid = y - X_t @ r - bic = n * np.log(max(np.var(resid), 1e-12)) + X_t.shape[1] * np.log(n) - except Exception: - bic = np.inf - if bic < best_bic - 1e-3: - best_bic = bic - new_qtns = trial - if len(new_qtns) >= 5: - break - if set(new_qtns) == set(qtns_prev): - break - qtns_prev = new_qtns + 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, se = stats.linregress(x, y_adj) + pvals[j] = p; betas[j] = slope; ses[j] = se return pvals, betas, ses def emmax_gwas(y, G, K): n, m = G.shape pvals = np.ones(m); betas = np.zeros(m); ses = np.zeros(m) - U, d, Uty, Ut1, Vg, Ve, delta = precompute_rotation(y, K) + tau = np.var(y) * 0.5 + sigma = np.var(y) * 0.5 + V = tau * K + sigma * np.eye(n) + try: + V_inv = np.linalg.inv(V + np.eye(n) * 1e-6) + except: + V_inv = np.eye(n) for j in range(m): - x = G[:, j] - if x.std() < 1e-8: - continue - Utx = U.T @ x - if Utx.std() < 1e-8: - continue - b, se, p = rotated_gls_snp(Utx, Uty, Ut1, d) - pvals[j] = p; betas[j] = b; ses[j] = se + x = G[:, j].reshape(-1, 1) + Px = V_inv @ x + beta = (x.T @ Px @ y) / (x.T @ Px @ x + 1e-10) + betas[j] = float(beta) + 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, ses def plink_gwas(y, G): n, m = G.shape 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): - b, se, p = ols_linregress(y, G[:, j]) - pvals[j] = p; betas[j] = b; ses[j] = se + x = G[:, j] + if x.std() < 1e-8: continue + try: + ct = np.zeros((2, 3)) + for g in [0, 1, 2]: + mask = x == g + ct[0, g] = np.sum(y_bin[mask]) + ct[1, g] = np.sum(1 - y_bin[mask]) + if ct.sum() > 4: + chi2, p, _, _ = stats.chi2_contingency(ct + 0.5) + pvals[j] = p + slope, _, _, p2, se = stats.linregress(x, y_bin) + betas[j] = slope; ses[j] = se + except: + pass return pvals, betas, ses def gapit3_gwas(y, G, K): n, m = G.shape pvals = np.ones(m); betas = np.zeros(m); ses = np.zeros(m) - n_pcs = min(3, n - 3, G.shape[1]) - try: - PCs = PCA(n_components=max(1, n_pcs)).fit_transform( - StandardScaler().fit_transform(G)) - except Exception: - PCs = np.zeros((n, 1)) - U, d, Uty, Ut1, Vg, Ve, delta = precompute_rotation(y, K) + 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]) qtns = [] - for iteration in range(6): - cov_parts = [PCs] - if qtns: - cov_parts.append(G[:, qtns]) - cov = np.hstack(cov_parts) + for iteration in range(2): for j in range(m): x = G[:, j] - if x.std() < 1e-8: - continue - try: - x_res = x - LinearRegression().fit(cov, x).predict(cov) - y_res = y - LinearRegression().fit(cov, y).predict(cov) - except Exception: - x_res = x - x.mean() - y_res = y - y.mean() - if x_res.std() < 1e-8: - continue - slope, _, _, _, se = stats.linregress(x_res, y_res) - df_c = max(n - cov.shape[1] - 2, 1) - t_stat = slope / (se + 1e-12) - pvals[j] = float(2 * stats.t.sf(abs(t_stat), df=df_c)) - betas[j] = slope; ses[j] = se - candidates = list(np.argsort(pvals)[:min(15, m)]) - best_bic = np.inf - new_qtns = [] - base_X = np.column_stack([np.ones(n), PCs]) - for cand in candidates: - trial = new_qtns + [cand] - X_t = np.hstack([base_X] + [G[:, q].reshape(-1, 1) for q in trial]) - try: - r = np.linalg.lstsq(X_t, y, rcond=None)[0] - resid = y - X_t @ r - bic = n * np.log(max(np.var(resid), 1e-12)) + X_t.shape[1] * np.log(n) - except Exception: - bic = np.inf - if bic < best_bic - 1e-3: - best_bic = bic - new_qtns = trial - if len(new_qtns) >= 5: - break - if set(new_qtns) == set(qtns): + if x.std() < 1e-8: continue + if len(qtns) > 0: + cov = np.column_stack([covars] + [G[:, q].reshape(-1,1) for q in qtns]) + else: + cov = covars + x_res = x - LinearRegression().fit(cov, x).predict(cov) + y_res = y - LinearRegression().fit(cov, y).predict(cov) + 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 - qtns = new_qtns return pvals, betas, ses def gemma_gwas(y, G, K): n, m = G.shape 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) + row_mean = K.mean(axis=1, keepdims=True) + col_mean = K.mean(axis=0, keepdims=True) grand_mean = K.mean() - Kc = K - row_mean - col_mean + grand_mean - U, d, Uty, Ut1, Vg, Ve, delta = precompute_rotation(y, Kc) + Kc = K - row_mean - col_mean + grand_mean + eigvals, eigvecs = np.linalg.eigh(Kc + np.eye(n) * 1e-6) + idx = np.argsort(eigvals)[::-1] + n_pcs = min(4, n - 2) + Q = eigvecs[:, idx[:n_pcs]] + y_res = y - LinearRegression().fit(Q, y).predict(Q) for j in range(m): x = G[:, j] - if x.std() < 1e-8: - continue - Utx = U.T @ x - if Utx.std() < 1e-8: - continue - b, se, p = rotated_gls_snp(Utx, Uty, Ut1, d) - pvals[j] = p; betas[j] = b; ses[j] = se + x_res = x - LinearRegression().fit(Q, x).predict(Q) + if x_res.std() < 1e-8: continue + 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, ses -# ─────────────────────── FIGURE HELPERS ─────────────────────────────────────── -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) - data = buf.read() - buf.close() - return data - -def _compute_x_coords(chroms, positions, chrom_list): - """FIX: Chromosome x-coordinates start from chromosome 1 (not 0).""" - x_coords = np.zeros(len(chroms)) +# ─────────────────────── PLOTS ─────────────────────────────────────────────────── +def plot_manhattan(pvals, chroms, positions, title="Manhattan Plot", model_name=""): + fig, ax = plt.subplots(figsize=(16, 5)) + style_fig(fig) + 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 - max_pos = max(positions) if len(positions) > 0 else 1 + tick_pos, tick_lab, x_coords = [], [], np.zeros(len(pvals)) for ch in chrom_list: mask = chroms == ch - if not mask.any(): - continue pos = positions[mask] - # Start from 1 for chromosome 1 - x_coords[mask] = pos - pos.min() + x_offset + 1 - x_offset += pos.max() - pos.min() + max_pos * 0.02 + 1 - return x_coords - -def _compute_tick_positions(x_coords, chroms, chrom_list): - tick_pos, tick_lab = [], [] - for ch in chrom_list: - mask = chroms == ch - if not mask.any(): - continue - xc = x_coords[mask] - tick_pos.append((xc.min() + xc.max()) / 2) + if len(pos) == 0: continue + order = np.argsort(pos) + x_vals = pos[order] - pos.min() + x_offset + x_coords[np.where(mask)[0][order]] = x_vals + tick_pos.append(x_vals.mean()) tick_lab.append(f"Chr{ch}") - return tick_pos, tick_lab - -def compute_lambda(pvals): - return (np.median(stats.chi2.ppf(1 - np.clip(pvals, 1e-10, 1), df=1)) - / stats.chi2.ppf(0.5, df=1)) + 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 + ax.axhline(sug_line, color=ACCENT_TEAL, ls=":", lw=1, alpha=0.7, label=f"Suggestive (1e-5)") + ax.axhline(sig_line, color=ACCENT_CORAL, ls="--", lw=1.5, label=f"GW sig. (5e-8)") + 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, + 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) + ax.set_xlim(-x_offset * 0.01, x_offset * 1.01) + fig.tight_layout() + return fig -def select_best_models(all_results, n_best=4): - """Select best-performing models based on lambda closest to 1.0.""" - scores = {} - for mname, (pvals, betas, ses) in all_results.items(): - lam = compute_lambda(pvals) - lam_score = abs(lam - 1.0) - n_sig = int((pvals < 5e-8).sum()) - total = len(pvals) - sig_frac = n_sig / max(total, 1) - if sig_frac > 0.2: - lam_score += 2.0 - scores[mname] = lam_score - best = sorted(scores.keys(), key=lambda m: scores[m])[:n_best] - return best - -# ─────────────────────── IMPROVED CIRCOS PLOT (NO OVERLAPPING LABELS) ───────── -def plot_circos_interactive(all_results, chroms, positions, snp_names): - """ - COMPLETELY REDESIGNED: No overlapping labels. - - Chromosome labels placed outside with radial lines pointing to arcs - - Model labels placed in dedicated sections around the circle - - Clean legend on the right - """ - best_models = select_best_models(all_results, n_best=min(4, len(all_results))) - selected_results = {m: all_results[m] for m in best_models if m in all_results} - - sort_idx = np.lexsort((positions, chroms)) - chroms_s = chroms[sort_idx] - positions_s = positions[sort_idx] - snp_s = [str(snp_names[i]) for i in sort_idx] - total_snps = len(chroms_s) - chrom_list = sorted(set(chroms_s)) - - # Angular positions for each SNP - angles_deg = np.linspace(0, 360, total_snps, endpoint=False) - - fig = go.Figure() - - n_models = len(selected_results) - r_chr_band = 0.82 - ring_outer = 0.78 - ring_inner = 0.15 - ring_gap = 0.02 - total_ring_space = ring_outer - ring_inner - ring_width = (total_ring_space - ring_gap * (n_models - 1)) / max(n_models, 1) +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 - sig_line = -np.log10(5e-8) +def plot_qq_all_models(all_results): + n_models = len(all_results) + ncols = min(3, n_models) + nrows = (n_models + ncols - 1) // ncols + 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()): + 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]) + 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))) + 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.set_xlabel("Expected -log₁₀(p)", fontsize=8) + ax.set_ylabel("Observed -log₁₀(p)", fontsize=8) + 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 - # ── 1. Chromosome color arcs and labels (no overlap) ── - for ci, ch in enumerate(chrom_list): - mask = chroms_s == ch - idxs = np.where(mask)[0] - if len(idxs) == 0: - continue - a_start = angles_deg[idxs[0]] - a_end = angles_deg[idxs[-1]] - a_width = max(a_end - a_start, 1.0) - mid_a = (a_start + a_end) / 2 - col = CHR_PALETTE[ci % len(CHR_PALETTE)] - - # Colored arc - fig.add_trace(go.Barpolar( - r=[0.05], - theta=[mid_a], - width=[a_width + 1.5], - base=[r_chr_band], - marker_color=col, - marker_line_color="white", - marker_line_width=0.3, - opacity=0.9, - showlegend=False, - hoverinfo='skip', - name=f"Chr{ch}", - )) - - # Chromosome label with connector line - label_radius = r_chr_band + 0.08 - rad = mid_a * np.pi / 180 - - # Determine if label should be placed radially outward or inward - if mid_a > 90 and mid_a < 270: - # Bottom half - place labels inside - label_radius = r_chr_band - 0.05 - text_angle = mid_a - else: - # Top half - place outside - label_radius = r_chr_band + 0.08 - text_angle = mid_a - - # Connector line - r_connector = [r_chr_band, label_radius] - theta_connector = [mid_a, mid_a] - fig.add_trace(go.Scatterpolar( - r=r_connector, - theta=theta_connector, - mode='lines', - line=dict(color=col, width=1.5), - showlegend=False, - hoverinfo='skip', - )) - - # Label text - fig.add_trace(go.Scatterpolar( - r=[label_radius - 0.02 if mid_a > 90 and mid_a < 270 else label_radius + 0.02], - theta=[mid_a], - mode='text', - text=[f"Chr{ch}"], - textfont=dict(size=9, color=col, weight='bold'), - showlegend=False, - hoverinfo='skip', - )) - - # ── 2. Model data rings ── - for midx, (mname, (pvals, betas, _)) in enumerate(selected_results.items()): - pvals_s = pvals[sort_idx] - log_p_s = -np.log10(np.clip(pvals_s, 1e-300, 1)) - - r_base = ring_inner + midx * (ring_width + ring_gap) - r_top = r_base + ring_width - max_lp = max(log_p_s.max(), sig_line, 1.0) - r_data = r_base + (log_p_s / max_lp) * ring_width * 0.9 - col = MODEL_COLORS.get(mname, CHR_PALETTE[midx % len(CHR_PALETTE)]) - - sig_mask = log_p_s >= sig_line - ns_mask = ~sig_mask - - # Non-significant SNPs - if ns_mask.any(): - fig.add_trace(go.Scatterpolar( - r=r_data[ns_mask], - theta=angles_deg[ns_mask], - mode='markers', - marker=dict(color=col, size=2.5, opacity=0.6, line=dict(width=0)), - name=mname, - legendgroup=mname, - text=[f"Model: {mname}
SNP: {snp_s[i]}
Chr: {chroms_s[i]}
" - f"p: {pvals_s[ns_mask][k]:.3e}
-log10(p): {log_p_s[ns_mask][k]:.2f}" - for k, i in enumerate(np.where(ns_mask)[0])], - hovertemplate="%{text}", - showlegend=(midx == 0), - )) - - # Significant SNPs - if sig_mask.any(): - sig_idxs = np.where(sig_mask)[0] - fig.add_trace(go.Scatterpolar( - r=r_data[sig_mask], - theta=angles_deg[sig_mask], - mode='markers', - marker=dict( - color='#FF1744', size=8, symbol='diamond', - line=dict(color='#7F0000', width=0.8) - ), - name=f"{mname} ★", - legendgroup=f"{mname}_sig", - text=[f"★ GW SIGNIFICANT ★
Model: {mname}
SNP: {snp_s[i]}
" - f"Chr: {chroms_s[i]}
p: {pvals_s[sig_mask][k]:.3e}" - for k, i in enumerate(sig_idxs)], - hovertemplate="%{text}", - showlegend=(midx == 0 and len(sig_idxs) > 0), - )) - - # Model label - placed in dedicated corner (bottom left) - lam_val = compute_lambda(pvals) - label_angle = 270 - (midx * 15) # Spread labels around bottom - r_mid = (r_base + r_top) / 2 - - fig.add_trace(go.Scatterpolar( - r=[r_mid], - theta=[label_angle], - mode='text', - text=[f"{mname}"], - textfont=dict(size=8, color=col), - showlegend=False, - hoverinfo='skip', - )) - - # Lambda annotation near model label - fig.add_trace(go.Scatterpolar( - r=[r_mid - 0.02], - theta=[label_angle + 2], - mode='text', - text=[f"λ={lam_val:.3f}"], - textfont=dict(size=6, color='gray'), - showlegend=False, - hoverinfo='skip', - )) - - # ── 3. Center circle ── - fig.add_trace(go.Scatterpolar( - r=[ring_inner] * 361, - theta=list(range(361)), - mode='lines', - line=dict(color='#CBD5E1', width=1), - fill='toself', - fillcolor='rgba(248,250,252,0.9)', - showlegend=False, - hoverinfo='skip', - )) - - # ── 4. Inner circle text (GWAS title) ── - fig.add_trace(go.Scatterpolar( - r=[ring_inner - 0.05], - theta=[0], - mode='text', - text=['GWAS
Circos
'], - textfont=dict(size=11, color='#2C5F8A'), - showlegend=False, - hoverinfo='skip', - )) - - lam_str = " | ".join([ - f"{m} λ={compute_lambda(all_results[m][0]):.3f}" for m in best_models - ]) - n_sig_total = sum(int((all_results[m][0] < 5e-8).sum()) for m in best_models) - - fig.update_layout( - title=dict( - text=(f"Circos Plot — Best {n_models} Models" - f"
{lam_str}" - f"
★ = Genome-wide significant (5×10⁻⁸) | Total sig hits: {n_sig_total}"), - font=dict(size=13, color="#1E293B"), - x=0.5, - xanchor='center', - ), - polar=dict( - radialaxis=dict( - showticklabels=False, - showgrid=False, - showline=False, - range=[0, 1.0], - ), - angularaxis=dict( - showticklabels=False, - showgrid=False, - showline=False, - direction="clockwise", - rotation=90, - ), - bgcolor="white", - ), - showlegend=True, - legend=dict( - orientation="v", - yanchor="middle", - y=0.5, - xanchor="left", - x=1.05, - font=dict(size=10), - itemsizing='constant', - bordercolor="#E2E8F0", - borderwidth=1, - bgcolor="rgba(255,255,255,0.95)", - ), - paper_bgcolor="white", - height=700, - width=900, - margin=dict(l=50, r=180, t=120, b=50), - ) +def plot_qq_overlay(all_results): + fig, ax = plt.subplots(figsize=(9, 9)) + style_fig(fig) + 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, 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) + ax.legend(fontsize=8, framealpha=0.2, facecolor=PANEL_MID, edgecolor=GRID_LINE, labelcolor=TEXT_MAIN) + fig.tight_layout() return fig -# ─────────────────────── INTERACTIVE MANHATTAN PLOT (STARTS FROM CHR1) ──────── -def plot_manhattan_interactive(pvals, chroms, positions, snp_names, title="Manhattan Plot", model_name=""): - """FIX: x-axis starts from chromosome 1 (not 0).""" - log_p = -np.log10(np.clip(pvals, 1e-300, 1)) - sig_line = -np.log10(5e-8) - sug_line = -np.log10(1e-5) +def plot_circos(all_results, chroms, positions): + fig, ax = plt.subplots(figsize=(14, 14), subplot_kw=dict(projection='polar')) + fig.patch.set_facecolor(BG_DARK) + ax.set_facecolor(BG_DARK) + ax.grid(False) + ax.set_yticks([]) + ax.set_xticks([]) + ax.spines['polar'].set_visible(False) chrom_list = sorted(set(chroms)) - x_coords = _compute_x_coords(chroms, positions, chrom_list) - - # Ensure x-axis starts at 1 - x_min = 1 - x_max = x_coords.max() if len(x_coords) > 0 else 100 - - fig = go.Figure() - - for ci, ch in enumerate(chrom_list): - mask = chroms == ch - col = CHR_PALETTE[ci % len(CHR_PALETTE)] - xc = x_coords[mask] - yc = log_p[mask] - nm = [str(snp_names[i]) for i in np.where(mask)[0]] - pc = [float(pvals[i]) for i in np.where(mask)[0]] - - sig_m = yc >= sig_line - ns_m = ~sig_m - - if ns_m.any(): - fig.add_trace(go.Scatter( - x=xc[ns_m], y=yc[ns_m], - mode='markers', - marker=dict(color=col, size=4, opacity=0.75, line=dict(width=0)), - name=f"Chr{ch}", - text=[f"SNP: {nm[i]}
Chr: {ch}
p-value: {pc[i]:.3e}
-log10(p): {yc[ns_m][i]:.2f}" - for i in range(ns_m.sum())], - hovertemplate="%{text}", - showlegend=(ci < 10), - )) - if sig_m.any(): - fig.add_trace(go.Scatter( - x=xc[sig_m], y=yc[sig_m], - mode='markers', - marker=dict(color='#FF1744', size=10, symbol='diamond', - line=dict(color='#7F0000', width=1)), - name=f"Sig (Chr{ch})", - text=[f"SIGNIFICANT
SNP: {nm[i]}
Chr: {ch}
p-value: {pc[i]:.3e}
-log10(p): {yc[sig_m][i]:.2f}" - for i in range(sig_m.sum())], - hovertemplate="%{text}", - showlegend=False, - )) - - fig.add_shape(type="line", x0=x_min, x1=x_max, y0=sig_line, y1=sig_line, - line=dict(color="#FF4560", width=2, dash="dash")) - fig.add_shape(type="line", x0=x_min, x1=x_max, y0=sug_line, y1=sug_line, - line=dict(color="#00D9E9", width=1.5, dash="dot")) - - fig.add_annotation(x=x_max*0.98, y=sig_line+0.3, text="GW significant (5×10⁻⁸)", - showarrow=False, font=dict(color="#FF4560", size=10), - xanchor="right") - fig.add_annotation(x=x_max*0.98, y=sug_line+0.3, text="Suggestive (1×10⁻⁵)", - showarrow=False, font=dict(color="#00D9E9", size=10), - xanchor="right") - - tick_pos, tick_lab = _compute_tick_positions(x_coords, chroms, chrom_list) - - lam = compute_lambda(pvals) - n_sig = int((pvals < 5e-8).sum()) - - fig.update_layout( - title=dict( - text=f"{title} — {model_name}
λ = {lam:.4f} | Significant SNPs: {n_sig} | Total: {len(pvals)}", - font=dict(size=15, color="#1E293B"), - ), - xaxis=dict( - tickmode='array', - tickvals=tick_pos, - ticktext=tick_lab, - tickangle=45, - tickfont=dict(size=9), - showgrid=False, - zeroline=False, - title="Chromosome", - range=[x_min * 0.95, x_max * 1.01], - ), - yaxis=dict( - title="-log₁₀(p-value)", - gridcolor="#E2E8F0", - gridwidth=0.5, - ), - plot_bgcolor="white", - paper_bgcolor="white", - height=520, - legend=dict( - orientation="h", - yanchor="bottom", - y=1.02, - xanchor="right", - x=1, - font=dict(size=9), - ), - hovermode="closest", - margin=dict(l=60, r=40, t=100, b=80), - ) + total_snps = len(chroms) + snp_angles = np.linspace(0, 2 * np.pi, total_snps, endpoint=False) + sort_idx = np.lexsort((positions, chroms)) + angles_sorted = snp_angles.copy() + outer_r = 1.0 + for ch in chrom_list: + mask = chroms[sort_idx] == ch + idxs = np.where(mask)[0] + if len(idxs) == 0: continue + theta = angles_sorted[idxs] + col = CHR_PALETTE[chrom_list.index(ch) % len(CHR_PALETTE)] + 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) + 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') + 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] + 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)]) + max_lp = max(log_p.max(), sig_line, 1) + lp_norm = log_p[sort_idx] / max_lp * r_max_data + 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) + 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, + 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 -# ─────────────────────── IMPROVED LD DECAY PLOT (WITH FULL INTERPRETATION) ───── -def plot_ld_decay_interactive(G, positions, chroms): - """ - IMPROVED LD Decay plot (distance in Mb) with comprehensive interpretation: - - x-axis: Physical distance (Megabases, Mb) - - y-axis: LD estimate (r²) - - Shows where LD starts dropping significantly - - Calculates half-decay distance - - Adds interpretation annotations - """ - chrom_list = sorted(set(chroms)) - sample_per_chr = 100 - sampled_idx = [] - rng = np.random.default_rng(42) - for ch in chrom_list: - idx_ch = np.where(chroms == ch)[0] - n_samp = min(sample_per_chr, len(idx_ch)) - if n_samp > 0: - sampled_idx.extend(rng.choice(idx_ch, n_samp, replace=False).tolist()) - sampled_idx = sorted(set(sampled_idx)) - - dists_bp, r2s, chrom_pairs = [], [], [] - for ii, i in enumerate(sampled_idx): - for j in sampled_idx[ii+1:]: - if chroms[i] != chroms[j]: - continue +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) + for i in range(n_pairs): + for j in range(i+1, n_pairs): xi, xj = G[:, i], G[:, j] - mask = ~(np.isnan(xi) | np.isnan(xj)) - if mask.sum() < 4: - continue - try: - r, _ = stats.pearsonr(xi[mask], xj[mask]) - except Exception: - continue + mask = ~(np.isnan(xi) | np.isnan(xj)) + if mask.sum() < 4: continue + r, _ = stats.pearsonr(xi[mask], xj[mask]) d = abs(positions[j] - positions[i]) - if d > 0: - dists_bp.append(d) - r2s.append(r**2) - chrom_pairs.append(chroms[i]) - - fig = go.Figure() - - if len(dists_bp) < 5: - fig.add_annotation( - text="Insufficient pairwise data for LD decay
(need more SNPs on same chromosome)", - x=0.5, y=0.5, xref="paper", yref="paper", - showarrow=False, font=dict(size=14, color="#666"), - ) - fig.update_layout( - title=dict(text="Linkage Disequilibrium (LD) Decay", font=dict(size=14)), - plot_bgcolor="white", paper_bgcolor="white", height=550, - ) + dists_bp.append(d); r2s.append(r**2) + if not dists_bp: + for ax in axes: + 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) - r2s = np.array(r2s) - chrom_pairs = np.array(chrom_pairs) - - # Convert bp → Mb - dists_Mb = dists_bp / 1_000_000 - - # ── Scatter: color by chromosome ── - for ci, ch in enumerate(chrom_list): - cmask = chrom_pairs == ch - if not cmask.any(): - continue - col = CHR_PALETTE[ci % len(CHR_PALETTE)] - idx_sub = np.where(cmask)[0] - if len(idx_sub) > 800: - idx_sub = rng.choice(idx_sub, 800, replace=False) - fig.add_trace(go.Scatter( - x=dists_Mb[idx_sub], - y=r2s[idx_sub], - mode='markers', - marker=dict( - color=col, size=3, opacity=0.35, - line=dict(width=0), - ), - name=f"Chr{ch}", - legendgroup=f"chr{ch}", - hovertemplate=f"Chromosome {ch}
Distance: %{{x:.3f}} Mb
r²: %{{y:.3f}}", - )) - - # ── Binned means for decay curve ── - n_bins = 40 - pctiles = np.percentile(dists_Mb, np.linspace(0, 100, n_bins + 1)) - bin_centers, bin_means, bin_sems, bin_counts = [], [], [], [] - for k in range(len(pctiles) - 1): - mask = (dists_Mb >= pctiles[k]) & (dists_Mb < pctiles[k + 1]) - if mask.sum() >= 3: - bin_centers.append(np.median(dists_Mb[mask])) - bin_means.append(np.mean(r2s[mask])) - bin_sems.append(stats.sem(r2s[mask]) if mask.sum() > 1 else 0) - bin_counts.append(mask.sum()) - - bin_centers = np.array(bin_centers) - bin_means = np.array(bin_means) - bin_sems = np.array(bin_sems) - - # Fit exponential decay curve - smooth_x = np.array([]) - smooth_y = np.array([]) - half_decay_dist = None - r2_plateau = None - r2_initial = None - - if len(bin_centers) >= 4: - try: - from scipy.optimize import curve_fit - def decay_func(d, a, b, c): - return a * np.exp(-b * d) + c - p0 = [0.8, 0.5, 0.05] - bounds = ([0, 0.01, 0], [1.0, 100, 0.5]) - popt, _ = curve_fit(decay_func, bin_centers, bin_means, - p0=p0, bounds=bounds, maxfev=5000) - smooth_x = np.linspace(dists_Mb.min(), dists_Mb.max(), 300) - smooth_y = decay_func(smooth_x, *popt) - smooth_y = np.clip(smooth_y, 0, 1) - - # Calculate half-decay distance (where r² drops to halfway between initial and plateau) - r2_plateau = float(popt[2]) - r2_initial = float(popt[0] + popt[2]) - r2_half = (r2_initial + r2_plateau) / 2 - - # Find distance where r² reaches half - above_half = smooth_x[smooth_y >= r2_half] - if len(above_half) > 0: - half_decay_dist = above_half[-1] - - except Exception: - smooth_x = bin_centers - smooth_y = bin_means - half_decay_dist = None - else: - smooth_x = bin_centers - smooth_y = bin_means - - # ── Smooth decay curve ── - if len(smooth_x) > 0: - fig.add_trace(go.Scatter( - x=smooth_x, y=smooth_y, - mode='lines', - line=dict(color='black', width=3), - name='Fitted decay curve', - hovertemplate="Distance: %{x:.3f} Mb
Fitted r²: %{y:.3f}", - )) - - # ── Binned mean points with error bars ── - if len(bin_centers) > 0: - fig.add_trace(go.Scatter( - x=bin_centers, y=bin_means, - mode='markers', - marker=dict(color='darkred', size=6, symbol='circle', - line=dict(color='white', width=1)), - name='Binned mean r²', - error_y=dict(type='data', array=bin_sems, visible=True, - color='rgba(0,0,0,0.4)', thickness=1.5, width=3), - hovertemplate="Distance: %{x:.3f} Mb
Mean r²: %{y:.3f}
±SEM", - )) - - # ── Reference lines ── - x_max_plot = float(np.percentile(dists_Mb, 98)) * 1.05 if len(dists_Mb) > 0 else 10 - - # r² = 0.5 line (strong LD threshold) - fig.add_shape( - type="line", x0=0, x1=x_max_plot, y0=0.5, y1=0.5, - line=dict(color="#E67E22", width=2, dash="dash"), - ) - fig.add_annotation( - x=x_max_plot * 0.98, y=0.52, - text="r² = 0.5 (Strong LD)", - showarrow=False, - font=dict(size=10, color="#E67E22", weight="bold"), - xanchor="right", - ) - - # r² = 0.2 line (weak LD threshold) - fig.add_shape( - type="line", x0=0, x1=x_max_plot, y0=0.2, y1=0.2, - line=dict(color="#3498DB", width=2, dash="dot"), - ) - fig.add_annotation( - x=x_max_plot * 0.98, y=0.22, - text="r² = 0.2 (Weak LD)", - showarrow=False, - font=dict(size=10, color="#3498DB"), - xanchor="right", - ) - - # ── Half-decay annotation ── - if half_decay_dist is not None and half_decay_dist > 0: - fig.add_shape( - type="line", x0=half_decay_dist, x1=half_decay_dist, y0=0, y1=r2_half, - line=dict(color='#2ECC71', width=2.5, dash='dash'), - ) - fig.add_annotation( - x=half_decay_dist + (x_max_plot * 0.02), y=r2_half + 0.05, - text=f"Half-decay distance
{half_decay_dist:.2f} Mb", - showarrow=True, - arrowhead=2, - arrowcolor='#2ECC71', - font=dict(size=10, color='#2ECC71', weight="bold"), - ax=30, ay=-30, - ) - - # ── Comprehensive interpretation box ── - overall_mean_r2 = float(np.mean(r2s)) if len(r2s) > 0 else 0 - n_pairs = len(r2s) - - # Calculate LD decay rate (percentage drop in first few Mb) - early_bins = bin_centers[bin_centers <= 1] if len(bin_centers) > 0 else [] - early_means = bin_means[bin_centers <= 1] if len(bin_centers) > 0 else [] - decay_rate = None - if len(early_bins) >= 2: - slope, _ = np.polyfit(early_bins, early_means, 1) - decay_rate = abs(slope * 100) # % drop per Mb - - interp_text = ( - f"📊 LD DECAY ANALYSIS
" - f"━━━━━━━━━━━━━━━━━━━━━━
" - f"Pairs analyzed: {n_pairs:,}
" - f"Mean r² overall: {overall_mean_r2:.3f}
" - ) - - if r2_initial is not None: - interp_text += f"Initial LD (0 Mb): {r2_initial:.3f}
" - if r2_plateau is not None: - interp_text += f"Plateau LD: {r2_plateau:.3f}
" - if half_decay_dist is not None: - interp_text += f"Half-decay distance: {half_decay_dist:.2f} Mb
" - if decay_rate is not None: - interp_text += f"Initial decay rate: {decay_rate:.1f}% per Mb
" - - interp_text += ( - f"━━━━━━━━━━━━━━━━━━━━━━
" - f"▼ INTERPRETATION
" - ) - - if half_decay_dist is not None: - if half_decay_dist < 0.1: - interp_text += f"• Very rapid LD decay (half at {half_decay_dist*1000:.0f} kb)
→ Suggests diverse germplasm / fine mapping feasible
" - elif half_decay_dist < 0.5: - interp_text += f"• Moderate LD decay (half at {half_decay_dist:.2f} Mb)
→ Moderate genetic diversity
" - else: - interp_text += f"• Slow LD decay (half at {half_decay_dist:.2f} Mb)
→ Narrow genetic base / linkage blocks large
" - - if overall_mean_r2 > 0.4: - interp_text += f"• High overall LD (mean r²={overall_mean_r2:.2f})
→ Fewer independent tests, lower mapping resolution
" - elif overall_mean_r2 > 0.2: - interp_text += f"• Moderate overall LD (mean r²={overall_mean_r2:.2f})
→ Balanced mapping resolution
" - else: - interp_text += f"• Low overall LD (mean r²={overall_mean_r2:.2f})
→ High mapping resolution, many independent tests
" - - fig.add_annotation( - x=0.02, y=0.98, xref="paper", yref="paper", - text=interp_text, - showarrow=False, - font=dict(size=10, color="#2D3142", family="monospace"), - bgcolor="rgba(255,255,255,0.92)", - bordercolor="#CBD5E1", - borderwidth=1.5, - borderpad=8, - align="left", - xanchor="left", - yanchor="top", - ) - - fig.update_layout( - title=dict( - text=( - "🔗 Linkage Disequilibrium (LD) Decay Analysis" - "
Intra-chromosomal pairwise r² vs physical distance (Mb) | " - "Black curve = fitted exponential decay | Colored points = individual SNP pairs" - ), - font=dict(size=14, color="#1E293B"), - ), - xaxis=dict( - title="Physical distance (Megabases, Mb)", - gridcolor="#E2E8F0", - gridwidth=0.8, - zeroline=True, - zerolinecolor="#CBD5E1", - range=[0, x_max_plot], - tickfont=dict(size=11), - ticksuffix=" Mb", - ), - yaxis=dict( - title="Linkage disequilibrium (r²)", - gridcolor="#E2E8F0", - gridwidth=0.8, - range=[0, 1.05], - tickfont=dict(size=11), - dtick=0.2, - ), - plot_bgcolor="white", - paper_bgcolor="white", - height=600, - hovermode="closest", - legend=dict( - orientation="v", - yanchor="top", - y=0.99, - xanchor="right", - x=0.99, - font=dict(size=9), - bgcolor="rgba(255,255,255,0.85)", - bordercolor="#E2E8F0", - borderwidth=1, - ), - margin=dict(l=80, r=220, t=100, b=70), - ) - return fig - - -# ─────────────────────── INTERACTIVE QQ PLOT ────────────────────────────────── -def plot_qq_interactive_single(pvals, model_name="", color=None): - """Interactive QQ plot with confidence band.""" - if color is None: - color = "#775DD0" - n = len(pvals) - obs_raw = -np.log10(np.clip(pvals, 1e-300, 1)) - sort_i = np.argsort(obs_raw)[::-1] - obs = obs_raw[sort_i] - exp = -np.log10(np.arange(1, n + 1) / n) - - ranks = np.arange(1, n + 1) - ci_lo = -np.log10(stats.beta.ppf(0.975, ranks, n - ranks + 1)) - ci_hi = -np.log10(stats.beta.ppf(0.025, ranks, n - ranks + 1)) - - lam = compute_lambda(pvals) - lam_col = "green" if lam <= 1.05 else "orange" if lam <= 1.15 else "red" - sig_thr = -np.log10(5e-8) - - fig = go.Figure() - - fig.add_trace(go.Scatter( - x=np.concatenate([exp, exp[::-1]]), - y=np.concatenate([ci_hi, ci_lo[::-1]]), - fill='toself', - fillcolor='rgba(120,120,180,0.15)', - line=dict(color='rgba(0,0,0,0)'), - name='95% CI', - hoverinfo='skip', - )) - - xy_max = max(float(exp.max()), float(obs.max())) * 1.06 - fig.add_trace(go.Scatter( - x=[0, xy_max], y=[0, xy_max], - mode='lines', - line=dict(color='#E8453C', width=2, dash='dash'), - name='Expected (y=x)', - hoverinfo='skip', - )) - - sig_mask = obs >= sig_thr - ns_mask = ~sig_mask - - if ns_mask.any(): - fig.add_trace(go.Scatter( - x=exp[ns_mask], y=obs[ns_mask], - mode='markers', - marker=dict(color=color, size=5, opacity=0.8), - name='Non-significant', - text=[f"Expected: {exp[ns_mask][i]:.3f}
Observed: {obs[ns_mask][i]:.3f}" - for i in range(ns_mask.sum())], - hovertemplate="%{text}", - )) - if sig_mask.any(): - fig.add_trace(go.Scatter( - x=exp[sig_mask], y=obs[sig_mask], - mode='markers', - marker=dict(color='#FF1744', size=10, symbol='diamond', - line=dict(color='#7F0000', width=1)), - name=f'GW Significant ({sig_mask.sum()})', - text=[f"Expected: {exp[sig_mask][i]:.3f}
Observed: {obs[sig_mask][i]:.3f}" - for i in range(sig_mask.sum())], - hovertemplate="%{text}", - )) - - fig.add_shape(type="line", x0=0, x1=xy_max, y0=sig_thr, y1=sig_thr, - line=dict(color="#FF4560", width=1, dash="dot")) - - fig.add_annotation( - x=0.05, y=0.95, xref="paper", yref="paper", - text=f"λ = {lam:.4f}", - showarrow=False, - font=dict(size=14, color=lam_col, family="monospace"), - bgcolor="white", - bordercolor=lam_col, - borderwidth=2, - borderpad=6, - ) - - fig.update_layout( - title=dict( - text=f"QQ Plot — {model_name}", - font=dict(size=15, color="#1E293B"), - ), - xaxis=dict(title="Expected −log₁₀(p)", gridcolor="#E2E8F0"), - yaxis=dict(title="Observed −log₁₀(p)", gridcolor="#E2E8F0"), - plot_bgcolor="white", - paper_bgcolor="white", - height=500, - legend=dict(font=dict(size=10)), - hovermode="closest", - margin=dict(l=60, r=40, t=80, b=60), - ) + 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 = [], [], [] + for k in range(len(bins)-1): + mask = (dists >= bins[k]) & (dists < bins[k+1]) + if mask.sum() > 2: + centers.append((bins[k] + bins[k+1]) / 2) + means.append(np.mean(r2s[mask])) + sems.append(stats.sem(r2s[mask])) + return np.array(centers), np.array(means), np.array(sems) + 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) + 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") + 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) + 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) + 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") + 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 -def plot_qq_overlay_interactive(all_results): - """Interactive QQ overlay for all models.""" - fig = go.Figure() - exp_max = 0 - for mname, (pvals, _, _) in all_results.items(): - n = len(pvals) - obs_raw = -np.log10(np.clip(pvals, 1e-300, 1)) - sort_i = np.argsort(obs_raw)[::-1] - obs = obs_raw[sort_i] - exp = -np.log10(np.arange(1, n + 1) / n) - exp_max = max(exp_max, exp.max()) - lam = compute_lambda(pvals) - col = MODEL_COLORS.get(mname, ACCENT_BLUE) - fig.add_trace(go.Scatter( - x=exp, y=obs, - mode='lines', - line=dict(color=col, width=2.5), - name=f"{mname} (λ={lam:.3f})", - )) - fig.add_trace(go.Scatter( - x=[0, exp_max * 1.05], y=[0, exp_max * 1.05], - mode='lines', - line=dict(color='#333333', width=1.5), - name='y = x (expected)', - )) - sig_thr = -np.log10(5e-8) - fig.add_shape(type="line", x0=0, x1=exp_max, y0=sig_thr, y1=sig_thr, - line=dict(color="#CC0000", width=1.5, dash="dash")) - fig.add_annotation(x=exp_max*0.98, y=sig_thr+0.2, - text="GW significant (5×10⁻⁸)", - showarrow=False, font=dict(color="#CC0000", size=10), - xanchor="right") - fig.update_layout( - title=dict(text="QQ Plot Overlay — All Models", font=dict(size=15)), - xaxis=dict(title="Expected −log₁₀(p)", gridcolor="#E2E8F0"), - yaxis=dict(title="Observed −log₁₀(p)", gridcolor="#E2E8F0"), - plot_bgcolor="white", - paper_bgcolor="white", - height=520, - legend=dict(font=dict(size=11)), - hovermode="x unified", - margin=dict(l=60, r=40, t=80, b=60), - ) +def plot_pca(G, y, ids): + fig, axes = plt.subplots(2, 2, figsize=(14, 12)) + style_fig(fig) + G_sc = StandardScaler().fit_transform(G) + n_comp = min(5, G_sc.shape[0]-1, G_sc.shape[1]) + pca = PCA(n_components=n_comp) + pcs = pca.fit_transform(G_sc) + var_exp = pca.explained_variance_ratio_ * 100 + sc = axes[0,0].scatter(pcs[:,0], pcs[:,1], c=y, cmap='plasma', s=60, edgecolors='none') + axes[0,0].set_xlabel(f"PC1 ({var_exp[0]:.1f}%)"); axes[0,0].set_ylabel(f"PC2 ({var_exp[1]:.1f}%)") + axes[0,0].set_title("PCA: PC1 vs PC2"); plt.colorbar(sc, ax=axes[0,0], label="Phenotype") + if n_comp >= 4: + 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") + 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 -# ─────────────────────── INTERACTIVE PVE / EFFECT SIZE PLOT ────────────────── -def plot_effect_sizes_interactive(pvals, betas, ses, snp_names, model_name=""): - """Interactive volcano + effect size plots.""" - log_p = -np.log10(np.clip(pvals, 1e-300, 1)) - bonf = 0.05 / len(pvals) - sig_thr = -np.log10(bonf) - gw_thr = -np.log10(5e-8) - - colors = [] - for i in range(len(pvals)): - if log_p[i] >= gw_thr: - colors.append('#FF1744') - elif log_p[i] >= sig_thr: - colors.append('#FF6B35') - elif betas[i] > 0: - colors.append('#00C9A7') - else: - colors.append('#775DD0') - - snp_str = [str(s) for s in snp_names] - - fig = make_subplots(rows=1, cols=2, - subplot_titles=["Volcano Plot", "Top 30 Effect Sizes"]) - - fig.add_trace(go.Scatter( - x=betas, y=log_p, - mode='markers', - marker=dict(color=colors, size=6, opacity=0.75), - text=[f"SNP: {snp_str[i]}
β: {betas[i]:.4f}
-log10(p): {log_p[i]:.2f}
p: {pvals[i]:.3e}" - for i in range(len(pvals))], - hovertemplate="%{text}", - name="SNPs", - ), row=1, col=1) - - fig.add_shape(type="line", x0=betas.min(), x1=betas.max(), - y0=gw_thr, y1=gw_thr, - line=dict(color="#FF4560", width=1.5, dash="dash"), - row=1, col=1) - fig.add_shape(type="line", x0=0, x1=0, - y0=0, y1=log_p.max()*1.05, - line=dict(color="#666", width=1), - row=1, col=1) - - top_idx = np.argsort(np.abs(betas))[-30:][::-1] - top_betas = betas[top_idx] - top_names = [snp_str[i][:20] for i in top_idx] - top_cols = ['#FF4560' if b < 0 else '#00C9A7' for b in top_betas] - - fig.add_trace(go.Bar( - x=top_betas, - y=top_names, - orientation='h', - marker_color=top_cols, - text=[f"β={b:.4f}" for b in top_betas], - textposition='outside', - hovertemplate="SNP: %{y}
β: %{x:.4f}", - name="Effect sizes", - ), row=1, col=2) - - fig.update_xaxes(title_text="Effect size (β)", row=1, col=1) - fig.update_yaxes(title_text="-log₁₀(p)", row=1, col=1) - fig.update_xaxes(title_text="Effect size (β)", row=1, col=2) - - fig.update_layout( - title=dict(text=f"Effect Sizes & Volcano — {model_name}", - font=dict(size=14)), - plot_bgcolor="white", - paper_bgcolor="white", - height=500, - showlegend=False, - hovermode="closest", - margin=dict(l=60, r=40, t=80, b=60), - ) - for i in [1, 2]: - fig.update_xaxes(gridcolor="#E2E8F0", row=1, col=i) - fig.update_yaxes(gridcolor="#E2E8F0", row=1, col=i) +def plot_model_comparison_manhattan(all_results, chroms, positions): + 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] + chrom_list = sorted(set(chroms)) + total_len = 0 + chrom_offsets = {} + for ch in chrom_list: + chrom_offsets[ch] = total_len + 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 = [], [] + 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()): + 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: + mask = chroms == ch + 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.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) + 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 -# ─────────────────────── INTERACTIVE PCA PLOT ───────────────────────────────── -def plot_pca_interactive(G, y, ids): - """Interactive PCA with Plotly.""" +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: - G_sc = StandardScaler().fit_transform(G) - n_comp = min(5, G_sc.shape[0] - 1, G_sc.shape[1]) - if n_comp < 2: - raise ValueError("Not enough components") - pca = PCA(n_components=n_comp) - pcs = pca.fit_transform(G_sc) - var_exp= pca.explained_variance_ratio_ * 100 - except Exception as e: - fig = go.Figure() - fig.add_annotation(text=f"PCA unavailable: {e}", x=0.5, y=0.5, - xref="paper", yref="paper", showarrow=False) - return fig - - fig = make_subplots(rows=1, cols=2, - subplot_titles=[ - f"PC1 ({var_exp[0]:.1f}%) vs PC2 ({var_exp[1]:.1f}%)", - "Scree Plot" - ]) - - fig.add_trace(go.Scatter( - x=pcs[:, 0], y=pcs[:, 1], - mode='markers', - marker=dict( - color=y, colorscale='Plasma', size=8, - colorbar=dict(title="Phenotype", x=0.46), - showscale=True, - ), - text=[f"ID: {ids[i]}
PC1: {pcs[i,0]:.3f}
PC2: {pcs[i,1]:.3f}
Pheno: {y[i]:.3f}" - for i in range(len(y))], - hovertemplate="%{text}", - name="Samples", - ), row=1, col=1) - - fig.add_trace(go.Bar( - x=[f"PC{i+1}" for i in range(n_comp)], - y=var_exp, - marker_color=ACCENT_BLUE, - name="Var. explained", - hovertemplate="PC%{x}: %{y:.1f}%", - ), row=1, col=2) - fig.add_trace(go.Scatter( - x=[f"PC{i+1}" for i in range(n_comp)], - y=np.cumsum(var_exp), - mode='lines+markers', - line=dict(color=ACCENT_CORAL, width=2), - marker=dict(size=8), - name="Cumulative", - hovertemplate="PC%{x}: cumulative %{y:.1f}%", - ), row=1, col=2) - - fig.update_xaxes(title_text=f"PC1 ({var_exp[0]:.1f}%)", gridcolor="#E2E8F0", row=1, col=1) - fig.update_yaxes(title_text=f"PC2 ({var_exp[1]:.1f}%)", gridcolor="#E2E8F0", row=1, col=1) - fig.update_yaxes(title_text="Variance Explained (%)", gridcolor="#E2E8F0", row=1, col=2) - - fig.update_layout( - title=dict(text="Principal Component Analysis (PCA)", font=dict(size=14)), - plot_bgcolor="white", - paper_bgcolor="white", - height=480, - hovermode="closest", - margin=dict(l=60, r=40, t=80, b=60), - ) + 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 -# ─────────────────────── INTERACTIVE KINSHIP PLOT ──────────────────────────── -def plot_kinship_interactive(K, ids): - """Interactive kinship heatmap + distribution.""" - n_samples = len(ids) - label_step = max(1, n_samples // 30) - tick_labels = [str(ids[i]) if i % label_step == 0 else "" for i in range(n_samples)] - - fig = make_subplots(rows=1, cols=2, - subplot_titles=[ - f"Kinship Matrix ({n_samples} samples)", - "Pairwise Kinship Distribution" - ]) - - fig.add_trace(go.Heatmap( - z=K, - colorscale='RdYlBu_r', - zmin=-0.5, zmax=1.0, - colorbar=dict(title="Kinship", x=0.46), - x=tick_labels, - y=tick_labels, - hovertemplate="Sample i: %{x}
Sample j: %{y}
K: %{z:.3f}", - ), row=1, col=1) - - K_flat = K[np.triu_indices_from(K, k=1)] - fig.add_trace(go.Histogram( - x=K_flat, - nbinsx=40, - marker_color=ACCENT_PURP, - opacity=0.85, - name="Pairwise kinship", - hovertemplate="Kinship: %{x:.3f}
Count: %{y}", - ), row=1, col=2) - fig.add_vline(x=K_flat.mean(), line_color=ACCENT_CORAL, line_dash="dash", - annotation_text=f"Mean: {K_flat.mean():.3f}", - annotation_font_color=ACCENT_CORAL, - row=1, col=2) - - fig.update_xaxes(title_text="Sample", gridcolor="#E2E8F0", row=1, col=1, - tickfont=dict(size=7)) - fig.update_yaxes(title_text="Sample", gridcolor="#E2E8F0", row=1, col=1, - tickfont=dict(size=7)) - fig.update_xaxes(title_text="Kinship Coefficient", gridcolor="#E2E8F0", row=1, col=2) - fig.update_yaxes(title_text="Count", gridcolor="#E2E8F0", row=1, col=2) - - fig.update_layout( - title=dict(text=f"Kinship Matrix Analysis — {n_samples} samples", - font=dict(size=14)), - plot_bgcolor="white", - paper_bgcolor="white", - height=480, - hovermode="closest", - margin=dict(l=60, r=40, t=80, b=60), - showlegend=False, - ) +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 -# ─────────────────────── INTERACTIVE SUMMARY DASHBOARD ─────────────────────── -def plot_summary_dashboard_interactive(y, maf, all_results, G_filt): - """Interactive summary dashboard.""" - lambdas = {m: compute_lambda(p) for m, (p, _, _) in all_results.items()} - bonf = 0.05 / len(list(all_results.values())[0][0]) - sig_bonf = {m: int((p < bonf).sum()) for m, (p, _, _) in all_results.items()} - sig_gw = {m: int((p < 5e-8).sum()) for m, (p, _, _) in all_results.items()} - - fig = make_subplots( - rows=2, cols=3, - subplot_titles=[ - "Phenotype Distribution", - "MAF Distribution", - "Genomic Inflation λ", - "Significant SNPs (Bonferroni)", - "Model Concordance (Spearman ρ)", - "Significant SNPs (GW 5×10⁻⁸)", - ] - ) - - fig.add_trace(go.Histogram( - x=y, nbinsx=20, - marker_color=ACCENT_PURP, opacity=0.85, - hovertemplate="Value: %{x:.2f}
Count: %{y}", - name="Phenotype", - ), row=1, col=1) - fig.add_vline(x=float(y.mean()), line_color=ACCENT_CORAL, line_dash="dash", - annotation_text=f"Mean={y.mean():.2f}", row=1, col=1) - - fig.add_trace(go.Histogram( - x=maf, nbinsx=20, - marker_color=ACCENT_TEAL, opacity=0.85, - hovertemplate="MAF: %{x:.3f}
Count: %{y}", - name="MAF", - ), row=1, col=2) - fig.add_vline(x=0.05, line_color=ACCENT_CORAL, line_dash="dash", - annotation_text="MAF=0.05", row=1, col=2) - - lam_cols = [('#00C9A7' if v <= 1.05 else '#FFB300' if v <= 1.15 else '#FF4560') - for v in lambdas.values()] - fig.add_trace(go.Bar( - x=list(lambdas.keys()), - y=list(lambdas.values()), - marker_color=lam_cols, - text=[f"{v:.3f}" for v in lambdas.values()], - textposition='outside', - hovertemplate="Model: %{x}
λ: %{y:.4f}", - name="Lambda", - ), row=1, col=3) - fig.add_hline(y=1.0, line_color="#333", line_dash="dash", row=1, col=3) - - cols_bar = [MODEL_COLORS.get(m, ACCENT_BLUE) for m in sig_bonf] - fig.add_trace(go.Bar( - x=list(sig_bonf.keys()), - y=list(sig_bonf.values()), - marker_color=cols_bar, - text=list(sig_bonf.values()), - textposition='outside', - name="Sig (Bonf)", - hovertemplate="Model: %{x}
Sig SNPs: %{y}", - ), row=2, col=1) - +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].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)}") + lambdas = {} + 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[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 = {} + 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[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()) - n_m = len(model_names) concordance = np.eye(n_m) for i in range(n_m): for j in range(i+1, n_m): lp_i = -np.log10(np.clip(all_results[model_names[i]][0], 1e-300, 1)) 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 - fig.add_trace(go.Heatmap( - z=concordance, - x=model_names, y=model_names, - colorscale='RdYlGn', zmin=-1, zmax=1, - text=[[f"{concordance[i,j]:.2f}" for j in range(n_m)] for i in range(n_m)], - texttemplate="%{text}", - textfont=dict(size=9), - hovertemplate="Model i: %{x}
Model j: %{y}
ρ: %{z:.3f}", - showscale=False, - ), row=2, col=2) - - cols_gw = [MODEL_COLORS.get(m, ACCENT_BLUE) for m in sig_gw] - fig.add_trace(go.Bar( - x=list(sig_gw.keys()), - y=list(sig_gw.values()), - marker_color=cols_gw, - text=list(sig_gw.values()), - textposition='outside', - name="Sig (GW)", - hovertemplate="Model: %{x}
GW Sig: %{y}", - ), row=2, col=3) - - fig.update_layout( - title=dict(text="GWAS Summary Dashboard", font=dict(size=15)), - plot_bgcolor="white", - paper_bgcolor="white", - height=680, - showlegend=False, - hovermode="closest", - margin=dict(l=60, r=40, t=100, b=60), - ) - for r in [1, 2]: - for c in [1, 2, 3]: - fig.update_xaxes(gridcolor="#E2E8F0", row=r, col=c) - fig.update_yaxes(gridcolor="#E2E8F0", row=r, col=c) + concordance[i,j] = concordance[j,i] = r + 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[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 -# ─────────────────────── INTERACTIVE ALL-MODELS MANHATTAN ──────────────────── -def plot_all_models_manhattan_interactive(all_results, chroms, positions, snp_names): - """FIX: x-axis starts from chromosome 1. Interactive stacked Manhattan for all models.""" - n_models = len(all_results) - chrom_list = sorted(set(chroms)) - x_coords = _compute_x_coords(chroms, positions, chrom_list) - tick_pos, tick_lab = _compute_tick_positions(x_coords, chroms, chrom_list) - - fig = make_subplots( - rows=n_models, cols=1, - shared_xaxes=True, - subplot_titles=[f"Manhattan — {m}" for m in all_results.keys()], - vertical_spacing=0.04, - ) - - sig_line = -np.log10(5e-8) - snp_str = [str(s) for s in snp_names] - - for midx, (mname, (pvals, betas, _)) in enumerate(all_results.items(), 1): - log_p = -np.log10(np.clip(pvals, 1e-300, 1)) - col = MODEL_COLORS.get(mname, CHR_PALETTE[midx % len(CHR_PALETTE)]) - lam = compute_lambda(pvals) - - sig_mask = log_p >= sig_line - ns_mask = ~sig_mask - - if ns_mask.any(): - fig.add_trace(go.Scatter( - x=x_coords[ns_mask], y=log_p[ns_mask], - mode='markers', - marker=dict(color=col, size=4, opacity=0.7), - name=mname, - text=[f"SNP: {snp_str[i]}
p: {pvals[ns_mask][k]:.3e}
β: {betas[ns_mask][k]:.4f}" - for k, i in enumerate(np.where(ns_mask)[0])], - hovertemplate="%{text}", - showlegend=False, - ), row=midx, col=1) - - if sig_mask.any(): - fig.add_trace(go.Scatter( - x=x_coords[sig_mask], y=log_p[sig_mask], - mode='markers', - marker=dict(color='#FF1744', size=9, symbol='diamond', - line=dict(color='#7F0000', width=0.8)), - name=f"{mname} sig", - text=[f"SIG SNP: {snp_str[i]}
p: {pvals[sig_mask][k]:.3e}
β: {betas[sig_mask][k]:.4f}" - for k, i in enumerate(np.where(sig_mask)[0])], - hovertemplate="%{text}", - showlegend=False, - ), row=midx, col=1) - - x_max = x_coords.max() if len(x_coords) > 0 else 1 - fig.add_shape(type="line", x0=1, x1=x_max, y0=sig_line, y1=sig_line, - line=dict(color="#FF4560", width=1, dash="dash"), - row=midx, col=1) - fig.update_yaxes(title_text=f"{mname}\n(λ={lam:.3f})", row=midx, col=1, - title_font=dict(size=9, color=col)) - - fig.update_xaxes( - tickmode='array', - tickvals=tick_pos, - ticktext=tick_lab, - tickangle=45, - tickfont=dict(size=8), - range=[0, x_coords.max() * 1.01], - row=n_models, col=1, - ) - - fig.update_layout( - title=dict(text="Manhattan Plots — All Models", font=dict(size=14)), - plot_bgcolor="white", - paper_bgcolor="white", - height=300 * n_models, - hovermode="closest", - showlegend=False, - margin=dict(l=100, r=40, t=80, b=80), - ) - for r in range(1, n_models + 1): - fig.update_xaxes(gridcolor="#E2E8F0", showgrid=False, row=r, col=1) - fig.update_yaxes(gridcolor="#E2E8F0", row=r, col=1) - 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() -# ─────────────────────── EXCEL EXPORT ───────────────────────────────────────── -def export_results_excel(all_results, snp_filt, chr_filt, pos_filt, - y, G_filt, maf_vals, bonf_threshold, 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") @@ -1858,69 +804,82 @@ def export_results_excel(all_results, snp_filt, chr_filt, pos_filt, left=Side(style='thin', color='CCCCCC'), right=Side(style='thin', color='CCCCCC'), top=Side(style='thin', color='CCCCCC'), - bottom=Side(style='thin', color='CCCCCC')) + bottom=Side(style='thin', color='CCCCCC') + ) + + bonf = 0.05 / len(list(all_results.values())[0][0]) - bonf = bonf_threshold + # ── 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"] + + 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 = compute_lambda(pvals) - row_data = [mname, len(pvals), f"{bonf:.2e}", - int((pvals < bonf).sum()), int((pvals < 5e-8).sum()), - 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")) + 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}_SNPs") - ws['A1'] = f"GWAS Results — {mname}" + 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) - _, pvals_fdr, _, _ = multipletests(pvals, method='fdr_bh') + + 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"] + + 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 - for i, w in enumerate([25,8,12,10,12,12,12,14,12,14,16], 1): + + 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 - for row_i, idx in enumerate(np.argsort(pvals), 4): + + 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 + 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), - 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"] + 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 @@ -1928,43 +887,51 @@ def export_results_excel(all_results, snp_filt, chr_filt, pos_filt, 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" + 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_%"] + + 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 + 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) + 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])] - pve_dict, _ = compute_pve(y, G_filt, pvals, betas, ses) + 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 + 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), + 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")) + "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 @@ -1973,30 +940,122 @@ def export_results_excel(all_results, snp_filt, chr_filt, pos_filt, 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"] + 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 + 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 - fill = (alt_fill if row_i % 2 == 0 - else PatternFill("solid", start_color="FFFFFF", end_color="FFFFFF")) + 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 "", - "Rare (<0.05)" if not np.isnan(maf_v) and maf_v < 0.05 else "Common"] + 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 @@ -2005,133 +1064,52 @@ def export_results_excel(all_results, snp_filt, chr_filt, pos_filt, wb.save(output_path) return output_path -def save_all_plots_zip(plot_figs_static, out_dir): +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_figs_static.items(): + for name, fig in plot_dict.items(): if fig is not None: - try: - data = fig_to_png_bytes(fig) - zf.writestr(f"{name}.png", data) - except Exception as e: - print(f"[WARN] Failed to save {name}: {e}") + 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 -# ─────────────────────── MATPLOTLIB STATIC PLOTS FOR ZIP ───────────────────── -def plot_qq_static(pvals, model_name, color): - """Static matplotlib QQ for zip export.""" - fig, ax = plt.subplots(figsize=(7, 7), facecolor="white") - ax.set_facecolor("white") - n = len(pvals) - obs_raw = -np.log10(np.clip(pvals, 1e-300, 1)) - sort_i = np.argsort(obs_raw)[::-1] - obs = obs_raw[sort_i] - exp = -np.log10(np.arange(1, n + 1) / n) - ranks = np.arange(1, n + 1) - ci_lo = -np.log10(stats.beta.ppf(0.975, ranks, n - ranks + 1)) - ci_hi = -np.log10(stats.beta.ppf(0.025, ranks, n - ranks + 1)) - ax.fill_between(exp, ci_lo, ci_hi, color=color, alpha=0.15) - xy_max = max(float(exp.max()), float(obs.max())) * 1.06 - ax.plot([0, xy_max], [0, xy_max], color="#E8453C", ls="--", lw=1.8) - ax.scatter(exp, obs, c=color, s=12, alpha=0.8, linewidths=0) - sig_mask = obs >= -np.log10(5e-8) - if sig_mask.any(): - ax.scatter(exp[sig_mask], obs[sig_mask], c='#FF1744', s=50, zorder=5, - marker='D', linewidths=0.5, edgecolors='white') - lam = compute_lambda(pvals) - ax.text(0.05, 0.95, f"λ = {lam:.4f}", transform=ax.transAxes, - fontsize=11, fontweight="bold", - color='green' if lam <= 1.05 else 'orange' if lam <= 1.15 else 'red', - va='top', bbox=dict(boxstyle='round', facecolor='white', alpha=0.8)) - ax.set_xlabel("Expected −log₁₀(p)"); ax.set_ylabel("Observed −log₁₀(p)") - ax.set_title(f"QQ Plot — {model_name}", fontweight='bold') - fig.tight_layout() - return fig - -def plot_manhattan_static(pvals, chroms, positions, model_name): - """Static matplotlib Manhattan — FIX: x-axis starts from 1 (not 0).""" - fig, ax = plt.subplots(figsize=(16, 5), facecolor=BG_WHITE) - ax.set_facecolor(PANEL_WHITE) - 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)) - x_coords = _compute_x_coords(chroms, positions, chrom_list) - tick_pos, tick_lab = _compute_tick_positions(x_coords, chroms, chrom_list) - for ch in chrom_list: - mask = chroms == ch - col = CHR_PALETTE[chrom_list.index(ch) % len(CHR_PALETTE)] - ax.scatter(x_coords[mask], log_p[mask], c=col, s=10, alpha=0.8, linewidths=0) - ax.axhline(sug_line, color=ACCENT_CYAN, ls=":", lw=1.4, alpha=0.9) - ax.axhline(sig_line, color=ACCENT_CORAL, ls="--", lw=2.0) - 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="D", zorder=10, - edgecolors="#7F0000", linewidth=0.8) - ax.set_xticks(tick_pos) - ax.set_xticklabels(tick_lab, rotation=45, fontsize=7) - ax.set_ylabel("-log₁₀(p)") - ax.set_title(f"Manhattan — {model_name}", fontweight='bold') - x_max = x_coords.max() if len(x_coords) > 0 else 1 - ax.set_xlim(0, x_max * 1.01) - fig.tight_layout() - return fig - -# ─────────────────────── MAIN PIPELINE ──────────────────────────────────────── +# ─────────────────────── 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: - empty = [None] * 10 - return empty + [None, None, f"❌ Data parsing error: {e}"] + return [None] * 30 + [f"❌ Data parsing error: {e}"] - y = df["Phenotype"].values.astype(float) - ids = df["ID"].values + y = df["Phenotype"].values.astype(float) + ids = df["ID"].values G_raw = df[snp_cols].values.astype(float) - - K_raw = build_kinship(G_raw) - G = impute_genotypes_mode(G_raw) + G = impute_genotypes(G_raw) n, m = G.shape maf_vals_all = compute_maf(G) - maf_thr = float(maf_threshold) - keep = maf_vals_all >= maf_thr + maf_thr = float(maf_threshold) + keep = maf_vals_all >= maf_thr if keep.sum() < 2: keep = np.ones(m, dtype=bool) - G_filt = G[:, keep] + 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) + 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) - maf_post = compute_maf(G_filt) - keep2 = maf_post >= maf_thr - if keep2.sum() >= 2: - G_filt = G_filt[:, keep2] - snp_filt = snp_filt[keep2] - chr_filt = chr_filt[keep2] - pos_filt = pos_filt[keep2] - maf_vals = maf_vals[keep2] - K = build_kinship(G_filt) - - ALL_MODELS_LIST = ["OLS","MLM","GLM","CMLM","BLINK", - "FarmCPU","EMMAX","PLINK","GAPIT3","GEMMA"] - if not selected_models or len(selected_models) == 0: - models_to_run = ALL_MODELS_LIST - else: - models_to_run = [mm for mm in selected_models if mm in ALL_MODELS_LIST] - if len(models_to_run) == 0: - models_to_run = ALL_MODELS_LIST model_funcs = { "OLS": lambda: ols_gwas(y, G_filt), "MLM": lambda: mlm_gwas(y, G_filt, K), "GLM": lambda: glm_gwas(y, G_filt), "CMLM": lambda: cmlm_gwas(y, G_filt, K), - "BLINK": lambda: blink_gwas(y, G_filt, K), + "BLINK": lambda: blink_gwas(y, G_filt), "FarmCPU": lambda: farmcpu_gwas(y, G_filt, K), "EMMAX": lambda: emmax_gwas(y, G_filt, K), "PLINK": lambda: plink_gwas(y, G_filt), @@ -2139,15 +1117,9 @@ def run_gwas(file_obj, text_input, selected_models, maf_threshold): "GEMMA": lambda: gemma_gwas(y, G_filt, K), } - all_results = {} - primary_p = None - primary_b = None - primary_se = None - primary_model = None - errors = [] - - Vg, Ve, delta, _, _ = reml_variance_components(y, K) - h2 = Vg / (Vg + Ve) + models_to_run = selected_models if selected_models else list(model_funcs.keys()) + all_results = {} + primary_p = primary_b = primary_se = None for mname in models_to_run: if mname in model_funcs: @@ -2156,218 +1128,301 @@ def run_gwas(file_obj, text_input, selected_models, maf_threshold): all_results[mname] = (p, b, se) if primary_p is None: primary_p, primary_b, primary_se = p, b, se - primary_model = mname except Exception as ex: - errors.append(f"{mname}: {ex}") - print(f"[WARN] Model {mname} failed: {ex}") + print(f"Model {mname} failed: {ex}") if primary_p is None: - return [None]*10 + [None, None, f"❌ No models succeeded.\nErrors:\n" + "\n".join(errors)] - - bonf = 0.05 / len(primary_p) - - # Build interactive Plotly figures - fig_mh_primary = plot_manhattan_interactive(primary_p, chr_filt, pos_filt, snp_filt, "Manhattan", primary_model) - fig_qq_primary = plot_qq_interactive_single(primary_p, primary_model, MODEL_COLORS.get(primary_model)) - fig_qq_overlay = plot_qq_overlay_interactive(all_results) - fig_circos = plot_circos_interactive(all_results, chr_filt, pos_filt, snp_filt) - fig_ld = plot_ld_decay_interactive(G_filt, pos_filt, chr_filt) - fig_pca = plot_pca_interactive(G_filt, y, ids) - fig_kinship = plot_kinship_interactive(K, ids) - fig_effects = plot_effect_sizes_interactive(primary_p, primary_b, primary_se, snp_filt, primary_model) - fig_all_mh = plot_all_models_manhattan_interactive(all_results, chr_filt, pos_filt, snp_filt) - fig_dashboard = plot_summary_dashboard_interactive(y, maf_vals, all_results, G_filt) - - # Static plots for ZIP export - static_plots = {} - try: - for mname, (p, b, se) in all_results.items(): - static_plots[f"{mname}_Manhattan"] = plot_manhattan_static(p, chr_filt, pos_filt, mname) - static_plots[f"{mname}_QQ"] = plot_qq_static(p, mname, MODEL_COLORS.get(mname, ACCENT_PURP)) - except Exception as ex: - errors.append(f"Static plot error: {ex}") + 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') - tmp_dir = tempfile.mkdtemp() - zip_path = save_all_plots_zip(static_plots, tmp_dir) - excel_path = os.path.join(tmp_dir, "gwas_results_complete.xlsx") - try: - export_results_excel(all_results, snp_filt, chr_filt, pos_filt, - y, G_filt, maf_vals, bonf, excel_path) - except Exception as ex: - errors.append(f"Excel export error: {ex}") - excel_path = None - - best_models = select_best_models(all_results) + # ── Summary text ─────────────────────────────────────────────────────────────── + bonf = 0.05 / len(primary_p) lambdas_str = "\n ".join([ - f"{mn}: λ={compute_lambda(p):.4f} sig(Bonf)={int((p