softwareDevelopment commited on
Commit
538ac6e
Β·
verified Β·
1 Parent(s): b86141b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +58 -40
app.py CHANGED
@@ -1,10 +1,11 @@
1
  # -*- coding: utf-8 -*-
2
  """
3
- MTA Analysis Tool v8.1 β€” FIXES:
4
  βœ… Persistent output directory (no tempfile cleanup race)
5
  βœ… BSLMM: n_boot reduced + Ridge fallback for speed
6
  βœ… FarmCPU: vectorised inner loop
7
- βœ… LD decay: max_m cap per chromosome
 
8
  βœ… Gradio: gr.File returns actual path (not None race)
9
  βœ… Progress status updates in UI
10
  βœ… Timeout-safe: all heavy loops have max-iteration caps
@@ -25,7 +26,7 @@ from sklearn.preprocessing import StandardScaler
25
  warnings.filterwarnings('ignore')
26
 
27
  # ── Persistent output directory (survives Gradio's file-serving lifecycle) ──
28
- OUTPUT_DIR = Path(os.path.expanduser("~")) / "gwas_outputs"
29
  OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
30
 
31
  # ══════════════════════════════════════════════════════════════
@@ -455,42 +456,51 @@ def plot_qq_multi(model_pvals, bonf_thresh, save_path):
455
 
456
 
457
  # ══════════════════════════════════════════════════════════════
458
- # LD COMPUTATION
459
  # ══════════════════════════════════════════════════════════════
460
- def _compute_ld_pairs_bp(G, bp_pos, max_lag=50):
461
- n = G.shape[1]
462
- dists, r2s, dps = [], [], []
463
- for lag in range(1, min(max_lag+1, n)):
464
- x = G[:, :n-lag].astype(float)
465
- y = G[:, lag: ].astype(float)
466
- xm, ym = x - x.mean(0), y - y.mean(0)
467
- num = (xm*ym).sum(0)
468
- den = np.sqrt((xm**2).sum(0) * (ym**2).sum(0))
469
- with np.errstate(invalid='ignore', divide='ignore'):
470
- r = np.where(den > 0, num/den, 0.0)
471
- r2 = np.clip(r**2, 0, 1)
472
-
473
- p1 = x.mean(0)/2.0; p2 = y.mean(0)/2.0
474
- p11 = ((x==2)&(y==2)).mean(0)/2.0
475
- D = p11 - p1*p2
476
- with np.errstate(invalid='ignore', divide='ignore'):
477
- Dmax = np.where(D<0,
478
- np.minimum(p1*(1-p2),(1-p1)*p2),
479
- np.minimum(p1*p2,(1-p1)*(1-p2)))
480
- dp = np.where(Dmax>0, np.abs(D/Dmax), 0.0)
481
-
482
- dist = np.abs(bp_pos[lag:] - bp_pos[:n-lag])
483
- dists.append(dist); r2s.append(r2); dps.append(dp)
484
-
485
- if not dists:
486
  return np.array([]), np.array([]), np.array([])
487
- return np.concatenate(dists), np.concatenate(r2s), np.concatenate(dps)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
488
 
489
 
490
  # ══════════════════════════════════════════════════════════════
491
- # PLOT: LD DECAY ← FIXED: per-chrom cap = 80 markers (was 120)
492
  # ══════════════════════════════════════════════════════════════
493
- def plot_ld_decay_bp(genotypes, chromosomes, positions, save_path, max_m=80):
494
  _style()
495
  unique_chroms = sorted(set(chromosomes),
496
  key=lambda x: (int(x) if str(x).isdigit() else 999, str(x)))
@@ -517,7 +527,7 @@ def plot_ld_decay_bp(genotypes, chromosomes, positions, save_path, max_m=80):
517
  srt = np.argsort(bp_ch)
518
  G_ch = G_ch[:, srt]; bp_ch = bp_ch[srt]
519
 
520
- dist, r2, dp = _compute_ld_pairs_bp(G_ch, bp_ch, max_lag=50)
521
  if not len(dist): continue
522
 
523
  all_dist.extend(dist.tolist()); all_r2.extend(r2.tolist())
@@ -593,10 +603,17 @@ def plot_ld_decay_bp(genotypes, chromosomes, positions, save_path, max_m=80):
593
  axt = fig.add_subplot(gs[1]); axt.axis('off')
594
  ax.set_facecolor('#EEE8FA')
595
 
 
 
 
 
 
596
  for ch in unique_chroms:
597
- key = str(ch); cmsk = (ch_arr==key) & mask
598
- if not cmsk.any(): continue
599
- ax.scatter(dist_scaled[cmsk], r2_arr[cmsk],
 
 
600
  c=chrom_color[key], s=6, alpha=0.38,
601
  linewidths=0, zorder=2, label=key)
602
 
@@ -947,7 +964,7 @@ h1{color:#2D1B5E;border-bottom:3px solid #7C3AED;padding-bottom:8px}
947
  .progress-bar{background:#7C3AED!important}
948
  """
