softwareDevelopment commited on
Commit
2370e1d
Β·
verified Β·
1 Parent(s): 4f46068

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +827 -364
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
- @author: Ashmi
 
 
 
 
 
 
 
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
- # 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
- )
 
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)