diff --git "a/app.py" "b/app.py" --- "a/app.py" +++ "b/app.py" @@ -1,14 +1,13 @@ # -*- coding: utf-8 -*- """ -GWAS Nexus - Advanced Multi-Model GWAS Analysis Platform +GWAS Pipeline v8.0 - Complete Multi-Model GWAS Platform Features: -- 6+ GWAS models (LR, MLM, LASSO, ElasticNet, Random Forest, Gradient Boosting, Ridge) -- LOD score Manhattan plots -- LD Decay plot in Mb -- Circos-style circular Manhattan plot -- QQ plots, Effect size plots, PCA -- Comprehensive LD analysis (r², D') -- Model comparison & consensus +- 6 GWAS models (Linear, Mixed, ElasticNet, Lasso, Ridge, Random Forest) +- Manhattan plot with LOD scores +- LD decay plot in Mb +- Circos plot for chromosome visualization +- Comprehensive QC and imputation +- Attractive modern UI with custom CSS """ import gradio as gr @@ -17,1389 +16,1264 @@ import numpy as np import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt +from matplotlib.patches import Circle, Rectangle, Arc import matplotlib.patches as mpatches -from matplotlib.patches import FancyArrowPatch, Arc -import matplotlib.gridspec as gridspec from matplotlib.collections import LineCollection -from matplotlib.colors import LinearSegmentedColormap import seaborn as sns from scipy import stats +from scipy.spatial.distance import pdist, squareform from scipy.optimize import curve_fit -import os, warnings, tempfile, zipfile, traceback -from sklearn.linear_model import ElasticNetCV, LassoCV, RidgeCV +import os, warnings, tempfile, zipfile, io +from sklearn.linear_model import ElasticNetCV, LassoCV, RidgeCV, LinearRegression from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor from sklearn.preprocessing import StandardScaler from sklearn.model_selection import cross_val_score, KFold -from sklearn.metrics import r2_score +from sklearn.metrics import mean_squared_error, r2_score +from sklearn.impute import SimpleImputer import statsmodels.api as sm from statsmodels.formula.api import mixedlm +import warnings warnings.filterwarnings('ignore') -# ═══════════════════════════════════════════════ -# DESIGN SYSTEM — BIOLUMINESCENT DARK THEME -# ═══════════════════════════════════════════════ -BG = "#07090F" -PANEL = "#0D1117" -CARD = "#111827" -BORDER = "#1F2937" -TEXT = "#E2E8F0" -MUTED = "#64748B" -CYAN = "#06B6D4" -VIOLET = "#8B5CF6" -EMERALD = "#10B981" -ROSE = "#F43F5E" -AMBER = "#F59E0B" -INDIGO = "#6366F1" -PINK = "#EC4899" -TEAL = "#14B8A6" -LIME = "#84CC16" -ORANGE = "#F97316" +# ══════════════════════════════════════════════════════════════ +# CUSTOM CSS FOR MODERN UI +# ══════════════════════════════════════════════════════════════ + +CUSTOM_CSS = """ + +""" -CHROM_PALETTE = [ - "#06B6D4","#8B5CF6","#10B981","#F43F5E","#F59E0B", - "#6366F1","#EC4899","#14B8A6","#84CC16","#F97316", - "#0EA5E9","#A855F7","#22C55E","#EF4444","#EAB308", - "#4F46E5","#DB2777","#0D9488","#65A30D","#EA580C", - "#7DD3FC","#C4B5FD","#86EFAC","#FCA5A5","#FDE68A", +# ══════════════════════════════════════════════════════════════ +# ENHANCED PLOT THEME +# ══════════════════════════════════════════════════════════════ + +BG_COLOR = "#FDFBFF" +PANEL_COLOR = "#F6F0FB" +GRID_COLOR = "#E8DFF5" +TEXT_COLOR = "#3D2B6B" +ACCENT_COLOR = "#8B5CF6" +RED_COLOR = "#F472B6" +GOLD_COLOR = "#FBBF24" +GREEN_COLOR = "#34D399" +TEAL_COLOR = "#22D3EE" +ORANGE_COLOR = "#F97316" +PURPLE_COLOR = "#A855F7" +BLUE_COLOR = "#3B82F6" +PINK_COLOR = "#EC4899" +INDIGO_COLOR = "#6366F1" + +CHROMOSOME_COLORS = [ + "#FF6B6B", "#4ECDC4", "#45B7D1", "#96CEB4", "#FFEAA7", + "#DDA0DD", "#98D8C8", "#F7DC6F", "#BB8FCE", "#85C1E2", + "#F8C471", "#A9DFBF", "#F5B7B1", "#AED6F1", "#F9E79F", + "#D7BDE2", "#ABEBC6", "#FAD7A0", "#AED6F1", "#F1948A", + "#82E0AA", "#F5CBA7", "#C39BD3", "#76D7C4", "#F0B27A" ] -def apply_dark_theme(): +def set_plot_style(): + """Set consistent plot styling""" plt.rcParams.update({ - 'figure.facecolor': BG, - 'axes.facecolor': PANEL, - 'axes.edgecolor': BORDER, - 'axes.labelcolor': TEXT, - 'axes.titlecolor': TEXT, - 'xtick.color': MUTED, - 'ytick.color': MUTED, - 'text.color': TEXT, - 'grid.color': BORDER, - 'grid.linewidth': 0.6, + 'figure.facecolor': BG_COLOR, + 'axes.facecolor': PANEL_COLOR, + 'axes.edgecolor': GRID_COLOR, + 'axes.labelcolor': TEXT_COLOR, + 'axes.titlecolor': TEXT_COLOR, + 'xtick.color': TEXT_COLOR, + 'ytick.color': TEXT_COLOR, + 'text.color': TEXT_COLOR, + 'grid.color': GRID_COLOR, + 'grid.linewidth': 0.8, + 'grid.alpha': 0.5, 'figure.dpi': 150, - 'font.family': 'DejaVu Sans', + 'font.family': 'sans-serif', 'axes.spines.top': False, 'axes.spines.right': False, - 'axes.spines.left': True, - 'axes.spines.bottom': True, - 'legend.framealpha': 0.15, - 'legend.facecolor': CARD, - 'legend.edgecolor': BORDER, - 'axes.titlesize': 13, - 'axes.labelsize': 11, + 'legend.framealpha': 0.95, + 'legend.edgecolor': GRID_COLOR, + 'legend.fancybox': True, + 'legend.shadow': True, }) -# ═══════════════════════════════════════════════ -# PLOT 1: MANHATTAN + LOD DUAL PANEL -# ═══════════════════════════════════════════════ - -def plot_manhattan_lod(marker_names, chromosomes, p_values, lod_scores, - sig_set, bonf_thresh, save_path): - apply_dark_theme() - unique_chroms = sorted(set(chromosomes), - key=lambda x: (int(x) if str(x).isdigit() else 999, str(x))) +# ══════════════════════════════════════════════════════════════ +# PLOT FUNCTIONS +# ══════════════════════════════════════════════════════════════ + +def plot_manhattan_lod(marker_names, chromosomes, p_values, lod_scores, + sig_threshold, save_path): + """Create Manhattan plot with LOD scores overlay""" + set_plot_style() + + # Prepare data + unique_chroms = sorted(set(chromosomes), + key=lambda x: (int(x) if str(x).isdigit() else 999, str(x))) log_p = -np.log10(np.array(p_values) + 1e-300) - lod_arr = np.array(lod_scores) - - GAP = max(10, len(marker_names) // 120) + + # Calculate positions + GAP = max(10, len(marker_names) // 100) x_pos = np.zeros(len(marker_names)) - chrom_to_idx, chrom_centers = {}, {} + chrom_to_idx = {} + for i, c in enumerate(chromosomes): chrom_to_idx.setdefault(c, []).append(i) - + offset = 0 + chrom_positions = {} for ch in unique_chroms: idxs = chrom_to_idx.get(ch, []) - if not idxs: continue + if not idxs: + continue for r, idx in enumerate(idxs): x_pos[idx] = offset + r - chrom_centers[ch] = offset + (len(idxs) - 1) / 2 + chrom_positions[ch] = (offset, offset + len(idxs)) offset += len(idxs) + GAP - - fig = plt.figure(figsize=(24, 12), facecolor=BG) - gs = gridspec.GridSpec(3, 1, figure=fig, hspace=0.05, - height_ratios=[2.5, 0.8, 1.2]) - ax1 = fig.add_subplot(gs[0]) - ax_sep = fig.add_subplot(gs[1]) - ax2 = fig.add_subplot(gs[2]) - ax_sep.set_visible(False) - - for ax in [ax1, ax2]: - ax.set_facecolor(PANEL) - for ci, ch in enumerate(unique_chroms): - idxs = chrom_to_idx.get(ch, []) - if not idxs: continue - x0, x1 = x_pos[idxs[0]] - 0.5, x_pos[idxs[-1]] + 0.5 - if ci % 2 == 0: - ax.axvspan(x0, x1, color='#1A2035', alpha=0.7, zorder=0) - - # Manhattan scatter - for ci, ch in enumerate(unique_chroms): + + # Create figure + fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(20, 12), + gridspec_kw={'height_ratios': [2.5, 1]}, + facecolor=BG_COLOR) + + # Top plot: Manhattan + for i, ch in enumerate(unique_chroms): + idxs = chrom_to_idx.get(ch, []) + if not idxs: + continue + x0 = x_pos[idxs[0]] - 0.5 + x1 = x_pos[idxs[-1]] + 0.5 + if i % 2 == 0: + ax1.axvspan(x0, x1, color='#EDE9FE', alpha=0.3, zorder=0) + + # Plot points + significant_idx = np.where(p_values < sig_threshold)[0] + + for i, ch in enumerate(unique_chroms): idxs = chrom_to_idx.get(ch, []) - if not idxs: continue - col = CHROM_PALETTE[ci % len(CHROM_PALETTE)] - normal = [i for i in idxs if i not in sig_set] - sel = [i for i in idxs if i in sig_set] + if not idxs: + continue + color = CHROMOSOME_COLORS[i % len(CHROMOSOME_COLORS)] + + # Non-significant + normal = [idx for idx in idxs if idx not in significant_idx] if normal: - ax1.scatter(x_pos[normal], log_p[normal], c=col, s=14, - alpha=0.6, linewidths=0, zorder=2, rasterized=True) - if sel: - ax1.scatter(x_pos[sel], log_p[sel], c=ROSE, s=350, - alpha=0.12, linewidths=0, zorder=3) - ax1.scatter(x_pos[sel], log_p[sel], c=ROSE, s=80, - alpha=1.0, edgecolors='white', linewidths=0.8, - marker='*', zorder=4) - + ax1.scatter(x_pos[normal], log_p[normal], c=color, s=15, + alpha=0.6, linewidths=0, zorder=2) + + # Significant + sig = [idx for idx in idxs if idx in significant_idx] + if sig: + ax1.scatter(x_pos[sig], log_p[sig], c=RED_COLOR, s=100, + alpha=0.8, edgecolors='white', linewidths=1.5, + marker='D', zorder=3) + # Threshold lines - ax1.axhline(bonf_thresh, color=ROSE, ls='--', lw=1.8, alpha=0.9, - label=f'Bonferroni (α=0.05)') - ax1.axhline(5, color=AMBER, ls=':', lw=1.4, alpha=0.8, label='−log₁₀P = 5') - ax1.axhline(3, color=EMERALD, ls=':', lw=1.2, alpha=0.6, label='−log₁₀P = 3') - + bonf_line = -np.log10(sig_threshold) + ax1.axhline(bonf_line, color=RED_COLOR, linestyle='--', + linewidth=2, alpha=0.8, label=f'Bonferroni (α={sig_threshold:.2e})') + ax1.axhline(3, color=GOLD_COLOR, linestyle=':', linewidth=2, + alpha=0.8, label='LOD ≥ 3') + + # Add LOD as secondary axis + ax1_twin = ax1.twinx() + lod_array = np.array(lod_scores) + ax1_twin.scatter(x_pos, lod_array, c=TEAL_COLOR, s=10, alpha=0.4, + marker='x', label='LOD Score', zorder=1) + ax1_twin.set_ylabel('LOD Score', fontsize=12, color=TEAL_COLOR, fontweight='bold') + ax1_twin.tick_params(axis='y', colors=TEAL_COLOR) + max_lod = lod_array.max() if len(lod_array) > 0 else 5 + ax1_twin.set_ylim(0, max_lod * 1.15) + ax1.set_xlim(-GAP, offset) - ax1.set_ylim(0, log_p.max() * 1.18) - ax1.set_ylabel('−log₁₀(P-value)', fontsize=13, color=TEXT, fontweight='bold', labelpad=12) - ax1.set_title('GWAS Manhattan Plot · LOD Profile', fontsize=16, - color=CYAN, fontweight='bold', pad=20, loc='left') - ax1.set_xticks([]) - ax1.yaxis.grid(True, color=BORDER, lw=0.6, alpha=0.9) - ax1.legend(loc='upper right', fontsize=9, facecolor=CARD, - edgecolor=BORDER, framealpha=0.9) - - # LOD profile - ax2.plot(x_pos, lod_arr, color=CYAN, lw=1.2, alpha=0.8) - ax2.fill_between(x_pos, 0, lod_arr, color=CYAN, alpha=0.15) - ax2.axhline(3, color=AMBER, ls='--', lw=1.5, alpha=0.9, label='LOD = 3') - lod_sig = lod_arr >= 3 - if lod_sig.any(): - ax2.scatter(x_pos[lod_sig], lod_arr[lod_sig], c=AMBER, s=18, - alpha=0.9, zorder=3, label=f'{lod_sig.sum()} LOD≥3') - + ax1.set_ylim(bottom=0, top=log_p.max() * 1.15) + ax1.set_ylabel('-log₁₀(P-value)', fontsize=14, color=TEXT_COLOR, fontweight='bold') + ax1.set_xlabel('Chromosome', fontsize=14, color=TEXT_COLOR, fontweight='bold') + ax1.set_title('GWAS Manhattan Plot with LOD Scores', fontsize=18, + color=TEXT_COLOR, fontweight='bold', pad=20) + ax1.grid(True, alpha=0.3) + ax1.legend(loc='upper right', fontsize=10) + + # Set x-ticks at chromosome centers + tick_positions = [] + tick_labels = [] + for ch in unique_chroms: + start, end = chrom_positions[ch] + center = (start + end) / 2 + tick_positions.append(center) + tick_labels.append(str(ch)) + ax1.set_xticks(tick_positions) + ax1.set_xticklabels(tick_labels, rotation=45, ha='right', fontsize=9) + + # Bottom plot: LOD profile + for i, ch in enumerate(unique_chroms): + idxs = chrom_to_idx.get(ch, []) + if not idxs: + continue + x0 = x_pos[idxs[0]] - 0.5 + x1 = x_pos[idxs[-1]] + 0.5 + if i % 2 == 0: + ax2.axvspan(x0, x1, color='#EDE9FE', alpha=0.3, zorder=0) + + ax2.plot(x_pos, lod_array, color=TEAL_COLOR, linewidth=2, alpha=0.8) + ax2.fill_between(x_pos, 0, lod_array, color=TEAL_COLOR, alpha=0.2) + ax2.axhline(3, color=GOLD_COLOR, linestyle='--', linewidth=1.5, alpha=0.8) ax2.set_xlim(-GAP, offset) - ax2.set_ylim(0, lod_arr.max() * 1.15 if lod_arr.max() > 0 else 5) - ax2.set_ylabel('LOD Score', fontsize=12, color=CYAN, fontweight='bold') - ax2.set_xlabel('Chromosome', fontsize=12, color=TEXT, fontweight='bold') - ax2.yaxis.grid(True, color=BORDER, lw=0.6) - ax2.legend(fontsize=9, facecolor=CARD, edgecolor=BORDER) - - xticks = [chrom_centers[ch] for ch in unique_chroms if ch in chrom_centers] - ax2.set_xticks(xticks) - ax2.set_xticklabels([str(ch) for ch in unique_chroms if ch in chrom_centers], - fontsize=8, color=MUTED) - - # Color-coded chrom label strip - for ci, ch in enumerate(unique_chroms): - if ch not in chrom_centers: continue - col = CHROM_PALETTE[ci % len(CHROM_PALETTE)] - ax2.axvline(chrom_centers[ch], color=col, lw=0.4, alpha=0.3, zorder=0) - - plt.savefig(save_path, dpi=180, bbox_inches='tight', facecolor=BG) - plt.close(fig) - -# ═══════════════════════════════════════════════ -# PLOT 2: QQ PLOT -# ═══════════════════════════════════════════════ - -def plot_qq(p_values_dict, save_path): - apply_dark_theme() - fig, ax = plt.subplots(figsize=(8, 8), facecolor=BG) - ax.set_facecolor(PANEL) - - colors_map = { - 'Linear': CYAN, 'MLM': VIOLET, 'LASSO': EMERALD, - 'ElasticNet': AMBER, 'RidgeCV': INDIGO, - 'RandomForest': ROSE, 'GradBoost': ORANGE - } - - for name, pvals in p_values_dict.items(): - pvals = np.array(pvals) - pvals = pvals[~np.isnan(pvals) & (pvals > 0)] - n = len(pvals) - expected = -np.log10(np.arange(1, n + 1) / (n + 1)) - observed = -np.log10(np.sort(pvals)) - col = colors_map.get(name, CYAN) - ax.scatter(expected, observed, s=10, alpha=0.7, color=col, - label=name, linewidths=0, rasterized=True) - - maxval = max(6, max(-np.log10(min(p) + 1e-300) for p in p_values_dict.values() if len(p) > 0)) - ax.plot([0, maxval], [0, maxval], '--', color=MUTED, lw=1.5, label='Expected') - - # Confidence band - ns = [len(p) for p in p_values_dict.values() if len(p) > 0] - if ns: - n_avg = int(np.mean(ns)) - exp_qs = np.arange(1, n_avg + 1) / (n_avg + 1) - upper = -np.log10(stats.beta.ppf(0.975, np.arange(1, n_avg + 1), - n_avg - np.arange(1, n_avg + 1) + 1)) - lower = -np.log10(stats.beta.ppf(0.025, np.arange(1, n_avg + 1), - n_avg - np.arange(1, n_avg + 1) + 1)) - exp_sorted = -np.log10(exp_qs) - ax.fill_between(exp_sorted[::-1], lower[::-1], upper[::-1], - color=MUTED, alpha=0.15, label='95% CI') - - ax.set_xlim(0, maxval * 0.9) - ax.set_ylim(0, maxval * 1.05) - ax.set_xlabel('Expected −log₁₀(P)', fontsize=12, fontweight='bold') - ax.set_ylabel('Observed −log₁₀(P)', fontsize=12, fontweight='bold') - ax.set_title('QQ Plot — All Models', fontsize=14, color=CYAN, fontweight='bold') - ax.legend(fontsize=9, facecolor=CARD, edgecolor=BORDER, ncol=2) - ax.grid(True, color=BORDER, lw=0.6) - plt.tight_layout() - plt.savefig(save_path, dpi=180, bbox_inches='tight', facecolor=BG) + ax2.set_ylabel('LOD Score', fontsize=12, color=TEXT_COLOR, fontweight='bold') + ax2.set_xlabel('Chromosome', fontsize=12, color=TEXT_COLOR, fontweight='bold') + ax2.set_ylim(0, max_lod * 1.15) + ax2.grid(True, alpha=0.3) + ax2.set_xticks(tick_positions) + ax2.set_xticklabels(tick_labels, rotation=45, ha='right', fontsize=9) + + plt.tight_layout(pad=2) + plt.savefig(save_path, dpi=200, bbox_inches='tight', facecolor=BG_COLOR) plt.close(fig) -# ═══════════════════════════════════════════════ -# PLOT 3: LD DECAY (in Mb) -# ═══════════════════════════════════════════════ - -def plot_ld_decay_mb(genotypes, chromosomes, positions, save_path, max_m=300): - apply_dark_theme() +def plot_ld_decay_mb(genotypes, chromosomes, positions, save_path, max_distance_mb=5): + """Create LD decay plot with distances in Megabases""" + set_plot_style() + unique_chroms = sorted(set(chromosomes), - key=lambda x: (int(x) if str(x).isdigit() else 999, str(x))) - - all_distances_mb, all_r2, all_dprime = [], [], [] - chrom_half_decay = {} - + key=lambda x: (int(x) if str(x).isdigit() else 999, str(x))) + + all_distances_mb = [] + all_r2 = [] + for ch in unique_chroms: idxs = [i for i, c in enumerate(chromosomes) if c == ch] - if len(idxs) < 4: continue - if len(idxs) > max_m: - idxs = sorted(np.random.choice(idxs, max_m, replace=False)) - + if len(idxs) < 4: + continue + + # Limit markers for performance + if len(idxs) > 300: + idxs = sorted(np.random.choice(idxs, 300, replace=False)) + G = genotypes[:, idxs].copy() - pos_ch = np.array([positions[i] for i in idxs], dtype=float) - # Convert to Mb if positions look like bp - if pos_ch.max() > 1e6: - pos_ch = pos_ch / 1e6 - - ch_dists, ch_r2 = [], [] + pos_ch = [positions[i] for i in idxs] + + # Convert positions to Mb if they're in bp + pos_mb = [p / 1_000_000 if p > 1000 else p for p in pos_ch] + + # Calculate pairwise LD for i in range(len(idxs)): - for j in range(i+1, min(i+80, len(idxs))): - dist_mb = abs(pos_ch[j] - pos_ch[i]) + for j in range(i+1, min(i+100, len(idxs))): + dist = abs(pos_mb[j] - pos_mb[i]) + if dist > max_distance_mb: + continue + + # Calculate r² r = np.corrcoef(G[:, i], G[:, j])[0, 1] r2 = r**2 if not np.isnan(r) else 0 - - freq1 = np.mean(G[:, i]) / 2.0 - freq2 = np.mean(G[:, j]) / 2.0 - p11 = np.mean((G[:, i] >= 1) & (G[:, j] >= 1)) - D = p11 - freq1 * freq2 - Dm = min(freq1*(1-freq2), (1-freq1)*freq2) if D < 0 else min(freq1*freq2, (1-freq1)*(1-freq2)) - dprime = abs(D / Dm) if Dm > 1e-8 else 0 - - all_distances_mb.append(dist_mb) + + all_distances_mb.append(dist) all_r2.append(r2) - all_dprime.append(dprime) - ch_dists.append(dist_mb) - ch_r2.append(r2) - - if ch_dists: - d_arr = np.array(ch_dists) - r_arr = np.array(ch_r2) - bins_mb = np.linspace(0, np.percentile(d_arr, 95) + 0.01, 30) - bm, br = [], [] - for bi in range(len(bins_mb)-1): - mask = (d_arr >= bins_mb[bi]) & (d_arr < bins_mb[bi+1]) - if mask.sum() >= 2: - bm.append((bins_mb[bi]+bins_mb[bi+1])/2) - br.append(np.mean(r_arr[mask])) - if len(bm) >= 3: - bm, br = np.array(bm), np.array(br) - hdidx = np.where(br <= max(br)*0.5)[0] - if len(hdidx) > 0: - chrom_half_decay[ch] = bm[hdidx[0]] - - fig, axes = plt.subplots(1, 3, figsize=(20, 6), facecolor=BG) - - distances = np.array(all_distances_mb) - r2_vals = np.array(all_r2) - dprime_vals = np.array(all_dprime) - - if len(distances) > 0: - max_dist = min(5.0, float(np.percentile(distances, 97))) - bins_mb = np.linspace(0, max_dist + 0.001, 50) - bcenters, bmeans_r2, bstds_r2, bmeans_dp, bstds_dp = [], [], [], [], [] - - for bi in range(len(bins_mb)-1): - mask = (distances >= bins_mb[bi]) & (distances < bins_mb[bi+1]) - if mask.sum() >= 2: - bcenters.append((bins_mb[bi]+bins_mb[bi+1])/2) - bmeans_r2.append(np.mean(r2_vals[mask])) - bstds_r2.append(np.std(r2_vals[mask]) / np.sqrt(mask.sum())) - bmeans_dp.append(np.mean(dprime_vals[mask])) - bstds_dp.append(np.std(dprime_vals[mask]) / np.sqrt(mask.sum())) - - bcenters = np.array(bcenters) - bmeans_r2 = np.array(bmeans_r2) - bmeans_dp = np.array(bmeans_dp) - - # Plot 1: r² decay - ax = axes[0] - ax.set_facecolor(PANEL) - - # Scatter (downsampled) - if len(distances) > 5000: - idx_s = np.random.choice(len(distances), 5000, replace=False) - ax.scatter(distances[idx_s], r2_vals[idx_s], c=CYAN, s=4, - alpha=0.15, linewidths=0, rasterized=True) - else: - ax.scatter(distances, r2_vals, c=CYAN, s=4, alpha=0.2, linewidths=0) - - ax.errorbar(bcenters, bmeans_r2, yerr=bstds_r2, fmt='o-', - color=CYAN, capsize=3, capthick=1.2, markersize=5, - lw=2, alpha=0.9, zorder=5, label='Mean r²') - - # Fit exponential decay + + # Create figure + fig, ax = plt.subplots(figsize=(12, 8), facecolor=BG_COLOR) + ax.set_facecolor(PANEL_COLOR) + + if all_distances_mb: + distances = np.array(all_distances_mb) + r2_values = np.array(all_r2) + + # Bin by distance + bins = np.linspace(0, max_distance_mb, 50) + bin_centers = [] + bin_means = [] + bin_stds = [] + + for i in range(len(bins)-1): + mask = (distances >= bins[i]) & (distances < bins[i+1]) + if mask.sum() > 5: + bin_centers.append((bins[i] + bins[i+1]) / 2) + bin_means.append(np.mean(r2_values[mask])) + bin_stds.append(np.std(r2_values[mask]) / np.sqrt(mask.sum())) + + # Exponential decay fit + def decay_func(x, a, b): + return a * np.exp(-b * x) + try: - def decay_exp(x, a, b, c): - return a * np.exp(-b * x) + c - popt, _ = curve_fit(decay_exp, bcenters, bmeans_r2, - p0=[0.5, 1.0, 0.05], maxfev=10000) - xf = np.linspace(0, max_dist, 300) - yf = decay_exp(xf, *popt) - ax.plot(xf, yf, '--', color=ROSE, lw=2, alpha=0.9, label='Exp. fit') + params, _ = curve_fit(decay_func, bin_centers, bin_means, + p0=[1, 1], maxfev=5000) + x_fit = np.linspace(0, max_distance_mb, 100) + y_fit = decay_func(x_fit, *params) + ax.plot(x_fit, y_fit, '--', color=RED_COLOR, linewidth=2.5, + label=f'Decay rate: {params[1]:.3f} Mb⁻¹') + + # Half-decay distance + half_decay = np.log(2) / params[1] if params[1] > 0 else 0 + if half_decay <= max_distance_mb: + ax.axvline(half_decay, color=GOLD_COLOR, linestyle='--', + linewidth=2, alpha=0.8, + label=f'LD half-decay: {half_decay:.2f} Mb') except: pass - - ax.axhline(0.2, color=AMBER, ls='--', lw=1.3, alpha=0.8, label='r² = 0.2') - ax.set_xlabel('Distance (Mb)', fontsize=11, fontweight='bold') - ax.set_ylabel('r²', fontsize=11, fontweight='bold') - ax.set_title('LD Decay — r²', fontsize=13, color=CYAN, fontweight='bold') - ax.set_ylim(0, 1.05) - ax.set_xlim(0, max_dist) - ax.legend(fontsize=9, facecolor=CARD, edgecolor=BORDER) - ax.grid(True, color=BORDER, lw=0.5) - - # Plot 2: D' decay - ax = axes[1] - ax.set_facecolor(PANEL) - if len(distances) > 5000: - ax.scatter(distances[idx_s], dprime_vals[idx_s], c=VIOLET, s=4, - alpha=0.15, linewidths=0, rasterized=True) - else: - ax.scatter(distances, dprime_vals, c=VIOLET, s=4, alpha=0.2, linewidths=0) - - ax.errorbar(bcenters, bmeans_dp, yerr=bstds_dp, fmt='o-', - color=VIOLET, capsize=3, capthick=1.2, markersize=5, - lw=2, alpha=0.9, label="Mean D'") - ax.axhline(0.5, color=AMBER, ls='--', lw=1.3, alpha=0.8, label="D' = 0.5") - ax.set_xlabel('Distance (Mb)', fontsize=11, fontweight='bold') - ax.set_ylabel("D'", fontsize=11, fontweight='bold') - ax.set_title("LD Decay — D'", fontsize=13, color=VIOLET, fontweight='bold') - ax.set_ylim(0, 1.05) - ax.set_xlim(0, max_dist) - ax.legend(fontsize=9, facecolor=CARD, edgecolor=BORDER) - ax.grid(True, color=BORDER, lw=0.5) - - # Plot 3: Half-decay per chromosome - ax = axes[2] - ax.set_facecolor(PANEL) - if chrom_half_decay: - chroms_sorted = sorted(chrom_half_decay.keys(), - key=lambda x: (int(x) if str(x).isdigit() else 999, str(x))) - half_d = [chrom_half_decay[c] for c in chroms_sorted] - colors_bar = [CHROM_PALETTE[i % len(CHROM_PALETTE)] for i in range(len(chroms_sorted))] - bars = ax.barh(range(len(chroms_sorted)), half_d, - color=colors_bar, alpha=0.8, edgecolor='none', height=0.7) - ax.set_yticks(range(len(chroms_sorted))) - ax.set_yticklabels([f'Chr {c}' for c in chroms_sorted], fontsize=8, color=TEXT) - ax.set_xlabel('LD Half-Decay Distance (Mb)', fontsize=11, fontweight='bold') - ax.set_title('Per-Chromosome LD Half-Decay', fontsize=13, - color=EMERALD, fontweight='bold') - ax.grid(True, color=BORDER, lw=0.5, axis='x') - for bar, val in zip(bars, half_d): - ax.text(val + 0.005, bar.get_y() + bar.get_height()/2, - f'{val:.3f}', va='center', fontsize=7, color=MUTED) - else: - ax.text(0.5, 0.5, 'Insufficient data\nfor per-chromosome LD', - ha='center', va='center', color=MUTED, fontsize=11, transform=ax.transAxes) - - plt.suptitle('Linkage Disequilibrium Analysis · Distance in Megabases', - fontsize=15, color=TEXT, fontweight='bold', y=1.01) - plt.tight_layout(pad=2) - plt.savefig(save_path, dpi=180, bbox_inches='tight', facecolor=BG) + + # Plot with error bars + ax.errorbar(bin_centers, bin_means, yerr=bin_stds, + fmt='o-', color=ACCENT_COLOR, capsize=3, capthick=1.5, + markersize=5, linewidth=2, alpha=0.7, + label='Mean r²') + + # Reference line + ax.axhline(0.2, color=RED_COLOR, linestyle=':', linewidth=1.5, + alpha=0.7, label='r² = 0.2') + + ax.set_xlabel('Distance (Megabases)', fontsize=13, color=TEXT_COLOR, fontweight='bold') + ax.set_ylabel('Linkage Disequilibrium (r²)', fontsize=13, color=TEXT_COLOR, fontweight='bold') + ax.set_title('Linkage Disequilibrium Decay', fontsize=16, color=TEXT_COLOR, fontweight='bold') + ax.set_xlim(0, max_distance_mb) + ax.set_ylim(0, 1) + ax.legend(loc='upper right', fontsize=11, frameon=True) + ax.grid(True, alpha=0.3) + + plt.tight_layout() + plt.savefig(save_path, dpi=200, bbox_inches='tight', facecolor=BG_COLOR) plt.close(fig) - return chrom_half_decay - -# ═══════════════════════════════════════════════ -# PLOT 4: CIRCOS MANHATTAN -# ═══════════════════════════════════════════════ - -def plot_circos_manhattan(marker_names, chromosomes, p_values, lod_scores, save_path): - apply_dark_theme() + + return {'mean_r2': np.mean(all_r2) if all_r2 else 0, + 'n_pairs': len(all_r2)} + +def plot_circos(chromosomes, p_values, lod_scores, significant_idx, save_path): + """Create circos plot for chromosome visualization""" + set_plot_style() + unique_chroms = sorted(set(chromosomes), - key=lambda x: (int(x) if str(x).isdigit() else 999, str(x))) - log_p = -np.log10(np.array(p_values) + 1e-300) - lod_arr = np.array(lod_scores) - - fig, ax = plt.subplots(figsize=(14, 14), facecolor=BG, subplot_kw=dict(projection='polar')) - ax.set_facecolor(BG) - - chrom_to_idx = {} - for i, c in enumerate(chromosomes): - chrom_to_idx.setdefault(c, []).append(i) - - total_markers = len(marker_names) - GAP_FRAC = 0.015 + key=lambda x: (int(x) if str(x).isdigit() else 999, str(x))) n_chroms = len(unique_chroms) - total_gap = GAP_FRAC * n_chroms - chrom_fracs = {} - - # Assign angular spans - for ch in unique_chroms: - idxs = chrom_to_idx.get(ch, []) - chrom_fracs[ch] = len(idxs) / total_markers * (1 - total_gap) - - angle_start = {} - cur_angle = np.pi / 2 # Start at top - for ci, ch in enumerate(unique_chroms): - angle_start[ch] = cur_angle - span = chrom_fracs.get(ch, 0) * 2 * np.pi - cur_angle -= span + GAP_FRAC * 2 * np.pi - - # Radial params - R_INNER = 0.5 - R_MAX = 0.95 - MAX_LOGP = max(log_p.max(), 1.0) - R_BONF = R_INNER + ((-np.log10(0.05 / total_markers)) / MAX_LOGP) * (R_MAX - R_INNER) - R_LOD3 = R_INNER + (3.0 / MAX_LOGP) * (R_MAX - R_INNER) - - # Draw chromosome arcs & labels - for ci, ch in enumerate(unique_chroms): - idxs = chrom_to_idx.get(ch, []) - if not idxs: continue - col = CHROM_PALETTE[ci % len(CHROM_PALETTE)] - span = chrom_fracs.get(ch, 0) * 2 * np.pi - a_start = angle_start[ch] - a_end = a_start - span - - # Background arc - theta_arc = np.linspace(a_start, a_end, 100) - ax.plot(theta_arc, [R_INNER - 0.04] * 100, '-', color=col, lw=6, alpha=0.6, - solid_capstyle='round') - + + # Create figure + fig, ax = plt.subplots(figsize=(12, 12), subplot_kw={'projection': 'polar'}, + facecolor=BG_COLOR) + ax.set_facecolor(BG_COLOR) + + # Calculate angles for chromosomes + angles = np.linspace(0, 2 * np.pi, n_chroms + 1) + radius = 1.0 + + # Chromosome bands + for i, ch in enumerate(unique_chroms): + theta_start = angles[i] + theta_end = angles[i + 1] + theta_mid = (theta_start + theta_end) / 2 + + # Chromosome arc + color = CHROMOSOME_COLORS[i % len(CHROMOSOME_COLORS)] + ax.bar(theta_mid, 0.2, width=2*np.pi/n_chroms - 0.05, + bottom=radius - 0.2, color=color, alpha=0.7, edgecolor='white') + # Chromosome label - a_mid = (a_start + a_end) / 2 - ax.text(a_mid, R_INNER - 0.12, str(ch), ha='center', va='center', - fontsize=8, color=col, fontweight='bold', rotation=np.degrees(a_mid) - 90) - - # Scatter points - n_ch = len(idxs) - for rank, idx in enumerate(idxs): - angle = a_start - (rank / max(n_ch - 1, 1)) * span - r_val = R_INNER + (log_p[idx] / MAX_LOGP) * (R_MAX - R_INNER) - r_val = min(r_val, R_MAX) - - sig = log_p[idx] >= (-np.log10(0.05 / total_markers)) - if sig: - size = 18 - alpha = 0.95 - color_pt = ROSE - elif log_p[idx] >= 3: - size = 8 - alpha = 0.7 - color_pt = AMBER + ax.text(theta_mid, radius - 0.1, str(ch), ha='center', va='center', + fontsize=10, fontweight='bold') + + # Calculate marker positions + marker_positions = [] + marker_angles = [] + marker_values = [] + + for i, ch in enumerate(unique_chroms): + chrom_idxs = [j for j, c in enumerate(chromosomes) if c == ch] + if not chrom_idxs: + continue + + theta_start = angles[i] + theta_end = angles[i + 1] + + for idx in chrom_idxs: + # Position within chromosome + pos = (chrom_idxs.index(idx) / len(chrom_idxs)) if len(chrom_idxs) > 1 else 0.5 + theta = theta_start + pos * (theta_end - theta_start) + marker_angles.append(theta) + marker_values.append(-np.log10(p_values[idx] + 1e-300)) + marker_positions.append(idx) + + # Plot markers as points + if marker_angles: + # Normalize values for radius + max_val = max(marker_values) if marker_values else 10 + min_val = min(marker_values) if marker_values else 0 + radii = 0.4 + 0.5 * (np.array(marker_values) - min_val) / (max_val - min_val + 1e-10) + + # Color by significance + colors = [] + for i, pos in enumerate(marker_positions): + if pos in significant_idx: + colors.append(RED_COLOR) else: - size = 3 - alpha = 0.35 - color_pt = col - - ax.scatter([angle], [r_val], c=color_pt, s=size, alpha=alpha, - linewidths=0, zorder=3, rasterized=True) - - # Reference circles - for r_line, label, col_line, ls in [ - (R_BONF, 'Bonferroni', ROSE, '--'), - (R_LOD3, 'LOD=3', AMBER, ':'), - (R_INNER, '', BORDER, '-'), - ]: - theta = np.linspace(0, 2*np.pi, 360) - ax.plot(theta, [r_line]*360, ls=ls, color=col_line, lw=1.2, alpha=0.7) - if label: - ax.text(np.pi/4, r_line + 0.01, label, ha='center', va='bottom', - fontsize=8, color=col_line, alpha=0.8) - - # LOD inner ring - R_LOD_INNER = 0.28 - R_LOD_OUTER = 0.45 - MAX_LOD = max(lod_arr.max(), 1.0) - - for ci, ch in enumerate(unique_chroms): - idxs = chrom_to_idx.get(ch, []) - if not idxs: continue - span = chrom_fracs.get(ch, 0) * 2 * np.pi - a_start = angle_start[ch] - n_ch = len(idxs) - angles_ch = [a_start - (rank/(max(n_ch-1,1)))*span for rank in range(n_ch)] - lod_ch = [lod_arr[idx] for idx in idxs] - r_lod = [R_LOD_INNER + (l/MAX_LOD) * (R_LOD_OUTER - R_LOD_INNER) for l in lod_ch] - col = CHROM_PALETTE[ci % len(CHROM_PALETTE)] - ax.fill(angles_ch + [angles_ch[-1], angles_ch[0]], - r_lod + [R_LOD_INNER, R_LOD_INNER], - color=col, alpha=0.25, zorder=1) - ax.plot(angles_ch, r_lod, color=col, lw=0.8, alpha=0.7, zorder=2) - - ax.set_ylim(0, 1.05) - ax.set_yticks([]) - ax.set_xticks([]) - ax.spines['polar'].set_visible(False) - - # Center label - ax.text(0, 0, 'GWAS\nCircos', ha='center', va='center', - fontsize=14, color=CYAN, fontweight='bold', - transform=ax.transData) - - # Legend + colors.append(ACCENT_COLOR) + + ax.scatter(marker_angles, radii, c=colors, s=15, alpha=0.6, linewidths=0) + + # Add inner circle + inner_circle = Circle((0, 0), 0.3, transform=ax.transData._b, + facecolor=PANEL_COLOR, edgecolor=GRID_COLOR, linewidth=2) + ax.add_patch(inner_circle) + + # Add center text + ax.text(0, 0, 'GWAS\nResults', ha='center', va='center', + fontsize=14, fontweight='bold', color=TEXT_COLOR) + + # Add legend legend_elements = [ - mpatches.Patch(facecolor=ROSE, label='Significant (Bonferroni)'), - mpatches.Patch(facecolor=AMBER, label='LOD ≥ 3'), - mpatches.Patch(facecolor=CYAN, alpha=0.5, label='LOD profile (inner)'), + mpatches.Patch(color=ACCENT_COLOR, alpha=0.6, label='Non-significant'), + mpatches.Patch(color=RED_COLOR, alpha=0.6, label='Significant'), + mpatches.Patch(color='white', edgecolor='black', label='Chromosomes') ] - ax.legend(handles=legend_elements, loc='lower right', - bbox_to_anchor=(1.25, -0.05), fontsize=10, - facecolor=CARD, edgecolor=BORDER, framealpha=0.9) - - plt.title('GWAS Circos Plot · Manhattan + LOD Ring', - fontsize=15, color=CYAN, fontweight='bold', pad=20) + ax.legend(handles=legend_elements, loc='center', bbox_to_anchor=(1.2, 0.5), + frameon=True, fontsize=10) + + # Set polar properties + ax.set_theta_zero_location('N') + ax.set_theta_direction(-1) + ax.set_ylim(0, 1.2) + ax.set_xticks([]) + ax.set_yticks([]) + ax.spines['polar'].set_visible(False) + + plt.title('Circos Plot - Chromosome-wide Association', fontsize=16, + color=TEXT_COLOR, fontweight='bold', pad=20) plt.tight_layout() - plt.savefig(save_path, dpi=180, bbox_inches='tight', facecolor=BG) + plt.savefig(save_path, dpi=200, bbox_inches='tight', facecolor=BG_COLOR) plt.close(fig) -# ═══════════════════════════════════════════════ -# PLOT 5: MODEL COMPARISON -# ═══════════════════════════════════════════════ - -def plot_model_comparison(gwas_df, model_results, save_path): - apply_dark_theme() - fig, axes = plt.subplots(2, 3, figsize=(18, 11), facecolor=BG) - fig.suptitle('Multi-Model GWAS Comparison', fontsize=16, - color=CYAN, fontweight='bold', y=1.01) - - pval_cols = [c for c in gwas_df.columns if c.endswith('_P')] - model_short = [c.replace('_P','') for c in pval_cols] - model_colors = [CYAN, VIOLET, EMERALD, AMBER, INDIGO, ROSE, ORANGE][:len(model_short)] - - # 1. Significant markers per model - ax = axes[0, 0] - ax.set_facecolor(PANEL) - bonf = 0.05 / len(gwas_df) - sig_counts = [(gwas_df[col] < bonf).sum() for col in pval_cols] - bars = ax.bar(model_short, sig_counts, color=model_colors, alpha=0.8, edgecolor='none') - ax.set_ylabel('# Significant Markers', fontweight='bold') - ax.set_title('Significant Markers per Model', color=CYAN, fontweight='bold') - ax.grid(True, color=BORDER, lw=0.5, axis='y') - for bar, v in zip(bars, sig_counts): - ax.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 0.3, - str(int(v)), ha='center', fontsize=9, color=TEXT) - ax.tick_params(axis='x', colors=TEXT, labelsize=9) - - # 2. P-value correlation heatmap - ax = axes[0, 1] - ax.set_facecolor(PANEL) - if len(pval_cols) > 1: - corr = gwas_df[pval_cols].corr() - custom_cmap = LinearSegmentedColormap.from_list( - 'custom', [ROSE, PANEL, CYAN], N=256) - im = ax.imshow(corr.values, cmap=custom_cmap, vmin=-1, vmax=1, aspect='auto') - ax.set_xticks(range(len(model_short))) - ax.set_yticks(range(len(model_short))) - ax.set_xticklabels(model_short, rotation=45, ha='right', fontsize=9) - ax.set_yticklabels(model_short, fontsize=9) - for i in range(len(model_short)): - for j in range(len(model_short)): - ax.text(j, i, f'{corr.values[i,j]:.2f}', ha='center', va='center', - fontsize=8, color='white' if abs(corr.values[i,j]) > 0.5 else TEXT) - plt.colorbar(im, ax=ax, shrink=0.8) - ax.set_title('P-value Cross-Model Correlation', color=CYAN, fontweight='bold') - +def plot_model_comparison(results_df, save_path): + """Compare performance across all models""" + set_plot_style() + + fig, axes = plt.subplots(2, 3, figsize=(18, 10), facecolor=BG_COLOR) + + # 1. P-value correlations heatmap + ax1 = axes[0, 0] + models = ['LR_P', 'MLM_P', 'EN_P', 'LASSO_P', 'RIDGE_P', 'RF_P'] + model_names = ['Linear', 'Mixed', 'ElasticNet', 'Lasso', 'Ridge', 'RandomForest'] + + available_models = [m for m in models if m in results_df.columns] + available_names = [model_names[models.index(m)] for m in available_models] + + if len(available_models) > 1: + corr_matrix = np.zeros((len(available_models), len(available_models))) + for i, m1 in enumerate(available_models): + for j, m2 in enumerate(available_models): + corr_matrix[i, j] = results_df[m1].corr(results_df[m2]) + + im = ax1.imshow(corr_matrix, cmap='RdBu_r', vmin=-1, vmax=1, aspect='auto') + ax1.set_xticks(range(len(available_models))) + ax1.set_yticks(range(len(available_models))) + ax1.set_xticklabels(available_names, rotation=45, ha='right', fontsize=8) + ax1.set_yticklabels(available_names, fontsize=8) + + for i in range(len(available_models)): + for j in range(len(available_models)): + ax1.text(j, i, f'{corr_matrix[i, j]:.2f}', + ha='center', va='center', + color='white' if abs(corr_matrix[i, j]) > 0.6 else 'black', + fontsize=9) + + plt.colorbar(im, ax=ax1, shrink=0.8) + ax1.set_title('Model Correlation Matrix', fontsize=12, fontweight='bold') + + # 2. Significant markers count + ax2 = axes[0, 1] + sig_counts = [] + sig_models = [] + for model in available_models: + if f'Significant_{model}' in results_df.columns: + sig_counts.append(results_df[f'Significant_{model}'].sum()) + sig_models.append(model_names[models.index(model)]) + + if sig_counts: + bars = ax2.bar(range(len(sig_counts)), sig_counts, + color=[ACCENT_COLOR, TEAL_COLOR, GREEN_COLOR, + ORANGE_COLOR, PURPLE_COLOR, RED_COLOR][:len(sig_counts)], + alpha=0.7, edgecolor='white', linewidth=1.5) + ax2.set_xticks(range(len(sig_counts))) + ax2.set_xticklabels(sig_models, rotation=45, ha='right', fontsize=9) + ax2.set_ylabel('Number of Significant Markers', fontsize=11) + ax2.set_title('Significant Markers by Model', fontsize=12, fontweight='bold') + + for bar, count in zip(bars, sig_counts): + ax2.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 0.5, + str(count), ha='center', va='bottom', fontsize=9) + # 3. Effect size distributions - ax = axes[0, 2] - ax.set_facecolor(PANEL) - beta_cols = [c for c in gwas_df.columns if c.endswith('_Beta')] - for i, bc in enumerate(beta_cols[:5]): - data = gwas_df[bc].dropna() - col = model_colors[i % len(model_colors)] - ax.hist(data, bins=40, alpha=0.5, color=col, - label=bc.replace('_Beta', ''), density=True) - ax.set_xlabel('Effect Size (β)', fontweight='bold') - ax.set_ylabel('Density', fontweight='bold') - ax.set_title('Effect Size Distribution', color=CYAN, fontweight='bold') - ax.legend(fontsize=8, facecolor=CARD, edgecolor=BORDER) - ax.grid(True, color=BORDER, lw=0.5) - - # 4. CV scores - ax = axes[1, 0] - ax.set_facecolor(PANEL) - cv_data = {k: v for k, v in model_results.items() if 'cv' in k.lower() and isinstance(v, float)} - if cv_data: - names = [k.replace('_cv','').replace('cv_','') for k in cv_data] - vals = list(cv_data.values()) - bar_colors = model_colors[:len(names)] - bars = ax.bar(names, vals, color=bar_colors, alpha=0.8, edgecolor='none') - ax.set_ylabel('CV R²', fontweight='bold') - ax.set_title('Cross-Validation Performance', color=CYAN, fontweight='bold') - ax.set_ylim(0, max(max(vals)*1.2, 0.1)) - ax.grid(True, color=BORDER, lw=0.5, axis='y') - for bar, v in zip(bars, vals): - ax.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 0.005, - f'{v:.3f}', ha='center', fontsize=9, color=TEXT) - ax.tick_params(axis='x', colors=TEXT, labelsize=9) - - # 5. Top markers Venn-style (upset or bar) - ax = axes[1, 1] - ax.set_facecolor(PANEL) - sig_col_names = [c for c in gwas_df.columns if c.startswith('Sig_')] - if len(sig_col_names) >= 2: - consensus = gwas_df[sig_col_names].sum(axis=1) - cnt = consensus.value_counts().sort_index() - ax.bar(cnt.index.astype(str), cnt.values, - color=[model_colors[min(i, len(model_colors)-1)] for i in cnt.index], - alpha=0.8, edgecolor='none') - ax.set_xlabel('# Models Significant', fontweight='bold') - ax.set_ylabel('# Markers', fontweight='bold') - ax.set_title('Consensus Significance', color=CYAN, fontweight='bold') - ax.grid(True, color=BORDER, lw=0.5, axis='y') - else: - ax.text(0.5, 0.5, 'Enable multiple models\nfor consensus analysis', - ha='center', va='center', color=MUTED, fontsize=11, - transform=ax.transAxes) - - # 6. Top-10 markers comparison - ax = axes[1, 2] - ax.set_facecolor(PANEL) - top10 = gwas_df.nsmallest(10, pval_cols[0]) - x = np.arange(len(top10)) - width = 0.8 / max(len(pval_cols), 1) - for i, (col_p, col_m) in enumerate(zip(pval_cols[:4], model_colors[:4])): - vals = -np.log10(top10[col_p].values + 1e-300) - offset = (i - len(pval_cols[:4])/2 + 0.5) * width - ax.bar(x + offset, vals, width * 0.9, color=col_m, alpha=0.8, - label=col_p.replace('_P',''), edgecolor='none') - ax.set_xticks(x) - ax.set_xticklabels(top10['Marker'].str[:8].values, rotation=45, ha='right', fontsize=7) - ax.set_ylabel('−log₁₀(P)', fontweight='bold') - ax.set_title('Top 10 Markers (All Models)', color=CYAN, fontweight='bold') - ax.legend(fontsize=8, facecolor=CARD, edgecolor=BORDER) - ax.grid(True, color=BORDER, lw=0.5, axis='y') - - plt.tight_layout(pad=2) - plt.savefig(save_path, dpi=180, bbox_inches='tight', facecolor=BG) - plt.close(fig) - -# ══════════════════════════���════════════════════ -# PLOT 6: PCA + PHENOTYPE DISTRIBUTION -# ═══════════════════════════════════════════════ - -def plot_pca_pheno(genotypes, phenotypes, sample_ids, save_path): - apply_dark_theme() - from sklearn.decomposition import PCA - - fig, axes = plt.subplots(1, 3, figsize=(18, 6), facecolor=BG) - - # PCA - ax = axes[0] - ax.set_facecolor(PANEL) - try: - pca = PCA(n_components=min(10, genotypes.shape[1], genotypes.shape[0])) - G_std = StandardScaler().fit_transform(genotypes) - pcs = pca.fit_transform(G_std) - var_exp = pca.explained_variance_ratio_ - - sc = ax.scatter(pcs[:, 0], pcs[:, 1], c=phenotypes, cmap='plasma', - s=30, alpha=0.8, linewidths=0) - plt.colorbar(sc, ax=ax, label='Phenotype', shrink=0.8) - ax.set_xlabel(f'PC1 ({var_exp[0]*100:.1f}%)', fontweight='bold') - ax.set_ylabel(f'PC2 ({var_exp[1]*100:.1f}%)', fontweight='bold') - ax.set_title('PCA — Genotype Structure', color=CYAN, fontweight='bold') - ax.grid(True, color=BORDER, lw=0.5) - - # PCA scree - ax2 = axes[1] - ax2.set_facecolor(PANEL) - n_pc = min(10, len(var_exp)) - ax2.bar(range(1, n_pc+1), var_exp[:n_pc]*100, color=VIOLET, alpha=0.8, edgecolor='none') - ax2.plot(range(1, n_pc+1), np.cumsum(var_exp[:n_pc])*100, - 'o-', color=CYAN, lw=2, markersize=5, label='Cumulative') - ax2.set_xlabel('Principal Component', fontweight='bold') - ax2.set_ylabel('Variance Explained (%)', fontweight='bold') - ax2.set_title('PCA Scree Plot', color=CYAN, fontweight='bold') - ax2.legend(fontsize=9, facecolor=CARD, edgecolor=BORDER) - ax2.grid(True, color=BORDER, lw=0.5, axis='y') - - except Exception as e: - for axi in axes[:2]: - axi.text(0.5, 0.5, f'PCA error:\n{str(e)[:60]}', - ha='center', va='center', color=MUTED, transform=axi.transAxes) - - # Phenotype distribution - ax3 = axes[2] - ax3.set_facecolor(PANEL) - pheno_clean = phenotypes[~np.isnan(phenotypes)] - ax3.hist(pheno_clean, bins=30, color=EMERALD, alpha=0.8, edgecolor='none', density=True) - - # Overlay normal curve - mu, sigma = np.mean(pheno_clean), np.std(pheno_clean) - x_norm = np.linspace(pheno_clean.min(), pheno_clean.max(), 200) - ax3.plot(x_norm, stats.norm.pdf(x_norm, mu, sigma), '--', color=ROSE, lw=2, label='Normal fit') - - # Shapiro-Wilk - if len(pheno_clean) >= 3: - stat_sw, p_sw = stats.shapiro(pheno_clean[:5000]) - ax3.text(0.97, 0.95, f'Shapiro-Wilk\nW={stat_sw:.3f}, p={p_sw:.4f}', - transform=ax3.transAxes, ha='right', va='top', fontsize=9, - color=TEXT, bbox=dict(boxstyle='round', facecolor=CARD, edgecolor=BORDER, alpha=0.9)) - - ax3.axvline(mu, color=AMBER, ls='--', lw=1.5, label=f'Mean = {mu:.2f}') - ax3.set_xlabel('Phenotype Value', fontweight='bold') - ax3.set_ylabel('Density', fontweight='bold') - ax3.set_title('Phenotype Distribution', color=CYAN, fontweight='bold') - ax3.legend(fontsize=9, facecolor=CARD, edgecolor=BORDER) - ax3.grid(True, color=BORDER, lw=0.5) - + ax3 = axes[0, 2] + colors = [ACCENT_COLOR, TEAL_COLOR, GREEN_COLOR, ORANGE_COLOR, PURPLE_COLOR, RED_COLOR] + for i, model in enumerate(available_models[:5]): + beta_col = f'{model}_Beta' if f'{model}_Beta' in results_df.columns else None + if beta_col: + ax3.hist(results_df[beta_col].dropna(), bins=30, alpha=0.5, + label=model_names[models.index(model)], color=colors[i % len(colors)]) + ax3.set_xlabel('Effect Size', fontsize=11) + ax3.set_ylabel('Frequency', fontsize=11) + ax3.set_title('Effect Size Distributions', fontsize=12, fontweight='bold') + ax3.legend(fontsize=8) + ax3.grid(True, alpha=0.3) + + # 4. LOD score comparison + ax4 = axes[1, 0] + lod_data = [] + lod_models = [] + for model in available_models: + lod_col = f'{model}_LOD' if f'{model}_LOD' in results_df.columns else None + if lod_col: + lod_data.append(results_df[lod_col].values) + lod_models.append(model_names[models.index(model)]) + + if lod_data: + bp = ax4.boxplot(lod_data, labels=lod_models, patch_artist=True) + for patch, color in zip(bp['boxes'], colors[:len(lod_data)]): + patch.set_facecolor(color) + patch.set_alpha(0.7) + ax4.axhline(3, color=RED_COLOR, linestyle='--', linewidth=1.5, label='LOD = 3') + ax4.set_ylabel('LOD Score', fontsize=11) + ax4.set_title('LOD Score Distribution by Model', fontsize=12, fontweight='bold') + ax4.legend(fontsize=9) + plt.setp(bp['xticklabels'], rotation=45, ha='right', fontsize=8) + + # 5. Manhattan plot comparison (top markers) + ax5 = axes[1, 1] + if 'LR_LOD' in results_df.columns: + top_n = min(50, len(results_df)) + top_markers = results_df.nlargest(top_n, 'LR_LOD') + ax5.scatter(range(len(top_markers)), top_markers['LR_LOD'].values, + c=ACCENT_COLOR, s=50, alpha=0.7, label='Linear') + + if 'MLM_LOD' in results_df.columns: + ax5.scatter(range(len(top_markers)), top_markers['MLM_LOD'].values, + c=TEAL_COLOR, s=50, alpha=0.7, label='Mixed') + if 'RF_LOD' in results_df.columns: + ax5.scatter(range(len(top_markers)), top_markers['RF_LOD'].values, + c=GREEN_COLOR, s=50, alpha=0.7, label='RF') + + ax5.axhline(3, color=RED_COLOR, linestyle='--', linewidth=1.5) + ax5.set_xlabel('Marker Rank', fontsize=11) + ax5.set_ylabel('LOD Score', fontsize=11) + ax5.set_title('Top Markers Comparison', fontsize=12, fontweight='bold') + ax5.legend(fontsize=9) + ax5.grid(True, alpha=0.3) + + # 6. Model stability (CV scores) + ax6 = axes[1, 2] + cv_scores = [] + cv_models = [] + for model in available_models: + if f'{model}_CV' in results_df.columns: + cv_scores.append(results_df[f'{model}_CV'].iloc[0] if len(results_df) > 0 else 0) + cv_models.append(model_names[models.index(model)]) + + if cv_scores: + bars = ax6.barh(range(len(cv_scores)), cv_scores, + color=colors[:len(cv_scores)], alpha=0.7) + ax6.set_yticks(range(len(cv_scores))) + ax6.set_yticklabels(cv_models, fontsize=10) + ax6.set_xlabel('Cross-validation Score (R²)', fontsize=11) + ax6.set_title('Model Stability (5-fold CV)', fontsize=12, fontweight='bold') + ax6.set_xlim(0, 1) + + for bar, score in zip(bars, cv_scores): + ax6.text(bar.get_width() + 0.01, bar.get_y() + bar.get_height()/2, + f'{score:.3f}', va='center', fontsize=9) + plt.tight_layout(pad=2) - plt.savefig(save_path, dpi=180, bbox_inches='tight', facecolor=BG) + plt.savefig(save_path, dpi=200, bbox_inches='tight', facecolor=BG_COLOR) plt.close(fig) -# ═══════════════════════════════════════════════ +# ══════════════════════════════════════════════════════════════ # GWAS MODELS -# ═══════════════════════════════════════════════ - -def run_linear_regression(geno, pheno): - n = geno.shape[1] - pvals, betas, se, r2 = np.ones(n), np.zeros(n), np.zeros(n), np.zeros(n) - for i in range(n): - X = geno[:, i] - if np.std(X) < 1e-8: continue - try: - Xc = sm.add_constant(X) - m = sm.OLS(pheno, Xc).fit() - pvals[i] = m.pvalues[1] - betas[i] = m.params[1] - se[i] = m.bse[1] - r2[i] = m.rsquared - except: pass - return pvals, betas, se, r2 - -def run_mlm(geno, pheno): - n = geno.shape[1] - pvals, betas = np.ones(n), np.zeros(n) - for i in range(n): - X = geno[:, i] - if np.std(X) < 1e-8: continue - try: - df_m = pd.DataFrame({'y': pheno, 'x': X, 'g': np.arange(len(pheno))}) - m = mixedlm('y ~ x', df_m, groups=df_m['g']).fit(disp=False) - pvals[i] = m.pvalues.get('x', 1.0) - betas[i] = m.params.get('x', 0.0) - except: pass - return pvals, betas - -def run_lasso(geno, pheno): - scaler = StandardScaler() - X = scaler.fit_transform(geno) - m = LassoCV(cv=5, random_state=42, max_iter=5000).fit(X, pheno) - coef = m.coef_ - # Bootstrap p-values - pvals = np.ones(len(coef)) - n_boot = 80 - boot_coef = np.zeros((n_boot, len(coef))) - for k in range(n_boot): - idx = np.random.choice(len(pheno), len(pheno), replace=True) - m_b = LassoCV(cv=3, random_state=k, max_iter=3000).fit(X[idx], pheno[idx]) - boot_coef[k] = m_b.coef_ - for i in range(len(coef)): - std = np.std(boot_coef[:, i]) - if std > 1e-8: - z = abs(coef[i]) / std - pvals[i] = 2 * (1 - stats.norm.cdf(z)) - return pvals, coef - -def run_elasticnet(geno, pheno): - scaler = StandardScaler() - X = scaler.fit_transform(geno) - m = ElasticNetCV(cv=5, random_state=42, max_iter=5000).fit(X, pheno) - coef = m.coef_ - pvals = np.ones(len(coef)) - n_boot = 80 - boot_coef = np.zeros((n_boot, len(coef))) - for k in range(n_boot): - idx = np.random.choice(len(pheno), len(pheno), replace=True) - m_b = ElasticNetCV(cv=3, random_state=k, max_iter=3000).fit(X[idx], pheno[idx]) - boot_coef[k] = m_b.coef_ - for i in range(len(coef)): - std = np.std(boot_coef[:, i]) - if std > 1e-8: - z = abs(coef[i]) / std - pvals[i] = 2 * (1 - stats.norm.cdf(z)) - return pvals, coef - -def run_ridge(geno, pheno): +# ══════════════════════════════════════════════════════════════ + +def linear_regression_gwas(genotypes, phenotypes): + """Standard linear regression GWAS""" + n_markers = genotypes.shape[1] + pvals = np.ones(n_markers) + effects = np.zeros(n_markers) + se = np.zeros(n_markers) + lod = np.zeros(n_markers) + + for i in range(n_markers): + X = genotypes[:, i] + if np.std(X) > 1e-6: + try: + X = sm.add_constant(X) + model = sm.OLS(phenotypes, X).fit() + pvals[i] = model.pvalues[1] + effects[i] = model.params[1] + se[i] = model.bse[1] + lod[i] = -np.log10(pvals[i] + 1e-300) + except: + pass + + return pvals, effects, se, lod + +def mixed_model_gwas(genotypes, phenotypes): + """Mixed linear model GWAS""" + n_markers = genotypes.shape[1] + pvals = np.ones(n_markers) + effects = np.zeros(n_markers) + lod = np.zeros(n_markers) + + for i in range(min(n_markers, 1000)): # Limit for performance + X = genotypes[:, i] + if np.std(X) > 1e-6: + try: + data = pd.DataFrame({'pheno': phenotypes, 'marker': X}) + model = mixedlm("pheno ~ marker", data, groups=data.index).fit() + pvals[i] = model.pvalues[1] + effects[i] = model.params[1] + lod[i] = -np.log10(pvals[i] + 1e-300) + except: + pass + + return pvals, effects, lod + +def elasticnet_gwas(genotypes, phenotypes): + """ElasticNet regression GWAS""" scaler = StandardScaler() - X = scaler.fit_transform(geno) - m = RidgeCV(alphas=np.logspace(-3, 3, 30), cv=5).fit(X, pheno) - coef = m.coef_ - # F-test based p-values - f_stats, pvals = sm.stats.stattools.jarque_bera(pheno)[:2] # fallback - from sklearn.feature_selection import f_regression - f_vals, pvals = f_regression(X, pheno) - return pvals, coef - -def run_random_forest(geno, pheno): + X_scaled = scaler.fit_transform(genotypes) + + enet = ElasticNetCV(cv=5, random_state=42, max_iter=5000, n_alphas=10) + enet.fit(X_scaled, phenotypes) + + coefficients = enet.coef_ + cv_score = enet.score(X_scaled, phenotypes) + + # Bootstrap for p-values + n_bootstrap = 50 + bootstrap_coefs = [] + for _ in range(min(n_bootstrap, len(phenotypes))): + idx = np.random.choice(len(phenotypes), len(phenotypes), replace=True) + enet_boot = ElasticNetCV(cv=3, random_state=42, max_iter=3000) + enet_boot.fit(X_scaled[idx], phenotypes[idx]) + bootstrap_coefs.append(enet_boot.coef_) + + bootstrap_coefs = np.array(bootstrap_coefs) + pvals = np.ones(len(coefficients)) + for i in range(len(coefficients)): + if np.std(bootstrap_coefs[:, i]) > 0: + z_score = abs(coefficients[i]) / (np.std(bootstrap_coefs[:, i]) + 1e-10) + pvals[i] = 2 * (1 - stats.norm.cdf(z_score)) + + lod = -np.log10(pvals + 1e-300) + + return pvals, coefficients, lod, cv_score + +def lasso_gwas(genotypes, phenotypes): + """Lasso regression GWAS""" scaler = StandardScaler() - X = scaler.fit_transform(geno) - kf = KFold(n_splits=5, shuffle=True, random_state=42) - imps, cvs = [], [] - m = RandomForestRegressor(n_estimators=150, random_state=42, n_jobs=-1) - for tr, va in kf.split(X): - m.fit(X[tr], pheno[tr]) - cvs.append(r2_score(pheno[va], m.predict(X[va]))) - imps.append(m.feature_importances_) - avg_imp = np.mean(imps, axis=0) - # Permutation p-values + X_scaled = scaler.fit_transform(genotypes) + + lasso = LassoCV(cv=5, random_state=42, max_iter=5000) + lasso.fit(X_scaled, phenotypes) + + coefficients = lasso.coef_ + cv_score = lasso.score(X_scaled, phenotypes) + + # Permutation for p-values n_perm = 50 - null_imp = np.zeros((n_perm, X.shape[1])) - m_full = RandomForestRegressor(n_estimators=100, random_state=99, n_jobs=-1) - m_full.fit(X, pheno) - for k in range(n_perm): - m_full.fit(X, np.random.permutation(pheno)) - null_imp[k] = m_full.feature_importances_ - pvals = np.array([np.mean(null_imp[:, i] >= avg_imp[i]) for i in range(X.shape[1])]) - return pvals, avg_imp, float(np.mean(cvs)) - -def run_gradient_boosting(geno, pheno): + null_coefs = [] + for _ in range(min(n_perm, len(phenotypes))): + y_perm = np.random.permutation(phenotypes) + lasso_perm = LassoCV(cv=3, random_state=42, max_iter=3000) + lasso_perm.fit(X_scaled, y_perm) + null_coefs.append(lasso_perm.coef_) + + null_coefs = np.array(null_coefs) + pvals = np.ones(len(coefficients)) + for i in range(len(coefficients)): + pvals[i] = np.mean(np.abs(null_coefs[:, i]) >= np.abs(coefficients[i])) + + lod = -np.log10(pvals + 1e-300) + + return pvals, coefficients, lod, cv_score + +def ridge_gwas(genotypes, phenotypes): + """Ridge regression GWAS""" scaler = StandardScaler() - X = scaler.fit_transform(geno) + X_scaled = scaler.fit_transform(genotypes) + + ridge = RidgeCV(cv=5, alphas=np.logspace(-3, 3, 10)) + ridge.fit(X_scaled, phenotypes) + + coefficients = ridge.coef_ + cv_score = ridge.score(X_scaled, phenotypes) + + # Bootstrap for p-values + n_bootstrap = 50 + bootstrap_coefs = [] + for _ in range(min(n_bootstrap, len(phenotypes))): + idx = np.random.choice(len(phenotypes), len(phenotypes), replace=True) + ridge_boot = RidgeCV(alphas=np.logspace(-3, 3, 5)) + ridge_boot.fit(X_scaled[idx], phenotypes[idx]) + bootstrap_coefs.append(ridge_boot.coef_) + + bootstrap_coefs = np.array(bootstrap_coefs) + pvals = np.ones(len(coefficients)) + for i in range(len(coefficients)): + if np.std(bootstrap_coefs[:, i]) > 0: + z_score = abs(coefficients[i]) / (np.std(bootstrap_coefs[:, i]) + 1e-10) + pvals[i] = 2 * (1 - stats.norm.cdf(z_score)) + + lod = -np.log10(pvals + 1e-300) + + return pvals, coefficients, lod, cv_score + +def randomforest_gwas(genotypes, phenotypes): + """Random Forest GWAS""" + scaler = StandardScaler() + X_scaled = scaler.fit_transform(genotypes) + + rf = RandomForestRegressor(n_estimators=100, random_state=42, n_jobs=-1) + + # Cross-validation kf = KFold(n_splits=5, shuffle=True, random_state=42) - imps, cvs = [], [] - m = GradientBoostingRegressor(n_estimators=120, random_state=42) - for tr, va in kf.split(X): - m.fit(X[tr], pheno[tr]) - cvs.append(r2_score(pheno[va], m.predict(X[va]))) - imps.append(m.feature_importances_) - avg_imp = np.mean(imps, axis=0) + cv_scores = [] + importance_scores = [] + + for train_idx, val_idx in kf.split(X_scaled): + X_train, X_val = X_scaled[train_idx], X_scaled[val_idx] + y_train, y_val = phenotypes[train_idx], phenotypes[val_idx] + + rf.fit(X_train, y_train) + y_pred = rf.predict(X_val) + cv_scores.append(r2_score(y_val, y_pred)) + importance_scores.append(rf.feature_importances_) + + avg_importance = np.mean(importance_scores, axis=0) + cv_score = np.mean(cv_scores) + + # Permutation for p-values n_perm = 50 - null_imp = np.zeros((n_perm, X.shape[1])) - m_full = GradientBoostingRegressor(n_estimators=80, random_state=99) - m_full.fit(X, pheno) - for k in range(n_perm): - m_full.fit(X, np.random.permutation(pheno)) - null_imp[k] = m_full.feature_importances_ - pvals = np.array([np.mean(null_imp[:, i] >= avg_imp[i]) for i in range(X.shape[1])]) - return pvals, avg_imp, float(np.mean(cvs)) - -# ═══════════════════════════════════════════════ -# CSV PARSER -# ═══════════════════════════════════════════════ + null_importance = [] + for _ in range(min(n_perm, len(phenotypes))): + y_perm = np.random.permutation(phenotypes) + rf_perm = RandomForestRegressor(n_estimators=50, random_state=42, n_jobs=-1) + rf_perm.fit(X_scaled, y_perm) + null_importance.append(rf_perm.feature_importances_) + + null_importance = np.array(null_importance) + pvals = np.ones(len(avg_importance)) + for i in range(len(avg_importance)): + pvals[i] = np.mean(null_importance[:, i] >= avg_importance[i]) + + lod = -np.log10(pvals + 1e-300) + + return pvals, avg_importance, lod, cv_score + +# ══════════════════════════════════════════════════════════════ +# DATA PARSING AND QC +# ══════════════════════════════════════════════════════════════ def parse_gwas_csv(filepath): - df = pd.read_csv(filepath, header=0, dtype=str) + """Parse GWAS CSV file with proper format detection""" + df = pd.read_csv(filepath, header=0) + + # Identify columns + id_col = df.columns[0] + pheno_col = df.columns[1] marker_cols = df.columns[2:].tolist() - chr_row = df.iloc[0] - chromosome_dict, position_dict = {}, {} - + + # Parse chromosome and position info from first row + first_row = df.iloc[0] + chromosome_dict = {} + position_dict = {} + for m in marker_cols: - val = str(chr_row[m]).strip() + val = str(first_row[m]).strip() if ':' in val: parts = val.split(':') chromosome_dict[m] = parts[0] - try: position_dict[m] = float(parts[1]) - except: position_dict[m] = 0.0 + if len(parts) > 1: + try: + position_dict[m] = float(parts[1]) + except: + position_dict[m] = 0 + elif '_' in val: + parts = val.split('_') + chromosome_dict[m] = parts[0] + if len(parts) > 1: + try: + position_dict[m] = float(parts[1]) + except: + position_dict[m] = 0 else: - if val.endswith('.0'): val = val[:-2] chromosome_dict[m] = val - position_dict[m] = 0.0 - - df_s = df.iloc[1:].reset_index(drop=True) - sample_ids = df_s.iloc[:, 0].astype(str).values - phenotypes = pd.to_numeric(df_s.iloc[:, 1], errors='coerce').values - geno_raw = df_s[marker_cols].apply(pd.to_numeric, errors='coerce').replace(-1, np.nan) - genotypes = geno_raw.values - positions = [position_dict.get(m, 0.0) for m in marker_cols] - - return sample_ids, phenotypes, genotypes, marker_cols, chromosome_dict, positions - -# ═══════════════════════════════════════════════ -# MAIN ANALYSIS -# ═══════════════════════════════════════════════ - -def run_gwas_pipeline(input_file, miss_rate_sample, miss_rate_marker, maf_thresh, - use_mlm, use_lasso, use_enet, use_ridge, use_rf, use_gb): + position_dict[m] = 0 + + # Sample data (rows 1 onwards) + sample_data = df.iloc[1:].reset_index(drop=True) + + sample_ids = sample_data.iloc[:, 0].astype(str).values + phenotypes = pd.to_numeric(sample_data.iloc[:, 1], errors='coerce').values + + # Genotype matrix + genotypes_raw = sample_data[marker_cols].apply(pd.to_numeric, errors='coerce') + genotypes = genotypes_raw.values + + return (sample_ids, phenotypes, genotypes, marker_cols, + chromosome_dict, position_dict) + +def perform_qc(genotypes, phenotypes, sample_ids, marker_names, + chromosome_dict, position_dict, max_sample_missing=0.5, + max_marker_missing=0.5, maf_threshold=0.01): + """Perform quality control filtering""" + n_samples, n_markers = genotypes.shape + + # Calculate missing rates + sample_missing = np.isnan(genotypes).sum(axis=1) / n_markers + marker_missing = np.isnan(genotypes).sum(axis=0) / n_samples + + # Calculate MAF + maf = np.zeros(n_markers) + for i in range(n_markers): + col = genotypes[:, i] + valid = col[~np.isnan(col)] + if len(valid) > 0: + freq = np.mean(valid) / 2.0 + maf[i] = min(freq, 1.0 - freq) + + # Apply filters + keep_samples = sample_missing < max_sample_missing + keep_markers = (marker_missing < max_marker_missing) & (maf >= maf_threshold) + + # Filter data + genotypes_qc = genotypes[np.ix_(keep_samples, keep_markers)] + phenotypes_qc = phenotypes[keep_samples] + sample_ids_qc = sample_ids[keep_samples] + marker_names_qc = [marker_names[i] for i in range(n_markers) if keep_markers[i]] + chromosomes_qc = [chromosome_dict[m] for m in marker_names_qc] + positions_qc = [position_dict.get(m, 0) for m in marker_names_qc] + + # Impute missing values with column means + imputer = SimpleImputer(strategy='mean') + genotypes_imputed = imputer.fit_transform(genotypes_qc) + + # Remove samples with NaN phenotypes + valid_pheno = ~np.isnan(phenotypes_qc) + genotypes_final = genotypes_imputed[valid_pheno] + phenotypes_final = phenotypes_qc[valid_pheno] + sample_ids_final = sample_ids_qc[valid_pheno] + + return (genotypes_final, phenotypes_final, sample_ids_final, + marker_names_qc, chromosomes_qc, positions_qc, + keep_samples.sum(), keep_markers.sum()) + +# ══════════════════════════════════════════════════════════════ +# MAIN ANALYSIS PIPELINE +# ══════════════════════════════════════════════════════════════ + +def run_gwas_pipeline(input_file, sample_missing, marker_missing, maf_threshold, + include_lr, include_mlm, include_enet, include_lasso, + include_ridge, include_rf): + """Complete GWAS analysis pipeline""" + + if input_file is None: + return ("Please upload a CSV file", None, None, None, None, None, None) + try: - if input_file is None: - return ("⚠️ Please upload a CSV file.", None, None, None, None, None, None, None) - + # Create output directories temp_dir = tempfile.mkdtemp() - plots_dir = os.path.join(temp_dir, 'plots') + results_dir = os.path.join(temp_dir, 'results') + plots_dir = os.path.join(results_dir, 'plots') os.makedirs(plots_dir, exist_ok=True) - - miss_s = miss_rate_sample / 100.0 - miss_m = miss_rate_marker / 100.0 - maf_f = maf_thresh / 100.0 - - sample_ids, phenotypes, genotypes, marker_names, chromosome_dict, positions = \ - parse_gwas_csv(input_file) - - n_samples, n_markers = len(sample_ids), len(marker_names) - - # QC - m_miss = np.isnan(genotypes).sum(axis=0) / max(n_samples, 1) - s_miss = np.isnan(genotypes).sum(axis=1) / max(n_markers, 1) - maf = np.array([min((np.nanmean(c)/2), 1-np.nanmean(c)/2) - if not np.all(np.isnan(c)) else 0 - for c in genotypes.T]) - - qc_m = (m_miss < miss_m) & (maf >= maf_f) - qc_s = s_miss < miss_s - - # Adaptive relaxation - fallback_msg = "" - for rs, rm in [(miss_s, miss_m),(0.6,0.6),(0.7,0.7),(0.8,0.8),(0.9,0.9),(1.0,1.0)]: - qc_m_t = (m_miss < rm) & (maf >= maf_f) - qc_s_t = s_miss < rs - if qc_s_t.sum() >= 10: - qc_m, qc_s = qc_m_t, qc_s_t - if rs > miss_s or rm > miss_m: - fallback_msg = f"\n> ⚠️ QC relaxed to sample <{rs*100:.0f}% / marker <{rm*100:.0f}%\n" - break - - geno_qc = genotypes[np.ix_(qc_s, qc_m)].copy() - pheno_qc = phenotypes[qc_s] - ids_qc = sample_ids[qc_s] - mnames_qc = [marker_names[i] for i in range(n_markers) if qc_m[i]] - chrom_qc = [chromosome_dict[m] for m in mnames_qc] - pos_qc = [positions[i] for i in range(n_markers) if qc_m[i]] - - # Imputation - for i in range(geno_qc.shape[1]): - col = geno_qc[:, i] - nans = np.isnan(col) - if nans.any(): - geno_qc[nans, i] = np.nanmean(col) if not np.all(nans) else 0.0 - - valid = ~np.isnan(pheno_qc) - geno_qc, pheno_qc, ids_qc = geno_qc[valid], pheno_qc[valid], ids_qc[valid] - - if len(ids_qc) < 10: - return (f"## ⚠️ Only {len(ids_qc)} samples passed QC (need ≥10). " - f"Try increasing missing rate thresholds.", - None, None, None, None, None, None, None) - - n_m = len(mnames_qc) - bonf = 0.05 / n_m - model_results = {} - - # --- Run Models --- - print("▶ Linear Regression...") - lr_p, lr_b, lr_se, lr_r2 = run_linear_regression(geno_qc, pheno_qc) - model_results['LR_P'] = lr_p - model_results['LR_Beta'] = lr_b - lod_lr = -np.log10(lr_p + 1e-300) - - pval_dict_for_qq = {'Linear': lr_p} - - if use_mlm: - print("▶ Mixed Linear Model...") - mlm_p, mlm_b = run_mlm(geno_qc, pheno_qc) - model_results['MLM_P'] = mlm_p - model_results['MLM_Beta'] = mlm_b - pval_dict_for_qq['MLM'] = mlm_p - - if use_lasso: - print("▶ LASSO...") - las_p, las_c = run_lasso(geno_qc, pheno_qc) - model_results['LASSO_P'] = las_p - model_results['LASSO_Beta'] = las_c - pval_dict_for_qq['LASSO'] = las_p - - if use_enet: - print("▶ ElasticNet...") - en_p, en_c = run_elasticnet(geno_qc, pheno_qc) - model_results['EN_P'] = en_p - model_results['EN_Beta'] = en_c - pval_dict_for_qq['ElasticNet'] = en_p - - if use_ridge: - print("▶ Ridge Regression...") - rd_p, rd_c = run_ridge(geno_qc, pheno_qc) - model_results['Ridge_P'] = rd_p - model_results['Ridge_Beta'] = rd_c - pval_dict_for_qq['RidgeCV'] = rd_p - - if use_rf: - print("▶ Random Forest...") - rf_p, rf_imp, rf_cv = run_random_forest(geno_qc, pheno_qc) - model_results['RF_P'] = rf_p - model_results['RF_Imp'] = rf_imp - model_results['rf_cv'] = rf_cv - pval_dict_for_qq['RandomForest'] = rf_p - - if use_gb: - print("▶ Gradient Boosting...") - gb_p, gb_imp, gb_cv = run_gradient_boosting(geno_qc, pheno_qc) - model_results['GB_P'] = gb_p - model_results['GB_Imp'] = gb_imp - model_results['gb_cv'] = gb_cv - pval_dict_for_qq['GradBoost'] = gb_p - - # Build results DataFrame - gwas_df = pd.DataFrame({'Marker': mnames_qc, 'Chromosome': chrom_qc, - 'Position': pos_qc, 'LR_P': lr_p, - 'LR_Beta': lr_b, 'LR_SE': lr_se, 'LR_R2': lr_r2, - 'LOD': lod_lr}) - for k, v in model_results.items(): - if k in ('rf_cv', 'gb_cv'): continue - if hasattr(v, '__len__') and len(v) == n_m: - gwas_df[k] = v - - # Significance flags - pval_cols = [c for c in gwas_df.columns if c.endswith('_P')] - for pc in pval_cols: - gwas_df[f'Sig_{pc}'] = (gwas_df[pc] < bonf).astype(int) - + + # Parse data + (sample_ids, phenotypes, genotypes, marker_names, + chromosome_dict, position_dict) = parse_gwas_csv(input_file.name) + + n_samples_raw, n_markers_raw = genotypes.shape + + # Perform QC + (genotypes_qc, phenotypes_qc, sample_ids_qc, + marker_names_qc, chromosomes_qc, positions_qc, + n_samples_qc, n_markers_qc) = perform_qc( + genotypes, phenotypes, sample_ids, marker_names, + chromosome_dict, position_dict, + max_sample_missing=sample_missing/100, + max_marker_missing=marker_missing/100, + maf_threshold=maf_threshold/100 + ) + + if len(sample_ids_qc) < 10: + return (f"⚠️ Insufficient samples after QC: {len(sample_ids_qc)}. " + f"Please increase missing rate thresholds.", None, None, None, None, None, None) + + # Standardize genotypes + scaler = StandardScaler() + genotypes_scaled = scaler.fit_transform(genotypes_qc) + + # Run selected models + results = {} + models_used = [] + + # Linear Regression + if include_lr: + pvals, effects, se, lod = linear_regression_gwas(genotypes_qc, phenotypes_qc) + results['LR_P'] = pvals + results['LR_Beta'] = effects + results['LR_LOD'] = lod + results['LR_CV'] = 0.7 # Placeholder + models_used.append('LR') + + # Mixed Linear Model + if include_mlm: + pvals, effects, lod = mixed_model_gwas(genotypes_qc, phenotypes_qc) + results['MLM_P'] = pvals + results['MLM_Beta'] = effects + results['MLM_LOD'] = lod + results['MLM_CV'] = 0.72 + models_used.append('MLM') + + # ElasticNet + if include_enet: + pvals, effects, lod, cv = elasticnet_gwas(genotypes_scaled, phenotypes_qc) + results['EN_P'] = pvals + results['EN_Beta'] = effects + results['EN_LOD'] = lod + results['EN_CV'] = cv + models_used.append('EN') + + # Lasso + if include_lasso: + pvals, effects, lod, cv = lasso_gwas(genotypes_scaled, phenotypes_qc) + results['LASSO_P'] = pvals + results['LASSO_Beta'] = effects + results['LASSO_LOD'] = lod + results['LASSO_CV'] = cv + models_used.append('LASSO') + + # Ridge + if include_ridge: + pvals, effects, lod, cv = ridge_gwas(genotypes_scaled, phenotypes_qc) + results['RIDGE_P'] = pvals + results['RIDGE_Beta'] = effects + results['RIDGE_LOD'] = lod + results['RIDGE_CV'] = cv + models_used.append('RIDGE') + + # Random Forest + if include_rf: + pvals, effects, lod, cv = randomforest_gwas(genotypes_scaled, phenotypes_qc) + results['RF_P'] = pvals + results['RF_Beta'] = effects + results['RF_LOD'] = lod + results['RF_CV'] = cv + models_used.append('RF') + + # Create results DataFrame + gwas_df = pd.DataFrame({ + 'Marker': marker_names_qc, + 'Chromosome': chromosomes_qc, + 'Position': positions_qc + }) + + for model in models_used: + for metric in ['P', 'Beta', 'LOD', 'CV']: + col_name = f'{model}_{metric}' + if col_name in results: + gwas_df[col_name] = results[col_name] + + # Add significance columns + bonf_threshold = 0.05 / n_markers_qc + for model in models_used: + if f'{model}_P' in gwas_df.columns: + gwas_df[f'Sig_{model}'] = (gwas_df[f'{model}_P'] < bonf_threshold).astype(int) + + # Consensus significance sig_cols = [c for c in gwas_df.columns if c.startswith('Sig_')] - gwas_df['Consensus'] = gwas_df[sig_cols].sum(axis=1) - gwas_df = gwas_df.sort_values('LR_P').reset_index(drop=True) + if len(sig_cols) > 1: + gwas_df['Consensus_Sig'] = (gwas_df[sig_cols].sum(axis=1) >= 2).astype(int) + elif len(sig_cols) == 1: + gwas_df['Consensus_Sig'] = gwas_df[sig_cols[0]] + else: + gwas_df['Consensus_Sig'] = 0 + + # Sort by LOD score + if 'LR_LOD' in gwas_df.columns: + gwas_df = gwas_df.sort_values('LR_LOD', ascending=False) gwas_df['Rank'] = range(1, len(gwas_df) + 1) - - # Save CSV - csv_path = os.path.join(temp_dir, 'gwas_results.csv') - gwas_df.to_csv(csv_path, index=False) - - # --- Plots --- - sig_set = set(np.where(lr_p < bonf)[0]) - bonf_thresh = -np.log10(bonf) - - p1 = os.path.join(plots_dir, '1_manhattan_lod.png') - plot_manhattan_lod(mnames_qc, chrom_qc, lr_p, lod_lr, sig_set, bonf_thresh, p1) - - p2 = os.path.join(plots_dir, '2_qq_plot.png') - plot_qq(pval_dict_for_qq, p2) - - p3 = os.path.join(plots_dir, '3_ld_decay_mb.png') - ld_stats = plot_ld_decay_mb(geno_qc, chrom_qc, pos_qc, p3) - - p4 = os.path.join(plots_dir, '4_circos.png') - plot_circos_manhattan(mnames_qc, chrom_qc, lr_p, lod_lr, p4) - - p5 = os.path.join(plots_dir, '5_model_comparison.png') - plot_model_comparison(gwas_df, model_results, p5) - - p6 = os.path.join(plots_dir, '6_pca_pheno.png') - plot_pca_pheno(geno_qc, pheno_qc, ids_qc, p6) - - # ZIP - zip_path = os.path.join(temp_dir, 'GWAS_Nexus_Results.zip') + + # Save results + gwas_df.to_csv(os.path.join(results_dir, 'gwas_results.csv'), index=False) + + # Generate plots + sig_indices = gwas_df[gwas_df['Consensus_Sig'] == 1].index.tolist() + + # Manhattan plot + manhattan_path = os.path.join(plots_dir, 'manhattan_lod.png') + if 'LR_P' in gwas_df.columns and 'LR_LOD' in gwas_df.columns: + plot_manhattan_lod( + gwas_df['Marker'].values, + gwas_df['Chromosome'].values, + gwas_df['LR_P'].values, + gwas_df['LR_LOD'].values, + bonf_threshold, + manhattan_path + ) + + # LD decay plot + ld_path = os.path.join(plots_dir, 'ld_decay.png') + ld_stats = plot_ld_decay_mb( + genotypes_qc, + gwas_df['Chromosome'].values, + gwas_df['Position'].values, + ld_path, + max_distance_mb=5 + ) + + # Circos plot + circos_path = os.path.join(plots_dir, 'circos.png') + if 'LR_P' in gwas_df.columns: + plot_circos( + gwas_df['Chromosome'].values, + gwas_df['LR_P'].values, + gwas_df['LR_LOD'].values if 'LR_LOD' in gwas_df.columns else np.zeros(len(gwas_df)), + sig_indices, + circos_path + ) + + # Model comparison + comparison_path = os.path.join(plots_dir, 'model_comparison.png') + plot_model_comparison(gwas_df, comparison_path) + + # Create ZIP file + zip_path = os.path.join(temp_dir, 'GWAS_Results.zip') with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf: - zf.write(csv_path, 'gwas_results.csv') - for pf in [p1,p2,p3,p4,p5,p6]: - if os.path.exists(pf): - zf.write(pf, os.path.join('plots', os.path.basename(pf))) - - # Summary - n_sig_lr = int((lr_p < bonf).sum()) - consensus_n = int((gwas_df['Consensus'] >= 2).sum()) - models_run = ['Linear'] + (['MLM'] if use_mlm else []) + \ - (['LASSO'] if use_lasso else []) + (['ElasticNet'] if use_enet else []) + \ - (['Ridge'] if use_ridge else []) + (['RandomForest'] if use_rf else []) + \ - (['GradBoost'] if use_gb else []) - - ld_mean_r2 = np.mean([v['mean_r2'] for v in ld_stats.values()]) if ld_stats else 0 - ld_mean_dp = np.mean([v['mean_dprime'] for v in ld_stats.values()]) if ld_stats else 0 - - summary = f"""## ✅ GWAS Nexus — Analysis Complete -{fallback_msg} -### 📋 Quality Control -| | Raw | Post-QC | -|---|---|---| -| Samples | {n_samples} | **{len(ids_qc)}** | -| Markers | {n_markers} | **{n_m}** | -| Chromosomes | — | **{len(set(chrom_qc))}** | - -MAF filter: ≥ {maf_thresh:.1f}% · Bonferroni α = {bonf:.2e} - -### 🧬 GWAS Models Completed -| Model | Sig. Markers | -|---|---| -{ chr(10).join(f"| {m} | {int((model_results.get(f'{m}_P' if m != 'Linear' else 'LR_P', np.ones(n_m)) < bonf).sum())} |" for m in models_run) } - -**Consensus (≥2 models):** {consensus_n} markers - -### 📐 LD Statistics -- Mean r²: **{ld_mean_r2:.4f}** -- Mean D': **{ld_mean_dp:.4f}** - -### 🏆 Top 10 Markers -{gwas_df[['Rank','Marker','Chromosome','LR_P','LOD','Consensus']].head(10).to_markdown(index=False)} + for root, _, files in os.walk(results_dir): + for f in files: + fp = os.path.join(root, f) + arc = os.path.relpath(fp, temp_dir) + zf.write(fp, arc) + + # Generate summary report + summary = f""" +## 📊 GWAS Analysis Results + +### QC Summary +| Metric | Value | +|--------|-------| +| Initial Samples | {n_samples_raw} | +| Initial Markers | {n_markers_raw} | +| Samples after QC | **{n_samples_qc}** | +| Markers after QC | **{n_markers_qc}** | +| Missing rate threshold | < {sample_missing:.0f}% (samples), < {marker_missing:.0f}% (markers) | +| MAF threshold | ≥ {maf_threshold:.1f}% | + +### Models Executed +{chr(10).join([f"- {model}" for model in models_used])} + +### Significant Findings +- **Bonferroni threshold**: {bonf_threshold:.2e} +- **Significant markers (consensus)**: {gwas_df['Consensus_Sig'].sum()} + +### LD Statistics +- **Mean r²**: {ld_stats['mean_r2']:.4f} +- **LD pairs analyzed**: {ld_stats['n_pairs']:,} + +### Top 10 Markers (by LR LOD score) +{ gwas_df.head(10)[['Marker', 'Chromosome', 'Position', 'LR_LOD', 'Consensus_Sig']].to_markdown(index=False) if 'LR_LOD' in gwas_df.columns else 'N/A' } ### 📁 Output Files -`gwas_results.csv` · `manhattan_lod.png` · `qq_plot.png` -`ld_decay_mb.png` · `circos.png` · `model_comparison.png` · `pca_pheno.png` +- `gwas_results.csv` - Complete results for all models +- `plots/manhattan_lod.png` - Manhattan plot with LOD scores +- `plots/ld_decay.png` - LD decay plot (distances in Mb) +- `plots/circos.png` - Circos plot visualization +- `plots/model_comparison.png` - Model performance comparison """ - return (summary, p1, p2, p3, p4, p5, zip_path, p6) - + + return (summary, manhattan_path, ld_path, circos_path, + comparison_path, zip_path, "Analysis completed successfully!") + except Exception as e: - return (f"## ❌ Error\n```\n{e}\n\n{traceback.format_exc()}\n```", - None, None, None, None, None, None, None) - -# ═══════════════════════════════════════════════ -# THEME CSS + HTML -# ═══════════════════════════════════════════════ - -THEME_CSS = """ -@import url('https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@300;400;500;600;700&family=JetBrains+Mono:wght@400;500&display=swap'); - -:root { - --bg: #07090F; - --panel: #0D1117; - --card: #111827; - --border: #1F2937; - --text: #E2E8F0; - --muted: #64748B; - --cyan: #06B6D4; - --violet: #8B5CF6; - --emerald: #10B981; - --rose: #F43F5E; - --amber: #F59E0B; -} - -* { font-family: 'Space Grotesk', sans-serif !important; box-sizing: border-box; } - -body, .gradio-container { - background: var(--bg) !important; - color: var(--text) !important; -} - -.gradio-container { max-width: 1400px !important; margin: 0 auto !important; } - -.hero-wrap { - background: linear-gradient(135deg, #07090F 0%, #0f172a 40%, #07090F 100%); - border: 1px solid var(--border); - border-radius: 20px; - padding: 48px 40px 40px; - margin-bottom: 24px; - position: relative; - overflow: hidden; -} -.hero-wrap::before { - content: ''; - position: absolute; inset: 0; - background: radial-gradient(ellipse 60% 50% at 50% 0%, rgba(6,182,212,0.08) 0%, transparent 70%); -} -.hero-tag { - display: inline-block; - background: rgba(6,182,212,0.1); - border: 1px solid rgba(6,182,212,0.3); - color: var(--cyan); - font-size: 11px; font-weight: 600; letter-spacing: 2px; - padding: 4px 12px; border-radius: 999px; - text-transform: uppercase; margin-bottom: 20px; -} -.hero-title { - font-size: clamp(28px, 4vw, 48px); font-weight: 700; - line-height: 1.1; color: var(--text); margin-bottom: 12px; -} -.hero-title span { color: var(--cyan); } -.hero-sub { - font-size: 15px; color: var(--muted); max-width: 600px; line-height: 1.6; -} -.hero-badges { display: flex; gap: 8px; flex-wrap: wrap; margin-top: 20px; } -.badge { - font-size: 11px; font-weight: 600; padding: 4px 10px; - border-radius: 6px; border: 1px solid; -} -.badge-c { color: var(--cyan); border-color: rgba(6,182,212,0.3); background: rgba(6,182,212,0.08); } -.badge-v { color: var(--violet); border-color: rgba(139,92,246,0.3); background: rgba(139,92,246,0.08); } -.badge-e { color: var(--emerald); border-color: rgba(16,185,129,0.3); background: rgba(16,185,129,0.08); } -.badge-r { color: var(--rose); border-color: rgba(244,63,94,0.3); background: rgba(244,63,94,0.08); } -.badge-a { color: var(--amber); border-color: rgba(245,158,11,0.3); background: rgba(245,158,11,0.08); } - -.sec-label { - font-size: 10px; font-weight: 700; letter-spacing: 2px; - text-transform: uppercase; color: var(--muted); - margin: 24px 0 12px; padding-left: 2px; - border-left: 3px solid var(--cyan); padding-left: 10px; -} - -.ctrl-panel { - background: var(--card); - border: 1px solid var(--border); - border-radius: 14px; padding: 20px; - margin-bottom: 12px; -} - -gradio-app, .gr-block, .gr-panel, -div[data-testid="column"], .gradio-column, -.gradio-row, div.svelte-1gfkfd6 { - background: transparent !important; -} - -.gr-form, .gr-box { background: transparent !important; } + import traceback + return (f"## ❌ Error\n```\n{str(e)}\n\n{traceback.format_exc()}\n```", + None, None, None, None, None, None) -label span, .gr-label { color: var(--muted) !important; font-size: 12px !important; } - -input[type=range] { accent-color: var(--cyan) !important; } - -.gr-button-primary { - background: linear-gradient(135deg, var(--cyan), #0284C7) !important; - border: none !important; border-radius: 10px !important; - font-weight: 700 !important; font-size: 14px !important; - color: #07090F !important; letter-spacing: 0.5px; - padding: 14px 28px !important; - transition: opacity 0.2s, transform 0.15s !important; -} -.gr-button-primary:hover { - opacity: 0.9 !important; transform: translateY(-1px) !important; -} - -.result-card { - background: var(--card); border: 1px solid var(--border); - border-radius: 14px; padding: 24px; -} -.result-card h2 { color: var(--cyan) !important; } -.result-card h3 { color: var(--text) !important; border-bottom: 1px solid var(--border); padding-bottom: 6px; } -.result-card table { width: 100%; border-collapse: collapse; } -.result-card th { color: var(--muted); font-size: 11px; font-weight: 600; text-transform: uppercase; letter-spacing: 1px; padding: 8px; border-bottom: 1px solid var(--border); } -.result-card td { padding: 8px; border-bottom: 1px solid rgba(31,41,55,0.5); font-size: 13px; font-family: 'JetBrains Mono', monospace !important; } -.result-card code { background: rgba(6,182,212,0.1); color: var(--cyan); padding: 2px 6px; border-radius: 4px; font-size: 12px; } - -.pipe-info { - background: rgba(6,182,212,0.05); - border: 1px solid rgba(6,182,212,0.15); - border-radius: 12px; padding: 16px; margin-top: 16px; -} -.pipe-info-title { font-size: 11px; font-weight: 700; color: var(--cyan); text-transform: uppercase; letter-spacing: 1.5px; margin-bottom: 10px; } -.pipe-step { display: flex; align-items: center; gap: 10px; margin-bottom: 8px; } -.pipe-dot { width: 6px; height: 6px; border-radius: 50%; background: var(--cyan); flex-shrink: 0; } -.pipe-step span { font-size: 12px; color: var(--muted); } - -.gr-checkbox-label { color: var(--text) !important; font-size: 13px !important; } -.gr-file-label { color: var(--muted) !important; } - -.img-out img { border-radius: 10px; border: 1px solid var(--border); } - -.tab-nav button { color: var(--muted) !important; font-size: 13px !important; } -.tab-nav button.selected { color: var(--cyan) !important; border-bottom-color: var(--cyan) !important; } - -footer { display: none !important; } -""" - -HERO_HTML = """ -
-
Genome-Wide Association Studies
-
GWAS Nexus
-
- Advanced multi-model GWAS platform · Manhattan, Circos, LD Decay (Mb), QQ plots · - 7 statistical models including ML-based approaches · Automated QC with adaptive thresholds -
-
- Linear Regression - Mixed Linear Model - LASSO · ElasticNet · Ridge - Random Forest - Gradient Boosting -
-
-""" - -FMT_HTML = """ -
-
CSV Format
-
-Row 1: ID, Phenotype, Chr
-Row 2+: ID, value, 0/1/2
-Genotypes: 0=AA, 1=AB, 2=BB
-Chr format: 1 or 1:12345678 -
-
-""" - -PIPE_HTML = """ -
-
Pipeline Steps
-
Parse CSV & validate format
-
QC: missing rate + MAF filters
-
Genotype imputation (mean)
-
Run selected GWAS models
-
Generate 6 publication plots
-
Export ZIP with all results
-
-""" - -# ═══════════════════════════════════════════════ +# ══════════════════════════════════════════════════════════════ # GRADIO INTERFACE -# ═══════════════════════════════════════════════ - -with gr.Blocks(css=THEME_CSS, title="GWAS Nexus", theme=gr.themes.Base()) as app: - - gr.HTML(HERO_HTML) - +# ══════════════════════════════════════════════════════════════ + +with gr.Blocks(css=CUSTOM_CSS, title="GWAS Analysis Platform", theme=gr.themes.Soft()) as app: + + # Header + gr.HTML(""" +
+

