Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,14 +1,24 @@
|
|
| 1 |
# -*- coding: utf-8 -*-
|
| 2 |
"""
|
| 3 |
-
Enhanced MTA Analysis - Gradio Interface (Fixed Version)
|
| 4 |
A comprehensive web interface for Multi-Trait Association analysis
|
| 5 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
"""
|
| 7 |
|
| 8 |
import gradio as 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
|
|
@@ -18,455 +28,908 @@ 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 |
-
#
|
| 30 |
-
|
| 31 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
|
| 34 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
"""
|
| 36 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
try:
|
| 39 |
if input_file is None:
|
| 40 |
-
return "Please upload a CSV file first.",
|
| 41 |
-
|
| 42 |
-
|
|
|
|
| 43 |
temp_dir = tempfile.mkdtemp()
|
| 44 |
results_dir = os.path.join(temp_dir, 'results')
|
| 45 |
-
plots_dir
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
for folder in [results_dir, plots_dir, chrom_dir]:
|
| 49 |
os.makedirs(folder, exist_ok=True)
|
| 50 |
-
|
| 51 |
-
#
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 59 |
df_data = df.iloc[1:].reset_index(drop=True)
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 71 |
qc_marker = (missing_per_marker < 0.1) & (maf > 0.01)
|
| 72 |
qc_sample = missing_per_sample < 0.1
|
| 73 |
-
|
| 74 |
-
genotypes_qc
|
| 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(
|
| 78 |
-
chromosome_qc
|
| 79 |
-
|
| 80 |
-
|
|
|
|
|
|
|
|
|
|
| 81 |
for i in range(genotypes_qc.shape[1]):
|
| 82 |
-
|
|
|
|
| 83 |
if mask.any():
|
| 84 |
-
genotypes_qc[mask, i] = np.nanmean(
|
| 85 |
-
|
| 86 |
TARGET_MARKERS = min(int(target_markers), len(marker_names_qc))
|
| 87 |
-
|
| 88 |
-
#
|
| 89 |
-
p_values
|
| 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 |
-
|
| 97 |
-
p_values[i]
|
| 98 |
-
gwas_effects[i] = slope
|
| 99 |
-
|
|
|
|
| 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 |
-
|
| 106 |
-
|
|
|
|
|
|
|
|
|
|
| 107 |
y = phenotypes_qc
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
|
|
|
| 127 |
votes = np.zeros(len(marker_names_qc))
|
| 128 |
-
for
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 137 |
models = {}
|
| 138 |
-
for
|
| 139 |
-
(
|
| 140 |
-
|
| 141 |
-
(
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
if hasattr(model_obj, 'feature_importances_'):
|
| 149 |
-
effects = model_obj.feature_importances_
|
| 150 |
else:
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
models[
|
| 154 |
-
'model':
|
| 155 |
-
'pred': pred,
|
| 156 |
'r2': r2_score(y, pred),
|
| 157 |
-
'
|
| 158 |
-
'
|
|
|
|
| 159 |
}
|
| 160 |
-
|
| 161 |
-
best_name
|
| 162 |
best_model = models[best_name]
|
| 163 |
-
|
| 164 |
-
#
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 175 |
mta_results = {}
|
| 176 |
-
for
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
if not chrom_idx:
|
| 206 |
continue
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 233 |
manhattan_path = os.path.join(plots_dir, 'manhattan_plot.png')
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
#
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 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.
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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,
|
| 293 |
for file in files:
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 299 |
summary = f"""
|
| 300 |
-
# MTA Analysis Complete
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 301 |
|
| 302 |
-
|
| 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 |
-
|
| 309 |
-
- **Cross-Validation RΒ²**: {best_model['cv']:.4f}
|
| 310 |
-
- **Training RΒ²**: {best_model['r2']:.4f}
|
| 311 |
|
| 312 |
-
##
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 313 |
"""
|
| 314 |
-
for
|
| 315 |
-
|
| 316 |
-
summary += f"
|
| 317 |
-
|
| 318 |
summary += f"""
|
| 319 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 320 |
"""
|
| 321 |
-
for
|
| 322 |
-
summary += f"{int(row[
|
| 323 |
-
|
|
|
|
|
|
|
| 324 |
summary += f"""
|
| 325 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 326 |
"""
|
| 327 |
-
for
|
| 328 |
-
summary += f"{int(row['Rank'])}
|
| 329 |
-
|
|
|
|
| 330 |
summary += """
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
- `
|
| 335 |
-
- `
|
| 336 |
-
- `
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 337 |
"""
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
except Exception as e:
|
| 342 |
import traceback
|
| 343 |
-
error_msg = f"
|
| 344 |
-
return error_msg, None, None, None, None
|
| 345 |
-
|
| 346 |
|
| 347 |
-
# ========== GRADIO INTERFACE ==========
|
| 348 |
|
| 349 |
-
#
|
|
|
|
|
|
|
| 350 |
custom_css = """
|
| 351 |
-
.gradio-container {
|
| 352 |
-
|
| 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 |
-
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
---
|
| 376 |
""")
|
| 377 |
-
|
| 378 |
with gr.Row():
|
| 379 |
with gr.Column(scale=1):
|
| 380 |
gr.Markdown("""
|
| 381 |
-
### π
|
| 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 |
-
-,
|
| 392 |
-
|
| 393 |
-
|
| 394 |
```
|
| 395 |
""")
|
| 396 |
-
|
| 397 |
-
|
| 398 |
-
|
| 399 |
-
|
| 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 |
-
|
| 415 |
-
|
| 416 |
-
|
| 417 |
-
|
|
|
|
| 418 |
with gr.Row():
|
| 419 |
with gr.Column():
|
| 420 |
-
gr.Markdown("###
|
| 421 |
-
|
| 422 |
-
|
|
|
|
|
|
|
|
|
|
| 423 |
with gr.Row():
|
| 424 |
with gr.Column():
|
| 425 |
-
gr.Markdown("###
|
| 426 |
-
comparison_output = gr.Image(label="Model
|
| 427 |
-
|
| 428 |
with gr.Column():
|
| 429 |
-
gr.Markdown("### π―
|
| 430 |
-
prediction_output = gr.Image(label="
|
| 431 |
-
|
| 432 |
-
|
| 433 |
-
|
| 434 |
-
|
| 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 |
-
|
| 450 |
-
|
| 451 |
-
|
| 452 |
-
|
| 453 |
-
|
| 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,
|
|
|
|
| 465 |
)
|
| 466 |
|
| 467 |
-
# Launch the app
|
| 468 |
if __name__ == "__main__":
|
| 469 |
-
app.launch(
|
| 470 |
-
share=True,
|
| 471 |
-
show_error=True
|
| 472 |
-
)
|
|
|
|
| 1 |
# -*- coding: utf-8 -*-
|
| 2 |
"""
|
| 3 |
+
Enhanced MTA Analysis - Gradio Interface (Fully Fixed Version)
|
| 4 |
A comprehensive web interface for Multi-Trait Association analysis
|
| 5 |
+
|
| 6 |
+
FIXES:
|
| 7 |
+
- Corrected CSV parsing: Column 2 = Chromosome, Column 3 = Phenotype, Column 4+ = Markers
|
| 8 |
+
- Manhattan plot: proper chromosome coloring, no overlapping labels, correct spacing
|
| 9 |
+
- Added QQ plot with confidence bands
|
| 10 |
+
- Added LD Decay plot and analysis
|
| 11 |
+
- Chromosome info now included in all CSV outputs
|
| 12 |
+
- Improved interpretations and summaries
|
| 13 |
"""
|
| 14 |
|
| 15 |
import gradio as gr
|
| 16 |
import pandas as pd
|
| 17 |
import numpy as np
|
| 18 |
+
import matplotlib
|
| 19 |
+
matplotlib.use('Agg')
|
| 20 |
import matplotlib.pyplot as plt
|
| 21 |
+
import matplotlib.patches as mpatches
|
| 22 |
import seaborn as sns
|
| 23 |
from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor
|
| 24 |
from sklearn.linear_model import LassoCV, ElasticNetCV, Ridge
|
|
|
|
| 28 |
from sklearn.metrics import r2_score, mean_squared_error
|
| 29 |
from scipy import stats
|
| 30 |
import os
|
|
|
|
| 31 |
import warnings
|
| 32 |
import tempfile
|
|
|
|
| 33 |
import zipfile
|
| 34 |
|
| 35 |
warnings.filterwarnings('ignore')
|
| 36 |
|
| 37 |
+
# βββββββββββββββββββββββββββββββββββββββββββββ
|
| 38 |
+
# GLOBAL PLOT STYLE
|
| 39 |
+
# βββββββββββββββββββββββββββββββββββββββββββββ
|
| 40 |
+
plt.rcParams.update({
|
| 41 |
+
'figure.dpi': 150,
|
| 42 |
+
'font.family': 'DejaVu Sans',
|
| 43 |
+
'axes.titlepad': 14,
|
| 44 |
+
'axes.labelpad': 8,
|
| 45 |
+
'xtick.labelsize': 11,
|
| 46 |
+
'ytick.labelsize': 11,
|
| 47 |
+
'axes.titlesize': 15,
|
| 48 |
+
'axes.labelsize': 13,
|
| 49 |
+
})
|
| 50 |
|
| 51 |
+
CHROM_COLORS = [
|
| 52 |
+
"#E41A1C", "#377EB8", "#4DAF4A", "#984EA3", "#FF7F00",
|
| 53 |
+
"#A65628", "#F781BF", "#999999", "#66C2A5", "#FC8D62",
|
| 54 |
+
"#8DA0CB", "#E78AC3", "#A6D854", "#FFD92F", "#E5C494",
|
| 55 |
+
"#B3B3B3", "#1B9E77", "#D95F02", "#7570B3", "#E7298A",
|
| 56 |
+
"#66A61E", "#E6AB02"
|
| 57 |
+
]
|
| 58 |
|
| 59 |
+
|
| 60 |
+
# βββββββββββββββββββββββββββββββββββββββββββββ
|
| 61 |
+
# HELPER: Manhattan Plot (Fixed)
|
| 62 |
+
# βββββββββββββββββββββββββββββββββββββββββββββ
|
| 63 |
+
def plot_manhattan(marker_names, chromosomes, p_values, consensus_set,
|
| 64 |
+
bonf_thresh, save_path):
|
| 65 |
"""
|
| 66 |
+
Draws a publication-quality Manhattan plot.
|
| 67 |
+
- No overlapping x-axis labels
|
| 68 |
+
- Alternating chromosome colors
|
| 69 |
+
- Highlighted selected markers in red
|
| 70 |
+
- Proper spacing between chromosomes
|
| 71 |
"""
|
| 72 |
+
unique_chroms = []
|
| 73 |
+
seen = set()
|
| 74 |
+
for c in chromosomes:
|
| 75 |
+
if c not in seen:
|
| 76 |
+
unique_chroms.append(c)
|
| 77 |
+
seen.add(c)
|
| 78 |
+
unique_chroms = sorted(unique_chroms, key=lambda x: (
|
| 79 |
+
int(x) if x.isdigit() else 999, x))
|
| 80 |
+
|
| 81 |
+
log_p = -np.log10(np.array(p_values) + 1e-300)
|
| 82 |
+
|
| 83 |
+
# Build x-positions with a gap between chromosomes
|
| 84 |
+
GAP = max(5, len(marker_names) // 200)
|
| 85 |
+
x_pos = np.zeros(len(marker_names))
|
| 86 |
+
chrom_centers = {}
|
| 87 |
+
chrom_starts = {}
|
| 88 |
+
offset = 0
|
| 89 |
+
|
| 90 |
+
chrom_to_idx = {}
|
| 91 |
+
for i, m in enumerate(marker_names):
|
| 92 |
+
c = chromosomes[i]
|
| 93 |
+
if c not in chrom_to_idx:
|
| 94 |
+
chrom_to_idx[c] = []
|
| 95 |
+
chrom_to_idx[c].append(i)
|
| 96 |
+
|
| 97 |
+
for ci, chrom in enumerate(unique_chroms):
|
| 98 |
+
idxs = chrom_to_idx.get(chrom, [])
|
| 99 |
+
if not idxs:
|
| 100 |
+
continue
|
| 101 |
+
chrom_starts[chrom] = offset
|
| 102 |
+
for rank, idx in enumerate(idxs):
|
| 103 |
+
x_pos[idx] = offset + rank
|
| 104 |
+
chrom_centers[chrom] = offset + (len(idxs) - 1) / 2
|
| 105 |
+
offset += len(idxs) + GAP
|
| 106 |
+
|
| 107 |
+
fig, ax = plt.subplots(figsize=(20, 6))
|
| 108 |
+
|
| 109 |
+
for ci, chrom in enumerate(unique_chroms):
|
| 110 |
+
idxs = chrom_to_idx.get(chrom, [])
|
| 111 |
+
if not idxs:
|
| 112 |
+
continue
|
| 113 |
+
color = CHROM_COLORS[ci % len(CHROM_COLORS)]
|
| 114 |
+
|
| 115 |
+
# Normal markers
|
| 116 |
+
normal = [i for i in idxs if i not in consensus_set]
|
| 117 |
+
if normal:
|
| 118 |
+
ax.scatter(x_pos[normal], log_p[normal],
|
| 119 |
+
c=color, s=14, alpha=0.65, linewidths=0, zorder=2)
|
| 120 |
+
|
| 121 |
+
# Selected / consensus markers
|
| 122 |
+
sel = [i for i in idxs if i in consensus_set]
|
| 123 |
+
if sel:
|
| 124 |
+
ax.scatter(x_pos[sel], log_p[sel],
|
| 125 |
+
c='red', s=55, alpha=0.95,
|
| 126 |
+
edgecolors='darkred', linewidths=0.6, zorder=4,
|
| 127 |
+
marker='D')
|
| 128 |
+
|
| 129 |
+
# Bonferroni line
|
| 130 |
+
ax.axhline(bonf_thresh, color='#333333', ls='--', lw=1.8, alpha=0.85,
|
| 131 |
+
label=f'Bonferroni threshold (Ξ±=0.05)')
|
| 132 |
+
|
| 133 |
+
# Suggestive line
|
| 134 |
+
suggestive = -np.log10(1e-5)
|
| 135 |
+
if suggestive < bonf_thresh:
|
| 136 |
+
ax.axhline(suggestive, color='steelblue', ls=':', lw=1.4, alpha=0.7,
|
| 137 |
+
label='Suggestive threshold (1Γ10β»β΅)')
|
| 138 |
+
|
| 139 |
+
# X-axis: chromosome labels centered, no overlap
|
| 140 |
+
xtick_pos = [chrom_centers[c] for c in unique_chroms if c in chrom_centers]
|
| 141 |
+
xtick_lab = [c for c in unique_chroms if c in chrom_centers]
|
| 142 |
+
|
| 143 |
+
ax.set_xticks(xtick_pos)
|
| 144 |
+
ax.set_xticklabels(xtick_lab, fontsize=9, rotation=45 if len(unique_chroms) > 15 else 0,
|
| 145 |
+
ha='center')
|
| 146 |
+
ax.set_xlim(-GAP, offset)
|
| 147 |
+
ax.set_ylim(bottom=0)
|
| 148 |
+
|
| 149 |
+
ax.set_xlabel('Chromosome', fontsize=13, fontweight='bold')
|
| 150 |
+
ax.set_ylabel('βlogββ(P-value)', fontsize=13, fontweight='bold')
|
| 151 |
+
ax.set_title('Genome-Wide Association Study β Manhattan Plot', fontsize=15, fontweight='bold')
|
| 152 |
+
|
| 153 |
+
# Legend
|
| 154 |
+
red_patch = mpatches.Patch(color='red', label='Selected markers (consensus ML)')
|
| 155 |
+
handles = [red_patch]
|
| 156 |
+
line1 = plt.Line2D([0], [0], color='#333333', ls='--', lw=1.8,
|
| 157 |
+
label=f'Bonferroni (Ξ±=0.05, βlogββp={bonf_thresh:.2f})')
|
| 158 |
+
handles.append(line1)
|
| 159 |
+
if suggestive < bonf_thresh:
|
| 160 |
+
line2 = plt.Line2D([0], [0], color='steelblue', ls=':', lw=1.4,
|
| 161 |
+
label='Suggestive (1Γ10β»β΅)')
|
| 162 |
+
handles.append(line2)
|
| 163 |
+
ax.legend(handles=handles, fontsize=10, loc='upper right', framealpha=0.9)
|
| 164 |
+
|
| 165 |
+
ax.spines['top'].set_visible(False)
|
| 166 |
+
ax.spines['right'].set_visible(False)
|
| 167 |
+
ax.grid(axis='y', alpha=0.25, linestyle='--')
|
| 168 |
+
|
| 169 |
+
plt.tight_layout()
|
| 170 |
+
plt.savefig(save_path, dpi=200, bbox_inches='tight')
|
| 171 |
+
plt.close(fig)
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
# βββββββββββββββββββββββββββββββββββββββββββββ
|
| 175 |
+
# HELPER: QQ Plot
|
| 176 |
+
# βββββββββββββββββββββββββββββββββββββββββββββ
|
| 177 |
+
def plot_qq(p_values, save_path):
|
| 178 |
+
"""
|
| 179 |
+
QQ plot of observed vs expected βlog10(p) with 95% confidence band.
|
| 180 |
+
"""
|
| 181 |
+
pv = np.array(p_values)
|
| 182 |
+
pv = pv[~np.isnan(pv)]
|
| 183 |
+
pv = np.clip(pv, 1e-300, 1.0)
|
| 184 |
+
n = len(pv)
|
| 185 |
+
|
| 186 |
+
obs = np.sort(pv)
|
| 187 |
+
expected_uniform = np.linspace(1 / n, 1, n)
|
| 188 |
+
log_obs = -np.log10(obs)
|
| 189 |
+
log_exp = -np.log10(expected_uniform)
|
| 190 |
+
|
| 191 |
+
# 95% confidence band (beta distribution)
|
| 192 |
+
ci_upper = -np.log10(stats.beta.ppf(0.025, np.arange(1, n + 1),
|
| 193 |
+
np.arange(n, 0, -1)))
|
| 194 |
+
ci_lower = -np.log10(stats.beta.ppf(0.975, np.arange(1, n + 1),
|
| 195 |
+
np.arange(n, 0, -1)))
|
| 196 |
+
ci_lower = np.maximum(ci_lower, 0)
|
| 197 |
+
|
| 198 |
+
# Genomic inflation factor Ξ»
|
| 199 |
+
chi2 = stats.chi2.ppf(1 - pv, df=1)
|
| 200 |
+
lam = np.median(chi2) / stats.chi2.ppf(0.5, df=1)
|
| 201 |
+
|
| 202 |
+
fig, ax = plt.subplots(figsize=(7, 7))
|
| 203 |
+
|
| 204 |
+
ax.fill_between(log_exp, ci_lower, ci_upper,
|
| 205 |
+
color='lightblue', alpha=0.5, label='95% CI')
|
| 206 |
+
ax.scatter(log_exp, log_obs, c='#E41A1C', s=12, alpha=0.7,
|
| 207 |
+
linewidths=0, zorder=3)
|
| 208 |
+
max_val = max(log_obs.max(), log_exp.max()) * 1.05
|
| 209 |
+
ax.plot([0, max_val], [0, max_val], 'k--', lw=1.5, label='Expected (null)')
|
| 210 |
+
|
| 211 |
+
ax.set_xlabel('Expected βlogββ(P)', fontsize=13, fontweight='bold')
|
| 212 |
+
ax.set_ylabel('Observed βlogββ(P)', fontsize=13, fontweight='bold')
|
| 213 |
+
ax.set_title(f'QQ Plot of GWAS P-values\nGenomic Inflation Factor Ξ» = {lam:.3f}',
|
| 214 |
+
fontsize=14, fontweight='bold')
|
| 215 |
+
ax.set_xlim(0, max_val)
|
| 216 |
+
ax.set_ylim(0, max_val)
|
| 217 |
+
ax.legend(fontsize=11)
|
| 218 |
+
ax.spines['top'].set_visible(False)
|
| 219 |
+
ax.spines['right'].set_visible(False)
|
| 220 |
+
ax.grid(alpha=0.2)
|
| 221 |
+
|
| 222 |
+
# Interpretation note
|
| 223 |
+
if lam < 1.05:
|
| 224 |
+
interp = "Ξ» β 1 β No inflation. GWAS well-controlled."
|
| 225 |
+
elif lam < 1.10:
|
| 226 |
+
interp = "Ξ» slightly elevated β Minor population stratification possible."
|
| 227 |
+
else:
|
| 228 |
+
interp = "Ξ» > 1.1 β Significant inflation. Consider genomic control."
|
| 229 |
+
ax.text(0.02, 0.97, interp, transform=ax.transAxes, fontsize=9,
|
| 230 |
+
va='top', color='navy',
|
| 231 |
+
bbox=dict(boxstyle='round,pad=0.3', fc='lightyellow', alpha=0.8))
|
| 232 |
+
|
| 233 |
+
plt.tight_layout()
|
| 234 |
+
plt.savefig(save_path, dpi=200, bbox_inches='tight')
|
| 235 |
+
plt.close(fig)
|
| 236 |
+
return lam
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
# βββββββββββββββββββββββββββββββββββββββββββββ
|
| 240 |
+
# HELPER: LD Decay Plot
|
| 241 |
+
# βββββββββββββββββββββββββββββββββββββββββββββ
|
| 242 |
+
def plot_ld_decay(genotypes, marker_names, chromosomes, save_path, max_markers_per_chrom=300):
|
| 243 |
+
"""
|
| 244 |
+
Computes pairwise rΒ² within chromosomes and plots LD decay vs physical distance (marker index).
|
| 245 |
+
"""
|
| 246 |
+
unique_chroms = sorted(set(chromosomes), key=lambda x: (int(x) if x.isdigit() else 999, x))
|
| 247 |
+
|
| 248 |
+
all_distances = []
|
| 249 |
+
all_r2 = []
|
| 250 |
+
|
| 251 |
+
chrom_summary = {}
|
| 252 |
+
|
| 253 |
+
for chrom in unique_chroms:
|
| 254 |
+
idxs = [i for i, c in enumerate(chromosomes) if c == chrom]
|
| 255 |
+
if len(idxs) < 4:
|
| 256 |
+
continue
|
| 257 |
+
|
| 258 |
+
# Subsample if needed
|
| 259 |
+
if len(idxs) > max_markers_per_chrom:
|
| 260 |
+
idxs = np.random.choice(idxs, max_markers_per_chrom, replace=False)
|
| 261 |
+
idxs = sorted(idxs)
|
| 262 |
+
|
| 263 |
+
G = genotypes[:, idxs].copy()
|
| 264 |
+
# Standardize
|
| 265 |
+
std = G.std(axis=0)
|
| 266 |
+
std[std == 0] = 1
|
| 267 |
+
G = (G - G.mean(axis=0)) / std
|
| 268 |
+
|
| 269 |
+
n_m = G.shape[1]
|
| 270 |
+
dist_list, r2_list = [], []
|
| 271 |
+
for i in range(n_m - 1):
|
| 272 |
+
for j in range(i + 1, min(i + 50, n_m)): # limit window
|
| 273 |
+
d = j - i
|
| 274 |
+
r = np.corrcoef(G[:, i], G[:, j])[0, 1]
|
| 275 |
+
r2 = r ** 2 if not np.isnan(r) else 0
|
| 276 |
+
dist_list.append(d)
|
| 277 |
+
r2_list.append(r2)
|
| 278 |
+
|
| 279 |
+
if dist_list:
|
| 280 |
+
all_distances.extend(dist_list)
|
| 281 |
+
all_r2.extend(r2_list)
|
| 282 |
+
chrom_summary[chrom] = {
|
| 283 |
+
'mean_r2': np.mean(r2_list),
|
| 284 |
+
'n_markers': len(idxs)
|
| 285 |
+
}
|
| 286 |
+
|
| 287 |
+
if not all_distances:
|
| 288 |
+
# No data β save blank
|
| 289 |
+
fig, ax = plt.subplots(figsize=(9, 5))
|
| 290 |
+
ax.text(0.5, 0.5, "Insufficient data for LD decay", ha='center', va='center')
|
| 291 |
+
plt.savefig(save_path, dpi=150)
|
| 292 |
+
plt.close(fig)
|
| 293 |
+
return {}
|
| 294 |
+
|
| 295 |
+
all_distances = np.array(all_distances)
|
| 296 |
+
all_r2 = np.array(all_r2)
|
| 297 |
+
|
| 298 |
+
# Bin by distance
|
| 299 |
+
max_dist = min(all_distances.max(), 50)
|
| 300 |
+
bins = np.arange(1, max_dist + 1)
|
| 301 |
+
mean_r2_per_bin = []
|
| 302 |
+
se_r2_per_bin = []
|
| 303 |
+
for b in bins:
|
| 304 |
+
mask = all_distances == b
|
| 305 |
+
if mask.sum() > 0:
|
| 306 |
+
mean_r2_per_bin.append(np.mean(all_r2[mask]))
|
| 307 |
+
se_r2_per_bin.append(np.std(all_r2[mask]) / np.sqrt(mask.sum()))
|
| 308 |
+
else:
|
| 309 |
+
mean_r2_per_bin.append(np.nan)
|
| 310 |
+
se_r2_per_bin.append(np.nan)
|
| 311 |
+
|
| 312 |
+
mean_r2_arr = np.array(mean_r2_per_bin)
|
| 313 |
+
se_arr = np.array(se_r2_per_bin)
|
| 314 |
+
|
| 315 |
+
# Find half-decay distance
|
| 316 |
+
start_r2 = mean_r2_arr[~np.isnan(mean_r2_arr)][0] if any(~np.isnan(mean_r2_arr)) else 1.0
|
| 317 |
+
half = start_r2 / 2
|
| 318 |
+
half_decay_dist = None
|
| 319 |
+
for i, r2 in enumerate(mean_r2_arr):
|
| 320 |
+
if not np.isnan(r2) and r2 <= half:
|
| 321 |
+
half_decay_dist = bins[i]
|
| 322 |
+
break
|
| 323 |
+
|
| 324 |
+
fig, axes = plt.subplots(1, 2, figsize=(16, 6))
|
| 325 |
+
|
| 326 |
+
# Left: LD decay curve
|
| 327 |
+
ax = axes[0]
|
| 328 |
+
valid = ~np.isnan(mean_r2_arr)
|
| 329 |
+
ax.fill_between(bins[valid],
|
| 330 |
+
(mean_r2_arr - se_arr)[valid].clip(0),
|
| 331 |
+
(mean_r2_arr + se_arr)[valid].clip(0, 1),
|
| 332 |
+
alpha=0.25, color='steelblue', label='Β±1 SE')
|
| 333 |
+
ax.plot(bins[valid], mean_r2_arr[valid], 'o-', color='steelblue',
|
| 334 |
+
markersize=5, lw=2, label='Mean rΒ²')
|
| 335 |
+
ax.axhline(0.2, color='red', ls='--', lw=1.4, alpha=0.8, label='rΒ²=0.2 (common LD threshold)')
|
| 336 |
+
if half_decay_dist:
|
| 337 |
+
ax.axvline(half_decay_dist, color='orange', ls='--', lw=1.4,
|
| 338 |
+
label=f'Half-decay at d={half_decay_dist}')
|
| 339 |
+
ax.set_xlabel('Marker Distance (index units)', fontsize=13, fontweight='bold')
|
| 340 |
+
ax.set_ylabel('Mean rΒ²', fontsize=13, fontweight='bold')
|
| 341 |
+
ax.set_title('LD Decay Across All Chromosomes', fontsize=14, fontweight='bold')
|
| 342 |
+
ax.set_ylim(0, 1)
|
| 343 |
+
ax.legend(fontsize=10)
|
| 344 |
+
ax.spines['top'].set_visible(False)
|
| 345 |
+
ax.spines['right'].set_visible(False)
|
| 346 |
+
ax.grid(alpha=0.2)
|
| 347 |
+
|
| 348 |
+
# Right: Per-chromosome mean rΒ²
|
| 349 |
+
ax2 = axes[1]
|
| 350 |
+
chroms_sorted = sorted(chrom_summary.keys(),
|
| 351 |
+
key=lambda x: (int(x) if x.isdigit() else 999, x))
|
| 352 |
+
mean_vals = [chrom_summary[c]['mean_r2'] for c in chroms_sorted]
|
| 353 |
+
colors = [CHROM_COLORS[i % len(CHROM_COLORS)] for i in range(len(chroms_sorted))]
|
| 354 |
+
bars = ax2.bar(range(len(chroms_sorted)), mean_vals, color=colors, edgecolor='black',
|
| 355 |
+
linewidth=0.6, alpha=0.85)
|
| 356 |
+
ax2.set_xticks(range(len(chroms_sorted)))
|
| 357 |
+
ax2.set_xticklabels(chroms_sorted, rotation=45 if len(chroms_sorted) > 10 else 0,
|
| 358 |
+
fontsize=9, ha='right')
|
| 359 |
+
ax2.set_xlabel('Chromosome', fontsize=13, fontweight='bold')
|
| 360 |
+
ax2.set_ylabel('Mean rΒ²', fontsize=13, fontweight='bold')
|
| 361 |
+
ax2.set_title('Mean LD (rΒ²) per Chromosome', fontsize=14, fontweight='bold')
|
| 362 |
+
ax2.set_ylim(0, 1)
|
| 363 |
+
ax2.spines['top'].set_visible(False)
|
| 364 |
+
ax2.spines['right'].set_visible(False)
|
| 365 |
+
ax2.grid(axis='y', alpha=0.25)
|
| 366 |
+
|
| 367 |
+
# Add value labels on bars
|
| 368 |
+
for bar, val in zip(bars, mean_vals):
|
| 369 |
+
ax2.text(bar.get_x() + bar.get_width() / 2, bar.get_height() + 0.01,
|
| 370 |
+
f'{val:.2f}', ha='center', va='bottom', fontsize=8)
|
| 371 |
+
|
| 372 |
+
plt.suptitle('Linkage Disequilibrium (LD) Analysis', fontsize=16, fontweight='bold', y=1.01)
|
| 373 |
+
plt.tight_layout()
|
| 374 |
+
plt.savefig(save_path, dpi=200, bbox_inches='tight')
|
| 375 |
+
plt.close(fig)
|
| 376 |
+
|
| 377 |
+
return chrom_summary
|
| 378 |
+
|
| 379 |
+
|
| 380 |
+
# βββββββββββββββββββββββββββββββββββββββββββββ
|
| 381 |
+
# MAIN ANALYSIS FUNCTION
|
| 382 |
+
# ββββββββββββββββββββββββββββοΏ½οΏ½ββββββββββββββββ
|
| 383 |
+
def run_mta_analysis(input_file, target_markers):
|
| 384 |
try:
|
| 385 |
if input_file is None:
|
| 386 |
+
return ("Please upload a CSV file first.",
|
| 387 |
+
None, None, None, None, None)
|
| 388 |
+
|
| 389 |
+
# ββ Temp dirs ββββββββββββββββββββββββββββββ
|
| 390 |
temp_dir = tempfile.mkdtemp()
|
| 391 |
results_dir = os.path.join(temp_dir, 'results')
|
| 392 |
+
plots_dir = os.path.join(results_dir, 'plots')
|
| 393 |
+
for folder in [results_dir, plots_dir]:
|
|
|
|
|
|
|
| 394 |
os.makedirs(folder, exist_ok=True)
|
| 395 |
+
|
| 396 |
+
# ββ LOAD DATA ββββββββββββββββββββββββββββββ
|
| 397 |
+
# Expected format:
|
| 398 |
+
# Col 0 : Sample ID
|
| 399 |
+
# Col 1 : Chromosome (row 0 = header "Chromosome", row 1+ = values)
|
| 400 |
+
# Col 2 : Phenotype (row 0 = header "Phenotype", row 1+ = values)
|
| 401 |
+
# Col 3+: Markers (row 0 = marker names, row 1 = chr info, row 2+ = genotype scores)
|
| 402 |
+
#
|
| 403 |
+
# HOWEVER β original script treats row 1 as chromosome info for markers.
|
| 404 |
+
# We preserve that logic but fix column indexing.
|
| 405 |
+
|
| 406 |
+
df = pd.read_csv(input_file, sep=',', header=0)
|
| 407 |
+
|
| 408 |
+
# Row 0 of df = chromosome info row (for markers starting col 3)
|
| 409 |
+
# Row 1+ = actual sample data
|
| 410 |
+
# Col 0 = ID, Col 1 = Chromosome (sample chrom β skip), Col 2 = Phenotype, Col 3+ = Markers
|
| 411 |
+
|
| 412 |
+
# --- Extract marker chromosome info (first data row) ---
|
| 413 |
+
marker_cols = df.columns[3:].tolist() # marker column names
|
| 414 |
+
chrom_info_row = df.iloc[0, 3:].values.astype(str) # chr per marker
|
| 415 |
+
chromosome_dict = {m: c for m, c in zip(marker_cols, chrom_info_row)}
|
| 416 |
+
|
| 417 |
+
# --- Actual data rows (skip row 0 which has chrom info) ---
|
| 418 |
df_data = df.iloc[1:].reset_index(drop=True)
|
| 419 |
+
|
| 420 |
+
sample_ids = df_data.iloc[:, 0].astype(str).values
|
| 421 |
+
sample_chrom = df_data.iloc[:, 1].astype(str).values # sample-level chrom (if any)
|
| 422 |
+
phenotypes = pd.to_numeric(df_data.iloc[:, 2], errors='coerce').values
|
| 423 |
+
genotypes = df_data.iloc[:, 3:].apply(pd.to_numeric, errors='coerce').values
|
| 424 |
+
marker_names = marker_cols
|
| 425 |
+
|
| 426 |
+
unique_chromosomes = sorted(set(chrom_info_row),
|
| 427 |
+
key=lambda x: (int(x) if x.isdigit() else 999, x))
|
| 428 |
+
|
| 429 |
+
n_samples = len(sample_ids)
|
| 430 |
+
n_markers = len(marker_names)
|
| 431 |
+
|
| 432 |
+
# ββ QC βββββββββββββββββββββββββββββββββββββ
|
| 433 |
+
missing_per_marker = np.isnan(genotypes).sum(axis=0) / n_samples
|
| 434 |
+
missing_per_sample = np.isnan(genotypes).sum(axis=1) / n_markers
|
| 435 |
+
|
| 436 |
+
maf = np.array([
|
| 437 |
+
min(np.nanmean(genotypes[:, i]) / 2,
|
| 438 |
+
1 - np.nanmean(genotypes[:, i]) / 2)
|
| 439 |
+
if not np.all(np.isnan(genotypes[:, i])) else 0
|
| 440 |
+
for i in range(n_markers)
|
| 441 |
+
])
|
| 442 |
+
|
| 443 |
qc_marker = (missing_per_marker < 0.1) & (maf > 0.01)
|
| 444 |
qc_sample = missing_per_sample < 0.1
|
| 445 |
+
|
| 446 |
+
genotypes_qc = genotypes[qc_sample][:, qc_marker].copy()
|
| 447 |
phenotypes_qc = phenotypes[qc_sample]
|
| 448 |
sample_ids_qc = sample_ids[qc_sample]
|
| 449 |
+
marker_names_qc = [marker_names[i] for i in range(n_markers) if qc_marker[i]]
|
| 450 |
+
chromosome_qc = [chromosome_dict[m] for m in marker_names_qc]
|
| 451 |
+
|
| 452 |
+
n_removed_markers = n_markers - len(marker_names_qc)
|
| 453 |
+
n_removed_samples = n_samples - len(sample_ids_qc)
|
| 454 |
+
|
| 455 |
+
# Impute missing
|
| 456 |
for i in range(genotypes_qc.shape[1]):
|
| 457 |
+
col = genotypes_qc[:, i]
|
| 458 |
+
mask = np.isnan(col)
|
| 459 |
if mask.any():
|
| 460 |
+
genotypes_qc[mask, i] = np.nanmean(col)
|
| 461 |
+
|
| 462 |
TARGET_MARKERS = min(int(target_markers), len(marker_names_qc))
|
| 463 |
+
|
| 464 |
+
# ββ GWAS βββββββββββββββββββββββββββββββββββ
|
| 465 |
+
p_values = np.ones(len(marker_names_qc))
|
| 466 |
gwas_effects = np.zeros(len(marker_names_qc))
|
| 467 |
+
gwas_se = np.zeros(len(marker_names_qc))
|
| 468 |
+
|
| 469 |
for i in range(len(marker_names_qc)):
|
| 470 |
marker = genotypes_qc[:, i]
|
| 471 |
if np.std(marker) > 0:
|
| 472 |
try:
|
| 473 |
+
result = stats.linregress(marker, phenotypes_qc)
|
| 474 |
+
p_values[i] = result.pvalue
|
| 475 |
+
gwas_effects[i] = result.slope
|
| 476 |
+
gwas_se[i] = result.stderr
|
| 477 |
+
except Exception:
|
| 478 |
pass
|
| 479 |
+
|
|
|
|
| 480 |
bonf_thresh = -np.log10(0.05 / len(marker_names_qc))
|
| 481 |
+
n_sig = int(np.sum(p_values < 0.05 / len(marker_names_qc)))
|
| 482 |
+
n_suggestive = int(np.sum(p_values < 1e-5))
|
| 483 |
+
|
| 484 |
+
# ββ ML FEATURE SELECTION βββββββββββββββββββ
|
| 485 |
+
scaler = StandardScaler()
|
| 486 |
+
X = scaler.fit_transform(genotypes_qc)
|
| 487 |
y = phenotypes_qc
|
| 488 |
+
|
| 489 |
+
rf_fs = RandomForestRegressor(n_estimators=100, max_depth=10,
|
| 490 |
+
random_state=42, n_jobs=-1)
|
| 491 |
+
rf_fs.fit(X, y)
|
| 492 |
+
rf_top = set(np.argsort(rf_fs.feature_importances_)[-TARGET_MARKERS:])
|
| 493 |
+
|
| 494 |
+
mi = mutual_info_regression(X, y, random_state=42)
|
| 495 |
+
mi_top = set(np.argsort(mi)[-TARGET_MARKERS:])
|
| 496 |
+
|
| 497 |
+
f_sc, _ = f_regression(X, y)
|
| 498 |
+
f_top = set(np.argsort(f_sc)[-TARGET_MARKERS:])
|
| 499 |
+
|
| 500 |
+
gb_fs = GradientBoostingRegressor(n_estimators=100, max_depth=5, random_state=42)
|
| 501 |
+
gb_fs.fit(X, y)
|
| 502 |
+
gb_top = set(np.argsort(gb_fs.feature_importances_)[-TARGET_MARKERS:])
|
| 503 |
+
|
| 504 |
+
enet_fs = ElasticNetCV(cv=5, random_state=42, max_iter=5000)
|
| 505 |
+
enet_fs.fit(X, y)
|
| 506 |
+
enet_top = set(np.argsort(np.abs(enet_fs.coef_))[-TARGET_MARKERS:])
|
| 507 |
+
|
| 508 |
votes = np.zeros(len(marker_names_qc))
|
| 509 |
+
for sel in [rf_top, mi_top, f_top, gb_top, enet_top]:
|
| 510 |
+
for idx in sel:
|
| 511 |
+
votes[idx] += 1
|
| 512 |
+
|
| 513 |
+
consensus_indices = np.argsort(votes)[-TARGET_MARKERS:]
|
| 514 |
+
consensus_set = set(consensus_indices)
|
| 515 |
+
|
| 516 |
+
# ββ PREDICTIVE MODELS ββββββββββββββββββββββ
|
| 517 |
+
X_sel = X[:, consensus_indices]
|
| 518 |
+
cv = KFold(n_splits=5, shuffle=True, random_state=42)
|
| 519 |
+
|
| 520 |
+
model_specs = [
|
| 521 |
+
('LASSO', LassoCV(cv=5, random_state=42, max_iter=10000)),
|
| 522 |
+
('RF', RandomForestRegressor(n_estimators=200, max_depth=15,
|
| 523 |
+
random_state=42, n_jobs=-1)),
|
| 524 |
+
('GB', GradientBoostingRegressor(n_estimators=200, max_depth=7,
|
| 525 |
+
random_state=42)),
|
| 526 |
+
('Ridge', Ridge(alpha=1.0)),
|
| 527 |
+
('ElasticNet', ElasticNetCV(cv=5, random_state=42, max_iter=5000)),
|
| 528 |
+
]
|
| 529 |
+
|
| 530 |
models = {}
|
| 531 |
+
for name, obj in model_specs:
|
| 532 |
+
obj.fit(X_sel, y)
|
| 533 |
+
pred = obj.predict(X_sel)
|
| 534 |
+
cv_r2 = cross_val_score(obj, X_sel, y, cv=cv, scoring='r2').mean()
|
| 535 |
+
|
| 536 |
+
if hasattr(obj, 'feature_importances_'):
|
| 537 |
+
eff = obj.feature_importances_
|
| 538 |
+
elif hasattr(obj, 'coef_'):
|
| 539 |
+
eff = np.abs(obj.coef_)
|
|
|
|
|
|
|
|
|
|
| 540 |
else:
|
| 541 |
+
eff = np.zeros(X_sel.shape[1])
|
| 542 |
+
|
| 543 |
+
models[name] = {
|
| 544 |
+
'model': obj, 'pred': pred,
|
|
|
|
| 545 |
'r2': r2_score(y, pred),
|
| 546 |
+
'rmse': np.sqrt(mean_squared_error(y, pred)),
|
| 547 |
+
'cv': cv_r2,
|
| 548 |
+
'effects': eff,
|
| 549 |
}
|
| 550 |
+
|
| 551 |
+
best_name = max(models, key=lambda k: models[k]['cv'])
|
| 552 |
best_model = models[best_name]
|
| 553 |
+
|
| 554 |
+
# ββ SAVE CSVs ββββββββββββββββββββββββββββββ
|
| 555 |
+
# Predictions
|
| 556 |
+
pred_df = pd.DataFrame({
|
| 557 |
+
'SampleID': sample_ids_qc,
|
| 558 |
+
'Observed': phenotypes_qc,
|
| 559 |
+
})
|
| 560 |
+
for nm, data in models.items():
|
| 561 |
+
pred_df[f'GEBV_{nm}'] = data['pred']
|
| 562 |
+
pred_df[f'Residual_{nm}'] = phenotypes_qc - data['pred']
|
| 563 |
+
pred_df['Best_GEBV'] = pred_df[f'GEBV_{best_name}']
|
| 564 |
+
pred_df['Rank'] = pred_df['Best_GEBV'].rank(ascending=False).astype(int)
|
| 565 |
+
pred_df = pred_df.sort_values('Best_GEBV', ascending=False)
|
| 566 |
+
pred_df.to_csv(os.path.join(results_dir, 'all_model_predictions.csv'), index=False)
|
| 567 |
+
|
| 568 |
+
# MTA associations β with Chromosome column
|
| 569 |
mta_results = {}
|
| 570 |
+
for nm, data in models.items():
|
| 571 |
+
rows = []
|
| 572 |
+
for rank_i, idx in enumerate(
|
| 573 |
+
np.argsort(data['effects'])[::-1]): # sort by effect desc
|
| 574 |
+
orig_idx = consensus_indices[idx]
|
| 575 |
+
rows.append({
|
| 576 |
+
'Rank': rank_i + 1,
|
| 577 |
+
'Marker': marker_names_qc[orig_idx],
|
| 578 |
+
'Chromosome': chromosome_qc[orig_idx], # β chromosome included
|
| 579 |
+
f'Effect_{nm}': data['effects'][idx],
|
| 580 |
+
'Vote_Count': int(votes[orig_idx]),
|
| 581 |
+
'GWAS_Pvalue': p_values[orig_idx],
|
| 582 |
+
'GWAS_logP': -np.log10(p_values[orig_idx] + 1e-300),
|
| 583 |
+
'GWAS_Effect': gwas_effects[orig_idx],
|
| 584 |
+
'GWAS_SE': gwas_se[orig_idx],
|
| 585 |
+
})
|
| 586 |
+
mta_df = pd.DataFrame(rows)
|
| 587 |
+
total = mta_df[f'Effect_{nm}'].sum()
|
| 588 |
+
mta_df[f'Contribution_pct_{nm}'] = (
|
| 589 |
+
mta_df[f'Effect_{nm}'] / total * 100 if total > 0 else 0)
|
| 590 |
+
mta_results[nm] = mta_df
|
| 591 |
+
mta_df.to_csv(
|
| 592 |
+
os.path.join(results_dir, f'mta_associations_{nm}.csv'), index=False)
|
| 593 |
+
|
| 594 |
+
# Per-chromosome summary
|
| 595 |
+
chrom_summary_rows = []
|
| 596 |
+
for chrom in unique_chromosomes:
|
| 597 |
+
c_idx = [i for i, c in enumerate(chromosome_qc) if c == chrom]
|
| 598 |
+
if not c_idx:
|
|
|
|
| 599 |
continue
|
| 600 |
+
c_pvals = p_values[c_idx]
|
| 601 |
+
c_sel = sum(1 for i in c_idx if i in consensus_set)
|
| 602 |
+
chrom_summary_rows.append({
|
| 603 |
+
'Chromosome': chrom,
|
| 604 |
+
'N_Markers': len(c_idx),
|
| 605 |
+
'N_Selected': c_sel,
|
| 606 |
+
'Min_Pvalue': c_pvals.min(),
|
| 607 |
+
'Best_logP': -np.log10(c_pvals.min() + 1e-300),
|
| 608 |
+
'Mean_logP': float(-np.log10(c_pvals + 1e-300).mean()),
|
| 609 |
+
'N_Significant': int((c_pvals < 0.05 / len(marker_names_qc)).sum()),
|
| 610 |
+
'N_Suggestive': int((c_pvals < 1e-5).sum()),
|
| 611 |
+
})
|
| 612 |
+
chrom_sum_df = pd.DataFrame(chrom_summary_rows)
|
| 613 |
+
chrom_sum_df.to_csv(
|
| 614 |
+
os.path.join(results_dir, 'chromosome_summary.csv'), index=False)
|
| 615 |
+
|
| 616 |
+
# QC summary
|
| 617 |
+
qc_df = pd.DataFrame({
|
| 618 |
+
'Metric': [
|
| 619 |
+
'Total Samples', 'Samples Passed QC', 'Samples Removed',
|
| 620 |
+
'Total Markers', 'Markers Passed QC', 'Markers Removed',
|
| 621 |
+
'Markers Selected', 'Chromosomes',
|
| 622 |
+
'Bonferroni Threshold (-log10p)', 'N Significant Markers',
|
| 623 |
+
'N Suggestive Markers',
|
| 624 |
+
],
|
| 625 |
+
'Value': [
|
| 626 |
+
n_samples, len(sample_ids_qc), n_removed_samples,
|
| 627 |
+
n_markers, len(marker_names_qc), n_removed_markers,
|
| 628 |
+
TARGET_MARKERS, len(unique_chromosomes),
|
| 629 |
+
round(bonf_thresh, 4), n_sig, n_suggestive,
|
| 630 |
+
]
|
| 631 |
+
})
|
| 632 |
+
qc_df.to_csv(os.path.join(results_dir, 'qc_summary.csv'), index=False)
|
| 633 |
+
|
| 634 |
+
# ββ PLOTS ββββββββββββββββββββββββββββββββββ
|
| 635 |
+
|
| 636 |
+
# 1) Manhattan
|
| 637 |
manhattan_path = os.path.join(plots_dir, 'manhattan_plot.png')
|
| 638 |
+
plot_manhattan(marker_names_qc, chromosome_qc, p_values,
|
| 639 |
+
consensus_set, bonf_thresh, manhattan_path)
|
| 640 |
+
|
| 641 |
+
# 2) QQ plot
|
| 642 |
+
qq_path = os.path.join(plots_dir, 'qq_plot.png')
|
| 643 |
+
lambda_gc = plot_qq(p_values, qq_path)
|
| 644 |
+
|
| 645 |
+
# 3) LD decay
|
| 646 |
+
ld_path = os.path.join(plots_dir, 'ld_decay.png')
|
| 647 |
+
ld_chrom_summary = plot_ld_decay(genotypes_qc, marker_names_qc,
|
| 648 |
+
chromosome_qc, ld_path)
|
| 649 |
+
|
| 650 |
+
# 4) Model comparison
|
| 651 |
+
comp_path = os.path.join(plots_dir, 'model_comparison.png')
|
| 652 |
+
fig, ax = plt.subplots(figsize=(11, 6))
|
| 653 |
+
names_list = list(models.keys())
|
| 654 |
+
cv_r2_list = [models[m]['cv'] for m in names_list]
|
| 655 |
+
train_r2_list = [models[m]['r2'] for m in names_list]
|
| 656 |
+
rmse_list = [models[m]['rmse'] for m in names_list]
|
| 657 |
+
x = np.arange(len(names_list))
|
| 658 |
+
w = 0.30
|
| 659 |
+
b1 = ax.bar(x - w, train_r2_list, w, label='Train RΒ²',
|
| 660 |
+
color='#AED6F1', edgecolor='black', alpha=0.9)
|
| 661 |
+
b2 = ax.bar(x, cv_r2_list, w, label='CV RΒ²',
|
| 662 |
+
color='#A9DFBF', edgecolor='black', alpha=0.9)
|
| 663 |
+
bi = names_list.index(best_name)
|
| 664 |
+
for b in [b1[bi], b2[bi]]:
|
| 665 |
+
b.set_edgecolor('red'); b.set_linewidth(2.5)
|
| 666 |
+
for xi, (tr, cv_r) in enumerate(zip(train_r2_list, cv_r2_list)):
|
| 667 |
+
ax.text(xi - w, tr + 0.01, f'{tr:.3f}', ha='center', va='bottom', fontsize=9)
|
| 668 |
+
ax.text(xi, cv_r + 0.01, f'{cv_r:.3f}', ha='center', va='bottom', fontsize=9)
|
| 669 |
+
ax.set_ylabel('RΒ²', fontsize=13, fontweight='bold')
|
| 670 |
+
ax.set_title('Predictive Model Performance Comparison\n(Red border = Best CV model)',
|
| 671 |
+
fontsize=14, fontweight='bold')
|
| 672 |
+
ax.set_xticks(x); ax.set_xticklabels(names_list, fontsize=11)
|
| 673 |
+
ax.legend(fontsize=11); ax.set_ylim(0, 1.1)
|
| 674 |
+
ax.spines['top'].set_visible(False); ax.spines['right'].set_visible(False)
|
| 675 |
+
ax.grid(axis='y', alpha=0.25)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 676 |
plt.tight_layout()
|
| 677 |
+
plt.savefig(comp_path, dpi=200, bbox_inches='tight'); plt.close(fig)
|
| 678 |
+
|
| 679 |
+
# 5) Observed vs Predicted
|
| 680 |
pred_path = os.path.join(plots_dir, 'observed_vs_predicted.png')
|
| 681 |
+
fig, ax = plt.subplots(figsize=(8, 7))
|
| 682 |
+
ax.scatter(phenotypes_qc, best_model['pred'],
|
| 683 |
+
alpha=0.65, s=55, edgecolors='black', lw=0.5, c='#7D3C98')
|
| 684 |
+
lims = [min(phenotypes_qc.min(), best_model['pred'].min()),
|
| 685 |
+
max(phenotypes_qc.max(), best_model['pred'].max())]
|
| 686 |
+
ax.plot(lims, lims, 'r--', lw=2)
|
| 687 |
+
corr, _ = stats.pearsonr(phenotypes_qc, best_model['pred'])
|
| 688 |
+
ax.set_xlabel('Observed Phenotype', fontsize=13, fontweight='bold')
|
| 689 |
+
ax.set_ylabel('Predicted GEBV', fontsize=13, fontweight='bold')
|
| 690 |
+
ax.set_title(
|
| 691 |
+
f'Best Model ({best_name}): Observed vs Predicted\n'
|
| 692 |
+
f'CV RΒ² = {best_model["cv"]:.4f} | RMSE = {best_model["rmse"]:.4f} | r = {corr:.4f}',
|
| 693 |
+
fontsize=13, fontweight='bold')
|
| 694 |
+
ax.grid(alpha=0.2); ax.spines['top'].set_visible(False); ax.spines['right'].set_visible(False)
|
| 695 |
+
plt.tight_layout()
|
| 696 |
+
plt.savefig(pred_path, dpi=200, bbox_inches='tight'); plt.close(fig)
|
| 697 |
+
|
| 698 |
+
# 6) Top marker effects (best model)
|
| 699 |
+
top_eff_path = os.path.join(plots_dir, 'top_marker_effects.png')
|
| 700 |
+
top_mta = mta_results[best_name].head(30)
|
| 701 |
+
fig, ax = plt.subplots(figsize=(12, 8))
|
| 702 |
+
colors_bar = [CHROM_COLORS[
|
| 703 |
+
sorted(set(chromosome_qc),
|
| 704 |
+
key=lambda x: (int(x) if x.isdigit() else 999, x)).index(c)
|
| 705 |
+
% len(CHROM_COLORS)]
|
| 706 |
+
for c in top_mta['Chromosome']]
|
| 707 |
+
bars = ax.barh(range(len(top_mta)),
|
| 708 |
+
top_mta[f'Effect_{best_name}'].values,
|
| 709 |
+
color=colors_bar, edgecolor='black', linewidth=0.5, alpha=0.85)
|
| 710 |
+
ax.set_yticks(range(len(top_mta)))
|
| 711 |
+
ax.set_yticklabels(
|
| 712 |
+
[f"{row['Marker']} (Chr {row['Chromosome']})"
|
| 713 |
+
for _, row in top_mta.iterrows()],
|
| 714 |
+
fontsize=9)
|
| 715 |
+
ax.invert_yaxis()
|
| 716 |
+
ax.set_xlabel(f'Effect Size ({best_name})', fontsize=12, fontweight='bold')
|
| 717 |
+
ax.set_title(f'Top 30 Selected Markers β {best_name} Model', fontsize=14, fontweight='bold')
|
| 718 |
+
ax.spines['top'].set_visible(False); ax.spines['right'].set_visible(False)
|
| 719 |
+
ax.grid(axis='x', alpha=0.2)
|
| 720 |
+
plt.tight_layout()
|
| 721 |
+
plt.savefig(top_eff_path, dpi=200, bbox_inches='tight'); plt.close(fig)
|
| 722 |
+
|
| 723 |
+
# ββ ZIP ββββββββββββββββββββββββββββββββββββ
|
| 724 |
zip_path = os.path.join(temp_dir, 'mta_results.zip')
|
| 725 |
with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
|
| 726 |
+
for root, _, files in os.walk(results_dir):
|
| 727 |
for file in files:
|
| 728 |
+
fp = os.path.join(root, file)
|
| 729 |
+
zipf.write(fp, os.path.relpath(fp, temp_dir))
|
| 730 |
+
|
| 731 |
+
# ββ SUMMARY TEXT βββββββββββββββββββββββββββ
|
| 732 |
+
# Interpret lambda
|
| 733 |
+
if lambda_gc < 1.05:
|
| 734 |
+
lam_interp = "β
Ξ» β 1 β excellent GWAS calibration, no inflation detected."
|
| 735 |
+
elif lambda_gc < 1.10:
|
| 736 |
+
lam_interp = "β οΈ Ξ» slightly elevated β minor stratification possible; consider STRUCTURE/PCA correction."
|
| 737 |
+
else:
|
| 738 |
+
lam_interp = "β Ξ» > 1.1 β significant inflation detected. Apply genomic control (GC correction) or use mixed models (EMMAX/GEMMA)."
|
| 739 |
+
|
| 740 |
+
# Interpret LD
|
| 741 |
+
if ld_chrom_summary:
|
| 742 |
+
global_mean_r2 = np.mean([v['mean_r2'] for v in ld_chrom_summary.values()])
|
| 743 |
+
if global_mean_r2 < 0.1:
|
| 744 |
+
ld_interp = "Low LD β high marker density needed; most markers are in low LD."
|
| 745 |
+
elif global_mean_r2 < 0.3:
|
| 746 |
+
ld_interp = "Moderate LD β typical for diverse panels. Good power for detection."
|
| 747 |
+
else:
|
| 748 |
+
ld_interp = "High LD β markers are correlated; fewer independent signals. Consider LD pruning."
|
| 749 |
+
else:
|
| 750 |
+
global_mean_r2 = 0
|
| 751 |
+
ld_interp = "LD data insufficient for interpretation."
|
| 752 |
+
|
| 753 |
summary = f"""
|
| 754 |
+
# 𧬠MTA Analysis Complete β
|
| 755 |
+
|
| 756 |
+
---
|
| 757 |
+
|
| 758 |
+
## π Dataset & QC Summary
|
| 759 |
+
| Metric | Value |
|
| 760 |
+
|--------|-------|
|
| 761 |
+
| Samples (raw) | {n_samples} |
|
| 762 |
+
| Samples after QC | {len(sample_ids_qc)} ({n_removed_samples} removed) |
|
| 763 |
+
| Markers (raw) | {n_markers} |
|
| 764 |
+
| Markers after QC | {len(marker_names_qc)} ({n_removed_markers} removed) |
|
| 765 |
+
| Markers selected | {TARGET_MARKERS} |
|
| 766 |
+
| Chromosomes | {len(unique_chromosomes)} ({', '.join(unique_chromosomes[:10])}{'...' if len(unique_chromosomes) > 10 else ''}) |
|
| 767 |
+
|
| 768 |
+
---
|
| 769 |
+
|
| 770 |
+
## π¬ GWAS Results
|
| 771 |
+
| Metric | Value |
|
| 772 |
+
|--------|-------|
|
| 773 |
+
| Bonferroni threshold | βlogββp = {bonf_thresh:.3f} |
|
| 774 |
+
| Significant markers (Bonferroni) | **{n_sig}** |
|
| 775 |
+
| Suggestive markers (p < 1Γ10β»β΅) | {n_suggestive} |
|
| 776 |
+
| Genomic inflation Ξ» | {lambda_gc:.4f} |
|
| 777 |
|
| 778 |
+
**Interpretation:** {lam_interp}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 779 |
|
| 780 |
+
---
|
|
|
|
|
|
|
| 781 |
|
| 782 |
+
## π LD Analysis
|
| 783 |
+
| Metric | Value |
|
| 784 |
+
|--------|-------|
|
| 785 |
+
| Global mean rΒ² | {global_mean_r2:.4f} |
|
| 786 |
+
|
| 787 |
+
**Interpretation:** {ld_interp}
|
| 788 |
+
|
| 789 |
+
---
|
| 790 |
+
|
| 791 |
+
## π€ Model Performance
|
| 792 |
+
| Model | CV RΒ² | Train RΒ² | RMSE |
|
| 793 |
+
|-------|--------|-----------|------|
|
| 794 |
"""
|
| 795 |
+
for nm, data in models.items():
|
| 796 |
+
star = " π" if nm == best_name else ""
|
| 797 |
+
summary += f"| **{nm}{star}** | {data['cv']:.4f} | {data['r2']:.4f} | {data['rmse']:.4f} |\n"
|
| 798 |
+
|
| 799 |
summary += f"""
|
| 800 |
+
**Best Model: {best_name}** (highest CV RΒ²)
|
| 801 |
+
|
| 802 |
+
**Interpretation:** {"The model explains " + str(round(best_model['cv']*100,1)) + "% of phenotypic variance on held-out data β " + ("excellent predictive accuracy." if best_model['cv'] > 0.5 else "moderate predictive accuracy; consider larger training sets or additional markers." if best_model['cv'] > 0.2 else "low accuracy β consider adding more samples or using relatedness-aware models.")}
|
| 803 |
+
|
| 804 |
+
---
|
| 805 |
+
|
| 806 |
+
## π― Top 5 Selected Markers ({best_name})
|
| 807 |
+
| Rank | Marker | Chromosome | Effect | Votes | GWAS βlogββp |
|
| 808 |
+
|------|--------|------------|--------|-------|---------------|
|
| 809 |
"""
|
| 810 |
+
for _, row in mta_results[best_name].head(5).iterrows():
|
| 811 |
+
summary += (f"| {int(row['Rank'])} | {row['Marker']} | Chr {row['Chromosome']} | "
|
| 812 |
+
f"{row[f'Effect_{best_name}']:.6f} | {int(row['Vote_Count'])}/5 | "
|
| 813 |
+
f"{row['GWAS_logP']:.3f} |\n")
|
| 814 |
+
|
| 815 |
summary += f"""
|
| 816 |
+
---
|
| 817 |
+
|
| 818 |
+
## π₯ Top 5 Samples (Highest GEBV)
|
| 819 |
+
| Rank | Sample ID | Observed | Predicted GEBV |
|
| 820 |
+
|------|-----------|----------|----------------|
|
| 821 |
"""
|
| 822 |
+
for _, row in pred_df.head(5).iterrows():
|
| 823 |
+
summary += (f"| {int(row['Rank'])} | {row['SampleID']} | "
|
| 824 |
+
f"{row['Observed']:.3f} | {row['Best_GEBV']:.3f} |\n")
|
| 825 |
+
|
| 826 |
summary += """
|
| 827 |
+
---
|
| 828 |
+
|
| 829 |
+
## π Output Files
|
| 830 |
+
- `all_model_predictions.csv` β GEBVs and rankings for all samples
|
| 831 |
+
- `mta_associations_<Model>.csv` β Marker associations with **Chromosome column** β
|
| 832 |
+
- `chromosome_summary.csv` β Per-chromosome GWAS summary
|
| 833 |
+
- `qc_summary.csv` β Quality control statistics
|
| 834 |
+
- `plots/manhattan_plot.png` β Fixed Manhattan plot (no overlap)
|
| 835 |
+
- `plots/qq_plot.png` β QQ plot with 95% CI and Ξ»
|
| 836 |
+
- `plots/ld_decay.png` β LD decay curve + per-chromosome rΒ²
|
| 837 |
+
- `plots/model_comparison.png` β CV vs Train RΒ² for all models
|
| 838 |
+
- `plots/observed_vs_predicted.png` β Best model prediction scatter
|
| 839 |
+
- `plots/top_marker_effects.png` β Top 30 markers colored by chromosome
|
| 840 |
"""
|
| 841 |
+
return summary, manhattan_path, qq_path, ld_path, comp_path, pred_path, zip_path
|
| 842 |
+
|
|
|
|
| 843 |
except Exception as e:
|
| 844 |
import traceback
|
| 845 |
+
error_msg = f"## β Error\n```\n{str(e)}\n\n{traceback.format_exc()}\n```"
|
| 846 |
+
return error_msg, None, None, None, None, None, None
|
|
|
|
| 847 |
|
|
|
|
| 848 |
|
| 849 |
+
# βββββββββββββββββββββββββββββββββββββββββββββ
|
| 850 |
+
# GRADIO UI
|
| 851 |
+
# βββββββββββββββββββββββββββββββββββββββββββββ
|
| 852 |
custom_css = """
|
| 853 |
+
.gradio-container { font-family: 'Segoe UI', sans-serif; }
|
| 854 |
+
h1 { color: #1a3c5e; border-bottom: 3px solid #2980b9; padding-bottom: 8px; }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 855 |
"""
|
| 856 |
|
| 857 |
with gr.Blocks(css=custom_css, title="MTA Analysis Tool") as app:
|
| 858 |
+
|
| 859 |
gr.Markdown("""
|
| 860 |
+
# 𧬠Enhanced Multi-Trait Association (MTA) Analysis Tool v3.0
|
| 861 |
+
### Genomic Prediction Β· GWAS Β· LD Analysis Β· ML Feature Selection
|
| 862 |
+
|
| 863 |
+
**CSV Format:**
|
| 864 |
+
- Col 1: Sample ID | Col 2: Chromosome | Col 3: Phenotype | Col 4+: Marker genotypes
|
| 865 |
+
- Row 1 (after header): Chromosome assignment per marker
|
| 866 |
+
- Rows 2+: Sample genotype data
|
| 867 |
---
|
| 868 |
""")
|
| 869 |
+
|
| 870 |
with gr.Row():
|
| 871 |
with gr.Column(scale=1):
|
| 872 |
gr.Markdown("""
|
| 873 |
+
### π Expected CSV Format
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 874 |
```
|
| 875 |
+
ID, Chromosome, Phenotype, M1, M2, M3, ...
|
| 876 |
+
-, -, -, 1, 1, 2, ... β marker chromosome row
|
| 877 |
+
S1, 1, 45.2, 0, 1, 2, ...
|
| 878 |
+
S2, 2, 38.7, 1, 0, 1, ...
|
| 879 |
```
|
| 880 |
""")
|
| 881 |
+
input_file = gr.File(label="π Upload Input CSV", file_types=[".csv"])
|
| 882 |
+
target_markers = gr.Slider(100, 5000, value=3000, step=100,
|
| 883 |
+
label="Target Markers to Select",
|
| 884 |
+
info="Top markers for predictive modeling")
|
| 885 |
+
run_button = gr.Button("π Run MTA Analysis", variant="primary", size="lg")
|
| 886 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 887 |
with gr.Row():
|
| 888 |
+
summary_output = gr.Markdown(label="Analysis Summary")
|
| 889 |
+
|
| 890 |
+
gr.Markdown("### πΊοΈ Manhattan Plot")
|
| 891 |
+
manhattan_output = gr.Image(label="GWAS Manhattan Plot")
|
| 892 |
+
|
| 893 |
with gr.Row():
|
| 894 |
with gr.Column():
|
| 895 |
+
gr.Markdown("### π QQ Plot")
|
| 896 |
+
qq_output = gr.Image(label="QQ Plot")
|
| 897 |
+
with gr.Column():
|
| 898 |
+
gr.Markdown("### π LD Decay")
|
| 899 |
+
ld_output = gr.Image(label="LD Decay Plot")
|
| 900 |
+
|
| 901 |
with gr.Row():
|
| 902 |
with gr.Column():
|
| 903 |
+
gr.Markdown("### π Model Comparison")
|
| 904 |
+
comparison_output = gr.Image(label="Model Performance")
|
|
|
|
| 905 |
with gr.Column():
|
| 906 |
+
gr.Markdown("### π― Observed vs Predicted")
|
| 907 |
+
prediction_output = gr.Image(label="Best Model Predictions")
|
| 908 |
+
|
| 909 |
+
gr.Markdown("### πΎ Download Complete Results")
|
| 910 |
+
download_output = gr.File(label="Download ZIP Package")
|
| 911 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 912 |
gr.Markdown("""
|
| 913 |
---
|
| 914 |
### π¬ Analysis Pipeline
|
| 915 |
+
1. **QC** β Filter markers (MAF>1%, missing<10%) and samples (missing<10%)
|
| 916 |
+
2. **GWAS** β Single-marker regression with Bonferroni + suggestive thresholds
|
| 917 |
+
3. **QQ Plot** β Genomic inflation factor (Ξ») assessment
|
| 918 |
+
4. **LD Decay** β Within-chromosome pairwise rΒ² decay analysis
|
| 919 |
+
5. **ML Selection** β Consensus from RF, MI, F-test, GradientBoosting, ElasticNet
|
| 920 |
+
6. **Prediction** β LASSO, RF, GB, Ridge, ElasticNet with 5-fold CV
|
| 921 |
+
7. **Output** β CSVs with Chromosome column, full visualizations, ZIP download
|
| 922 |
+
|
| 923 |
---
|
| 924 |
+
**Created by Ashmi** | Enhanced MTA Analysis Tool v3.0
|
|
|
|
| 925 |
""")
|
| 926 |
+
|
|
|
|
| 927 |
run_button.click(
|
| 928 |
fn=run_mta_analysis,
|
| 929 |
inputs=[input_file, target_markers],
|
| 930 |
+
outputs=[summary_output, manhattan_output, qq_output, ld_output,
|
| 931 |
+
comparison_output, prediction_output, download_output]
|
| 932 |
)
|
| 933 |
|
|
|
|
| 934 |
if __name__ == "__main__":
|
| 935 |
+
app.launch(share=True, show_error=True)
|
|
|
|
|
|
|
|
|