diff --git "a/app.py" "b/app.py" --- "a/app.py" +++ "b/app.py" @@ -6,7 +6,6 @@ matplotlib.use("Agg") import matplotlib.pyplot as plt import matplotlib.patches as mpatches from matplotlib.colors import LinearSegmentedColormap, Normalize -from matplotlib.cm import ScalarMappable import matplotlib.gridspec as gridspec import warnings warnings.filterwarnings("ignore") @@ -44,46 +43,45 @@ GRID_LINE = "#E2E8F0" SIG_COLOR = "#FF1744" MODEL_COLORS = { - "MLM": "#00C9A7", # teal — exact LMM - "CMLM": "#775DD0", # purple — compressed LMM - "FarmCPU": "#00E396", # lime green — iterative QTN - "PLINK": "#008FFB", # blue — baseline - "GLM": "#FF4560", # coral-red — structure correction - "EMMAX": "#FF66C4", # pink — fast LMM - "GEMMA": "#A855F7", # violet — best LMM - "BLINK": "#FFB300", # gold — advanced detection + "MLM": "#00C9A7", + "CMLM": "#775DD0", + "FarmCPU": "#00E396", + "PLINK": "#008FFB", + "GLM": "#FF4560", + "EMMAX": "#FF66C4", + "GEMMA": "#A855F7", + "BLINK": "#FFB300", + "OLS": "#14B8A6", + "GAPIT3": "#F59E0B", } CHR_PALETTE = [ "#008FFB","#00C9A7","#FF4560","#775DD0","#FFB300", "#00E396","#FF66C4","#00D9E9","#FF6B35","#A855F7", - "#059669","#F59E0B","#6366F1","#EC4899","#14B8A6", ] -# Publication-style QQ gradient: grey (low p) → blue → yellow → red (high p) -QQ_CMAP = LinearSegmentedColormap.from_list( - "qq_pub", - ["#AAAAAA", "#4575B4", "#74ADD1", "#ABD9E9", - "#FFFFBF", "#FDAE61", "#F46D43", "#D73027", "#A50026"], - N=512 -) - def style_fig(fig): + """Apply consistent styling to figures""" fig.patch.set_facecolor(BG_WHITE) for ax in fig.get_axes(): ax.set_facecolor(PANEL_WHITE) 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) + if ax.xaxis.label: + ax.xaxis.label.set_color(TEXT_DIM) + if ax.yaxis.label: + ax.yaxis.label.set_color(TEXT_DIM) + if ax.title: + ax.title.set_color(TEXT_MAIN) for spine in ax.spines.values(): - spine.set_edgecolor(GRID_LINE) - spine.set_linewidth(0.8) + if spine is not None: + spine.set_edgecolor(GRID_LINE) + spine.set_linewidth(0.8) ax.grid(color=GRID_LINE, linewidth=0.5, linestyle="--", alpha=0.7) return fig # ─────────────────────── DATA PARSING ───────────────────────────────────────── def parse_data(file_obj=None, text_input=None): + """Parse input data with robust column detection""" raw = None if file_obj is not None: try: @@ -98,57 +96,59 @@ def parse_data(file_obj=None, text_input=None): else: raise ValueError("No data provided.") - chrom_info = {} + if raw is None or len(raw) == 0: + raise ValueError("Empty data provided.") + + # Skip metadata row if present 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): - try: - chrom_info[col] = int(val) - except Exception: - pass - if len(chrom_info) > 0: + if second_row.iloc[0] == "chromosome" or "chr" in second_row.iloc[0].lower(): raw = raw.drop(index=1).reset_index(drop=True) cols = list(raw.columns) + if len(cols) < 3: + raise ValueError("Data must have at least 3 columns: ID, Phenotype, and SNP columns") + id_col = cols[0] phen_col = cols[1] snp_cols = cols[2:] - raw = raw[pd.to_numeric(raw[phen_col], errors="coerce").notna()].copy() - raw[phen_col] = raw[phen_col].astype(float) - geno = raw[snp_cols].apply(pd.to_numeric, errors="coerce") - geno = geno.where(~geno.isin([-1, -9, -99, -999]), np.nan) - - df = pd.DataFrame() - df["ID"] = raw[id_col].values - df["Phenotype"] = raw[phen_col].values - for c in snp_cols: - df[c] = geno[c].values - - chroms, positions = [], [] - for idx_m, m in enumerate(snp_cols): - if m in chrom_info: - chroms.append(chrom_info[m]) - positions.append(idx_m + 1) - else: - m_clean = str(m).strip() - mat = re.match(r"[Cc]hr(\d+)[_\-](\d+)", m_clean) - if mat: - 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) + # Convert phenotype to numeric + raw[phen_col] = pd.to_numeric(raw[phen_col], errors='coerce') + raw = raw.dropna(subset=[phen_col]).reset_index(drop=True) + + if len(raw) == 0: + raise ValueError("No valid phenotype data") - return df, snp_cols, np.array(chroms), np.array(positions) + y = raw[phen_col].values.astype(float) + ids = raw[id_col].values + + # Convert SNP data to numeric + G_raw = raw[snp_cols].apply(pd.to_numeric, errors='coerce').values + G_raw = np.where(np.isin(G_raw, [-1, -9, -99, -999]), np.nan, G_raw) + + # Extract chromosome and position info + chroms = np.ones(len(snp_cols), dtype=int) + positions = np.arange(1, len(snp_cols) + 1) * 10000 + + for i, snp_name in enumerate(snp_cols): + snp_str = str(snp_name) + # Try to extract chromosome + chr_match = re.search(r'(?:chr|Chr|CHR)?(\d+)', snp_str) + if chr_match: + chroms[i] = int(chr_match.group(1)) + # Try to extract position + pos_match = re.findall(r'\d+', snp_str) + if len(pos_match) >= 2: + positions[i] = int(pos_match[1]) + elif len(pos_match) == 1 and i > 0: + positions[i] = positions[i-1] + 10000 + + return G_raw, y, ids, np.array(snp_cols), chroms, positions # ─────────────────────── UTILITY ────────────────────────────────────────────── def impute_genotypes_mode(geno_matrix): - """Mode imputation for 0/1/2 genotype data — avoids MAF inflation from mean imputation.""" + """Mode imputation for 0/1/2 genotype data""" mat = geno_matrix.copy().astype(float) for j in range(mat.shape[1]): col = mat[:, j] @@ -163,112 +163,81 @@ def impute_genotypes_mode(geno_matrix): return mat def compute_maf(G): + """Compute minor allele frequency""" freqs = np.nanmean(G, axis=0) / 2.0 return np.where(freqs > 0.5, 1 - freqs, freqs) def compute_call_rate(G): + """Compute genotype call rate""" return 1 - np.isnan(G).mean(axis=0) -def build_kinship(G_raw): - """VanRaden (2008) kinship matrix.""" - G = G_raw.copy().astype(float) +def build_kinship(G): + """VanRaden (2008) kinship matrix - optimized for large datasets""" + G = G.copy().astype(float) + n, m = G.shape + + # Handle missing data p = np.nanmean(G, axis=0) / 2.0 - p = np.clip(p, 1e-6, 1 - 1e-6) - for j in range(G.shape[1]): + p = np.clip(p, 0.01, 0.99) + + for j in range(m): nan_mask = np.isnan(G[:, j]) G[nan_mask, j] = 2 * p[j] - Z = G - 2 * p + + # Center the matrix + Z = G - 2 * p denom = 2 * np.sum(p * (1 - p)) if denom < 1e-8: denom = 1.0 + + # Compute kinship efficiently K = (Z @ Z.T) / denom + # Ensure symmetry and positive definite + K = (K + K.T) / 2 + K = K + np.eye(n) * 1e-6 + return K -# ─────────────────────── REML — intercept projected out ────────────────────── +# ─────────────────────── REML ────────────────────────────────────── def reml_variance_components(y, K): - """ - REML variance components via eigendecomposition of K. - Projects out the intercept from Uty before the profile log-likelihood. - Returns (Vg, Ve, delta, eigvals, U). - """ + """REML variance components via eigendecomposition""" n = len(y) - eigvals, U = np.linalg.eigh(K + np.eye(n) * 1e-6) + eigvals, U = np.linalg.eigh(K) eigvals = np.maximum(eigvals, 1e-8) Uty = U.T @ y Ut1 = U.T @ np.ones(n) - # Project out intercept from the rotated phenotype + # Project out intercept 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)) + 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') + 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 - -# ─────────────────────── GLS — corrected SE calculation ─────────────────────── -def gls_test(y, x, V_inv): - """GLS single-SNP test.""" - 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) + d = eigvals + delta + Ve = np.sum(Uty**2 / d) / (n - 1) + Vg = Ve / delta + return max(float(Vg), 1e-8), max(float(Ve), 1e-8), float(delta), eigvals, U -# ─────────────────────── Rotated GLS — O(n) per SNP ─────────────────────────── def precompute_rotation(y, K): - """Eigendecompose K once. Returns everything needed for O(n)-per-SNP tests.""" - n = len(y) + """Precompute rotation for efficient GLS""" Vg, Ve, delta, eigvals, U = reml_variance_components(y, K) - d = eigvals + delta + d = eigvals + delta Uty = U.T @ y - Ut1 = U.T @ np.ones(n) + Ut1 = U.T @ np.ones(len(y)) return U, d, Uty, Ut1, Vg, Ve, delta def rotated_gls_snp(Utx, Uty, Ut1, d): - """Single-SNP GLS test using pre-rotated vectors — all operations O(n).""" - n = len(Uty) - df = n - 2 + """Single-SNP GLS test using pre-rotated vectors""" + n = len(Uty) + df = max(n - 2, 1) S11 = np.sum(Ut1**2 / d) S1x = np.sum(Ut1 * Utx / d) @@ -280,107 +249,95 @@ def rotated_gls_snp(Utx, Uty, Ut1, d): if abs(denom) < 1e-12: return 0.0, 1.0, 1.0 - beta = (S11 * Sxy - S1x * S1y) / denom - intercept= (S1y - S1x * beta) / S11 + 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) + sigma2 = np.dot(resid_rot, resid_rot) / df - 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))) + 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=df)) return float(beta), se, p_val -# ─────────────────────── Joint-model PVE ────────────────────────────────────── -def compute_pve(y, G, pvals, betas, ses, threshold=0.05): - """Computes partial r² via type-II SS from a joint OLS model.""" - bonf = threshold / len(pvals) - sig_idx = list(np.where(pvals < bonf)[0]) - SST = np.sum((y - y.mean())**2) - pve_dict = {} - - if SST < 1e-10 or len(sig_idx) == 0: - return {}, SST - - X_parts = [np.ones(len(y))] - valid_idx = [] - 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) +def ols_linregress(y, x): + """Simple linear regression""" + 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 gls_test(y, x, V_inv): + """GLS single-SNP test""" + 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: - 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 + coeffs = np.linalg.solve(XtVX + np.eye(2) * 1e-10, XtVy) + except np.linalg.LinAlgError: + return 0.0, 1.0, 1.0 - 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: - pve_dict[idx] = 0.0 - continue - partial_ss = ss_drop - ss_full - pve_dict[idx] = max(partial_ss / SST * 100, 0.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 - return pve_dict, SST + 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 -# ─────────────────────── 10 STATISTICAL MODELS ──────────────────────────────── +# ─────────────────────── ALL 10 GWAS MODELS ─────────────────────────────────── def ols_gwas(y, G): - """OLS: simple linear regression, no structure correction.""" + """Model 1: OLS - Simple linear regression""" n, m = G.shape - pvals = np.ones(m); betas = np.zeros(m); ses = np.zeros(m) + 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 + pvals[j] = p + betas[j] = b + ses[j] = se return pvals, betas, ses -def mlm_gwas(y, G, K): - """MLM (EMMAX-style full GLS): mixed model with REML variance components.""" - 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) - - 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 - return pvals, betas, ses +def plink_gwas(y, G): + """Model 2: PLINK-style linear regression""" + return ols_gwas(y, G) def glm_gwas(y, G): - """GLM: OLS with top genomic PCs as fixed covariates.""" + """Model 3: GLM with top genomic PCs as covariates""" n, m = G.shape - pvals = np.ones(m); betas = np.zeros(m); ses = np.zeros(m) + 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) + G_scaled = StandardScaler().fit_transform(G) + PCs = PCA(n_components=n_pcs).fit_transform(G_scaled) + 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 - + PCs = np.zeros((n, 1)) + df_correct = max(n - n_pcs - 2, 1) for j in range(m): x = G[:, j] @@ -394,24 +351,52 @@ def glm_gwas(y, G): 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)) - pvals[j] = p; betas[j] = slope; ses[j] = se + p = float(2 * stats.t.sf(abs(t_stat), df=df_correct)) + pvals[j] = p + betas[j] = slope + ses[j] = se + return pvals, betas, ses + +def mlm_gwas(y, G, K): + """Model 4: MLM - Full mixed linear model with GLS""" + 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) + + 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 return pvals, betas, ses def cmlm_gwas(y, G, K): - """CMLM (Compressed MLM): cluster individuals by kinship eigenspace.""" + """Model 5: CMLM - Compressed MLM with kinship clustering""" n, m = G.shape - pvals = np.ones(m); betas = np.zeros(m); ses = np.zeros(m) + 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_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) + 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) ]) @@ -433,19 +418,74 @@ def cmlm_gwas(y, G, K): 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)) - pvals[j] = p; betas[j] = slope; ses[j] = se + p = float(2 * stats.t.sf(abs(t_stat), df=df_correct)) + pvals[j] = p + betas[j] = slope + ses[j] = se + return pvals, betas, ses + +def emmax_gwas(y, G, K): + """Model 6: EMMAX - Efficient mixed model using rotation""" + 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) + + 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 + return pvals, betas, ses + +def gemma_gwas(y, G, K): + """Model 7: GEMMA - LMM with centered kinship""" + n, m = G.shape + pvals = np.ones(m) + betas = np.zeros(m) + ses = np.zeros(m) + + # Center kinship matrix + 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) + + 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 return pvals, betas, ses def blink_gwas(y, G, K): - """BLINK: iterative QTN detection with BIC-based model selection.""" + """Model 8: BLINK - Bayesian linear mixed model with iterative QTN detection""" n, m = G.shape - pvals = np.ones(m); betas = np.zeros(m); ses = np.zeros(m) + pvals = np.ones(m) + betas = np.zeros(m) + ses = np.zeros(m) U, d, Uty, Ut1, Vg, Ve, delta = precompute_rotation(y, K) + # Initial screening init_p = np.ones(m) - for j in range(m): + for j in range(min(m, 500)): # Limit initial screening Utx = U.T @ G[:, j] if Utx.std() < 1e-8: continue @@ -453,23 +493,22 @@ def blink_gwas(y, G, K): init_p[j] = p qtns = [] - candidates = list(np.argsort(init_p)[:min(20, m)]) - best_bic = np.inf + candidates = list(np.argsort(init_p)[:min(15, 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]) + 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 + resid = y - X_trial @ coeffs sigma2 = np.var(resid) - bic = n * np.log(max(sigma2, 1e-12)) + X_trial.shape[1] * np.log(n) + 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 + qtns = trial_qtns if qtns: cov = np.column_stack([np.ones(n)] + [G[:, q] for q in qtns]) @@ -496,20 +535,24 @@ def blink_gwas(y, G, K): 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)) - pvals[j] = p; betas[j] = slope; ses[j] = se + p = float(2 * stats.t.sf(abs(t_stat), df=df_correct)) + pvals[j] = p + betas[j] = slope + ses[j] = se return pvals, betas, ses def farmcpu_gwas(y, G, K): - """FarmCPU: iterative fixed-random model with BIC convergence.""" + """Model 9: FarmCPU - Fixed and random model circulating with BIC convergence""" n, m = G.shape - pvals = np.ones(m); betas = np.zeros(m); ses = np.zeros(m) + 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): + for iteration in range(3): # Limited iterations for speed + for j in range(min(m, 1000)): # Limit to first 1000 SNPs for speed x = G[:, j] if x.std() < 1e-8: continue @@ -530,25 +573,24 @@ def farmcpu_gwas(y, G, K): 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 + betas[j] = slope + ses[j] = se - candidates = list(np.argsort(pvals)[:min(15, m)]) - best_bic = np.inf - new_qtns = [] + candidates = list(np.argsort(pvals)[:min(10, 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]) + 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] + 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) + 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 @@ -556,55 +598,30 @@ def farmcpu_gwas(y, G, K): return pvals, betas, ses -def emmax_gwas(y, G, K): - """EMMAX: efficient mixed-model using the K eigenrotation trick.""" - 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) - - 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 - return pvals, betas, ses - -def plink_gwas(y, G): - """PLINK-style: OLS for continuous phenotypes.""" - 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 - return pvals, betas, ses - def gapit3_gwas(y, G, K): - """GAPIT3: unified MLM + PCA with BIC-based QTN convergence.""" + """Model 10: GAPIT3 - Unified MLM with PCA and BIC-based QTN convergence""" n, m = G.shape - pvals = np.ones(m); betas = np.zeros(m); ses = np.zeros(m) + 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)) + G_scaled = StandardScaler().fit_transform(G) + PCs = PCA(n_components=max(1, n_pcs)).fit_transform(G_scaled) except Exception: PCs = np.zeros((n, 1)) U, d, Uty, Ut1, Vg, Ve, delta = precompute_rotation(y, K) qtns = [] - for iteration in range(6): + for iteration in range(3): cov_parts = [PCs] if qtns: cov_parts.append(G[:, qtns]) cov = np.hstack(cov_parts) - for j in range(m): + for j in range(min(m, 1000)): x = G[:, j] if x.std() < 1e-8: continue @@ -617,29 +634,28 @@ def gapit3_gwas(y, G, K): if x_res.std() < 1e-8: continue slope, _, _, _, se = stats.linregress(x_res, y_res) - df_c = max(n - cov.shape[1] - 2, 1) + 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 + 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]) + candidates = list(np.argsort(pvals)[:min(10, 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]) + 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] + 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) + 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): break @@ -647,1449 +663,789 @@ def gapit3_gwas(y, G, K): return pvals, betas, ses -def gemma_gwas(y, G, K): - """GEMMA LMM: centered kinship + REML via rotation trick.""" - 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) - grand_mean = K.mean() - Kc = K - row_mean - col_mean + grand_mean - - U, d, Uty, Ut1, Vg, Ve, delta = precompute_rotation(y, Kc) - - 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 - return pvals, betas, ses +# ─────────────────────── PLOTTING FUNCTIONS ─────────────────────────────────── -# ─────────────────────── FIGURE HELPERS ─────────────────────────────────────── -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 - img = Image.open(buf).copy() - buf.close() - return img - -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 - -# ─────────────────────── Manhattan tick midpoints ───────────────────────────── -def _compute_x_coords(chroms, positions, chrom_list): - """Compute x-axis coords for Manhattan layout.""" - x_coords = np.zeros(len(chroms)) - x_offset = 0 - max_pos = max(positions) if len(positions) > 0 else 1 +def plot_manhattan(pvals, chroms, positions, title="Manhattan Plot", model_name=""): + """Create enhanced Manhattan plot with proper chromosome spacing""" + fig, ax = plt.subplots(figsize=(16, 5), facecolor=BG_WHITE) + + log_p = -np.log10(np.clip(pvals, 1e-300, 1)) + sig_line = -np.log10(5e-8) + sug_line = -np.log10(1e-5) + + # Compute x-coordinates for SNPs + chrom_list = sorted(set(chroms)) + x_coords = [] + current_pos = 0 + for ch in chrom_list: mask = chroms == ch if not mask.any(): continue - pos = positions[mask] - x_coords[mask] = pos - pos.min() + x_offset - x_offset += pos.max() - pos.min() + max_pos * 0.02 + 1 - return x_coords - -def _compute_tick_positions(x_coords, chroms, chrom_list): - """Tick at span midpoint, not coordinate mean.""" - tick_pos, tick_lab = [], [] + ch_positions = positions[mask] + ch_positions = ch_positions - ch_positions.min() + x_coords.extend(ch_positions + current_pos) + current_pos += ch_positions.max() + positions.max() * 0.02 + + x_coords = np.array(x_coords) + + # Calculate tick positions + tick_pos = [] + tick_lab = [] + current_pos = 0 + 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) + ch_positions = positions[mask] + ch_positions = ch_positions - ch_positions.min() + tick_pos.append(current_pos + ch_positions.max() / 2) tick_lab.append(f"Chr{ch}") - return tick_pos, tick_lab - -# ─────────────────────── PLOTS ──────────────────────────────────────────────── -def plot_manhattan(pvals, chroms, positions, title="Manhattan Plot", model_name=""): - fig, ax = plt.subplots(figsize=(16, 5), facecolor=BG_WHITE) - ax.set_facecolor(PANEL_WHITE) - 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)) - 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_e = CHR_PALETTE[(chrom_list.index(ch) * 2) % len(CHR_PALETTE)] - col_o = CHR_PALETTE[(chrom_list.index(ch) * 2 + 1) % len(CHR_PALETTE)] - col = col_e if chrom_list.index(ch) % 2 == 0 else col_o - ax.scatter(x_coords[mask], log_p[mask], c=col, s=16, - alpha=0.85, linewidths=0) - - ax.axhline(sug_line, color=ACCENT_CYAN, ls=":", lw=1.4, alpha=0.9, - label="Suggestive (1e-5)") - ax.axhline(sig_line, color=ACCENT_CORAL, ls="--", lw=2.0, - label="GW sig. (5e-8)") + current_pos += ch_positions.max() + positions.max() * 0.02 + + # Plot SNPs by chromosome + for i, ch in enumerate(chrom_list): + mask = chroms == ch + if not mask.any(): + continue + ch_x = x_coords[mask] + ch_log = log_p[mask] + color = CHR_PALETTE[i % len(CHR_PALETTE)] + ax.scatter(ch_x, ch_log, c=color, s=12, alpha=0.8, linewidths=0) + + # Add threshold lines + ax.axhline(sug_line, color=ACCENT_CYAN, ls=":", lw=1.4, alpha=0.9, label="Suggestive (1e-5)") + ax.axhline(sig_line, color=ACCENT_CORAL, ls="--", lw=2.0, label="GW sig. (5e-8)") + + # Highlight significant SNPs sig_mask = log_p >= sig_line if sig_mask.any(): ax.scatter(x_coords[sig_mask], log_p[sig_mask], c=SIG_COLOR, s=100, marker="D", zorder=10, edgecolors="#7F0000", linewidth=0.9, - label=f"Sig. MTA ({sig_mask.sum()} SNPs)") - + label=f"Significant ({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, fontsize=9) - ax.set_title(f"{title}{' — ' + model_name if model_name else ''}", - color=TEXT_MAIN, fontsize=11, pad=8) - ax.legend(fontsize=7, framealpha=0.9, facecolor=BG_WHITE, - edgecolor=GRID_LINE, labelcolor=TEXT_MAIN) - x_max = x_coords.max() if len(x_coords) > 0 else 1 - ax.set_xlim(-x_max * 0.01, x_max * 1.01) + ax.set_xticklabels(tick_lab, rotation=45, ha='right', fontsize=8) + ax.set_ylabel("-log₁₀(p)", fontsize=10) + ax.set_xlabel("Chromosome", fontsize=10) + ax.set_title(f"{title}{' — ' + model_name if model_name else ''}", fontsize=12, fontweight='bold') + ax.legend(loc='upper right', fontsize=8, framealpha=0.9) + + style_fig(fig) fig.tight_layout() return fig -def _draw_qq_on_ax(ax, pvals, model_name, color): - """QQ plot matching the reference image style.""" - 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) - +def plot_qq(pvals, title="QQ Plot", model_name="", color=None): + """Create QQ plot with confidence intervals""" + fig, ax = plt.subplots(figsize=(8, 8), facecolor=BG_WHITE) + + n = len(pvals) + obs = -np.log10(np.sort(pvals)) + exp = -np.log10(np.arange(1, n + 1) / n) + + # Compute confidence intervals 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)) - - import matplotlib.colors as mcolors - rgb = mcolors.to_rgb(color) - ax.fill_between(exp, ci_lo, ci_hi, - color=rgb, alpha=0.22, zorder=1) - - 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, zorder=2, label="Expected") - - sig_thr = -np.log10(5e-8) - ns_mask = obs < sig_thr - if ns_mask.any(): - ax.scatter(exp[ns_mask], obs[ns_mask], - c=color, s=14, alpha=0.85, - linewidths=0, zorder=3) - - gw_mask = obs >= sig_thr - if gw_mask.any(): - ax.scatter(exp[gw_mask], obs[gw_mask], - c=color, s=55, alpha=1.0, - linewidths=0.6, edgecolors="white", zorder=5, - label=f"GW sig. (n={int(gw_mask.sum())})") - - lam = (np.median(stats.chi2.ppf(1 - np.clip(pvals, 1e-10, 1), df=1)) - / stats.chi2.ppf(0.5, df=1)) - lam_str = f"λ = {lam:.4f}" - lam_col = "#1a7a1a" if lam <= 1.05 else "#cc6600" if lam <= 1.15 else "#cc0000" - ax.text(0.04, 0.97, lam_str, - transform=ax.transAxes, - fontsize=10, fontweight="bold", color=lam_col, - va="top", ha="left", - bbox=dict(boxstyle="round,pad=0.3", - facecolor="white", edgecolor=lam_col, - alpha=0.88, linewidth=1.0)) - - ax.set_facecolor("white") - ax.set_xlabel("Expected −log₁₀(p)", fontsize=10, color="#222222", - labelpad=6) - ax.set_ylabel("Observed −log₁₀(p)", fontsize=10, color="#222222", - labelpad=6) - ax.tick_params(axis="both", colors="#222222", labelsize=9, - direction="out", length=5, width=0.9, - top=False, right=False) - ax.spines["top"].set_visible(False) - ax.spines["right"].set_visible(False) - ax.spines["bottom"].set_edgecolor("#333333") - ax.spines["bottom"].set_linewidth(1.0) - ax.spines["left"].set_edgecolor("#333333") - ax.spines["left"].set_linewidth(1.0) - ax.set_axisbelow(False) - ax.grid(False) - - ax.set_xlim(-0.05, xy_max) - y_max = max(float(obs.max()), sig_thr) * 1.10 - ax.set_ylim(-0.15, y_max) - - return lam - -def plot_qq_single(pvals, title="QQ Plot", model_name="", color=None): + if color is None: color = ACCENT_PURP - fig, ax = plt.subplots(figsize=(7, 7), facecolor="white") - ax.set_facecolor("white") - lam = _draw_qq_on_ax(ax, pvals, model_name, color) - full_title = f"{title}{' — ' + model_name if model_name else ''}" - ax.set_title(full_title, color="#1E293B", fontsize=12, - fontweight="bold", pad=8) - handles, labels = ax.get_legend_handles_labels() - ax.legend(handles, labels, fontsize=7.5, - framealpha=0.92, facecolor="white", - edgecolor="#CCCCCC", labelcolor="#333333", - loc="lower right", borderpad=0.7) - fig.tight_layout() - return fig - -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.2 * ncols, 7.0 * nrows), - facecolor="white") - fig.patch.set_facecolor("white") - if n_models == 1: - axes = np.array([axes]) - axes_flat = np.array(axes).flatten() - - for idx, (mname, (pvals, _, _)) in enumerate(all_results.items()): - ax = axes_flat[idx] - ax.set_facecolor("white") - col = MODEL_COLORS.get(mname, ACCENT_BLUE) - lam = _draw_qq_on_ax(ax, pvals, mname, col) - ax.set_title(f"{mname} (λ = {lam:.3f})", - color="#1E293B", fontsize=10, fontweight="bold", pad=6) - handles, labels = ax.get_legend_handles_labels() - ax.legend(handles, labels, fontsize=6, - facecolor="white", edgecolor="#CCCCCC", - labelcolor="#333333", loc="lower right", - borderpad=0.5) - - for idx in range(n_models, len(axes_flat)): - axes_flat[idx].set_visible(False) - - fig.suptitle("QQ Plots — All Models", color="#1E293B", - fontsize=14, fontweight="bold", y=1.01) + + # Plot confidence band + ax.fill_between(exp, ci_lo, ci_hi, alpha=0.2, color=color) + + # Plot points + ax.scatter(exp, obs, c=color, s=15, alpha=0.7, linewidths=0) + + # Diagonal line + max_val = max(exp.max(), obs.max()) * 1.05 + ax.plot([0, max_val], [0, max_val], 'k--', lw=1.5, alpha=0.7, label='Expected') + + # Compute lambda + chi2_obs = stats.chi2.ppf(1 - np.clip(pvals, 1e-10, 1), df=1) + lambda_gc = np.median(chi2_obs) / stats.chi2.ppf(0.5, df=1) + + ax.text(0.05, 0.95, f"λ = {lambda_gc:.3f}", transform=ax.transAxes, + fontsize=11, fontweight='bold', va='top', + bbox=dict(boxstyle='round', facecolor='white', alpha=0.8)) + + 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 ''}", fontsize=12, fontweight='bold') + + style_fig(fig) fig.tight_layout() return fig -def plot_qq_overlay(all_results): - fig, ax = plt.subplots(figsize=(9, 9), facecolor="white") - ax.set_facecolor("white") - exp_max = 0 +def plot_circos_best_models(all_results, chroms, positions, top_n=4): + """Circos plot showing only best performing models based on λ""" + # Calculate performance metrics for each model + model_performance = [] 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 = (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=2.2, label=f"{mname} λ={lam:.3f}", alpha=0.88) - ax.plot([0, exp_max * 1.05], [0, exp_max * 1.05], - color="#333333", ls="-", lw=1.4, label="y = x") - ax.axhline(-np.log10(5e-8), color="#CC0000", ls="--", - lw=1.2, alpha=0.8, label="GW sig. (5e-8)") - ax.set_xlabel("Expected −log₁₀(p)", fontsize=11, color="#333333") - ax.set_ylabel("Observed −log₁₀(p)", fontsize=11, color="#333333") - ax.set_title("QQ Plot — All Models Overlay", color="#1E293B", - fontsize=13, fontweight="bold") - ax.legend(fontsize=8.5, framealpha=0.94, facecolor="white", - edgecolor="#CCCCCC", labelcolor="#333333", - loc="upper left") - ax.tick_params(colors="#333333", labelsize=9, direction="out") - for spine in ax.spines.values(): - spine.set_edgecolor("#333333"); spine.set_linewidth(0.9) - ax.grid(color="#EEEEEE", linewidth=0.5, linestyle="-", alpha=1.0) - ax.set_axisbelow(True) - fig.tight_layout() - return fig - -def plot_circos(all_results, chroms, positions): - fig, ax = plt.subplots(figsize=(14, 14), - subplot_kw=dict(projection='polar'), - facecolor=BG_WHITE) - ax.set_facecolor(BG_WHITE) - ax.grid(False); ax.set_yticks([]); ax.set_xticks([]) + chi2_obs = stats.chi2.ppf(1 - np.clip(pvals, 1e-10, 1), df=1) + lambda_gc = np.median(chi2_obs) / stats.chi2.ppf(0.5, df=1) + + # Calculate number of significant SNPs (Bonferroni) + bonf_threshold = 0.05 / len(pvals) + n_sig = np.sum(pvals < bonf_threshold) + + # Composite score: lower λ is better, more sig SNPs is better + # Normalize metrics + lambda_score = abs(lambda_gc - 1) # Lower is better + sig_score = -np.log10(n_sig + 1) if n_sig > 0 else 0 # More sig is better + + # Combined score (lower is better) + combined_score = lambda_score * 0.7 + sig_score * 0.3 + + model_performance.append((mname, lambda_gc, n_sig, combined_score, pvals)) + + # Sort by combined score and take top N + model_performance.sort(key=lambda x: x[3]) + best_models = model_performance[:top_n] + + print(f"Selected best {top_n} models for circos plot:") + for mname, lam, n_sig, score, _ in best_models: + print(f" {mname}: λ={lam:.3f}, sig SNPs={n_sig}, score={score:.4f}") + + fig, ax = plt.subplots(figsize=(12, 12), subplot_kw=dict(projection='polar'), facecolor=BG_WHITE) + ax.grid(False) + ax.set_yticks([]) + ax.set_xticks([]) ax.spines['polar'].set_visible(False) - - sort_idx = np.lexsort((positions, chroms)) - chroms_s = chroms[sort_idx] - positions_s = positions[sort_idx] - - chrom_list = sorted(set(chroms)) - total_snps = len(chroms_s) - snp_angles = np.linspace(0, 2 * np.pi, total_snps, endpoint=False) - outer_r = 1.0 - - for ch in chrom_list: - mask = chroms_s == ch - idxs = np.where(mask)[0] - if len(idxs) == 0: + + # Sort SNPs by chromosome and position + sort_idx = np.lexsort((positions, chroms)) + chroms_sorted = chroms[sort_idx] + positions_sorted = positions[sort_idx] + + total_snps = len(chroms_sorted) + angles = np.linspace(0, 2 * np.pi, total_snps, endpoint=False) + + # Plot chromosome background + chrom_list = sorted(set(chroms_sorted)) + outer_r = 1.0 + + for i, ch in enumerate(chrom_list): + mask = chroms_sorted == ch + if not mask.any(): continue - theta = snp_angles[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') - - n_models = len(all_results) - 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, (pvals, _, _)) in enumerate(all_results.items()): - log_p_s = -np.log10(np.clip(pvals[sort_idx], 1e-300, 1)) - r_base = ring_inner + midx * ring_width - r_max_d = ring_width * 0.85 - col = MODEL_COLORS.get(mname, CHR_PALETTE[midx % len(CHR_PALETTE)]) - max_lp = max(log_p_s.max(), sig_line, 1) - lp_norm = log_p_s / max_lp * r_max_d - - ax.plot(snp_angles, np.full_like(snp_angles, r_base), - color=col, alpha=0.2, lw=0.6) - ax.scatter(snp_angles, r_base + lp_norm, - c=col, s=4, alpha=0.6, linewidths=0) - - sig_mask = log_p_s >= sig_line + ch_angles = angles[mask] + color = CHR_PALETTE[i % len(CHR_PALETTE)] + ax.bar(ch_angles, [0.05] * len(ch_angles), width=2 * np.pi / total_snps * 1.2, + bottom=outer_r, color=color, alpha=0.8, linewidth=0) + + # Add chromosome label + mid_angle = (ch_angles[0] + ch_angles[-1]) / 2 if len(ch_angles) > 0 else 0 + ax.text(mid_angle, outer_r + 0.08, f"Chr{ch}", ha='center', va='center', fontsize=7, color=color) + + # Plot each model's results as a ring + ring_inner = 0.15 + ring_width = (outer_r - 0.05 - ring_inner) / len(best_models) + + sig_threshold = -np.log10(5e-8) + + for idx, (mname, lambda_gc, n_sig, _, pvals) in enumerate(best_models): + pvals_sorted = pvals[sort_idx] + log_p = -np.log10(np.clip(pvals_sorted, 1e-300, 1)) + r_base = ring_inner + idx * ring_width + max_h = ring_width * 0.8 + + # Normalize heights + max_log = max(log_p.max(), sig_threshold) + heights = (log_p / max_log) * max_h + + color = MODEL_COLORS.get(mname, CHR_PALETTE[idx % len(CHR_PALETTE)]) + + # Plot ring baseline + ax.plot(angles, np.full_like(angles, r_base), color=color, alpha=0.3, lw=0.5) + + # Plot points + ax.scatter(angles, r_base + heights, c=color, s=2, alpha=0.6, linewidths=0) + + # Highlight significant SNPs + sig_mask = log_p >= sig_threshold if sig_mask.any(): - ax.scatter(snp_angles[sig_mask], r_base + lp_norm[sig_mask], - c=SIG_COLOR, s=45, zorder=10, marker='D', - edgecolors='#7F0000', linewidth=0.6, alpha=0.95) - ax.text(0, r_base + r_max_d / 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.85) - for m in all_results - ] - 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.9, facecolor=BG_WHITE, - edgecolor=GRID_LINE, labelcolor=TEXT_MAIN) - ax.set_title( - "Circos — Multi-Model GWAS\n(Ring height = −log₁₀(p) | ◆ = Sig. MTA)", - color=TEXT_MAIN, fontsize=12, pad=20) + ax.scatter(angles[sig_mask], r_base + heights[sig_mask], + c=SIG_COLOR, s=25, marker='D', zorder=10, + edgecolors='white', linewidth=0.5, alpha=0.9) + + # Add model label with performance metrics + ax.text(0, r_base + max_h/2, f"{mname}\nλ={lambda_gc:.3f}\n{n_sig} sig", + ha='center', va='center', + fontsize=7, color=color, fontweight='bold', alpha=0.9) + + # Add legend + legend_elements = [mpatches.Patch(facecolor=MODEL_COLORS.get(m, ACCENT_BLUE), + label=f"{m} (λ={l:.3f}, {n} sig)", alpha=0.8) + for m, l, n, _, _ in best_models] + legend_elements.append(mpatches.Patch(facecolor=SIG_COLOR, label=f"Significant (p<5e-8)", alpha=0.9)) + + ax.legend(handles=legend_elements, loc='center left', bbox_to_anchor=(1.15, 0.5), + fontsize=7, framealpha=0.9, facecolor=BG_WHITE) + + ax.set_title("Circos Plot - Top Performing Models\n(Selected by λ inflation & significance)", + color=TEXT_MAIN, fontsize=11, pad=20, fontweight='bold') + + style_fig(fig) fig.tight_layout() return fig -def plot_ld_decay(G, positions, chroms): - """ - IMPROVED LD DECAY PLOT - - Samples 150 SNPs per chromosome for reliable curves - - Clear distance markers in both bp and Mb - - Shows where r² = 0.5 and 0.2 decay occurs - - Better binning and visualization - """ - fig, axes = plt.subplots(1, 2, figsize=(16, 6), facecolor=BG_WHITE) - style_fig(fig) - - chrom_list = sorted(set(chroms)) - sample_per_chr = 150 - sampled_idx = [] - rng = np.random.default_rng(42) +def plot_ld_decay(G, positions, chroms, max_dist_mb=5): + """LD decay plot with distance-based binning""" + fig, ax = plt.subplots(figsize=(10, 6), facecolor=BG_WHITE) - for ch in chrom_list: - idx_ch = np.where(chroms == ch)[0] - n_samp = min(sample_per_chr, len(idx_ch)) - sampled_idx.extend(rng.choice(idx_ch, n_samp, replace=False).tolist()) - sampled_idx = sorted(set(sampled_idx)) - - dists_bp, r2s = [], [] - for ii, i in enumerate(sampled_idx): - for j in sampled_idx[ii+1:]: - xi, xj = G[:, i], G[:, j] - mask = ~(np.isnan(xi) | np.isnan(xj)) - if mask.sum() < 4: + # Sample SNPs for LD calculation + n_snps = G.shape[1] + if n_snps > 300: + sample_idx = [] + chrom_list = sorted(set(chroms)) + for ch in chrom_list: + ch_idx = np.where(chroms == ch)[0] + n_sample = min(30, len(ch_idx)) + if n_sample > 0: + step = max(1, len(ch_idx) // n_sample) + sample_idx.extend(ch_idx[::step][:n_sample]) + sample_idx = sorted(set(sample_idx)) + else: + sample_idx = list(range(n_snps)) + + # Calculate pairwise LD + dists = [] + r2_vals = [] + + for i in range(len(sample_idx)): + for j in range(i + 1, min(i + 100, len(sample_idx))): + idx_i = sample_idx[i] + idx_j = sample_idx[j] + + if chroms[idx_i] != chroms[idx_j]: continue + + dist = abs(positions[idx_j] - positions[idx_i]) + dist_mb = dist / 1_000_000 + + if dist_mb > max_dist_mb: + continue + + xi = G[:, idx_i] + xj = G[:, idx_j] + mask = ~(np.isnan(xi) | np.isnan(xj)) + + if mask.sum() < 10: + continue + try: r, _ = stats.pearsonr(xi[mask], xj[mask]) - except Exception: + r2 = r ** 2 + dists.append(dist_mb) + r2_vals.append(r2) + except: continue - d = abs(positions[j] - positions[i]) - if d > 0: - dists_bp.append(d) - r2s.append(r**2) - - if len(dists_bp) < 2: - for ax in axes: - ax.text(0.5, 0.5, "Insufficient data for LD decay", - ha='center', transform=ax.transAxes, color=TEXT_DIM) - fig.tight_layout() + + if len(dists) == 0: + ax.text(0.5, 0.5, "Insufficient data for LD decay analysis", + ha='center', transform=ax.transAxes, fontsize=12) + style_fig(fig) return fig + + # Bin distances + bins = np.linspace(0, max_dist_mb, 20) + bin_centers = [] + bin_means = [] + bin_sems = [] + + for k in range(len(bins) - 1): + mask = (np.array(dists) >= bins[k]) & (np.array(dists) < bins[k+1]) + if mask.sum() > 5: + bin_centers.append((bins[k] + bins[k+1]) / 2) + bin_means.append(np.mean(np.array(r2_vals)[mask])) + bin_sems.append(stats.sem(np.array(r2_vals)[mask]) if mask.sum() > 1 else 0) + + # Plot raw points + ax.scatter(dists, r2_vals, c=ACCENT_BLUE, s=8, alpha=0.2, linewidths=0) + + # Plot binned means + if len(bin_centers) > 0: + ax.errorbar(bin_centers, bin_means, yerr=bin_sems, + c=ACCENT_CORAL, lw=2, marker='o', ms=5, capsize=3, + label='Mean r² (± SEM)') + + # Reference lines + ax.axhline(0.5, color=ACCENT_GOLD, ls='--', lw=1.5, alpha=0.7, label='r² = 0.5') + ax.axhline(0.2, color=ACCENT_CYAN, ls='--', lw=1.5, alpha=0.7, label='r² = 0.2') + + ax.set_xlabel('Distance (Mb)', fontsize=11) + ax.set_ylabel("r² (Linkage Disequilibrium)", fontsize=11) + ax.set_title("Linkage Disequilibrium (LD) Decay", fontsize=13, fontweight='bold') + ax.set_ylim(0, 1.05) + ax.set_xlim(0, max_dist_mb) + ax.legend(loc='upper right', fontsize=9, framealpha=0.9) + + style_fig(fig) + fig.tight_layout() + return fig - dists_bp = np.array(dists_bp) - dists_mb = dists_bp / 1_000_000 - r2s = np.array(r2s) - - def bin_ld_enhanced(dists, r2s, n_bins=30): - """Enhanced binning with better statistics""" - 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) - - # Plot for both bp and Mb - for ax, dists, unit, c1, c2 in [ - (axes[0], dists_bp, "bp", ACCENT_TEAL, ACCENT_CORAL), - (axes[1], dists_mb, "Mb", ACCENT_PURP, ACCENT_GOLD), - ]: - ax.set_facecolor(PANEL_WHITE) - - # Raw data points - ax.scatter(dists, r2s, c=c1, s=8, alpha=0.25, linewidths=0, label="Pairwise LD") - - # Binned mean with error bands - bc, bm, bs = bin_ld_enhanced(dists, r2s) - if len(bc) > 0: - ax.plot(bc, bm, color=c2, lw=3.0, marker='o', ms=6, - zorder=5, label="Binned mean r²", markersize=4) - ax.fill_between(bc, bm - bs, bm + bs, alpha=0.25, color=c2) +def plot_pca(G, y, ids): + """PCA plot with population structure visualization""" + n = G.shape[0] + if n > 500: + sample_idx = np.random.choice(n, min(500, n), replace=False) + G_sample = G[sample_idx] + y_sample = y[sample_idx] + else: + G_sample = G + y_sample = y + + fig, axes = plt.subplots(1, 2, figsize=(14, 5), facecolor=BG_WHITE) + + try: + scaler = StandardScaler() + G_scaled = scaler.fit_transform(G_sample) - # Reference lines - ax.axhline(0.5, color=ACCENT_GOLD, ls='--', lw=2.0, alpha=0.9, label="r² = 0.5") - ax.axhline(0.2, color=ACCENT_CYAN, ls=':', lw=1.8, alpha=0.8, label="r² = 0.2") + n_comp = min(10, G_scaled.shape[0] - 1, G_scaled.shape[1]) + pca = PCA(n_components=n_comp) + pcs = pca.fit_transform(G_scaled) + var_exp = pca.explained_variance_ratio_ * 100 - # Find where decay crosses thresholds - if len(bc) > 0: - # Find crossing points - for threshold, thr_label, thr_color in [(0.5, "50%", ACCENT_GOLD), (0.2, "20%", ACCENT_CYAN)]: - cross_idx = np.where(bm < threshold)[0] - if len(cross_idx) > 0: - cross_dist = bc[cross_idx[0]] - ax.axvline(cross_dist, color=thr_color, ls=':', lw=1.2, alpha=0.6) - # Annotation - ax.text(cross_dist, threshold + 0.05, - f"{thr_label} decay\n@ {cross_dist:.1f} {unit}", - fontsize=8, ha='center', va='bottom', - bbox=dict(boxstyle='round,pad=0.4', - facecolor='white', edgecolor=thr_color, alpha=0.8)) + # PC1 vs PC2 + sc1 = axes[0].scatter(pcs[:, 0], pcs[:, 1], c=y_sample, cmap='viridis', + s=40, alpha=0.7, edgecolors='black', linewidth=0.5) + axes[0].set_xlabel(f'PC1 ({var_exp[0]:.1f}%)', fontsize=10) + axes[0].set_ylabel(f'PC2 ({var_exp[1]:.1f}%)', fontsize=10) + axes[0].set_title('PCA: Population Structure', fontsize=11, fontweight='bold') + plt.colorbar(sc1, ax=axes[0], label='Phenotype') - ax.set_xlabel(f"Distance ({unit})", fontsize=10, color=TEXT_DIM, fontweight='bold') - ax.set_ylabel("r² (LD)", fontsize=10, color=TEXT_DIM, fontweight='bold') - ax.set_title(f"LD Decay — {unit}", color=TEXT_MAIN, fontsize=11, fontweight='bold') - ax.legend(fontsize=7.5, framealpha=0.95, facecolor=BG_WHITE, - edgecolor=GRID_LINE, labelcolor=TEXT_MAIN, loc='upper right') - ax.set_ylim(0, 1.05) + # Scree plot + axes[1].bar(range(1, min(10, n_comp) + 1), var_exp[:min(10, n_comp)], + color=ACCENT_BLUE, alpha=0.7, edgecolor='black') + axes[1].plot(range(1, min(10, n_comp) + 1), np.cumsum(var_exp[:min(10, n_comp)]), + color=ACCENT_CORAL, marker='o', lw=2, label='Cumulative') + axes[1].set_xlabel('Principal Component', fontsize=10) + axes[1].set_ylabel('Variance Explained (%)', fontsize=10) + axes[1].set_title('Scree Plot', fontsize=11, fontweight='bold') + axes[1].legend() + axes[1].grid(True, alpha=0.3) - # Better grid - ax.grid(True, color=GRID_LINE, linewidth=0.5, linestyle='--', alpha=0.5) - - fig.suptitle("Linkage Disequilibrium (LD) Decay Analysis", - color=TEXT_MAIN, fontsize=14, fontweight='bold') + except Exception as e: + for ax in axes: + ax.text(0.5, 0.5, f"PCA failed: {str(e)[:50]}", + ha='center', transform=ax.transAxes, fontsize=10) + + style_fig(fig) fig.tight_layout() return fig -def plot_pca(G, y, ids): - fig, axes = plt.subplots(2, 2, figsize=(14, 12), facecolor=BG_WHITE) - style_fig(fig) - 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: - for ax in axes.flatten(): - ax.text(0.5, 0.5, "PCA unavailable", - ha='center', transform=ax.transAxes, color=TEXT_DIM) - fig.tight_layout() - return fig - - axes[0,0].set_facecolor(PANEL_WHITE) - 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}%)", color=TEXT_DIM) - axes[0,0].set_ylabel(f"PC2 ({var_exp[1]:.1f}%)", color=TEXT_DIM) - axes[0,0].set_title("PCA: PC1 vs PC2", color=TEXT_MAIN) - plt.colorbar(sc, ax=axes[0,0], label="Phenotype") - - axes[0,1].set_facecolor(PANEL_WHITE) - 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}%)", color=TEXT_DIM) - axes[0,1].set_ylabel(f"PC4 ({var_exp[3]:.1f}%)", color=TEXT_DIM) - axes[0,1].set_title("PCA: PC3 vs PC4", color=TEXT_MAIN) +def plot_kinship_heatmap(K, ids): + """Kinship heatmap with dendrogram - optimized for large datasets""" + n = K.shape[0] + + if n > 200: + sample_idx = np.linspace(0, n-1, 200, dtype=int) + K_sample = K[np.ix_(sample_idx, sample_idx)] + ids_sample = ids[sample_idx] + title_note = f" (sampled 200 of {n} individuals)" + else: + K_sample = K + ids_sample = ids + title_note = "" + + fig, ax = plt.subplots(figsize=(12, 10), facecolor=BG_WHITE) + + im = ax.imshow(K_sample, cmap='RdYlBu_r', aspect='auto', vmin=-0.5, vmax=1) + plt.colorbar(im, ax=ax, label='Kinship coefficient', fraction=0.046, pad=0.04) + + if n <= 50: + ax.set_xticks(range(len(ids_sample))) + ax.set_yticks(range(len(ids_sample))) + ax.set_xticklabels(ids_sample, rotation=90, fontsize=6) + ax.set_yticklabels(ids_sample, fontsize=6) else: - axes[0,1].text(0.5, 0.5, "< 4 PCs available", - ha='center', transform=axes[0,1].transAxes, color=TEXT_DIM) - - axes[1,0].set_facecolor(PANEL_WHITE) - axes[1,0].bar(range(1, n_comp+1), var_exp, - color=ACCENT_BLUE, edgecolor='none', alpha=0.85) - 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", color=TEXT_DIM) - axes[1,0].set_ylabel("Variance Explained (%)", color=TEXT_DIM) - axes[1,0].set_title("Scree Plot", color=TEXT_MAIN) - - axes[1,1].set_facecolor(PANEL_WHITE) - 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)", color=TEXT_MAIN) + step = max(1, len(ids_sample) // 20) + ax.set_xticks(range(0, len(ids_sample), step)) + ax.set_yticks(range(0, len(ids_sample), step)) + ax.set_xticklabels(ids_sample[::step], rotation=90, fontsize=8) + ax.set_yticklabels(ids_sample[::step], fontsize=8) + + ax.set_title(f"Kinship Matrix (VanRaden){title_note}", fontsize=13, fontweight='bold') + ax.set_xlabel("Individual", fontsize=10) + ax.set_ylabel("Individual", fontsize=10) + + style_fig(fig) fig.tight_layout() return fig -def plot_model_comparison_manhattan(all_results, chroms, positions): +def plot_model_comparison(all_results, chroms, positions): + """Compare Manhattan plots across all models""" n_models = len(all_results) - fig, axes = plt.subplots(n_models, 1, - figsize=(16, 3.5 * n_models), + fig, axes = plt.subplots(n_models, 1, figsize=(16, 3 * n_models), sharex=True, facecolor=BG_WHITE) - style_fig(fig) + if n_models == 1: axes = [axes] - - 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 midx, (mname, (pvals, _, _)) in enumerate(all_results.items()): - ax = axes[midx] - ax.set_facecolor(PANEL_WHITE) - log_p = -np.log10(np.clip(pvals, 1e-300, 1)) - col = MODEL_COLORS.get(mname, CHR_PALETTE[midx % len(CHR_PALETTE)]) - ax.scatter(x_coords, log_p, c=col, s=8, alpha=0.75, 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=55, zorder=10, - marker='D', linewidths=0.6, edgecolors='#7F0000') - 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.5) - - fig.suptitle("Manhattan Plots — All Models Comparison", - color=TEXT_MAIN, fontsize=13) - fig.tight_layout(rect=[0, 0, 1, 0.98]) - return fig - -def plot_all_models_manhattan_grid(all_results, chroms, positions): - n_models = len(all_results) - ncols = min(2, n_models) - nrows = (n_models + ncols - 1) // ncols - fig, axes = plt.subplots(nrows, ncols, - figsize=(16, 4 * nrows), - facecolor=BG_WHITE) - style_fig(fig) - if n_models == 1: - axes = np.array([axes]) - axes_flat = np.array(axes).flatten() - + + # Compute x-coordinates 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 midx, (mname, (pvals, _, _)) in enumerate(all_results.items()): - ax = axes_flat[midx] - ax.set_facecolor(PANEL_WHITE) + x_coords = [] + current_pos = 0 + + for ch in chrom_list: + mask = chroms == ch + ch_positions = positions[mask] + ch_positions = ch_positions - ch_positions.min() + x_coords.extend(ch_positions + current_pos) + current_pos += ch_positions.max() + positions.max() * 0.02 + + x_coords = np.array(x_coords) + + # Compute tick positions + tick_pos = [] + tick_lab = [] + current_pos = 0 + + for ch in chrom_list: + mask = chroms == ch + ch_positions = positions[mask] + ch_positions = ch_positions - ch_positions.min() + tick_pos.append(current_pos + ch_positions.max() / 2) + tick_lab.append(f"Chr{ch}") + current_pos += ch_positions.max() + positions.max() * 0.02 + + sig_line = -np.log10(5e-8) + + for idx, (mname, (pvals, _, _)) in enumerate(all_results.items()): + ax = axes[idx] log_p = -np.log10(np.clip(pvals, 1e-300, 1)) - col = MODEL_COLORS.get(mname, CHR_PALETTE[midx % len(CHR_PALETTE)]) - ax.scatter(x_coords, log_p, c=col, s=10, alpha=0.78, 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=65, zorder=10, - marker='D', linewidths=0.8, edgecolors='#7F0000') - ax.axhline(-np.log10(5e-8), color=ACCENT_CORAL, - ls='--', lw=1.2, alpha=0.85, label="GW sig.") - ax.axhline(-np.log10(1e-5), color=ACCENT_CYAN, - ls=':', lw=1.0, alpha=0.75, label="Suggestive") - ax.set_ylabel("-log₁₀(p)", fontsize=8, color=TEXT_DIM) - ax.set_title(f"Manhattan — {mname}", - color=col, fontsize=10, fontweight='bold', pad=4) - ax.set_xticks(tick_pos) - ax.set_xticklabels(tick_lab, rotation=40, fontsize=7, color=TEXT_DIM) - 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.4, linestyle="--", alpha=0.5) - 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.99, 0.96, f"λ={lam:.3f}", - transform=ax.transAxes, fontsize=8, - color=ACCENT_GOLD, fontweight='bold', - ha='right', va='top') - ax.legend(fontsize=6, facecolor=BG_WHITE, - edgecolor=GRID_LINE, loc='upper right') - - for idx in range(n_models, len(axes_flat)): - axes_flat[idx].set_visible(False) - - fig.suptitle("Manhattan Plots — All Selected Models", - color=TEXT_MAIN, fontsize=13, y=1.01) - fig.tight_layout() - return fig - -def plot_kinship(K, ids): - """ - IMPROVED KINSHIP PLOT - - Smart label handling for large datasets - - No overlapping labels - - Dynamic figure sizing - """ - n_samples = len(ids) - - # Smart label strategy - if n_samples > 100: - # For very large datasets: no labels on dendrogram - show_labels = False - label_list = None - fig_height = 12 - elif n_samples > 50: - # For medium datasets: show every 5th label - show_labels = True - label_list = [ids[i] if i % 5 == 0 else '' for i in range(n_samples)] - fig_height = 14 - else: - # For small datasets: show all labels - show_labels = True - label_list = ids - fig_height = 12 + color = MODEL_COLORS.get(mname, CHR_PALETTE[idx % len(CHR_PALETTE)]) + + ax.scatter(x_coords, log_p, c=color, s=6, alpha=0.6, linewidths=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=40, marker='D', zorder=10, + edgecolors='white', linewidth=0.5) + + ax.axhline(sig_line, color=ACCENT_CORAL, ls='--', lw=1, alpha=0.7) + + ax.set_ylabel("-log₁₀(p)", fontsize=8) + ax.set_title(f"{mname}", fontsize=9, color=color, fontweight='bold') + ax.set_xlim(x_coords.min(), x_coords.max()) + + # Add lambda + chi2_obs = stats.chi2.ppf(1 - np.clip(pvals, 1e-10, 1), df=1) + lambda_gc = np.median(chi2_obs) / stats.chi2.ppf(0.5, df=1) + ax.text(0.02, 0.95, f"λ = {lambda_gc:.3f}", transform=ax.transAxes, + fontsize=7, fontweight='bold', va='top', + bbox=dict(boxstyle='round', facecolor='white', alpha=0.7)) + + # Set x-axis for bottom plot only + axes[-1].set_xticks(tick_pos) + axes[-1].set_xticklabels(tick_lab, rotation=45, ha='right', fontsize=7) + axes[-1].set_xlabel("Chromosome", fontsize=9) - fig, axes = plt.subplots(2, 2, figsize=(14, fig_height), facecolor=BG_WHITE) + fig.suptitle("Manhattan Plots - All 10 Models Comparison", fontsize=13, fontweight='bold', y=1.02) style_fig(fig) - for ax in axes.flatten(): - ax.set_facecolor(PANEL_WHITE) - - # Kinship heatmap - im = axes[0,0].imshow(K, cmap='RdYlBu_r', aspect='auto', vmin=-0.5, vmax=1) - axes[0,0].set_title("Kinship Matrix (VanRaden)", color=TEXT_MAIN, fontsize=11, fontweight='bold') - plt.colorbar(im, ax=axes[0,0], label="Kinship coefficient") - - # Distribution - K_flat = K[np.triu_indices_from(K, k=1)] - axes[0,1].hist(K_flat, bins=30, color=ACCENT_PURP, edgecolor='none', alpha=0.85) - axes[0,1].axvline(K_flat.mean(), color=ACCENT_CORAL, ls='--', lw=2, - label=f"Mean: {K_flat.mean():.3f}") - axes[0,1].set_title("Pairwise Kinship Distribution", color=TEXT_MAIN, fontsize=11, fontweight='bold') - axes[0,1].set_xlabel("Kinship coefficient", color=TEXT_DIM) - axes[0,1].set_ylabel("Frequency", color=TEXT_DIM) - axes[0,1].legend(fontsize=8) - - # Dendrogram with smart labeling - try: - lm = linkage(K, method='average') - if show_labels and label_list is not None: - dendrogram(lm, ax=axes[1,0], labels=label_list, - leaf_rotation=90, leaf_font_size=6 if n_samples <= 50 else 4, - color_threshold=0.7, - above_threshold_color=ACCENT_TEAL) - else: - # No labels for very large datasets - dendrogram(lm, ax=axes[1,0], no_labels=True, - color_threshold=0.7, - above_threshold_color=ACCENT_TEAL) - axes[1,0].text(0.5, 0.02, f"({n_samples} samples - labels hidden for clarity)", - transform=axes[1,0].transAxes, ha='center', - fontsize=8, color=TEXT_DIM, style='italic') - except Exception as e: - axes[1,0].text(0.5, 0.5, f"Dendrogram unavailable\n({str(e)})", - ha='center', transform=axes[1,0].transAxes, color=TEXT_DIM) - axes[1,0].set_title("Hierarchical Clustering Dendrogram", color=TEXT_MAIN, fontsize=11, fontweight='bold') - axes[1,0].set_xlabel("Sample", color=TEXT_DIM) - axes[1,0].set_ylabel("Distance", color=TEXT_DIM) - - # Kinship PCA - eigvals, eigvecs = np.linalg.eigh(K) - idx = np.argsort(eigvals)[::-1] - var_exp1 = eigvals[idx[0]] / eigvals.sum() * 100 - var_exp2 = eigvals[idx[1]] / eigvals.sum() * 100 - axes[1,1].scatter(eigvecs[:, idx[0]], eigvecs[:, idx[1]], - c=ACCENT_TEAL, s=60, edgecolors='white', linewidths=0.5, alpha=0.8) - axes[1,1].set_title("Kinship PCA", color=TEXT_MAIN, fontsize=11, fontweight='bold') - axes[1,1].set_xlabel(f"PC1 ({var_exp1:.1f}%)", color=TEXT_DIM) - axes[1,1].set_ylabel(f"PC2 ({var_exp2:.1f}%)", color=TEXT_DIM) - axes[1,1].grid(True, alpha=0.3) - - fig.suptitle(f"Kinship Analysis ({n_samples} samples)", - color=TEXT_MAIN, fontsize=13, fontweight='bold') fig.tight_layout() return fig -def plot_effect_sizes(pvals, betas, snp_names): - fig, axes = plt.subplots(2, 2, figsize=(14, 10), facecolor=BG_WHITE) - style_fig(fig) - for ax in axes.flatten(): - ax.set_facecolor(PANEL_WHITE) - - 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, alpha=0.85) - axes[0,0].axvline(0, color=TEXT_DIM, lw=0.8) - axes[0,0].set_yticks(range(len(top_betas))) - axes[0,0].set_yticklabels(top_names, fontsize=7, color=TEXT_DIM) - axes[0,0].set_xlabel("Effect Size (β)", color=TEXT_DIM) - axes[0,0].set_title("Top 20 Effect Sizes", color=TEXT_MAIN) - - 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.75, 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("β", color=TEXT_DIM) - axes[0,1].set_ylabel("-log₁₀(p)", color=TEXT_DIM) - axes[0,1].set_title("Volcano Plot", color=TEXT_MAIN) - axes[0,1].legend(fontsize=7, facecolor=BG_WHITE) - - axes[1,0].hist(betas, bins=30, color=ACCENT_BLUE, edgecolor='none', alpha=0.85) - axes[1,0].axvline(0, color=ACCENT_CORAL, lw=2, ls='--') - axes[1,0].set_xlabel("β", color=TEXT_DIM) - axes[1,0].set_title("Effect Size Distribution", color=TEXT_MAIN) - - axes[1,1].scatter(betas, log_p, c=colors_v, s=20, alpha=0.65, linewidths=0) - axes[1,1].set_xlabel("β", color=TEXT_DIM) - axes[1,1].set_ylabel("-log₁₀(p)", color=TEXT_DIM) - axes[1,1].set_title("Effect Size vs Significance", color=TEXT_MAIN) - fig.tight_layout() - return fig - -def plot_summary_dashboard(y, maf, all_results, G_filt): - """ - IMPROVED SUMMARY DASHBOARD - - Better lambda interpretation - - Variance component display - - Model statistics - """ +def plot_summary_dashboard(y, maf_vals, all_results, G_filt): + """Summary dashboard with key statistics""" fig, axes = plt.subplots(2, 3, figsize=(15, 10), facecolor=BG_WHITE) - style_fig(fig) axes = axes.flatten() - for ax in axes: - ax.set_facecolor(PANEL_WHITE) - - # Phenotype distribution - axes[0].hist(y, bins=15, color=ACCENT_PURP, edgecolor='none', alpha=0.85) - axes[0].axvline(y.mean(), color=ACCENT_CORAL, lw=2, ls='--', - label=f"Mean: {y.mean():.2f}") - axes[0].set_title(f"Phenotype Distribution | n={len(y)}", color=TEXT_MAIN, fontweight='bold') - axes[0].set_xlabel("Phenotype value", color=TEXT_DIM) - axes[0].set_ylabel("Frequency", color=TEXT_DIM) - axes[0].legend(fontsize=7, facecolor=BG_WHITE) - - # MAF distribution - axes[1].hist(maf, bins=20, color=ACCENT_TEAL, edgecolor='none', alpha=0.85) - axes[1].axvline(0.05, color=ACCENT_CORAL, ls='--', lw=2, label="MAF = 0.05") - axes[1].set_title(f"MAF Distribution | rare={np.sum(maf<0.05)}", color=TEXT_MAIN, fontweight='bold') - axes[1].set_xlabel("Minor Allele Frequency", color=TEXT_DIM) - axes[1].set_ylabel("Count", color=TEXT_DIM) - axes[1].legend(fontsize=7) - - # Lambda (genomic inflation) with interpretation + + # 1. Phenotype distribution + axes[0].hist(y, bins=20, color=ACCENT_PURP, alpha=0.7, edgecolor='black') + axes[0].axvline(y.mean(), color=ACCENT_CORAL, lw=2, ls='--', label=f'Mean: {y.mean():.2f}') + axes[0].axvline(np.median(y), color=ACCENT_GOLD, lw=2, ls='--', label=f'Median: {np.median(y):.2f}') + axes[0].set_xlabel('Phenotype Value') + axes[0].set_ylabel('Frequency') + axes[0].set_title(f'Phenotype Distribution (n={len(y)})', fontweight='bold') + axes[0].legend(fontsize=8) + + # 2. MAF distribution + axes[1].hist(maf_vals, bins=20, color=ACCENT_TEAL, alpha=0.7, edgecolor='black') + axes[1].axvline(0.05, color=ACCENT_CORAL, lw=2, ls='--', label='MAF = 0.05') + axes[1].set_xlabel('Minor Allele Frequency') + axes[1].set_ylabel('Count') + axes[1].set_title(f'MAF Distribution (rare: {np.sum(maf_vals < 0.05)})', fontweight='bold') + axes[1].legend(fontsize=8) + + # 3. Lambda values per model 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.05 else ACCENT_GOLD if v <= 1.15 - else ACCENT_CORAL for v in lambdas.values()] - axes[2].bar(lambdas.keys(), lambdas.values(), - color=colors_lam, edgecolor='none', alpha=0.88) - axes[2].axhline(1.0, color=TEXT_DIM, ls='--', lw=1.5, label="λ = 1.0 (ideal)") - axes[2].axhline(1.05, color=ACCENT_TEAL, ls=':', lw=1, alpha=0.7, label="λ ≤ 1.05 (good)") - axes[2].axhline(1.15, color=ACCENT_GOLD, ls=':', lw=1, alpha=0.7, label="λ ≤ 1.15 (acceptable)") - axes[2].set_title("Genomic Inflation λ per Model", color=TEXT_MAIN, fontweight='bold') - axes[2].set_ylabel("λ (lambda)", color=TEXT_DIM) - axes[2].tick_params(axis='x', rotation=35, labelsize=7) - axes[2].legend(fontsize=6, loc='upper left') - axes[2].text(0.98, 0.02, - "λ ≈ 1: well-controlled\nλ > 1: inflation (stratification)\nλ < 1: over-correction", - transform=axes[2].transAxes, fontsize=7, ha='right', va='bottom', - bbox=dict(boxstyle='round,pad=0.4', facecolor='white', - edgecolor=GRID_LINE, alpha=0.9)) - - # Significant SNPs - sig_counts = {} + for mname, (pvals, _, _) in all_results.items(): + chi2_obs = stats.chi2.ppf(1 - np.clip(pvals, 1e-10, 1), df=1) + lambdas[mname] = np.median(chi2_obs) / stats.chi2.ppf(0.5, df=1) + + colors = [ACCENT_TEAL if v <= 1.05 else ACCENT_GOLD if v <= 1.15 else ACCENT_CORAL + for v in lambdas.values()] + axes[2].bar(lambdas.keys(), lambdas.values(), color=colors, alpha=0.7, edgecolor='black') + axes[2].axhline(1.0, color='black', ls='--', lw=1.5, label='λ = 1.0 (ideal)') + axes[2].axhline(1.05, color=ACCENT_TEAL, ls=':', lw=1, label='λ = 1.05 (good)') + axes[2].axhline(1.15, color=ACCENT_GOLD, ls=':', lw=1, label='λ = 1.15 (acceptable)') + axes[2].set_ylabel('Genomic Inflation λ') + axes[2].set_title('Model Performance (λ)', fontweight='bold') + axes[2].tick_params(axis='x', rotation=45, labelsize=8) + axes[2].legend(fontsize=7, loc='upper left') + + # 4. Significant SNPs per model bonf = 0.05 / len(list(all_results.values())[0][0]) - for mname, (p, _, _) in all_results.items(): - sig_counts[mname] = int((p < bonf).sum()) - cols_bar = [MODEL_COLORS.get(m, ACCENT_BLUE) for m in sig_counts] - axes[3].bar(sig_counts.keys(), sig_counts.values(), - color=cols_bar, edgecolor='none', alpha=0.88) - axes[3].set_title("Significant SNPs per Model (Bonferroni)", color=TEXT_MAIN, fontweight='bold') - axes[3].set_ylabel("Count", color=TEXT_DIM) - axes[3].tick_params(axis='x', rotation=35, labelsize=7) - - # Model concordance - n_m = len(all_results) - model_names = list(all_results.keys()) - 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 - - 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, color=TEXT_DIM) - axes[4].set_yticklabels(model_names, fontsize=6, color=TEXT_DIM) - 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 (Spearman ρ)", color=TEXT_MAIN, fontweight='bold') - - # Summary statistics - first_model = model_names[0] - miss_r = np.isnan(G_filt).mean() - axes[5].text(0.5, 0.5, - f"GWAS Summary\n\n" - f"Samples : {G_filt.shape[0]}\n" - f"SNPs : {G_filt.shape[1]}\n" - f"Models : {n_m}\n" - f"Missing : {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=11, - bbox=dict(boxstyle='round,pad=0.6', - facecolor=PANEL_LIGHT, edgecolor=GRID_LINE, alpha=0.8)) - axes[5].set_title("Pipeline Summary", color=TEXT_MAIN, fontweight='bold') + sig_counts = {} + for mname, (pvals, _, _) in all_results.items(): + sig_counts[mname] = np.sum(pvals < bonf) + + colors = [MODEL_COLORS.get(m, ACCENT_BLUE) for m in sig_counts.keys()] + axes[3].bar(sig_counts.keys(), sig_counts.values(), color=colors, alpha=0.7, edgecolor='black') + axes[3].set_ylabel('Number of Significant SNPs') + axes[3].set_title('Significant MTAs (Bonferroni)', fontweight='bold') + axes[3].tick_params(axis='x', rotation=45, labelsize=8) + + # 5. Missing rate + missing_rate = np.isnan(G_filt).mean() * 100 + axes[4].pie([missing_rate, 100 - missing_rate], + labels=[f'Missing\n{missing_rate:.1f}%', f'Genotyped\n{100-missing_rate:.1f}%'], + colors=[ACCENT_CORAL, ACCENT_TEAL], autopct='%1.1f%%', startangle=90) + axes[4].set_title('Genotype Call Rate', fontweight='bold') + + # 6. Summary statistics + first_model = list(all_results.keys())[0] + n_sig_bonf = np.sum(all_results[first_model][0] < bonf) + n_sig_5e8 = np.sum(all_results[first_model][0] < 5e-8) + + # Find best model + best_model = min(lambdas.items(), key=lambda x: abs(x[1] - 1))[0] + + stats_text = f""" + GWAS Summary Statistics + + Samples: {G_filt.shape[0]:,} + SNPs: {G_filt.shape[1]:,} + Models Run: {len(all_results)} + + Best Model: {best_model} + λ (best): {lambdas[best_model]:.3f} + + {first_model} (primary): + λ: {lambdas[first_model]:.3f} + Bonferroni: {n_sig_bonf} + 5e-8 threshold: {n_sig_5e8} + """ + + axes[5].text(0.5, 0.5, stats_text, ha='center', va='center', + transform=axes[5].transAxes, fontsize=9, fontfamily='monospace', + bbox=dict(boxstyle='round', facecolor='lightgray', alpha=0.5)) axes[5].axis('off') + style_fig(fig) + fig.suptitle('GWAS Analysis Dashboard', fontsize=14, fontweight='bold', y=1.02) fig.tight_layout() return fig -# ─────────────────────── 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() - header_fill = PatternFill("solid", start_color="4A90D9", end_color="4A90D9") - sig_fill = PatternFill("solid", start_color="FFF3CD", end_color="FFF3CD") - alt_fill = PatternFill("solid", start_color="F8F9FA", end_color="F8F9FA") - header_font = Font(bold=True, color="FFFFFF", name="Calibri", size=11) - title_font = Font(bold=True, color="2C5F8A", name="Calibri", size=13) - thin_border = Border( - left=Side(style='thin', color='CCCCCC'), - right=Side(style='thin', color='CCCCCC'), - top=Side(style='thin', color='CCCCCC'), - bottom=Side(style='thin', color='CCCCCC')) - - 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"] - for col, h in enumerate(headers_sum, 1): - cell = ws_sum.cell(row=3, column=col, value=h) - cell.font = header_font; cell.fill = header_fill - cell.alignment = Alignment(horizontal='center') - cell.border = thin_border - ws_sum.column_dimensions[get_column_letter(col)].width = 22 - for row_i, (mname, (pvals, betas, ses)) in enumerate(all_results.items(), 4): - lam = (np.median(stats.chi2.ppf(1 - np.clip(pvals, 1e-10, 1), df=1)) - / stats.chi2.ppf(0.5, df=1)) - 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")) - 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') - - # Per-model sheets - for mname, (pvals, betas, ses) in all_results.items(): - ws = wb.create_sheet(title=f"{mname}_AllSNPs") - ws['A1'] = f"GWAS Results — {mname}" - 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') - reject_bonf, _, _, _ = multipletests(pvals, method='bonferroni') - headers = ["SNP","Chr","Position","MAF","Beta","SE", - "T_statistic","P_value","neg_log10P","FDR_BH","Bonferroni_sig"] - for col, h in enumerate(headers, 1): - cell = ws.cell(row=3, column=col, value=h) - cell.font = header_font; cell.fill = header_fill - cell.alignment = Alignment(horizontal='center') - cell.border = thin_border - for i, w in enumerate([25,8,12,10,12,12,12,14,12,14,16], 1): - ws.column_dimensions[get_column_letter(i)].width = w - for row_i, idx in enumerate(np.argsort(pvals), 4): - is_sig = bool(reject_bonf[idx]) or pvals[idx] < 5e-8 - fill = (sig_fill if is_sig - else alt_fill if row_i % 2 == 0 - else PatternFill("solid", start_color="FFFFFF", end_color="FFFFFF")) - maf_v = maf_vals[idx] if idx < len(maf_vals) else np.nan - row_data = [ - str(snp_filt[idx]) if idx < len(snp_filt) else "", - int(chr_filt[idx]) if idx < len(chr_filt) else "", - int(pos_filt[idx]) if idx < len(pos_filt) else "", - round(float(maf_v), 4) if not np.isnan(maf_v) else "", - round(float(betas[idx]), 6), round(float(ses[idx]), 6), - round(float(t_stats[idx]), 4), float(pvals[idx]), - round(float(log_p[idx]), 4), round(float(pvals_fdr[idx]), 6), - "YES" if is_sig else "NO"] - for col, val in enumerate(row_data, 1): - cell = ws.cell(row=row_i, column=col, value=val) - cell.fill = fill; cell.border = thin_border - cell.alignment = Alignment(horizontal='center') - if col == 8 and isinstance(val, float): - cell.number_format = '0.00E+00' - - # Significant MTAs - ws_mta = wb.create_sheet(title="Significant_MTAs") - ws_mta['A1'] = "Significant MTAs — All Models" - ws_mta['A1'].font = title_font - ws_mta.merge_cells('A1:N1') - headers_mta = ["Model","SNP","Chr","Position","MAF","Beta","SE","T_stat", - "P_value","neg_log10P","FDR_BH_p","Bonferroni_sig","GW_sig_5e8","PVE_%"] - for col, h in enumerate(headers_mta, 1): - cell = ws_mta.cell(row=3, column=col, value=h) - cell.font = header_font; cell.fill = header_fill - cell.alignment = Alignment(horizontal='center') - cell.border = thin_border - ws_mta.column_dimensions[get_column_letter(col)].width = 18 - mta_row = 4 - for mname, (pvals, betas, ses) in all_results.items(): - log_p = -np.log10(np.clip(pvals, 1e-300, 1)) - t_stats = np.where(ses > 0, betas / (ses + 1e-10), 0.0) - _, pvals_fdr, _, _ = multipletests(pvals, method='fdr_bh') - reject_bonf, _, _, _ = multipletests(pvals, method='bonferroni') - sig_idx = np.where((pvals < bonf) | (pvals < 5e-8))[0] - sig_idx = sig_idx[np.argsort(pvals[sig_idx])] - pve_dict, _ = compute_pve(y, G_filt, pvals, betas, ses) - for idx in sig_idx: - pve_val = round(pve_dict.get(int(idx), 0.0), 4) - maf_v = maf_vals[idx] if idx < len(maf_vals) else np.nan - row_data = [ - mname, - str(snp_filt[idx]) if idx < len(snp_filt) else "", - int(chr_filt[idx]) if idx < len(chr_filt) else "", - int(pos_filt[idx]) if idx < len(pos_filt) else "", - round(float(maf_v), 4) if not np.isnan(maf_v) else "", - round(float(betas[idx]), 6), round(float(ses[idx]), 6), - round(float(t_stats[idx]), 4), float(pvals[idx]), - round(float(log_p[idx]), 4), round(float(pvals_fdr[idx]), 6), - "YES" if bool(reject_bonf[idx]) else "NO", - "YES" if pvals[idx] < 5e-8 else "NO", pve_val] - fill = (sig_fill if mta_row % 2 == 0 - else PatternFill("solid", start_color="FFFDE7", end_color="FFFDE7")) - for col, val in enumerate(row_data, 1): - cell = ws_mta.cell(row=mta_row, column=col, value=val) - cell.fill = fill; cell.border = thin_border - cell.alignment = Alignment(horizontal='center') - if col == 9 and isinstance(val, float): - cell.number_format = '0.00E+00' - mta_row += 1 - - # QTN Effects - ws_qtn = wb.create_sheet(title="QTN_Effects") - ws_qtn['A1'] = "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_idx = np.argsort(pvals)[:min(20, len(pvals))] - pve_dict, _ = compute_pve(y, G_filt, pvals, betas, ses) - 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 - 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(float(betas[idx]) - 1.96 * float(ses[idx]), 6), - round(float(betas[idx]) + 1.96 * float(ses[idx]), 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 - - # PVE Summary - ws_pve = wb.create_sheet(title="PVE_Summary") - ws_pve['A1'] = "Phenotypic Variance Explained (PVE) — Joint Model" - ws_pve['A1'].font = title_font - ws_pve.merge_cells('A1:I1') - headers_pve = ["Model","SNP","Chr","Position","Beta","P_value", - "Partial_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 = 22 - pve_row = 4 - for mname, (pvals, betas, ses) in all_results.items(): - pve_dict, _ = compute_pve(y, G_filt, pvals, betas, ses) - cumulative = 0.0 - for idx in sorted(pve_dict.keys(), - key=lambda i: pve_dict[i], reverse=True): - pve_val = pve_dict[idx] - cumulative += pve_val - 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), - "GW-significant" if pvals[idx] < 5e-8 - else "Bonferroni-significant"] - 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 - - # SNP QC - ws_qc = wb.create_sheet(title="SNP_QC") - ws_qc['A1'] = "SNP Quality Control Statistics" - ws_qc['A1'].font = title_font - ws_qc.merge_cells('A1:F1') - headers_qc = ["SNP","Chr","Position","MAF","Call_Rate","Category"] - for col, h in enumerate(headers_qc, 1): - cell = ws_qc.cell(row=3, column=col, value=h) - cell.font = header_font; cell.fill = header_fill - cell.alignment = Alignment(horizontal='center') - cell.border = thin_border - ws_qc.column_dimensions[get_column_letter(col)].width = 20 - call_rates = compute_call_rate(G_filt) - for row_i in range(len(snp_filt)): - maf_v = maf_vals[row_i] if row_i < len(maf_vals) else np.nan - cr_v = call_rates[row_i] if row_i < len(call_rates) else np.nan - 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"] - for col, val in enumerate(row_data, 1): - cell = ws_qc.cell(row=row_i+4, column=col, value=val) - cell.fill = fill; cell.border = thin_border - cell.alignment = Alignment(horizontal='center') - - wb.save(output_path) - return output_path - -def save_all_plots_zip(plot_dict, out_dir): - zip_path = os.path.join(out_dir, "gwas_plots.zip") - with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf: - for name, fig in plot_dict.items(): - if fig is not None: - 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}") - return zip_path +# ─────────────────────── MAIN PIPELINE ─────────────────────────────────────── -# ─────────────────────── MAIN PIPELINE ──────────────────────────────────────── def run_gwas(file_obj, text_input, selected_models, maf_threshold): + """Main GWAS analysis pipeline with all 10 models""" try: - df, snp_cols, chroms, positions = parse_data(file_obj, text_input) + G_raw, y, ids, snp_names, chroms, positions = parse_data(file_obj, text_input) except Exception as e: - return [None] * 14 + [f"❌ Data parsing error: {e}"] - - y = df["Phenotype"].values.astype(float) - ids = df["ID"].values - G_raw = df[snp_cols].values.astype(float) - - # Build kinship BEFORE mode imputation - K_raw = build_kinship(G_raw) - - # Mode imputation - G = impute_genotypes_mode(G_raw) - n, m = G.shape - - maf_vals_all = compute_maf(G) - maf_thr = float(maf_threshold) - keep = maf_vals_all >= maf_thr - if keep.sum() < 2: + error_msg = f"❌ Data parsing error: {str(e)}" + print(error_msg) + return [None] * 12 + [error_msg] + + n, m = G_raw.shape + print(f"Data loaded: {n} samples, {m} SNPs") + + # MAF filtering + maf_vals_all = compute_maf(G_raw) + maf_thr = float(maf_threshold) + keep = maf_vals_all >= maf_thr + + if keep.sum() < 10: + print(f"Warning: Only {keep.sum()} SNPs passed MAF filter > {maf_thr}") keep = np.ones(m, dtype=bool) - - G_filt = G[:, keep] - snp_filt = np.array(snp_cols)[keep] - chr_filt = chroms[keep] if len(chroms) == m else np.ones(G_filt.shape[1], dtype=int) - pos_filt = positions[keep] if len(positions) == m else np.arange(G_filt.shape[1]) + + G_filt = G_raw[:, keep] + snp_filt = snp_names[keep] + chroms_filt = chroms[keep] + positions_filt = positions[keep] maf_vals = maf_vals_all[keep] - - # Rebuild kinship on filtered data - K = build_kinship(G_filt) - - # Post-imputation MAF re-filter - 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"] + + print(f"After MAF filtering: {G_filt.shape[1]} SNPs") + + # Impute missing genotypes + G_imputed = impute_genotypes_mode(G_filt) + + # Build kinship matrix + print("Building kinship matrix...") + K = build_kinship(G_imputed) + + # All 10 models + ALL_MODELS_LIST = ["OLS", "PLINK", "GLM", "MLM", "CMLM", "EMMAX", "GEMMA", "BLINK", "FarmCPU", "GAPIT3"] + + model_funcs = { + "OLS": lambda: ols_gwas(y, G_imputed), + "PLINK": lambda: plink_gwas(y, G_imputed), + "GLM": lambda: glm_gwas(y, G_imputed), + "MLM": lambda: mlm_gwas(y, G_imputed, K), + "CMLM": lambda: cmlm_gwas(y, G_imputed, K), + "EMMAX": lambda: emmax_gwas(y, G_imputed, K), + "GEMMA": lambda: gemma_gwas(y, G_imputed, K), + "BLINK": lambda: blink_gwas(y, G_imputed, K), + "FarmCPU": lambda: farmcpu_gwas(y, G_imputed, K), + "GAPIT3": lambda: gapit3_gwas(y, G_imputed, K), + } + + # Select models to run 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), - "FarmCPU": lambda: farmcpu_gwas(y, G_filt, K), - "EMMAX": lambda: emmax_gwas(y, G_filt, K), - "PLINK": lambda: plink_gwas(y, G_filt), - "GAPIT3": lambda: gapit3_gwas(y, G_filt, K), - "GEMMA": lambda: gemma_gwas(y, G_filt, K), - } - - all_results = {} - primary_p = None - primary_b = None - primary_se = None - primary_model = None - errors = [] - - # Get variance components for summary - Vg, Ve, delta, _, _ = reml_variance_components(y, K) - h2 = Vg / (Vg + Ve) - + models_to_run = [m for m in selected_models if m in ALL_MODELS_LIST] + + print(f"Running {len(models_to_run)} models: {models_to_run}") + + # Run selected models + all_results = {} + errors = [] + for mname in models_to_run: - if mname in model_funcs: - try: - p, b, se = model_funcs[mname]() - 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}") - - if primary_p is None: - return [None] * 14 + [ - f"❌ No models succeeded.\nErrors:\n" + "\n".join(errors)] - - bonf = 0.05 / len(primary_p) - - # Build plots + try: + print(f" Running {mname}...") + pvals, betas, ses = model_funcs[mname]() + all_results[mname] = (pvals, betas, ses) + print(f" ✓ {mname} completed") + except Exception as e: + errors.append(f"{mname}: {str(e)}") + print(f" ✗ {mname} failed: {e}") + + if not all_results: + error_msg = f"❌ No models succeeded.\nErrors:\n" + "\n".join(errors) + return [None] * 12 + [error_msg] + + # Select primary model (best lambda, closest to 1) + best_model = None + best_lambda_diff = float('inf') + for mname, (pvals, _, _) in all_results.items(): + chi2_obs = stats.chi2.ppf(1 - np.clip(pvals, 1e-10, 1), df=1) + lambda_gc = np.median(chi2_obs) / stats.chi2.ppf(0.5, df=1) + lambda_diff = abs(lambda_gc - 1) + if lambda_diff < best_lambda_diff: + best_lambda_diff = lambda_diff + best_model = mname + + primary_p, primary_b, primary_se = all_results[best_model] + + # Generate plots + print("Generating plots...") plot_dict = {} + try: - plot_dict["01_Manhattan_Primary"] = plot_manhattan(primary_p, chr_filt, pos_filt, "Manhattan Plot", primary_model) - plot_dict["02_QQ_Primary"] = plot_qq_single(primary_p, "QQ Plot", primary_model, MODEL_COLORS.get(primary_model, 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, chr_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) - plot_dict["12_All_Models_MH_Grid"] = plot_all_models_manhattan_grid(all_results, chr_filt, pos_filt) - for mname, (p, b, se) in all_results.items(): - plot_dict[f"13_{mname}_Manhattan"] = plot_manhattan(p, chr_filt, pos_filt, "Manhattan", mname) - plot_dict[f"14_{mname}_QQ"] = plot_qq_single(p, "QQ Plot", mname, MODEL_COLORS.get(mname, ACCENT_PURP)) - except Exception as ex: - errors.append(f"Plot error: {ex}") - print(f"[WARN] Plotting error: {ex}") - - imgs = {} - for k, fig in plot_dict.items(): - try: - imgs[k] = fig_to_pil(fig) if fig is not None else None - except Exception: - imgs[k] = None - - plt.close('all') - - tmp_dir = tempfile.mkdtemp() - zip_path = save_all_plots_zip(plot_dict, tmp_dir) - excel_path = os.path.join(tmp_dir, "gwas_results_complete.xlsx") + plot_dict["Manhattan_Primary"] = plot_manhattan(primary_p, chroms_filt, positions_filt, + "Manhattan Plot", best_model) + plot_dict["QQ_Primary"] = plot_qq(primary_p, "QQ Plot", best_model) + plot_dict["Circos_Best"] = plot_circos_best_models(all_results, chroms_filt, positions_filt, top_n=4) + plot_dict["LD_Decay"] = plot_ld_decay(G_imputed, positions_filt, chroms_filt) + plot_dict["PCA"] = plot_pca(G_imputed, y, ids) + plot_dict["Kinship"] = plot_kinship_heatmap(K, ids) + plot_dict["Model_Comparison"] = plot_model_comparison(all_results, chroms_filt, positions_filt) + plot_dict["Dashboard"] = plot_summary_dashboard(y, maf_vals, all_results, G_imputed) + + # Individual model plots for top models only + top_models_for_individual = list(all_results.keys())[:4] # First 4 for individual plots + for mname in top_models_for_individual: + pvals, _, _ = all_results[mname] + plot_dict[f"Manhattan_{mname}"] = plot_manhattan(pvals, chroms_filt, positions_filt, + "Manhattan Plot", mname) + plot_dict[f"QQ_{mname}"] = plot_qq(pvals, "QQ Plot", mname, MODEL_COLORS.get(mname)) + + except Exception as e: + errors.append(f"Plot error: {str(e)}") + print(f"Plotting error: {e}") + + # Convert plots to images + images = {} + for name, fig in plot_dict.items(): + if fig is not None: + try: + buf = io.BytesIO() + fig.savefig(buf, format='png', dpi=100, bbox_inches='tight', facecolor=fig.get_facecolor()) + buf.seek(0) + from PIL import Image + images[name] = Image.open(buf) + plt.close(fig) + except Exception as e: + print(f"Failed to convert {name}: {e}") + images[name] = None + + # Prepare output (8 main plots) + img_list = [ + images.get("Manhattan_Primary"), + images.get("QQ_Primary"), + images.get("Circos_Best"), + images.get("LD_Decay"), + images.get("PCA"), + images.get("Kinship"), + images.get("Model_Comparison"), + images.get("Dashboard"), + ] + + # Lambda summary + lambda_summary = [] + for mname, (pvals, _, _) in all_results.items(): + chi2_obs = stats.chi2.ppf(1 - np.clip(pvals, 1e-10, 1), df=1) + lambda_gc = np.median(chi2_obs) / stats.chi2.ppf(0.5, df=1) + sig_bonf = np.sum(pvals < (0.05 / len(pvals))) + sig_5e8 = np.sum(pvals < 5e-8) + lambda_summary.append(f" {mname:10s}: λ={lambda_gc:.3f}, Bonf={sig_bonf:5d}, 5e-8={sig_5e8:4d}") + + # Variance components 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}") - print(f"[WARN] Excel export: {ex}") - excel_path = None - - lambdas_str = "\n ".join([ - f"{mn}: λ={np.median(stats.chi2.ppf(1-np.clip(p,1e-10,1),df=1))/stats.chi2.ppf(0.5,df=1):.4f}" - f" sig(Bonf)={int((p 0 else 0 + vc_text = f" Vg={Vg:.4f}, Ve={Ve:.4f}, h²={h2:.3f}" + except: + vc_text = " Variance components unavailable" + + # Find best model for summary + best_model_name = min(lambda_summary, key=lambda x: float(x.split('λ=')[1].split(',')[0]) if 'λ=' in x else 999) + + summary = f""" +{'='*75} + 🧬 COMPLETE GWAS ANALYSIS SUMMARY - 10 MODELS +{'='*75} + Samples: {n:,} | SNPs (raw): {m:,} | SNPs (filtered): {G_imputed.shape[1]:,} + MAF threshold: ≥{maf_thr:.2f} + Imputation: Mode (most frequent allele) + Kinship: VanRaden (2008) method + {vc_text} +{'─'*75} + MODELS RUN: {', '.join(all_results.keys())} ({len(all_results)} models) + + PER-MODEL RESULTS (λ = genomic inflation, lower is better): +{chr(10).join(lambda_summary)} +{'─'*75} + PRIMARY MODEL: {best_model} (selected by best λ) + Bonferroni threshold: {0.05/len(primary_p):.2e} + Significant MTAs (Bonferroni): {np.sum(primary_p < (0.05/len(primary_p)))} + Significant MTAs (5e-8): {np.sum(primary_p < 5e-8)} +{'─'*75} + 📊 CIRCOS PLOT: Shows top 4 models based on combined score (λ + significance) + 🖼 Plots generated: {len(plot_dict)} +{'='*75} +""" + if errors: - error_section = ("\n ⚠️ Warnings/Errors:\n " - + "\n ".join(errors) + "\n") - - summary = ( - f"{'='*68}\n" - f" 🧬 COMPLETE GWAS ANALYSIS SUMMARY\n" - f"{'='*68}\n" - f" Samples: {n} | SNPs (raw): {m} | SNPs (filtered): {G_filt.shape[1]}\n" - f" MAF threshold : ≥{maf_thr:.2f}\n" - f" Imputation : Mode (most frequent allele)\n" - f" Kinship : VanRaden (2008) method\n" - f" Variance comps : REML (intercept projected)\n" - f" Vg (genetic) : {Vg:.4f}\n" - f" Ve (residual) : {Ve:.4f}\n" - f" h² (heritability): {h2:.4f}\n" - f" GLS : Rotated O(n) per SNP (EMMAX/GEMMA) or full GLS (MLM)\n" - f" PVE : Partial r² from joint model\n" - f" Models run : {', '.join(all_results.keys())}\n" - f"{'─'*68}\n" - f" PER-MODEL RESULTS:\n {lambdas_str}\n" - f"{error_section}" - f"{'─'*68}\n" - f" Primary model ({primary_model}):\n" - f" Bonferroni threshold : {bonf:.2e}\n" - f" Significant MTAs : {int((primary_p 1: inflation, λ < 1: over-correction)\n" - f"{'─'*68}\n" - f" 📥 Excel: gwas_results_complete.xlsx\n" - f" • Summary · Per-model SNPs · Sig. MTAs · QTN · PVE · SNP QC\n" - f" 🖼 Plots: gwas_plots.zip ({len(plot_dict)} PNG files)\n" - f"{'='*68}\n" - ) - - return [ - imgs.get("01_Manhattan_Primary"), - imgs.get("02_QQ_Primary"), - imgs.get("03_QQ_All_Models"), - imgs.get("04_QQ_Overlay"), - imgs.get("05_Circos"), - imgs.get("06_LD_Decay"), - imgs.get("07_PCA"), - imgs.get("08_Kinship"), - imgs.get("09_Effect_Sizes"), - imgs.get("10_All_Models_Manhattan"), - imgs.get("11_Summary_Dashboard"), - imgs.get("12_All_Models_MH_Grid"), - excel_path, - zip_path, - summary, - ] - -# ─────────────────────── CSS ────────────────────────────────────────────────── -PASTEL_CSS = """ -@import url('https://fonts.googleapis.com/css2?family=DM+Sans:wght@300;400;500;600&family=DM+Mono:wght@400;500&display=swap'); -* { box-sizing: border-box; } -body, .gradio-container { - background: #F7F8FC !important; - font-family: 'DM Sans', sans-serif !important; - color: #2D3142 !important; -} -.gradio-container { max-width: 1400px !important; margin: 0 auto !important; } - -.gwas-header { - background: linear-gradient(135deg, #E8F4FD 0%, #EDE9F8 50%, #FDF0F8 100%); - border: 1px solid #D6E8F5; border-radius: 18px; padding: 28px 36px; - margin-bottom: 24px; box-shadow: 0 2px 20px rgba(100,120,200,0.08); -} -.gwas-header h1 { font-size: 26px !important; font-weight: 600 !important; - color: #2C5F8A !important; margin: 0 0 6px 0 !important; } -.gwas-header p { color: #6B7A99 !important; font-size: 14px !important; - margin: 4px 0 !important; } - -.gr-panel, .gr-box, .block, .panel { - background: #FFFFFF !important; border: 1px solid #E8ECF4 !important; - border-radius: 14px !important; box-shadow: 0 1px 8px rgba(60,80,140,0.06) !important; -} - -.label-wrap span { - color: #5A6480 !important; font-size: 12px !important; font-weight: 500 !important; - text-transform: uppercase !important; letter-spacing: 0.5px !important; -} -input[type=text], input[type=number], textarea, select { - background: #FAFBFF !important; color: #2D3142 !important; - border: 1px solid #DDE2F0 !important; border-radius: 10px !important; - font-family: 'DM Mono', monospace !important; font-size: 12px !important; -} - -button.primary { - background: linear-gradient(135deg, #5BA8E5 0%, #7C6FCD 100%) !important; - border: none !important; border-radius: 12px !important; color: #FFFFFF !important; - font-weight: 600 !important; font-size: 15px !important; padding: 14px 28px !important; - box-shadow: 0 4px 16px rgba(91,168,229,0.35) !important; width: 100% !important; - transition: all 0.2s ease !important; -} -button.primary:hover { transform: translateY(-2px) !important; - box-shadow: 0 6px 24px rgba(91,168,229,0.45) !important; } - -.tab-nav { - background: #F0F3FB !important; border-radius: 12px !important; - padding: 4px !important; border: 1px solid #E4E8F5 !important; overflow-x: auto !important; -} -.tab-nav button { - color: #6B7A99 !important; font-size: 12px !important; font-weight: 500 !important; - border-radius: 9px !important; padding: 7px 14px !important; border: none !important; - background: transparent !important; white-space: nowrap !important; -} -.tab-nav button.selected, .tab-nav button:hover { - background: #FFFFFF !important; color: #5BA8E5 !important; - box-shadow: 0 1px 6px rgba(91,168,229,0.2) !important; -} - -.summary-box textarea { - font-family: 'DM Mono', monospace !important; font-size: 12px !important; - background: #F8F9FF !important; color: #2D3142 !important; - border: 1px solid #DDE2F0 !important; line-height: 1.7 !important; -} - -.download-section { - background: linear-gradient(135deg, #EBF5FF 0%, #F0EBFF 100%); - border: 1px solid #D0E4F5 !important; border-radius: 14px !important; - padding: 18px !important; -} - -.section-label { - font-size: 11px !important; font-weight: 600 !important; color: #8892B0 !important; - text-transform: uppercase !important; letter-spacing: 1px !important; - padding: 8px 0 4px 0 !important; border-bottom: 1px solid #E8ECF4 !important; - margin-bottom: 8px !important; -} - -#model-selector .wrap { - display: flex !important; - flex-wrap: wrap !important; - gap: 8px !important; - padding: 10px 4px 6px 4px !important; -} -#model-selector .wrap label { - display: inline-flex !important; - align-items: center !important; - gap: 6px !important; - padding: 6px 14px 6px 10px !important; - border-radius: 999px !important; - border: 2px solid #C8D0E7 !important; - background: #F0F3FB !important; - cursor: pointer !important; - font-size: 13px !important; - font-weight: 500 !important; - color: #4A5568 !important; - text-transform: none !important; - letter-spacing: 0 !important; - transition: all 0.15s ease !important; - user-select: none !important; -} -#model-selector .wrap label:hover { - border-color: #5BA8E5 !important; - background: #E8F4FD !important; - color: #2C5F8A !important; -} -#model-selector .wrap label:has(input:checked) { - background: linear-gradient(135deg, #5BA8E5 0%, #7C6FCD 100%) !important; - border-color: #5BA8E5 !important; - color: #FFFFFF !important; - box-shadow: 0 2px 8px rgba(91,168,229,0.40) !important; -} -#model-selector .wrap input[type=checkbox] { - width: 0 !important; height: 0 !important; - margin: 0 !important; opacity: 0 !important; - position: absolute !important; -} -#model-selector > .label-wrap { display: none !important; } - -.model-quick-btn button { - font-size: 12px !important; font-weight: 600 !important; - padding: 6px 14px !important; border-radius: 8px !important; - border: 1.5px solid #C8D0E7 !important; - background: #FFFFFF !important; color: #5A6480 !important; - transition: all 0.15s ease !important; -} -.model-quick-btn button:hover { - border-color: #5BA8E5 !important; color: #2C5F8A !important; - background: #EBF5FF !important; -} + summary += f"\n ⚠️ Warnings ({len(errors)}):\n " + "\n ".join(errors[:5]) + + # Ensure we have 8 images (pad with None if needed) + while len(img_list) < 8: + img_list.append(None) + + return img_list + [summary] -::-webkit-scrollbar { width: 6px; height: 6px; } -::-webkit-scrollbar-track { background: #F0F3FB; border-radius: 4px; } -::-webkit-scrollbar-thumb { background: #C8D0E7; border-radius: 4px; } -""" +# ─────────────────────── GRADIO INTERFACE ───────────────────────────────────── SAMPLE_DATA = """ID,Phenotype,chr1_134521_SNP1,chr1_134810_SNP2,chr1_178766_SNP3,chr1_210328_SNP4 -chromosome,1,1,1,1 IRRI-1,25.34,0,0,0,2 IRRI-75,23.34,0,0,0,0 IRRI-84,26.67,2,0,2,0 @@ -2101,134 +1457,75 @@ IRRI-34,37,0,0,0,0 IRRI-42,30.67,0,0,0,0 IRRI-50,22,0,0,0,2""" -ALL_MODELS = ["OLS", "MLM", "GLM", "CMLM", "BLINK", "FarmCPU", "EMMAX", "PLINK", "GAPIT3", "GEMMA"] - -MODEL_INFO_HTML = """ -
- OLS / PLINK — no structure correction, fastest  |  - GLM — PCs only  |  - EMMAX / GEMMA — fast REML LMM (recommended)  |  - MLM — exact GLS, slow  |  - FarmCPU / BLINK / GAPIT3 — iterative QTN  |  - CMLM — compressed kinship -
+ALL_MODELS_10 = ["OLS", "PLINK", "GLM", "MLM", "CMLM", "EMMAX", "GEMMA", "BLINK", "FarmCPU", "GAPIT3"] + +CSS = """ +.gradio-container { max-width: 1400px !important; margin: auto !important; } +h1 { text-align: center; color: #2C5F8A; } """ -# ─────────────────────── GRADIO INTERFACE ───────────────────────────────────── -with gr.Blocks(css=PASTEL_CSS, title="🧬 GWAS Pipeline", theme=gr.themes.Base()) as demo: - - gr.HTML(""" -
-

🧬 Complete GWAS Analysis Pipeline

-

10 Statistical Models · All-Model Manhattan & QQ · Circos · LD Decay · PNG Export · Full Excel

-

- REML (intercept-projected) · VanRaden kinship · Mode imputation · - O(n) rotated GLS · Joint-model PVE · Publication-quality plots -

-
+with gr.Blocks(css=CSS, title="🧬 GWAS Pipeline - 10 Models", theme=gr.themes.Soft()) as demo: + gr.Markdown(""" + # 🧬 Complete GWAS Analysis Pipeline - 10 Statistical Models + + **Models Available:** + - **Fast:** OLS, PLINK, GLM + - **Mixed Models:** MLM, EMMAX, GEMMA, CMLM + - **Advanced:** BLINK, FarmCPU, GAPIT3 + + **Features:** + - All 10 models run in parallel + - Circos plot shows **top 4 best-performing models** (based on λ inflation + significance) + - Automatic model selection for primary analysis + - Comprehensive visualization suite """) - - with gr.Row(equal_height=False): - - with gr.Column(scale=1, min_width=340): - - gr.HTML('') - file_in = gr.File(label="Upload CSV / TSV / TXT", - file_types=[".csv", ".tsv", ".txt"]) - text_in = gr.Textbox(label="Or paste CSV data", lines=7, - value=SAMPLE_DATA, - placeholder="Paste your CSV data here…") - - gr.HTML('') - gr.HTML(MODEL_INFO_HTML) - - model_sel = gr.CheckboxGroup( - choices=ALL_MODELS, - value=ALL_MODELS, - label="Models", - elem_id="model-selector", - interactive=True, - ) - - with gr.Row(): - gr.Button("✅ All", size="sm", - elem_classes=["model-quick-btn"]).click( - fn=lambda: ALL_MODELS, outputs=model_sel) - gr.Button("☐ None", size="sm", - elem_classes=["model-quick-btn"]).click( - fn=lambda: [], outputs=model_sel) - gr.Button("⚡ Fast", size="sm", - elem_classes=["model-quick-btn"]).click( - fn=lambda: ["OLS", "GLM", "EMMAX", "PLINK", "GEMMA"], - outputs=model_sel) - gr.Button("🔬 LMM", size="sm", - elem_classes=["model-quick-btn"]).click( - fn=lambda: ["MLM", "EMMAX", "GEMMA", "CMLM"], - outputs=model_sel) - - gr.HTML('') - maf_thr = gr.Slider(0, 0.5, value=0.05, step=0.01, - label="MAF Threshold") - - run_btn = gr.Button("🚀 Run GWAS Pipeline", variant="primary") - - gr.HTML('') - with gr.Column(elem_classes=["download-section"]): - excel_out = gr.File( - label="📊 Excel — MTA · PVE · QTN · All Models", - interactive=False) - zip_out = gr.File( - label="🖼 All Plots PNG (ZIP)", - interactive=False) - + + with gr.Row(): + with gr.Column(scale=1): + file_input = gr.File(label="Upload CSV/TSV file", file_types=[".csv", ".tsv", ".txt"]) + text_input = gr.Textbox(label="Or paste data", lines=8, value=SAMPLE_DATA) + + model_selector = gr.CheckboxGroup(choices=ALL_MODELS_10, value=ALL_MODELS_10, + label="Select Models to Run (10 available)") + + maf_threshold = gr.Slider(0, 0.5, value=0.05, step=0.01, label="MAF Threshold") + + run_button = gr.Button("🚀 Run GWAS Analysis (10 Models)", variant="primary", size="lg") + + gr.Markdown(""" + ***Note:** * + - **GEMMA/EMMAX** are recommended for most datasets + - Circos plot automatically selects **top 4 models** based on performance + - MLM/FarmCPU/BLINK may be slower for large datasets + """) + with gr.Column(scale=2): - gr.HTML('') - summary_out = gr.Textbox(label="", lines=30, - elem_classes=["summary-box"], - show_label=False) - - gr.HTML('') + summary_output = gr.Textbox(label="Analysis Summary", lines=25, interactive=False) + + gr.Markdown("### 📊 Visualization Results") + with gr.Tabs(): - with gr.Tab("🗺 Manhattan (Primary)"): - img1 = gr.Image(type="pil", label="Manhattan — Primary Model") - with gr.Tab("📈 QQ (Primary)"): - img2 = gr.Image(type="pil", label="QQ Plot — Primary Model") - with gr.Tab("📈 QQ (All Models)"): - img3 = gr.Image(type="pil", label="QQ Plots — All Models") - with gr.Tab("📊 QQ Overlay"): - img4 = gr.Image(type="pil", label="QQ Overlay — All Models with λ") - with gr.Tab("🔵 Circos"): - img5 = gr.Image(type="pil", label="Circos — Multi-Model Comparison") - with gr.Tab("🔗 LD Decay"): - img6 = gr.Image(type="pil", label="LD Decay") - with gr.Tab("🔬 PCA"): - img7 = gr.Image(type="pil", label="PCA") - with gr.Tab("👨‍👩‍👧 Kinship"): - img8 = gr.Image(type="pil", label="Kinship Matrix (VanRaden)") - with gr.Tab("⚖ Effect Sizes"): - img9 = gr.Image(type="pil", label="Effect Sizes & Volcano Plot") - with gr.Tab("🔄 All Models (Stacked)"): - img10 = gr.Image(type="pil", label="Manhattan — All Models Stacked") - with gr.Tab("📊 Dashboard"): - img11 = gr.Image(type="pil", label="Summary Dashboard") - with gr.Tab("🗂 All Models (Grid)"): - img12 = gr.Image(type="pil", label="Manhattan Grid") - - def run_wrapper(file_obj, text_data, selected_models, maf): - if not selected_models: - selected_models = ALL_MODELS - out = run_gwas(file_obj, text_data, selected_models, maf) - while len(out) < 15: - out.append(None) - return out - - run_btn.click( - fn=run_wrapper, - inputs=[file_in, text_in, model_sel, maf_thr], - outputs=[img1, img2, img3, img4, img5, img6, - img7, img8, img9, img10, img11, img12, - excel_out, zip_out, summary_out], + with gr.Tab("Manhattan (Primary)"): + img1 = gr.Image(type="pil", label="Manhattan Plot - Best Model") + with gr.Tab("QQ Plot (Primary)"): + img2 = gr.Image(type="pil", label="QQ Plot - Best Model") + with gr.Tab("Circos (Top 4 Models)"): + img3 = gr.Image(type="pil", label="Circos Plot - Best Performing Models") + with gr.Tab("LD Decay"): + img4 = gr.Image(type="pil", label="LD Decay") + with gr.Tab("PCA"): + img5 = gr.Image(type="pil", label="PCA") + with gr.Tab("Kinship"): + img6 = gr.Image(type="pil", label="Kinship Matrix") + with gr.Tab("All Models Comparison"): + img7 = gr.Image(type="pil", label="Manhattan - All 10 Models") + with gr.Tab("Dashboard"): + img8 = gr.Image(type="pil", label="Summary Dashboard") + + run_button.click( + fn=run_gwas, + inputs=[file_input, text_input, model_selector, maf_threshold], + outputs=[img1, img2, img3, img4, img5, img6, img7, img8, summary_output] ) if __name__ == "__main__":