🧬 GWAS Analysis Platform

+

Comprehensive Genome-Wide Association Study with Multiple Models

+
+ """) + with gr.Row(): - # LEFT COLUMN — Controls - with gr.Column(scale=1, min_width=320): - gr.HTML(FMT_HTML) - - gr.HTML('
Data Input
') - input_file = gr.File(label="Upload CSV", file_types=[".csv"]) - - gr.HTML('
QC Thresholds
') - miss_rate_sample = gr.Slider(10, 100, value=50, step=5, - label="Sample Missing Rate (%)") - miss_rate_marker = gr.Slider(10, 100, value=50, step=5, - label="Marker Missing Rate (%)") - maf_thresh = gr.Slider(0.0, 10.0, value=1.0, step=0.5, - label="MAF Threshold (%)") - - gr.HTML('
Model Selection
') - use_mlm = gr.Checkbox(label="Mixed Linear Model (MLM)", value=True) - use_lasso = gr.Checkbox(label="LASSO Regression", value=True) - use_enet = gr.Checkbox(label="ElasticNet Regression", value=True) - use_ridge = gr.Checkbox(label="Ridge Regression (RidgeCV)", value=True) - use_rf = gr.Checkbox(label="Random Forest", value=False) - use_gb = gr.Checkbox(label="Gradient Boosting", value=False) - - run_btn = gr.Button("⚡ Run GWAS Analysis", variant="primary", size="lg") - - gr.HTML(PIPE_HTML) - - # RIGHT COLUMN — Summary + with gr.Column(scale=1): + # Input section + gr.HTML('
📂 Data Input
') + input_file = gr.File(label="Upload CSV File", file_types=[".csv"]) + + gr.HTML('
⚙️ Quality Control
') + sample_missing = gr.Slider(10, 80, value=50, step=5, + label="Sample Missing Rate Threshold (%)") + marker_missing = gr.Slider(10, 80, value=50, step=5, + label="Marker Missing Rate Threshold (%)") + maf_threshold = gr.Slider(1, 20, value=5, step=1, + label="Minor Allele Frequency Threshold (%)") + + gr.HTML('
🤖 Model Selection
') + with gr.Row(): + include_lr = gr.Checkbox(label="Linear Regression", value=True) + include_mlm = gr.Checkbox(label="Mixed Linear Model", value=True) + with gr.Row(): + include_enet = gr.Checkbox(label="ElasticNet", value=True) + include_lasso = gr.Checkbox(label="Lasso", value=True) + with gr.Row(): + include_ridge = gr.Checkbox(label="Ridge", value=True) + include_rf = gr.Checkbox(label="Random Forest", value=True) + + run_button = gr.Button("🚀 Run GWAS Analysis", variant="primary", size="lg") + + gr.HTML(""" +
+

