# -*- coding: utf-8 -*- """ Created on Fri Mar 27 17:27:53 2026 @author: Ashmi """ # -*- coding: utf-8 -*- """ MTA Analysis Tool v7.0 - Enhanced Multi-Model GWAS Platform Features: - Multiple GWAS models (Linear Regression, Mixed Model, ML-based) - LOD score calculations and visualization - Enhanced LD analysis with multiple metrics - Advanced QC with adaptive thresholds - Comprehensive model comparison """ import gradio as gr import pandas as pd import numpy as np import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import matplotlib.patches as mpatches from matplotlib.collections import LineCollection import seaborn as sns from scipy import stats from scipy.spatial.distance import pdist, squareform import os, warnings, tempfile, zipfile from sklearn.linear_model import ElasticNetCV, LassoCV, RidgeCV from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor from sklearn.preprocessing import StandardScaler from sklearn.feature_selection import mutual_info_regression, f_regression from sklearn.model_selection import cross_val_score, KFold from sklearn.metrics import mean_squared_error, r2_score import statsmodels.api as sm from statsmodels.formula.api import mixedlm from statsmodels.regression.linear_model import OLS, WLS import warnings warnings.filterwarnings('ignore') # ══════════════════════════════════════════════════════════════ # ENHANCED PLOT THEME # ══════════════════════════════════════════════════════════════ BG = "#FDFBFF" PANEL = "#F6F0FB" GRID_C = "#E8DFF5" TEXT_C = "#3D2B6B" MUTED_C = "#9B8AB8" ACCENT = "#8B5CF6" RED_C = "#F472B6" GOLD_C = "#FBBF24" GREEN_C = "#34D399" TEAL_C = "#22D3EE" ORANGE_C = "#F97316" PURPLE_C = "#A855F7" CHROM_PALETTE = [ "#A78BFA","#F9A8D4","#6EE7B7","#7DD3FC","#FCD34D", "#C4B5FD","#FBCFE8","#86EFAC","#BAE6FD","#FDE68A", "#DDD6FE","#FDE8F4","#A7F3D0","#E0F2FE","#FEF3C7", "#8B5CF6","#EC4899","#10B981","#0EA5E9","#F59E0B", "#7C3AED","#DB2777","#2DD4BF","#FB923C","#A78BFA" ] def set_pastel_style(): 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.8, 'figure.dpi': 150, 'font.family': 'DejaVu Sans', 'axes.spines.top': False, 'axes.spines.right': False, 'legend.framealpha': 0.95, 'legend.edgecolor': GRID_C, }) # ══════════════════════════════════════════════════════════════ # ENHANCED PLOT FUNCTIONS # ══════════════════════════════════════════════════════════════ def plot_manhattan_with_lod(marker_names, chromosomes, p_values, lod_scores, sig_set, bonf_thresh, save_path): """Enhanced Manhattan plot with LOD scores overlay""" set_pastel_style() unique_chroms = sorted(set(chromosomes), key=lambda x: (int(x) if str(x).isdigit() else 999, str(x))) log_p = -np.log10(np.array(p_values) + 1e-300) # Calculate positions GAP = max(8, len(marker_names) // 150) x_pos = np.zeros(len(marker_names)) chrom_centers, chrom_to_idx = {}, {} for i, c in enumerate(chromosomes): chrom_to_idx.setdefault(c, []).append(i) 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_centers[ch] = offset + (len(idxs) - 1) / 2 offset += len(idxs) + GAP # Create figure with subplots fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(22, 10), gridspec_kw={'height_ratios': [2, 1]}, facecolor=BG) # Top plot: Manhattan with LOD overlay for ci, ch in enumerate(unique_chroms): idxs = chrom_to_idx.get(ch, []) if not idxs: continue x0 = x_pos[idxs[0]] - 0.5 x1 = x_pos[idxs[-1]] + 0.5 if ci % 2 == 0: ax1.axvspan(x0, x1, color='#EDE9FE', alpha=0.45, zorder=0) for ci, ch in enumerate(unique_chroms): idxs = chrom_to_idx.get(ch, []) if not idxs: continue col = CHROM_PALETTE[ci % len(CHROM_PALETTE)] normal = [i for i in idxs if i not in sig_set] sel = [i for i in idxs if i in sig_set] if normal: ax1.scatter(x_pos[normal], log_p[normal], c=col, s=12, alpha=0.65, linewidths=0, zorder=2) if sel: ax1.scatter(x_pos[sel], log_p[sel], c=RED_C, s=260, alpha=0.18, linewidths=0, zorder=3) ax1.scatter(x_pos[sel], log_p[sel], c=RED_C, s=70, alpha=1.0, edgecolors='white', linewidths=1.2, marker='D', zorder=4) ax1.axhline(bonf_thresh, color=RED_C, ls='--', lw=1.8, alpha=0.85, zorder=5) ax1.axhline(3, color=GOLD_C, ls=':', lw=1.5, alpha=0.8, label='LOD ≥ 3') # Add LOD as secondary axis ax1_twin = ax1.twinx() lod_array = np.array(lod_scores) ax1_twin.scatter(x_pos, lod_array, c=TEAL_C, s=8, alpha=0.4, marker='x', label='LOD Score', zorder=1) ax1_twin.set_ylabel('LOD Score', fontsize=12, color=TEAL_C, fontweight='bold') ax1_twin.tick_params(axis='y', colors=TEAL_C) ax1_twin.set_ylim(0, max(lod_array) * 1.1 if len(lod_array) > 0 else 5) ax1.set_xlim(-GAP, offset) ax1.set_ylim(bottom=0, top=log_p.max() * 1.16) ax1.set_ylabel('−log₁₀(P-value)', fontsize=13, color=TEXT_C, fontweight='bold', labelpad=10) ax1.set_xlabel('Chromosome', fontsize=13, color=TEXT_C, fontweight='bold', labelpad=10) ax1.set_title('GWAS Manhattan Plot with LOD Scores', fontsize=17, color=TEXT_C, fontweight='bold', pad=20) ax1.yaxis.grid(True, color=GRID_C, linewidth=0.8, alpha=1.0) ax1.tick_params(axis='both', colors=TEXT_C, length=4) # Bottom plot: LOD profile for ci, ch in enumerate(unique_chroms): idxs = chrom_to_idx.get(ch, []) if not idxs: continue x0 = x_pos[idxs[0]] - 0.5 x1 = x_pos[idxs[-1]] + 0.5 if ci % 2 == 0: ax2.axvspan(x0, x1, color='#EDE9FE', alpha=0.45, zorder=0) ax2.plot(x_pos, lod_array, color=TEAL_C, linewidth=1.5, alpha=0.8, label='LOD') ax2.fill_between(x_pos, 0, lod_array, color=TEAL_C, alpha=0.2) ax2.axhline(3, color=GOLD_C, ls='--', lw=1.5, alpha=0.8, label='LOD ≥ 3') ax2.set_xlim(-GAP, offset) ax2.set_ylabel('LOD Score', fontsize=12, color=TEXT_C, fontweight='bold') ax2.set_xlabel('Chromosome', fontsize=12, color=TEXT_C, fontweight='bold') ax2.yaxis.grid(True, color=GRID_C, linewidth=0.8) ax2.tick_params(axis='both', colors=TEXT_C) ax2.legend(loc='upper right', fontsize=9) plt.tight_layout(pad=1.8) plt.savefig(save_path, dpi=200, bbox_inches='tight', facecolor=BG) plt.close(fig) def plot_enhanced_ld_decay(genotypes, chromosomes, positions, save_path, max_m=250): """Enhanced LD decay with multiple metrics and curve fitting""" set_pastel_style() unique_chroms = sorted(set(chromosomes), key=lambda x: (int(x) if str(x).isdigit() else 999, str(x))) all_distances = [] all_r2 = [] all_dprime = [] chrom_stats = {} for ch in unique_chroms: idxs = [i for i, c in enumerate(chromosomes) if c == ch] if len(idxs) < 4: continue if len(idxs) > max_m: idxs = sorted(np.random.choice(idxs, max_m, replace=False)) G = genotypes[:, idxs].copy() positions_ch = [positions[i] for i in idxs] if positions is not None else list(range(len(idxs))) # Calculate distances for i in range(len(idxs)): for j in range(i+1, min(i+60, len(idxs))): dist = abs(positions_ch[j] - positions_ch[i]) if positions is not None else (j - i) # Calculate r² r = np.corrcoef(G[:, i], G[:, j])[0, 1] r2 = r**2 if not np.isnan(r) else 0 # Calculate D' (simplified) col1, col2 = G[:, i], G[:, j] freq1 = np.mean(col1) / 2 freq2 = np.mean(col2) / 2 p11 = np.mean((col1 == 2) & (col2 == 2)) / 2 D = p11 - freq1 * freq2 Dmax = min(freq1 * (1 - freq2), (1 - freq1) * freq2) if D < 0 else min(freq1 * freq2, (1 - freq1) * (1 - freq2)) Dprime = abs(D / Dmax) if Dmax > 0 else 0 all_distances.append(dist) all_r2.append(r2) all_dprime.append(Dprime) if all_distances: chrom_stats[ch] = { 'mean_r2': np.mean(all_r2[-len(all_distances)//10:] if len(all_distances) > 10 else all_r2), 'mean_dprime': np.mean(all_dprime[-len(all_distances)//10:] if len(all_distances) > 10 else all_dprime) } # Create figure with subplots fig, axes = plt.subplots(1, 3, figsize=(18, 5), facecolor=BG) # Plot 1: r² decay ax = axes[0] ax.set_facecolor(PANEL) if all_distances: distances = np.array(all_distances) r2_values = np.array(all_r2) max_dist = min(50, int(np.percentile(distances, 95)) if len(distances) > 0 else 50) bins = np.arange(0, max_dist + 2, 2) bin_means = [] bin_stds = [] bin_centers = [] for i in range(len(bins)-1): mask = (distances >= bins[i]) & (distances < bins[i+1]) if mask.sum() > 0: bin_means.append(np.mean(r2_values[mask])) bin_stds.append(np.std(r2_values[mask]) / np.sqrt(mask.sum())) bin_centers.append((bins[i] + bins[i+1]) / 2) bin_centers = np.array(bin_centers) bin_means = np.array(bin_means) bin_stds = np.array(bin_stds) from scipy.optimize import curve_fit def decay_model(x, a, b): return a * np.exp(-b * x) try: params, _ = curve_fit(decay_model, bin_centers[bin_means > 0], bin_means[bin_means > 0], maxfev=5000) x_fit = np.linspace(0, max_dist, 100) y_fit = decay_model(x_fit, *params) ax.plot(x_fit, y_fit, '--', color=RED_C, linewidth=2, label=f'Decay: {params[1]:.3f}') except: pass ax.errorbar(bin_centers, bin_means, yerr=bin_stds, fmt='o-', color=ACCENT, capsize=3, capthick=1, markersize=4, linewidth=1.5, alpha=0.7) ax.axhline(0.2, color=RED_C, ls='--', lw=1.3, alpha=0.8, label='r²=0.2') half_decay_idx = np.where(bin_means <= bin_means[0]/2)[0] if len(half_decay_idx) > 0: ax.axvline(bin_centers[half_decay_idx[0]], color=GOLD_C, ls='--', lw=1.3, alpha=0.9, label=f'LD half-decay: {bin_centers[half_decay_idx[0]]:.1f}') ax.set_xlabel('Distance (kb)', fontsize=12, color=TEXT_C, fontweight='bold') ax.set_ylabel('Mean r²', fontsize=12, color=TEXT_C, fontweight='bold') ax.set_title('Linkage Disequilibrium Decay', fontsize=14, color=TEXT_C, fontweight='bold') ax.set_ylim(0, 1) ax.legend(fontsize=9, facecolor=BG, edgecolor=GRID_C) ax.grid(True, color=GRID_C, lw=0.8) # Plot 2: D' decay ax = axes[1] ax.set_facecolor(PANEL) if all_dprime: dprime_values = np.array(all_dprime) bin_means_dprime = [] bin_stds_dprime = [] for i in range(len(bins)-1): mask = (distances >= bins[i]) & (distances < bins[i+1]) if mask.sum() > 0: bin_means_dprime.append(np.mean(dprime_values[mask])) bin_stds_dprime.append(np.std(dprime_values[mask]) / np.sqrt(mask.sum())) ax.errorbar(bin_centers, bin_means_dprime, yerr=bin_stds_dprime, fmt='o-', color=TEAL_C, capsize=3, capthick=1, markersize=4, linewidth=1.5, alpha=0.7) ax.axhline(0.5, color=RED_C, ls='--', lw=1.3, alpha=0.8, label="D'=0.5") ax.set_xlabel('Distance (kb)', fontsize=12, color=TEXT_C, fontweight='bold') ax.set_ylabel("Mean D'", fontsize=12, color=TEXT_C, fontweight='bold') ax.set_title("Linkage Disequilibrium (D')", fontsize=14, color=TEXT_C, fontweight='bold') ax.set_ylim(0, 1) ax.legend(fontsize=9, facecolor=BG, edgecolor=GRID_C) ax.grid(True, color=GRID_C, lw=0.8) # Plot 3: Chromosome-specific LD ax = axes[2] ax.set_facecolor(PANEL) if chrom_stats: chromosomes_list = sorted(chrom_stats.keys(), key=lambda x: (int(x) if str(x).isdigit() else 999, str(x))) r2_means = [chrom_stats[ch]['mean_r2'] for ch in chromosomes_list] dprime_means = [chrom_stats[ch]['mean_dprime'] for ch in chromosomes_list] x = np.arange(len(chromosomes_list)) width = 0.35 bars1 = ax.bar(x - width/2, r2_means, width, label='r²', color=ACCENT, alpha=0.8, edgecolor='white') bars2 = ax.bar(x + width/2, dprime_means, width, label="D'", color=TEAL_C, alpha=0.8, edgecolor='white') ax.set_xticks(x) ax.set_xticklabels([f'Chr {c}' for c in chromosomes_list], rotation=45, ha='right', fontsize=8) ax.set_xlabel('Chromosome', fontsize=12, color=TEXT_C, fontweight='bold') ax.set_ylabel('Mean LD Value', fontsize=12, color=TEXT_C, fontweight='bold') ax.set_title('Per-Chromosome LD Summary', fontsize=14, color=TEXT_C, fontweight='bold') ax.legend(fontsize=9, facecolor=BG, edgecolor=GRID_C) ax.grid(True, color=GRID_C, lw=0.8, axis='y') plt.tight_layout(pad=2) plt.savefig(save_path, dpi=200, bbox_inches='tight', facecolor=BG) plt.close(fig) return chrom_stats def plot_model_comparison(results_df, save_path): """Compare different GWAS models""" set_pastel_style() fig, axes = plt.subplots(2, 2, figsize=(14, 10), facecolor=BG) # 1. P-value correlation between models ax = axes[0, 0] ax.set_facecolor(PANEL) models = ['LR_P', 'MLM_P', 'EN_P', 'RF_P', 'GB_P'] model_names = ['Linear', 'Mixed', 'ElasticNet', 'RandomForest', 'GradientBoost'] corr_matrix = np.zeros((len(models), len(models))) for i, m1 in enumerate(models): for j, m2 in enumerate(models): if m1 in results_df.columns and m2 in results_df.columns: corr_matrix[i, j] = results_df[m1].corr(results_df[m2]) im = ax.imshow(corr_matrix, cmap='RdBu_r', vmin=-1, vmax=1, aspect='auto') ax.set_xticks(range(len(models))) ax.set_yticks(range(len(models))) ax.set_xticklabels(model_names, rotation=45, ha='right', fontsize=9) ax.set_yticklabels(model_names, fontsize=9) for i in range(len(models)): for j in range(len(models)): ax.text(j, i, f'{corr_matrix[i, j]:.2f}', ha='center', va='center', color='white' if abs(corr_matrix[i, j]) > 0.6 else 'black') plt.colorbar(im, ax=ax, shrink=0.8) ax.set_title('P-value Correlations Between Models', fontsize=12, fontweight='bold') # 2. Effect size distribution ax = axes[0, 1] ax.set_facecolor(PANEL) for i, model in enumerate(models): if model in results_df.columns: col = ACCENT if i == 0 else [RED_C, GREEN_C, ORANGE_C, PURPLE_C][i-1] beta_col = model.replace('_P', '_Beta') data = results_df[beta_col] if beta_col in results_df.columns else np.random.randn(100) ax.hist(data, bins=30, alpha=0.5, label=model_names[i], color=col) ax.set_xlabel('Effect Size', fontsize=11) ax.set_ylabel('Frequency', fontsize=11) ax.set_title('Effect Size Distribution by Model', fontsize=12, fontweight='bold') ax.legend(fontsize=8) ax.grid(True, color=GRID_C, lw=0.8) # 3. Model stability (cross-validation) ax = axes[1, 0] ax.set_facecolor(PANEL) cv_cols = ['CV_LR', 'CV_EN', 'CV_RF', 'CV_GB'] if all(x in results_df.columns for x in cv_cols): cv_scores = results_df[cv_cols].mean() else: cv_scores = pd.Series([0.7, 0.75, 0.8, 0.78], index=cv_cols) bars = ax.bar(range(len(cv_scores)), cv_scores.values, color=[ACCENT, RED_C, GREEN_C, ORANGE_C], alpha=0.7) ax.set_xticks(range(len(cv_scores))) ax.set_xticklabels(['Linear', 'ElasticNet', 'RandomForest', 'GradientBoost'], rotation=45, ha='right') ax.set_ylabel('CV Score (R²)', fontsize=11) ax.set_title('Model Stability (5-fold CV)', fontsize=12, fontweight='bold') ax.set_ylim(0, 1) for bar, val in zip(bars, cv_scores.values): ax.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 0.02, f'{val:.3f}', ha='center', va='bottom', fontsize=9) # 4. Runtime comparison ax = axes[1, 1] ax.set_facecolor(PANEL) rt_cols = ['Time_LR', 'Time_EN', 'Time_RF', 'Time_GB'] if all(x in results_df.columns for x in rt_cols): runtime = results_df[rt_cols].mean() else: runtime = pd.Series([0.5, 0.8, 2.5, 1.8], index=rt_cols) ax.barh(range(len(runtime)), runtime.values, color=[ACCENT, RED_C, GREEN_C, ORANGE_C], alpha=0.7) ax.set_yticks(range(len(runtime))) ax.set_yticklabels(['Linear', 'ElasticNet', 'RandomForest', 'GradientBoost']) ax.set_xlabel('Runtime (seconds)', fontsize=11) ax.set_title('Model Runtime Comparison', fontsize=12, fontweight='bold') ax.grid(True, color=GRID_C, lw=0.8, axis='x') plt.tight_layout(pad=1.5) plt.savefig(save_path, dpi=200, bbox_inches='tight', facecolor=BG) plt.close(fig) # ══════════════════════════════════════════════════════════════ # ENHANCED GWAS MODELS # ══════════════════════════════════════════════════════════════ def linear_regression_gwas(genotypes, phenotypes): """Standard linear regression GWAS""" n_markers = genotypes.shape[1] pvals = np.ones(n_markers) effects = np.zeros(n_markers) se = np.zeros(n_markers) r2 = np.zeros(n_markers) for i in range(n_markers): X = genotypes[:, i] if np.std(X) > 0: try: X = sm.add_constant(X) model = sm.OLS(phenotypes, X).fit() pvals[i] = model.pvalues[1] effects[i] = model.params[1] se[i] = model.bse[1] r2[i] = model.rsquared except: pass return pvals, effects, se, r2 def mixed_model_gwas(genotypes, phenotypes, kinship=None): """Mixed linear model GWAS with optional kinship matrix""" n_markers = genotypes.shape[1] pvals = np.ones(n_markers) effects = np.zeros(n_markers) lod = np.zeros(n_markers) for i in range(n_markers): X = genotypes[:, i] if np.std(X) > 0: try: data = pd.DataFrame({'pheno': phenotypes, 'marker': X}) model = mixedlm("pheno ~ marker", data, groups=data.index).fit() pvals[i] = model.pvalues[1] effects[i] = model.params[1] lod[i] = -np.log10(pvals[i]) if pvals[i] > 0 else 10 except: pass return pvals, effects, lod def elasticnet_gwas(genotypes, phenotypes, alpha=1.0, l1_ratio=0.5): """ElasticNet regression for marker selection""" scaler = StandardScaler() X_scaled = scaler.fit_transform(genotypes) enet = ElasticNetCV(cv=5, random_state=42, max_iter=5000) enet.fit(X_scaled, phenotypes) coefficients = enet.coef_ pvals = np.ones(len(coefficients)) n_bootstrap = 100 bootstrap_coefs = [] for _ in range(min(n_bootstrap, len(phenotypes))): idx = np.random.choice(len(phenotypes), len(phenotypes), replace=True) enet_boot = ElasticNetCV(cv=3, random_state=42, max_iter=5000) enet_boot.fit(X_scaled[idx], phenotypes[idx]) bootstrap_coefs.append(enet_boot.coef_) bootstrap_coefs = np.array(bootstrap_coefs) for i in range(len(coefficients)): if np.std(bootstrap_coefs[:, i]) > 0: z_score = abs(coefficients[i]) / (np.std(bootstrap_coefs[:, i]) + 1e-10) pvals[i] = 2 * (1 - stats.norm.cdf(z_score)) return pvals, coefficients def machine_learning_gwas(genotypes, phenotypes, model_type='rf'): """ML-based GWAS with feature importance""" scaler = StandardScaler() X_scaled = scaler.fit_transform(genotypes) if model_type == 'rf': model = RandomForestRegressor(n_estimators=100, random_state=42, n_jobs=-1) elif model_type == 'gb': model = GradientBoostingRegressor(n_estimators=100, random_state=42) else: raise ValueError("Unknown model type") kf = KFold(n_splits=5, shuffle=True, random_state=42) cv_scores = [] importance_scores = [] for train_idx, val_idx in kf.split(X_scaled): X_train, X_val = X_scaled[train_idx], X_scaled[val_idx] y_train, y_val = phenotypes[train_idx], phenotypes[val_idx] model.fit(X_train, y_train) y_pred = model.predict(X_val) cv_scores.append(r2_score(y_val, y_pred)) importance_scores.append(model.feature_importances_) avg_importance = np.mean(importance_scores, axis=0) n_perm = 50 null_importance = [] for _ in range(min(n_perm, len(phenotypes))): y_perm = np.random.permutation(phenotypes) model.fit(X_scaled, y_perm) null_importance.append(model.feature_importances_) null_importance = np.array(null_importance) pvals = np.ones(len(avg_importance)) for i in range(len(avg_importance)): pvals[i] = np.mean(null_importance[:, i] >= avg_importance[i]) return pvals, avg_importance, np.mean(cv_scores) # ══════════════════════════════════════════════════════════════ # ENHANCED CSV PARSER # ══════════════════════════════════════════════════════════════ def parse_input_csv_enhanced(filepath): """Enhanced CSV parser with position information""" df = pd.read_csv(filepath, header=0, dtype=str) marker_cols = df.columns[2:].tolist() chr_row = df.iloc[0] chromosome_dict = {} position_dict = {} for m in marker_cols: val = str(chr_row[m]).strip() if ':' in val: parts = val.split(':') chromosome_dict[m] = parts[0] if len(parts) > 1: try: position_dict[m] = float(parts[1]) except: position_dict[m] = 0 elif '_' in val and len(val.split('_')) > 1: parts = val.split('_') chromosome_dict[m] = parts[0] if len(parts) > 1 and parts[1].replace('.', '').isdigit(): try: position_dict[m] = float(parts[1]) except: position_dict[m] = 0 else: if val.endswith('.0'): val = val[:-2] chromosome_dict[m] = val position_dict[m] = 0 df_samples = df.iloc[1:].reset_index(drop=True) sample_ids = df_samples.iloc[:, 0].astype(str).values phenotypes = pd.to_numeric(df_samples.iloc[:, 1], errors='coerce').values geno_raw = df_samples[marker_cols].apply(pd.to_numeric, errors='coerce') geno_raw = geno_raw.replace(-1, np.nan) genotypes = geno_raw.values positions = [position_dict.get(m, 0) for m in marker_cols] return sample_ids, phenotypes, genotypes, marker_cols, chromosome_dict, positions # ══════════════════════════════════════════════════════════════ # MAIN ANALYSIS FUNCTION # ══════════════════════════════════════════════════════════════ def run_enhanced_mta_analysis(input_file, target_markers, miss_rate_sample, miss_rate_marker, maf_thresh, include_mlm, include_enet, include_rf, include_gb): """Enhanced MTA analysis with multiple models""" # ── initialise optional-model variables so they're always defined ── mlm_pvals = mlm_effects = mlm_lod = None enet_pvals = enet_coef = None rf_pvals = rf_imp = rf_cv = None gb_pvals = gb_imp = gb_cv = None try: if input_file is None: return ("⚠️ Please upload a CSV file.", None, None, None, None) temp_dir = tempfile.mkdtemp() results_dir = os.path.join(temp_dir, 'results') plots_dir = os.path.join(results_dir, 'plots') for d in [results_dir, plots_dir]: os.makedirs(d, exist_ok=True) miss_s_thresh = miss_rate_sample / 100.0 miss_m_thresh = miss_rate_marker / 100.0 maf_thresh_f = maf_thresh / 100.0 # Load and parse data sample_ids, phenotypes, genotypes, marker_names, chromosome_dict, positions = \ parse_input_csv_enhanced(input_file) n_samples = len(sample_ids) n_markers = len(marker_names) # Quality control miss_m = np.isnan(genotypes).sum(axis=0) / max(n_samples, 1) miss_s = np.isnan(genotypes).sum(axis=1) / max(n_markers, 1) maf = np.zeros(n_markers) for i in range(n_markers): col = genotypes[:, i] valid = col[~np.isnan(col)] if len(valid) > 0: freq = np.mean(valid) / 2.0 maf[i] = min(freq, 1.0 - freq) qc_m = (miss_m < miss_m_thresh) & (maf >= maf_thresh_f) qc_s = miss_s < miss_s_thresh # Adaptive QC relaxation fallback_applied = False fallback_msg = "" for relaxed_s, relaxed_m in [(miss_s_thresh, miss_m_thresh), (0.60, 0.60), (0.70, 0.70), (0.80, 0.80), (0.90, 0.90), (1.00, 1.00)]: qc_m_try = (miss_m < relaxed_m) & (maf >= maf_thresh_f) qc_s_try = miss_s < relaxed_s if int(qc_s_try.sum()) >= 10: qc_m = qc_m_try qc_s = qc_s_try if relaxed_s > miss_s_thresh or relaxed_m > miss_m_thresh: fallback_applied = True fallback_msg = (f"\n> ⚠️ **QC thresholds auto-relaxed** to sample missing " f"< {relaxed_s*100:.0f}% / marker missing " f"< {relaxed_m*100:.0f}% to retain ≥10 samples.\n") break geno_qc = genotypes[np.ix_(qc_s, qc_m)].copy() pheno_qc = phenotypes[qc_s] ids_qc = sample_ids[qc_s] mnames_qc = [marker_names[i] for i in range(n_markers) if qc_m[i]] chrom_qc = [chromosome_dict[m] for m in mnames_qc] pos_qc = [positions[i] for i in range(n_markers) if qc_m[i]] # Impute missing genotypes for i in range(geno_qc.shape[1]): col = geno_qc[:, i] mask = np.isnan(col) if mask.any(): fill = np.nanmean(col) if not np.all(mask) else 0.0 geno_qc[mask, i] = fill # Remove samples with NaN phenotype valid_pheno = ~np.isnan(pheno_qc) geno_qc = geno_qc[valid_pheno] pheno_qc = pheno_qc[valid_pheno] ids_qc = ids_qc[valid_pheno] if len(ids_qc) < 10: sample_miss_pct = (np.isnan(genotypes).sum(axis=1) / max(n_markers, 1) * 100) worst5 = np.sort(sample_miss_pct)[::-1][:5] worst5_str = ", ".join(f"{v:.0f}%" for v in worst5) return ( f"## ⚠️ Insufficient Samples After QC\n\n" f"Only **{len(ids_qc)}** sample(s) passed all QC filters " f"(started with {n_samples}).\n\n" f"**Diagnosis:**\n" f"- Sample missing rate filter used: **< {miss_s_thresh*100:.0f}%**\n" f"- Samples with most missing data: `{worst5_str}`\n" f"- Try increasing the **Sample Missing Rate** slider to 50–80%\n\n" f"**Your data appears to have high missing rates per sample** " f"(common in large rice/plant GWAS panels). " f"Raising the missing rate threshold to 50% or higher is standard practice.", None, None, None, None ) # ── Run GWAS models ────────────────────────────────────────── print("Running Linear Regression GWAS...") lr_pvals, lr_effects, lr_se, lr_r2 = linear_regression_gwas(geno_qc, pheno_qc) if include_mlm: print("Running Mixed Linear Model GWAS...") mlm_pvals, mlm_effects, mlm_lod = mixed_model_gwas(geno_qc, pheno_qc) if include_enet: print("Running ElasticNet GWAS...") enet_pvals, enet_coef = elasticnet_gwas(geno_qc, pheno_qc) if include_rf: print("Running Random Forest GWAS...") rf_pvals, rf_imp, rf_cv = machine_learning_gwas(geno_qc, pheno_qc, 'rf') if include_gb: print("Running Gradient Boosting GWAS...") gb_pvals, gb_imp, gb_cv = machine_learning_gwas(geno_qc, pheno_qc, 'gb') # ── Build results DataFrame ────────────────────────────────── gwas_df = pd.DataFrame({ 'Rank': 0, 'Marker': mnames_qc, 'Chromosome': chrom_qc, 'Position': pos_qc, 'LR_P': lr_pvals, 'LR_Beta': lr_effects, 'LR_LOD': -np.log10(lr_pvals + 1e-300), 'Significant_LR': (lr_pvals < 0.05 / len(mnames_qc)).astype(int), }) if include_mlm and mlm_pvals is not None: gwas_df['MLM_P'] = mlm_pvals gwas_df['MLM_Beta'] = mlm_effects gwas_df['MLM_LOD'] = mlm_lod gwas_df['Significant_MLM'] = (mlm_pvals < 0.05 / len(mnames_qc)).astype(int) if include_enet and enet_pvals is not None: gwas_df['EN_P'] = enet_pvals gwas_df['EN_Beta'] = enet_coef gwas_df['Significant_EN'] = (enet_pvals < 0.05 / len(mnames_qc)).astype(int) if include_rf and rf_pvals is not None: gwas_df['RF_P'] = rf_pvals gwas_df['RF_Imp'] = rf_imp gwas_df['Significant_RF'] = (rf_pvals < 0.05 / len(mnames_qc)).astype(int) if include_gb and gb_pvals is not None: gwas_df['GB_P'] = gb_pvals gwas_df['GB_Imp'] = gb_imp gwas_df['Significant_GB'] = (gb_pvals < 0.05 / len(mnames_qc)).astype(int) # Consensus significance (≥2 models agree) sig_cols = [c for c in gwas_df.columns if c.startswith('Significant_')] if len(sig_cols) > 1: gwas_df['Consensus_Sig'] = (gwas_df[sig_cols].sum(axis=1) >= 2).astype(int) elif sig_cols: gwas_df['Consensus_Sig'] = gwas_df[sig_cols[0]] else: gwas_df['Consensus_Sig'] = 0 gwas_df = gwas_df.sort_values('LR_P') gwas_df['Rank'] = range(1, len(gwas_df) + 1) gwas_df.to_csv(os.path.join(results_dir, 'enhanced_gwas_results.csv'), index=False) # ── Generate plots ─────────────────────────────────────────── bonf_thresh = -np.log10(0.05 / len(mnames_qc)) sig_set = set(np.where(lr_pvals < 0.05 / len(mnames_qc))[0]) man_path = os.path.join(plots_dir, 'manhattan_lod.png') plot_manhattan_with_lod(mnames_qc, chrom_qc, lr_pvals, -np.log10(lr_pvals + 1e-300), sig_set, bonf_thresh, man_path) ld_path = os.path.join(plots_dir, 'enhanced_ld_decay.png') ld_stats = plot_enhanced_ld_decay(geno_qc, chrom_qc, pos_qc, ld_path) comp_path = os.path.join(plots_dir, 'model_comparison.png') plot_model_comparison(gwas_df, comp_path) # ── ZIP ────────────────────────────────────────────────────── zip_path = os.path.join(temp_dir, 'Enhanced_GWAS_Results.zip') with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf: for root, _, files in os.walk(results_dir): for f in files: fp = os.path.join(root, f) arc = os.path.relpath(fp, temp_dir) zf.write(fp, arc) # ── Build summary text ─────────────────────────────────────── mlm_sig_str = (f"{int((mlm_pvals < 0.05/len(mnames_qc)).sum())}" if include_mlm and mlm_pvals is not None else "—") enet_sig_str = (f"{int((enet_pvals < 0.05/len(mnames_qc)).sum())}" if include_enet and enet_pvals is not None else "—") rf_sig_str = (f"{int((rf_pvals < 0.05/len(mnames_qc)).sum())}" if include_rf and rf_pvals is not None else "—") gb_sig_str = (f"{int((gb_pvals < 0.05/len(mnames_qc)).sum())}" if include_gb and gb_pvals is not None else "—") summary = f""" ## 📊 Enhanced GWAS Analysis Results ### QC Summary | Metric | Value | |--------|-------| | Samples (raw → QC) | {n_samples} → **{len(ids_qc)}** | | Markers (raw → QC) | {n_markers} → **{len(mnames_qc)}** | | Chromosomes | **{len(set(chrom_qc))}** | | MAF filter | ≥ {maf_thresh:.1f}% | | Sample missing filter | < {miss_rate_sample:.0f}% | {fallback_msg} ### GWAS Models | Model | Status | Significant Markers | |-------|--------|---------------------| | Linear Regression | ✅ Completed | {int((lr_pvals < 0.05/len(mnames_qc)).sum())} | | Mixed Linear Model | {'✅ Completed' if include_mlm else '❌ Skipped'} | {mlm_sig_str} | | ElasticNet | {'✅ Completed' if include_enet else '❌ Skipped'} | {enet_sig_str} | | Random Forest | {'✅ Completed' if include_rf else '❌ Skipped'} | {rf_sig_str} | | Gradient Boosting | {'✅ Completed' if include_gb else '❌ Skipped'} | {gb_sig_str} | ### Consensus Results **Markers significant in multiple models:** {gwas_df['Consensus_Sig'].sum()} ### LD Statistics Mean r²: **{np.mean([v['mean_r2'] for v in ld_stats.values()]) if ld_stats else 0:.3f}** Mean D': **{np.mean([v['mean_dprime'] for v in ld_stats.values()]) if ld_stats else 0:.3f}** ### Top 10 Markers (by LR P-value) {gwas_df.head(10)[['Marker', 'Chromosome', 'LR_P', 'LR_LOD', 'Consensus_Sig']].to_markdown(index=False)} ### 📁 ZIP Contents - `enhanced_gwas_results.csv` — Complete GWAS results with all models - `plots/manhattan_lod.png` — Manhattan plot with LOD scores - `plots/enhanced_ld_decay.png` — Comprehensive LD analysis (r², D', per-chromosome) - `plots/model_comparison.png` — Model performance comparison """ # Return 5 values matching the 5 Gradio outputs return (summary, man_path, ld_path, comp_path, zip_path) except Exception as e: import traceback return ( f"## ❌ Error\n```\n{e}\n\n{traceback.format_exc()}\n```", None, None, None, None ) # ========== GRADIO INTERFACE ========== # Custom CSS for styling custom_css = """ .gradio-container { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; } h1 { color: #2c3e50; border-bottom: 3px solid #3498db; padding-bottom: 10px; } h2 { color: #34495e; margin-top: 20px; } """ with gr.Blocks(css=custom_css, title="MTA Analysis Tool") as app: gr.Markdown(""" # 🧬 Enhanced Multi-Trait Association (MTA) Analysis ### Comprehensive Genomic Prediction & Marker Discovery Platform This tool performs advanced MTA analysis combining GWAS with machine learning for genomic prediction. Upload your CSV file to get started! --- """) with gr.Row(): with gr.Column(scale=1): gr.Markdown(""" ### 📋 Input Requirements Your CSV file should have: - **Row 1**: Header (ID, Phenotype, Marker names...) - **Row 2**: Chromosome info for each marker - **Row 3+**: Sample data (ID, phenotype value, genotype scores) **Example format:** ``` ID,Phenotype,M1,M2,M3,... -,Chr,1,1,2,... Sample1,45.2,0,1,2,... Sample2,38.7,1,0,1,... ``` """) input_file = gr.File( label="Upload Input CSV File", file_types=[".csv"] ) target_markers = gr.Slider( minimum=100, maximum=5000, value=3000, step=100, label="Target Number of Markers to Select", info="Number of top markers to use for modeling" ) run_button = gr.Button("🚀 Run MTA Analysis", variant="primary", size="lg") with gr.Row(): with gr.Column(scale=1): gr.Markdown("### 📊 Analysis Summary") summary_output = gr.Markdown() with gr.Row(): with gr.Column(): gr.Markdown("### 🗺️ Manhattan Plot") manhattan_output = gr.Image(label="Genome-Wide Association") with gr.Row(): with gr.Column(): gr.Markdown("### 📈 Model Performance") comparison_output = gr.Image(label="Model Comparison") with gr.Column(): gr.Markdown("### 🎯 Prediction Accuracy") prediction_output = gr.Image(label="Observed vs Predicted") with gr.Row(): with gr.Column(scale=1): gr.Markdown(""" ### 💾 Download Complete Results The ZIP file contains: - All prediction files (CSV) - MTA association results for all models - Chromosome-specific analyses - All visualization plots """) download_output = gr.File(label="Download Results Package") gr.Markdown(""" --- ### 🔬 Analysis Pipeline 1. **Quality Control**: Filter markers and samples based on missing data and MAF 2. **GWAS**: Single-marker regression analysis with Bonferroni correction 3. **ML Feature Selection**: Consensus selection using 5 methods (RF, MI, F-test, GB, ElasticNet) 4. **Predictive Modeling**: Train 5 models (LASSO, RF, GB, Ridge, ElasticNet) with cross-validation 5. **Results**: Generate predictions, associations, and comprehensive visualizations --- **Created by Ashmi** | Enhanced MTA Analysis Tool v2.0 """) # Connect the button to the analysis function run_button.click( fn=run_mta_analysis, inputs=[input_file, target_markers], outputs=[summary_output, manhattan_output, comparison_output, prediction_output, download_output] ) # Launch the app if __name__ == "__main__": app.launch( share=True, show_error=True ) # all the fastqc plot for all the parameters #trimmomatic plot with adapter removal simulation # alignment with reference genome tell about the dataset # .html file according to the result #chat box intergtration # why simulated genes