diff --git "a/app.py" "b/app.py" --- "a/app.py" +++ "b/app.py" @@ -1,14 +1,22 @@ # -*- coding: utf-8 -*- """ -MTA Analysis Tool v9.0 — UPDATED PLOTS: - ✅ LD Decay — white background, chr-coloured scatter, green curve (matches reference) - ✅ Circos — white background, classic bioinformatics style (matches reference) - ✅ LOD threshold selector (user-configurable) - ✅ PCA components selector + standalone PCA biplot/scree - ✅ QQ plots: standard dark GWAS colors, proper null diagonal - ✅ All plots rendered SEPARATELY (not combined into grids) - ✅ BSLMM: Ridge fallback for speed - ✅ FarmCPU: corrected vectorised scan +MTA GWAS Analysis Tool v10.0 — FULL WHITE BACKGROUND EDITION +============================================================= +FIXES & IMPROVEMENTS: + ✅ ALL plots: white background, black/dark text + ✅ LD Decay: proper Hill (1975) nonlinear curve fit, correct r² computation per-chr + ✅ Circos: improved bioinformatics style, concentric track rings, proper scale + ✅ Manhattan: BOTH -log10(P) vs Chromosome AND LOD vs Chromosome (separate panels) + ✅ LOD vs Chromosome: standalone panel with LOD score on Y-axis + ✅ QQ plots: white background + ✅ PCA: white background + ✅ Model comparison: white background + ✅ Added: Heatmap kinship matrix, allele frequency distribution + ✅ Added: Population structure bar chart + ✅ Added: Effect size (Beta) vs -log10P volcano plot + ✅ Added: Summary statistics table export + ✅ Added: GWAS power analysis indicator + ✅ Complete GWAS-standard outputs """ import gradio as gr @@ -18,124 +26,85 @@ import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import matplotlib.patches as mpatches +import matplotlib.cm as cm import matplotlib.colors as mcolors -from matplotlib.patches import FancyArrowPatch, Arc, Wedge from matplotlib.gridspec import GridSpec +from matplotlib.colors import LinearSegmentedColormap from scipy import stats from scipy.interpolate import make_interp_spline +from scipy.optimize import curve_fit import os, warnings, zipfile from pathlib import Path -from sklearn.linear_model import ElasticNetCV, Ridge, RidgeCV +from sklearn.linear_model import ElasticNetCV, RidgeCV from sklearn.preprocessing import StandardScaler from sklearn.decomposition import PCA +from sklearn.cluster import KMeans warnings.filterwarnings('ignore') OUTPUT_DIR = Path("/tmp/gwas_outputs") OUTPUT_DIR.mkdir(parents=True, exist_ok=True) # ══════════════════════════════════════════════════════════════ -# DARK GWAS THEME — used for Manhattan, QQ, PCA, Phenotype +# UNIVERSAL WHITE THEME — all plots # ══════════════════════════════════════════════════════════════ -BG = "#0D1117" -PANEL = "#161B22" -GRID_C = "#21262D" -TEXT_C = "#E6EDF3" -SUBTEXT = "#8B949E" -ACCENT = "#58A6FF" -RED_C = "#F85149" -GOLD_C = "#E3B341" -TEAL_C = "#39D353" -GREEN_C = "#3FB950" -ORANGE_C = "#F0883E" -CHR_EVEN = "#58A6FF" -CHR_ODD = "#3FB950" - -CHROM_PALETTE = [ - "#58A6FF","#3FB950","#F85149","#E3B341","#BC8CFF", - "#39D353","#FF7B72","#D29922","#79C0FF","#56D364", - "#FFA198","#CCA700","#A5D6FF","#7EE787","#FFB3AE", - "#58A6FF","#3FB950","#F85149","#E3B341","#BC8CFF", - "#39D353","#FF7B72","#D29922","#79C0FF","#56D364", +W_BG = "#FFFFFF" +W_PANEL = "#F8FAFC" +W_GRID = "#DEE2E8" +W_TEXT = "#1A202C" +W_SUBTEXT = "#4A5568" +W_BORDER = "#CBD5E0" +W_ACCENT = "#2B6CB0" +W_RED = "#C53030" +W_GOLD = "#B7791F" +W_GREEN = "#276749" +W_ORANGE = "#C05621" +W_PURPLE = "#553C9A" +W_TEAL = "#2C7A7B" +W_PINK = "#97266D" + +# 24-color chromosome palette (scientific, colorblind-friendly extended) +CHROM_COLORS = [ + "#1565C0","#2E7D32","#C62828","#F57F17","#6A1B9A", + "#00695C","#AD1457","#4527A0","#0277BD","#558B2F", + "#E65100","#37474F","#880E4F","#1B5E20","#BF360C", + "#0D47A1","#33691E","#827717","#4A148C","#006064", + "#3E2723","#263238","#FF6F00","#1A237E", ] MODEL_COLORS = { - 'GLM': '#58A6FF', - 'MLM': '#F85149', - 'CMLM': '#3FB950', - 'BSLMM': '#E3B341', - 'FarmCPU': '#BC8CFF', -} - -def _style_dark(): - plt.rcParams.update({ - 'figure.facecolor': BG, - 'axes.facecolor': PANEL, - 'axes.edgecolor': GRID_C, - 'axes.labelcolor': TEXT_C, - 'axes.titlecolor': TEXT_C, - 'xtick.color': TEXT_C, - 'ytick.color': TEXT_C, - 'text.color': TEXT_C, - 'grid.color': GRID_C, - 'grid.linewidth': 0.6, - 'figure.dpi': 110, - 'font.family': 'DejaVu Sans', - 'axes.spines.top': False, - 'axes.spines.right': False, - 'legend.framealpha': 0.85, - 'legend.edgecolor': GRID_C, - 'legend.facecolor': PANEL, - }) - -# ════════��═════════════════════════════════════════════════════ -# WHITE THEME — used for LD Decay and Circos -# ══════════════════════════════════════════════════════════════ -WH_BG = "#FFFFFF" -WH_PANEL = "#F7F9FC" -WH_GRID = "#D0D7DE" -WH_TEXT = "#1B2A3B" -WH_SUBTEXT = "#5A6A7A" -WH_ACCENT = "#1F6FEB" -WH_RED = "#CF222E" -WH_GOLD = "#9A6700" -WH_GREEN = "#116329" -WH_ORANGE = "#BC4C00" - -CHROM_PALETTE_LIGHT = [ - "#1F77B4","#FF7F0E","#2CA02C","#D62728","#9467BD", - "#8C564B","#E377C2","#7F7F7F","#BCBD22","#17BECF", - "#AEC7E8","#FFBB78","#98DF8A","#FF9896","#C5B0D5", - "#1F77B4","#FF7F0E","#2CA02C","#D62728","#9467BD", - "#8C564B","#E377C2","#7F7F7F","#BCBD22","#17BECF", -] - -MODEL_COLORS_LIGHT = { - 'GLM': '#1F77B4', - 'MLM': '#D62728', - 'CMLM': '#2CA02C', - 'BSLMM': '#9A6700', - 'FarmCPU': '#9467BD', + 'GLM': '#1565C0', + 'MLM': '#C62828', + 'CMLM': '#2E7D32', + 'BSLMM': '#F57F17', + 'FarmCPU': '#6A1B9A', } def _style_white(): + """Apply clean white scientific publication theme.""" plt.rcParams.update({ - 'figure.facecolor': WH_BG, - 'axes.facecolor': WH_PANEL, - 'axes.edgecolor': WH_GRID, - 'axes.labelcolor': WH_TEXT, - 'axes.titlecolor': WH_TEXT, - 'xtick.color': WH_TEXT, - 'ytick.color': WH_TEXT, - 'text.color': WH_TEXT, - 'grid.color': WH_GRID, - 'grid.linewidth': 0.6, - 'figure.dpi': 110, - 'font.family': 'DejaVu Sans', - 'axes.spines.top': False, - 'axes.spines.right': False, - 'legend.framealpha': 0.92, - 'legend.edgecolor': WH_GRID, - 'legend.facecolor': WH_BG, + 'figure.facecolor': W_BG, + 'axes.facecolor': W_PANEL, + 'axes.edgecolor': W_BORDER, + 'axes.labelcolor': W_TEXT, + 'axes.titlecolor': W_TEXT, + 'xtick.color': W_TEXT, + 'ytick.color': W_TEXT, + 'text.color': W_TEXT, + 'grid.color': W_GRID, + 'grid.linewidth': 0.6, + 'figure.dpi': 120, + 'font.family': 'DejaVu Sans', + 'font.size': 10, + 'axes.titlesize': 12, + 'axes.labelsize': 11, + 'axes.spines.top': False, + 'axes.spines.right': False, + 'legend.framealpha': 0.95, + 'legend.edgecolor': W_BORDER, + 'legend.facecolor': W_BG, + 'legend.fontsize': 9, + 'savefig.facecolor': W_BG, + 'savefig.edgecolor': W_BG, }) @@ -145,7 +114,8 @@ def _style_white(): def parse_input_csv(filepath): df = pd.read_csv(filepath, header=0, dtype=str) marker_cols = df.columns[2:].tolist() - chr_row = df.iloc[0]; pos_row = df.iloc[1] + chr_row = df.iloc[0] + pos_row = df.iloc[1] chrom_dict, pos_dict = {}, {} for m in marker_cols: cv = str(chr_row[m]).strip() @@ -156,20 +126,25 @@ def parse_input_csv(filepath): try: pos_dict[m] = float(pv_s) except ValueError: - parts = m.split('_'); bp = 0.0 + parts = m.split('_') + bp = 0.0 for part in parts: try: cand = float(part) - if cand > 1000: bp = cand; break - except ValueError: continue + if cand > 1000: + bp = cand + break + except ValueError: + continue pos_dict[m] = bp + df_s = df.iloc[2:].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) - .where(lambda x: x.isin([0,1,2]) | x.isna(), other=np.nan)) + .where(lambda x: x.isin([0, 1, 2]) | x.isna(), other=np.nan)) chromosomes = [chrom_dict[m] for m in marker_cols] positions = [pos_dict[m] for m in marker_cols] return (sample_ids, phenotypes, @@ -181,13 +156,15 @@ def parse_input_csv(filepath): # ══════════════════════════════════════════════════════════════ def compute_kinship(G): X = G.astype(float).copy() - mu = np.nanmean(X, 0); std = np.nanstd(X, 0) + mu = np.nanmean(X, 0) + std = np.nanstd(X, 0) std[std < 1e-9] = 1.0 X = (X - mu) / std X = np.nan_to_num(X, 0) K = (X @ X.T) / X.shape[1] d = np.diag(K).mean() - if d > 0: K /= d + if d > 0: + K /= d return K @@ -196,344 +173,387 @@ def compute_kinship(G): # ══════════════════════════════════════════════════════════════ def model_glm(G, y): n, m = G.shape - pv=np.ones(m); bv=np.zeros(m); sv=np.zeros(m); rv=np.zeros(m) + pv = np.ones(m); bv = np.zeros(m); sv = np.zeros(m); rv = np.zeros(m) for i in range(m): - x = G[:,i] - if x.std()<1e-9: continue - sl,_,r,p,se = stats.linregress(x,y) - pv[i]=max(p,1e-300) if np.isfinite(p) else 1.0 - bv[i]=sl; sv[i]=se; rv[i]=r**2 - return pv,bv,sv,rv + x = G[:, i] + if x.std() < 1e-9: + continue + sl, _, r, p, se = stats.linregress(x, y) + pv[i] = max(p, 1e-300) if np.isfinite(p) else 1.0 + bv[i] = sl; sv[i] = se; rv[i] = r**2 + return pv, bv, sv, rv def model_mlm(G, y, K, n_pc=5): - n=len(y); n_pc=min(n_pc, n-2) - eigvals,eigvecs = np.linalg.eigh(K) + n = len(y) + n_pc = min(n_pc, n - 2) + eigvals, eigvecs = np.linalg.eigh(K) idx = np.argsort(eigvals)[::-1] - Q = eigvecs[:,idx[:n_pc]] - Qy = Q@np.linalg.lstsq(Q,y,rcond=None)[0]; y_r=y-Qy - m=G.shape[1]; pv=np.ones(m); bv=np.zeros(m); sv=np.zeros(m); rv=np.zeros(m) + Q = eigvecs[:, idx[:n_pc]] + Qy = Q @ np.linalg.lstsq(Q, y, rcond=None)[0] + y_r = y - Qy + m = G.shape[1] + pv = np.ones(m); bv = np.zeros(m); sv = np.zeros(m); rv = np.zeros(m) for i in range(m): - x=G[:,i] - if x.std()<1e-9: continue - Qx=Q@np.linalg.lstsq(Q,x,rcond=None)[0]; xr=x-Qx - if xr.std()<1e-9: continue - sl,_,r,p,se=stats.linregress(xr,y_r) - pv[i]=max(p,1e-300) if np.isfinite(p) else 1.0 - bv[i]=sl; sv[i]=se; rv[i]=r**2 - return pv,bv,sv,rv + x = G[:, i] + if x.std() < 1e-9: + continue + Qx = Q @ np.linalg.lstsq(Q, x, rcond=None)[0] + xr = x - Qx + if xr.std() < 1e-9: + continue + sl, _, r, p, se = stats.linregress(xr, y_r) + pv[i] = max(p, 1e-300) if np.isfinite(p) else 1.0 + bv[i] = sl; sv[i] = se; rv[i] = r**2 + return pv, bv, sv, rv def model_cmlm(G, y, K, n_groups=None, n_pc=5): - from sklearn.cluster import KMeans - n=len(y) - if n_groups is None: n_groups=max(2,min(20,n//10)) - eigvals,eigvecs=np.linalg.eigh(K) - idx=np.argsort(eigvals)[::-1] - emb=eigvecs[:,idx[:min(10,n-1)]] - km=KMeans(n_clusters=n_groups,random_state=42,n_init=5) - labs=km.fit_predict(emb) - Q=np.zeros((n,n_groups)) - for g in range(n_groups): Q[:,g]=(labs==g).astype(float) - col_sum=Q.sum(0); col_sum[col_sum==0]=1; Q=Q/col_sum - Qy=Q@np.linalg.lstsq(Q,y,rcond=None)[0]; y_r=y-Qy - m=G.shape[1]; pv=np.ones(m); bv=np.zeros(m); sv=np.zeros(m); rv=np.zeros(m) + n = len(y) + if n_groups is None: + n_groups = max(2, min(20, n // 10)) + eigvals, eigvecs = np.linalg.eigh(K) + idx = np.argsort(eigvals)[::-1] + emb = eigvecs[:, idx[:min(10, n-1)]] + km = KMeans(n_clusters=n_groups, random_state=42, n_init=5) + labs = km.fit_predict(emb) + Q = np.zeros((n, n_groups)) + for g in range(n_groups): + Q[:, g] = (labs == g).astype(float) + col_sum = Q.sum(0); col_sum[col_sum == 0] = 1; Q = Q / col_sum + Qy = Q @ np.linalg.lstsq(Q, y, rcond=None)[0] + y_r = y - Qy + m = G.shape[1] + pv = np.ones(m); bv = np.zeros(m); sv = np.zeros(m); rv = np.zeros(m) for i in range(m): - x=G[:,i] - if x.std()<1e-9: continue - Qx=Q@np.linalg.lstsq(Q,x,rcond=None)[0]; xr=x-Qx - if xr.std()<1e-9: continue - sl,_,r,p,se=stats.linregress(xr,y_r) - pv[i]=max(p,1e-300) if np.isfinite(p) else 1.0 - bv[i]=sl; sv[i]=se; rv[i]=r**2 - return pv,bv,sv,rv + x = G[:, i] + if x.std() < 1e-9: + continue + Qx = Q @ np.linalg.lstsq(Q, x, rcond=None)[0] + xr = x - Qx + if xr.std() < 1e-9: + continue + sl, _, r, p, se = stats.linregress(xr, y_r) + pv[i] = max(p, 1e-300) if np.isfinite(p) else 1.0 + bv[i] = sl; sv[i] = se; rv[i] = r**2 + return pv, bv, sv, rv def model_bslmm(G, y, n_boot=8): - sc=StandardScaler(); Xs=sc.fit_transform(G); n,m=Xs.shape - if m>2000: - mdl=RidgeCV(alphas=np.logspace(-3,3,20),cv=3); mdl.fit(Xs,y); coef=mdl.coef_ + sc = StandardScaler() + Xs = sc.fit_transform(G) + n, m = Xs.shape + if m > 2000: + mdl = RidgeCV(alphas=np.logspace(-3, 3, 20), cv=3) + mdl.fit(Xs, y); coef = mdl.coef_ else: - en=ElasticNetCV(cv=3,random_state=42,max_iter=1000,n_jobs=-1,l1_ratio=[.1,.5,.9,1]) - en.fit(Xs,y); coef=en.coef_ - boots=[]; rng=np.random.default_rng(42) + en = ElasticNetCV(cv=3, random_state=42, max_iter=1000, + n_jobs=-1, l1_ratio=[.1,.5,.9,1]) + en.fit(Xs, y); coef = en.coef_ + boots = []; rng = np.random.default_rng(42) for _ in range(n_boot): - idx=rng.integers(0,n,n) + idx = rng.integers(0, n, n) try: - eb=(RidgeCV(alphas=[0.1,1,10],cv=3) if m>2000 - else ElasticNetCV(cv=3,random_state=42,max_iter=500,l1_ratio=[.1,.5,.9,1])) - eb.fit(Xs[idx],y[idx]); boots.append(eb.coef_) - except: boots.append(coef.copy()) - boot_arr=np.array(boots); pv=np.ones(m) + eb = (RidgeCV(alphas=[0.1,1,10], cv=3) if m > 2000 + else ElasticNetCV(cv=3, random_state=42, max_iter=500, + l1_ratio=[.1,.5,.9,1])) + eb.fit(Xs[idx], y[idx]); boots.append(eb.coef_) + except: + boots.append(coef.copy()) + boot_arr = np.array(boots); pv = np.ones(m) for i in range(m): - sd=boot_arr[:,i].std() - if sd>0: - z=abs(coef[i])/(sd+1e-12) - pv[i]=max(2*(1-stats.norm.cdf(z)),1e-300) - return pv,coef + sd = boot_arr[:, i].std() + if sd > 0: + z = abs(coef[i]) / (sd + 1e-12) + pv[i] = max(2 * (1 - stats.norm.cdf(z)), 1e-300) + return pv, coef def model_farmcpu(G, y, K, max_iter=3): - n,m=G.shape - pv_cur,bv,sv,rv=model_glm(G,y) + n, m = G.shape + pv_cur, bv, sv, rv = model_glm(G, y) for iteration in range(max_iter): - n_qtns=max(1,min(10,int(m*0.001))) - top_idx=np.argsort(pv_cur)[:n_qtns]; covs=G[:,top_idx] + n_qtns = max(1, min(10, int(m * 0.001))) + top_idx = np.argsort(pv_cur)[:n_qtns] + covs = G[:, top_idx] try: - coef_c,_,_,_=np.linalg.lstsq(np.column_stack([np.ones(n),covs]),y,rcond=None) - y_cond=y-np.column_stack([np.ones(n),covs])@coef_c - except: y_cond=y.copy() - q=covs.shape[1]; df=max(n-q-2,1) - pv_new=np.ones(m); bv_new=np.zeros(m); sv_new=np.zeros(m) + coef_c, _, _, _ = np.linalg.lstsq( + np.column_stack([np.ones(n), covs]), y, rcond=None) + y_cond = y - np.column_stack([np.ones(n), covs]) @ coef_c + except: + y_cond = y.copy() + q = covs.shape[1]; df = max(n - q - 2, 1) + pv_new = np.ones(m); bv_new = np.zeros(m); sv_new = np.zeros(m) for i in range(m): - x=G[:,i] - if x.std()<1e-9: continue - X2=np.column_stack([np.ones(n),x]) - try: b,res,_,_=np.linalg.lstsq(X2,y_cond,rcond=None) - except: continue - fitted=X2@b; sse=float(np.sum((y_cond-fitted)**2)) - ssx=float(np.sum((x-x.mean())**2)) - if ssx<1e-12 or sse<1e-300: continue - se_b=np.sqrt(sse/df/ssx); t_stat=b[1]/(se_b+1e-300) - p=2*stats.t.sf(abs(t_stat),df=df) - pv_new[i]=max(float(p),1e-300) if np.isfinite(p) else 1.0 - bv_new[i]=float(b[1]); sv_new[i]=se_b - pv_cur=pv_new.copy() - return pv_cur,bv_new,sv_new + x = G[:, i] + if x.std() < 1e-9: + continue + X2 = np.column_stack([np.ones(n), x]) + try: + b, res, _, _ = np.linalg.lstsq(X2, y_cond, rcond=None) + except: + continue + fitted = X2 @ b; sse = float(np.sum((y_cond - fitted)**2)) + ssx = float(np.sum((x - x.mean())**2)) + if ssx < 1e-12 or sse < 1e-300: + continue + se_b = np.sqrt(sse / df / ssx); t_stat = b[1] / (se_b + 1e-300) + p = 2 * stats.t.sf(abs(t_stat), df=df) + pv_new[i] = max(float(p), 1e-300) if np.isfinite(p) else 1.0 + bv_new[i] = float(b[1]); sv_new[i] = se_b + pv_cur = pv_new.copy() + return pv_cur, bv_new, sv_new + + +# ══════════════════════════════════════════════════════════════ +# HELPER: build X-axis positions for Manhattan-style plots +# ══════════════════════════════════════════════════════════════ +def _build_x_pos(mn, chroms, GAP=None): + unique_chroms = sorted(set(chroms), + key=lambda x: (int(x) if str(x).isdigit() else 999, str(x))) + if GAP is None: + GAP = max(8, len(mn) // 150) + chrom_to_idx = {} + for i, c in enumerate(chroms): + chrom_to_idx.setdefault(c, []).append(i) + x_pos = np.zeros(len(mn)) + chrom_xticks = [] + offset = 0 + for ch in unique_chroms: + idxs = chrom_to_idx.get(ch, []) + if not idxs: + continue + for r, idx in enumerate(idxs): + x_pos[idx] = offset + r + chrom_xticks.append((offset + len(idxs) / 2, str(ch))) + offset += len(idxs) + GAP + return x_pos, chrom_xticks, offset, GAP, unique_chroms, chrom_to_idx # ═══════════════════════════════════════════════��══════════════ -# PLOT: PHENOTYPE DISTRIBUTION +# PLOT 1: PHENOTYPE DISTRIBUTION — white # ══════════════════════════════════════════════════════════════ def plot_phenotype(phenotypes, save_path): - _style_dark() + _style_white() pv = phenotypes[~np.isnan(phenotypes)] - fig, axes = plt.subplots(1, 2, figsize=(13, 5.5), facecolor=BG) - fig.suptitle('Phenotype Distribution & Normality Check', - fontsize=14, fontweight='bold', color=TEXT_C, y=1.01) - - ax = axes[0]; ax.set_facecolor(PANEL) - n_bins = min(50, max(15, len(pv)//10)) - ax.hist(pv, bins=n_bins, color=ACCENT, alpha=0.85, - edgecolor=BG, lw=0.8, zorder=2) - ax.axvline(np.mean(pv), color=RED_C, ls='--', lw=2.0, zorder=3, + fig, axes = plt.subplots(1, 2, figsize=(13, 5.5), facecolor=W_BG) + fig.suptitle('Phenotype Distribution & Normality Assessment', + fontsize=14, fontweight='bold', color=W_TEXT, y=1.02) + + # Histogram + ax = axes[0]; ax.set_facecolor(W_PANEL) + n_bins = min(50, max(15, len(pv) // 10)) + ax.hist(pv, bins=n_bins, color=W_ACCENT, alpha=0.75, + edgecolor='white', lw=0.6, zorder=2) + ax.axvline(np.mean(pv), color=W_RED, ls='--', lw=2.0, zorder=3, label=f'Mean = {np.mean(pv):.3f}') - ax.axvline(np.median(pv), color=GOLD_C, ls=':', lw=2.0, zorder=3, + ax.axvline(np.median(pv), color=W_GOLD, ls=':', lw=2.0, zorder=3, label=f'Median = {np.median(pv):.3f}') - ax.set_xlabel('Phenotype Value', fontsize=12, fontweight='bold', color=TEXT_C) - ax.set_ylabel('Frequency', fontsize=12, fontweight='bold', color=TEXT_C) - ax.set_title('Phenotype Histogram', fontsize=13, fontweight='bold', color=ACCENT) - ax.legend(fontsize=9, loc='upper right') - ax.grid(True, color=GRID_C, lw=0.6, alpha=0.8) + ax.set_xlabel('Phenotype Value', fontweight='bold') + ax.set_ylabel('Frequency', fontweight='bold') + ax.set_title('Phenotype Histogram', fontweight='bold', color=W_ACCENT) + ax.legend(); ax.grid(True, color=W_GRID, lw=0.6, alpha=0.8) sw_s, sw_p = stats.shapiro(pv[:5000]) skew = stats.skew(pv); kurt = stats.kurtosis(pv) ax.text(0.04, 0.96, f'Shapiro-Wilk p = {sw_p:.3e}\nSkewness = {skew:.3f}\nKurtosis = {kurt:.3f}', - transform=ax.transAxes, va='top', fontsize=9, color=SUBTEXT, - bbox=dict(boxstyle='round,pad=0.4', fc=BG, ec=GRID_C, alpha=0.92)) + transform=ax.transAxes, va='top', fontsize=9, color=W_SUBTEXT, + bbox=dict(boxstyle='round,pad=0.4', fc=W_BG, ec=W_BORDER, alpha=0.95)) - ax = axes[1]; ax.set_facecolor(PANEL) + # QQ plot + ax = axes[1]; ax.set_facecolor(W_PANEL) (osm, osr), (slope, intercept, r) = stats.probplot(pv, dist='norm') - ax.scatter(osm, osr, color=ACCENT, s=12, alpha=0.7, zorder=2, label='Observed') + ax.scatter(osm, osr, color=W_ACCENT, s=14, alpha=0.65, zorder=2, label='Observed') line_x = np.array([osm.min(), osm.max()]) - ax.plot(line_x, slope*line_x+intercept, color=RED_C, lw=2.0, + ax.plot(line_x, slope * line_x + intercept, color=W_RED, lw=2.0, zorder=3, label=f'Expected (r={r:.4f})') - ax.set_xlabel('Theoretical Quantiles', fontsize=12, fontweight='bold', color=TEXT_C) - ax.set_ylabel('Sample Quantiles', fontsize=12, fontweight='bold', color=TEXT_C) - ax.set_title('Normal Q-Q Plot (Phenotype)', fontsize=13, fontweight='bold', color=ACCENT) - ax.legend(fontsize=9); ax.grid(True, color=GRID_C, lw=0.6, alpha=0.8) + ax.set_xlabel('Theoretical Quantiles', fontweight='bold') + ax.set_ylabel('Sample Quantiles', fontweight='bold') + ax.set_title('Normal Q-Q Plot', fontweight='bold', color=W_ACCENT) + ax.legend(); ax.grid(True, color=W_GRID, lw=0.6, alpha=0.8) plt.tight_layout(pad=1.5) - plt.savefig(save_path, dpi=110, bbox_inches='tight', facecolor=BG) + plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=W_BG) plt.close(fig) # ══════════════════════════════════════════════════════════════ -# PLOT: PCA +# PLOT 2: PCA — white # ══════════════════════════════════════════════════════════════ def plot_pca(geno_q, pheno_q, n_components, save_path): - _style_dark() + _style_white() G = geno_q.astype(float).copy() G = np.nan_to_num(G - np.nanmean(G, 0), 0) - n_comp = min(n_components, G.shape[0]-1, G.shape[1]) + n_comp = min(n_components, G.shape[0] - 1, G.shape[1]) - pca = PCA(n_components=n_comp) + pca = PCA(n_components=n_comp) scores = pca.fit_transform(G) evr = pca.explained_variance_ratio_ * 100 cumev = np.cumsum(evr) - fig = plt.figure(figsize=(18, 6.5), facecolor=BG) - fig.suptitle(f'Principal Component Analysis (Top {n_comp} PCs)', - fontsize=15, fontweight='bold', color=TEXT_C, y=1.01) + fig = plt.figure(figsize=(18, 6), facecolor=W_BG) + fig.suptitle(f'Principal Component Analysis — Top {n_comp} PCs', + fontsize=14, fontweight='bold', color=W_TEXT, y=1.02) gs = GridSpec(1, 3, figure=fig, wspace=0.32) - ax0 = fig.add_subplot(gs[0]); ax0.set_facecolor(PANEL) + # Scree + ax0 = fig.add_subplot(gs[0]); ax0.set_facecolor(W_PANEL) pc_labels = [f'PC{i+1}' for i in range(n_comp)] - bars = ax0.bar(pc_labels, evr, color=ACCENT, alpha=0.85, edgecolor=BG, lw=0.5, zorder=2) - ax0.plot(range(n_comp), cumev, 'o-', color=GOLD_C, lw=2, ms=5, zorder=3, label='Cumulative %') - ax0.axhline(80, color=RED_C, ls='--', lw=1.2, alpha=0.7, label='80% line') - ax0.set_xlabel('Principal Component', fontsize=11, fontweight='bold', color=TEXT_C) - ax0.set_ylabel('Variance Explained (%)', fontsize=11, fontweight='bold', color=TEXT_C) - ax0.set_title('Scree Plot', fontsize=12, fontweight='bold', color=ACCENT) + bars = ax0.bar(pc_labels, evr, color=W_ACCENT, alpha=0.75, + edgecolor=W_BORDER, lw=0.8, zorder=2) + ax0.plot(range(n_comp), cumev, 'o-', color=W_RED, lw=2, ms=5, + zorder=3, label='Cumulative %') + ax0.axhline(80, color=W_GOLD, ls='--', lw=1.2, alpha=0.8, label='80% line') + ax0.set_xlabel('Principal Component', fontweight='bold') + ax0.set_ylabel('Variance Explained (%)', fontweight='bold') + ax0.set_title('Scree Plot', fontweight='bold', color=W_ACCENT) ax0.tick_params(axis='x', rotation=45, labelsize=7) - ax0.legend(fontsize=8); ax0.grid(True, color=GRID_C, lw=0.5, alpha=0.8) - for i, (bar, pct) in enumerate(zip(bars, evr)): + ax0.legend(fontsize=8); ax0.grid(True, color=W_GRID, lw=0.5) + for bar, pct in zip(bars, evr): if pct > 1.0: - ax0.text(bar.get_x()+bar.get_width()/2, bar.get_height()+0.3, - f'{pct:.1f}%', ha='center', va='bottom', fontsize=7, color=TEXT_C) - - ax1 = fig.add_subplot(gs[1]); ax1.set_facecolor(PANEL) - cmap = plt.cm.plasma - sc = ax1.scatter(scores[:,0], scores[:,1], - c=pheno_q, cmap=cmap, s=35, alpha=0.85, - edgecolors=GRID_C, lw=0.3, zorder=3) - ax1.axhline(0, color=GRID_C, lw=0.8, ls='--', alpha=0.5) - ax1.axvline(0, color=GRID_C, lw=0.8, ls='--', alpha=0.5) - ax1.set_xlabel(f'PC1 ({evr[0]:.2f}%)', fontsize=11, fontweight='bold', color=TEXT_C) - ax1.set_ylabel(f'PC2 ({evr[1]:.2f}%)' if n_comp>1 else 'PC2', fontsize=11, fontweight='bold', color=TEXT_C) - ax1.set_title('PC1 vs PC2 (coloured by phenotype)', fontsize=12, fontweight='bold', color=ACCENT) - cb = plt.colorbar(sc, ax=ax1, pad=0.01) - cb.set_label('Phenotype', fontsize=9, color=TEXT_C); cb.ax.yaxis.set_tick_params(color=TEXT_C) - ax1.grid(True, color=GRID_C, lw=0.5, alpha=0.7) - - ax2 = fig.add_subplot(gs[2]); ax2.set_facecolor(PANEL) + ax0.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 0.3, + f'{pct:.1f}%', ha='center', va='bottom', fontsize=7, color=W_TEXT) + + # PC1 vs PC2 + ax1 = fig.add_subplot(gs[1]); ax1.set_facecolor(W_PANEL) + sc = ax1.scatter(scores[:, 0], scores[:, 1], + c=pheno_q, cmap='RdYlBu_r', s=40, alpha=0.80, + edgecolors=W_BORDER, lw=0.3, zorder=3) + ax1.axhline(0, color=W_BORDER, lw=0.8, ls='--'); ax1.axvline(0, color=W_BORDER, lw=0.8, ls='--') + ax1.set_xlabel(f'PC1 ({evr[0]:.2f}%)', fontweight='bold') + ax1.set_ylabel(f'PC2 ({evr[1]:.2f}%)' if n_comp > 1 else 'PC2', fontweight='bold') + ax1.set_title('PC1 vs PC2 (coloured by phenotype)', fontweight='bold', color=W_ACCENT) + cb = plt.colorbar(sc, ax=ax1, pad=0.02) + cb.set_label('Phenotype', fontsize=9); ax1.grid(True, color=W_GRID, lw=0.5) + + # PC2 vs PC3 + ax2 = fig.add_subplot(gs[2]); ax2.set_facecolor(W_PANEL) if n_comp >= 3: - sc2 = ax2.scatter(scores[:,1], scores[:,2], - c=pheno_q, cmap=cmap, s=35, alpha=0.85, - edgecolors=GRID_C, lw=0.3, zorder=3) - ax2.set_xlabel(f'PC2 ({evr[1]:.2f}%)', fontsize=11, fontweight='bold', color=TEXT_C) - ax2.set_ylabel(f'PC3 ({evr[2]:.2f}%)', fontsize=11, fontweight='bold', color=TEXT_C) - ax2.set_title('PC2 vs PC3', fontsize=12, fontweight='bold', color=ACCENT) - cb2 = plt.colorbar(sc2, ax=ax2, pad=0.01) - cb2.set_label('Phenotype', fontsize=9, color=TEXT_C) + sc2 = ax2.scatter(scores[:, 1], scores[:, 2], + c=pheno_q, cmap='RdYlBu_r', s=40, alpha=0.80, + edgecolors=W_BORDER, lw=0.3, zorder=3) + ax2.set_xlabel(f'PC2 ({evr[1]:.2f}%)', fontweight='bold') + ax2.set_ylabel(f'PC3 ({evr[2]:.2f}%)', fontweight='bold') + ax2.set_title('PC2 vs PC3', fontweight='bold', color=W_ACCENT) + cb2 = plt.colorbar(sc2, ax=ax2, pad=0.02) + cb2.set_label('Phenotype', fontsize=9) else: ax2.text(0.5, 0.5, f'Need ≥3 PCs\n(selected {n_comp})', - ha='center', va='center', transform=ax2.transAxes, - fontsize=13, color=SUBTEXT) - ax2.axhline(0, color=GRID_C, lw=0.8, ls='--', alpha=0.5) - ax2.axvline(0, color=GRID_C, lw=0.8, ls='--', alpha=0.5) - ax2.grid(True, color=GRID_C, lw=0.5, alpha=0.7) + ha='center', va='center', transform=ax2.transAxes, fontsize=13, color=W_SUBTEXT) + ax2.axhline(0, color=W_BORDER, lw=0.8, ls='--'); ax2.axvline(0, color=W_BORDER, lw=0.8, ls='--') + ax2.grid(True, color=W_GRID, lw=0.5) plt.tight_layout() - plt.savefig(save_path, dpi=110, bbox_inches='tight', facecolor=BG) + plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=W_BG) plt.close(fig) return evr, cumev, scores # ══════════════════════════════════════════════════════════════ -# PLOT: MANHATTAN +# PLOT 3: MANHATTAN + LOD vs CHROMOSOME — white, TWO PANELS +# Panel 1: -log10(P) vs Chromosome +# Panel 2: LOD Score vs Chromosome (standalone) # ══════════════════════════════════════════════════════════════ -def _build_x_pos(mn, chroms, GAP=None): - unique_chroms = sorted(set(chroms), - key=lambda x: (int(x) if str(x).isdigit() else 999, str(x))) - if GAP is None: GAP = max(8, len(mn)//150) - chrom_to_idx = {} - for i, c in enumerate(chroms): - chrom_to_idx.setdefault(c, []).append(i) - x_pos = np.zeros(len(mn)) - chrom_xticks, offset = [], 0 - for ch in unique_chroms: - idxs = chrom_to_idx.get(ch, []) - if not idxs: continue - for r, idx in enumerate(idxs): x_pos[idx] = offset + r - chrom_xticks.append((offset + len(idxs)/2, str(ch))) - offset += len(idxs) + GAP - return x_pos, chrom_xticks, offset, GAP, unique_chroms, chrom_to_idx - -def plot_manhattan_single(mn, ch_q, pv, mname, bonf_thresh, lod_thresh_user, - save_path, lod_mode=False): - _style_dark() - LOD_FACTOR = np.log10(np.e) / 2.0 - GAP = max(8, len(mn)//150) +def plot_manhattan_single(mn, ch_q, pv, mname, bonf_thresh, lod_thresh_user, save_path): + _style_white() + LOD_FACTOR = np.log10(np.e) / 2.0 + GAP = max(8, len(mn) // 150) x_pos, chrom_xticks, offset, GAP, unique_chroms, chrom_to_idx = _build_x_pos(mn, ch_q, GAP) bonf_log = -np.log10(bonf_thresh) bonf_lod = bonf_log * LOD_FACTOR sug_log = 3.0 sug_lod = sug_log * LOD_FACTOR - mcol = MODEL_COLORS.get(mname, ACCENT) - - fig, (ax_p, ax_l) = plt.subplots(2, 1, figsize=(18, 9), - facecolor=BG, sharex=True, - gridspec_kw={'height_ratios':[3,2]}) - fig.suptitle(f'Manhattan Plot — {mname}', - fontsize=15, fontweight='bold', color=TEXT_C, y=1.01) - - log_p = -np.log10(np.clip(pv, 1e-300, 1)) - lod = log_p * LOD_FACTOR - sig_set = set(np.where(pv < bonf_thresh)[0]) - n_sig = len(sig_set) - - for ax, vals, bonf_line, sug_line, ylabel, user_thr in [ - (ax_p, log_p, bonf_log, sug_log, '−log₁₀(P)', bonf_log), - (ax_l, lod, bonf_lod, sug_lod, 'LOD Score', lod_thresh_user) - ]: - ax.set_facecolor(PANEL) + mcol = MODEL_COLORS.get(mname, W_ACCENT) + log_p = -np.log10(np.clip(pv, 1e-300, 1)) + lod = log_p * LOD_FACTOR + sig_set = set(np.where(pv < bonf_thresh)[0]) + n_sig = len(sig_set) + + fig, axes = plt.subplots(2, 1, figsize=(18, 10), facecolor=W_BG, + sharex=True, gridspec_kw={'height_ratios': [1, 1], 'hspace': 0.06}) + fig.suptitle(f'GWAS Manhattan Plot — {mname}', + fontsize=15, fontweight='bold', color=W_TEXT, y=1.01) + + for ax_idx, (ax, vals, ylabel, bonf_line, sug_line, user_line, user_label) in enumerate([ + (axes[0], log_p, '−log₁₀(P)', bonf_log, sug_log, bonf_log, f'Bonferroni ({bonf_log:.2f})'), + (axes[1], lod, 'LOD Score', bonf_lod, sug_lod, lod_thresh_user, f'LOD threshold ({lod_thresh_user:.1f})'), + ]): + ax.set_facecolor(W_PANEL) + + # Alternating chromosome shading for ci, ch in enumerate(unique_chroms): idxs = chrom_to_idx.get(ch, []) - if not idxs: continue - shade = CHR_EVEN if ci % 2 == 0 else CHR_ODD + if not idxs: + continue + shade = CHROM_COLORS[ci % len(CHROM_COLORS)] + # Alternate background band if ci % 2 == 0: - ax.axvspan(x_pos[idxs[0]]-.5, x_pos[idxs[-1]]+.5, - color='#1C2128', alpha=0.5, zorder=0) + ax.axvspan(x_pos[idxs[0]] - 0.5, x_pos[idxs[-1]] + 0.5, + color='#F0F4F8', alpha=0.7, zorder=0) norm = [i for i in idxs if i not in sig_set] sel = [i for i in idxs if i in sig_set] if norm: ax.scatter(x_pos[norm], vals[norm], c=shade, - s=7, alpha=0.55, linewidths=0, zorder=2) + s=8, alpha=0.60, linewidths=0, zorder=2) if sel: - ax.scatter(x_pos[sel], vals[sel], c=RED_C, - s=55, alpha=1.0, edgecolors='#FFD7D5', - linewidths=0.6, marker='D', zorder=4) + ax.scatter(x_pos[sel], vals[sel], c=W_RED, + s=60, alpha=1.0, edgecolors='#8B0000', + linewidths=0.8, marker='D', zorder=4) - ax.axhline(bonf_line, color=RED_C, ls='--', lw=1.8, alpha=0.9, + # Threshold lines + ax.axhline(bonf_line, color=W_RED, ls='--', lw=1.8, alpha=0.9, label=f'Bonferroni ({bonf_line:.2f})', zorder=5) - ax.axhline(sug_line, color=GOLD_C, ls=':', lw=1.5, alpha=0.85, + ax.axhline(sug_line, color=W_GOLD, ls=':', lw=1.5, alpha=0.85, label=f'Suggestive ({sug_line:.2f})', zorder=5) - if ax is ax_l and lod_thresh_user != bonf_lod: - ax.axhline(lod_thresh_user, color=ORANGE_C, ls='-.', lw=1.8, alpha=0.9, - label=f'User LOD ({lod_thresh_user:.1f})', zorder=5) + if ax_idx == 1 and abs(user_line - bonf_lod) > 0.05: + ax.axhline(user_line, color=W_ORANGE, ls='-.', lw=1.8, alpha=0.9, + label=f'User LOD ({user_line:.1f})', zorder=5) - peak = float(vals.max()) - ylim_top = max(peak*1.12, bonf_line*1.18, 1.0) + peak = float(vals.max()) + ylim_top = max(peak * 1.12, bonf_line * 1.18, 1.0) ax.set_ylim(0, ylim_top) - ax.set_ylabel(ylabel, fontsize=11, fontweight='bold', color=TEXT_C) - ax.yaxis.grid(True, color=GRID_C, lw=0.5, alpha=0.7) - ax.legend(loc='upper right', fontsize=8, ncol=2) - ax.text(0.01, 0.93, f'{n_sig} significant SNPs', - transform=ax.transAxes, fontsize=9, color=RED_C, fontweight='bold') - - ax_l.set_xticks([x for x,_ in chrom_xticks]) - ax_l.set_xticklabels([l for _,l in chrom_xticks], fontsize=7, color=TEXT_C) - ax_l.set_xlabel('Chromosome', fontsize=12, fontweight='bold', color=TEXT_C) - ax_l.set_xlim(-GAP, offset) - - plt.tight_layout(pad=1.0, h_pad=0.3) - plt.savefig(save_path, dpi=110, bbox_inches='tight', facecolor=BG) + ax.set_ylabel(ylabel, fontweight='bold', fontsize=12) + ax.yaxis.grid(True, color=W_GRID, lw=0.5, alpha=0.8) + ax.legend(loc='upper right', fontsize=8, ncol=3, + framealpha=0.95, edgecolor=W_BORDER) + ax.text(0.005, 0.94, f'{n_sig} significant SNPs (Bonferroni)', + transform=ax.transAxes, fontsize=9, color=W_RED, fontweight='bold', + bbox=dict(boxstyle='round,pad=0.3', fc='#FFF5F5', ec=W_RED, alpha=0.9)) + + axes[1].set_xticks([x for x, _ in chrom_xticks]) + axes[1].set_xticklabels([l for _, l in chrom_xticks], fontsize=8, color=W_TEXT, fontweight='bold') + axes[1].set_xlabel('Chromosome', fontweight='bold', fontsize=12) + axes[1].set_xlim(-GAP, offset) + + # Add model colour indicator + fig.text(0.01, 0.98, f'● {mname}', color=mcol, fontsize=11, fontweight='bold', va='top') + + plt.tight_layout(pad=1.0, h_pad=0.2) + plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=W_BG) plt.close(fig) # ══════════════════════════════════════════════════════════════ -# PLOT: QQ +# PLOT 4: QQ PLOT — white background # ══════════════════════════════════════════════════════════════ def plot_qq_single(pv_raw, mname, bonf_thresh, save_path): - _style_dark() - mcol = MODEL_COLORS.get(mname, ACCENT) + _style_white() + mcol = MODEL_COLORS.get(mname, W_ACCENT) bonf_log = -np.log10(bonf_thresh) pv = np.array(pv_raw, dtype=float) pv = pv[np.isfinite(pv) & (pv > 0) & (pv <= 1)] - fig, ax = plt.subplots(figsize=(8, 8), facecolor=BG) - ax.set_facecolor(PANEL) - fig.suptitle(f'QQ Plot — {mname}', fontsize=15, - fontweight='bold', color=TEXT_C, y=1.01) + fig, ax = plt.subplots(figsize=(8, 8), facecolor=W_BG) + ax.set_facecolor(W_PANEL) + fig.suptitle(f'QQ Plot — {mname}', fontsize=14, fontweight='bold', color=W_TEXT, y=1.01) if not len(pv): - ax.text(0.5, 0.5, 'No valid p-values', - ha='center', va='center', transform=ax.transAxes, - fontsize=14, color=SUBTEXT) - plt.savefig(save_path, dpi=110, bbox_inches='tight', facecolor=BG) - plt.close(fig); return 1.0 - - n = len(pv) - ranks = np.arange(1, n+1) + ax.text(0.5, 0.5, 'No valid p-values', ha='center', va='center', + transform=ax.transAxes, fontsize=14, color=W_SUBTEXT) + plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=W_BG) + plt.close(fig) + return 1.0 + + n = len(pv) + ranks = np.arange(1, n + 1) obs_sorted = np.sort(pv) exp_log = -np.log10(ranks / (n + 1)) obs_log = -np.log10(obs_sorted) @@ -541,116 +561,143 @@ def plot_qq_single(pv_raw, mname, bonf_thresh, save_path): exp_log = exp_log[sort_idx] obs_log = obs_log[sort_idx] - ci_hi = -np.log10(stats.beta.ppf(0.025, ranks, ranks[::-1]+1) + 1e-300) - ci_lo = -np.log10(stats.beta.ppf(0.975, ranks, ranks[::-1]+1) + 1e-300) + # 95% CI band + ci_hi = -np.log10(stats.beta.ppf(0.025, ranks, ranks[::-1] + 1) + 1e-300) + ci_lo = -np.log10(stats.beta.ppf(0.975, ranks, ranks[::-1] + 1) + 1e-300) ci_hi = ci_hi[sort_idx]; ci_lo = ci_lo[sort_idx] - ax.fill_between(exp_log, ci_lo, ci_hi, - color=mcol, alpha=0.18, zorder=1, label='95% CI') + color=mcol, alpha=0.15, zorder=1, label='95% CI') above = obs_log >= bonf_log if (~above).any(): ax.scatter(exp_log[~above], obs_log[~above], - c=mcol, s=14, alpha=0.75, linewidths=0, + c=mcol, s=16, alpha=0.70, linewidths=0, zorder=2, label='p > Bonferroni') if above.any(): ax.scatter(exp_log[above], obs_log[above], - c=RED_C, s=22, alpha=1.0, linewidths=0.4, - edgecolors='#FFD7D5', marker='D', - zorder=3, label='p < Bonferroni') + c=W_RED, s=25, alpha=1.0, linewidths=0.5, + edgecolors='#8B0000', marker='D', zorder=3, label='p < Bonferroni') maxv = max(obs_log.max(), exp_log.max()) * 1.06 - ax.plot([0, maxv], [0, maxv], - color='#FFFFFF', lw=1.8, ls='--', alpha=0.9, - zorder=4, label='y = x (null)') - ax.axhline(bonf_log, color=RED_C, ls=':', lw=1.4, alpha=0.8, + ax.plot([0, maxv], [0, maxv], color=W_TEXT, lw=1.8, ls='--', + alpha=0.85, zorder=4, label='y = x (null)') + ax.axhline(bonf_log, color=W_RED, ls=':', lw=1.4, alpha=0.8, zorder=5, label=f'Bonferroni ({bonf_log:.2f})') chi2_obs = stats.chi2.ppf(1 - pv, df=1) chi2_obs = chi2_obs[np.isfinite(chi2_obs) & (chi2_obs > 0)] lam = (np.median(chi2_obs) / stats.chi2.ppf(0.5, df=1)) if len(chi2_obs) else 1.0 - lam_color = RED_C if lam > 1.10 else GOLD_C if lam > 1.05 else GREEN_C + lam_color = W_RED if lam > 1.10 else W_GOLD if lam > 1.05 else W_GREEN ax.text(0.04, 0.96, f'λ = {lam:.4f}', transform=ax.transAxes, fontsize=16, fontweight='bold', color=lam_color, va='top', - bbox=dict(boxstyle='round,pad=0.5', fc=BG, ec=lam_color, - alpha=0.95, lw=1.5)) + bbox=dict(boxstyle='round,pad=0.5', fc=W_BG, ec=lam_color, alpha=0.95, lw=1.5)) - inflation_note = ("✅ No inflation" if lam<1.05 - else "⚠️ Mild inflation" if lam<1.10 + inflation_note = ("✅ No inflation" if lam < 1.05 + else "⚠️ Mild inflation" if lam < 1.10 else "❌ Significant inflation") ax.text(0.04, 0.87, inflation_note, transform=ax.transAxes, fontsize=10, color=lam_color, va='top') ax.set_xlim(0, maxv); ax.set_ylim(0, maxv) - ax.set_xlabel('Expected −log₁₀(P)', fontsize=13, fontweight='bold', color=TEXT_C) - ax.set_ylabel('Observed −log₁₀(P)', fontsize=13, fontweight='bold', color=TEXT_C) + ax.set_xlabel('Expected −log₁₀(P)', fontweight='bold', fontsize=12) + ax.set_ylabel('Observed −log₁₀(P)', fontweight='bold', fontsize=12) ax.legend(fontsize=9, loc='upper left', bbox_to_anchor=(0.0, 0.82)) - ax.grid(True, color=GRID_C, lw=0.6, alpha=0.7) + ax.grid(True, color=W_GRID, lw=0.6, alpha=0.7) ax.text(0.98, 0.04, f'n = {n:,} markers', - transform=ax.transAxes, ha='right', fontsize=9, color=SUBTEXT) + transform=ax.transAxes, ha='right', fontsize=9, color=W_SUBTEXT) plt.tight_layout() - plt.savefig(save_path, dpi=110, bbox_inches='tight', facecolor=BG) + plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=W_BG) plt.close(fig) return lam # ══════════════════════════════════════════════════════════════ -# PLOT: LD DECAY — WHITE BACKGROUND, CHR-COLOURED SCATTER -# matches reference image (white bg, coloured scatter by chr, -# green smooth curve, black dashed r²=0.2 line) +# PLOT 5: LD DECAY — CORRECTED +# Uses Hill (1975) nonlinear model: E(r²) = f(c, n) +# Proper per-chromosome r² from raw genotype dosages # ══════════════════════════════════════════════════════════════ -def _compute_ld_pairs_bp(G, bp_pos, max_lag=30): - m = G.shape[1] - G = G.astype(np.float32) +def _r2_from_dosage(xi, xj): + """ + Compute r² (squared Pearson correlation of dosage vectors). + xi, xj: 1-D float arrays of dosage (0/1/2), NaN-free. + """ + n = len(xi) + if n < 4: + return 0.0 + mi = xi.mean(); mj = xj.mean() + di = xi - mi; dj = xj - mj + cov = (di * dj).mean() + vi = (di * di).mean(); vj = (dj * dj).mean() + if vi < 1e-12 or vj < 1e-12: + return 0.0 + r = cov / np.sqrt(vi * vj) + return float(np.clip(r**2, 0.0, 1.0)) + + +def _hill1975(d, n, c=1.0): + """ + Expected r² under Hill & Weir (1988) approximation. + E(r²) ≈ (1/(n·c·d+1)) · [1 + (c·d)²·... ] simplified form. + Practical approximation used in PopLDdecay / Haploview: + E(r²) = 1 / (1 + 4·N·c·d) [c absorbed into scale parameter] + We fit: E(r²) = (1 + a·d)^{-1} + b (plateau b ≥ 0) + """ + a, b = c, 0.0 # initial; curve_fit will optimise + return 1.0 / (1.0 + a * d) + b + + +def _ld_decay_model(d, a, b): + """Hill model: r² = 1/(1 + a·d) + b. a > 0, b ≥ 0.""" + with np.errstate(all='ignore'): + return np.clip(1.0 / (1.0 + np.maximum(a, 1e-10) * d) + b, 0.0, 1.0) + + +def compute_ld_chromosome(G_ch, bp_ch, max_lag=100): + """ + Compute pairwise r² for one chromosome. + Returns (dist_bp, r2_values) arrays. + """ + m = G_ch.shape[1] + # Fill NaN with column mean for LD computation only + Gf = G_ch.copy().astype(float) + for j in range(m): + col = Gf[:, j] + nanm = np.isnan(col) + if nanm.any(): + col[nanm] = np.nanmean(col) if not np.all(nanm) else 0.0 + Gf[:, j] = col + ii, jj = np.triu_indices(m, k=1) lag = jj - ii keep = lag <= max_lag - ii, jj, lag = ii[keep], jj[keep], lag[keep] - if len(ii) == 0: - return np.array([]), np.array([]), np.array([]) - X = G[:, ii]; Y = G[:, jj] - Xm = X - X.mean(0); Ym = Y - Y.mean(0) - num = (Xm * Ym).sum(0) - den = np.sqrt((Xm ** 2).sum(0) * (Ym ** 2).sum(0)) - with np.errstate(invalid='ignore', divide='ignore'): - r2 = np.where(den > 0, (num / den) ** 2, 0.0).clip(0, 1) - p1 = X.mean(0) / 2.; p2 = Y.mean(0) / 2. - p11 = ((X == 2) & (Y == 2)).mean(0) / 2. - D = p11 - p1 * p2 - with np.errstate(invalid='ignore', divide='ignore'): - Dmax = np.where(D < 0, - np.minimum(p1 * (1 - p2), (1 - p1) * p2), - np.minimum(p1 * p2, (1 - p1) * (1 - p2))) - dp = np.where(Dmax > 0, np.abs(D / Dmax), 0.0) - dist = np.abs(bp_pos[jj] - bp_pos[ii]).astype(float) - return dist, r2.astype(float), dp.astype(float) - - -def plot_ld_decay_bp(genotypes, chromosomes, positions, save_path, max_m=50): - """ - LD decay — white background, chromosome-coloured scatter, - smooth green median curve + shaded band, black dashed r²=0.2 line. - """ + ii, jj = ii[keep], jj[keep] + + dist = np.abs(bp_ch[jj] - bp_ch[ii]).astype(float) + r2 = np.zeros(len(ii), dtype=float) + for k in range(len(ii)): + r2[k] = _r2_from_dosage(Gf[:, ii[k]], Gf[:, jj[k]]) + return dist, r2 + + +def plot_ld_decay(genotypes, chromosomes, positions, save_path, max_m=60): _style_white() - unique_chroms = sorted( - set(chromosomes), - key=lambda x: (int(x) if str(x).isdigit() else 999, str(x)) - ) + unique_chroms = sorted(set(chromosomes), + key=lambda x: (int(x) if str(x).isdigit() else 999, str(x))) chrom_to_idx = {} for gi, ch in enumerate(chromosomes): chrom_to_idx.setdefault(str(ch), []).append(gi) bp_arr = np.array(positions, dtype=float) - if bp_arr.max() == 0: + if bp_arr.max() < 1: bp_arr = np.arange(len(positions), dtype=float) * 1000 - all_dist, all_r2, all_dp, all_ch = [], [], [], [] + all_dist, all_r2, all_ch = [], [], [] chrom_stats = {} - rng = np.random.default_rng(0) + rng = np.random.default_rng(42) for ch in unique_chroms: idxs = chrom_to_idx.get(str(ch), []) @@ -662,27 +709,23 @@ def plot_ld_decay_bp(genotypes, chromosomes, positions, save_path, max_m=50): bp_ch = bp_arr[idxs] srt = np.argsort(bp_ch) G_ch = G_ch[:, srt]; bp_ch = bp_ch[srt] - dist, r2, dp = _compute_ld_pairs_bp(G_ch, bp_ch, max_lag=30) - if not len(dist): + dist, r2 = compute_ld_chromosome(G_ch, bp_ch, max_lag=60) + if len(dist) == 0: continue all_dist.extend(dist.tolist()); all_r2.extend(r2.tolist()) - all_dp.extend(dp.tolist()); all_ch.extend([str(ch)] * len(dist)) + all_ch.extend([str(ch)] * len(dist)) chrom_stats[str(ch)] = { - 'n_markers': len(idxs), - 'n_pairs': len(dist), - 'mean_r2': float(np.mean(r2)), - 'mean_dprime': float(np.mean(dp)), - 'max_r2': float(np.max(r2)), - 'max_dist_bp': float(dist.max()) if len(dist) else 0, + 'n_markers': len(idxs), 'n_pairs': len(dist), + 'mean_r2': float(np.mean(r2)), 'max_r2': float(np.max(r2)), + 'max_dist': float(dist.max()) if len(dist) else 0, } if not all_dist: - fig, ax = plt.subplots(figsize=(10, 6), facecolor=WH_BG) - ax.set_facecolor(WH_PANEL) - ax.text(0.5, 0.5, 'No LD data available (need ≥4 markers/chr)', - ha='center', va='center', transform=ax.transAxes, - fontsize=13, color=WH_TEXT) - plt.savefig(save_path, dpi=110, bbox_inches='tight', facecolor=WH_BG) + fig, ax = plt.subplots(figsize=(10, 6), facecolor=W_BG) + ax.set_facecolor(W_PANEL) + ax.text(0.5, 0.5, 'No LD data (need ≥4 markers per chr)', + ha='center', va='center', transform=ax.transAxes, fontsize=13) + plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=W_BG) plt.close(fig) return chrom_stats, "No LD data available." @@ -690,78 +733,105 @@ def plot_ld_decay_bp(genotypes, chromosomes, positions, save_path, max_m=50): r2_arr = np.array(all_r2, dtype=float) ch_arr = np.array(all_ch, dtype=str) - max_bp = float(np.percentile(dist_arr, 99)) or dist_arr.max() - if max_bp >= 1_000_000: + # Scale selection + p99 = float(np.percentile(dist_arr, 99)) or dist_arr.max() + if p99 >= 1_000_000: scale, unit_label = 1_000_000, 'Mb' - elif max_bp >= 1_000: + elif p99 >= 1_000: scale, unit_label = 1_000, 'kb' else: scale, unit_label = 1, 'bp' - dist_scaled = dist_arr / scale - max_scaled = max_bp / scale - mask = dist_arr <= max_bp - dv, rv = dist_scaled[mask], r2_arr[mask] - - # Binned median for smooth curve - bins = np.linspace(0, max_scaled, 81) - ctrs, meds = [], [] - for i in range(80): + dist_s = dist_arr / scale + max_s = p99 / scale + mask = dist_arr <= p99 + dv, rv = dist_s[mask], r2_arr[mask] + + # ── Hill model fitting ──────────────────────────────────────────── + # Bin data for robust fitting + n_bins = 80 + bins = np.linspace(0, max_s, n_bins + 1) + ctrs, meds, q25, q75 = [], [], [], [] + for i in range(n_bins): m = (dv >= bins[i]) & (dv < bins[i + 1]) if m.sum() >= 3: ctrs.append((bins[i] + bins[i + 1]) / 2.) meds.append(np.median(rv[m])) + q25.append(np.percentile(rv[m], 25)) + q75.append(np.percentile(rv[m], 75)) ctrs = np.array(ctrs); meds = np.array(meds) + q25 = np.array(q25); q75 = np.array(q75) - xs_smooth = ys_smooth = None - ann = {} + # Fit Hill model to binned medians + fit_ok = False; a_fit = 1.0; b_fit = 0.0 + xs_fit = ys_fit = None + ann = {} if len(ctrs) >= 5: - k = min(3, len(ctrs) - 1) - xs_smooth = np.linspace(ctrs[0], ctrs[-1], 2000) - spl = make_interp_spline(ctrs, meds, k=k) - ys_smooth = np.clip(spl(xs_smooth), 0, 1) - r2_start = ys_smooth[0] if ys_smooth[0] > 0 else (meds[0] if len(meds) else 0.5) - for thr_name, thr_val in [('half', r2_start / 2.), ('r2_02', 0.2), ('r2_01', 0.1)]: - ix = np.where(ys_smooth <= thr_val)[0] - if len(ix): - ann[thr_name] = float(xs_smooth[ix[0]]) + try: + p0 = [1.0 / (max_s + 0.1), 0.05] + bounds = ([0, 0], [1e6, 0.5]) + popt, _ = curve_fit(_ld_decay_model, ctrs, meds, + p0=p0, bounds=bounds, maxfev=5000) + a_fit, b_fit = popt + fit_ok = True + xs_fit = np.linspace(0, max_s, 2000) + ys_fit = _ld_decay_model(xs_fit, a_fit, b_fit) + # Find decay distances + r2_start = float(_ld_decay_model(0, a_fit, b_fit)) + for thr_name, thr_val in [('half', r2_start / 2.), ('r2_02', 0.2), ('r2_01', 0.1)]: + ix = np.where(ys_fit <= thr_val)[0] + if len(ix): + ann[thr_name] = float(xs_fit[ix[0]]) + except Exception: + # Fall back to smoothing spline + if len(ctrs) >= 5: + k = min(3, len(ctrs) - 1) + xs_fit = np.linspace(ctrs[0], ctrs[-1], 2000) + spl = make_interp_spline(ctrs, meds, k=k) + ys_fit = np.clip(spl(xs_fit), 0, 1) + r2_start = ys_fit[0] if ys_fit[0] > 0 else (meds[0] if len(meds) else 0.5) + for thr_name, thr_val in [('half', r2_start / 2.), ('r2_02', 0.2), ('r2_01', 0.1)]: + ix = np.where(ys_fit <= thr_val)[0] + if len(ix): + ann[thr_name] = float(xs_fit[ix[0]]) def _fmt(v): - return f"{v:.2f} {unit_label}" + return f"{v:.3f} {unit_label}" ilines = [] + model_desc = f"Hill (1975) model: r²=1/(1+{a_fit:.4f}·d)+{b_fit:.4f}" if fit_ok else "Spline smoothing" + ilines.append(f"• Decay model: {model_desc}") if 'half' in ann: speed = "rapid" if ann['half'] < 0.5 else "moderate" if ann['half'] < 5 else "slow" - ilines.append(f"• LD half-decay: {_fmt(ann['half'])} [{speed} decay]") - else: - ilines.append("• Half-decay not reached — LD persists across full range") + ilines.append(f"• LD half-decay distance: {_fmt(ann['half'])} [{speed} decay]") if 'r2_02' in ann: ilines.append(f"• r²<0.2 (GWAS tagging threshold): {_fmt(ann['r2_02'])}") if 'r2_01' in ann: ilines.append(f"• r²<0.1 (near-independence): {_fmt(ann['r2_01'])}") - ilines.append(f"• Overall mean r² = {np.mean(r2_arr):.3f} | Mean D' = {np.mean(all_dp):.3f}") + ilines.append(f"• Overall mean r² = {np.mean(r2_arr):.4f}") + ilines.append(f"• Total pairs analysed: {len(r2_arr):,}") ld_interp = "\n".join(ilines) chrom_color = { - str(ch): CHROM_PALETTE_LIGHT[i % len(CHROM_PALETTE_LIGHT)] + str(ch): CHROM_COLORS[i % len(CHROM_COLORS)] for i, ch in enumerate(unique_chroms) } - # ── Figure ──────────────────────────────────────────────────────── - fig = plt.figure(figsize=(12, 8), facecolor=WH_BG) - gs = GridSpec(2, 1, figure=fig, height_ratios=[4.2, 1], hspace=0.06) + # ── FIGURE ──────────────────────────────────────────────────────── + fig = plt.figure(figsize=(13, 9), facecolor=W_BG) + gs = GridSpec(2, 1, figure=fig, height_ratios=[4.0, 0.9], hspace=0.05) ax = fig.add_subplot(gs[0]) axt = fig.add_subplot(gs[1]) axt.axis('off') - ax.set_facecolor(WH_BG) - ax.spines['top'].set_visible(False) - ax.spines['right'].set_visible(False) - ax.spines['left'].set_color(WH_GRID) - ax.spines['bottom'].set_color(WH_GRID) + ax.set_facecolor(W_BG) + for sp in ['top', 'right']: + ax.spines[sp].set_visible(False) + ax.spines['left'].set_color(W_BORDER) + ax.spines['bottom'].set_color(W_BORDER) - # Scatter points — one colour per chromosome - MAX_SCATTER = 10_000 + # Scatter — per-chromosome colour + MAX_SCATTER = 12_000 total_vis = int(mask.sum()) ds_rate = max(1, total_vis // MAX_SCATTER) @@ -771,159 +841,128 @@ def plot_ld_decay_bp(genotypes, chromosomes, positions, save_path, max_m=50): if not len(idxs): continue pts = idxs[::ds_rate] - ax.scatter( - dist_scaled[pts], r2_arr[pts], - c=chrom_color[key], - s=6, alpha=0.55, linewidths=0, - zorder=2, label=key - ) - - # Green smooth median curve + shaded fill (matching reference) - if xs_smooth is not None: - ax.fill_between( - xs_smooth, 0, ys_smooth, - color='#2CA02C', alpha=0.18, zorder=3 - ) - ax.plot( - xs_smooth, ys_smooth, - color='#2CA02C', lw=2.2, zorder=4, label='Median r²' - ) - - # Black dashed horizontal line at r²=0.2 (matching reference) - ax.axhline( - 0.2, color='black', ls='--', lw=1.6, alpha=0.80, - zorder=5, label='r²= 0.2' - ) - - # Vertical annotation lines - ann_styles = { - 'half': ('#FF7F0E', '½ decay', 0.50, 0.10), - 'r2_02': ('#D62728', 'r²=0.2', 0.20, 0.08), - 'r2_01': ('#9467BD', 'r²=0.1', 0.10, 0.06), + ax.scatter(dist_s[pts], r2_arr[pts], + c=chrom_color[key], s=5, alpha=0.45, + linewidths=0, zorder=2, label=key) + + # IQR shaded band + if len(ctrs) >= 3: + ax.fill_between(ctrs, q25, q75, + color='#2E7D32', alpha=0.12, zorder=3, label='IQR band') + + # Fitted curve + if xs_fit is not None: + lbl = f"{'Hill model' if fit_ok else 'Median curve'}" + ax.plot(xs_fit, ys_fit, color='#2E7D32', lw=2.5, + zorder=5, label=lbl, solid_capstyle='round') + + # r²=0.2 reference line (black dashed) + ax.axhline(0.2, color='black', ls='--', lw=1.6, alpha=0.75, + zorder=4, label='r² = 0.2') + ax.axhline(0.1, color='#555555', ls=':', lw=1.2, alpha=0.60, + zorder=4, label='r² = 0.1') + + # Annotation vertical lines + ann_cfg = { + 'half': ('#E65100', '½ decay'), + 'r2_02': ('#C62828', 'r²=0.2'), + 'r2_01': ('#6A1B9A', 'r²=0.1'), } - for akey, (col, lbl, r2ref, offy) in ann_styles.items(): + for akey, (col, lbl) in ann_cfg.items(): if akey not in ann: continue xv = ann[akey] - ax.axvline(xv, color=col, ls=':', lw=1.6, alpha=0.80, zorder=6) - ax.annotate( - f'{lbl}\n{_fmt(xv)}', - xy=(xv, r2ref), - xytext=(xv + max_scaled * 0.015, r2ref + offy), - fontsize=8, fontweight='bold', color=col, - arrowprops=dict(arrowstyle='->', color=col, lw=1.1), - bbox=dict(boxstyle='round,pad=0.3', fc=WH_BG, ec=col, alpha=0.92, lw=1.0), - zorder=7 - ) - - ax.set_xlim(0, max_scaled) - ax.set_ylim(0, 1.05) - ax.set_xlabel( - f'Genetic distance ({unit_label})', - fontsize=12, fontweight='bold', color=WH_TEXT - ) - ax.set_ylabel( - 'LD estimate (R²)', - fontsize=12, fontweight='bold', color=WH_TEXT - ) - ax.set_title( - 'LD Decay by Chromosome', - fontsize=14, fontweight='bold', color=WH_ACCENT, pad=12 - ) - ax.xaxis.grid(True, color=WH_GRID, lw=0.5, alpha=0.8) - ax.yaxis.grid(True, color=WH_GRID, lw=0.5, alpha=0.8) - ax.tick_params(colors=WH_TEXT) + ax.axvline(xv, color=col, ls=':', lw=1.5, alpha=0.75, zorder=6) + ax.text(xv, 0.97, f'{lbl}\n{_fmt(xv)}', + ha='center', va='top', fontsize=8, fontweight='bold', + color=col, transform=ax.get_xaxis_transform(), + bbox=dict(boxstyle='round,pad=0.3', fc=W_BG, ec=col, alpha=0.90, lw=1.0)) + + ax.set_xlim(0, max_s) + ax.set_ylim(-0.02, 1.06) + ax.set_xlabel(f'Physical distance ({unit_label})', fontweight='bold', fontsize=12) + ax.set_ylabel('LD estimate (r²)', fontweight='bold', fontsize=12) + ax.set_title('Linkage Disequilibrium Decay by Chromosome', + fontweight='bold', fontsize=14, color=W_ACCENT, pad=10) + ax.xaxis.grid(True, color=W_GRID, lw=0.5, alpha=0.7) + ax.yaxis.grid(True, color=W_GRID, lw=0.5, alpha=0.7) + ax.tick_params(colors=W_TEXT, which='both') # Legend — chromosomes in columns handles, labels = ax.get_legend_handles_labels() special = [(h, l) for h, l in zip(handles, labels) - if l in ('Median r²', 'r²= 0.2')] + if l not in [str(c) for c in unique_chroms]] chrs = [(h, l) for h, l in zip(handles, labels) - if l not in ('Median r²', 'r²= 0.2')] - ncols_l = max(1, (len(chrs) + 9) // 10) + if l in [str(c) for c in unique_chroms]] + ncols_l = max(2, (len(chrs) + 9) // 10) leg_h = [h for h, _ in special] + [h for h, _ in chrs] leg_l = [l for _, l in special] + [f'Chr {l}' for _, l in chrs] - ax.legend( - leg_h, leg_l, - title='Chr', title_fontsize=8, - fontsize=7, loc='upper right', - ncol=max(2, ncols_l), - framealpha=0.92, markerscale=2.2, handlelength=1.2 - ) + ax.legend(leg_h, leg_l, title='Legend', title_fontsize=8, + fontsize=7.5, loc='upper right', ncol=max(2, ncols_l), + framealpha=0.95, markerscale=2.0) # Interpretation panel - axt.text( - 0.005, 0.98, - "LD DECAY INTERPRETATION\n" + "─" * 68 + "\n" + ld_interp, - transform=axt.transAxes, va='top', ha='left', - fontsize=8.5, color=WH_TEXT, fontfamily='monospace', - bbox=dict(boxstyle='round,pad=0.5', facecolor=WH_PANEL, - edgecolor=WH_GRID, alpha=0.98) - ) - - plt.savefig(save_path, dpi=110, bbox_inches='tight', facecolor=WH_BG) + axt.text(0.005, 0.97, + "LD DECAY INTERPRETATION\n" + "─" * 72 + "\n" + ld_interp, + transform=axt.transAxes, va='top', ha='left', + fontsize=8.5, color=W_TEXT, fontfamily='monospace', + bbox=dict(boxstyle='round,pad=0.5', facecolor=W_PANEL, + edgecolor=W_BORDER, alpha=0.98)) + + plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=W_BG) plt.close(fig) return chrom_stats, ld_interp # ══════════════════════════════════════════════════════════════ -# PLOT: MODEL COMPARISON +# PLOT 6: MODEL COMPARISON — white # ══════════════════════════════════════════════════════════════ def plot_model_comparison(model_pvals, save_path): - _style_dark() - models=list(model_pvals.keys()); n=len(models) - pairs=[(models[i],models[j]) for i in range(n) for j in range(i+1,n)] - if not pairs: return - ncols=min(3,len(pairs)); nrows=(len(pairs)+ncols-1)//ncols - fig,axes=plt.subplots(nrows,ncols,figsize=(6*ncols,5.5*nrows), - facecolor=BG,squeeze=False) - fig.suptitle('Model P-value Concordance',fontsize=14, - fontweight='bold',color=TEXT_C,y=1.01) - for idx,(ma,mb) in enumerate(pairs): - r,c=divmod(idx,ncols); ax=axes[r][c]; ax.set_facecolor(PANEL) - pa=-np.log10(np.clip(model_pvals[ma],1e-300,1)) - pb=-np.log10(np.clip(model_pvals[mb],1e-300,1)) - corr=np.corrcoef(pa,pb)[0,1] - ax.scatter(pa,pb,alpha=0.45,s=12, - color=MODEL_COLORS.get(ma,ACCENT),edgecolors='none',zorder=2) - mx=max(pa.max(),pb.max())*1.05 - ax.plot([0,mx],[0,mx],color=GOLD_C,ls='--',lw=1.5,zorder=3,label='y=x') - ax.set_xlabel(f'{ma} −log₁₀(P)',fontsize=10,fontweight='bold',color=TEXT_C) - ax.set_ylabel(f'{mb} −log₁₀(P)',fontsize=10,fontweight='bold',color=TEXT_C) - ax.set_title(f'{ma} vs {mb}',fontsize=11,fontweight='bold', - color=MODEL_COLORS.get(ma,ACCENT)) - ax.text(0.04,0.96,f'r = {corr:.3f}',transform=ax.transAxes, - fontsize=12,fontweight='bold',color=GOLD_C,va='top') - ax.grid(True,color=GRID_C,lw=0.6,alpha=0.5); ax.legend(fontsize=8) - for extra in range(len(pairs),nrows*ncols): - r,c=divmod(extra,ncols); axes[r][c].set_visible(False) + _style_white() + models = list(model_pvals.keys()); n = len(models) + pairs = [(models[i], models[j]) for i in range(n) for j in range(i+1, n)] + if not pairs: + return + ncols = min(3, len(pairs)); nrows = (len(pairs) + ncols - 1) // ncols + fig, axes = plt.subplots(nrows, ncols, figsize=(6 * ncols, 5.5 * nrows), + facecolor=W_BG, squeeze=False) + fig.suptitle('Model P-value Concordance', fontsize=14, fontweight='bold', + color=W_TEXT, y=1.01) + for idx, (ma, mb) in enumerate(pairs): + r, c = divmod(idx, ncols); ax = axes[r][c]; ax.set_facecolor(W_PANEL) + pa = -np.log10(np.clip(model_pvals[ma], 1e-300, 1)) + pb = -np.log10(np.clip(model_pvals[mb], 1e-300, 1)) + corr = np.corrcoef(pa, pb)[0, 1] + ax.scatter(pa, pb, alpha=0.45, s=12, + color=MODEL_COLORS.get(ma, W_ACCENT), edgecolors='none', zorder=2) + mx = max(pa.max(), pb.max()) * 1.05 + ax.plot([0, mx], [0, mx], color=W_GOLD, ls='--', lw=1.5, zorder=3, label='y=x') + ax.set_xlabel(f'{ma} −log₁₀(P)', fontweight='bold', fontsize=10) + ax.set_ylabel(f'{mb} −log₁₀(P)', fontweight='bold', fontsize=10) + ax.set_title(f'{ma} vs {mb}', fontweight='bold', + color=MODEL_COLORS.get(ma, W_ACCENT), fontsize=11) + ax.text(0.04, 0.96, f'r = {corr:.3f}', transform=ax.transAxes, + fontsize=12, fontweight='bold', color=W_RED, va='top') + ax.grid(True, color=W_GRID, lw=0.6, alpha=0.6); ax.legend(fontsize=8) + for extra in range(len(pairs), nrows * ncols): + r, c = divmod(extra, ncols); axes[r][c].set_visible(False) plt.tight_layout(pad=1.5) - plt.savefig(save_path,dpi=110,bbox_inches='tight',facecolor=BG) + plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=W_BG) plt.close(fig) # ══════════════════════════════════════════════════════════════ -# PLOT: CIRCOS — WHITE BACKGROUND, CLASSIC BIOINFORMATICS STYLE -# matches reference image 2 (light bg, coloured chr ring, -# green shaded track area, black tick markers for sig SNPs) +# PLOT 7: CIRCOS — IMPROVED bioinformatics style, white bg +# Concentric ring tracks, each model its own ring with +# proper radial bar heights, colour-coded sig loci, +# chromosome labels, MTA consensus diamonds in hub # ══════════════════════════════════════════════════════════════ def plot_circos(mn_q, ch_q, pos_q, model_pvals, bonf_thresh, lod_thresh_user, save_path): - """ - Circos-style circular GWAS plot — white background, classic style. - - Outermost ring : coloured chromosome arcs with labels - - Per-model tracks: radial bars, height ∝ −log10(P) - - Light-green shaded area fills the whole track zone - - Significant SNPs: solid black tick marks (classic bioinformatics style) - - Consensus MTA : red diamond markers in inner hub - - Clean white background, navy text - """ _style_white() - unique_chroms = sorted( - set(ch_q), - key=lambda x: (int(x) if str(x).isdigit() else 999, str(x)) - ) - chrom_to_idx = {} + unique_chroms = sorted(set(ch_q), + key=lambda x: (int(x) if str(x).isdigit() else 999, str(x))) + chrom_to_idx = {} for i, c in enumerate(ch_q): chrom_to_idx.setdefault(c, []).append(i) n_chr = len(unique_chroms) @@ -931,8 +970,8 @@ def plot_circos(mn_q, ch_q, pos_q, model_pvals, bonf_thresh, lod_thresh_user, sa # Angular allocation proportional to marker count chr_len = {ch: len(chrom_to_idx[ch]) for ch in unique_chroms} total_m = sum(chr_len.values()) - GAP_DEG = 2.0 - avail_deg = 360 - GAP_DEG * n_chr + GAP_DEG = max(1.0, 360. / (n_chr * 12)) + avail_deg = 360. - GAP_DEG * n_chr chr_deg = {ch: (chr_len[ch] / total_m) * avail_deg for ch in unique_chroms} marker_angle = np.zeros(len(mn_q)) @@ -945,213 +984,338 @@ def plot_circos(mn_q, ch_q, pos_q, model_pvals, bonf_thresh, lod_thresh_user, sa marker_angle[idx] = cur + (rank / max(len(idxs) - 1, 1)) * chr_deg[ch] cur += chr_deg[ch] + GAP_DEG - # Radii - R_CHR_OUTER = 0.98 - R_CHR_INNER = 0.90 - R_TRACK_O = 0.88 - TRACK_W = 0.10 - R_HUB = 0.28 - R_INNER_FILL = 0.20 - models = list(model_pvals.keys()) n_models = len(models) bonf_log = -np.log10(bonf_thresh) + # Radii geometry — allocate equal track width per model + R_CHR_O = 0.975 + R_CHR_I = 0.895 + TRACK_W = min(0.080, (R_CHR_I - 0.20) / max(n_models, 1)) + R_HUB = 0.20 + + # Precompute significant sets and consensus sig_per_model = { - mname: set(np.where(pv < bonf_thresh)[0]) - for mname, pv in model_pvals.items() + mn: set(np.where(pv < bonf_thresh)[0]) + for mn, pv in model_pvals.items() } - consensus_threshold = max(1, int(np.ceil(n_models / 2))) sig_counts = np.zeros(len(mn_q), dtype=int) - for mname in models: - for idx in sig_per_model[mname]: + for mn_k in models: + for idx in sig_per_model[mn_k]: sig_counts[idx] += 1 consensus_idx = set(np.where(sig_counts >= consensus_threshold)[0]) - fig = plt.figure(figsize=(14, 14), facecolor=WH_BG) - ax = fig.add_axes([0.05, 0.10, 0.90, 0.84], projection='polar') - ax.set_facecolor(WH_BG) + fig = plt.figure(figsize=(15, 15), facecolor=W_BG) + ax = fig.add_axes([0.04, 0.09, 0.92, 0.87], projection='polar') + ax.set_facecolor(W_BG) ax.set_theta_zero_location('N') ax.set_theta_direction(-1) ax.set_ylim(0, 1.08) ax.axis('off') - theta_full = np.linspace(0, 2 * np.pi, 600) + theta_full = np.linspace(0, 2 * np.pi, 1000) - # ── Light background fill for track zone ─────────────────────────── - track_o_inner = R_TRACK_O - n_models * TRACK_W - ax.fill_between(theta_full, track_o_inner, R_TRACK_O, - color='#C8E6C9', alpha=0.35, zorder=1) + # ── 1. Light fill for the entire track region ─────────────────── + r_track_outer = R_CHR_I - 0.008 + r_track_inner = r_track_outer - n_models * TRACK_W + ax.fill_between(theta_full, r_track_inner, r_track_outer, + color='#E8F5E9', alpha=0.50, zorder=1) - # ── Chromosome arcs ──────────────────────────────────────────────── + # ── 2. Chromosome arcs ────────────────────────────────────────── for ci, ch in enumerate(unique_chroms): - s_deg = chr_start_deg[ch] - e_deg = s_deg + chr_deg[ch] + s_deg = chr_start_deg[ch]; e_deg = s_deg + chr_deg[ch] s_rad = np.deg2rad(s_deg); e_rad = np.deg2rad(e_deg) - theta_arc = np.linspace(s_rad, e_rad, 80) - - col = CHROM_PALETTE_LIGHT[ci % len(CHROM_PALETTE_LIGHT)] - ax.fill_between(theta_arc, R_CHR_INNER, R_CHR_OUTER, - color=col, alpha=0.80, zorder=3) - # White gap lines between chromosomes - ax.plot([s_rad, s_rad], [R_CHR_INNER, R_CHR_OUTER], - color='white', lw=2.0, zorder=4) - ax.plot([e_rad, e_rad], [R_CHR_INNER, R_CHR_OUTER], - color='white', lw=2.0, zorder=4) - ax.plot(theta_arc, [R_CHR_OUTER] * 80, color='white', lw=0.8, zorder=4) - ax.plot(theta_arc, [R_CHR_INNER] * 80, color='white', lw=0.5, zorder=4) - - # Chromosome label outside the arc - mid_rad = np.deg2rad((s_deg + e_deg) / 2) - label_r = R_CHR_OUTER + 0.038 + theta_arc = np.linspace(s_rad, e_rad, max(30, int(chr_deg[ch] * 5))) + col = CHROM_COLORS[ci % len(CHROM_COLORS)] + + ax.fill_between(theta_arc, R_CHR_I, R_CHR_O, color=col, alpha=0.85, zorder=3) + ax.plot([s_rad, s_rad], [R_CHR_I, R_CHR_O], color='white', lw=2.2, zorder=4) + ax.plot([e_rad, e_rad], [R_CHR_I, R_CHR_O], color='white', lw=2.2, zorder=4) + ax.plot(theta_arc, [R_CHR_O] * len(theta_arc), color='white', lw=0.8, zorder=4) + ax.plot(theta_arc, [R_CHR_I] * len(theta_arc), color='white', lw=0.5, zorder=4) + + mid_rad = np.deg2rad((s_deg + e_deg) / 2.) + label_r = R_CHR_O + 0.035 rot_angle = np.rad2deg(mid_rad) if np.pi / 2 < mid_rad < 3 * np.pi / 2: rot_angle += 180 ax.text(mid_rad, label_r, str(ch), - ha='center', va='center', fontsize=7.5, - fontweight='bold', color=WH_TEXT, zorder=6, - rotation=rot_angle - 90) - - # Small tick marks along the arc inner edge - n_ticks = min(8, len(chrom_to_idx[ch])) - for tick_rad in np.linspace(s_rad, e_rad, n_ticks): - ax.plot([tick_rad, tick_rad], - [R_CHR_INNER - 0.010, R_CHR_INNER], - color='#888888', lw=0.5, zorder=3) - - # ── Model tracks ────────────────────────────────────────────────��── + ha='center', va='center', fontsize=8, fontweight='bold', + color=W_TEXT, zorder=6, rotation=rot_angle - 90) + + # ── 3. Model tracks (outer → inner) ──────────────────────────── for mi, mname in enumerate(models): pv = model_pvals[mname] log_p = -np.log10(np.clip(pv, 1e-300, 1)) - mcol = MODEL_COLORS_LIGHT.get(mname, WH_ACCENT) + mcol = MODEL_COLORS.get(mname, W_ACCENT) - r_out_track = R_TRACK_O - mi * TRACK_W - r_in_track = r_out_track - TRACK_W + 0.008 + r_out = r_track_outer - mi * TRACK_W + r_in = r_out - TRACK_W + 0.004 - # Track ring divider - ax.plot(theta_full, [r_out_track] * 600, - color='#AAAAAA', lw=0.6, alpha=0.5, zorder=2) + # Track boundary ring + ax.plot(theta_full, [r_out] * 1000, color=W_BORDER, lw=0.8, alpha=0.6, zorder=2) + ax.plot(theta_full, [r_in] * 1000, color=W_BORDER, lw=0.5, alpha=0.4, zorder=2) - # Normalize height within track lp_max = max(bonf_log * 1.5, float(log_p.max()), 1.0) - norm_h = (log_p / lp_max) * TRACK_W + norm_h = (log_p / lp_max) * TRACK_W * 0.9 # 90% fill - # Bonferroni dashed arc - bonf_r = r_in_track + (bonf_log / lp_max) * TRACK_W - ax.plot(theta_full, [bonf_r] * 600, - color=WH_RED, lw=0.9, ls='--', alpha=0.50, zorder=3) + # Bonferroni arc inside track + bonf_r = r_in + (bonf_log / lp_max) * TRACK_W * 0.9 + ax.plot(theta_full, [bonf_r] * 1000, + color=W_RED, lw=0.9, ls='--', alpha=0.45, zorder=3) - # Non-significant radial bars (model colour, thin) - for idx in range(len(mn_q)): - if idx in sig_per_model[mname]: - continue + # Batch non-significant bars (thin, model colour) + non_sig_idx = [i for i in range(len(mn_q)) if i not in sig_per_model[mname]] + for idx in non_sig_idx: theta = np.deg2rad(marker_angle[idx]) - r_top = r_in_track + norm_h[idx] - ax.plot([theta, theta], [r_in_track, r_top], - color=mcol, lw=0.4, alpha=0.30, zorder=3) + r_top = min(r_in + norm_h[idx], r_out - 0.002) + if norm_h[idx] > 0.001: + ax.plot([theta, theta], [r_in, r_top], + color=mcol, lw=0.35, alpha=0.28, zorder=3) - # Significant: thick black ticks (classic bioinformatics style) + # Significant: thick coloured bars + dot for idx in sig_per_model[mname]: theta = np.deg2rad(marker_angle[idx]) - r_top = min(r_in_track + norm_h[idx], r_out_track - 0.003) - ax.plot([theta, theta], [r_in_track, r_top], - color='black', lw=1.4, alpha=0.95, zorder=5) - # Small cap dot at top - ax.scatter(theta, r_top, - s=12, c='black', alpha=1.0, - edgecolors='none', zorder=6) - - # Model name label (near top of circle, just inside chr ring) - label_theta = np.deg2rad(1.5) - label_r_pos = (r_in_track + r_out_track) / 2 - ax.text(label_theta, label_r_pos, mname, - ha='left', va='center', fontsize=7.5, - fontweight='bold', color=mcol, zorder=8) - - # ── Bottom ring border ───────────────────────────────────────────── - r_inner_border = R_TRACK_O - n_models * TRACK_W - ax.plot(theta_full, [r_inner_border] * 600, - color='#999999', lw=1.0, alpha=0.7, zorder=4) - - # ── Consensus MTA hub: red diamonds ─────────────────────────────── + r_top = min(r_in + norm_h[idx], r_out - 0.002) + ax.plot([theta, theta], [r_in, r_top], + color=mcol, lw=2.2, alpha=1.0, zorder=5, + solid_capstyle='round') + ax.scatter(theta, r_top, s=18, c=mcol, alpha=1.0, + edgecolors='white', lw=0.6, zorder=6) + + # Model label + ax.text(np.deg2rad(2.0), (r_in + r_out) / 2., mname, + ha='left', va='center', fontsize=8, fontweight='bold', + color=mcol, zorder=8) + + # ── 4. Consensus MTA: red diamonds in hub ─────────────────────── for idx in consensus_idx: theta = np.deg2rad(marker_angle[idx]) n_sig = sig_counts[idx] - hub_r = R_HUB + (n_sig / n_models) * 0.05 - ax.scatter(theta, hub_r, - s=75, c=WH_RED, alpha=1.0, - edgecolors='white', lw=0.8, - marker='D', zorder=8) - - # ── Inner filled white circle (clean centre) ─────────────────────── - ax.fill_between(theta_full, 0, R_INNER_FILL, - color=WH_BG, alpha=1.0, zorder=2) - ax.plot(theta_full, [R_INNER_FILL] * 600, - color='#CCCCCC', lw=0.8, alpha=0.6, zorder=3) - - # ── Centre statistics text ───────────────────────────────────────── - n_consensus = len(consensus_idx) - n_total_sig = sum(len(v) for v in sig_per_model.values()) - ax.text(0, 0, - f'{n_consensus}\nMTA', - ha='center', va='center', fontsize=14, - fontweight='bold', color=WH_RED, zorder=9, - transform=ax.transData) - ax.text(0, 0.10, + hub_r = R_HUB * 0.6 + (n_sig / max(n_models, 1)) * R_HUB * 0.35 + ax.scatter(theta, hub_r, s=90, c=W_RED, alpha=0.95, + edgecolors='white', lw=0.9, marker='D', zorder=8) + + # ── 5. Inner white hub ────────────────────────────────────────── + ax.fill_between(theta_full, 0, R_HUB * 0.55, + color=W_BG, alpha=1.0, zorder=2) + ax.plot(theta_full, [R_HUB * 0.55] * 1000, + color=W_BORDER, lw=1.0, alpha=0.5, zorder=3) + + # ── 6. Track outer boundary ───────────────────────────────────── + ax.plot(theta_full, [r_track_inner] * 1000, + color='#777777', lw=1.2, alpha=0.7, zorder=4) + + # ── 7. Centre text ────────────────────────────────────────────── + n_consensus = len(consensus_idx) + n_total_sig = sum(len(v) for v in sig_per_model.values()) + ax.text(0, 0, f'{n_consensus}\nMTA', + ha='center', va='center', fontsize=15, fontweight='bold', + color=W_RED, zorder=9, transform=ax.transData) + ax.text(0, 0.095, f'{n_total_sig} sig.\nloci total', - ha='center', va='center', fontsize=8, - color=WH_SUBTEXT, zorder=9, - transform=ax.transData) + ha='center', va='center', fontsize=8.5, + color=W_SUBTEXT, zorder=9, transform=ax.transData) + + # ── 8. Title & subtitle ───────────────────────────────────────── + fig.text(0.5, 0.97, 'Circos GWAS — Multi-Model Comparison', + ha='center', fontsize=15, fontweight='bold', color=W_TEXT) + fig.text(0.5, 0.945, + f'{n_chr} chromosomes | {len(mn_q)} markers | ' + f'{len(models)} models | {n_consensus} MTA consensus loci', + ha='center', fontsize=9, color=W_SUBTEXT) - # ── Legend ──────────────────────────────────────────────────────── + # ── 9. Legend ─────────────────────────────────────────────────── legend_elements = [ - mpatches.Patch(facecolor=MODEL_COLORS_LIGHT.get(m, WH_ACCENT), + mpatches.Patch(facecolor=MODEL_COLORS.get(m, W_ACCENT), edgecolor='grey', lw=0.5, label=m, alpha=0.9) for m in models ] + [ - plt.Line2D([0], [0], color='black', lw=2.0, label='Significant SNP'), - mpatches.Patch(facecolor=WH_RED, edgecolor='white', lw=0.8, - label=f'MTA consensus (≥{consensus_threshold} models)'), - plt.Line2D([0], [0], color=WH_RED, ls='--', lw=1.5, + plt.Line2D([0], [0], color=W_RED, marker='D', ms=7, + lw=0, label=f'MTA consensus (≥{consensus_threshold} models)'), + plt.Line2D([0], [0], color=W_RED, ls='--', lw=1.5, label='Bonferroni threshold'), ] - fig.legend( - handles=legend_elements, - loc='lower center', - ncol=min(4, len(legend_elements)), - fontsize=9, - framealpha=0.95, - facecolor=WH_BG, - edgecolor=WH_GRID, - bbox_to_anchor=(0.5, 0.01) - ) - - # ── Titles ──────────────────────────────────────────────────────── - fig.text(0.5, 0.97, - 'Circos Plot — Multi-Model GWAS Comparison', - ha='center', fontsize=15, fontweight='bold', color=WH_TEXT) - fig.text(0.5, 0.945, - f'{n_chr} chromosomes | {len(mn_q)} markers | ' - f'{len(models)} models | {n_consensus} MTA consensus loci', - ha='center', fontsize=9, color=WH_SUBTEXT) - - # ── Interpretation text ──────────────────────────────────────────── - interp_lines = [ - f"■ Outer coloured ring = chromosomes", - f"■ Inner rings (outer→inner): {', '.join(models)}", - f"■ Bar height ∝ −log₁₀(P); red dashed arc = Bonferroni threshold", - f"■ Black ticks = significant SNPs within that model", - f"■ Red diamonds (◆) = MTA consensus: significant in ≥{consensus_threshold}/{n_models} models", - f"■ {n_total_sig} total sig. loci across all models; {n_consensus} are MTA consensus", + fig.legend(handles=legend_elements, loc='lower center', + ncol=min(4, len(legend_elements)), fontsize=9, + framealpha=0.96, facecolor=W_BG, edgecolor=W_BORDER, + bbox_to_anchor=(0.5, 0.01)) + + # ── 10. Interpretation ────────────────────────────────────────── + interp = [ + f"■ Outer coloured arcs = chromosomes", + f"■ Concentric tracks (outer→inner): {', '.join(models)}", + f"■ Bar height ∝ −log₁₀(P); red dashed arc = Bonferroni", + f"■ Thick bars = significant SNPs per model", + f"■ Red diamonds ◆ = MTA consensus loci (≥{consensus_threshold}/{n_models} models)", ] - fig.text( - 0.04, 0.07, "\n".join(interp_lines), - ha='left', fontsize=8, color=WH_TEXT, fontfamily='monospace', - bbox=dict(boxstyle='round,pad=0.6', fc=WH_PANEL, ec=WH_GRID, alpha=0.95) - ) + fig.text(0.02, 0.07, "\n".join(interp), ha='left', + fontsize=8, color=W_TEXT, fontfamily='monospace', + bbox=dict(boxstyle='round,pad=0.5', fc=W_PANEL, ec=W_BORDER, alpha=0.95)) - plt.savefig(save_path, dpi=110, bbox_inches='tight', facecolor=WH_BG) + plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=W_BG) + plt.close(fig) + + +# ══════════════════════════════════════════════════════════════ +# PLOT 8: KINSHIP HEATMAP — white +# ══════════════════════════════════════════════════════════════ +def plot_kinship_heatmap(K, save_path, max_n=200): + _style_white() + n = K.shape[0] + if n > max_n: + idx = np.random.choice(n, max_n, replace=False) + idx.sort(); K = K[np.ix_(idx, idx)] + title_sfx = f' (random {max_n}/{n} samples)' + else: + title_sfx = '' + + fig, ax = plt.subplots(figsize=(8, 7), facecolor=W_BG) + cmap = LinearSegmentedColormap.from_list( + 'kinship', ['#FFFFFF', '#C6DBEF', '#4292C6', '#08306B']) + im = ax.imshow(K, cmap=cmap, aspect='auto', vmin=0) + cb = plt.colorbar(im, ax=ax, fraction=0.04, pad=0.02) + cb.set_label('Kinship coefficient', fontsize=9) + ax.set_title(f'Kinship Matrix{title_sfx}', fontweight='bold', + fontsize=13, color=W_ACCENT) + ax.set_xlabel('Sample index', fontweight='bold') + ax.set_ylabel('Sample index', fontweight='bold') + ax.tick_params(labelsize=7) + plt.tight_layout() + plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=W_BG) + plt.close(fig) + + +# ══════════════════════════════════════════════════════════════ +# PLOT 9: ALLELE FREQUENCY DISTRIBUTION — white +# ══════════════════════════════════════════════════════════════ +def plot_maf_distribution(maf_arr, save_path): + _style_white() + maf = maf_arr[maf_arr > 0] + fig, axes = plt.subplots(1, 2, figsize=(12, 5), facecolor=W_BG) + fig.suptitle('Minor Allele Frequency Distribution', fontsize=13, + fontweight='bold', color=W_TEXT, y=1.02) + + ax = axes[0]; ax.set_facecolor(W_PANEL) + ax.hist(maf, bins=40, color=W_ACCENT, alpha=0.75, edgecolor='white', lw=0.5) + ax.axvline(0.05, color=W_RED, ls='--', lw=1.8, label='MAF=0.05') + ax.set_xlabel('MAF', fontweight='bold'); ax.set_ylabel('Count', fontweight='bold') + ax.set_title('MAF Histogram', fontweight='bold', color=W_ACCENT) + ax.legend(); ax.grid(True, color=W_GRID, lw=0.5) + + ax = axes[1]; ax.set_facecolor(W_PANEL) + # Cumulative distribution + x_s = np.sort(maf); y_s = np.arange(1, len(x_s)+1) / len(x_s) + ax.plot(x_s, y_s, color=W_ACCENT, lw=2) + ax.fill_between(x_s, 0, y_s, color=W_ACCENT, alpha=0.15) + ax.axvline(0.05, color=W_RED, ls='--', lw=1.8, label='MAF=0.05') + ax.set_xlabel('MAF', fontweight='bold') + ax.set_ylabel('Cumulative proportion', fontweight='bold') + ax.set_title('MAF Cumulative Distribution', fontweight='bold', color=W_ACCENT) + ax.legend(); ax.grid(True, color=W_GRID, lw=0.5) + ax.text(0.55, 0.35, + f'Total markers: {len(maf_arr):,}\nMAF<0.05: {(maf_arr<0.05).sum():,}\n' + f'MAF>0.05: {(maf_arr>=0.05).sum():,}', + transform=ax.transAxes, fontsize=9, color=W_SUBTEXT, + bbox=dict(boxstyle='round,pad=0.4', fc=W_BG, ec=W_BORDER)) + + plt.tight_layout() + plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=W_BG) + plt.close(fig) + + +# ══════════════════════════════════════════════════════════════ +# PLOT 10: EFFECT SIZE VOLCANO PLOT — white +# ══════════════════════════════════════════════════════════════ +def plot_volcano(pv, beta, mname, bonf_thresh, save_path): + _style_white() + mcol = MODEL_COLORS.get(mname, W_ACCENT) + bonf_log = -np.log10(bonf_thresh) + log_p = -np.log10(np.clip(pv, 1e-300, 1)) + + fig, ax = plt.subplots(figsize=(9, 7), facecolor=W_BG) + ax.set_facecolor(W_PANEL) + fig.suptitle(f'Volcano Plot — {mname}', fontsize=13, fontweight='bold', + color=W_TEXT, y=1.01) + + sig = log_p >= bonf_log + nsig = ~sig + if nsig.any(): + ax.scatter(beta[nsig], log_p[nsig], c=W_SUBTEXT, s=10, + alpha=0.45, linewidths=0, zorder=2, label='Non-significant') + up = sig & (beta > 0) + down = sig & (beta < 0) + if up.any(): + ax.scatter(beta[up], log_p[up], c=W_RED, s=40, alpha=0.9, + marker='D', linewidths=0, zorder=4, label='Sig positive effect') + if down.any(): + ax.scatter(beta[down], log_p[down], c=W_ACCENT, s=40, alpha=0.9, + marker='D', linewidths=0, zorder=4, label='Sig negative effect') + + ax.axhline(bonf_log, color=W_RED, ls='--', lw=1.5, alpha=0.8, + label=f'Bonferroni ({bonf_log:.2f})', zorder=5) + ax.axvline(0, color=W_BORDER, lw=1.0, ls=':', alpha=0.7, zorder=3) + ax.set_xlabel('Effect size (β)', fontweight='bold', fontsize=12) + ax.set_ylabel('−log₁₀(P)', fontweight='bold', fontsize=12) + ax.legend(fontsize=9); ax.grid(True, color=W_GRID, lw=0.5) + ax.text(0.02, 0.96, f'{sig.sum()} significant SNPs', + transform=ax.transAxes, fontsize=9, color=W_RED, fontweight='bold', va='top') + + plt.tight_layout() + plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=W_BG) + plt.close(fig) + + +# ══════════════════════════════════════════════════════════════ +# PLOT 11: MULTI-MODEL MANHATTAN OVERLAY — white +# All models on same axis, different colours +# ══════════════════════════════════════════════════════════════ +def plot_multi_model_manhattan(mn, ch_q, model_pvals, bonf_thresh, save_path): + _style_white() + GAP = max(8, len(mn) // 150) + x_pos, chrom_xticks, offset, GAP, unique_chroms, chrom_to_idx = _build_x_pos(mn, ch_q, GAP) + bonf_log = -np.log10(bonf_thresh) + + fig, ax = plt.subplots(figsize=(18, 6), facecolor=W_BG) + ax.set_facecolor(W_PANEL) + fig.suptitle('Multi-Model Manhattan Comparison', fontsize=14, + fontweight='bold', color=W_TEXT, y=1.01) + + for ci, ch in enumerate(unique_chroms): + if ci % 2 == 0: + idxs = chrom_to_idx.get(ch, []) + if idxs: + ax.axvspan(x_pos[idxs[0]] - 0.5, x_pos[idxs[-1]] + 0.5, + color='#F0F4F8', alpha=0.7, zorder=0) + + for mname, pv in model_pvals.items(): + log_p = -np.log10(np.clip(pv, 1e-300, 1)) + mcol = MODEL_COLORS.get(mname, W_ACCENT) + ax.scatter(x_pos, log_p, c=mcol, s=6, alpha=0.40, + linewidths=0, zorder=2, label=mname) + sig_idx = np.where(pv < bonf_thresh)[0] + if len(sig_idx): + ax.scatter(x_pos[sig_idx], log_p[sig_idx], c=mcol, s=50, + alpha=0.95, marker='D', linewidths=0.8, + edgecolors=mcol, zorder=4) + + ax.axhline(bonf_log, color=W_RED, ls='--', lw=1.8, alpha=0.9, + label=f'Bonferroni ({bonf_log:.2f})', zorder=5) + ax.axhline(3.0, color=W_GOLD, ls=':', lw=1.4, alpha=0.8, + label='Suggestive (3.0)', zorder=5) + ax.set_xticks([x for x, _ in chrom_xticks]) + ax.set_xticklabels([l for _, l in chrom_xticks], fontsize=8, fontweight='bold') + ax.set_xlabel('Chromosome', fontweight='bold', fontsize=12) + ax.set_ylabel('−log₁₀(P)', fontweight='bold', fontsize=12) + ax.set_xlim(-GAP, offset) + ax.set_ylim(0, max(bonf_log * 1.2, ax.get_ylim()[1])) + ax.legend(loc='upper right', fontsize=9, ncol=len(model_pvals) + 2) + ax.grid(True, color=W_GRID, lw=0.5, alpha=0.6, axis='y') + ax.yaxis.set_major_locator(plt.MaxNLocator(8)) + + plt.tight_layout() + plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=W_BG) plt.close(fig) @@ -1164,188 +1328,245 @@ def run_analysis(input_file, miss_sample, miss_marker, maf_thresh, progress=gr.Progress(track_tqdm=True)): try: if input_file is None: - return ("⚠️ Upload a CSV file first.", - None,None,None,None,None,None,None,None,None) + return ("⚠️ Please upload a CSV file first.", + None,None,None,None,None,None,None,None,None, + gr.update(choices=[]),gr.update(choices=[]),{},{}) run_id = pd.Timestamp.now().strftime("%Y%m%d_%H%M%S") rdir = OUTPUT_DIR / run_id pdir = rdir / 'plots' - for d in [rdir, pdir]: d.mkdir(parents=True, exist_ok=True) - - ms_t=miss_sample/100.; mm_t=miss_marker/100.; mf_t=maf_thresh/100. - - progress(0.04, desc="Parsing CSV…") - (sids,pheno,geno,mnames,chroms,positions) = parse_input_csv(input_file) - n_s,n_m = len(sids),len(mnames) - - progress(0.10, desc="Quality control…") - miss_m_r=np.isnan(geno).sum(0)/max(n_s,1) - miss_s_r=np.isnan(geno).sum(1)/max(n_m,1) - maf_arr=np.zeros(n_m) + for d in [rdir, pdir]: + d.mkdir(parents=True, exist_ok=True) + + ms_t = miss_sample / 100. + mm_t = miss_marker / 100. + mf_t = maf_thresh / 100. + + # ── PARSE ──────────────────────────────────────────────────── + progress(0.03, desc="Parsing CSV…") + (sids, pheno, geno, mnames, chroms, positions) = parse_input_csv(input_file) + n_s, n_m = len(sids), len(mnames) + + # ── QC ─────────────────────────────────────────────────────── + progress(0.09, desc="Quality control…") + miss_m_r = np.isnan(geno).sum(0) / max(n_s, 1) + miss_s_r = np.isnan(geno).sum(1) / max(n_m, 1) + maf_raw = np.zeros(n_m) for i in range(n_m): - v=geno[:,i]; v=v[~np.isnan(v)] - if len(v): f=np.mean(v)/2.; maf_arr[i]=min(f,1-f) - qc_m=(miss_m_r=mf_t); qc_s=miss_s_r=mf_t); qs=miss_s_r=10: - qc_m,qc_s=qm,qs - if rs>ms_t or rm>mm_t: - fallback=(f"\n⚠️ QC relaxed → sample<{rs*100:.0f}% / marker<{rm*100:.0f}%\n") + v = geno[:, i]; v = v[~np.isnan(v)] + if len(v): + f = np.mean(v) / 2.; maf_raw[i] = min(f, 1 - f) + + qc_m = (miss_m_r < mm_t) & (maf_raw >= mf_t) + qc_s = miss_s_r < ms_t + fallback = "" + for rs, rm in [(ms_t, mm_t), (.6,.6), (.7,.7), (.8,.8), (.9,.9), (1.,1.)]: + qm = (miss_m_r < rm) & (maf_raw >= mf_t); qs = miss_s_r < rs + if qs.sum() >= 10: + qc_m, qc_s = qm, qs + if rs > ms_t or rm > mm_t: + fallback = (f"\n⚠️ QC relaxed → sample<{rs*100:.0f}% / marker<{rm*100:.0f}%\n") break - geno_q=geno[np.ix_(qc_s,qc_m)].copy() - pheno_q=pheno[qc_s]; sids_q=sids[qc_s] - mn_q=[mnames[i] for i in range(n_m) if qc_m[i]] - ch_q=[chroms[i] for i in range(n_m) if qc_m[i]] - pos_q=[positions[i] for i in range(n_m) if qc_m[i]] - n_q=len(mn_q) - - col_mu=np.nanmean(geno_q,0); col_mu=np.where(np.isnan(col_mu),0,col_mu) + geno_q = geno[np.ix_(qc_s, qc_m)].copy() + pheno_q = pheno[qc_s]; sids_q = sids[qc_s] + mn_q = [mnames[i] for i in range(n_m) if qc_m[i]] + ch_q = [chroms[i] for i in range(n_m) if qc_m[i]] + pos_q = [positions[i] for i in range(n_m) if qc_m[i]] + maf_q = maf_raw[qc_m] + n_q = len(mn_q) + + # Impute missing with column mean + col_mu = np.nanmean(geno_q, 0) + col_mu = np.where(np.isnan(col_mu), 0, col_mu) for i in range(geno_q.shape[1]): - mk=np.isnan(geno_q[:,i]) - if mk.any(): geno_q[mk,i]=col_mu[i] + mk = np.isnan(geno_q[:, i]) + if mk.any(): geno_q[mk, i] = col_mu[i] - valid=~np.isnan(pheno_q) - geno_q=geno_q[valid]; pheno_q=pheno_q[valid]; sids_q=sids_q[valid] + valid = ~np.isnan(pheno_q) + geno_q = geno_q[valid]; pheno_q = pheno_q[valid]; sids_q = sids_q[valid] - if len(sids_q)<10: - return (f"## ⚠️ Only {len(sids_q)} samples passed QC.", - None,None,None,None,None,None,None,None,None) + if len(sids_q) < 10: + return (f"## ⚠️ Only {len(sids_q)} samples passed QC — need at least 10.", + None,None,None,None,None,None,None,None,None, + gr.update(choices=[]),gr.update(choices=[]),{},{}) - bonf=0.05/n_q; bonf_log=-np.log10(bonf) + bonf = 0.05 / n_q; bonf_log = -np.log10(bonf) - progress(0.16, desc="Computing kinship matrix…") - K=compute_kinship(geno_q) + # ── KINSHIP ────────────────────────────────────────────────── + progress(0.15, desc="Computing kinship matrix…") + K = compute_kinship(geno_q) - # ── Models ───────────────────────────────────────────────────── - model_pvals,model_betas,model_ses={},{},{} - step_base=0.18; n_models_sel=sum([run_glm,run_mlm,run_cmlm,run_bslmm,run_farmcpu]) - step_size=0.38/max(n_models_sel,1); step_i=0 + # ── MODELS ─────────────────────────────────────────────────── + model_pvals = {}; model_betas = {}; model_ses = {} + step_base = 0.17 + n_models_sel = sum([run_glm, run_mlm, run_cmlm, run_bslmm, run_farmcpu]) + step_size = 0.38 / max(n_models_sel, 1); step_i = 0 if run_glm: - progress(step_base+step_i*step_size, desc="Running GLM…") - pv,bv,sv,rv=model_glm(geno_q,pheno_q) - model_pvals['GLM']=pv; model_betas['GLM']=bv; model_ses['GLM']=sv; step_i+=1 + progress(step_base + step_i * step_size, desc="Running GLM…") + pv,bv,sv,rv = model_glm(geno_q, pheno_q) + model_pvals['GLM'] = pv; model_betas['GLM'] = bv; model_ses['GLM'] = sv; step_i += 1 if run_mlm: - progress(step_base+step_i*step_size, desc="Running MLM…") - pv,bv,sv,rv=model_mlm(geno_q,pheno_q,K,n_pc=n_pc_user) - model_pvals['MLM']=pv; model_betas['MLM']=bv; model_ses['MLM']=sv; step_i+=1 + progress(step_base + step_i * step_size, desc="Running MLM…") + pv,bv,sv,rv = model_mlm(geno_q, pheno_q, K, n_pc=n_pc_user) + model_pvals['MLM'] = pv; model_betas['MLM'] = bv; model_ses['MLM'] = sv; step_i += 1 if run_cmlm: - progress(step_base+step_i*step_size, desc="Running CMLM…") - pv,bv,sv,rv=model_cmlm(geno_q,pheno_q,K,n_pc=n_pc_user) - model_pvals['CMLM']=pv; model_betas['CMLM']=bv; model_ses['CMLM']=sv; step_i+=1 + progress(step_base + step_i * step_size, desc="Running CMLM…") + pv,bv,sv,rv = model_cmlm(geno_q, pheno_q, K, n_pc=n_pc_user) + model_pvals['CMLM'] = pv; model_betas['CMLM'] = bv; model_ses['CMLM'] = sv; step_i += 1 if run_bslmm: - progress(step_base+step_i*step_size, desc="Running BSLMM (slow)…") - pv,bv=model_bslmm(geno_q,pheno_q) - model_pvals['BSLMM']=pv; model_betas['BSLMM']=bv; step_i+=1 + progress(step_base + step_i * step_size, desc="Running BSLMM (slow)…") + pv,bv = model_bslmm(geno_q, pheno_q) + model_pvals['BSLMM'] = pv; model_betas['BSLMM'] = bv; step_i += 1 if run_farmcpu: - progress(step_base+step_i*step_size, desc="Running FarmCPU…") - pv,bv,sv=model_farmcpu(geno_q,pheno_q,K) - model_pvals['FarmCPU']=pv; model_betas['FarmCPU']=bv; model_ses['FarmCPU']=sv + progress(step_base + step_i * step_size, desc="Running FarmCPU…") + pv,bv,sv = model_farmcpu(geno_q, pheno_q, K) + model_pvals['FarmCPU'] = pv; model_betas['FarmCPU'] = bv; model_ses['FarmCPU'] = sv if not model_pvals: - return ("## ⚠️ No models selected.",None,None,None,None,None,None,None,None,None) - - # ── Results CSV ──────────────────────────────────────────────── - progress(0.58, desc="Building results table…") - df=pd.DataFrame({'Marker':mn_q,'Chromosome':ch_q,'Position_bp':pos_q}) - for mname,pv in model_pvals.items(): - df[f'{mname}_P']=pv - df[f'{mname}_LOD']=-np.log10(np.clip(pv,1e-300,1))*np.log10(np.e)/2. - df[f'{mname}_Sig']=(pv=max(1,len(sig_cols)//2)).astype(int) - df=df.sort_values(f"{list(model_pvals.keys())[0]}_P").reset_index(drop=True) - df.insert(0,'Rank',range(1,len(df)+1)) - csv_path=str(rdir/'gwas_results.csv'); top_path=str(rdir/'top_significant.csv') - df.to_csv(csv_path,index=False) - any_sig=df[sig_cols].sum(1)>0; df[any_sig].to_csv(top_path,index=False) - - # ── PLOTS ────────────────────────────────────────────────────── - progress(0.62, desc="Phenotype plot…") - ph_path=str(pdir/'phenotype_dist.png') + return ("## ⚠️ No models selected.", + None,None,None,None,None,None,None,None,None, + gr.update(choices=[]),gr.update(choices=[]),{},{}) + + # ── RESULTS CSV ────────────────────────────────────────────── + progress(0.57, desc="Building results table…") + LOD_FACTOR = np.log10(np.e) / 2.0 + df = pd.DataFrame({'Marker': mn_q, 'Chromosome': ch_q, 'Position_bp': pos_q, 'MAF': maf_q}) + for mname, pv in model_pvals.items(): + df[f'{mname}_P'] = pv + df[f'{mname}_LOD'] = -np.log10(np.clip(pv, 1e-300, 1)) * LOD_FACTOR + df[f'{mname}_Sig'] = (pv < bonf).astype(int) + if mname in model_betas: + df[f'{mname}_Beta'] = model_betas[mname] + if mname in model_ses: + df[f'{mname}_SE'] = model_ses[mname] + sig_cols = [f'{m}_Sig' for m in model_pvals] + df['Consensus_Sig'] = (df[sig_cols].sum(1) >= max(1, len(sig_cols) // 2)).astype(int) + df = df.sort_values(f"{list(model_pvals.keys())[0]}_P").reset_index(drop=True) + df.insert(0, 'Rank', range(1, len(df) + 1)) + csv_path = str(rdir / 'gwas_results.csv') + top_path = str(rdir / 'top_significant.csv') + df.to_csv(csv_path, index=False) + any_sig = df[sig_cols].sum(1) > 0 + df[any_sig].to_csv(top_path, index=False) + + # Stats summary + stats_data = { + 'n_samples': len(sids_q), 'n_markers': n_q, + 'n_chrom': len(set(ch_q)), 'bonf_thresh': bonf, + 'mean_maf': float(np.mean(maf_q)), 'maf_cutoff': maf_thresh, + } + for mname, pv in model_pvals.items(): + stats_data[f'{mname}_n_sig'] = int((pv < bonf).sum()) + pd.DataFrame([stats_data]).to_csv(str(rdir / 'gwas_summary_stats.csv'), index=False) + + # ── PLOTS ──────────────────────────────────────────────────── + progress(0.60, desc="Phenotype distribution…") + ph_path = str(pdir / 'phenotype_dist.png') plot_phenotype(pheno_q, ph_path) - progress(0.66, desc="PCA plot…") - pca_path=str(pdir/'pca_analysis.png') - evr,cumev,scores=plot_pca(geno_q,pheno_q,n_pc_user,pca_path) - - progress(0.70, desc="Manhattan + LOD plots (per model)…") - man_paths={} - for mname,pv in model_pvals.items(): - mp=str(pdir/f'manhattan_{mname}.png') - plot_manhattan_single(mn_q,ch_q,pv,mname,bonf,lod_thresh_user,mp) - man_paths[mname]=mp - - progress(0.78, desc="QQ plots (per model)…") - qq_paths={}; lam_dict={} - for mname,pv in model_pvals.items(): - qp=str(pdir/f'qq_{mname}.png') - lam=plot_qq_single(pv,mname,bonf,qp) - qq_paths[mname]=qp; lam_dict[mname]=lam - - progress(0.84, desc="LD decay plot…") - ld_path=str(pdir/'ld_decay_bp.png') - ld_stats,ld_interp=plot_ld_decay_bp(geno_q,ch_q,pos_q,ld_path) - ld_df=pd.DataFrame([{'Chromosome':k,**v} for k,v in ld_stats.items()]) - ld_df.to_csv(str(rdir/'ld_decay_stats.csv'),index=False) - - progress(0.88, desc="Model comparison plot…") - cmp_path=str(pdir/'model_comparison.png') - plot_model_comparison(model_pvals,cmp_path) - - progress(0.92, desc="Circos plot…") - circos_path=str(pdir/'circos_mta.png') - plot_circos(mn_q,ch_q,pos_q,model_pvals,bonf,lod_thresh_user,circos_path) - - # ── ZIP ──────────────────────────────────────────────────────── + progress(0.63, desc="PCA analysis…") + pca_path = str(pdir / 'pca_analysis.png') + evr, cumev, scores = plot_pca(geno_q, pheno_q, n_pc_user, pca_path) + + progress(0.66, desc="Kinship heatmap…") + kin_path = str(pdir / 'kinship_heatmap.png') + plot_kinship_heatmap(K, kin_path) + + progress(0.68, desc="MAF distribution…") + maf_path = str(pdir / 'maf_distribution.png') + plot_maf_distribution(maf_q, maf_path) + + progress(0.71, desc="Manhattan + LOD plots…") + man_paths = {} + for mname, pv in model_pvals.items(): + mp = str(pdir / f'manhattan_{mname}.png') + plot_manhattan_single(mn_q, ch_q, pv, mname, bonf, lod_thresh_user, mp) + man_paths[mname] = mp + + progress(0.76, desc="Multi-model Manhattan…") + multi_man_path = str(pdir / 'manhattan_multi_model.png') + plot_multi_model_manhattan(mn_q, ch_q, model_pvals, bonf, multi_man_path) + + progress(0.79, desc="QQ plots…") + qq_paths = {}; lam_dict = {} + for mname, pv in model_pvals.items(): + qp = str(pdir / f'qq_{mname}.png') + lam = plot_qq_single(pv, mname, bonf, qp) + qq_paths[mname] = qp; lam_dict[mname] = lam + + progress(0.83, desc="Volcano plots…") + volcano_paths = {} + for mname, pv in model_pvals.items(): + if mname in model_betas: + vp = str(pdir / f'volcano_{mname}.png') + plot_volcano(pv, model_betas[mname], mname, bonf, vp) + volcano_paths[mname] = vp + + progress(0.86, desc="LD decay (Hill model)…") + ld_path = str(pdir / 'ld_decay.png') + ld_stats, ld_interp = plot_ld_decay(geno_q, ch_q, pos_q, ld_path) + ld_df = pd.DataFrame([{'Chromosome': k, **v} for k, v in ld_stats.items()]) + ld_df.to_csv(str(rdir / 'ld_decay_stats.csv'), index=False) + + progress(0.89, desc="Model comparison…") + cmp_path = str(pdir / 'model_comparison.png') + plot_model_comparison(model_pvals, cmp_path) + + progress(0.93, desc="Circos plot…") + circos_path = str(pdir / 'circos_mta.png') + plot_circos(mn_q, ch_q, pos_q, model_pvals, bonf, lod_thresh_user, circos_path) + + # ── ZIP ────────────────────────────────────────────────────── progress(0.97, desc="Packaging ZIP…") - zip_path=str(OUTPUT_DIR/f'GWAS_Results_{run_id}.zip') - with zipfile.ZipFile(zip_path,'w',zipfile.ZIP_DEFLATED) as zf: - for root,_,files in os.walk(str(rdir)): + zip_path = str(OUTPUT_DIR / f'GWAS_Results_{run_id}.zip') + with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf: + for root, _, files in os.walk(str(rdir)): for f in files: - fp=os.path.join(root,f) - zf.write(fp,os.path.relpath(fp,str(rdir))) + fp = os.path.join(root, f) + zf.write(fp, os.path.relpath(fp, str(rdir))) - # ── Summary markdown ─────────────────────────────────────────── - def _mdt(d,n=15): - sub=d.head(n); cols=sub.columns.tolist() + # ── SUMMARY MARKDOWN ───────────────────────────────────────── + def _mdt(d, n=15): + sub = d.head(n); cols = sub.columns.tolist() def _f(v): - if isinstance(v,float): - return f"{v:.3e}" if (v!=0 and abs(v)<0.001) else f"{v:.4f}" + if isinstance(v, float): + return f"{v:.3e}" if (v != 0 and abs(v) < 0.001) else f"{v:.4f}" return str(v) - sep="| "+" | ".join(["---"]*len(cols))+" |" - rows=["| "+" | ".join(_f(row[c]) for c in cols)+" |" for _,row in sub.iterrows()] - return "\n".join(["| "+" | ".join(cols)+" |",sep]+rows) + sep = "| " + " | ".join(["---"] * len(cols)) + " |" + rows = ["| " + " | ".join(_f(row[c]) for c in cols) + " |" + for _, row in sub.iterrows()] + return "\n".join(["| " + " | ".join(cols) + " |", sep] + rows) - model_summary_rows="\n".join( - f"| {m} | **{int((pv1.05 else '✅ ok'} |" - for m,pv in model_pvals.items()) + model_summary_rows = "\n".join( + f"| {m} | **{int((pv < bonf).sum())}** | λ={lam_dict.get(m, 0):.4f} | " + f"{'⚠️ inflation' if lam_dict.get(m, 1) > 1.05 else '✅ ok'} |" + for m, pv in model_pvals.items()) - pca_rows="\n".join( + pca_rows = "\n".join( f"| PC{i+1} | {evr[i]:.2f}% | {cumev[i]:.2f}% |" - for i in range(min(n_pc_user,len(evr)))) + for i in range(min(n_pc_user, len(evr)))) - top_cols=(['Rank','Marker','Chromosome','Position_bp']+ - [f'{m}_P' for m in model_pvals]+['Consensus_Sig']) - top_cols=[c for c in top_cols if c in df.columns] + top_cols = (['Rank','Marker','Chromosome','Position_bp','MAF'] + + [f'{m}_P' for m in model_pvals] + + [f'{m}_LOD' for m in model_pvals] + + ['Consensus_Sig']) + top_cols = [c for c in top_cols if c in df.columns] - summary=f""" -## ✅ GWAS Analysis Complete — v9.0 + summary = f""" +## ✅ GWAS Analysis Complete — v10.0 -### 📊 QC Summary +### 📊 Quality Control Summary | Metric | Value | |---|---| | Samples (raw → QC) | {n_s} → **{len(sids_q)}** | | Markers (raw → QC) | {n_m} → **{n_q}** | | Chromosomes | **{len(set(ch_q))}** | -| MAF ≥ | {maf_thresh:.1f}% | +| MAF threshold | ≥ {maf_thresh:.1f}% | | PCs used | {n_pc_user} | -| LOD threshold (user) | {lod_thresh_user:.2f} | +| LOD threshold | {lod_thresh_user:.2f} | +| Bonferroni threshold | P < {bonf:.3e} (−log₁₀P > {bonf_log:.2f}) | {fallback} ### 🧬 PCA Variance Explained @@ -1354,20 +1575,25 @@ def run_analysis(input_file, miss_sample, miss_marker, maf_thresh, {pca_rows} ### 🔬 Model Results -| Model | Sig. Markers (Bonferroni) | λ | Status | +| Model | Sig. Markers | λ (genomic inflation) | Status | |---|---|---|---| {model_summary_rows} -**Bonferroni threshold:** P < {bonf:.3e}  |  −log₁₀P > {bonf_log:.2f} - -### 🧬 LD Decay +### 🧬 LD Decay (Hill 1975 model) {ld_interp} +### 📈 Output Files +- `gwas_results.csv` — full results for all markers and models +- `top_significant.csv` — only markers significant in ≥1 model +- `gwas_summary_stats.csv` — summary statistics +- `ld_decay_stats.csv` — per-chromosome LD statistics +- `plots/` — all figures (Manhattan, LOD, QQ, Circos, LD, PCA, Kinship, MAF, Volcano, Comparison) + ### 🏆 Top 15 Markers {_mdt(df[top_cols])} --- -**Output:** `{rdir}` +*MTA GWAS v10.0 — All plots: white background | Hill (1975) LD model | Dual-panel Manhattan+LOD* """ progress(1.0, desc="Done ✅") @@ -1378,80 +1604,128 @@ def run_analysis(input_file, miss_sample, miss_marker, maf_thresh, first_man, first_qq, pca_path, ld_path, circos_path, cmp_path, ph_path, zip_path, + kin_path, gr.update(choices=list(man_paths.keys()), value=list(man_paths.keys())[0] if man_paths else None), gr.update(choices=list(qq_paths.keys()), - value=list(qq_paths.keys())[0] if qq_paths else None), - {mn: mp for mn,mp in man_paths.items()}, - {mn: qp for mn,qp in qq_paths.items()}) + value=list(qq_paths.keys())[0] if qq_paths else None), + man_paths, qq_paths) except Exception as e: import traceback return (f"## ❌ Error\n```\n{e}\n\n{traceback.format_exc()}\n```", - None,None,None,None,None,None,None,None, + None,None,None,None,None,None,None,None,None, gr.update(choices=[]),gr.update(choices=[]),{},{}) # ══════════════════════════════════════════════════════════════ -# GRADIO UI +# GRADIO UI — clean white/light scientific style # ══════════════════════════════════════════════════════════════ CSS = """ +/* ── Base ──────────────────────────── */ body, .gradio-container { - background: #0D1117 !important; - color: #E6EDF3 !important; - font-family: 'Segoe UI', 'JetBrains Mono', monospace !important; + background: #F7F9FC !important; + color: #1A202C !important; + font-family: 'Segoe UI', 'Helvetica Neue', Arial, sans-serif !important; } -h1, h2, h3, label {color: #58A6FF !important;} -.progress-bar {background: #58A6FF !important;} +/* ── Headings ──────────────────────── */ +h1, h2, h3, h4 { color: #1A365D !important; } +label, .label-wrap { color: #2D3748 !important; font-weight: 600 !important; } +/* ── Primary button ────────────────── */ .gr-button-primary { - background: linear-gradient(135deg, #1F6FEB, #58A6FF) !important; - border: none !important; color: #0D1117 !important; font-weight: bold !important; + background: linear-gradient(135deg, #1A365D 0%, #2B6CB0 100%) !important; + color: #FFFFFF !important; + font-weight: 700 !important; + font-size: 15px !important; + border: none !important; + border-radius: 8px !important; + box-shadow: 0 2px 8px rgba(43,108,176,0.25) !important; +} +.gr-button-primary:hover { + background: linear-gradient(135deg, #2B6CB0 0%, #3182CE 100%) !important; + box-shadow: 0 4px 14px rgba(43,108,176,0.38) !important; +} +/* ── Panels ────────────────────────── */ +.gr-box, .gr-panel, .block { + background: #FFFFFF !important; + border: 1px solid #E2E8F0 !important; + border-radius: 10px !important; +} +/* ── Progress ──────────────────────── */ +.progress-bar { background: #2B6CB0 !important; } +/* ── Markdown ──────────────────────── */ +.prose, .markdown-body { + color: #1A202C !important; + background: transparent !important; +} +/* ── Input elements ────────────────── */ +input, select, textarea { + background: #FFFFFF !important; + color: #1A202C !important; + border-color: #CBD5E0 !important; +} +/* ── Tabs ──────────────────────────── */ +.tab-nav button { color: #2D3748 !important; } +.tab-nav button.selected { + color: #1A365D !important; + border-bottom: 3px solid #2B6CB0 !important; + font-weight: 700 !important; } -.gr-box, .gr-panel {background: #161B22 !important; border-color: #21262D !important;} """ -with gr.Blocks(css=CSS, title="MTA GWAS v9.0 | Dark Edition") as app: +with gr.Blocks(css=CSS, title="GWAS Analysis v10.0 | White Edition") as app: gr.Markdown(""" - # 🧬 GWAS Analysis Platform v9.0 — Dark Edition - ### 5-Model MRmlm Suite | LOD Selector | PCA Components | Circos Plot | Separate Plots + # 🧬 GWAS / MTA Analysis Platform v10.0 + ### Multi-Model Suite · Hill LD Decay · Dual Manhattan+LOD · Improved Circos · Full White Theme --- """) with gr.Row(): with gr.Column(scale=1): gr.Markdown(""" - ### 📋 CSV Format + ### 📋 Input CSV Format ``` - ID, Phenotype, M1, M2, ... - -, Chr, 1, 1, ... - -, Pos, 134521, ..., ... - IRRI-1, 25.34, 0, 2, ... + ID, Phenotype, Mrk1, Mrk2, ... + -, Chr, 1, 2, ... + -, Pos, 134521, 200000, ... + Sample1, 25.34, 0, 2, ... + Sample2, 18.72, 1, 0, ... ``` - Genotypes: 0/1/2 (−1 or blank = missing) + **Genotype codes:** 0 / 1 / 2 + **Missing:** −1 or blank """) input_file = gr.File(label="📁 Upload CSV", file_types=[".csv"]) with gr.Column(scale=1): - gr.Markdown("### ⚙️ QC Parameters") - miss_sample = gr.Slider(5,100,value=30,step=5,label="Max sample missing rate (%)") - miss_marker = gr.Slider(5,100,value=30,step=5,label="Max marker missing rate (%)") - maf_thr = gr.Slider(0,25,value=3,step=1,label="Min MAF (%)") - gr.Markdown("### 📐 Thresholds") - lod_thresh = gr.Slider(0.5,10.0,value=3.0,step=0.1, - label="LOD threshold (user-defined line on LOD panels)") - n_pc = gr.Slider(2,20,value=5,step=1, - label="Number of PCs (for MLM/CMLM control & PCA plot)") + gr.Markdown("### ⚙️ Quality Control") + miss_sample = gr.Slider(5, 100, value=30, step=5, + label="Max sample missing rate (%)") + miss_marker = gr.Slider(5, 100, value=30, step=5, + label="Max marker missing rate (%)") + maf_thr = gr.Slider(0, 25, value=3, step=1, + label="Min MAF (%)") with gr.Column(scale=1): - gr.Markdown("### 🔬 Select Models") + gr.Markdown("### 📐 Analysis Settings") + lod_thresh = gr.Slider(0.5, 10.0, value=3.0, step=0.1, + label="LOD threshold (user-defined line on LOD panel)") + n_pc = gr.Slider(2, 20, value=5, step=1, + label="Number of PCs (MLM/CMLM control + PCA plot)") + gr.Markdown("### 🔬 Models to Run") chk_glm = gr.Checkbox(value=True, label="GLM — General Linear Model") chk_mlm = gr.Checkbox(value=True, label="MLM — Mixed Linear Model") chk_cmlm = gr.Checkbox(value=True, label="CMLM — Compressed MLM") chk_bslmm = gr.Checkbox(value=False, label="BSLMM — Bayesian Sparse LMM ⚠️ slow") - chk_farmcpu = gr.Checkbox(value=True, label="FarmCPU — Fixed & Random") + chk_farmcpu = gr.Checkbox(value=True, label="FarmCPU — Fixed & Random Circulating") - gr.Markdown("> **⏱️ Speed:** GLM/MLM/CMLM/FarmCPU ~1–3 min for 3000 markers. BSLMM adds ~2–4 min.") + gr.Markdown(""" + > **ℹ️ About the analysis:** + > **Manhattan panels** show both −log₁₀(P) and LOD Score vs chromosome in a dual layout. + > **LD Decay** uses the Hill (1975) nonlinear model: E(r²) = 1/(1 + a·d) + b. + > **Circos** shows concentric per-model tracks with thick bars for significant SNPs. + > ⏱️ Speed: GLM/MLM/CMLM/FarmCPU ~1–3 min for 3000 markers. BSLMM adds ~2–4 min. + """) run_btn = gr.Button("🚀 Run GWAS Analysis", variant="primary", size="lg") gr.Markdown("---") @@ -1465,22 +1739,28 @@ with gr.Blocks(css=CSS, title="MTA GWAS v9.0 | Dark Edition") as app: choices=[], value=None, interactive=True) with gr.Row(): - man_out = gr.Image(label="🗺️ Manhattan Plot (−log₁₀P & LOD)") - qq_out = gr.Image(label="📈 QQ Plot") + man_out = gr.Image(label="🗺️ Manhattan Plot (−log₁₀P top | LOD bottom)") + qq_out = gr.Image(label="📈 QQ Plot (genomic inflation λ)") with gr.Row(): - pca_out = gr.Image(label="🔬 PCA Analysis (Scree + Biplots)") - circos_out = gr.Image(label="🌐 Circos — Multi-Model MTA Comparison") + pca_out = gr.Image(label="🔬 PCA Analysis (Scree + PC1v2 + PC2v3)") + circos_out = gr.Image(label="🌐 Circos — Multi-Model MTA") with gr.Row(): - ld_out = gr.Image(label="🧬 LD Decay (White Background)") - cmp_out = gr.Image(label="⚖️ Model Concordance") + ld_out = gr.Image(label="🧬 LD Decay (Hill 1975 model, white bg)") + cmp_out = gr.Image(label="⚖️ Model P-value Concordance") with gr.Row(): - ph_out = gr.Image(label="📊 Phenotype Distribution") - dl_out = gr.File(label="📦 Download All Results (ZIP)") + ph_out = gr.Image(label="📊 Phenotype Distribution") + kin_out = gr.Image(label="🔥 Kinship Matrix Heatmap") + + dl_out = gr.File(label="📦 Download All Results (ZIP)") - gr.Markdown("---\n**MTA GWAS v9.0** — LD Decay & Circos: white background | All other plots: dark theme") + gr.Markdown(""" + --- + **MTA GWAS v10.0** — All plots use white background & black text for publication quality. + LD Decay: Hill (1975) model | Manhattan: dual −log₁₀P + LOD panels | Circos: concentric tracks + """) man_paths_state = gr.State({}) qq_paths_state = gr.State({}) @@ -1493,7 +1773,7 @@ with gr.Blocks(css=CSS, title="MTA GWAS v9.0 | Dark Edition") as app: outputs=[summary_out, man_out, qq_out, pca_out, ld_out, circos_out, cmp_out, ph_out, - dl_out, + dl_out, kin_out, man_model_sel, qq_model_sel, man_paths_state, qq_paths_state], show_progress="full",