softwareDevelopment commited on
Commit
74d2f6b
·
verified ·
1 Parent(s): de3c61a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +390 -383
app.py CHANGED
@@ -1,7 +1,11 @@
1
  # -*- coding: utf-8 -*-
2
  """
3
- MTA Analysis Tool v5.0
4
- White theme · Dark-blue text · GWAS only · Bug-fixed · Attractive UI
 
 
 
 
5
  """
6
 
7
  import gradio as gr
@@ -18,28 +22,28 @@ import os, warnings, tempfile, zipfile
18
  warnings.filterwarnings('ignore')
19
 
20
  # ══════════════════════════════════════════════════════════════
21
- # PLOT THEME — clean white, navy/blue palette
22
  # ══════════════════════════════════════════════════════════════
23
- BG = "#FFFFFF"
24
- PANEL = "#F8FAFD"
25
- GRID_C = "#E2EAF4"
26
- TEXT_C = "#0D2B5E" # dark navy
27
- MUTED_C = "#5A7599"
28
- ACCENT = "#1A56DB" # royal blue
29
- RED_C = "#E53E3E" # significance red
30
- GOLD_C = "#D97706" # suggestive amber
31
- GREEN_C = "#0D9488" # teal green
32
- PURPLE_C = "#7C3AED"
33
 
34
  CHROM_PALETTE = [
35
- "#1A56DB","#0D9488","#E53E3E","#7C3AED","#D97706",
36
- "#0891B2","#059669","#DC2626","#6D28D9","#B45309",
37
- "#2563EB","#10B981","#EF4444","#8B5CF6","#F59E0B",
38
- "#0284C7","#34D399","#F87171","#A78BFA","#FCD34D",
39
- "#1D4ED8","#047857",
40
  ]
41
 
