diff --git "a/app.py" "b/app.py" --- "a/app.py" +++ "b/app.py" @@ -1,14 +1,15 @@ # -*- coding: utf-8 -*- """ -MTA Analysis Tool v8.3 — FIXES: - ✅ Persistent output directory (no tempfile cleanup race) - ✅ BSLMM: n_boot reduced + Ridge fallback for speed - ✅ FarmCPU: vectorised inner loop - ✅ LD decay: fully vectorised (no Python lag loop) - ✅ LD scatter: capped at 8000 pts for fast PNG rendering - ✅ Gradio: gr.File returns actual path (not None race) - ✅ Progress status updates in UI - ✅ Timeout-safe: all heavy loops have max-iteration caps +MTA Analysis Tool v9.0 — NEW FEATURES: + ✅ 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) + ✅ Circos plot: all models compared, MTA detections with per-model colors + ✅ Interpretation text for Circos and LD + ✅ Persistent output directory + ✅ BSLMM: Ridge fallback for speed + ✅ FarmCPU: corrected vectorised scan """ import gradio as gr @@ -17,57 +18,76 @@ import numpy as np import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt +import matplotlib.patches as mpatches +import matplotlib.colors as mcolors +from matplotlib.patches import FancyArrowPatch, Arc, Wedge +from matplotlib.gridspec import GridSpec from scipy import stats from scipy.interpolate import make_interp_spline -import os, warnings, zipfile, shutil +import os, warnings, zipfile from pathlib import Path -from sklearn.linear_model import ElasticNetCV, Ridge +from sklearn.linear_model import ElasticNetCV, Ridge, RidgeCV from sklearn.preprocessing import StandardScaler +from sklearn.decomposition import PCA warnings.filterwarnings('ignore') -# ── Persistent output directory (survives Gradio's file-serving lifecycle) ── OUTPUT_DIR = Path("/tmp/gwas_outputs") OUTPUT_DIR.mkdir(parents=True, exist_ok=True) # ══════════════════════════════════════════════════════════════ -# THEME +# DARK GWAS THEME — Standard dark palette # ══════════════════════════════════════════════════════════════ -BG = "#FDFBFF" -PANEL = "#F4EFFE" -GRID_C = "#E2D9F3" -TEXT_C = "#2D1B5E" -ACCENT = "#7C3AED" -RED_C = "#E11D48" -GOLD_C = "#D97706" -TEAL_C = "#0891B2" -GREEN_C = "#15803D" +BG = "#0D1117" # GitHub dark bg +PANEL = "#161B22" # slightly lighter panel +GRID_C = "#21262D" # subtle grid +TEXT_C = "#E6EDF3" # primary text +SUBTEXT = "#8B949E" # secondary text +ACCENT = "#58A6FF" # blue accent +RED_C = "#F85149" # significant SNP red +GOLD_C = "#E3B341" # suggestive gold +TEAL_C = "#39D353" # teal +GREEN_C = "#3FB950" # green +ORANGE_C = "#F0883E" # orange + +# Standard GWAS chromosome alternating colors (dark mode) +CHR_EVEN = "#58A6FF" # blue +CHR_ODD = "#3FB950" # green CHROM_PALETTE = [ - "#7C3AED","#DB2777","#059669","#0284C7","#D97706", - "#6D28D9","#BE185D","#047857","#0369A1","#B45309", - "#4F46E5","#9D174D","#065F46","#075985","#92400E", - "#7C3AED","#C026D3","#0F766E","#1D4ED8","#CA8A04", - "#6366F1","#EC4899","#10B981","#3B82F6","#F59E0B", + "#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", ] MODEL_COLORS = { - 'GLM': '#7C3AED', - 'MLM': '#DB2777', - 'CMLM': '#059669', - 'BSLMM': '#D97706', - 'FarmCPU': '#0284C7', + 'GLM': '#58A6FF', # blue + 'MLM': '#F85149', # red + 'CMLM': '#3FB950', # green + 'BSLMM': '#E3B341', # gold + 'FarmCPU': '#BC8CFF', # purple } -def _style(): +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.7, - 'figure.dpi': 100, 'font.family': 'DejaVu Sans', - 'axes.spines.top': False, 'axes.spines.right': False, - 'legend.framealpha':0.95, 'legend.edgecolor': GRID_C, + '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, }) @@ -77,31 +97,24 @@ def _style(): 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() cv = cv[:-2] if cv.endswith('.0') else cv cv = cv.replace('chr','').replace('Chr','').strip() chrom_dict[m] = cv if cv not in ('', 'nan', '-') else '0' - - pv = str(pos_row[m]).strip() + pv_s = str(pos_row[m]).strip() try: - pos_dict[m] = float(pv) + 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 @@ -109,12 +122,10 @@ def parse_input_csv(filepath): .apply(pd.to_numeric, errors='coerce') .replace(-1, 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, - geno_raw.values, marker_cols, - chromosomes, positions) + geno_raw.values, marker_cols, chromosomes, positions) # ══════════════════════════════════════════════════════════════ @@ -133,854 +144,998 @@ def compute_kinship(G): # ══════════════════════════════════════════════════════════════ -# MODEL 1: GLM +# MODELS # ══════════════════════════════════════════════════════════════ 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 - - -# ══════════════════════════════════════════════════════════════ -# MODEL 2: MLM -# ══════════════════════════════════════════════════════════════ -def model_mlm(G, y, K): - n = len(y) - n_pc = min(5, n - 2) - eigvals, eigvecs = np.linalg.eigh(K) + 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) 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 - - -# ══════════════════════════════════════════════════════════════ -# MODEL 3: CMLM -# ═══════���══════════════════════════════════════════════════════ -def model_cmlm(G, y, K, n_groups=None): + 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 - - -# ══════════════════════════════════════════════════════════════ -# MODEL 4: BSLMM ← FIXED: faster with Ridge fallback + fewer boots -# ══════════════════════════════════════════════════════════════ -def model_bslmm(G, y, n_boot=8): # ← was 20, now 8 - """ - Speed fix: - - Reduced bootstrap iterations to 8 (was 20). - - Ridge fallback if ElasticNet is slow (n_markers > 2000). - - max_iter capped at 1000. - """ - sc = StandardScaler() - Xs = sc.fit_transform(G) - n, m = Xs.shape - - # Use Ridge for large marker sets — much faster, still regularised - if m > 2000: - alphas = np.logspace(-3, 3, 20) - mdl = Ridge(alpha=1.0, fit_intercept=True) - from sklearn.linear_model import RidgeCV as _RCV - mdl = _RCV(alphas=alphas, cv=3) - mdl.fit(Xs, y) - coef = mdl.coef_ + 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_ 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: - if m > 2000: - from sklearn.linear_model import RidgeCV as _RCV2 - eb = _RCV2(alphas=[0.1,1,10], cv=3) - else: - eb = 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 Exception: - 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) + 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] + 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) + 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 # ══════════════════════════════════════════════════════════════ -# MODEL 5: FarmCPU ← FIXED: vectorised scan +# PLOT: PHENOTYPE DISTRIBUTION (separate) # ══════════════════════════════════════════════════════════════ -def model_farmcpu(G, y, K, max_iter=3): - """ - Corrected FarmCPU: - - Pseudo-QTNs enter as fixed covariates in y only (not projected from G) - - Each marker tested raw against y_cond via OLS with df = n - q - 2 - - This avoids the double-projection inflation seen when both X and y - are residualised by the same projector. - """ - 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 × q pseudo-QTNs as fixed covariates +def plot_phenotype(phenotypes, save_path): + _style_dark() + 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) - # Partial y on pseudo-QTNs only (leave G raw) - 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 Exception: - y_cond = y.copy() + 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, + label=f'Mean = {np.mean(pv):.3f}') + ax.axvline(np.median(pv), color=GOLD_C, 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) + 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)) - q = covs.shape[1] - df = max(n - q - 2, 1) # corrected degrees of freedom + ax = axes[1]; ax.set_facecolor(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') + line_x = np.array([osm.min(), osm.max()]) + ax.plot(line_x, slope*line_x+intercept, color=RED_C, 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) - pv_new = np.ones(m); bv_new = np.zeros(m); sv_new = np.zeros(m) - for i in range(m): - x = G[:, i] # raw marker (NOT residualised) - if x.std() < 1e-9: continue - # OLS with intercept: [1, x] → y_cond - X2 = np.column_stack([np.ones(n), x]) - try: - b, res, _, _ = np.linalg.lstsq(X2, y_cond, rcond=None) - except Exception: - 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 + plt.tight_layout(pad=1.5) + plt.savefig(save_path, dpi=110, bbox_inches='tight', facecolor=BG) + plt.close(fig) # ══════════════════════════════════════════════════════════════ -# PLOT: MANHATTAN +# PLOT: PCA (separate — scree + biplot) # ══════════════════════════════════════════════════════════════ -def _draw_manhattan_ax(ax, x_pos, log_vals, sig_set, unique_chroms, - chrom_to_idx, CHROM_PALETTE, bonf_line, - sug_line, ylabel, mcol, mname, n_sig, offset, GAP, - y_cap=None): - """Shared drawing helper for one Manhattan subplot.""" - for ci, ch in enumerate(unique_chroms): - idxs = chrom_to_idx.get(ch, []) - if not idxs: continue - if ci % 2 == 0: - ax.axvspan(x_pos[idxs[0]]-.5, x_pos[idxs[-1]]+.5, - color='#EDE9FE', alpha=0.35, zorder=0) - shade = CHROM_PALETTE[ci % len(CHROM_PALETTE)] - 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], log_vals[norm], c=shade, - s=8, alpha=0.55, linewidths=0, zorder=2) - if sel: - ax.scatter(x_pos[sel], log_vals[sel], c=RED_C, s=180, - alpha=0.15, linewidths=0, zorder=3) - ax.scatter(x_pos[sel], log_vals[sel], c=RED_C, s=45, - alpha=1.0, edgecolors='white', linewidths=0.7, - marker='D', zorder=4) - ax.axhline(bonf_line, color=RED_C, ls='--', lw=1.5, alpha=0.85, - label=f'Bonferroni ({bonf_line:.1f})') - ax.axhline(sug_line, color=GOLD_C, ls=':', lw=1.3, alpha=0.8, - label=f'Suggestive ({sug_line:.1f})') - ax.set_xlim(-GAP, offset) - peak = float(log_vals.max()) - ylim_top = max(peak * 1.15, bonf_line * 1.15, 1.0) - if y_cap is not None: - ylim_top = min(ylim_top, y_cap) - ax.set_ylim(0, ylim_top) - ax.set_ylabel(ylabel, fontsize=9, fontweight='bold') - ax.set_title(f'Model: {mname}', fontsize=10, fontweight='bold', - color=mcol, pad=3) - ax.yaxis.grid(True, color=GRID_C, lw=0.5) - ax.legend(loc='upper right', fontsize=7) - ax.text(0.01, 0.90, f'{n_sig} sig.', - transform=ax.transAxes, fontsize=8, color=RED_C, fontweight='bold') - - -def plot_manhattan_multi(mn, chroms, model_pvals, bonf_thresh, save_path): - """ - Two panels per model: - Top : −log₁₀(P) — standard GWAS significance scale - Bottom : LOD score = −log₁₀(P) × log₁₀(e) / 2 ≈ −log₁₀(P) × 0.2171 - Significant SNPs (red diamonds) shown on both panels. - FarmCPU y-axis capped at 3× Bonferroni to prevent inflation blowout. - """ - _style() - LOD_FACTOR = np.log10(np.e) / 2.0 # ≈ 0.2171 P→LOD conversion +def plot_pca(geno_q, pheno_q, n_components, save_path): + _style_dark() + 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]) + + 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) + gs = GridSpec(1, 3, figure=fig, wspace=0.32) + + # --- Scree plot --- + ax0 = fig.add_subplot(gs[0]); ax0.set_facecolor(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) + 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)): + 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) + + # --- PC1 vs PC2 biplot coloured by phenotype --- + ax1 = fig.add_subplot(gs[1]); ax1.set_facecolor(PANEL) + pheno_norm = (pheno_q - np.nanmin(pheno_q)) / (np.nanmax(pheno_q)-np.nanmin(pheno_q)+1e-9) + 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) + + # --- PC2 vs PC3 biplot (if available) --- + ax2 = fig.add_subplot(gs[2]); ax2.set_facecolor(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) + 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) + + plt.tight_layout() + plt.savefig(save_path, dpi=110, bbox_inches='tight', facecolor=BG) + plt.close(fig) + return evr, cumev, scores + +# ══════════════════════════════════════════════════════════════ +# PLOT: MANHATTAN (one per model, separate files) +# ══════════════════════════════════════════════════════════════ +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))) - n_models = len(model_pvals) - GAP = max(8, len(mn) // 150) - + 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 + 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 - # 2 rows per model (−log10P + LOD) - n_rows = n_models * 2 - row_h = [3.0 if r % 2 == 0 else 2.2 for r in range(n_rows)] - fig, axes = plt.subplots(n_rows, 1, - figsize=(18, sum(row_h)), - facecolor=BG, - gridspec_kw={'height_ratios': row_h}, - sharex=True) - axes = list(axes) +def plot_manhattan_single(mn, ch_q, pv, mname, bonf_thresh, lod_thresh_user, + save_path, lod_mode=False): + """ + Single-model Manhattan. + lod_mode: if True plot LOD instead of -log10P. + lod_thresh_user: user-specified LOD threshold line (extra annotation). + """ + _style_dark() + 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 - - for mi, (mname, pv) in enumerate(model_pvals.items()): - ax_p = axes[mi * 2] # −log10P panel - ax_lod = axes[mi * 2 + 1] # LOD panel - for ax in (ax_p, ax_lod): - ax.set_facecolor(PANEL) - - 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 = int(len(sig_set)) - mcol = MODEL_COLORS.get(mname, ACCENT) - - # Cap FarmCPU y-axis at 3× Bonferroni to prevent inflation blowout - y_cap_p = bonf_log * 3.5 if mname == 'FarmCPU' else None - y_cap_lod = bonf_lod * 3.5 if mname == 'FarmCPU' else None - - _draw_manhattan_ax(ax_p, x_pos, log_p, sig_set, unique_chroms, - chrom_to_idx, CHROM_PALETTE, bonf_log, sug_log, - '−log₁₀(P)', mcol, mname, n_sig, offset, GAP, - y_cap=y_cap_p) - _draw_manhattan_ax(ax_lod, x_pos, lod, sig_set, unique_chroms, - chrom_to_idx, CHROM_PALETTE, bonf_lod, sug_lod, - 'LOD score', mcol, f'{mname} (LOD)', n_sig, - offset, GAP, y_cap=y_cap_lod) - - # Subtle divider between model pairs - ax_lod.spines['bottom'].set_linewidth(2.0) - ax_lod.spines['bottom'].set_color(GRID_C) - - axes[-1].set_xticks([x for x, _ in chrom_xticks]) - axes[-1].set_xticklabels([l for _, l in chrom_xticks], fontsize=7) - axes[-1].set_xlabel('Chromosome', fontsize=11, fontweight='bold') - - plt.suptitle('GWAS Manhattan Plots — −log₁₀(P) & LOD Score', - fontsize=13, fontweight='bold', y=1.005, color=TEXT_C) - plt.tight_layout(pad=1.0, h_pad=0.4) - plt.savefig(save_path, dpi=100, bbox_inches='tight', facecolor=BG) + mcol = MODEL_COLORS.get(mname, ACCENT) + + # Two panels: −log10P + LOD + 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) + 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 ci % 2 == 0: + ax.axvspan(x_pos[idxs[0]]-.5, x_pos[idxs[-1]]+.5, + color='#1C2128', alpha=0.5, 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) + 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.axhline(bonf_line, color=RED_C, 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, + label=f'Suggestive ({sug_line:.2f})', zorder=5) + # User-defined LOD threshold on LOD panel + 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) + + 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) plt.close(fig) # ══════════════════════════════════════════════════════════════ -# PLOT: QQ +# PLOT: QQ — FIXED (standard dark GWAS, proper diagonal) # ══════════════════════════════════════════════════════════════ -def plot_qq_multi(model_pvals, bonf_thresh, save_path): - _style() - n_models = len(model_pvals) - ncols = min(3, n_models) - nrows = (n_models + ncols - 1) // ncols - fig, axes = plt.subplots(nrows, ncols, - figsize=(5.5*ncols, 5*nrows), - facecolor=BG, squeeze=False) +def plot_qq_single(pv_raw, mname, bonf_thresh, save_path): + """ + Standard GWAS QQ plot: + - Dark background + - Proper y=x null diagonal (expected = observed under H0) + - 95% confidence band (beta distribution) + - Red: above Bonferroni, blue: below + - λ (genomic inflation factor) displayed prominently + """ + _style_dark() + mcol = MODEL_COLORS.get(mname, ACCENT) bonf_log = -np.log10(bonf_thresh) - lam_dict = {} - - for idx, (mname, pv_raw) in enumerate(model_pvals.items()): - row, col = divmod(idx, ncols) - ax = axes[row][col]; ax.set_facecolor(PANEL) - - pv = np.array(pv_raw, dtype=float) - pv = pv[np.isfinite(pv) & (pv > 0) & (pv <= 1)] - if not len(pv): - ax.text(0.5, 0.5, 'No valid p-values', - ha='center', va='center', transform=ax.transAxes); continue - - n = len(pv) - obs_log = -np.log10(np.sort(pv))[::-1] - exp_log = -np.log10(np.arange(1, n+1) / (n+1))[::-1] - - 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_dict[mname] = lam - - mcol = MODEL_COLORS.get(mname, ACCENT) - colors_dot = np.where(obs_log >= bonf_log, RED_C, mcol) - ax.scatter(exp_log, obs_log, c=colors_dot, s=10, - alpha=0.65, linewidths=0, zorder=2) - - maxv = max(obs_log.max(), exp_log.max()) * 1.08 - ax.plot([0,maxv],[0,maxv], color='#374151', lw=1.5, ls='--', zorder=3) - ax.axhline(bonf_log, color=RED_C, ls=':', lw=1.3, alpha=0.8) - - ci_up = -np.log10(stats.beta.ppf(0.025, np.arange(1,n+1), - np.arange(n,0,-1)) + 1e-300)[::-1] - ci_lo = -np.log10(stats.beta.ppf(0.975, np.arange(1,n+1), - np.arange(n,0,-1)) + 1e-300)[::-1] - ax.fill_between(exp_log, ci_lo, ci_up, color=mcol, alpha=0.12, zorder=1) - - ax.set_xlim(0, maxv); ax.set_ylim(0, maxv) - ax.set_xlabel('Expected −log₁₀(P)', fontsize=10, fontweight='bold') - ax.set_ylabel('Observed −log₁₀(P)', fontsize=10, fontweight='bold') - ax.set_title(f'{mname} QQ', fontsize=11, fontweight='bold', color=mcol) - ax.text(0.05, 0.92, f'λ = {lam:.3f}', - transform=ax.transAxes, fontsize=11, fontweight='bold', - color=mcol, - bbox=dict(boxstyle='round', facecolor=BG, - edgecolor=mcol, alpha=0.9, lw=1.2)) - ax.grid(True, color=GRID_C, lw=0.6) - - for extra in range(n_models, nrows*ncols): - r, c = divmod(extra, ncols) - axes[r][c].set_visible(False) - - plt.suptitle('QQ Plots — λ = genomic inflation', - fontsize=13, fontweight='bold', color=TEXT_C) - plt.tight_layout(pad=1.5) - plt.savefig(save_path, dpi=100, bbox_inches='tight', facecolor=BG) + + 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) + + 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) + obs_sorted = np.sort(pv) + # Expected: uniform p-values → -log10((rank)/(n+1)) + exp_log = -np.log10(ranks / (n + 1)) + obs_log = -np.log10(obs_sorted) + # Sort both descending so largest exp goes to right + sort_idx = np.argsort(exp_log)[::-1] + exp_log = exp_log[sort_idx] + obs_log = obs_log[sort_idx] + + # 95% CI via Beta distribution + 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: red if above Bonferroni, model color otherwise + 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, + 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') + + # Null diagonal (y = x): this IS the expected line + 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)') + + # Bonferroni horizontal line + ax.axhline(bonf_log, color=RED_C, ls=':', lw=1.4, alpha=0.8, + zorder=5, label=f'Bonferroni ({bonf_log:.2f})') + + # Genomic inflation factor λ + 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 + 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)) + + 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.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.text(0.98, 0.04, f'n = {n:,} markers', + transform=ax.transAxes, ha='right', fontsize=9, color=SUBTEXT) + + plt.tight_layout() + plt.savefig(save_path, dpi=110, bbox_inches='tight', facecolor=BG) plt.close(fig) - return lam_dict + return lam # ══════════════════════════════════════════════════════════════ -# LD COMPUTATION — fully vectorised, no Python lag loop +# PLOT: LD DECAY (separate) # ══════════════════════════════════════════════════════════════ def _compute_ld_pairs_bp(G, bp_pos, max_lag=30): - """ - Vectorised: compute all (i,j) pairs with j-i <= max_lag - using upper-triangle index trick — no Python for-loop over lags. - For 40 markers × 30 lags → 1 numpy call instead of 30. - """ - m = G.shape[1] - G = G.astype(np.float32) # float32 halves memory - - # All pairs (i,j) with 0 < j-i <= max_lag - 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] # n_samples × n_pairs - 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.0 - p2 = Y.mean(0) / 2.0 - p11 = ((X == 2) & (Y == 2)).mean(0) / 2.0 - 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) - + m=G.shape[1]; G=G.astype(np.float32) + 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) -# ══════════════════════════════════════════════════════════════ -# PLOT: LD DECAY — fast + scatter downsampled for rendering -# ══════════════════════════════════════════════════════════════ def plot_ld_decay_bp(genotypes, chromosomes, positions, save_path, max_m=50): - _style() - 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: - bp_arr = np.arange(len(positions), dtype=float) * 1000 - - all_dist, all_r2, all_dp, all_ch = [], [], [], [] - chrom_stats = {} - rng = np.random.default_rng(0) - + _style_dark() + 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: bp_arr=np.arange(len(positions),dtype=float)*1000 + all_dist,all_r2,all_dp,all_ch=[],[],[],[] + chrom_stats={}; rng=np.random.default_rng(0) for ch in unique_chroms: - idxs = chrom_to_idx.get(str(ch), []) - if len(idxs) < 4: continue - if len(idxs) > max_m: - idxs = sorted(rng.choice(idxs, max_m, replace=False).tolist()) - - G_ch = genotypes[:, idxs].copy().astype(float) - 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) + idxs=chrom_to_idx.get(str(ch),[]) + if len(idxs)<4: continue + if len(idxs)>max_m: idxs=sorted(rng.choice(idxs,max_m,replace=False).tolist()) + G_ch=genotypes[:,idxs].copy().astype(float); 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): continue - all_dist.extend(dist.tolist()); all_r2.extend(r2.tolist()) all_dp.extend(dp.tolist()); 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, - } - + 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} if not all_dist: - fig, ax = plt.subplots(figsize=(10,6), facecolor=BG) - ax.text(0.5, 0.5, 'No LD data available (need ≥4 markers/chr)', - ha='center', va='center', transform=ax.transAxes, - fontsize=13, color=TEXT_C) - plt.savefig(save_path, dpi=100, bbox_inches='tight') - plt.close(fig) - return chrom_stats, "No LD data available." - - dist_arr = np.array(all_dist, dtype=float) - 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() - scale, unit_label = (1_000_000,'Mb') if max_bp>=1e6 else (1_000,'kb') if max_bp>=1000 else (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] - bins = np.linspace(0, max_scaled, 81) - ctrs, meds = [], [] + fig,ax=plt.subplots(figsize=(10,6),facecolor=BG) + ax.set_facecolor(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=TEXT_C) + plt.savefig(save_path,dpi=110,bbox_inches='tight',facecolor=BG) + plt.close(fig); return chrom_stats,"No LD data available." + dist_arr=np.array(all_dist,dtype=float); 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() + scale,unit_label=((1_000_000,'Mb') if max_bp>=1e6 else (1_000,'kb') if max_bp>=1000 else (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] + bins=np.linspace(0,max_scaled,81); ctrs,meds=[],[] for i in range(80): - m = (dv>=bins[i]) & (dv=3: - ctrs.append((bins[i]+bins[i+1])/2.) - meds.append(np.median(rv[m])) - - ctrs = np.array(ctrs); meds = np.array(meds) - xs_smooth = ys_smooth = 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]]) - + m=(dv>=bins[i])&(dv=3: ctrs.append((bins[i]+bins[i+1])/2.); meds.append(np.median(rv[m])) + ctrs=np.array(ctrs); meds=np.array(meds) + xs_smooth=ys_smooth=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]]) def _fmt(v): return f"{v:.2f} {unit_label}" - ilines = [] + ilines=[] 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}]") - else: - ilines.append("• Half-decay not reached — LD persists across full range") - if 'r2_02' in ann: - ilines.append(f"• r²<0.2 (GWAS tagging): {_fmt(ann['r2_02'])}") - if 'r2_01' in ann: - ilines.append(f"• r²<0.1 (independence): {_fmt(ann['r2_01'])}") - ilines.append(f"• Mean r²={np.mean(r2_arr):.3f} | Mean D'={np.mean(all_dp):.3f}") - ld_interp = "\n".join(ilines) - - chrom_color = {str(ch): CHROM_PALETTE[i%len(CHROM_PALETTE)] - for i, ch in enumerate(unique_chroms)} - - fig = plt.figure(figsize=(14,9), facecolor=BG) - gs = fig.add_gridspec(2,1, height_ratios=[3.8,1], hspace=0.08) - ax = fig.add_subplot(gs[0]) - axt = fig.add_subplot(gs[1]); axt.axis('off') - ax.set_facecolor('#EEE8FA') - - # Downsample scatter for fast PNG rendering (cap at 8000 total points) - MAX_SCATTER = 8000 - total_vis = int(mask.sum()) - ds_rate = max(1, total_vis // MAX_SCATTER) - + 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") + 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}") + ld_interp="\n".join(ilines) + chrom_color={str(ch):CHROM_PALETTE[i%len(CHROM_PALETTE)] + for i,ch in enumerate(unique_chroms)} + fig=plt.figure(figsize=(14,9),facecolor=BG) + gs=GridSpec(2,1,figure=fig,height_ratios=[3.8,1],hspace=0.08) + ax=fig.add_subplot(gs[0]); axt=fig.add_subplot(gs[1]); axt.axis('off') + ax.set_facecolor(PANEL) + MAX_SCATTER=8000; total_vis=int(mask.sum()); ds_rate=max(1,total_vis//MAX_SCATTER) for ch in unique_chroms: - key = str(ch) - idxs = np.where((ch_arr == key) & mask)[0] + key=str(ch); idxs=np.where((ch_arr==key)&mask)[0] if not len(idxs): continue - pts = idxs[::ds_rate] # uniform downsample - ax.scatter(dist_scaled[pts], r2_arr[pts], - c=chrom_color[key], s=6, alpha=0.38, - linewidths=0, zorder=2, label=key) - + pts=idxs[::ds_rate] + ax.scatter(dist_scaled[pts],r2_arr[pts],c=chrom_color[key], + s=7,alpha=0.45,linewidths=0,zorder=2,label=key) if xs_smooth is not None: - ax.fill_between(xs_smooth, 0, ys_smooth, color='#22C55E', alpha=0.22, zorder=3) - ax.plot(xs_smooth, ys_smooth, color=GREEN_C, lw=2.4, zorder=4, label='Median r²') - - ax.axhline(0.2, color='#111827', ls='--', lw=1.6, alpha=0.75, zorder=5, label='r²=0.2') - ann_styles = {'half':(GOLD_C,'½ decay',0.50,0.10), - 'r2_02':(RED_C,'r²=0.2',0.20,0.08), - 'r2_01':(TEAL_C,'r²=0.1',0.10,0.06)} + ax.fill_between(xs_smooth,0,ys_smooth,color=GREEN_C,alpha=0.18,zorder=3) + ax.plot(xs_smooth,ys_smooth,color=GREEN_C,lw=2.5,zorder=4,label='Median r²') + ax.axhline(0.2,color=GOLD_C,ls='--',lw=1.8,alpha=0.85,zorder=5,label='r²=0.2 (GWAS tag)') + ann_styles={'half':(GOLD_C,'½ decay',0.50,0.10), + 'r2_02':(RED_C,'r²=0.2',0.20,0.08), + 'r2_01':(TEAL_C,'r²=0.1',0.10,0.06)} for akey,(col,lbl,r2ref,offy) in ann_styles.items(): if akey not in ann: continue - xv = ann[akey] - ax.axvline(xv, color=col, ls=':', lw=1.9, alpha=0.88, zorder=6) - ax.annotate(f'{lbl}\n{_fmt(xv)}', xy=(xv,r2ref), - xytext=(xv+max_scaled*0.012, r2ref+offy), - fontsize=8.5, fontweight='bold', color=col, - arrowprops=dict(arrowstyle='->', color=col, lw=1.2), - bbox=dict(boxstyle='round,pad=0.3', fc=BG, ec=col, alpha=0.92, lw=1.1), - zorder=7) - - ax.set_xlim(0, max_scaled); ax.set_ylim(0, 1.05) - ax.set_xlabel(f'Physical distance ({unit_label})', fontsize=12, fontweight='bold') - ax.set_ylabel('LD estimate (R²)', fontsize=12, fontweight='bold') + xv=ann[akey] + ax.axvline(xv,color=col,ls=':',lw=1.9,alpha=0.88,zorder=6) + ax.annotate(f'{lbl}\n{_fmt(xv)}',xy=(xv,r2ref), + xytext=(xv+max_scaled*0.012,r2ref+offy), + fontsize=8.5,fontweight='bold',color=col, + arrowprops=dict(arrowstyle='->',color=col,lw=1.2), + bbox=dict(boxstyle='round,pad=0.3',fc=BG,ec=col,alpha=0.92,lw=1.1),zorder=7) + ax.set_xlim(0,max_scaled); ax.set_ylim(0,1.05) + ax.set_xlabel(f'Physical distance ({unit_label})',fontsize=12,fontweight='bold',color=TEXT_C) + ax.set_ylabel('LD (R²)',fontsize=12,fontweight='bold',color=TEXT_C) ax.set_title('LD Decay by Chromosome (Physical Distance)', - fontsize=14, fontweight='bold', color=TEXT_C, pad=10) - ax.xaxis.grid(True, color=GRID_C, lw=0.6, alpha=0.9) - ax.yaxis.grid(True, color=GRID_C, lw=0.6, alpha=0.9) - ax.set_axisbelow(True) - - 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')] - 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) - 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=9, fontsize=7.5, - loc='upper right', ncol=ncols_l, framealpha=0.93, - markerscale=2.2, handlelength=1.3) - - axt.text(0.005, 0.98, "LD DECAY INTERPRETATION\n"+"─"*70+"\n"+ld_interp, - transform=axt.transAxes, va='top', ha='left', - fontsize=8.5, color=TEXT_C, fontfamily='monospace', - bbox=dict(boxstyle='round,pad=0.5', facecolor='#EDE9FE', - edgecolor=GRID_C, alpha=0.95)) - - plt.savefig(save_path, dpi=110, bbox_inches='tight', facecolor=BG) + fontsize=14,fontweight='bold',color=TEXT_C,pad=10) + ax.xaxis.grid(True,color=GRID_C,lw=0.6,alpha=0.7) + ax.yaxis.grid(True,color=GRID_C,lw=0.6,alpha=0.7) + 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 (GWAS tag)')] + chrs=[(h,l) for h,l in zip(handles,labels) if l not in ('Median r²','r²=0.2 (GWAS tag)')] + ncols_l=max(1,(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=9,fontsize=7.5, + loc='upper right',ncol=ncols_l,framealpha=0.93, + markerscale=2.2,handlelength=1.3) + axt.text(0.005,0.98, + "LD DECAY INTERPRETATION\n"+"─"*72+"\n"+ld_interp, + transform=axt.transAxes,va='top',ha='left', + fontsize=9,color=TEXT_C,fontfamily='monospace', + bbox=dict(boxstyle='round,pad=0.5',facecolor=PANEL, + edgecolor=GRID_C,alpha=0.98)) + plt.savefig(save_path,dpi=110,bbox_inches='tight',facecolor=BG) plt.close(fig) - return chrom_stats, ld_interp + return chrom_stats,ld_interp # ══════════════════════════════════════════════════════════════ -# PLOT: MODEL COMPARISON +# PLOT: MODEL COMPARISON (separate) # ══════════════════════════════════════════════════════════════ def plot_model_comparison(model_pvals, save_path): - _style() - 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)] + _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=(5.5*ncols, 5*nrows), - facecolor=BG, squeeze=False) + 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.40,s=12,color=MODEL_COLORS.get(ma,ACCENT),edgecolors='none') - mx = max(pa.max(),pb.max())*1.05 - ax.plot([0,mx],[0,mx],color=GOLD_C,ls='--',lw=1.2) - ax.set_xlabel(f'{ma} −log₁₀(P)',fontsize=9,fontweight='bold') - ax.set_ylabel(f'{mb} −log₁₀(P)',fontsize=9,fontweight='bold') - ax.set_title(f'{ma} vs {mb} (r={corr:.3f})',fontsize=10,fontweight='bold') - ax.grid(True,color=GRID_C,lw=0.6,alpha=0.5) + 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) - plt.suptitle('Model P-value Concordance',fontsize=12,fontweight='bold',color=TEXT_C) + r,c=divmod(extra,ncols); axes[r][c].set_visible(False) plt.tight_layout(pad=1.5) - plt.savefig(save_path,dpi=100,bbox_inches='tight',facecolor=BG) + plt.savefig(save_path,dpi=110,bbox_inches='tight',facecolor=BG) plt.close(fig) # ══════════════════════════════════════════════════════════════ -# PLOT: PHENOTYPE +# PLOT: CIRCOS — all models, MTA detections, per-model colors # ══════════════════════════════════════════════════════════════ -def plot_phenotype(phenotypes, save_path): - _style() - pv = phenotypes[~np.isnan(phenotypes)] - fig, axes = plt.subplots(1,2,figsize=(11,4.5),facecolor=BG) - ax = axes[0]; ax.set_facecolor(PANEL) - ax.hist(pv,bins=30,color=ACCENT,alpha=0.72,edgecolor='white',lw=0.5) - ax.axvline(np.mean(pv),color=RED_C,ls='--',lw=1.6, - label=f'Mean={np.mean(pv):.2f}') - ax.axvline(np.median(pv),color=GOLD_C,ls=':',lw=1.6, - label=f'Median={np.median(pv):.2f}') - ax.set_xlabel('Phenotype Value',fontsize=11,fontweight='bold') - ax.set_ylabel('Frequency',fontsize=11,fontweight='bold') - ax.set_title('Phenotype Distribution',fontsize=12,fontweight='bold') - ax.legend(fontsize=9); ax.grid(True,color=GRID_C,lw=0.7) - sw_s,sw_p = stats.shapiro(pv[:5000]) - ax.text(0.97,0.95,f'Shapiro-Wilk p={sw_p:.3e}', - transform=ax.transAxes,ha='right',va='top',fontsize=8.5, - bbox=dict(boxstyle='round',facecolor=BG,edgecolor=GRID_C,alpha=0.9)) - ax = axes[1]; ax.set_facecolor(PANEL) - stats.probplot(pv,dist='norm',plot=ax) - ax.get_lines()[0].set(color=ACCENT,markersize=3,alpha=0.6) - ax.get_lines()[1].set(color=RED_C,lw=1.5) - ax.set_title('Normal Q-Q (Phenotype)',fontsize=12,fontweight='bold') - ax.grid(True,color=GRID_C,lw=0.7) - plt.tight_layout(pad=1.5) - plt.savefig(save_path,dpi=100,bbox_inches='tight',facecolor=BG) +def plot_circos(mn_q, ch_q, pos_q, model_pvals, bonf_thresh, lod_thresh_user, save_path): + """ + Circos-style circular plot: + - Outer ring: chromosomes (arc segments, alternating colors) + - Inner tracks: one ring per model, height = −log10(P) + - Significant SNPs (above Bonferroni): large colored dots on model ring + - MTA consensus (significant in ���2 models): inner hub markers + - Color-coded per model with legend + - Interpretation text below + """ + _style_dark() + LOD_FACTOR = np.log10(np.e) / 2.0 + + 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) + + # Assign angular span per chromosome 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 = 1.5 # degrees gap between chromosomes + total_gap = GAP_DEG * n_chr + avail_deg = 360 - total_gap + chr_deg = {ch: (chr_len[ch]/total_m)*avail_deg for ch in unique_chroms} + + # Build per-marker angle + marker_angle = np.zeros(len(mn_q)) + chr_start_deg = {} + cur = 0.0 + for ch in unique_chroms: + chr_start_deg[ch] = cur + idxs = chrom_to_idx[ch] + for rank, idx in enumerate(idxs): + marker_angle[idx] = cur + (rank/max(len(idxs)-1,1)) * chr_deg[ch] + cur += chr_deg[ch] + GAP_DEG + + # Radii + R_OUTER = 1.00 # outer chromosome ring + R_CHR = 0.94 # chromosome arc inner edge + R_TRACK_O = 0.90 # outermost model track + TRACK_W = 0.09 # width per model track + R_HUB = 0.30 # consensus MTA hub radius + R_INNER = 0.25 # inner decorative circle + + models = list(model_pvals.keys()) + n_models = len(models) + + bonf_log = -np.log10(bonf_thresh) + + # Detect significant markers per model + sig_per_model = {} + for mname, pv in model_pvals.items(): + sig_per_model[mname] = set(np.where(pv < bonf_thresh)[0]) + + # Consensus: significant in ≥ ceil(n_models/2) models + 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]: sig_counts[idx] += 1 + consensus_idx = set(np.where(sig_counts >= consensus_threshold)[0]) + + fig = plt.figure(figsize=(14, 14), facecolor=BG) + ax = fig.add_axes([0.05, 0.12, 0.90, 0.82], projection='polar') + ax.set_facecolor(BG) + ax.set_theta_zero_location('N') + ax.set_theta_direction(-1) + ax.set_ylim(0, 1.05) + ax.axis('off') + + # ── Chromosome outer arcs ────────────────────────────────────────── + for ci, ch in enumerate(unique_chroms): + 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[ci % len(CHROM_PALETTE)] + # Outer ring fill + ax.fill_between(theta_arc, R_CHR, R_OUTER, + color=col, alpha=0.75, zorder=3) + # Chromosome label + mid_rad = np.deg2rad((s_deg + e_deg)/2) + label_r = (R_CHR + R_OUTER)/2 + 0.025 + ax.text(mid_rad, label_r, str(ch), + ha='center', va='center', fontsize=7.5, + fontweight='bold', color=BG, zorder=6, + rotation=np.rad2deg(mid_rad)-90 if mid_rad < np.pi else np.rad2deg(mid_rad)+90) + + # ── Model tracks ─────────────────────────────────────────────────── + for mi, mname in enumerate(models): + pv = model_pvals[mname] + log_p = -np.log10(np.clip(pv, 1e-300, 1)) + mcol = MODEL_COLORS.get(mname, ACCENT) + # Track radii + r_out_track = R_TRACK_O - mi * TRACK_W + r_in_track = r_out_track - TRACK_W + 0.01 + + # Draw faint track background + theta_full = np.linspace(0, 2*np.pi, 500) + ax.fill_between(theta_full, r_in_track, r_out_track, + color=mcol, alpha=0.06, zorder=1) + ax.plot(theta_full, [r_out_track]*500, + color=mcol, lw=0.5, alpha=0.3, zorder=2) + + # Normalize log_p to track height + lp_max = max(bonf_log * 1.5, log_p.max(), 1.0) + norm_h = (log_p / lp_max) * TRACK_W + + # Bonferroni ring + bonf_r = r_in_track + (bonf_log/lp_max)*TRACK_W + ax.plot(theta_full, [bonf_r]*500, + color=RED_C, lw=0.8, ls='--', alpha=0.5, zorder=3) + + # Plot bars as radial lines (non-significant) + for idx, angle_deg in enumerate(marker_angle): + if idx in sig_per_model[mname]: continue + theta = np.deg2rad(angle_deg) + r_top = r_in_track + norm_h[idx] + ax.plot([theta, theta], [r_in_track, r_top], + color=mcol, lw=0.5, alpha=0.4, zorder=3) + + # Significant markers: large dots + 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) + ax.scatter(theta, r_top, s=45, c=mcol, alpha=1.0, + edgecolors='white', lw=0.6, zorder=6, + marker='o' if idx not in consensus_idx else 'D') + + # ── Consensus MTA hub ────────────────────────────────────────────── + for idx in consensus_idx: + theta = np.deg2rad(marker_angle[idx]) + n_models_sig = sig_counts[idx] + hub_r = R_HUB + (n_models_sig / n_models) * 0.06 + ax.scatter(theta, hub_r, s=80, c=ORANGE_C, + alpha=1.0, edgecolors='white', lw=0.8, + marker='*', zorder=8) + + # ── Inner decorative circle ──────────────────────────────────────── + theta_full = np.linspace(0, 2*np.pi, 500) + ax.plot(theta_full, [R_INNER]*500, color=GRID_C, lw=1.2, alpha=0.5, zorder=2) + ax.fill_between(theta_full, 0, R_INNER, + color='#1C2128', alpha=0.8, zorder=1) + + # ── Centre text ──────────────────────────────────────────────────── + n_consensus = len(consensus_idx) + n_total_sig = sum(len(v) for v in sig_per_model.values()) + ax.text(np.pi/2, 0, f'{n_consensus}\nMTA', + ha='center', va='center', fontsize=13, + fontweight='bold', color=ORANGE_C, zorder=9, + transform=ax.transData) + ax.text(np.pi/2, 0.12, f'{n_total_sig} total\nsig.', + ha='center', va='center', fontsize=8, + color=SUBTEXT, zorder=9, transform=ax.transData) + + # ── Legend ──────────────────────────────────────────────────────── + legend_elements = [ + mpatches.Patch(facecolor=MODEL_COLORS.get(m, ACCENT), alpha=0.85, + edgecolor='white', lw=0.5, label=m) + for m in models + ] + [ + plt.scatter([], [], marker='D', c=ACCENT, s=60, + edgecolors='white', lw=0.6, label='Sig. (single model)'), + plt.scatter([], [], marker='*', c=ORANGE_C, s=120, + edgecolors='white', lw=0.8, label=f'MTA consensus (≥{consensus_threshold} models)'), + plt.Line2D([0],[0], color=RED_C, 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.9, + facecolor=PANEL, edgecolor=GRID_C, + bbox_to_anchor=(0.5, 0.01)) + + # ── Title & interpretation ───────────────────────────────────────── + fig.text(0.5, 0.96, 'Circos Plot — Multi-Model GWAS Comparison', + ha='center', fontsize=15, fontweight='bold', color=TEXT_C) + fig.text(0.5, 0.935, + f'{n_chr} chromosomes | {len(mn_q)} markers | ' + f'{len(models)} models | {n_consensus} MTA consensus loci', + ha='center', fontsize=9, color=SUBTEXT) + + # Interpretation box + interp_lines = [ + f"■ Each coloured ring = one GWAS model (outer→inner: {', '.join(models)})", + f"■ Bar height ∝ −log₁₀(P); red dashed ring = Bonferroni threshold", + f"■ Diamond markers (◆) = significant in that model alone", + f"■ Star markers (★) = MTA consensus: significant in ≥{consensus_threshold}/{n_models} models", + f"■ Total significant loci: {n_total_sig} across all models; {n_consensus} are MTA consensus", + ] + fig.text(0.04, 0.07, "\n".join(interp_lines), + ha='left', fontsize=8, color=TEXT_C, fontfamily='monospace', + bbox=dict(boxstyle='round,pad=0.6', fc=PANEL, ec=GRID_C, alpha=0.95)) + + plt.savefig(save_path, dpi=110, bbox_inches='tight', facecolor=BG) plt.close(fig) # ══════════════════════════════════════════════════════════════ -# MAIN ANALYSIS ← FIXED: persistent paths, progress yields +# MAIN ANALYSIS # ══════════════════════════════════════════════════════════════ def run_analysis(input_file, miss_sample, miss_marker, maf_thresh, + lod_thresh_user, n_pc_user, run_glm, run_mlm, run_cmlm, run_bslmm, run_farmcpu, 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,None,None,None,None,None,None) - # ── FIXED: use a persistent, named output folder ��───────────────────── - run_id = pd.Timestamp.now().strftime("%Y%m%d_%H%M%S") - rdir = OUTPUT_DIR / run_id - pdir = rdir / 'plots' + 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.0 - mm_t = miss_marker/100.0 - mf_t = maf_thresh /100.0 + ms_t=miss_sample/100.; mm_t=miss_marker/100.; mf_t=maf_thresh/100. - progress(0.05, desc="Parsing CSV…") - (sids, pheno, geno, - mnames, chroms, positions) = parse_input_csv(input_file) - n_s, n_m = len(sids), len(mnames) + 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) - # ── QC ───────────────────────────────────────────────────────────── 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) + 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 i in range(n_m): - v = geno[:,i]; v = v[~np.isnan(v)] - if len(v): - f = np.mean(v)/2.0; maf_arr[i] = min(f,1-f) - - qc_m = (miss_m_r < mm_t) & (maf_arr >= mf_t) - qc_s = miss_s_r < ms_t - fallback = "" + 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 < rs - if qs.sum() >= 10: - qc_m,qc_s = qm,qs + qm=(miss_m_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}% / " - f"marker<{rm*100:.0f}%\n") + 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) + 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) + 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. " - "Try increasing missing-rate sliders.", - None,None,None,None,None,None) + if len(sids_q)<10: + return (f"## ⚠️ Only {len(sids_q)} samples passed QC.", + None,None,None,None,None,None,None,None,None) - bonf = 0.05 / n_q; bonf_log = -np.log10(bonf) + bonf=0.05/n_q; bonf_log=-np.log10(bonf) - progress(0.18, desc="Computing kinship matrix…") - K = compute_kinship(geno_q) + progress(0.16, desc="Computing kinship matrix…") + K=compute_kinship(geno_q) - # ── Models ───────────────────────────────────────────────────────── - model_pvals, model_betas, model_ses = {}, {}, {} - step_base = 0.20; n_models = sum([run_glm,run_mlm,run_cmlm,run_bslmm,run_farmcpu]) - step_size = 0.40 / max(n_models,1); step_i = 0 + # ── 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 if run_glm: - progress(step_base+step_i*step_size, desc="GLM…") - pv,bv,sv,rv = model_glm(geno_q,pheno_q) + 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="MLM (kinship PCs)…") - pv,bv,sv,rv = model_mlm(geno_q,pheno_q,K) + 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="CMLM (compressed kinship)…") - pv,bv,sv,rv = model_cmlm(geno_q,pheno_q,K) + 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="BSLMM (ElasticNet/Ridge + bootstrap)… [may take 1-2 min]") - pv,bv = model_bslmm(geno_q,pheno_q) + 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="FarmCPU (iterative QTN control)…") - pv,bv,sv = model_farmcpu(geno_q,pheno_q,K) + 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) + return ("## ⚠️ No models selected.",None,None,None,None,None,None,None,None,None) - # ── Results CSV ───────────────────────────────────────────────────── - progress(0.62, desc="Building results table…") - df = pd.DataFrame({'Marker':mn_q,'Chromosome':ch_q,'Position_bp':pos_q}) + # ── 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)) - 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[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) - 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.65, desc="Phenotype distribution plot…") - ph_path = str(pdir/'phenotype_dist.png') + # ── PLOTS (all separate) ─────────────────────────────────────── + progress(0.62, desc="Phenotype plot…") + ph_path=str(pdir/'phenotype_dist.png') plot_phenotype(pheno_q, ph_path) - progress(0.72, desc="Manhattan plots…") - man_path = str(pdir/'manhattan_lod.png') - plot_manhattan_multi(mn_q, ch_q, model_pvals, bonf, man_path) - - progress(0.80, desc="QQ plots…") - qq_path = str(pdir/'qq_plot.png') - lam_dict = plot_qq_multi(model_pvals, bonf, qq_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.87, desc="LD decay (bp)…") - 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.93, desc="Model comparison plot…") - cmp_path = str(pdir/'model_comparison.png') - plot_model_comparison(model_pvals, cmp_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 - # ── ZIP ────────────────────────────────────────────────────────────── - progress(0.96, desc="Packaging ZIP…") - zip_path = str(OUTPUT_DIR / f'GWAS_Results_{run_id}.zip') + 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.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)): 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}" return str(v) - sep = "| "+" | ".join(["---"]*len(cols))+" |" - rows = ["| "+" | ".join(_f(row[c]) for c in cols)+" |" - for _,row in sub.iterrows()] + 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()) - 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] + pca_rows="\n".join( + f"| PC{i+1} | {evr[i]:.2f}% | {cumev[i]:.2f}% |" + 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] - summary = f""" -## ✅ GWAS Analysis Complete — v8.3 + summary=f""" +## ✅ GWAS Analysis Complete — v9.0 ### 📊 QC Summary | Metric | Value | @@ -989,10 +1144,15 @@ def run_analysis(input_file, miss_sample, miss_marker, maf_thresh, | Markers (raw → QC) | {n_m} → **{n_q}** | | Chromosomes | **{len(set(ch_q))}** | | MAF ≥ | {maf_thresh:.1f}% | -| Sample missing < | {miss_sample:.0f}% | -| Marker missing < | {miss_marker:.0f}% | +| PCs used | {n_pc_user} | +| LOD threshold (user) | {lod_thresh_user:.2f} | {fallback} +### 🧬 PCA Variance Explained +| PC | % Variance | Cumulative | +|---|---|---| +{pca_rows} + ### 🔬 Model Results | Model | Sig. Markers (Bonferroni) | λ | Status | |---|---|---|---| @@ -1007,59 +1167,85 @@ def run_analysis(input_file, miss_sample, miss_marker, maf_thresh, {_mdt(df[top_cols])} --- -**Output saved to:** `{rdir}` +**Output:** `{rdir}` """ - progress(1.0, desc="Done! ✅") - # Return all actual file paths (not None) so Gradio can serve them + progress(1.0, desc="Done ✅") + + # Return: summary + first Manhattan, first QQ, PCA, LD, Circos, comparison, ZIP + first_man = list(man_paths.values())[0] if man_paths else None + first_qq = list(qq_paths.values())[0] if qq_paths else None + return (summary, - man_path, ld_path, qq_path, - cmp_path, ph_path, zip_path) + first_man, first_qq, pca_path, + ld_path, circos_path, cmp_path, ph_path, + zip_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()}) 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, + gr.update(choices=[]),gr.update(choices=[]),{},{}) # ══════════════════════════════════════════════════════════════ # GRADIO UI # ══════════════════════════════════════════════════════════════ CSS = """ -.gradio-container{font-family:'Segoe UI',Tahoma,sans-serif} -h1{color:#2D1B5E;border-bottom:3px solid #7C3AED;padding-bottom:8px} -.progress-bar{background:#7C3AED!important} +body, .gradio-container { + background: #0D1117 !important; + color: #E6EDF3 !important; + font-family: 'Segoe UI', 'JetBrains Mono', monospace !important; +} +h1, h2, h3, label {color: #58A6FF !important;} +.progress-bar {background: #58A6FF !important;} +.gr-button-primary { + background: linear-gradient(135deg, #1F6FEB, #58A6FF) !important; + border: none !important; color: #0D1117 !important; font-weight: bold !important; +} +.gr-box, .gr-panel {background: #161B22 !important; border-color: #21262D !important;} """ -with gr.Blocks(css=CSS, title="MTA GWAS v8.3") as app: +# Store plot paths between runs +_state = {"man_paths": {}, "qq_paths": {}} + +with gr.Blocks(css=CSS, title="MTA GWAS v9.0 | Dark Edition") as app: gr.Markdown(""" - # 🧬 GWAS Analysis Platform v8.3 - ### 5-Model MRmlm Suite | LD Decay in bp | Persistent Outputs | Progress Tracking + # 🧬 GWAS Analysis Platform v9.0 — Dark Edition + ### 5-Model MRmlm Suite | LOD Selector | PCA Components | Circos Plot | Separate Plots --- """) with gr.Row(): with gr.Column(scale=1): gr.Markdown(""" - ### 📋 CSV Format (3-row header) + ### 📋 CSV Format ``` - ID, Phenotype, M1, M2, ... - -, Chr, 1, 1, ... - -, Pos, 134521, ..., ... - IRRI-1, 25.34, 0, 2, ... + ID, Phenotype, M1, M2, ... + -, Chr, 1, 1, ... + -, Pos, 134521, ..., ... + IRRI-1, 25.34, 0, 2, ... ``` - **Genotypes:** 0/1/2 (−1 or blank = missing) + Genotypes: 0/1/2 (−1 or blank = missing) """) 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 (%)") + 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)") with gr.Column(scale=1): gr.Markdown("### 🔬 Select Models") @@ -1069,39 +1255,74 @@ with gr.Blocks(css=CSS, title="MTA GWAS v8.3") as app: chk_bslmm = gr.Checkbox(value=False, label="BSLMM — Bayesian Sparse LMM ⚠️ slow") chk_farmcpu = gr.Checkbox(value=True, label="FarmCPU — Fixed & Random") - gr.Markdown(""" - > **⏱️ Speed guide:** GLM/MLM/CMLM/FarmCPU take ~1–3 min for 3000 markers. - > BSLMM adds ~2–4 min extra. Disable it for quick runs. - """) + gr.Markdown("> **⏱️ 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("---") summary_out = gr.Markdown() + # ── Per-model selectors ─────────────────────────────────────────── with gr.Row(): - man_out = gr.Image(label="🗺️ Manhattan Plots") - ld_out = gr.Image(label="🧬 LD Decay (bp/kb/Mb)") + man_model_sel = gr.Dropdown(label="🗺️ Manhattan — select model", + choices=[], value=None, interactive=True) + qq_model_sel = gr.Dropdown(label="📈 QQ Plot — select model", + choices=[], value=None, interactive=True) with gr.Row(): - qq_out = gr.Image(label="📈 QQ Plots + λ") + man_out = gr.Image(label="🗺️ Manhattan Plot (−log₁₀P & LOD)") + qq_out = gr.Image(label="📈 QQ Plot") + + with gr.Row(): + pca_out = gr.Image(label="🔬 PCA Analysis (Scree + Biplots)") + circos_out = gr.Image(label="🌐 Circos — Multi-Model MTA Comparison") + + with gr.Row(): + ld_out = gr.Image(label="🧬 LD Decay") cmp_out = gr.Image(label="⚖️ Model 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") + dl_out = gr.File(label="📦 Download All Results (ZIP)") + + gr.Markdown("---\n**MTA GWAS v9.0** — Dark Edition | Separate plots | Circos | PCA | LOD selector") - gr.Markdown("---\n**MTA GWAS v8.3** | Persistent output paths | Progress tracking") + # Hidden state for plot paths + man_paths_state = gr.State({}) + qq_paths_state = gr.State({}) + # Run analysis run_btn.click( fn=run_analysis, inputs=[input_file, miss_sample, miss_marker, maf_thr, + lod_thresh, n_pc, chk_glm, chk_mlm, chk_cmlm, chk_bslmm, chk_farmcpu], - outputs=[summary_out, man_out, ld_out, qq_out, - cmp_out, ph_out, dl_out], + outputs=[summary_out, + man_out, qq_out, pca_out, + ld_out, circos_out, cmp_out, ph_out, + dl_out, + man_model_sel, qq_model_sel, + man_paths_state, qq_paths_state], show_progress="full", ) + # Model selector callbacks + def switch_manhattan(model_name, paths): + if not model_name or not paths: return None + return paths.get(model_name) + + def switch_qq(model_name, paths): + if not model_name or not paths: return None + return paths.get(model_name) + + man_model_sel.change(fn=switch_manhattan, + inputs=[man_model_sel, man_paths_state], + outputs=[man_out]) + qq_model_sel.change(fn=switch_qq, + inputs=[qq_model_sel, qq_paths_state], + outputs=[qq_out]) + + if __name__ == "__main__": app.launch(share=False, show_error=True, max_threads=4,