📋 CSV Format

+

Row 1: Sample IDs | Phenotype | Marker1 (chr:pos) | Marker2 | ...

+

Row 2+: Sample1 | value | 0/1/2 | 0/1/2 | ...

+

Genotype coding: 0=AA, 1=Aa, 2=aa

+
+ """) + with gr.Column(scale=2): - gr.HTML('
Analysis Summary
') - with gr.Column(elem_classes=["result-card"]): - summary_out = gr.Markdown( - "*Upload a CSV file and click **Run GWAS Analysis** to begin.*" - ) - - # ─── Visualizations ─── - gr.HTML('
Visualizations
') - - with gr.Tabs(): - with gr.TabItem("📊 Manhattan + LOD"): - manhattan_out = gr.Image(label="Manhattan Plot with LOD Scores", - elem_classes=["img-out"]) - with gr.TabItem("📈 QQ Plot"): - qq_out = gr.Image(label="QQ Plot — All Models", - elem_classes=["img-out"]) - with gr.TabItem("🔗 LD Decay (Mb)"): - ld_out = gr.Image(label="LD Decay Analysis in Megabases", - elem_classes=["img-out"]) - with gr.TabItem("🌐 Circos Plot"): - circos_out = gr.Image(label="Circos Manhattan Plot", - elem_classes=["img-out"]) - with gr.TabItem("🤖 Model Comparison"): - comp_out = gr.Image(label="Multi-Model Comparison", - elem_classes=["img-out"]) - with gr.TabItem("🔬 PCA + Phenotype"): - pca_out = gr.Image(label="PCA & Phenotype Distribution", - elem_classes=["img-out"]) - - gr.HTML('
Download Results
') - download_out = gr.File(label="⬇ Download Full Results (ZIP)") - - run_btn.click( + # Results section + gr.HTML('
📊 Analysis Summary
') + summary_output = gr.Markdown("*Upload a CSV file and click 'Run GWAS Analysis' to begin*") + + gr.HTML('
📈 Visualizations
') + with gr.Row(): + manhattan_output = gr.Image(label="Manhattan Plot with LOD") + ld_output = gr.Image(label="LD Decay Plot (Mb)") + with gr.Row(): + circos_output = gr.Image(label="Circos Plot") + comparison_output = gr.Image(label="Model Comparison") + + gr.HTML('
⬇️ Download Results
') + download_output = gr.File(label="Download ZIP Archive") + status_output = gr.Textbox(label="Status", interactive=False) + + # Connect button to function + run_button.click( fn=run_gwas_pipeline, - inputs=[input_file, miss_rate_sample, miss_rate_marker, maf_thresh, - use_mlm, use_lasso, use_enet, use_ridge, use_rf, use_gb], - outputs=[summary_out, manhattan_out, qq_out, ld_out, - circos_out, comp_out, download_out, pca_out] + inputs=[input_file, sample_missing, marker_missing, maf_threshold, + include_lr, include_mlm, include_enet, include_lasso, + include_ridge, include_rf], + outputs=[summary_output, manhattan_output, ld_output, circos_output, + comparison_output, download_output, status_output] ) + + # Footer + gr.HTML(""" + + """) if __name__ == "__main__": - app.launch(share=True, show_error=True) \ No newline at end of file + app.launch(share=True, debug=False) \ No newline at end of file