42
- def set_white_style():
43
  plt.rcParams.update({
44
  'figure.facecolor' : BG,
45
  'axes.facecolor' : PANEL,
@@ -64,10 +68,9 @@ def set_white_style():
64
  # PLOT 1 — MANHATTAN
65
  # ══════════════════════════════════════════════════════════════
66
  def plot_manhattan(marker_names, chromosomes, p_values, sig_set, bonf_thresh, save_path):
67
- set_white_style()
68
-
69
  unique_chroms = sorted(set(chromosomes),
70
- key=lambda x: (int(x) if x.isdigit() else 999, x))
71
  log_p = -np.log10(np.array(p_values) + 1e-300)
72
 
73
  GAP = max(8, len(marker_names) // 150)
@@ -88,47 +91,40 @@ def plot_manhattan(marker_names, chromosomes, p_values, sig_set, bonf_thresh, sa
88
  fig = plt.figure(figsize=(22, 7), facecolor=BG)
89
  ax = fig.add_subplot(111, facecolor=PANEL)
90
 
91
- # Alternating chromosome bands
92
  for ci, ch in enumerate(unique_chroms):
93
  idxs = chrom_to_idx.get(ch, [])
94
  if not idxs: continue
95
  x0 = x_pos[idxs[0]] - 0.5
96
  x1 = x_pos[idxs[-1]] + 0.5
97
  if ci % 2 == 0:
98
- ax.axvspan(x0, x1, color='#EBF2FF', alpha=0.55, zorder=0)
99
 
100
  for ci, ch in enumerate(unique_chroms):
101
  idxs = chrom_to_idx.get(ch, [])
102
  if not idxs: continue
103
  col = CHROM_PALETTE[ci % len(CHROM_PALETTE)]
104
-
105
  normal = [i for i in idxs if i not in sig_set]
106
  sel = [i for i in idxs if i in sig_set]
107
-
108
  if normal:
109
  ax.scatter(x_pos[normal], log_p[normal],
110
- c=col, s=12, alpha=0.60, linewidths=0, zorder=2)
111
  if sel:
112
- # shadow glow
113
  ax.scatter(x_pos[sel], log_p[sel],
114
- c=RED_C, s=260, alpha=0.15, linewidths=0, zorder=3)
115
  ax.scatter(x_pos[sel], log_p[sel],
116
  c=RED_C, s=70, alpha=1.0,
117
- edgecolors='white', linewidths=1.0,
118
  marker='D', zorder=4)
119
 
120
- # Threshold lines
121
  ax.axhline(bonf_thresh, color=RED_C, ls='--', lw=1.8, alpha=0.85, zorder=5)
122
  ax.text(offset * 0.005, bonf_thresh + log_p.max()*0.02,
123
- f'Bonferroni α=0.05', color=RED_C, fontsize=9,
124
- fontweight='bold', va='bottom')
125
 
126
  sugg = -np.log10(1e-5)
127
  if sugg < bonf_thresh:
128
  ax.axhline(sugg, color=GOLD_C, ls=':', lw=1.5, alpha=0.8, zorder=5)
129
  ax.text(offset * 0.005, sugg + log_p.max()*0.02,
130
- 'Suggestive 1×10⁻⁵', color=GOLD_C, fontsize=9,
131
- fontweight='bold', va='bottom')
132
 
133
  xtick_pos = [chrom_centers[c] for c in unique_chroms if c in chrom_centers]
134
  xtick_lab = [f'Chr {c}' for c in unique_chroms if c in chrom_centers]
@@ -139,14 +135,10 @@ def plot_manhattan(marker_names, chromosomes, p_values, sig_set, bonf_thresh, sa
139
  ha='center', color=TEXT_C, fontweight='600')
140
  ax.set_xlim(-GAP, offset)
141
  ax.set_ylim(bottom=0, top=log_p.max() * 1.16)
142
-
143
- ax.set_ylabel('−log₁₀(P-value)', fontsize=13, color=TEXT_C,
144
- fontweight='bold', labelpad=10)
145
- ax.set_xlabel('Chromosome', fontsize=13, color=TEXT_C,
146
- fontweight='bold', labelpad=10)
147
  ax.set_title('Genome-Wide Association Study · Manhattan Plot',
148
  fontsize=17, color=TEXT_C, fontweight='bold', pad=20)
149
-
150
  ax.yaxis.grid(True, color=GRID_C, linewidth=0.8, alpha=1.0)
151
  ax.set_axisbelow(True)
152
  ax.tick_params(axis='both', colors=TEXT_C, length=4)
@@ -157,7 +149,6 @@ def plot_manhattan(marker_names, chromosomes, p_values, sig_set, bonf_thresh, sa
157
  ax.legend(handles=[h_sig, h_bonf, h_sugg], fontsize=10,
158
  loc='upper right', facecolor=BG, edgecolor=GRID_C)
159
 
160
- # Top annotation: highlight strongest hit per chrom
161
  for ch in unique_chroms:
162
  idxs = chrom_to_idx.get(ch, [])
163
  if not idxs: continue
@@ -178,8 +169,7 @@ def plot_manhattan(marker_names, chromosomes, p_values, sig_set, bonf_thresh, sa
178
  # PLOT 2 — QQ PLOT
179
  # ══════════════════════════════════════════════════════════════
180
  def plot_qq(p_values, save_path):
181
- set_white_style()
182
-
183
  pv = np.clip(np.array(p_values)[~np.isnan(p_values)], 1e-300, 1.0)
184
  n = len(pv)
185
  obs = np.sort(pv)
@@ -198,9 +188,9 @@ def plot_qq(p_values, save_path):
198
  ax.set_facecolor(PANEL)
199
 
200
  ax.fill_between(log_exp, ci_lo, ci_up,
201
- color=ACCENT, alpha=0.12, label='95% Confidence Band')
202
 
203
- sc = ax.scatter(log_exp, log_obs, c=log_obs, cmap='RdYlBu_r',
204
  s=14, alpha=0.80, linewidths=0, zorder=3)
205
  plt.colorbar(sc, ax=ax, shrink=0.75, label='−log₁₀(P)')
206
 
@@ -211,8 +201,7 @@ def plot_qq(p_values, save_path):
211
  lam_col = GREEN_C if lam < 1.05 else (GOLD_C if lam < 1.10 else RED_C)
212
  lam_lbl = ("Well-calibrated" if lam < 1.05
213
  else "Minor inflation" if lam < 1.10 else "Significant inflation")
214
- ax.text(0.05, 0.95,
215
- f'λ = {lam:.4f}\n{lam_lbl}',
216
  transform=ax.transAxes, fontsize=11, va='top', color=lam_col,
217
  fontweight='bold',
218
  bbox=dict(boxstyle='round,pad=0.5', fc=BG, ec=lam_col, lw=1.5, alpha=0.9))
@@ -237,10 +226,9 @@ def plot_qq(p_values, save_path):
237
  # PLOT 3 — LD DECAY
238
  # ══════════════════════════════════════════════════════════════
239
  def plot_ld_decay(genotypes, chromosomes, save_path, max_m=250):
240
- set_white_style()
241
-
242
  unique_chroms = sorted(set(chromosomes),
243
- key=lambda x: (int(x) if x.isdigit() else 999, x))
244
  all_d, all_r2, chrom_mean = [], [], {}
245
 
246
  for ch in unique_chroms:
@@ -264,7 +252,6 @@ def plot_ld_decay(genotypes, chromosomes, save_path, max_m=250):
264
 
265
  fig, axes = plt.subplots(1, 2, figsize=(16, 6), facecolor=BG)
266
 
267
- # ── Left: decay curve ──
268
  ax = axes[0]; ax.set_facecolor(PANEL)
269
  if all_d:
270
  all_d = np.array(all_d)
@@ -283,19 +270,16 @@ def plot_ld_decay(genotypes, chromosomes, save_path, max_m=250):
283
  v = ~np.isnan(mu)
284
 
285
  ax.fill_between(bins[v],
286
- np.clip(mu[v]-se[v], 0, 1),
287
- np.clip(mu[v]+se[v], 0, 1),
288
- color=ACCENT, alpha=0.15, label='±1 SE')
289
 
290
- # gradient line
291
  pts = np.array([bins[v], mu[v]]).T.reshape(-1, 1, 2)
292
  segs = np.concatenate([pts[:-1], pts[1:]], axis=1)
293
- lc = LineCollection(segs, cmap='Blues', linewidth=2.8, zorder=4)
294
  lc.set_array(mu[v])
295
  ax.add_collection(lc)
296
- ax.scatter(bins[v], mu[v], c=mu[v], cmap='Blues',
297
- s=22, zorder=5, linewidths=0.5,
298
- edgecolors=MUTED_C)
299
 
300
  ax.axhline(0.2, color=RED_C, ls='--', lw=1.3, alpha=0.8, label='r²=0.2 threshold')
301
 
@@ -308,16 +292,14 @@ def plot_ld_decay(genotypes, chromosomes, save_path, max_m=250):
308
 
309
  ax.set_xlabel('Marker Distance (index)', fontsize=12, color=TEXT_C, fontweight='bold')
310
  ax.set_ylabel('Mean r²', fontsize=12, color=TEXT_C, fontweight='bold')
311
- ax.set_title('LD Decay Across Chromosomes', fontsize=14, color=TEXT_C,
312
- fontweight='bold', pad=12)
313
  ax.set_ylim(0, 1); ax.tick_params(colors=TEXT_C)
314
  ax.yaxis.grid(True, color=GRID_C, lw=0.8)
315
  ax.legend(fontsize=9, facecolor=BG, edgecolor=GRID_C)
316
 
317
- # ── Right: per-chromosome bars ──
318
  ax2 = axes[1]; ax2.set_facecolor(PANEL)
319
  if chrom_mean:
320
- cs = sorted(chrom_mean.keys(), key=lambda x: (int(x) if x.isdigit() else 999, x))
321
  vals = [chrom_mean[c] for c in cs]
322
  cols = [CHROM_PALETTE[i % len(CHROM_PALETTE)] for i in range(len(cs))]
323
  bars = ax2.bar(range(len(cs)), vals, color=cols,
@@ -327,16 +309,12 @@ def plot_ld_decay(genotypes, chromosomes, save_path, max_m=250):
327
  rotation=45 if len(cs) > 10 else 0,
328
  fontsize=8.5, ha='right', color=TEXT_C)
329
  for bar, val in zip(bars, vals):
330
- ax2.text(bar.get_x() + bar.get_width()/2,
331
- bar.get_height() + 0.02,
332
- f'{val:.2f}', ha='center', va='bottom',
333
- fontsize=8, color=TEXT_C, fontweight='600')
334
  ax2.set_xlabel('Chromosome', fontsize=12, color=TEXT_C, fontweight='bold')
335
  ax2.set_ylabel('Mean r²', fontsize=12, color=TEXT_C, fontweight='bold')
336
- ax2.set_title('Mean LD per Chromosome', fontsize=14, color=TEXT_C,
337
- fontweight='bold', pad=12)
338
- ax2.set_ylim(0, 1.15)
339
- ax2.tick_params(colors=TEXT_C)
340
  ax2.yaxis.grid(True, color=GRID_C, lw=0.8)
341
 
342
  fig.suptitle('Linkage Disequilibrium (LD) Analysis',
@@ -351,35 +329,29 @@ def plot_ld_decay(genotypes, chromosomes, save_path, max_m=250):
351
  # PLOT 4 — GWAS EFFECT SIZE VOLCANO
352
  # ══════════════════════════════════════════════════════════════
353
  def plot_volcano(marker_names, effects, p_values, bonf_thresh, save_path, top_n=10):
354
- set_white_style()
355
-
356
- log_p = -np.log10(np.array(p_values) + 1e-300)
357
  sig_mask = log_p >= bonf_thresh
358
  sug_mask = (log_p >= -np.log10(1e-5)) & ~sig_mask
359
 
360
  fig, ax = plt.subplots(figsize=(10, 7), facecolor=BG)
361
  ax.set_facecolor(PANEL)
362
 
363
- # Non-significant
364
  ns = ~sig_mask & ~sug_mask
365
  ax.scatter(np.array(effects)[ns], log_p[ns],
366
  c=MUTED_C, s=10, alpha=0.35, linewidths=0, zorder=1, label='Non-significant')
367
- # Suggestive
368
  if sug_mask.any():
369
  ax.scatter(np.array(effects)[sug_mask], log_p[sug_mask],
370
  c=GOLD_C, s=20, alpha=0.65, linewidths=0, zorder=2, label='Suggestive')
371
- # Significant
372
  if sig_mask.any():
373
  ax.scatter(np.array(effects)[sig_mask], log_p[sig_mask],
374
  c=RED_C, s=55, alpha=0.90,
375
- edgecolors='white', linewidths=0.7,
376
- zorder=3, label='Significant')
377
 
378
  ax.axhline(bonf_thresh, color=RED_C, ls='--', lw=1.6, alpha=0.8)
379
  ax.axhline(-np.log10(1e-5), color=GOLD_C, ls=':', lw=1.3, alpha=0.8)
380
  ax.axvline(0, color=MUTED_C, lw=0.8, ls='-', alpha=0.4)
381
 
382
- # Annotate top hits
383
  top_idx = np.argsort(log_p)[-top_n:]
384
  for i in top_idx:
385
  if log_p[i] >= bonf_thresh:
@@ -404,45 +376,37 @@ def plot_volcano(marker_names, effects, p_values, bonf_thresh, save_path, top_n=
404
 
405
 
406
  # ══════════════════════════════════════════════════════════════
407
- # PLOT 5 — TOP GWAS HITS (bar chart)
408
  # ═══════════��══════════════════════════════════════════════════
409
  def plot_top_hits(marker_names, chromosomes, p_values, effects, bonf_thresh,
410
  save_path, top_n=25):
411
- set_white_style()
412
-
413
  log_p = -np.log10(np.array(p_values) + 1e-300)
414
  order = np.argsort(log_p)[-top_n:][::-1]
415
 
416
  unique_chroms = sorted(set(chromosomes),
417
- key=lambda x: (int(x) if x.isdigit() else 999, x))
418
- col_map = {c: CHROM_PALETTE[i % len(CHROM_PALETTE)]
419
- for i,c in enumerate(unique_chroms)}
420
 
421
  fig, axes = plt.subplots(1, 2, figsize=(16, 8), facecolor=BG)
422
 
423
- # Left: −log10(p) bars
424
  ax = axes[0]; ax.set_facecolor(PANEL)
425
  labels = [f"{marker_names[i]} (Chr {chromosomes[i]})" for i in order]
426
  vals = [log_p[i] for i in order]
427
  cols = [col_map.get(chromosomes[i], ACCENT) for i in order]
428
-
429
- bars = ax.barh(range(len(order)), vals, color=cols,
430
- edgecolor='white', linewidth=0.6, alpha=0.88, height=0.65)
431
  ax.axvline(bonf_thresh, color=RED_C, ls='--', lw=1.5, alpha=0.9, label='Bonferroni')
432
  ax.set_yticks(range(len(order)))
433
  ax.set_yticklabels(labels, fontsize=8.5, color=TEXT_C)
434
  ax.invert_yaxis()
435
  ax.set_xlabel('−log₁₀(P-value)', fontsize=12, color=TEXT_C, fontweight='bold')
436
- ax.set_title(f'Top {top_n} GWAS Hits', fontsize=14, color=TEXT_C,
437
- fontweight='bold', pad=12)
438
- ax.xaxis.grid(True, color=GRID_C, lw=0.8)
439
- ax.tick_params(colors=TEXT_C)
440
- ax.legend(fontsize=9, facecolor=BG, edgecolor=GRID_C)
441
  for bar, val in zip(bars, vals):
442
  ax.text(bar.get_width() + 0.05, bar.get_y() + bar.get_height()/2,
443
  f'{val:.2f}', va='center', fontsize=8, color=TEXT_C)
444
 
445
- # Right: effect size bars (positive=blue, negative=red)
446
  ax2 = axes[1]; ax2.set_facecolor(PANEL)
447
  eff_vals = [effects[i] for i in order]
448
  eff_cols = [ACCENT if e >= 0 else RED_C for e in eff_vals]
@@ -453,12 +417,9 @@ def plot_top_hits(marker_names, chromosomes, p_values, effects, bonf_thresh,
453
  ax2.set_yticklabels(labels, fontsize=8.5, color=TEXT_C)
454
  ax2.invert_yaxis()
455
  ax2.set_xlabel('Effect Size (β)', fontsize=12, color=TEXT_C, fontweight='bold')
456
- ax2.set_title('Effect Directions of Top Hits', fontsize=14, color=TEXT_C,
457
- fontweight='bold', pad=12)
458
- ax2.xaxis.grid(True, color=GRID_C, lw=0.8)
459
- ax2.tick_params(colors=TEXT_C)
460
 
461
- # Chromosome legend
462
  handles = []
463
  shown = set()
464
  for i in order:
@@ -476,7 +437,50 @@ def plot_top_hits(marker_names, chromosomes, p_values, effects, bonf_thresh,
476
 
477
 
478
  # ══════════════════════════════════════════════════════════════
479
- # MAIN ANALYSIS (GWAS only — no GEBV)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
480
  # ══════════════════════════════════════════════════════════════
481
  def run_mta_analysis(input_file, target_markers):
482
  try:
@@ -489,29 +493,20 @@ def run_mta_analysis(input_file, target_markers):
489
  for d in [results_dir, plots_dir]:
490
  os.makedirs(d, exist_ok=True)
491
 
492
- # ── LOAD ──────────────────────────────────
493
- df = pd.read_csv(input_file, sep=',', header=0)
494
- # Col 0=ID, Col 1=Chromosome, Col 2=Phenotype, Col 3+=Markers
495
- # Row 0 = marker chromosome assignments, Row 1+ = samples
496
-
497
- marker_cols = df.columns[3:].tolist()
498
- chrom_info_row = df.iloc[0, 3:].values.astype(str)
499
- chromosome_dict = {m: c for m, c in zip(marker_cols, chrom_info_row)}
500
 
501
- df_data = df.iloc[1:].reset_index(drop=True)
502
- sample_ids = df_data.iloc[:, 0].astype(str).values
503
- phenotypes = pd.to_numeric(df_data.iloc[:, 2], errors='coerce').values
504
- genotypes = df_data.iloc[:, 3:].apply(pd.to_numeric, errors='coerce').values
505
- marker_names = marker_cols
506
 
507
- unique_chroms = sorted(set(chrom_info_row),
508
- key=lambda x: (int(x) if x.isdigit() else 999, x))
509
  n_samples = len(sample_ids)
510
  n_markers = len(marker_names)
511
 
512
  # ── QC ────────────────────────────────────
513
- miss_m = np.isnan(genotypes).sum(axis=0) / n_samples
514
- miss_s = np.isnan(genotypes).sum(axis=1) / n_markers
515
  maf = np.array([
516
  min(np.nanmean(genotypes[:,i])/2, 1-np.nanmean(genotypes[:,i])/2)
517
  if not np.all(np.isnan(genotypes[:,i])) else 0
@@ -520,7 +515,7 @@ def run_mta_analysis(input_file, target_markers):
520
  qc_m = (miss_m < 0.1) & (maf > 0.01)
521
  qc_s = miss_s < 0.1
522
 
523
- geno_qc = genotypes[qc_s][:, qc_m].copy()
524
  pheno_qc = phenotypes[qc_s]
525
  ids_qc = sample_ids[qc_s]
526
  mnames_qc = [marker_names[i] for i in range(n_markers) if qc_m[i]]
@@ -529,12 +524,18 @@ def run_mta_analysis(input_file, target_markers):
529
  n_rm_m = n_markers - len(mnames_qc)
530
  n_rm_s = n_samples - len(ids_qc)
531
 
532
- # Impute
533
  for i in range(geno_qc.shape[1]):
534
  col = geno_qc[:, i]
535
  mask = np.isnan(col)
536
  if mask.any():
537
- geno_qc[mask, i] = np.nanmean(col)
 
 
 
 
 
 
538
 
539
  TARGET = min(int(target_markers), len(mnames_qc))
540
 
@@ -556,12 +557,12 @@ def run_mta_analysis(input_file, target_markers):
556
  except:
557
  pass
558
 
559
- bonf = -np.log10(0.05 / len(mnames_qc))
560
- n_sig = int((pvals < 0.05/len(mnames_qc)).sum())
561
- n_sugg = int((pvals < 1e-5).sum())
562
- sig_set = set(np.where(pvals < 0.05/len(mnames_qc))[0])
563
 
564
- # ── ML marker selection (for annotation) ──
565
  from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor
566
  from sklearn.linear_model import ElasticNetCV
567
  from sklearn.feature_selection import mutual_info_regression, f_regression
@@ -575,15 +576,14 @@ def run_mta_analysis(input_file, target_markers):
575
  random_state=42, n_jobs=-1)
576
  rf_fs.fit(X, y)
577
 
578
- gb_fs = GradientBoostingRegressor(n_estimators=100, max_depth=5,
579
- random_state=42)
580
  gb_fs.fit(X, y)
581
 
582
  en_fs = ElasticNetCV(cv=5, random_state=42, max_iter=5000)
583
  en_fs.fit(X, y)
584
 
585
- mi = mutual_info_regression(X, y, random_state=42)
586
- fsc, _ = f_regression(X, y)
587
 
588
  votes = np.zeros(len(mnames_qc))
589
  for arr in [rf_fs.feature_importances_, gb_fs.feature_importances_,
@@ -591,8 +591,6 @@ def run_mta_analysis(input_file, target_markers):
591
  top = np.argsort(arr)[-TARGET:]
592
  votes[top] += 1
593
 
594
- ml_top_set = set(np.argsort(votes)[-TARGET:])
595
-
596
  # ── SAVE CSVs ─────────────────────────────
597
  gwas_df = pd.DataFrame({
598
  'Rank' : 0,
@@ -611,7 +609,6 @@ def run_mta_analysis(input_file, target_markers):
611
  gwas_df['Rank'] = range(1, len(gwas_df)+1)
612
  gwas_df.to_csv(os.path.join(results_dir, 'gwas_results.csv'), index=False)
613
 
614
- # Per-chromosome summary
615
  chr_rows = []
616
  for ch in unique_chroms:
617
  ci = [i for i,c in enumerate(chrom_qc) if c == ch]
@@ -630,7 +627,6 @@ def run_mta_analysis(input_file, target_markers):
630
  pd.DataFrame(chr_rows).to_csv(
631
  os.path.join(results_dir, 'chromosome_summary.csv'), index=False)
632
 
633
- # QC summary
634
  pd.DataFrame({
635
  'Metric': ['Samples_raw','Samples_QC','Markers_raw','Markers_QC',
636
  'Target_Selected','Chromosomes',
@@ -641,11 +637,11 @@ def run_mta_analysis(input_file, target_markers):
641
  }).to_csv(os.path.join(results_dir,'qc_summary.csv'), index=False)
642
 
643
  # ── PLOTS ─────────────────────────────────
644
- man_path = os.path.join(plots_dir, 'manhattan_plot.png')
645
- qq_path = os.path.join(plots_dir, 'qq_plot.png')
646
- ld_path = os.path.join(plots_dir, 'ld_decay.png')
647
- vol_path = os.path.join(plots_dir, 'volcano_plot.png')
648
- top_path = os.path.join(plots_dir, 'top_gwas_hits.png')
649
 
650
  plot_manhattan(mnames_qc, chrom_qc, pvals, sig_set, bonf, man_path)
651
  lam = plot_qq(pvals, qq_path)
@@ -653,7 +649,7 @@ def run_mta_analysis(input_file, target_markers):
653
  plot_volcano(mnames_qc, effects, pvals, bonf, vol_path)
654
  plot_top_hits(mnames_qc, chrom_qc, pvals, effects, bonf, top_path)
655
 
656
- # ── ZIP (all results + plots) ──────────────
657
  zip_path = os.path.join(temp_dir, 'GWAS_Analysis_Results.zip')
658
  with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf:
659
  for root, _, files in os.walk(results_dir):
@@ -662,7 +658,7 @@ def run_mta_analysis(input_file, target_markers):
662
  arc = os.path.relpath(fp, temp_dir)
663
  zf.write(fp, arc)
664
 
665
- # ── SUMMARY ───────────────────────────────
666
  lam_txt = ("✅ Well-calibrated (λ ≈ 1)" if lam < 1.05
667
  else "⚠️ Minor inflation — consider PCA correction" if lam < 1.10
668
  else "❌ Significant inflation — use mixed model (GEMMA/EMMAX)")
@@ -672,14 +668,12 @@ def run_mta_analysis(input_file, target_markers):
672
  else "Moderate LD — typical for diverse panels" if gm_r2 < 0.3
673
  else "High LD — consider LD pruning before analysis")
674
 
675
- # Top 8 hits table
676
  top8 = gwas_df.head(8)
677
  top8_rows = "\n".join(
678
  f"| {int(r['Rank'])} | `{r['Marker']}` | Chr {r['Chromosome']} | "
679
  f"{r['Effect_beta']:+.5f} | {r['P_value']:.3e} | {r['neglog10_P']:.3f} |"
680
  for _, r in top8.iterrows())
681
 
682
- # Top chromosomes
683
  chr_df = pd.DataFrame(chr_rows).sort_values('Best_logP', ascending=False)
684
  chr_rows_txt = "\n".join(
685
  f"| Chr {r['Chromosome']} | {int(r['N_Markers'])} | "
@@ -722,11 +716,7 @@ Global mean r² = **{gm_r2:.4f}** — {ld_txt}
722
  - `results/gwas_results.csv` — full GWAS with effects, p-values, ML votes
723
  - `results/chromosome_summary.csv` — per-chromosome statistics
724
  - `results/qc_summary.csv` — QC metrics
725
- - `results/plots/manhattan_plot.png`
726
- - `results/plots/qq_plot.png`
727
- - `results/plots/ld_decay.png`
728
- - `results/plots/volcano_plot.png`
729
- - `results/plots/top_gwas_hits.png`
730
  """
731
  return summary, man_path, qq_path, ld_path, vol_path, top_path, zip_path
732
 
@@ -737,298 +727,315 @@ Global mean r² = **{gm_r2:.4f}** — {ld_txt}
737
 
738
 
739
  # ══════════════════════════════════════════════════════════════
740
- # HTML / CSS — white background, dark-blue text
741
  # ══════════════════════════════════════════════════════════════
742
  THEME_CSS = """
743
  <style>
744
- @import url('https://fonts.googleapis.com/css2?family=DM+Sans:wght@300;400;500;600;700&family=DM+Mono:wght@400;500&display=swap');
745
 
746
  :root {
747
- --navy: #0D2B5E;
748
- --blue: #1A56DB;
749
- --blue2: #2563EB;
750
- --sky: #EBF2FF;
751
- --skymed: #C7D9F8;
752
- --teal: #0D9488;
753
- --red: #E53E3E;
754
- --amber: #D97706;
755
- --white: #FFFFFF;
756
- --offwhite:#F8FAFD;
757
- --border: #D1DEF0;
758
- --muted: #5A7599;
759
- --radius: 14px;
760
- --shadow: 0 2px 16px rgba(13,43,94,0.08);
 
 
 
 
 
 
 
 
761
  }
762
 
763
  body, .gradio-container {
764
  background: var(--white) !important;
765
- color: var(--navy) !important;
766
- font-family: 'DM Sans', sans-serif !important;
767
  }
768
 
769
- /* ── Hero ── */
770
  .hero {
771
- background: linear-gradient(135deg, #0D2B5E 0%, #1A56DB 55%, #2563EB 100%);
772
- border-radius: 20px;
773
- padding: 52px 60px 44px;
774
- margin-bottom: 30px;
 
775
  position: relative;
776
  overflow: hidden;
777
- box-shadow: 0 8px 40px rgba(13,43,94,0.20);
778
  }
779
  .hero::before {
780
- content:'';
781
- position:absolute; top:-100px; right:-80px;
782
- width:350px; height:350px; border-radius:50%;
783
- background:radial-gradient(circle,rgba(255,255,255,0.10) 0%,transparent 70%);
784
  }
785
  .hero::after {
786
- content:'';
787
- position:absolute; bottom:-80px; left:60px;
788
- width:260px; height:260px; border-radius:50%;
789
- background:radial-gradient(circle,rgba(255,255,255,0.07) 0%,transparent 70%);
790
  }
791
  .hero-badge {
792
- display:inline-flex; align-items:center; gap:8px;
793
- background:rgba(255,255,255,0.15);
794
- border:1px solid rgba(255,255,255,0.25);
795
- color:#fff;
796
- font-family:'DM Mono',monospace;
797
- font-size:11px; letter-spacing:2px;
798
- padding:5px 16px; border-radius:30px;
799
- margin-bottom:20px;
800
  }
801
  .hero-badge::before {
802
- content:''; width:7px; height:7px; border-radius:50%;
803
- background:#3fb950; animation:pulse 2s infinite;
804
  }
805
  @keyframes pulse {
806
  0%,100%{opacity:1;transform:scale(1)}
807
- 50%{opacity:0.6;transform:scale(1.3)}
808
  }
809
  .hero-title {
810
- font-family:'DM Sans',sans-serif;
811
- font-weight:700; font-size:42px; color:#fff;
812
- line-height:1.1; margin:0 0 12px;
813
- letter-spacing:-0.8px;
 
814
  }
815
- .hero-title em { color:#93C5FD; font-style:normal; }
816
  .hero-sub {
817
- color:rgba(255,255,255,0.72);
818
- font-family:'DM Mono',monospace;
819
- font-size:13px; margin:0 0 24px;
820
- }
821
- .hero-pills {
822
- display:flex; gap:8px; flex-wrap:wrap;
823
  }
 
824
  .hero-pill {
825
- background:rgba(255,255,255,0.14);
826
- border:1px solid rgba(255,255,255,0.22);
827
- color:#fff; border-radius:20px;
828
- padding:4px 14px; font-size:12px;
 
 
829
  }
830
 
831
- /* ── Section header ── */
832
  .sec-head {
833
- display:flex; align-items:center; gap:12px;
834
- font-family:'DM Mono',monospace;
835
- font-size:10px; letter-spacing:2.5px;
836
- color:var(--blue); text-transform:uppercase;
837
- margin:28px 0 14px;
838
  }
839
  .sec-head::after {
840
- content:''; flex:1; height:1px;
841
- background:linear-gradient(90deg,var(--border),transparent);
842
  }
843
 
844
- /* ── Left panel card ── */
845
  .left-card {
846
- background:var(--offwhite);
847
- border:1px solid var(--border);
848
- border-radius:var(--radius);
849
- padding:24px;
850
  }
851
 
852
  /* ── Format box ── */
853
  .fmt-box {
854
- background:var(--white);
855
- border:1px solid var(--border);
856
- border-left:4px solid var(--blue);
857
- border-radius:10px;
858
- padding:18px 20px;
859
- font-family:'DM Mono',monospace;
860
- font-size:11.5px;
861
- color:var(--muted);
862
- line-height:2.0;
863
- margin-bottom:20px;
 
 
 
 
 
 
 
 
864
  }
865
- .fmt-box .col { color:var(--blue); font-weight:600; }
866
- .fmt-box .val { color:var(--teal); }
867
- .fmt-box .cmt { color:var(--border); }
868
 
869
  /* ── Run button ── */
870
  .run-btn button {
871
- background:linear-gradient(135deg,#1A56DB,#2563EB) !important;
872
- border:none !important;
873
- border-radius:12px !important;
874
- color:#fff !important;
875
- font-family:'DM Sans',sans-serif !important;
876
- font-weight:600 !important;
877
- font-size:16px !important;
878
- padding:15px 0 !important;
879
- width:100% !important;
880
- box-shadow:0 4px 20px rgba(26,86,219,0.35) !important;
881
- transition:all 0.2s !important;
882
- cursor:pointer !important;
 
883
  }
884
  .run-btn button:hover {
885
- transform:translateY(-2px) !important;
886
- box-shadow:0 8px 30px rgba(26,86,219,0.45) !important;
887
  }
888
 
889
  /* ── Pipeline ── */
890
- .pipeline {
891
- display:flex; margin-top:20px;
892
- }
893
  .pipe-step {
894
- flex:1;
895
- background:var(--white);
896
- border:1px solid var(--border);
897
- padding:14px 8px;
898
- text-align:center;
899
- position:relative;
900
  }
901
  .pipe-step:not(:last-child)::after {
902
- content:'›'; position:absolute;
903
- right:-10px; top:50%; transform:translateY(-50%);
904
- color:var(--blue); font-size:18px; font-weight:700;
905
- background:var(--white); padding:0 2px; z-index:1;
906
  }
907
- .pipe-step:first-child { border-radius:10px 0 0 10px; }
908
- .pipe-step:last-child { border-radius:0 10px 10px 0; }
909
  .pipe-num {
910
- font-family:'DM Mono',monospace;
911
- font-size:17px; font-weight:500;
912
- color:var(--blue); display:block;
913
  }
914
  .pipe-name {
915
- font-size:10px; color:var(--muted);
916
- margin-top:3px; display:block;
 
917
  }
918
 
919
  /* ── Summary card ── */
920
  .sum-card {
921
- background:var(--white);
922
- border:1px solid var(--border);
923
- border-radius:var(--radius);
924
- padding:24px 28px;
925
- box-shadow:var(--shadow);
926
  }
927
  .sum-card h2 {
928
- color:var(--blue) !important;
929
- font-family:'DM Sans',sans-serif !important;
930
- font-size:15px !important;
931
- font-weight:600 !important;
932
- margin-top:22px !important;
933
- padding-bottom:6px;
934
- border-bottom:1px solid var(--border);
935
- }
936
- .sum-card table {
937
- width:100%; border-collapse:collapse; margin:10px 0;
938
  }
 
939
  .sum-card th {
940
- background:var(--sky) !important;
941
- color:var(--navy) !important;
942
- font-family:'DM Mono',monospace !important;
943
- font-size:11px !important;
944
- padding:8px 12px !important;
945
- border:1px solid var(--border) !important;
946
- text-align:left;
947
  }
948
  .sum-card td {
949
- color:var(--navy) !important;
950
- font-size:12.5px !important;
951
- padding:7px 12px !important;
952
- border:1px solid var(--border) !important;
953
- font-family:'DM Mono',monospace !important;
954
  }
 
955
  .sum-card td code, .sum-card p code {
956
- background:var(--sky); color:var(--blue);
957
- border-radius:4px; padding:1px 5px;
958
- font-family:'DM Mono',monospace;
959
- font-size:11.5px;
960
  }
961
- .sum-card p { color:var(--navy) !important; font-size:13px !important; }
962
 
963
- /* ── Plot card ── */
964
  .plot-wrap {
965
- background:var(--white);
966
- border:1px solid var(--border);
967
- border-radius:var(--radius);
968
- overflow:hidden;
969
- box-shadow:var(--shadow);
970
- margin-bottom:16px;
971
  }
972
  .plot-label {
973
- padding:12px 18px;
974
- font-family:'DM Mono',monospace;
975
- font-size:10px; letter-spacing:2px;
976
- text-transform:uppercase;
977
- color:var(--muted);
978
- border-bottom:1px solid var(--border);
979
- background:var(--offwhite);
980
  }
981
 
982
  /* ── Download box ── */
983
  .dl-box {
984
- background:var(--sky);
985
- border:1px solid var(--skymed);
986
- border-radius:var(--radius);
987
- padding:20px 24px;
988
  }
989
  .dl-box-title {
990
- font-family:'DM Mono',monospace;
991
- font-size:10px; letter-spacing:2px;
992
- color:var(--blue); text-transform:uppercase;
993
- margin-bottom:10px;
994
  }
995
  .dl-box-list {
996
- font-family:'DM Mono',monospace;
997
- font-size:12px; color:var(--navy);
998
- line-height:2.0;
999
  }
1000
- .dl-box-list span { color:var(--blue); font-weight:500; }
1001
 
1002
- /* ── Gradio overrides ── */
1003
  .gradio-container .block,
1004
  .gradio-container .wrap,
1005
  .gradio-container .gap {
1006
- background:transparent !important;
1007
- border:none !important;
1008
- box-shadow:none !important;
1009
  }
1010
  .gradio-container label {
1011
- color:var(--navy) !important;
1012
- font-family:'DM Sans',sans-serif !important;
1013
- font-weight:500 !important;
 
1014
  }
1015
  .gradio-container input,
1016
  .gradio-container textarea {
1017
- background:var(--white) !important;
1018
- border:1px solid var(--border) !important;
1019
- color:var(--navy) !important;
1020
- border-radius:8px !important;
1021
- font-family:'DM Sans',sans-serif !important;
1022
  }
1023
- .gradio-container input[type=range] {
1024
- accent-color:var(--blue) !important;
 
 
1025
  }
 
1026
  .gradio-container .output-markdown {
1027
- background:transparent !important;
1028
- color:var(--navy) !important;
1029
  }
1030
  footer, .gradio-container .built-with,
1031
- .gradio-container .svelte-1ipelgc { display:none !important; }
1032
  </style>
1033
  """
1034
 
@@ -1036,14 +1043,14 @@ HERO_HTML = """
1036
  <div class="hero">
1037
  <div class="hero-badge">GWAS · QQ · LD DECAY · ML SELECTION</div>
1038
  <h1 class="hero-title">Multi-Trait <em>Association</em><br>Analysis Platform</h1>
1039
- <p class="hero-sub">Genome-Wide Association · Quality Control · LD Analysis · Marker Discovery</p>
1040
  <div class="hero-pills">
1041
- <span class="hero-pill">Manhattan Plot</span>
1042
- <span class="hero-pill">QQ Plot + λ</span>
1043
- <span class="hero-pill">LD Decay</span>
1044
- <span class="hero-pill">Volcano Plot</span>
1045
- <span class="hero-pill">Top Hits</span>
1046
- <span class="hero-pill">ZIP Export</span>
1047
  </div>
1048
  </div>
1049
  """
@@ -1052,35 +1059,38 @@ FMT_HTML = """
1052
  <div class="sec-head">Input Format</div>
1053
  <div class="fmt-box">
1054
  <span class="col">Col 1</span> Sample ID &nbsp;
1055
- <span class="col">Col 2</span> Chromosome &nbsp;
1056
- <span class="col">Col 3</span> Phenotype &nbsp;
1057
- <span class="col">Col 4+</span> Markers<br><br>
1058
- <span class="col">ID</span>, <span class="col">Chr</span>, <span class="col">Pheno</span>,
1059
- <span class="val">M0001</span>, <span class="val">M0002</span>, ...<br>
1060
- <span class="cmt">- , - , - ,</span>
1061
- <span class="val">1</span> ,
1062
- <span class="val">1</span> , ...
1063
- <span class="cmt"> ← marker chr row</span><br>
1064
- S1 , 1 , <span class="val">45.2</span> ,
1065
- <span class="val">0</span> ,
1066
- <span class="val">1</span> , ...
 
 
 
1067
  </div>
1068
  """
1069
 
1070
  PIPE_HTML = """
1071
- <div class="sec-head" style="margin-top:24px">Pipeline</div>
1072
  <div class="pipeline">
1073
- <div class="pipe-step"><span class="pipe-num">01</span><span class="pipe-name">QC</span></div>
1074
  <div class="pipe-step"><span class="pipe-num">02</span><span class="pipe-name">GWAS</span></div>
1075
  <div class="pipe-step"><span class="pipe-num">03</span><span class="pipe-name">QQ / LD</span></div>
1076
- <div class="pipe-step"><span class="pipe-num">04</span><span class="pipe-name">Volcano</span></div>
1077
  <div class="pipe-step"><span class="pipe-num">05</span><span class="pipe-name">Export</span></div>
1078
  </div>
1079
  """
1080
 
1081
  DL_HTML = """
1082
  <div class="dl-box">
1083
- <div class="dl-box-title">ZIP Contents</div>
1084
  <div class="dl-box-list">
1085
  <span>📊</span> gwas_results.csv — full marker statistics<br>
1086
  <span>🗺️</span> chromosome_summary.csv<br>
@@ -1094,66 +1104,63 @@ DL_HTML = """
1094
  </div>
1095
  """
1096
 
 
1097
  # ══════════════════════════════════════════════════════════════
1098
  # GRADIO APP
1099
  # ══════════════════════════════════════════════════════════════
1100
- with gr.Blocks(css=THEME_CSS, title="MTA Analysis") as app:
1101
 
1102
  gr.HTML(HERO_HTML)
1103
 
1104
  with gr.Row():
1105
- # ── LEFT ──
1106
- with gr.Column(scale=1, min_width=300):
1107
  gr.HTML(FMT_HTML)
1108
  gr.HTML('<div class="sec-head">Configure</div>')
1109
 
1110
- input_file = gr.File(label="Upload CSV File", file_types=[".csv"])
1111
  target_markers = gr.Slider(
1112
  100, 5000, value=3000, step=100,
1113
  label="Target Markers for ML Selection",
1114
- info="Used for feature voting; does not affect GWAS p-values")
1115
 
1116
  with gr.Row(elem_classes=["run-btn"]):
1117
- run_btn = gr.Button("⚡ Run GWAS Analysis", variant="primary", size="lg")
1118
 
1119
  gr.HTML(PIPE_HTML)
1120
 
1121
- # ── RIGHT ──
1122
  with gr.Column(scale=2):
1123
  gr.HTML('<div class="sec-head">Results Summary</div>')
1124
  with gr.Column(elem_classes=["sum-card"]):
1125
- summary_out = gr.Markdown(value="*Upload a CSV and click Run to begin.*")
1126
 
1127
- # ── PLOTS ──
1128
  gr.HTML('<div class="sec-head" style="margin-top:10px">Visualizations</div>')
1129
 
1130
  with gr.Column(elem_classes=["plot-wrap"]):
1131
- gr.HTML('<div class="plot-label">Manhattan Plot — Genome-Wide Significance</div>')
1132
  manhattan_out = gr.Image(show_label=False)
1133
 
1134
  with gr.Row():
1135
  with gr.Column(elem_classes=["plot-wrap"]):
1136
- gr.HTML('<div class="plot-label">QQ Plot — Genomic Inflation Factor</div>')
1137
  qq_out = gr.Image(show_label=False)
1138
  with gr.Column(elem_classes=["plot-wrap"]):
1139
- gr.HTML('<div class="plot-label">LD Decay — Linkage Disequilibrium</div>')
1140
  ld_out = gr.Image(show_label=False)
1141
 
1142
  with gr.Row():
1143
  with gr.Column(elem_classes=["plot-wrap"]):
1144
- gr.HTML('<div class="plot-label">Volcano Plot — Effect vs Significance</div>')
1145
  vol_out = gr.Image(show_label=False)
1146
  with gr.Column(elem_classes=["plot-wrap"]):
1147
- gr.HTML('<div class="plot-label">Top GWAS Hits — Ranked by −log₁₀(P)</div>')
1148
  top_out = gr.Image(show_label=False)
1149
 
1150
- # ── DOWNLOAD ──
1151
- gr.HTML('<div class="sec-head" style="margin-top:10px">Export</div>')
1152
  with gr.Row():
1153
  with gr.Column(scale=1):
1154
  gr.HTML(DL_HTML)
1155
  with gr.Column(scale=1):
1156
- download_out = gr.File(label="⬇ Download All Results (ZIP)")
1157
  with gr.Column(scale=1):
1158
  pass
1159
 
 
1
  # -*- coding: utf-8 -*-
2
  """
3
+ MTA Analysis Tool v6.0
4
+ Soft Pastel Theme · Corrected CSV Format Parser
5
+ CSV Format:
6
+ Row 1 (header): ID, Phenotype, marker1, marker2, ...
7
+ Row 2 (chr row): -, -, chr_number, chr_number, ...
8
+ Row 3+: sample_id, phenotype_value, genotype, genotype, ...
9
  """
10
 
11
  import gradio as gr
 
22
  warnings.filterwarnings('ignore')
23
 
24
  # ══════════════════════════════════════════════════════════════
25
+ # SOFT PASTEL PLOT THEME
26
  # ══════════════════════════════════════════════════════════════
27
+ BG = "#FDFBFF"
28
+ PANEL = "#F6F0FB"
29
+ GRID_C = "#E8DFF5"
30
+ TEXT_C = "#3D2B6B"
31
+ MUTED_C = "#9B8AB8"
32
+ ACCENT = "#8B5CF6"
33
+ RED_C = "#F472B6"
34
+ GOLD_C = "#FBBF24"
35
+ GREEN_C = "#34D399"
36
+ TEAL_C = "#22D3EE"
37
 
38
  CHROM_PALETTE = [
39
+ "#A78BFA","#F9A8D4","#6EE7B7","#7DD3FC","#FCD34D",
40
+ "#C4B5FD","#FBCFE8","#86EFAC","#BAE6FD","#FDE68A",
41
+ "#DDD6FE","#FDE8F4","#A7F3D0","#E0F2FE","#FEF3C7",
42
+ "#8B5CF6","#EC4899","#10B981","#0EA5E9","#F59E0B",
43
+ "#7C3AED","#DB2777",
44
  ]
45
 
46
+ def set_pastel_style():
47
  plt.rcParams.update({
48
  'figure.facecolor' : BG,
49
  'axes.facecolor' : PANEL,
 
68
  # PLOT 1 — MANHATTAN
69
  # ══════════════════════════════════════════════════════════════
70
  def plot_manhattan(marker_names, chromosomes, p_values, sig_set, bonf_thresh, save_path):
71
+ set_pastel_style()
 
72
  unique_chroms = sorted(set(chromosomes),
73
+ key=lambda x: (int(x) if str(x).isdigit() else 999, str(x)))
74
  log_p = -np.log10(np.array(p_values) + 1e-300)
75
 
76
  GAP = max(8, len(marker_names) // 150)
 
91
  fig = plt.figure(figsize=(22, 7), facecolor=BG)
92
  ax = fig.add_subplot(111, facecolor=PANEL)
93
 
 
94
  for ci, ch in enumerate(unique_chroms):
95
  idxs = chrom_to_idx.get(ch, [])
96
  if not idxs: continue
97
  x0 = x_pos[idxs[0]] - 0.5
98
  x1 = x_pos[idxs[-1]] + 0.5
99
  if ci % 2 == 0:
100
+ ax.axvspan(x0, x1, color='#EDE9FE', alpha=0.45, zorder=0)
101
 
102
  for ci, ch in enumerate(unique_chroms):
103
  idxs = chrom_to_idx.get(ch, [])
104
  if not idxs: continue
105
  col = CHROM_PALETTE[ci % len(CHROM_PALETTE)]
 
106
  normal = [i for i in idxs if i not in sig_set]
107
  sel = [i for i in idxs if i in sig_set]
 
108
  if normal:
109
  ax.scatter(x_pos[normal], log_p[normal],
110
+ c=col, s=12, alpha=0.65, linewidths=0, zorder=2)
111
  if sel:
 
112
  ax.scatter(x_pos[sel], log_p[sel],
113
+ c=RED_C, s=260, alpha=0.18, linewidths=0, zorder=3)
114
  ax.scatter(x_pos[sel], log_p[sel],
115
  c=RED_C, s=70, alpha=1.0,
116
+ edgecolors='white', linewidths=1.2,
117
  marker='D', zorder=4)
118
 
 
119
  ax.axhline(bonf_thresh, color=RED_C, ls='--', lw=1.8, alpha=0.85, zorder=5)
120
  ax.text(offset * 0.005, bonf_thresh + log_p.max()*0.02,
121
+ f'Bonferroni α=0.05', color=RED_C, fontsize=9, fontweight='bold', va='bottom')
 
122
 
123
  sugg = -np.log10(1e-5)
124
  if sugg < bonf_thresh:
125
  ax.axhline(sugg, color=GOLD_C, ls=':', lw=1.5, alpha=0.8, zorder=5)
126
  ax.text(offset * 0.005, sugg + log_p.max()*0.02,
127
+ 'Suggestive 1×10⁻⁵', color=GOLD_C, fontsize=9, fontweight='bold', va='bottom')
 
128
 
129
  xtick_pos = [chrom_centers[c] for c in unique_chroms if c in chrom_centers]
130
  xtick_lab = [f'Chr {c}' for c in unique_chroms if c in chrom_centers]
 
135
  ha='center', color=TEXT_C, fontweight='600')
136
  ax.set_xlim(-GAP, offset)
137
  ax.set_ylim(bottom=0, top=log_p.max() * 1.16)
138
+ ax.set_ylabel('−log₁₀(P-value)', fontsize=13, color=TEXT_C, fontweight='bold', labelpad=10)
139
+ ax.set_xlabel('Chromosome', fontsize=13, color=TEXT_C, fontweight='bold', labelpad=10)
 
 
 
140
  ax.set_title('Genome-Wide Association Study · Manhattan Plot',
141
  fontsize=17, color=TEXT_C, fontweight='bold', pad=20)
 
142
  ax.yaxis.grid(True, color=GRID_C, linewidth=0.8, alpha=1.0)
143
  ax.set_axisbelow(True)
144
  ax.tick_params(axis='both', colors=TEXT_C, length=4)
 
149
  ax.legend(handles=[h_sig, h_bonf, h_sugg], fontsize=10,
150
  loc='upper right', facecolor=BG, edgecolor=GRID_C)
151
 
 
152
  for ch in unique_chroms:
153
  idxs = chrom_to_idx.get(ch, [])
154
  if not idxs: continue
 
169
  # PLOT 2 — QQ PLOT
170
  # ══════════════════════════════════════════════════════════════
171
  def plot_qq(p_values, save_path):
172
+ set_pastel_style()
 
173
  pv = np.clip(np.array(p_values)[~np.isnan(p_values)], 1e-300, 1.0)
174
  n = len(pv)
175
  obs = np.sort(pv)
 
188
  ax.set_facecolor(PANEL)
189
 
190
  ax.fill_between(log_exp, ci_lo, ci_up,
191
+ color=ACCENT, alpha=0.15, label='95% Confidence Band')
192
 
193
+ sc = ax.scatter(log_exp, log_obs, c=log_obs, cmap='RdPu',
194
  s=14, alpha=0.80, linewidths=0, zorder=3)
195
  plt.colorbar(sc, ax=ax, shrink=0.75, label='−log₁₀(P)')
196
 
 
201
  lam_col = GREEN_C if lam < 1.05 else (GOLD_C if lam < 1.10 else RED_C)
202
  lam_lbl = ("Well-calibrated" if lam < 1.05
203
  else "Minor inflation" if lam < 1.10 else "Significant inflation")
204
+ ax.text(0.05, 0.95, f'λ = {lam:.4f}\n{lam_lbl}',
 
205
  transform=ax.transAxes, fontsize=11, va='top', color=lam_col,
206
  fontweight='bold',
207
  bbox=dict(boxstyle='round,pad=0.5', fc=BG, ec=lam_col, lw=1.5, alpha=0.9))
 
226
  # PLOT 3 — LD DECAY
227
  # ══════════════════════════════════════════════════════════════
228
  def plot_ld_decay(genotypes, chromosomes, save_path, max_m=250):
229
+ set_pastel_style()
 
230
  unique_chroms = sorted(set(chromosomes),
231
+ key=lambda x: (int(x) if str(x).isdigit() else 999, str(x)))
232
  all_d, all_r2, chrom_mean = [], [], {}
233
 
234
  for ch in unique_chroms:
 
252
 
253
  fig, axes = plt.subplots(1, 2, figsize=(16, 6), facecolor=BG)
254
 
 
255
  ax = axes[0]; ax.set_facecolor(PANEL)
256
  if all_d:
257
  all_d = np.array(all_d)
 
270
  v = ~np.isnan(mu)
271
 
272
  ax.fill_between(bins[v],
273
+ np.clip(mu[v]-se[v], 0, 1), np.clip(mu[v]+se[v], 0, 1),
274
+ color=ACCENT, alpha=0.18, label='±1 SE')
 
275
 
 
276
  pts = np.array([bins[v], mu[v]]).T.reshape(-1, 1, 2)
277
  segs = np.concatenate([pts[:-1], pts[1:]], axis=1)
278
+ lc = LineCollection(segs, cmap='PuRd', linewidth=2.8, zorder=4)
279
  lc.set_array(mu[v])
280
  ax.add_collection(lc)
281
+ ax.scatter(bins[v], mu[v], c=mu[v], cmap='PuRd',
282
+ s=22, zorder=5, linewidths=0.5, edgecolors=MUTED_C)
 
283
 
284
  ax.axhline(0.2, color=RED_C, ls='--', lw=1.3, alpha=0.8, label='r²=0.2 threshold')
285
 
 
292
 
293
  ax.set_xlabel('Marker Distance (index)', fontsize=12, color=TEXT_C, fontweight='bold')
294
  ax.set_ylabel('Mean r²', fontsize=12, color=TEXT_C, fontweight='bold')
295
+ ax.set_title('LD Decay Across Chromosomes', fontsize=14, color=TEXT_C, fontweight='bold', pad=12)
 
296
  ax.set_ylim(0, 1); ax.tick_params(colors=TEXT_C)
297
  ax.yaxis.grid(True, color=GRID_C, lw=0.8)
298
  ax.legend(fontsize=9, facecolor=BG, edgecolor=GRID_C)
299
 
 
300
  ax2 = axes[1]; ax2.set_facecolor(PANEL)
301
  if chrom_mean:
302
+ cs = sorted(chrom_mean.keys(), key=lambda x: (int(x) if str(x).isdigit() else 999, str(x)))
303
  vals = [chrom_mean[c] for c in cs]
304
  cols = [CHROM_PALETTE[i % len(CHROM_PALETTE)] for i in range(len(cs))]
305
  bars = ax2.bar(range(len(cs)), vals, color=cols,
 
309
  rotation=45 if len(cs) > 10 else 0,
310
  fontsize=8.5, ha='right', color=TEXT_C)
311
  for bar, val in zip(bars, vals):
312
+ ax2.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 0.02,
313
+ f'{val:.2f}', ha='center', va='bottom', fontsize=8, color=TEXT_C, fontweight='600')
 
 
314
  ax2.set_xlabel('Chromosome', fontsize=12, color=TEXT_C, fontweight='bold')
315
  ax2.set_ylabel('Mean r²', fontsize=12, color=TEXT_C, fontweight='bold')
316
+ ax2.set_title('Mean LD per Chromosome', fontsize=14, color=TEXT_C, fontweight='bold', pad=12)
317
+ ax2.set_ylim(0, 1.15); ax2.tick_params(colors=TEXT_C)
 
 
318
  ax2.yaxis.grid(True, color=GRID_C, lw=0.8)
319
 
320
  fig.suptitle('Linkage Disequilibrium (LD) Analysis',
 
329
  # PLOT 4 — GWAS EFFECT SIZE VOLCANO
330
  # ══════════════════════════════════════════════════════════════
331
  def plot_volcano(marker_names, effects, p_values, bonf_thresh, save_path, top_n=10):
332
+ set_pastel_style()
333
+ log_p = -np.log10(np.array(p_values) + 1e-300)
 
334
  sig_mask = log_p >= bonf_thresh
335
  sug_mask = (log_p >= -np.log10(1e-5)) & ~sig_mask
336
 
337
  fig, ax = plt.subplots(figsize=(10, 7), facecolor=BG)
338
  ax.set_facecolor(PANEL)
339
 
 
340
  ns = ~sig_mask & ~sug_mask
341
  ax.scatter(np.array(effects)[ns], log_p[ns],
342
  c=MUTED_C, s=10, alpha=0.35, linewidths=0, zorder=1, label='Non-significant')
 
343
  if sug_mask.any():
344
  ax.scatter(np.array(effects)[sug_mask], log_p[sug_mask],
345
  c=GOLD_C, s=20, alpha=0.65, linewidths=0, zorder=2, label='Suggestive')
 
346
  if sig_mask.any():
347
  ax.scatter(np.array(effects)[sig_mask], log_p[sig_mask],
348
  c=RED_C, s=55, alpha=0.90,
349
+ edgecolors='white', linewidths=0.7, zorder=3, label='Significant')
 
350
 
351
  ax.axhline(bonf_thresh, color=RED_C, ls='--', lw=1.6, alpha=0.8)
352
  ax.axhline(-np.log10(1e-5), color=GOLD_C, ls=':', lw=1.3, alpha=0.8)
353
  ax.axvline(0, color=MUTED_C, lw=0.8, ls='-', alpha=0.4)
354
 
 
355
  top_idx = np.argsort(log_p)[-top_n:]
356
  for i in top_idx:
357
  if log_p[i] >= bonf_thresh:
 
376
 
377
 
378
  # ══════════════════════════════════════════════════════════════
379
+ # PLOT 5 — TOP GWAS HITS
380
  # ═══════════��══════════════════════════════════════════════════
381
  def plot_top_hits(marker_names, chromosomes, p_values, effects, bonf_thresh,
382
  save_path, top_n=25):
383
+ set_pastel_style()
 
384
  log_p = -np.log10(np.array(p_values) + 1e-300)
385
  order = np.argsort(log_p)[-top_n:][::-1]
386
 
387
  unique_chroms = sorted(set(chromosomes),
388
+ key=lambda x: (int(x) if str(x).isdigit() else 999, str(x)))
389
+ col_map = {c: CHROM_PALETTE[i % len(CHROM_PALETTE)] for i,c in enumerate(unique_chroms)}
 
390
 
391
  fig, axes = plt.subplots(1, 2, figsize=(16, 8), facecolor=BG)
392
 
 
393
  ax = axes[0]; ax.set_facecolor(PANEL)
394
  labels = [f"{marker_names[i]} (Chr {chromosomes[i]})" for i in order]
395
  vals = [log_p[i] for i in order]
396
  cols = [col_map.get(chromosomes[i], ACCENT) for i in order]
397
+ bars = ax.barh(range(len(order)), vals, color=cols,
398
+ edgecolor='white', linewidth=0.6, alpha=0.88, height=0.65)
 
399
  ax.axvline(bonf_thresh, color=RED_C, ls='--', lw=1.5, alpha=0.9, label='Bonferroni')
400
  ax.set_yticks(range(len(order)))
401
  ax.set_yticklabels(labels, fontsize=8.5, color=TEXT_C)
402
  ax.invert_yaxis()
403
  ax.set_xlabel('−log₁₀(P-value)', fontsize=12, color=TEXT_C, fontweight='bold')
404
+ ax.set_title(f'Top {top_n} GWAS Hits', fontsize=14, color=TEXT_C, fontweight='bold', pad=12)
405
+ ax.xaxis.grid(True, color=GRID_C, lw=0.8); ax.tick_params(colors=TEXT_C)
 
 
 
406
  for bar, val in zip(bars, vals):
407
  ax.text(bar.get_width() + 0.05, bar.get_y() + bar.get_height()/2,
408
  f'{val:.2f}', va='center', fontsize=8, color=TEXT_C)
409
 
 
410
  ax2 = axes[1]; ax2.set_facecolor(PANEL)
411
  eff_vals = [effects[i] for i in order]
412
  eff_cols = [ACCENT if e >= 0 else RED_C for e in eff_vals]
 
417
  ax2.set_yticklabels(labels, fontsize=8.5, color=TEXT_C)
418
  ax2.invert_yaxis()
419
  ax2.set_xlabel('Effect Size (β)', fontsize=12, color=TEXT_C, fontweight='bold')
420
+ ax2.set_title('Effect Directions of Top Hits', fontsize=14, color=TEXT_C, fontweight='bold', pad=12)
421
+ ax2.xaxis.grid(True, color=GRID_C, lw=0.8); ax2.tick_params(colors=TEXT_C)
 
 
422
 
 
423
  handles = []
424
  shown = set()
425
  for i in order:
 
437
 
438
 
439
  # ══════════════════════════════════════════════════════════════
440
+ # CSV FORMAT PARSER
441
+ # Format:
442
+ # Row 1 (header): ID, Phenotype, marker1, marker2, ...
443
+ # Row 2 (chr row): anything, anything, chr_num, chr_num, ...
444
+ # Row 3+: sample_id, pheno_value, geno, geno, ...
445
+ # ══════════════════════════════════════════════════════════════
446
+ def parse_input_csv(filepath):
447
+ """
448
+ Parses the custom MTA CSV format:
449
+ - Header row: ID, Phenotype, markerName1, markerName2, ...
450
+ - Row 1 (first data row): chromosome assignments for each marker column
451
+ - Rows 2+: actual sample data
452
+ """
453
+ df = pd.read_csv(filepath, header=0, dtype=str)
454
+
455
+ # Identify marker columns (everything after col 0=ID, col 1=Phenotype)
456
+ marker_cols = df.columns[2:].tolist()
457
+
458
+ # First row = chromosome assignments for markers
459
+ chr_row = df.iloc[0]
460
+ chromosome_dict = {}
461
+ for m in marker_cols:
462
+ val = str(chr_row[m]).strip()
463
+ # Clean up: remove decimals (e.g. "45.0" → "45")
464
+ if val.endswith('.0'):
465
+ val = val[:-2]
466
+ chromosome_dict[m] = val
467
+
468
+ # Remaining rows = actual sample data
469
+ df_samples = df.iloc[1:].reset_index(drop=True)
470
+
471
+ sample_ids = df_samples.iloc[:, 0].astype(str).values
472
+ phenotypes = pd.to_numeric(df_samples.iloc[:, 1], errors='coerce').values
473
+
474
+ # Genotype matrix — replace -1 with NaN (missing data code)
475
+ geno_raw = df_samples[marker_cols].apply(pd.to_numeric, errors='coerce')
476
+ geno_raw = geno_raw.replace(-1, np.nan)
477
+ genotypes = geno_raw.values
478
+
479
+ return sample_ids, phenotypes, genotypes, marker_cols, chromosome_dict
480
+
481
+
482
+ # ══════════════════════════════════════════════════════════════
483
+ # MAIN ANALYSIS
484
  # ══════════════════════════════════════════════════════════════
485
  def run_mta_analysis(input_file, target_markers):
486
  try:
 
493
  for d in [results_dir, plots_dir]:
494
  os.makedirs(d, exist_ok=True)
495
 
496
+ # ── LOAD & PARSE ──────────────────────────
497
+ sample_ids, phenotypes, genotypes, marker_names, chromosome_dict = \
498
+ parse_input_csv(input_file)
 
 
 
 
 
499
 
500
+ chrom_info_row = [chromosome_dict[m] for m in marker_names]
501
+ unique_chroms = sorted(set(chrom_info_row),
502
+ key=lambda x: (int(x) if str(x).isdigit() else 999, str(x)))
 
 
503
 
 
 
504
  n_samples = len(sample_ids)
505
  n_markers = len(marker_names)
506
 
507
  # ── QC ────────────────────────────────────
508
+ miss_m = np.isnan(genotypes).sum(axis=0) / max(n_samples, 1)
509
+ miss_s = np.isnan(genotypes).sum(axis=1) / max(n_markers, 1)
510
  maf = np.array([
511
  min(np.nanmean(genotypes[:,i])/2, 1-np.nanmean(genotypes[:,i])/2)
512
  if not np.all(np.isnan(genotypes[:,i])) else 0
 
515
  qc_m = (miss_m < 0.1) & (maf > 0.01)
516
  qc_s = miss_s < 0.1
517
 
518
+ geno_qc = genotypes[np.ix_(qc_s, qc_m)].copy()
519
  pheno_qc = phenotypes[qc_s]
520
  ids_qc = sample_ids[qc_s]
521
  mnames_qc = [marker_names[i] for i in range(n_markers) if qc_m[i]]
 
524
  n_rm_m = n_markers - len(mnames_qc)
525
  n_rm_s = n_samples - len(ids_qc)
526
 
527
+ # Impute missing
528
  for i in range(geno_qc.shape[1]):
529
  col = geno_qc[:, i]
530
  mask = np.isnan(col)
531
  if mask.any():
532
+ geno_qc[mask, i] = np.nanmean(col) if not np.all(mask) else 0
533
+
534
+ # Remove samples with NaN phenotype
535
+ valid_pheno = ~np.isnan(pheno_qc)
536
+ geno_qc = geno_qc[valid_pheno]
537
+ pheno_qc = pheno_qc[valid_pheno]
538
+ ids_qc = ids_qc[valid_pheno]
539
 
540
  TARGET = min(int(target_markers), len(mnames_qc))
541
 
 
557
  except:
558
  pass
559
 
560
+ bonf = -np.log10(0.05 / len(mnames_qc))
561
+ n_sig = int((pvals < 0.05/len(mnames_qc)).sum())
562
+ n_sugg = int((pvals < 1e-5).sum())
563
+ sig_set = set(np.where(pvals < 0.05/len(mnames_qc))[0])
564
 
565
+ # ── ML marker selection ────────────────────
566
  from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor
567
  from sklearn.linear_model import ElasticNetCV
568
  from sklearn.feature_selection import mutual_info_regression, f_regression
 
576
  random_state=42, n_jobs=-1)
577
  rf_fs.fit(X, y)
578
 
579
+ gb_fs = GradientBoostingRegressor(n_estimators=100, max_depth=5, random_state=42)
 
580
  gb_fs.fit(X, y)
581
 
582
  en_fs = ElasticNetCV(cv=5, random_state=42, max_iter=5000)
583
  en_fs.fit(X, y)
584
 
585
+ mi = mutual_info_regression(X, y, random_state=42)
586
+ fsc, _ = f_regression(X, y)
587
 
588
  votes = np.zeros(len(mnames_qc))
589
  for arr in [rf_fs.feature_importances_, gb_fs.feature_importances_,
 
591
  top = np.argsort(arr)[-TARGET:]
592
  votes[top] += 1
593
 
 
 
594
  # ── SAVE CSVs ─────────────────────────────
595
  gwas_df = pd.DataFrame({
596
  'Rank' : 0,
 
609
  gwas_df['Rank'] = range(1, len(gwas_df)+1)
610
  gwas_df.to_csv(os.path.join(results_dir, 'gwas_results.csv'), index=False)
611
 
 
612
  chr_rows = []
613
  for ch in unique_chroms:
614
  ci = [i for i,c in enumerate(chrom_qc) if c == ch]
 
627
  pd.DataFrame(chr_rows).to_csv(
628
  os.path.join(results_dir, 'chromosome_summary.csv'), index=False)
629
 
 
630
  pd.DataFrame({
631
  'Metric': ['Samples_raw','Samples_QC','Markers_raw','Markers_QC',
632
  'Target_Selected','Chromosomes',
 
637
  }).to_csv(os.path.join(results_dir,'qc_summary.csv'), index=False)
638
 
639
  # ── PLOTS ─────────────────────────────────
640
+ man_path = os.path.join(plots_dir, 'manhattan_plot.png')
641
+ qq_path = os.path.join(plots_dir, 'qq_plot.png')
642
+ ld_path = os.path.join(plots_dir, 'ld_decay.png')
643
+ vol_path = os.path.join(plots_dir, 'volcano_plot.png')
644
+ top_path = os.path.join(plots_dir, 'top_gwas_hits.png')
645
 
646
  plot_manhattan(mnames_qc, chrom_qc, pvals, sig_set, bonf, man_path)
647
  lam = plot_qq(pvals, qq_path)
 
649
  plot_volcano(mnames_qc, effects, pvals, bonf, vol_path)
650
  plot_top_hits(mnames_qc, chrom_qc, pvals, effects, bonf, top_path)
651
 
652
+ # ── ZIP ───────────────────────────────────
653
  zip_path = os.path.join(temp_dir, 'GWAS_Analysis_Results.zip')
654
  with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf:
655
  for root, _, files in os.walk(results_dir):
 
658
  arc = os.path.relpath(fp, temp_dir)
659
  zf.write(fp, arc)
660
 
661
+ # ── SUMMARY TEXT ──────────────────────────
662
  lam_txt = ("✅ Well-calibrated (λ ≈ 1)" if lam < 1.05
663
  else "⚠️ Minor inflation — consider PCA correction" if lam < 1.10
664
  else "❌ Significant inflation — use mixed model (GEMMA/EMMAX)")
 
668
  else "Moderate LD — typical for diverse panels" if gm_r2 < 0.3
669
  else "High LD — consider LD pruning before analysis")
670
 
 
671
  top8 = gwas_df.head(8)
672
  top8_rows = "\n".join(
673
  f"| {int(r['Rank'])} | `{r['Marker']}` | Chr {r['Chromosome']} | "
674
  f"{r['Effect_beta']:+.5f} | {r['P_value']:.3e} | {r['neglog10_P']:.3f} |"
675
  for _, r in top8.iterrows())
676
 
 
677
  chr_df = pd.DataFrame(chr_rows).sort_values('Best_logP', ascending=False)
678
  chr_rows_txt = "\n".join(
679
  f"| Chr {r['Chromosome']} | {int(r['N_Markers'])} | "
 
716
  - `results/gwas_results.csv` — full GWAS with effects, p-values, ML votes
717
  - `results/chromosome_summary.csv` — per-chromosome statistics
718
  - `results/qc_summary.csv` — QC metrics
719
+ - `results/plots/` — all 5 plots
 
 
 
 
720
  """
721
  return summary, man_path, qq_path, ld_path, vol_path, top_path, zip_path
722
 
 
727
 
728
 
729
  # ══════════════════════════════════════════════════════════════
730
+ # SOFT PASTEL THEME CSS
731
  # ══════════════════════════════════════════════════════════════
732
  THEME_CSS = """
733
  <style>
734
+ @import url('https://fonts.googleapis.com/css2?family=Nunito:wght@300;400;500;600;700;800&family=Nunito+Sans:wght@300;400;500;600&family=Space+Mono:wght@400;700&display=swap');
735
 
736
  :root {
737
+ --lavender: #EDE9FE;
738
+ --lavender2: #DDD6FE;
739
+ --purple: #8B5CF6;
740
+ --purple-d: #6D28D9;
741
+ --rose: #FCE7F3;
742
+ --rose2: #FBCFE8;
743
+ --pink: #EC4899;
744
+ --mint: #D1FAE5;
745
+ --mint2: #A7F3D0;
746
+ --teal: #0D9488;
747
+ --sky: #DBEAFE;
748
+ --sky2: #BFDBFE;
749
+ --blue: #3B82F6;
750
+ --peach: #FEF3C7;
751
+ --amber: #F59E0B;
752
+ --white: #FDFBFF;
753
+ --offwhite: #F6F0FB;
754
+ --text: #3D2B6B;
755
+ --muted: #9B8AB8;
756
+ --border: #E8DFF5;
757
+ --shadow: 0 4px 24px rgba(139,92,246,0.10);
758
+ --radius: 16px;
759
  }
760
 
761
  body, .gradio-container {
762
  background: var(--white) !important;
763
+ color: var(--text) !important;
764
+ font-family: 'Nunito Sans', sans-serif !important;
765
  }
766
 
767
+ /* ── HERO ── */
768
  .hero {
769
+ background: linear-gradient(135deg, #F3E8FF 0%, #FCE7F3 35%, #DBEAFE 70%, #D1FAE5 100%);
770
+ border: 1.5px solid var(--lavender2);
771
+ border-radius: 24px;
772
+ padding: 50px 60px 42px;
773
+ margin-bottom: 28px;
774
  position: relative;
775
  overflow: hidden;
776
+ box-shadow: 0 8px 40px rgba(139,92,246,0.12);
777
  }
778
  .hero::before {
779
+ content: '';
780
+ position: absolute; top: -60px; right: -60px;
781
+ width: 280px; height: 280px; border-radius: 50%;
782
+ background: radial-gradient(circle, rgba(236,72,153,0.12) 0%, transparent 70%);
783
  }
784
  .hero::after {
785
+ content: '';
786
+ position: absolute; bottom: -40px; left: 80px;
787
+ width: 200px; height: 200px; border-radius: 50%;
788
+ background: radial-gradient(circle, rgba(59,130,246,0.10) 0%, transparent 70%);
789
  }
790
  .hero-badge {
791
+ display: inline-flex; align-items: center; gap: 8px;
792
+ background: rgba(139,92,246,0.12);
793
+ border: 1px solid rgba(139,92,246,0.25);
794
+ color: var(--purple-d);
795
+ font-family: 'Space Mono', monospace;
796
+ font-size: 10px; letter-spacing: 2px;
797
+ padding: 5px 16px; border-radius: 30px;
798
+ margin-bottom: 18px;
799
  }
800
  .hero-badge::before {
801
+ content: ''; width: 7px; height: 7px; border-radius: 50%;
802
+ background: #10B981; animation: pulse 2s infinite;
803
  }
804
  @keyframes pulse {
805
  0%,100%{opacity:1;transform:scale(1)}
806
+ 50%{opacity:0.5;transform:scale(1.4)}
807
  }
808
  .hero-title {
809
+ font-family: 'Nunito', sans-serif;
810
+ font-weight: 800; font-size: 40px;
811
+ color: var(--text);
812
+ line-height: 1.15; margin: 0 0 10px;
813
+ letter-spacing: -0.5px;
814
  }
815
+ .hero-title em { color: var(--purple); font-style: normal; }
816
  .hero-sub {
817
+ color: var(--muted);
818
+ font-family: 'Space Mono', monospace;
819
+ font-size: 11px; margin: 0 0 22px;
820
+ letter-spacing: 0.5px;
 
 
821
  }
822
+ .hero-pills { display: flex; gap: 8px; flex-wrap: wrap; }
823
  .hero-pill {
824
+ background: rgba(255,255,255,0.70);
825
+ border: 1px solid var(--lavender2);
826
+ color: var(--purple-d); border-radius: 20px;
827
+ padding: 4px 14px; font-size: 12px;
828
+ font-family: 'Nunito', sans-serif; font-weight: 600;
829
+ backdrop-filter: blur(4px);
830
  }
831
 
832
+ /* ── Section headers ── */
833
  .sec-head {
834
+ display: flex; align-items: center; gap: 12px;
835
+ font-family: 'Space Mono', monospace;
836
+ font-size: 9px; letter-spacing: 3px;
837
+ color: var(--purple); text-transform: uppercase;
838
+ margin: 28px 0 14px;
839
  }
840
  .sec-head::after {
841
+ content: ''; flex: 1; height: 1px;
842
+ background: linear-gradient(90deg, var(--lavender2), transparent);
843
  }
844
 
845
+ /* ── Left card ── */
846
  .left-card {
847
+ background: var(--offwhite);
848
+ border: 1.5px solid var(--border);
849
+ border-radius: var(--radius);
850
+ padding: 24px;
851
  }
852
 
853
  /* ── Format box ── */
854
  .fmt-box {
855
+ background: var(--white);
856
+ border: 1px solid var(--lavender2);
857
+ border-left: 4px solid var(--purple);
858
+ border-radius: 12px;
859
+ padding: 18px 20px;
860
+ font-family: 'Space Mono', monospace;
861
+ font-size: 11px; color: var(--muted);
862
+ line-height: 2.1; margin-bottom: 20px;
863
+ }
864
+ .fmt-box .col { color: var(--purple); font-weight: 700; }
865
+ .fmt-box .val { color: var(--teal); }
866
+ .fmt-box .cmt { color: var(--border); }
867
+ .fmt-box .note {
868
+ display: block;
869
+ background: var(--peach); border: 1px solid #FDE68A;
870
+ border-radius: 8px; padding: 8px 12px;
871
+ color: #92400E; font-size: 10.5px;
872
+ margin-top: 12px; line-height: 1.7;
873
  }
 
 
 
874
 
875
  /* ── Run button ── */
876
  .run-btn button {
877
+ background: linear-gradient(135deg, #8B5CF6, #EC4899) !important;
878
+ border: none !important;
879
+ border-radius: 14px !important;
880
+ color: #fff !important;
881
+ font-family: 'Nunito', sans-serif !important;
882
+ font-weight: 700 !important;
883
+ font-size: 16px !important;
884
+ padding: 15px 0 !important;
885
+ width: 100% !important;
886
+ box-shadow: 0 4px 20px rgba(139,92,246,0.30) !important;
887
+ transition: all 0.25s !important;
888
+ cursor: pointer !important;
889
+ letter-spacing: 0.3px !important;
890
  }
891
  .run-btn button:hover {
892
+ transform: translateY(-3px) !important;
893
+ box-shadow: 0 10px 32px rgba(139,92,246,0.40) !important;
894
  }
895
 
896
  /* ── Pipeline ── */
897
+ .pipeline { display: flex; margin-top: 20px; }
 
 
898
  .pipe-step {
899
+ flex: 1;
900
+ background: var(--white);
901
+ border: 1.5px solid var(--border);
902
+ padding: 14px 8px;
903
+ text-align: center;
904
+ position: relative;
905
  }
906
  .pipe-step:not(:last-child)::after {
907
+ content: '›'; position: absolute;
908
+ right: -11px; top: 50%; transform: translateY(-50%);
909
+ color: var(--purple); font-size: 18px; font-weight: 700;
910
+ background: var(--white); padding: 0 3px; z-index: 1;
911
  }
912
+ .pipe-step:first-child { border-radius: 12px 0 0 12px; }
913
+ .pipe-step:last-child { border-radius: 0 12px 12px 0; }
914
  .pipe-num {
915
+ font-family: 'Space Mono', monospace;
916
+ font-size: 16px; font-weight: 700;
917
+ color: var(--purple); display: block;
918
  }
919
  .pipe-name {
920
+ font-size: 10px; color: var(--muted);
921
+ font-family: 'Nunito', sans-serif;
922
+ font-weight: 600; margin-top: 3px; display: block;
923
  }
924
 
925
  /* ── Summary card ── */
926
  .sum-card {
927
+ background: var(--white);
928
+ border: 1.5px solid var(--border);
929
+ border-radius: var(--radius);
930
+ padding: 24px 28px;
931
+ box-shadow: var(--shadow);
932
  }
933
  .sum-card h2 {
934
+ color: var(--purple) !important;
935
+ font-family: 'Nunito', sans-serif !important;
936
+ font-size: 15px !important; font-weight: 700 !important;
937
+ margin-top: 22px !important;
938
+ padding-bottom: 6px;
939
+ border-bottom: 1px solid var(--lavender2);
 
 
 
 
940
  }
941
+ .sum-card table { width: 100%; border-collapse: collapse; margin: 10px 0; }
942
  .sum-card th {
943
+ background: var(--lavender) !important;
944
+ color: var(--text) !important;
945
+ font-family: 'Space Mono', monospace !important;
946
+ font-size: 10px !important;
947
+ padding: 8px 12px !important;
948
+ border: 1px solid var(--border) !important;
949
+ text-align: left;
950
  }
951
  .sum-card td {
952
+ color: var(--text) !important;
953
+ font-size: 12.5px !important;
954
+ padding: 7px 12px !important;
955
+ border: 1px solid var(--border) !important;
956
+ font-family: 'Space Mono', monospace !important;
957
  }
958
+ .sum-card td:nth-child(odd) { background: rgba(237,233,254,0.3) !important; }
959
  .sum-card td code, .sum-card p code {
960
+ background: var(--lavender); color: var(--purple-d);
961
+ border-radius: 4px; padding: 1px 5px;
962
+ font-family: 'Space Mono', monospace; font-size: 11px;
 
963
  }
964
+ .sum-card p { color: var(--text) !important; font-size: 13px !important; }
965
 
966
+ /* ── Plot cards ── */
967
  .plot-wrap {
968
+ background: var(--white);
969
+ border: 1.5px solid var(--border);
970
+ border-radius: var(--radius);
971
+ overflow: hidden;
972
+ box-shadow: var(--shadow);
973
+ margin-bottom: 16px;
974
  }
975
  .plot-label {
976
+ padding: 11px 18px;
977
+ font-family: 'Space Mono', monospace;
978
+ font-size: 9px; letter-spacing: 2px;
979
+ text-transform: uppercase;
980
+ color: var(--muted);
981
+ border-bottom: 1px solid var(--border);
982
+ background: linear-gradient(90deg, var(--lavender) 0%, var(--white) 100%);
983
  }
984
 
985
  /* ── Download box ── */
986
  .dl-box {
987
+ background: linear-gradient(135deg, var(--lavender) 0%, var(--rose) 100%);
988
+ border: 1.5px solid var(--lavender2);
989
+ border-radius: var(--radius);
990
+ padding: 20px 24px;
991
  }
992
  .dl-box-title {
993
+ font-family: 'Space Mono', monospace;
994
+ font-size: 9px; letter-spacing: 2.5px;
995
+ color: var(--purple-d); text-transform: uppercase;
996
+ margin-bottom: 12px; font-weight: 700;
997
  }
998
  .dl-box-list {
999
+ font-family: 'Nunito', sans-serif;
1000
+ font-size: 12.5px; color: var(--text);
1001
+ line-height: 2.2; font-weight: 600;
1002
  }
1003
+ .dl-box-list span { color: var(--purple); }
1004
 
1005
+ /* ── Gradio base overrides ── */
1006
  .gradio-container .block,
1007
  .gradio-container .wrap,
1008
  .gradio-container .gap {
1009
+ background: transparent !important;
1010
+ border: none !important;
1011
+ box-shadow: none !important;
1012
  }
1013
  .gradio-container label {
1014
+ color: var(--text) !important;
1015
+ font-family: 'Nunito', sans-serif !important;
1016
+ font-weight: 600 !important;
1017
+ font-size: 13px !important;
1018
  }
1019
  .gradio-container input,
1020
  .gradio-container textarea {
1021
+ background: var(--white) !important;
1022
+ border: 1.5px solid var(--border) !important;
1023
+ color: var(--text) !important;
1024
+ border-radius: 10px !important;
1025
+ font-family: 'Nunito Sans', sans-serif !important;
1026
  }
1027
+ .gradio-container input:focus,
1028
+ .gradio-container textarea:focus {
1029
+ border-color: var(--purple) !important;
1030
+ box-shadow: 0 0 0 3px rgba(139,92,246,0.12) !important;
1031
  }
1032
+ .gradio-container input[type=range] { accent-color: var(--purple) !important; }
1033
  .gradio-container .output-markdown {
1034
+ background: transparent !important;
1035
+ color: var(--text) !important;
1036
  }
1037
  footer, .gradio-container .built-with,
1038
+ .gradio-container .svelte-1ipelgc { display: none !important; }
1039
  </style>
1040
  """
1041
 
 
1043
  <div class="hero">
1044
  <div class="hero-badge">GWAS · QQ · LD DECAY · ML SELECTION</div>
1045
  <h1 class="hero-title">Multi-Trait <em>Association</em><br>Analysis Platform</h1>
1046
+ <p class="hero-sub">GENOME-WIDE ASSOCIATION · QUALITY CONTROL · LD ANALYSIS · MARKER DISCOVERY</p>
1047
  <div class="hero-pills">
1048
+ <span class="hero-pill">🗺 Manhattan Plot</span>
1049
+ <span class="hero-pill">📊 QQ Plot + λ</span>
1050
+ <span class="hero-pill">🔗 LD Decay</span>
1051
+ <span class="hero-pill">🌋 Volcano Plot</span>
1052
+ <span class="hero-pill">🏆 Top Hits</span>
1053
+ <span class="hero-pill">📦 ZIP Export</span>
1054
  </div>
1055
  </div>
1056
  """
 
1059
  <div class="sec-head">Input Format</div>
1060
  <div class="fmt-box">
1061
  <span class="col">Col 1</span> Sample ID &nbsp;
1062
+ <span class="col">Col 2</span> Phenotype &nbsp;
1063
+ <span class="col">Col 3+</span> Markers (named)<br><br>
1064
+ <span class="col">ID</span>, <span class="col">Phenotype</span>,
1065
+ <span class="val">chr1_134521_LOC</span>, <span class="val">chr1_134810_LOC</span>, ...<br>
1066
+ <span class="cmt">-</span>&nbsp;, <span class="cmt">-</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;,
1067
+ <span class="val">1</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;,
1068
+ <span class="val">1</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;,
1069
+ <span class="cmt">← chr row</span><br>
1070
+ IRRI-1&nbsp;, <span class="val">45.0</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;,
1071
+ <span class="val">0</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;,
1072
+ <span class="val">2</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;, ...
1073
+ <span class="note">
1074
+ ⚠️ <strong>Missing values:</strong> Use <code>-1</code> for missing genotypes — they are automatically converted to NaN during QC.<br>
1075
+ ✅ <strong>Genotype coding:</strong> 0 = homozygous ref · 1 = heterozygous · 2 = homozygous alt
1076
+ </span>
1077
  </div>
1078
  """
1079
 
1080
  PIPE_HTML = """
1081
+ <div class="sec-head" style="margin-top:24px">Analysis Pipeline</div>
1082
  <div class="pipeline">
1083
+ <div class="pipe-step"><span class="pipe-num">01</span><span class="pipe-name">QC Filter</span></div>
1084
  <div class="pipe-step"><span class="pipe-num">02</span><span class="pipe-name">GWAS</span></div>
1085
  <div class="pipe-step"><span class="pipe-num">03</span><span class="pipe-name">QQ / LD</span></div>
1086
+ <div class="pipe-step"><span class="pipe-num">04</span><span class="pipe-name">ML Votes</span></div>
1087
  <div class="pipe-step"><span class="pipe-num">05</span><span class="pipe-name">Export</span></div>
1088
  </div>
1089
  """
1090
 
1091
  DL_HTML = """
1092
  <div class="dl-box">
1093
+ <div class="dl-box-title">📦 ZIP Contents</div>
1094
  <div class="dl-box-list">
1095
  <span>📊</span> gwas_results.csv — full marker statistics<br>
1096
  <span>🗺️</span> chromosome_summary.csv<br>
 
1104
  </div>
1105
  """
1106
 
1107
+
1108
  # ══════════════════════════════════════════════════════════════
1109
  # GRADIO APP
1110
  # ══════════════════════════════════════════════════════════════
1111
+ with gr.Blocks(css=THEME_CSS, title="MTA Analysis Platform") as app:
1112
 
1113
  gr.HTML(HERO_HTML)
1114
 
1115
  with gr.Row():
1116
+ with gr.Column(scale=1, min_width=310):
 
1117
  gr.HTML(FMT_HTML)
1118
  gr.HTML('<div class="sec-head">Configure</div>')
1119
 
1120
+ input_file = gr.File(label="📂 Upload CSV File", file_types=[".csv"])
1121
  target_markers = gr.Slider(
1122
  100, 5000, value=3000, step=100,
1123
  label="Target Markers for ML Selection",
1124
+ info="Controls ML feature voting; GWAS p-values are unaffected")
1125
 
1126
  with gr.Row(elem_classes=["run-btn"]):
1127
+ run_btn = gr.Button("✨ Run GWAS Analysis", variant="primary", size="lg")
1128
 
1129
  gr.HTML(PIPE_HTML)
1130
 
 
1131
  with gr.Column(scale=2):
1132
  gr.HTML('<div class="sec-head">Results Summary</div>')
1133
  with gr.Column(elem_classes=["sum-card"]):
1134
+ summary_out = gr.Markdown(value="*Upload a CSV file and click **Run GWAS Analysis** to begin.*")
1135
 
 
1136
  gr.HTML('<div class="sec-head" style="margin-top:10px">Visualizations</div>')
1137
 
1138
  with gr.Column(elem_classes=["plot-wrap"]):
1139
+ gr.HTML('<div class="plot-label">📍 Manhattan Plot — Genome-Wide Significance</div>')
1140
  manhattan_out = gr.Image(show_label=False)
1141
 
1142
  with gr.Row():
1143
  with gr.Column(elem_classes=["plot-wrap"]):
1144
+ gr.HTML('<div class="plot-label">📐 QQ Plot — Genomic Inflation Factor (λ)</div>')
1145
  qq_out = gr.Image(show_label=False)
1146
  with gr.Column(elem_classes=["plot-wrap"]):
1147
+ gr.HTML('<div class="plot-label">🔗 LD Decay — Linkage Disequilibrium</div>')
1148
  ld_out = gr.Image(show_label=False)
1149
 
1150
  with gr.Row():
1151
  with gr.Column(elem_classes=["plot-wrap"]):
1152
+ gr.HTML('<div class="plot-label">🌋 Volcano Plot — Effect Size vs Significance</div>')
1153
  vol_out = gr.Image(show_label=False)
1154
  with gr.Column(elem_classes=["plot-wrap"]):
1155
+ gr.HTML('<div class="plot-label">🏆 Top GWAS Hits — Ranked by −log₁₀(P)</div>')
1156
  top_out = gr.Image(show_label=False)
1157
 
1158
+ gr.HTML('<div class="sec-head" style="margin-top:10px">Export Results</div>')
 
1159
  with gr.Row():
1160
  with gr.Column(scale=1):
1161
  gr.HTML(DL_HTML)
1162
  with gr.Column(scale=1):
1163
+ download_out = gr.File(label="⬇️ Download All Results (ZIP)")
1164
  with gr.Column(scale=1):
1165
  pass
1166