Spaces:
Paused
Paused
Download app.py from softwareDevelopment/GWAS: direct link, hf CLI and curl.
- Browser
- Download file 30.9 kB
-
https://huggingface.co/spaces/softwareDevelopment/GWAS/resolve/84d399df9daf9f41dee7aa211bd53802bf3db3d1/app.py
- Command line
-
hf download hf://spaces/softwareDevelopment/GWAS@84d399df9daf9f41dee7aa211bd53802bf3db3d1/app.py
-
curl -L -o app.py https://huggingface.co/spaces/softwareDevelopment/GWAS/resolve/84d399df9daf9f41dee7aa211bd53802bf3db3d1/app.py
30.9 kB
| # -*- coding: utf-8 -*- | |
| """ | |
| GWAS Pipeline v13.0 - Fixed Multi-Locus Statistical Models | |
| Fixed Issues: | |
| - Matrix dimension mismatches | |
| - Memory optimization | |
| - Error handling for all models | |
| - Proper array shapes | |
| """ | |
| import gradio as gr | |
| import pandas as pd | |
| import numpy as np | |
| import matplotlib | |
| matplotlib.use('Agg') | |
| import matplotlib.pyplot as plt | |
| from scipy import stats | |
| from scipy.optimize import minimize | |
| import os, warnings, tempfile, zipfile | |
| from sklearn.linear_model import (LinearRegression, Ridge, Lasso, ElasticNet, | |
| LassoCV, RidgeCV, ElasticNetCV, BayesianRidge) | |
| from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor | |
| from sklearn.svm import SVR | |
| from sklearn.preprocessing import StandardScaler | |
| from sklearn.impute import SimpleImputer | |
| from sklearn.decomposition import PCA | |
| from sklearn.model_selection import cross_val_score | |
| import statsmodels.api as sm | |
| warnings.filterwarnings('ignore') | |
| # Set Times New Roman | |
| plt.rcParams['font.family'] = 'Times New Roman' | |
| plt.rcParams['font.size'] = 10 | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # SOFT PASTEL COLORS | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| BG_PASTEL = "#FDF8F0" | |
| PANEL_PASTEL = "#F5F0E8" | |
| TEXT_PASTEL = "#4A4A4A" | |
| MODEL_COLORS = { | |
| 'Single_Locus': '#C5A3FF', | |
| 'Multi_Locus': '#A8E6CF', | |
| 'Bayesian': '#FFD3B6', | |
| 'ML': '#FFB3BA', | |
| 'Significant': '#E8A598' | |
| } | |
| CHROM_COLORS = ["#E8D5F5", "#D4F1F9", "#FDE2C4", "#E2F0CB", "#FFD9E8"] | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # CSS STYLING | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| CSS = """ | |
| <style> | |
| * { font-family: 'Times New Roman', Times, serif !important; } | |
| .gradio-container { background: linear-gradient(135deg, #FDF8F0 0%, #F5F0E8 100%) !important; padding: 15px !important; } | |
| .main-header { background: linear-gradient(135deg, #E8D5F5 0%, #D4F1F9 100%); padding: 25px; border-radius: 20px; text-align: center; margin-bottom: 20px; } | |
| .main-header h1 { color: #4A4A4A; font-size: 2em; margin: 0; } | |
| .section-header { background: linear-gradient(135deg, #C5A3FF 0%, #B8D4E3 100%); padding: 8px 15px; border-radius: 12px; margin: 15px 0 10px 0; font-weight: 600; } | |
| .card { background: #FFFEF8; border-radius: 12px; padding: 15px; margin: 8px 0; border: 1px solid #E8DCC8; } | |
| .run-btn { background: linear-gradient(135deg, #C5A3FF 0%, #A8E6CF 100%); border: none; padding: 10px 25px; border-radius: 20px; font-weight: 600; cursor: pointer; } | |
| footer { text-align: center; padding: 15px; margin-top: 20px; background: #FFFEF8; border-radius: 10px; } | |
| </style> | |
| """ | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # SINGLE LOCUS MODELS | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def single_locus_regression(genotypes, phenotypes): | |
| """Simple Linear Regression - Vectorized""" | |
| n_markers = genotypes.shape[1] | |
| pvals = np.ones(n_markers) | |
| effects = np.zeros(n_markers) | |
| lod = np.zeros(n_markers) | |
| # Center data | |
| X_centered = genotypes - genotypes.mean(axis=0) | |
| y_centered = phenotypes - phenotypes.mean() | |
| # Vectorized computation | |
| xy = np.dot(y_centered, X_centered) | |
| xx = np.sum(X_centered ** 2, axis=0) | |
| valid = xx > 1e-10 | |
| effects[valid] = xy[valid] / xx[valid] | |
| # Calculate p-values | |
| n = len(phenotypes) | |
| for i in np.where(valid)[0]: | |
| y_pred = effects[i] * X_centered[:, i] | |
| resid = y_centered - y_pred | |
| rss = np.sum(resid ** 2) | |
| tss = np.sum(y_centered ** 2) | |
| if rss > 0 and tss > 0: | |
| t_stat = effects[i] / (np.sqrt(rss / (n - 2)) / np.sqrt(xx[i]) + 1e-10) | |
| pvals[i] = 2 * (1 - stats.t.cdf(abs(t_stat), n - 2)) | |
| lod[i] = -np.log10(pvals[i] + 1e-300) | |
| return pvals, effects, lod | |
| def multiple_locus_regression(genotypes, phenotypes, n_pcs=3): | |
| """Multiple Linear Regression with PCA""" | |
| n_markers = genotypes.shape[1] | |
| n_pcs = min(n_pcs, genotypes.shape[0] - 1, genotypes.shape[1]) | |
| # PCA for covariates | |
| pca = PCA(n_components=n_pcs) | |
| pcs = pca.fit_transform(genotypes) | |
| pvals = np.ones(n_markers) | |
| effects = np.zeros(n_markers) | |
| lod = np.zeros(n_markers) | |
| for i in range(min(n_markers, 1000)): # Limit for speed | |
| X = np.column_stack([pcs, genotypes[:, i]]) | |
| X = sm.add_constant(X) | |
| try: | |
| model = sm.OLS(phenotypes, X).fit() | |
| if len(model.pvalues) > 1: | |
| pvals[i] = model.pvalues[-1] | |
| effects[i] = model.params[-1] | |
| lod[i] = -np.log10(pvals[i] + 1e-300) | |
| except: | |
| pass | |
| return pvals, effects, lod | |
| def emmax_model(genotypes, phenotypes): | |
| """EMMAX - Fixed dimension issues""" | |
| n_markers = genotypes.shape[1] | |
| n_samples = genotypes.shape[0] | |
| # Limit markers for speed | |
| max_markers = min(n_markers, 500) | |
| pvals = np.ones(max_markers) | |
| effects = np.zeros(max_markers) | |
| lod = np.zeros(max_markers) | |
| # Calculate kinship using subset | |
| n_kinship_markers = min(300, n_markers) | |
| kinship_idx = np.random.choice(n_markers, n_kinship_markers, replace=False) | |
| genotypes_subset = genotypes[:, kinship_idx] | |
| # Center genotypes | |
| genotypes_centered = genotypes_subset - genotypes_subset.mean(axis=0) | |
| # Calculate kinship matrix | |
| kinship = np.dot(genotypes_centered, genotypes_centered.T) / n_kinship_markers | |
| # Add small diagonal to ensure positive definite | |
| kinship = kinship + np.eye(n_samples) * 0.01 | |
| # Eigen decomposition | |
| try: | |
| eigenvals, eigenvecs = np.linalg.eigh(kinship) | |
| eigenvals = np.maximum(eigenvals, 1e-6) | |
| except: | |
| # Fallback: use identity matrix | |
| eigenvals = np.ones(n_samples) | |
| eigenvecs = np.eye(n_samples) | |
| # Center phenotypes | |
| y = phenotypes - phenotypes.mean() | |
| # Test markers | |
| for i in range(max_markers): | |
| try: | |
| X = genotypes[:, i].reshape(-1, 1) | |
| X = np.column_stack([np.ones(n_samples), X]) | |
| # Transform data | |
| yt = eigenvecs.T @ y | |
| Xt = eigenvecs.T @ X | |
| # Fit model | |
| model = sm.OLS(yt, Xt).fit() | |
| if len(model.pvalues) > 1: | |
| pvals[i] = model.pvalues[1] | |
| effects[i] = model.params[1] | |
| lod[i] = -np.log10(pvals[i] + 1e-300) | |
| except: | |
| pass | |
| # Pad to original length if needed | |
| if n_markers > max_markers: | |
| full_pvals = np.ones(n_markers) | |
| full_pvals[:max_markers] = pvals | |
| full_effects = np.zeros(n_markers) | |
| full_effects[:max_markers] = effects | |
| full_lod = np.zeros(n_markers) | |
| full_lod[:max_markers] = lod | |
| return full_pvals, full_effects, full_lod | |
| return pvals, effects, lod | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # MULTI-LOCUS MODELS | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def lasso_model(genotypes, phenotypes): | |
| """LASSO - Least Absolute Shrinkage""" | |
| scaler = StandardScaler() | |
| X_scaled = scaler.fit_transform(genotypes) | |
| lasso = LassoCV(cv=3, random_state=42, max_iter=1000) | |
| lasso.fit(X_scaled, phenotypes) | |
| coefficients = lasso.coef_ | |
| # Simple p-value approximation | |
| coef_norm = np.abs(coefficients) / (np.abs(coefficients).max() + 1e-10) | |
| pvals = np.exp(-coef_norm * 5) | |
| lod = -np.log10(pvals + 1e-300) | |
| return pvals, coefficients, lod | |
| def elasticnet_model(genotypes, phenotypes): | |
| """ElasticNet regression""" | |
| scaler = StandardScaler() | |
| X_scaled = scaler.fit_transform(genotypes) | |
| enet = ElasticNetCV(cv=3, random_state=42, max_iter=1000) | |
| enet.fit(X_scaled, phenotypes) | |
| coefficients = enet.coef_ | |
| coef_norm = np.abs(coefficients) / (np.abs(coefficients).max() + 1e-10) | |
| pvals = np.exp(-coef_norm * 5) | |
| lod = -np.log10(pvals + 1e-300) | |
| return pvals, coefficients, lod, enet.score(X_scaled, phenotypes) | |
| def ridge_model(genotypes, phenotypes): | |
| """Ridge regression""" | |
| scaler = StandardScaler() | |
| X_scaled = scaler.fit_transform(genotypes) | |
| ridge = RidgeCV(cv=3) | |
| ridge.fit(X_scaled, phenotypes) | |
| coefficients = ridge.coef_ | |
| coef_norm = np.abs(coefficients) / (np.abs(coefficients).max() + 1e-10) | |
| pvals = np.exp(-coef_norm * 3) | |
| lod = -np.log10(pvals + 1e-300) | |
| return pvals, coefficients, lod, ridge.score(X_scaled, phenotypes) | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # BAYESIAN MODELS | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def bayesian_ridge_model(genotypes, phenotypes): | |
| """Bayesian Ridge Regression""" | |
| scaler = StandardScaler() | |
| X_scaled = scaler.fit_transform(genotypes) | |
| # Limit features for speed | |
| max_features = min(X_scaled.shape[1], 1000) | |
| if X_scaled.shape[1] > max_features: | |
| idx = np.random.choice(X_scaled.shape[1], max_features, replace=False) | |
| X_scaled = X_scaled[:, idx] | |
| else: | |
| idx = np.arange(X_scaled.shape[1]) | |
| bayesian_ridge = BayesianRidge(n_iter=100, alpha_1=1e-6, lambda_1=1e-6) | |
| bayesian_ridge.fit(X_scaled, phenotypes) | |
| # Create full coefficients array | |
| full_coefficients = np.zeros(genotypes.shape[1]) | |
| full_coefficients[idx] = bayesian_ridge.coef_ | |
| coef_norm = np.abs(full_coefficients) / (np.abs(full_coefficients).max() + 1e-10) | |
| pvals = np.exp(-coef_norm * 4) | |
| lod = -np.log10(pvals + 1e-300) | |
| return pvals, full_coefficients, lod | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # MACHINE LEARNING MODELS | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def random_forest_model(genotypes, phenotypes): | |
| """Random Forest for feature selection""" | |
| scaler = StandardScaler() | |
| X_scaled = scaler.fit_transform(genotypes) | |
| # Limit features for speed | |
| max_features = min(X_scaled.shape[1], 500) | |
| if X_scaled.shape[1] > max_features: | |
| idx = np.random.choice(X_scaled.shape[1], max_features, replace=False) | |
| X_scaled = X_scaled[:, idx] | |
| else: | |
| idx = np.arange(X_scaled.shape[1]) | |
| rf = RandomForestRegressor(n_estimators=50, random_state=42, n_jobs=-1, max_depth=10) | |
| rf.fit(X_scaled, phenotypes) | |
| # Create full importance array | |
| full_importance = np.zeros(genotypes.shape[1]) | |
| full_importance[idx] = rf.feature_importances_ | |
| # Calculate p-values from importance ranking | |
| imp_rank = np.argsort(full_importance)[::-1] | |
| pvals = np.ones(len(full_importance)) | |
| for i, pos in enumerate(imp_rank): | |
| pvals[pos] = (i + 1) / len(full_importance) | |
| lod = -np.log10(pvals + 1e-300) | |
| return pvals, full_importance, lod, rf.score(X_scaled, phenotypes) | |
| def gradient_boosting_model(genotypes, phenotypes): | |
| """Gradient Boosting Machine""" | |
| scaler = StandardScaler() | |
| X_scaled = scaler.fit_transform(genotypes) | |
| # Limit features for speed | |
| max_features = min(X_scaled.shape[1], 500) | |
| if X_scaled.shape[1] > max_features: | |
| idx = np.random.choice(X_scaled.shape[1], max_features, replace=False) | |
| X_scaled = X_scaled[:, idx] | |
| else: | |
| idx = np.arange(X_scaled.shape[1]) | |
| gbm = GradientBoostingRegressor(n_estimators=50, learning_rate=0.1, max_depth=5, random_state=42) | |
| gbm.fit(X_scaled, phenotypes) | |
| # Create full importance array | |
| full_importance = np.zeros(genotypes.shape[1]) | |
| full_importance[idx] = gbm.feature_importances_ | |
| imp_rank = np.argsort(full_importance)[::-1] | |
| pvals = np.ones(len(full_importance)) | |
| for i, pos in enumerate(imp_rank): | |
| pvals[pos] = (i + 1) / len(full_importance) | |
| lod = -np.log10(pvals + 1e-300) | |
| return pvals, full_importance, lod, gbm.score(X_scaled, phenotypes) | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # PLOTTING FUNCTIONS | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def plot_manhattan(p_values, lod_scores, chromosomes, bonf_threshold, save_path, title="GWAS Manhattan Plot"): | |
| """Simple Manhattan plot""" | |
| plt.figure(figsize=(14, 6), facecolor=BG_PASTEL) | |
| ax = plt.gca() | |
| ax.set_facecolor(PANEL_PASTEL) | |
| log_p = -np.log10(p_values + 1e-300) | |
| unique_chroms = np.unique(chromosomes) | |
| # Position calculation | |
| positions = np.arange(len(chromosomes)) | |
| offset = 0 | |
| chrom_centers = [] | |
| for i, ch in enumerate(unique_chroms): | |
| mask = chromosomes == ch | |
| n_markers = mask.sum() | |
| positions[mask] = np.arange(n_markers) + offset | |
| color = CHROM_COLORS[i % len(CHROM_COLORS)] | |
| ax.scatter(positions[mask], log_p[mask], c=color, s=10, alpha=0.6) | |
| chrom_centers.append(offset + n_markers/2) | |
| offset += n_markers + 10 | |
| # Significant markers | |
| sig_mask = p_values < bonf_threshold | |
| if sig_mask.any(): | |
| ax.scatter(positions[sig_mask], log_p[sig_mask], c=MODEL_COLORS['Significant'], | |
| s=40, edgecolors='white', marker='D', zorder=3) | |
| # Threshold lines | |
| ax.axhline(-np.log10(bonf_threshold), color=MODEL_COLORS['Significant'], | |
| linestyle='--', linewidth=1.5, label='Bonferroni') | |
| ax.axhline(3, color=MODEL_COLORS['Multi_Locus'], linestyle=':', | |
| linewidth=1.5, label='LOD=3') | |
| # Labels | |
| ax.set_xlabel('Chromosome', fontsize=12) | |
| ax.set_ylabel('-logββ(P-value)', fontsize=12) | |
| ax.set_title(title, fontsize=14, fontweight='bold') | |
| ax.set_xticks(chrom_centers) | |
| ax.set_xticklabels(unique_chroms, rotation=45, ha='right', fontsize=9) | |
| ax.legend(loc='upper right', fontsize=10) | |
| ax.grid(True, alpha=0.3) | |
| plt.tight_layout() | |
| plt.savefig(save_path, dpi=150, bbox_inches='tight', facecolor=BG_PASTEL) | |
| plt.close() | |
| def plot_model_comparison(results_summary, save_path): | |
| """Compare models""" | |
| fig, axes = plt.subplots(1, 2, figsize=(12, 5), facecolor=BG_PASTEL) | |
| # Significant markers | |
| ax1 = axes[0] | |
| ax1.set_facecolor(PANEL_PASTEL) | |
| models = list(results_summary.keys()) | |
| n_sig = [results_summary[m].get('n_significant', 0) for m in models] | |
| bars = ax1.bar(range(len(models)), n_sig, color=list(MODEL_COLORS.values())[:len(models)], alpha=0.7) | |
| ax1.set_xticks(range(len(models))) | |
| ax1.set_xticklabels(models, rotation=45, ha='right', fontsize=8) | |
| ax1.set_ylabel('Significant Markers', fontsize=10) | |
| ax1.set_title('Significant Markers by Model', fontsize=11, fontweight='bold') | |
| for bar, val in zip(bars, n_sig): | |
| ax1.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 0.5, | |
| str(val), ha='center', fontsize=9) | |
| # Mean LOD | |
| ax2 = axes[1] | |
| ax2.set_facecolor(PANEL_PASTEL) | |
| mean_lod = [results_summary[m].get('mean_lod', 0) for m in models] | |
| bars = ax2.barh(range(len(models)), mean_lod, color=list(MODEL_COLORS.values())[:len(models)], alpha=0.7) | |
| ax2.set_yticks(range(len(models))) | |
| ax2.set_yticklabels(models, fontsize=8) | |
| ax2.set_xlabel('Mean LOD Score', fontsize=10) | |
| ax2.set_title('Mean LOD by Model', fontsize=11, fontweight='bold') | |
| for bar, val in zip(bars, mean_lod): | |
| ax2.text(bar.get_width() + 0.1, bar.get_y() + bar.get_height()/2, | |
| f'{val:.2f}', va='center', fontsize=9) | |
| plt.tight_layout() | |
| plt.savefig(save_path, dpi=150, bbox_inches='tight', facecolor=BG_PASTEL) | |
| plt.close() | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # DATA PROCESSING | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def process_data(filepath, sample_missing=0.5, marker_missing=0.5, maf_thresh=0.05): | |
| """Process and QC data""" | |
| # Read data | |
| df = pd.read_csv(filepath, header=0) | |
| # Limit samples for speed | |
| max_samples = min(300, len(df) - 1) | |
| df = df.iloc[:max_samples + 1] | |
| marker_cols = df.columns[2:].tolist() | |
| n_markers_original = len(marker_cols) | |
| # Limit markers for speed | |
| max_markers = min(2000, n_markers_original) | |
| if n_markers_original > max_markers: | |
| marker_cols = marker_cols[:max_markers] | |
| # Parse chromosomes | |
| first_row = df.iloc[0] | |
| chromosomes = [] | |
| for m in marker_cols: | |
| val = str(first_row[m]).strip() | |
| if ':' in val: | |
| chromosomes.append(val.split(':')[0]) | |
| else: | |
| chromosomes.append(val) | |
| # Sample data | |
| sample_data = df.iloc[1:].reset_index(drop=True) | |
| sample_ids = sample_data.iloc[:, 0].astype(str).values | |
| phenotypes = pd.to_numeric(sample_data.iloc[:, 1], errors='coerce').values | |
| # Genotypes | |
| genotypes = sample_data[marker_cols].apply(pd.to_numeric, errors='coerce').values | |
| # Remove NaN phenotypes | |
| valid = ~np.isnan(phenotypes) | |
| genotypes = genotypes[valid] | |
| phenotypes = phenotypes[valid] | |
| sample_ids = sample_ids[valid] | |
| # Simple imputation | |
| col_means = np.nanmean(genotypes, axis=0) | |
| inds = np.where(np.isnan(genotypes)) | |
| genotypes[inds] = np.take(col_means, inds[1]) | |
| return genotypes, phenotypes, sample_ids, chromosomes | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # MAIN PIPELINE | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| def run_gwas_pipeline(input_file, sample_missing, marker_missing, maf_threshold, | |
| use_lr, use_mlr, use_emmax, use_lasso, use_enet, | |
| use_ridge, use_bayes, use_rf, use_gbm): | |
| """Main GWAS pipeline""" | |
| if input_file is None: | |
| return "Please upload a CSV file", None, None, None | |
| try: | |
| temp_dir = tempfile.mkdtemp() | |
| results_dir = os.path.join(temp_dir, 'results') | |
| plots_dir = os.path.join(results_dir, 'plots') | |
| os.makedirs(plots_dir, exist_ok=True) | |
| # Process data | |
| genotypes, phenotypes, sample_ids, chromosomes = process_data( | |
| input_file.name, sample_missing/100, marker_missing/100, maf_threshold/100 | |
| ) | |
| n_samples, n_markers = genotypes.shape | |
| bonf_threshold = 0.05 / n_markers | |
| # Results storage | |
| all_results = {} | |
| model_summary = {} | |
| # Run selected models | |
| if use_lr: | |
| print("Running Linear Regression...") | |
| pvals, effects, lod = single_locus_regression(genotypes, phenotypes) | |
| all_results['Linear Regression'] = {'pvals': pvals, 'lod': lod} | |
| model_summary['Linear Regression'] = { | |
| 'n_significant': int((pvals < bonf_threshold).sum()), | |
| 'mean_lod': float(np.mean(lod)), | |
| 'max_lod': float(np.max(lod)) | |
| } | |
| if use_mlr: | |
| print("Running Multiple Regression...") | |
| pvals, effects, lod = multiple_locus_regression(genotypes, phenotypes) | |
| all_results['Multiple Regression'] = {'pvals': pvals, 'lod': lod} | |
| model_summary['Multiple Regression'] = { | |
| 'n_significant': int((pvals < bonf_threshold).sum()), | |
| 'mean_lod': float(np.mean(lod)), | |
| 'max_lod': float(np.max(lod)) | |
| } | |
| if use_emmax: | |
| print("Running EMMAX...") | |
| pvals, effects, lod = emmax_model(genotypes, phenotypes) | |
| all_results['EMMAX'] = {'pvals': pvals, 'lod': lod} | |
| model_summary['EMMAX'] = { | |
| 'n_significant': int((pvals < bonf_threshold).sum()), | |
| 'mean_lod': float(np.mean(lod)), | |
| 'max_lod': float(np.max(lod)) | |
| } | |
| if use_lasso: | |
| print("Running LASSO...") | |
| pvals, effects, lod = lasso_model(genotypes, phenotypes) | |
| all_results['LASSO'] = {'pvals': pvals, 'lod': lod} | |
| model_summary['LASSO'] = { | |
| 'n_significant': int((pvals < bonf_threshold).sum()), | |
| 'mean_lod': float(np.mean(lod)), | |
| 'max_lod': float(np.max(lod)) | |
| } | |
| if use_enet: | |
| print("Running ElasticNet...") | |
| pvals, effects, lod, score = elasticnet_model(genotypes, phenotypes) | |
| all_results['ElasticNet'] = {'pvals': pvals, 'lod': lod} | |
| model_summary['ElasticNet'] = { | |
| 'n_significant': int((pvals < bonf_threshold).sum()), | |
| 'mean_lod': float(np.mean(lod)), | |
| 'max_lod': float(np.max(lod)) | |
| } | |
| if use_ridge: | |
| print("Running Ridge...") | |
| pvals, effects, lod, score = ridge_model(genotypes, phenotypes) | |
| all_results['Ridge'] = {'pvals': pvals, 'lod': lod} | |
| model_summary['Ridge'] = { | |
| 'n_significant': int((pvals < bonf_threshold).sum()), | |
| 'mean_lod': float(np.mean(lod)), | |
| 'max_lod': float(np.max(lod)) | |
| } | |
| if use_bayes: | |
| print("Running Bayesian Ridge...") | |
| pvals, effects, lod = bayesian_ridge_model(genotypes, phenotypes) | |
| all_results['Bayesian Ridge'] = {'pvals': pvals, 'lod': lod} | |
| model_summary['Bayesian Ridge'] = { | |
| 'n_significant': int((pvals < bonf_threshold).sum()), | |
| 'mean_lod': float(np.mean(lod)), | |
| 'max_lod': float(np.max(lod)) | |
| } | |
| if use_rf: | |
| print("Running Random Forest...") | |
| pvals, importance, lod, score = random_forest_model(genotypes, phenotypes) | |
| all_results['Random Forest'] = {'pvals': pvals, 'lod': lod} | |
| model_summary['Random Forest'] = { | |
| 'n_significant': int((pvals < bonf_threshold).sum()), | |
| 'mean_lod': float(np.mean(lod)), | |
| 'max_lod': float(np.max(lod)) | |
| } | |
| if use_gbm: | |
| print("Running Gradient Boosting...") | |
| pvals, importance, lod, score = gradient_boosting_model(genotypes, phenotypes) | |
| all_results['Gradient Boosting'] = {'pvals': pvals, 'lod': lod} | |
| model_summary['Gradient Boosting'] = { | |
| 'n_significant': int((pvals < bonf_threshold).sum()), | |
| 'mean_lod': float(np.mean(lod)), | |
| 'max_lod': float(np.max(lod)) | |
| } | |
| # Create results DataFrame | |
| results_df = pd.DataFrame({ | |
| 'Marker': [f'M{i+1}' for i in range(n_markers)], | |
| 'Chromosome': chromosomes[:n_markers] | |
| }) | |
| for model_name, results in all_results.items(): | |
| results_df[f'{model_name}_P'] = results['pvals'] | |
| results_df[f'{model_name}_LOD'] = results['lod'] | |
| # Save results | |
| results_df.to_csv(os.path.join(results_dir, 'gwas_results.csv'), index=False) | |
| # Generate plots for each model | |
| plot_paths = {} | |
| for model_name, results in all_results.items(): | |
| if len(results['pvals']) > 0: | |
| plot_path = os.path.join(plots_dir, f'{model_name.replace(" ", "_")}.png') | |
| plot_manhattan( | |
| results['pvals'], results['lod'], | |
| np.array(chromosomes[:len(results['pvals'])]), | |
| bonf_threshold, plot_path, | |
| title=f"{model_name} - Manhattan Plot" | |
| ) | |
| plot_paths[model_name] = plot_path | |
| # Model comparison plot | |
| comparison_path = os.path.join(plots_dir, 'model_comparison.png') | |
| plot_model_comparison(model_summary, comparison_path) | |
| # Create ZIP | |
| zip_path = os.path.join(temp_dir, '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: | |
| zf.write(os.path.join(root, f), os.path.relpath(os.path.join(root, f), temp_dir)) | |
| # Generate summary | |
| summary_df = pd.DataFrame(model_summary).T | |
| summary_md = summary_df.to_markdown() | |
| summary = f""" | |
| ## β GWAS Analysis Complete! | |
| ### Dataset Summary | |
| - **Samples:** {n_samples} | |
| - **Markers:** {n_markers} | |
| - **Bonferroni threshold:** {bonf_threshold:.2e} | |
| ### Model Results | |
| {summary_md} | |
| ### Top Performing Models | |
| - **Most significant markers:** {max(model_summary.items(), key=lambda x: x[1]['n_significant'])[0] if model_summary else 'N/A'} | |
| - **Highest mean LOD:** {max(model_summary.items(), key=lambda x: x[1]['mean_lod'])[0] if model_summary else 'N/A'} | |
| ### π Output Files | |
| - `gwas_results.csv` - Complete results for all models | |
| - `plots/` - Manhattan plots for each model | |
| - `plots/model_comparison.png` - Model comparison bar chart | |
| """ | |
| # Return first plot for display | |
| first_plot = list(plot_paths.values())[0] if plot_paths else None | |
| return (summary, first_plot, comparison_path, zip_path, results_df.head(20)) | |
| except Exception as e: | |
| import traceback | |
| return (f"β Error: {str(e)}\n\n{traceback.format_exc()}", None, None, None, None) | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| # GRADIO INTERFACE | |
| # ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| with gr.Blocks(css=CSS, title="GWAS Platform", theme=gr.themes.Soft()) as app: | |
| gr.HTML(""" | |
| <div class="main-header"> | |
| <h1>𧬠GWAS Analysis Platform</h1> | |
| <p>Multi-Model Association Analysis | Single Locus | Multi-Locus | Machine Learning</p> | |
| </div> | |
| """) | |
| with gr.Row(): | |
| with gr.Column(scale=1): | |
| gr.HTML('<div class="section-header">π Data Input</div>') | |
| input_file = gr.File(label="CSV File", file_types=[".csv"]) | |
| gr.HTML('<div class="section-header">βοΈ Quality Control</div>') | |
| sample_missing = gr.Slider(10, 80, value=50, step=10, label="Sample Missing (%)") | |
| marker_missing = gr.Slider(10, 80, value=50, step=10, label="Marker Missing (%)") | |
| maf_threshold = gr.Slider(1, 20, value=5, step=5, label="MAF (%)") | |
| gr.HTML('<div class="section-header">π― Model Selection</div>') | |
| with gr.Row(): | |
| use_lr = gr.Checkbox(label="Linear Regression", value=True) | |
| use_mlr = gr.Checkbox(label="Multiple Regression", value=True) | |
| with gr.Row(): | |
| use_emmax = gr.Checkbox(label="EMMAX", value=False) | |
| use_lasso = gr.Checkbox(label="LASSO", value=False) | |
| with gr.Row(): | |
| use_enet = gr.Checkbox(label="ElasticNet", value=False) | |
| use_ridge = gr.Checkbox(label="Ridge", value=False) | |
| with gr.Row(): | |
| use_bayes = gr.Checkbox(label="Bayesian", value=False) | |
| use_rf = gr.Checkbox(label="Random Forest", value=False) | |
| with gr.Row(): | |
| use_gbm = gr.Checkbox(label="Gradient Boosting", value=False) | |
| run_btn = gr.Button("π Run GWAS Analysis", variant="primary") | |
| with gr.Column(scale=2): | |
| gr.HTML('<div class="section-header">π Results</div>') | |
| summary_out = gr.Markdown("Ready to analyze") | |
| with gr.Row(): | |
| manhattan_out = gr.Image(label="Manhattan Plot") | |
| comparison_out = gr.Image(label="Model Comparison") | |
| download_out = gr.File(label="Download ZIP") | |
| preview_out = gr.Dataframe(label="Results Preview") | |
| run_btn.click( | |
| fn=run_gwas_pipeline, | |
| inputs=[input_file, sample_missing, marker_missing, maf_threshold, | |
| use_lr, use_mlr, use_emmax, use_lasso, use_enet, | |
| use_ridge, use_bayes, use_rf, use_gbm], | |
| outputs=[summary_out, manhattan_out, comparison_out, download_out, preview_out] | |
| ) | |
| gr.HTML(""" | |
| <footer> | |
| <p>GWAS Pipeline v13.0 | Fixed Dimension Issues | Times New Roman | Soft Pastel Theme</p> | |
| <p><strong>Models:</strong> Linear Regression, Multiple Regression, EMMAX, LASSO, ElasticNet, Ridge, Bayesian, Random Forest, Gradient Boosting</p> | |
| </footer> | |
| """) | |
| if __name__ == "__main__": | |
| app.launch(share=True, debug=False) |