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gr
|
| 9 |
+
import pandas as pd
|
| 10 |
+
import numpy as np
|
| 11 |
+
import matplotlib.pyplot as plt
|
| 12 |
+
import seaborn as sns
|
| 13 |
+
from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor
|
| 14 |
+
from sklearn.linear_model import LassoCV, ElasticNetCV, Ridge
|
| 15 |
+
from sklearn.feature_selection import mutual_info_regression, f_regression
|
| 16 |
+
from sklearn.model_selection import cross_val_score, KFold
|
| 17 |
+
from sklearn.preprocessing import StandardScaler
|
| 18 |
+
from sklearn.metrics import r2_score, mean_squared_error
|
| 19 |
+
from scipy import stats
|
| 20 |
+
import os
|
| 21 |
+
import shutil
|
| 22 |
+
import warnings
|
| 23 |
+
import tempfile
|
| 24 |
+
from pathlib import Path
|
| 25 |
+
import zipfile
|
| 26 |
+
|
| 27 |
+
warnings.filterwarnings('ignore')
|
| 28 |
+
|
| 29 |
+
# Set style
|
| 30 |
+
plt.style.use('seaborn-v0_8-darkgrid')
|
| 31 |
+
sns.set_palette("husl")
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def run_mta_analysis(input_file, target_markers):
|
| 35 |
+
"""
|
| 36 |
+
Main analysis function that processes the uploaded CSV file
|
| 37 |
+
"""
|
| 38 |
+
try:
|
| 39 |
+
if input_file is None:
|
| 40 |
+
return "Please upload a CSV file first.", None, None, None, None
|
| 41 |
+
|
| 42 |
+
# Create temporary directory for results
|
| 43 |
+
temp_dir = tempfile.mkdtemp()
|
| 44 |
+
results_dir = os.path.join(temp_dir, 'results')
|
| 45 |
+
plots_dir = os.path.join(results_dir, 'plots')
|
| 46 |
+
chrom_dir = os.path.join(results_dir, 'chromosome_specific')
|
| 47 |
+
|
| 48 |
+
for folder in [results_dir, plots_dir, chrom_dir]:
|
| 49 |
+
os.makedirs(folder, exist_ok=True)
|
| 50 |
+
|
| 51 |
+
# ========== LOAD DATA ==========
|
| 52 |
+
df = pd.read_csv(input_file, sep=',')
|
| 53 |
+
|
| 54 |
+
chromosome_info = df.iloc[0, 2:].values.astype(str)
|
| 55 |
+
marker_names_all = df.columns[2:].tolist()
|
| 56 |
+
chromosome_dict = {m: c for m, c in zip(marker_names_all, chromosome_info)}
|
| 57 |
+
unique_chromosomes = sorted(set(chromosome_info))
|
| 58 |
+
|
| 59 |
+
df_data = df.iloc[1:].reset_index(drop=True)
|
| 60 |
+
sample_ids = df_data.iloc[:, 0].values
|
| 61 |
+
phenotypes = pd.to_numeric(df_data.iloc[:, 1], errors='coerce').values
|
| 62 |
+
genotypes = df_data.iloc[:, 2:].apply(pd.to_numeric, errors='coerce').values
|
| 63 |
+
marker_names = df.columns[2:].tolist()
|
| 64 |
+
|
| 65 |
+
# ========== QC ==========
|
| 66 |
+
missing_per_marker = np.isnan(genotypes).sum(axis=0) / len(sample_ids)
|
| 67 |
+
missing_per_sample = np.isnan(genotypes).sum(axis=1) / len(marker_names)
|
| 68 |
+
maf = np.array([np.nanmean(genotypes[:, i]) / 2 for i in range(genotypes.shape[1])])
|
| 69 |
+
maf = np.minimum(maf, 1 - maf)
|
| 70 |
+
|
| 71 |
+
qc_marker = (missing_per_marker < 0.1) & (maf > 0.01)
|
| 72 |
+
qc_sample = missing_per_sample < 0.1
|
| 73 |
+
|
| 74 |
+
genotypes_qc = genotypes[qc_sample][:, qc_marker]
|
| 75 |
+
phenotypes_qc = phenotypes[qc_sample]
|
| 76 |
+
sample_ids_qc = sample_ids[qc_sample]
|
| 77 |
+
marker_names_qc = [marker_names[i] for i in range(len(marker_names)) if qc_marker[i]]
|
| 78 |
+
chromosome_qc = [chromosome_dict[m] for m in marker_names_qc]
|
| 79 |
+
|
| 80 |
+
# Impute missing values
|
| 81 |
+
for i in range(genotypes_qc.shape[1]):
|
| 82 |
+
mask = np.isnan(genotypes_qc[:, i])
|
| 83 |
+
if mask.any():
|
| 84 |
+
genotypes_qc[mask, i] = np.nanmean(genotypes_qc[:, i])
|
| 85 |
+
|
| 86 |
+
TARGET_MARKERS = min(int(target_markers), len(marker_names_qc))
|
| 87 |
+
|
| 88 |
+
# ========== GWAS ==========
|
| 89 |
+
p_values = np.ones(len(marker_names_qc))
|
| 90 |
+
gwas_effects = np.zeros(len(marker_names_qc))
|
| 91 |
+
|
| 92 |
+
for i in range(len(marker_names_qc)):
|
| 93 |
+
marker = genotypes_qc[:, i]
|
| 94 |
+
if np.std(marker) > 0:
|
| 95 |
+
try:
|
| 96 |
+
slope, _, _, p_val, _ = stats.linregress(marker, phenotypes_qc)
|
| 97 |
+
p_values[i] = p_val
|
| 98 |
+
gwas_effects[i] = slope
|
| 99 |
+
except:
|
| 100 |
+
pass
|
| 101 |
+
|
| 102 |
+
log_p = -np.log10(p_values + 1e-300)
|
| 103 |
+
bonf_thresh = -np.log10(0.05 / len(marker_names_qc))
|
| 104 |
+
|
| 105 |
+
# ========== ML FEATURE SELECTION ==========
|
| 106 |
+
X = StandardScaler().fit_transform(genotypes_qc)
|
| 107 |
+
y = phenotypes_qc
|
| 108 |
+
|
| 109 |
+
rf = RandomForestRegressor(n_estimators=100, max_depth=10, random_state=42, n_jobs=-1)
|
| 110 |
+
rf.fit(X, y)
|
| 111 |
+
rf_top = np.argsort(rf.feature_importances_)[-TARGET_MARKERS:]
|
| 112 |
+
|
| 113 |
+
mi = mutual_info_regression(X, y, random_state=42)
|
| 114 |
+
mi_top = np.argsort(mi)[-TARGET_MARKERS:]
|
| 115 |
+
|
| 116 |
+
f_scores, _ = f_regression(X, y)
|
| 117 |
+
f_top = np.argsort(f_scores)[-TARGET_MARKERS:]
|
| 118 |
+
|
| 119 |
+
gb = GradientBoostingRegressor(n_estimators=100, max_depth=5, random_state=42)
|
| 120 |
+
gb.fit(X, y)
|
| 121 |
+
gb_top = np.argsort(gb.feature_importances_)[-TARGET_MARKERS:]
|
| 122 |
+
|
| 123 |
+
enet = ElasticNetCV(cv=5, random_state=42, max_iter=5000)
|
| 124 |
+
enet.fit(X, y)
|
| 125 |
+
enet_top = np.argsort(np.abs(enet.coef_))[-TARGET_MARKERS:]
|
| 126 |
+
|
| 127 |
+
votes = np.zeros(len(marker_names_qc))
|
| 128 |
+
for selection in [rf_top, mi_top, f_top, gb_top, enet_top]:
|
| 129 |
+
votes[selection] += 1
|
| 130 |
+
|
| 131 |
+
consensus = np.argsort(votes)[-TARGET_MARKERS:]
|
| 132 |
+
|
| 133 |
+
# ========== PREDICTIVE MODELS ==========
|
| 134 |
+
X_sel = X[:, consensus]
|
| 135 |
+
cv = KFold(n_splits=5, shuffle=True, random_state=42)
|
| 136 |
+
|
| 137 |
+
models = {}
|
| 138 |
+
for model_name, model_obj in [
|
| 139 |
+
('LASSO', LassoCV(cv=5, random_state=42, max_iter=10000)),
|
| 140 |
+
('RF', RandomForestRegressor(n_estimators=200, max_depth=15, random_state=42, n_jobs=-1)),
|
| 141 |
+
('GB', GradientBoostingRegressor(n_estimators=200, max_depth=7, random_state=42)),
|
| 142 |
+
('Ridge', Ridge(alpha=1.0)),
|
| 143 |
+
('ElasticNet', ElasticNetCV(cv=5, random_state=42, max_iter=5000))
|
| 144 |
+
]:
|
| 145 |
+
model_obj.fit(X_sel, y)
|
| 146 |
+
pred = model_obj.predict(X_sel)
|
| 147 |
+
|
| 148 |
+
if hasattr(model_obj, 'feature_importances_'):
|
| 149 |
+
effects = model_obj.feature_importances_
|
| 150 |
+
else:
|
| 151 |
+
effects = np.abs(model_obj.coef_)
|
| 152 |
+
|
| 153 |
+
models[model_name] = {
|
| 154 |
+
'model': model_obj,
|
| 155 |
+
'pred': pred,
|
| 156 |
+
'r2': r2_score(y, pred),
|
| 157 |
+
'cv': cross_val_score(model_obj, X_sel, y, cv=cv, scoring='r2').mean(),
|
| 158 |
+
'effects': effects
|
| 159 |
+
}
|
| 160 |
+
|
| 161 |
+
best_name = max(models.keys(), key=lambda k: models[k]['cv'])
|
| 162 |
+
best_model = models[best_name]
|
| 163 |
+
|
| 164 |
+
# ========== SAVE OUTPUTS ==========
|
| 165 |
+
all_predictions = pd.DataFrame({'ID': sample_ids_qc, 'Observed': phenotypes_qc})
|
| 166 |
+
for name, data in models.items():
|
| 167 |
+
all_predictions[f'GEBV_{name}'] = data['pred']
|
| 168 |
+
all_predictions[f'Residual_{name}'] = phenotypes_qc - data['pred']
|
| 169 |
+
|
| 170 |
+
all_predictions['Rank'] = all_predictions[f'GEBV_{best_name}'].rank(ascending=False).astype(int)
|
| 171 |
+
all_predictions = all_predictions.sort_values(f'GEBV_{best_name}', ascending=False)
|
| 172 |
+
all_predictions.to_csv(os.path.join(results_dir, 'all_model_predictions.csv'), index=False)
|
| 173 |
+
|
| 174 |
+
# MTA Associations
|
| 175 |
+
mta_results = {}
|
| 176 |
+
for name, data in models.items():
|
| 177 |
+
mta_df = pd.DataFrame({
|
| 178 |
+
'Marker': [marker_names_qc[i] for i in consensus],
|
| 179 |
+
'Chromosome': [chromosome_qc[i] for i in consensus],
|
| 180 |
+
f'Effect_{name}': data['effects'],
|
| 181 |
+
'Votes': votes[consensus].astype(int),
|
| 182 |
+
'GWAS_Pvalue': p_values[consensus],
|
| 183 |
+
'GWAS_Effect': gwas_effects[consensus]
|
| 184 |
+
})
|
| 185 |
+
|
| 186 |
+
total = np.sum(np.abs(data['effects']))
|
| 187 |
+
mta_df[f'Contribution_{name}'] = data['effects'] / total if total > 0 else 0
|
| 188 |
+
mta_df = mta_df.sort_values(f'Effect_{name}', ascending=False)
|
| 189 |
+
mta_df[f'Rank_{name}'] = range(1, len(mta_df) + 1)
|
| 190 |
+
mta_results[name] = mta_df
|
| 191 |
+
mta_df.to_csv(os.path.join(results_dir, f'mta_associations_{name}.csv'), index=False)
|
| 192 |
+
|
| 193 |
+
# ========== MANHATTAN PLOT ==========
|
| 194 |
+
chrom_colors = dict(zip(sorted(unique_chromosomes),
|
| 195 |
+
plt.cm.tab20(np.linspace(0, 1, len(unique_chromosomes)))))
|
| 196 |
+
|
| 197 |
+
fig_man = plt.figure(figsize=(26, 7))
|
| 198 |
+
ax_man = fig_man.add_subplot(111)
|
| 199 |
+
|
| 200 |
+
pos = 0
|
| 201 |
+
xticks_pos, xticks_labels = [], []
|
| 202 |
+
|
| 203 |
+
for chrom in sorted(unique_chromosomes):
|
| 204 |
+
chrom_idx = [i for i in range(len(marker_names_qc)) if chromosome_qc[i] == chrom]
|
| 205 |
+
if not chrom_idx:
|
| 206 |
+
continue
|
| 207 |
+
|
| 208 |
+
start_pos = pos
|
| 209 |
+
for idx in chrom_idx:
|
| 210 |
+
if idx in consensus:
|
| 211 |
+
ax_man.scatter(pos, log_p[idx], c='red', s=80, alpha=0.9,
|
| 212 |
+
edgecolors='black', linewidth=0.8, zorder=3)
|
| 213 |
+
else:
|
| 214 |
+
ax_man.scatter(pos, log_p[idx], c=chrom_colors[chrom], s=30,
|
| 215 |
+
alpha=0.7, zorder=1)
|
| 216 |
+
pos += 1
|
| 217 |
+
|
| 218 |
+
xticks_pos.append((start_pos + pos - 1) / 2)
|
| 219 |
+
xticks_labels.append(chrom)
|
| 220 |
+
|
| 221 |
+
ax_man.axhline(bonf_thresh, color='red', ls='--', lw=2.5, alpha=0.8,
|
| 222 |
+
label=f'Bonferroni (α=0.05)')
|
| 223 |
+
ax_man.set_xlabel('Chromosome', fontsize=18, fontweight='bold')
|
| 224 |
+
ax_man.set_ylabel('-log₁₀(P-value)', fontsize=18, fontweight='bold')
|
| 225 |
+
ax_man.set_title('Genome-Wide Association Manhattan Plot',
|
| 226 |
+
fontsize=20, fontweight='bold', pad=20)
|
| 227 |
+
ax_man.set_xticks(xticks_pos)
|
| 228 |
+
ax_man.set_xticklabels(xticks_labels, fontsize=13, fontweight='bold')
|
| 229 |
+
ax_man.legend(fontsize=13)
|
| 230 |
+
ax_man.grid(alpha=0.2, axis='y')
|
| 231 |
+
|
| 232 |
+
plt.tight_layout()
|
| 233 |
+
manhattan_path = os.path.join(plots_dir, 'manhattan_plot.png')
|
| 234 |
+
plt.savefig(manhattan_path, dpi=300, bbox_inches='tight')
|
| 235 |
+
plt.close()
|
| 236 |
+
|
| 237 |
+
# ========== MODEL COMPARISON PLOT ==========
|
| 238 |
+
fig_comp = plt.figure(figsize=(12, 6))
|
| 239 |
+
ax = fig_comp.add_subplot(111)
|
| 240 |
+
|
| 241 |
+
names = list(models.keys())
|
| 242 |
+
cv_r2 = [models[m]['cv'] for m in names]
|
| 243 |
+
train_r2 = [models[m]['r2'] for m in names]
|
| 244 |
+
x = np.arange(len(names))
|
| 245 |
+
w = 0.35
|
| 246 |
+
|
| 247 |
+
b1 = ax.bar(x - w/2, train_r2, w, label='Train R²', color='lightblue',
|
| 248 |
+
edgecolor='black', alpha=0.8)
|
| 249 |
+
b2 = ax.bar(x + w/2, cv_r2, w, label='CV R²', color='lightgreen',
|
| 250 |
+
edgecolor='black', alpha=0.8)
|
| 251 |
+
|
| 252 |
+
best_idx = names.index(best_name)
|
| 253 |
+
b1[best_idx].set_edgecolor('red')
|
| 254 |
+
b1[best_idx].set_linewidth(3)
|
| 255 |
+
b2[best_idx].set_edgecolor('red')
|
| 256 |
+
b2[best_idx].set_linewidth(3)
|
| 257 |
+
|
| 258 |
+
ax.set_ylabel('R²', fontsize=14, fontweight='bold')
|
| 259 |
+
ax.set_title('Model Performance Comparison', fontsize=16, fontweight='bold')
|
| 260 |
+
ax.set_xticks(x)
|
| 261 |
+
ax.set_xticklabels(names, fontsize=12)
|
| 262 |
+
ax.legend(fontsize=12)
|
| 263 |
+
ax.grid(alpha=0.2, axis='y')
|
| 264 |
+
|
| 265 |
+
plt.tight_layout()
|
| 266 |
+
comparison_path = os.path.join(plots_dir, 'model_comparison.png')
|
| 267 |
+
plt.savefig(comparison_path, dpi=300, bbox_inches='tight')
|
| 268 |
+
plt.close()
|
| 269 |
+
|
| 270 |
+
# ========== OBSERVED VS PREDICTED ==========
|
| 271 |
+
fig_pred = plt.figure(figsize=(10, 8))
|
| 272 |
+
ax = fig_pred.add_subplot(111)
|
| 273 |
+
|
| 274 |
+
ax.scatter(phenotypes_qc, best_model['pred'], alpha=0.6, s=60,
|
| 275 |
+
edgecolors='black', lw=0.6, c='purple')
|
| 276 |
+
ax.plot([phenotypes_qc.min(), phenotypes_qc.max()],
|
| 277 |
+
[phenotypes_qc.min(), phenotypes_qc.max()], 'r--', lw=2.5)
|
| 278 |
+
ax.set_xlabel('Observed Phenotype', fontsize=14, fontweight='bold')
|
| 279 |
+
ax.set_ylabel('Predicted Phenotype', fontsize=14, fontweight='bold')
|
| 280 |
+
ax.set_title(f'{best_name} Model: Observed vs Predicted (CV R²={best_model["cv"]:.3f})',
|
| 281 |
+
fontsize=16, fontweight='bold')
|
| 282 |
+
ax.grid(alpha=0.2)
|
| 283 |
+
|
| 284 |
+
plt.tight_layout()
|
| 285 |
+
pred_path = os.path.join(plots_dir, 'observed_vs_predicted.png')
|
| 286 |
+
plt.savefig(pred_path, dpi=300, bbox_inches='tight')
|
| 287 |
+
plt.close()
|
| 288 |
+
|
| 289 |
+
# ========== CREATE ZIP FILE ==========
|
| 290 |
+
zip_path = os.path.join(temp_dir, 'mta_results.zip')
|
| 291 |
+
with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
|
| 292 |
+
for root, dirs, files in os.walk(results_dir):
|
| 293 |
+
for file in files:
|
| 294 |
+
file_path = os.path.join(root, file)
|
| 295 |
+
arcname = os.path.relpath(file_path, temp_dir)
|
| 296 |
+
zipf.write(file_path, arcname)
|
| 297 |
+
|
| 298 |
+
# ========== SUMMARY TEXT ==========
|
| 299 |
+
summary = f"""
|
| 300 |
+
# MTA Analysis Complete ✓
|
| 301 |
+
|
| 302 |
+
## Dataset Summary
|
| 303 |
+
- **Samples**: {len(sample_ids_qc)}
|
| 304 |
+
- **Total Markers**: {len(marker_names_qc)}
|
| 305 |
+
- **Selected Markers**: {TARGET_MARKERS}
|
| 306 |
+
- **Chromosomes**: {len(unique_chromosomes)}
|
| 307 |
+
|
| 308 |
+
## Best Model: {best_name}
|
| 309 |
+
- **Cross-Validation R²**: {best_model['cv']:.4f}
|
| 310 |
+
- **Training R²**: {best_model['r2']:.4f}
|
| 311 |
+
|
| 312 |
+
## All Models Performance
|
| 313 |
+
"""
|
| 314 |
+
for name, data in models.items():
|
| 315 |
+
marker = "🏆" if name == best_name else " "
|
| 316 |
+
summary += f"{marker} **{name}**: CV R² = {data['cv']:.4f}, Train R² = {data['r2']:.4f}\n"
|
| 317 |
+
|
| 318 |
+
summary += f"""
|
| 319 |
+
## Top 5 Markers ({best_name})
|
| 320 |
+
"""
|
| 321 |
+
for idx, row in mta_results[best_name].head(5).iterrows():
|
| 322 |
+
summary += f"{int(row[f'Rank_{best_name}'])}. **{row['Marker']}** (Chr {row['Chromosome']}) - Effect: {row[f'Effect_{best_name}']:.6f}\n"
|
| 323 |
+
|
| 324 |
+
summary += f"""
|
| 325 |
+
## Top 3 Samples (Highest GEBV)
|
| 326 |
+
"""
|
| 327 |
+
for idx, row in all_predictions.head(3).iterrows():
|
| 328 |
+
summary += f"{int(row['Rank'])}. **{row['ID']}** - GEBV: {row[f'GEBV_{best_name}']:.2f}, Observed: {row['Observed']:.2f}\n"
|
| 329 |
+
|
| 330 |
+
summary += """
|
| 331 |
+
## Output Files
|
| 332 |
+
- `all_model_predictions.csv` - Predictions from all models
|
| 333 |
+
- `mta_associations_*.csv` - Marker associations for each model
|
| 334 |
+
- `plots/manhattan_plot.png` - Genome-wide association plot
|
| 335 |
+
- `plots/model_comparison.png` - Model performance comparison
|
| 336 |
+
- `plots/observed_vs_predicted.png` - Prediction accuracy plot
|
| 337 |
+
"""
|
| 338 |
+
|
| 339 |
+
return summary, manhattan_path, comparison_path, pred_path, zip_path
|
| 340 |
+
|
| 341 |
+
except Exception as e:
|
| 342 |
+
import traceback
|
| 343 |
+
error_msg = f"Error: {str(e)}\n\nTraceback:\n{traceback.format_exc()}"
|
| 344 |
+
return error_msg, None, None, None, None
|
| 345 |
+
|
| 346 |
+
|
| 347 |
+
# ========== GRADIO INTERFACE ==========
|
| 348 |
+
|
| 349 |
+
# Custom CSS for styling
|
| 350 |
+
custom_css = """
|
| 351 |
+
.gradio-container {
|
| 352 |
+
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
|
| 353 |
+
}
|
| 354 |
+
h1 {
|
| 355 |
+
color: #2c3e50;
|
| 356 |
+
border-bottom: 3px solid #3498db;
|
| 357 |
+
padding-bottom: 10px;
|
| 358 |
+
}
|
| 359 |
+
h2 {
|
| 360 |
+
color: #34495e;
|
| 361 |
+
margin-top: 20px;
|
| 362 |
+
}
|
| 363 |
+
"""
|
| 364 |
+
|
| 365 |
+
with gr.Blocks(css=custom_css, title="MTA Analysis Tool") as app:
|
| 366 |
+
|
| 367 |
+
gr.Markdown("""
|
| 368 |
+
# 🧬 Enhanced Multi-Trait Association (MTA) Analysis
|
| 369 |
+
|
| 370 |
+
### Comprehensive Genomic Prediction & Marker Discovery Platform
|
| 371 |
+
|
| 372 |
+
This tool performs advanced MTA analysis combining GWAS with machine learning for genomic prediction.
|
| 373 |
+
Upload your CSV file to get started!
|
| 374 |
+
|
| 375 |
+
---
|
| 376 |
+
""")
|
| 377 |
+
|
| 378 |
+
with gr.Row():
|
| 379 |
+
with gr.Column(scale=1):
|
| 380 |
+
gr.Markdown("""
|
| 381 |
+
### 📋 Input Requirements
|
| 382 |
+
|
| 383 |
+
Your CSV file should have:
|
| 384 |
+
- **Row 1**: Header (ID, Phenotype, Marker names...)
|
| 385 |
+
- **Row 2**: Chromosome info for each marker
|
| 386 |
+
- **Row 3+**: Sample data (ID, phenotype value, genotype scores)
|
| 387 |
+
|
| 388 |
+
**Example format:**
|
| 389 |
+
```
|
| 390 |
+
ID,Phenotype,M1,M2,M3,...
|
| 391 |
+
-,Chr,1,1,2,...
|
| 392 |
+
Sample1,45.2,0,1,2,...
|
| 393 |
+
Sample2,38.7,1,0,1,...
|
| 394 |
+
```
|
| 395 |
+
""")
|
| 396 |
+
|
| 397 |
+
input_file = gr.File(
|
| 398 |
+
label="Upload Input CSV File",
|
| 399 |
+
file_types=[".csv"]
|
| 400 |
+
)
|
| 401 |
+
|
| 402 |
+
target_markers = gr.Slider(
|
| 403 |
+
minimum=100,
|
| 404 |
+
maximum=5000,
|
| 405 |
+
value=3000,
|
| 406 |
+
step=100,
|
| 407 |
+
label="Target Number of Markers to Select",
|
| 408 |
+
info="Number of top markers to use for modeling"
|
| 409 |
+
)
|
| 410 |
+
|
| 411 |
+
run_button = gr.Button("🚀 Run MTA Analysis", variant="primary", size="lg")
|
| 412 |
+
|
| 413 |
+
with gr.Row():
|
| 414 |
+
with gr.Column(scale=1):
|
| 415 |
+
gr.Markdown("### 📊 Analysis Summary")
|
| 416 |
+
summary_output = gr.Markdown()
|
| 417 |
+
|
| 418 |
+
with gr.Row():
|
| 419 |
+
with gr.Column():
|
| 420 |
+
gr.Markdown("### 🗺️ Manhattan Plot")
|
| 421 |
+
manhattan_output = gr.Image(label="Genome-Wide Association")
|
| 422 |
+
|
| 423 |
+
with gr.Row():
|
| 424 |
+
with gr.Column():
|
| 425 |
+
gr.Markdown("### 📈 Model Performance")
|
| 426 |
+
comparison_output = gr.Image(label="Model Comparison")
|
| 427 |
+
|
| 428 |
+
with gr.Column():
|
| 429 |
+
gr.Markdown("### 🎯 Prediction Accuracy")
|
| 430 |
+
prediction_output = gr.Image(label="Observed vs Predicted")
|
| 431 |
+
|
| 432 |
+
with gr.Row():
|
| 433 |
+
with gr.Column(scale=1):
|
| 434 |
+
gr.Markdown("""
|
| 435 |
+
### 💾 Download Complete Results
|
| 436 |
+
|
| 437 |
+
The ZIP file contains:
|
| 438 |
+
- All prediction files (CSV)
|
| 439 |
+
- MTA association results for all models
|
| 440 |
+
- Chromosome-specific analyses
|
| 441 |
+
- All visualization plots
|
| 442 |
+
""")
|
| 443 |
+
download_output = gr.File(label="Download Results Package")
|
| 444 |
+
|
| 445 |
+
gr.Markdown("""
|
| 446 |
+
---
|
| 447 |
+
### 🔬 Analysis Pipeline
|
| 448 |
+
|
| 449 |
+
1. **Quality Control**: Filter markers and samples based on missing data and MAF
|
| 450 |
+
2. **GWAS**: Single-marker regression analysis with Bonferroni correction
|
| 451 |
+
3. **ML Feature Selection**: Consensus selection using 5 methods (RF, MI, F-test, GB, ElasticNet)
|
| 452 |
+
4. **Predictive Modeling**: Train 5 models (LASSO, RF, GB, Ridge, ElasticNet) with cross-validation
|
| 453 |
+
5. **Results**: Generate predictions, associations, and comprehensive visualizations
|
| 454 |
+
|
| 455 |
+
---
|
| 456 |
+
|
| 457 |
+
**Created by Ashmi** | Enhanced MTA Analysis Tool v2.0
|
| 458 |
+
""")
|
| 459 |
+
|
| 460 |
+
# Connect the button to the analysis function
|
| 461 |
+
run_button.click(
|
| 462 |
+
fn=run_mta_analysis,
|
| 463 |
+
inputs=[input_file, target_markers],
|
| 464 |
+
outputs=[summary_output, manhattan_output, comparison_output, prediction_output, download_output]
|
| 465 |
+
)
|
| 466 |
+
|
| 467 |
+
# Launch the app
|
| 468 |
+
if __name__ == "__main__":
|
| 469 |
+
app.launch(
|
| 470 |
+
share=True,
|
| 471 |
+
show_error=True
|
| 472 |
+
)
|