949
 
950
- with gr.Blocks(css=CSS, title="MTA GWAS v8.1") as app:
951
 
952
  gr.Markdown("""
953
  # 🧬 GWAS Analysis Platform v8.1
@@ -1008,7 +1025,7 @@ with gr.Blocks(css=CSS, title="MTA GWAS v8.1") as app:
1008
  ph_out = gr.Image(label="πŸ“Š Phenotype Distribution")
1009
  dl_out = gr.File(label="πŸ“¦ Download All Results (ZIP)")
1010
 
1011
- gr.Markdown("---\n**MTA GWAS v8.1** | Persistent output paths | Progress tracking")
1012
 
1013
  run_btn.click(
1014
  fn=run_analysis,
@@ -1021,4 +1038,5 @@ with gr.Blocks(css=CSS, title="MTA GWAS v8.1") as app:
1021
 
1022
  if __name__ == "__main__":
1023
  app.launch(share=False, show_error=True,
1024
- max_threads=4) # prevent thread exhaustion
 
 
1
  # -*- coding: utf-8 -*-
2
  """
3
+ MTA Analysis Tool v8.2 β€” FIXES:
4
  βœ… Persistent output directory (no tempfile cleanup race)
5
  βœ… BSLMM: n_boot reduced + Ridge fallback for speed
6
  βœ… FarmCPU: vectorised inner loop
7
+ βœ… LD decay: fully vectorised (no Python lag loop)
8
+ βœ… LD scatter: capped at 8000 pts for fast PNG rendering
9
  βœ… Gradio: gr.File returns actual path (not None race)
10
  βœ… Progress status updates in UI
11
  βœ… Timeout-safe: all heavy loops have max-iteration caps
 
26
  warnings.filterwarnings('ignore')
27
 
28
  # ── Persistent output directory (survives Gradio's file-serving lifecycle) ──
29
+ OUTPUT_DIR = Path("/tmp/gwas_outputs")
30
  OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
31
 
32
  # ══════════════════════════════════════════════════════════════
 
456
 
457
 
458
  # ══════════════════════════════════════════════════════════════
459
+ # LD COMPUTATION β€” fully vectorised, no Python lag loop
460
  # ══════════════════════════════════════════════════════════════
461
+ def _compute_ld_pairs_bp(G, bp_pos, max_lag=30):
462
+ """
463
+ Vectorised: compute all (i,j) pairs with j-i <= max_lag
464
+ using upper-triangle index trick β€” no Python for-loop over lags.
465
+ For 40 markers Γ— 30 lags β†’ 1 numpy call instead of 30.
466
+ """
467
+ m = G.shape[1]
468
+ G = G.astype(np.float32) # float32 halves memory
469
+
470
+ # All pairs (i,j) with 0 < j-i <= max_lag
471
+ ii, jj = np.triu_indices(m, k=1)
472
+ lag = jj - ii
473
+ keep = lag <= max_lag
474
+ ii, jj, lag = ii[keep], jj[keep], lag[keep]
475
+
476
+ if len(ii) == 0:
 
 
 
 
 
 
 
 
 
 
477
  return np.array([]), np.array([]), np.array([])
478
+
479
+ X = G[:, ii]; Y = G[:, jj] # n_samples Γ— n_pairs
480
+ Xm = X - X.mean(0); Ym = Y - Y.mean(0)
481
+ num = (Xm * Ym).sum(0)
482
+ den = np.sqrt((Xm**2).sum(0) * (Ym**2).sum(0))
483
+ with np.errstate(invalid='ignore', divide='ignore'):
484
+ r2 = np.where(den > 0, (num/den)**2, 0.0).clip(0, 1)
485
+
486
+ p1 = X.mean(0) / 2.0
487
+ p2 = Y.mean(0) / 2.0
488
+ p11 = ((X == 2) & (Y == 2)).mean(0) / 2.0
489
+ D = p11 - p1 * p2
490
+ with np.errstate(invalid='ignore', divide='ignore'):
491
+ Dmax = np.where(D < 0,
492
+ np.minimum(p1*(1-p2), (1-p1)*p2),
493
+ np.minimum(p1*p2, (1-p1)*(1-p2)))
494
+ dp = np.where(Dmax > 0, np.abs(D / Dmax), 0.0)
495
+
496
+ dist = np.abs(bp_pos[jj] - bp_pos[ii]).astype(float)
497
+ return dist, r2.astype(float), dp.astype(float)
498
 
499
 
500
  # ══════════════════════════════════════════════════════════════
501
+ # PLOT: LD DECAY β€” fast + scatter downsampled for rendering
502
  # ══════════════════════════════════════════════════════════════
503
+ def plot_ld_decay_bp(genotypes, chromosomes, positions, save_path, max_m=50):
504
  _style()
505
  unique_chroms = sorted(set(chromosomes),
506
  key=lambda x: (int(x) if str(x).isdigit() else 999, str(x)))
 
527
  srt = np.argsort(bp_ch)
528
  G_ch = G_ch[:, srt]; bp_ch = bp_ch[srt]
529
 
530
+ dist, r2, dp = _compute_ld_pairs_bp(G_ch, bp_ch, max_lag=30)
531
  if not len(dist): continue
532
 
533
  all_dist.extend(dist.tolist()); all_r2.extend(r2.tolist())
 
603
  axt = fig.add_subplot(gs[1]); axt.axis('off')
604
  ax.set_facecolor('#EEE8FA')
605
 
606
+ # Downsample scatter for fast PNG rendering (cap at 8000 total points)
607
+ MAX_SCATTER = 8000
608
+ total_vis = int(mask.sum())
609
+ ds_rate = max(1, total_vis // MAX_SCATTER)
610
+
611
  for ch in unique_chroms:
612
+ key = str(ch)
613
+ idxs = np.where((ch_arr == key) & mask)[0]
614
+ if not len(idxs): continue
615
+ pts = idxs[::ds_rate] # uniform downsample
616
+ ax.scatter(dist_scaled[pts], r2_arr[pts],
617
  c=chrom_color[key], s=6, alpha=0.38,
618
  linewidths=0, zorder=2, label=key)
619
 
 
964
  .progress-bar{background:#7C3AED!important}
965
  """
966
 
967
+ with gr.Blocks(css=CSS, title="MTA GWAS v8.2") as app:
968
 
969
  gr.Markdown("""
970
  # 🧬 GWAS Analysis Platform v8.1
 
1025
  ph_out = gr.Image(label="πŸ“Š Phenotype Distribution")
1026
  dl_out = gr.File(label="πŸ“¦ Download All Results (ZIP)")
1027
 
1028
+ gr.Markdown("---\n**MTA GWAS v8.2** | Persistent output paths | Progress tracking")
1029
 
1030
  run_btn.click(
1031
  fn=run_analysis,
 
1038
 
1039
  if __name__ == "__main__":
1040
  app.launch(share=False, show_error=True,
1041
+ max_threads=4,
1042
+ allowed_paths=[str(OUTPUT_DIR)])