softwareDevelopment commited on
Commit
23a552e
Β·
verified Β·
1 Parent(s): fab0b40

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +512 -320
app.py CHANGED
@@ -1,13 +1,12 @@
1
  # -*- coding: utf-8 -*-
2
  """
3
- MTA Analysis Tool v9.0 β€” NEW FEATURES:
 
 
4
  βœ… LOD threshold selector (user-configurable)
5
  βœ… PCA components selector + standalone PCA biplot/scree
6
  βœ… QQ plots: standard dark GWAS colors, proper null diagonal
7
  βœ… All plots rendered SEPARATELY (not combined into grids)
8
- βœ… Circos plot: all models compared, MTA detections with per-model colors
9
- βœ… Interpretation text for Circos and LD
10
- βœ… Persistent output directory
11
  βœ… BSLMM: Ridge fallback for speed
12
  βœ… FarmCPU: corrected vectorised scan
13
  """
@@ -35,23 +34,21 @@ OUTPUT_DIR = Path("/tmp/gwas_outputs")
35
  OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
36
 
37
  # ══════════════════════════════════════════════════════════════
38
- # DARK GWAS THEME β€” Standard dark palette
39
  # ══════════════════════════════════════════════════════════════
40
- BG = "#0D1117" # GitHub dark bg
41
- PANEL = "#161B22" # slightly lighter panel
42
- GRID_C = "#21262D" # subtle grid
43
- TEXT_C = "#E6EDF3" # primary text
44
- SUBTEXT = "#8B949E" # secondary text
45
- ACCENT = "#58A6FF" # blue accent
46
- RED_C = "#F85149" # significant SNP red
47
- GOLD_C = "#E3B341" # suggestive gold
48
- TEAL_C = "#39D353" # teal
49
- GREEN_C = "#3FB950" # green
50
- ORANGE_C = "#F0883E" # orange
51
-
52
- # Standard GWAS chromosome alternating colors (dark mode)
53
- CHR_EVEN = "#58A6FF" # blue
54
- CHR_ODD = "#3FB950" # green
55
 
56
  CHROM_PALETTE = [
57
  "#58A6FF","#3FB950","#F85149","#E3B341","#BC8CFF",
@@ -62,11 +59,11 @@ CHROM_PALETTE = [
62
  ]
63
 
64
  MODEL_COLORS = {
65
- 'GLM': '#58A6FF', # blue
66
- 'MLM': '#F85149', # red
67
- 'CMLM': '#3FB950', # green
68
- 'BSLMM': '#E3B341', # gold
69
- 'FarmCPU': '#BC8CFF', # purple
70
  }
71
 
72
  def _style_dark():
@@ -90,6 +87,57 @@ def _style_dark():
90
  'legend.facecolor': PANEL,
91
  })
92
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93
 
94
  # ══════════════════════════════════════════════════════════════
95
  # CSV PARSER
@@ -251,7 +299,7 @@ def model_farmcpu(G, y, K, max_iter=3):
251
 
252
 
253
  # ══════════════════════════════════════════════════════════════
254
- # PLOT: PHENOTYPE DISTRIBUTION (separate)
255
  # ══════════════════════════════════════════════════════════════
256
  def plot_phenotype(phenotypes, save_path):
257
  _style_dark()
@@ -297,7 +345,7 @@ def plot_phenotype(phenotypes, save_path):
297
 
298
 
299
  # ══════════════════════════════════════════════════════════════
300
- # PLOT: PCA (separate β€” scree + biplot)
301
  # ══════════════════════════════════════════════════════════════
302
  def plot_pca(geno_q, pheno_q, n_components, save_path):
303
  _style_dark()
@@ -315,7 +363,6 @@ def plot_pca(geno_q, pheno_q, n_components, save_path):
315
  fontsize=15, fontweight='bold', color=TEXT_C, y=1.01)
316
  gs = GridSpec(1, 3, figure=fig, wspace=0.32)
317
 
318
- # --- Scree plot ---
319
  ax0 = fig.add_subplot(gs[0]); ax0.set_facecolor(PANEL)
320
  pc_labels = [f'PC{i+1}' for i in range(n_comp)]
321
  bars = ax0.bar(pc_labels, evr, color=ACCENT, alpha=0.85, edgecolor=BG, lw=0.5, zorder=2)
@@ -331,9 +378,7 @@ def plot_pca(geno_q, pheno_q, n_components, save_path):
331
  ax0.text(bar.get_x()+bar.get_width()/2, bar.get_height()+0.3,
332
  f'{pct:.1f}%', ha='center', va='bottom', fontsize=7, color=TEXT_C)
333
 
334
- # --- PC1 vs PC2 biplot coloured by phenotype ---
335
  ax1 = fig.add_subplot(gs[1]); ax1.set_facecolor(PANEL)
336
- pheno_norm = (pheno_q - np.nanmin(pheno_q)) / (np.nanmax(pheno_q)-np.nanmin(pheno_q)+1e-9)
337
  cmap = plt.cm.plasma
338
  sc = ax1.scatter(scores[:,0], scores[:,1],
339
  c=pheno_q, cmap=cmap, s=35, alpha=0.85,
@@ -347,7 +392,6 @@ def plot_pca(geno_q, pheno_q, n_components, save_path):
347
  cb.set_label('Phenotype', fontsize=9, color=TEXT_C); cb.ax.yaxis.set_tick_params(color=TEXT_C)
348
  ax1.grid(True, color=GRID_C, lw=0.5, alpha=0.7)
349
 
350
- # --- PC2 vs PC3 biplot (if available) ---
351
  ax2 = fig.add_subplot(gs[2]); ax2.set_facecolor(PANEL)
352
  if n_comp >= 3:
353
  sc2 = ax2.scatter(scores[:,1], scores[:,2],
@@ -373,7 +417,7 @@ def plot_pca(geno_q, pheno_q, n_components, save_path):
373
 
374
 
375
  # ══════════════════════════════════════════════════════════════
376
- # PLOT: MANHATTAN (one per model, separate files)
377
  # ══════════════════════════════════════════════════════════════
378
  def _build_x_pos(mn, chroms, GAP=None):
379
  unique_chroms = sorted(set(chroms),
@@ -394,11 +438,6 @@ def _build_x_pos(mn, chroms, GAP=None):
394
 
395
  def plot_manhattan_single(mn, ch_q, pv, mname, bonf_thresh, lod_thresh_user,
396
  save_path, lod_mode=False):
397
- """
398
- Single-model Manhattan.
399
- lod_mode: if True plot LOD instead of -log10P.
400
- lod_thresh_user: user-specified LOD threshold line (extra annotation).
401
- """
402
  _style_dark()
403
  LOD_FACTOR = np.log10(np.e) / 2.0
404
  GAP = max(8, len(mn)//150)
@@ -410,7 +449,6 @@ def plot_manhattan_single(mn, ch_q, pv, mname, bonf_thresh, lod_thresh_user,
410
  sug_lod = sug_log * LOD_FACTOR
411
  mcol = MODEL_COLORS.get(mname, ACCENT)
412
 
413
- # Two panels: βˆ’log10P + LOD
414
  fig, (ax_p, ax_l) = plt.subplots(2, 1, figsize=(18, 9),
415
  facecolor=BG, sharex=True,
416
  gridspec_kw={'height_ratios':[3,2]})
@@ -448,7 +486,6 @@ def plot_manhattan_single(mn, ch_q, pv, mname, bonf_thresh, lod_thresh_user,
448
  label=f'Bonferroni ({bonf_line:.2f})', zorder=5)
449
  ax.axhline(sug_line, color=GOLD_C, ls=':', lw=1.5, alpha=0.85,
450
  label=f'Suggestive ({sug_line:.2f})', zorder=5)
451
- # User-defined LOD threshold on LOD panel
452
  if ax is ax_l and lod_thresh_user != bonf_lod:
453
  ax.axhline(lod_thresh_user, color=ORANGE_C, ls='-.', lw=1.8, alpha=0.9,
454
  label=f'User LOD ({lod_thresh_user:.1f})', zorder=5)
@@ -473,17 +510,9 @@ def plot_manhattan_single(mn, ch_q, pv, mname, bonf_thresh, lod_thresh_user,
473
 
474
 
475
  # ══════════════════════════════════════════════════════════════
476
- # PLOT: QQ β€” FIXED (standard dark GWAS, proper diagonal)
477
  # ══════════════════════════════════════════════════════════════
478
  def plot_qq_single(pv_raw, mname, bonf_thresh, save_path):
479
- """
480
- Standard GWAS QQ plot:
481
- - Dark background
482
- - Proper y=x null diagonal (expected = observed under H0)
483
- - 95% confidence band (beta distribution)
484
- - Red: above Bonferroni, blue: below
485
- - Ξ» (genomic inflation factor) displayed prominently
486
- """
487
  _style_dark()
488
  mcol = MODEL_COLORS.get(mname, ACCENT)
489
  bonf_log = -np.log10(bonf_thresh)
@@ -506,15 +535,12 @@ def plot_qq_single(pv_raw, mname, bonf_thresh, save_path):
506
  n = len(pv)
507
  ranks = np.arange(1, n+1)
508
  obs_sorted = np.sort(pv)
509
- # Expected: uniform p-values β†’ -log10((rank)/(n+1))
510
  exp_log = -np.log10(ranks / (n + 1))
511
  obs_log = -np.log10(obs_sorted)
512
- # Sort both descending so largest exp goes to right
513
  sort_idx = np.argsort(exp_log)[::-1]
514
  exp_log = exp_log[sort_idx]
515
  obs_log = obs_log[sort_idx]
516
 
517
- # 95% CI via Beta distribution
518
  ci_hi = -np.log10(stats.beta.ppf(0.025, ranks, ranks[::-1]+1) + 1e-300)
519
  ci_lo = -np.log10(stats.beta.ppf(0.975, ranks, ranks[::-1]+1) + 1e-300)
520
  ci_hi = ci_hi[sort_idx]; ci_lo = ci_lo[sort_idx]
@@ -522,7 +548,6 @@ def plot_qq_single(pv_raw, mname, bonf_thresh, save_path):
522
  ax.fill_between(exp_log, ci_lo, ci_hi,
523
  color=mcol, alpha=0.18, zorder=1, label='95% CI')
524
 
525
- # Color: red if above Bonferroni, model color otherwise
526
  above = obs_log >= bonf_log
527
  if (~above).any():
528
  ax.scatter(exp_log[~above], obs_log[~above],
@@ -534,17 +559,13 @@ def plot_qq_single(pv_raw, mname, bonf_thresh, save_path):
534
  edgecolors='#FFD7D5', marker='D',
535
  zorder=3, label='p < Bonferroni')
536
 
537
- # Null diagonal (y = x): this IS the expected line
538
  maxv = max(obs_log.max(), exp_log.max()) * 1.06
539
  ax.plot([0, maxv], [0, maxv],
540
  color='#FFFFFF', lw=1.8, ls='--', alpha=0.9,
541
  zorder=4, label='y = x (null)')
542
-
543
- # Bonferroni horizontal line
544
  ax.axhline(bonf_log, color=RED_C, ls=':', lw=1.4, alpha=0.8,
545
  zorder=5, label=f'Bonferroni ({bonf_log:.2f})')
546
 
547
- # Genomic inflation factor Ξ»
548
  chi2_obs = stats.chi2.ppf(1 - pv, df=1)
549
  chi2_obs = chi2_obs[np.isfinite(chi2_obs) & (chi2_obs > 0)]
550
  lam = (np.median(chi2_obs) / stats.chi2.ppf(0.5, df=1)) if len(chi2_obs) else 1.0
@@ -565,8 +586,7 @@ def plot_qq_single(pv_raw, mname, bonf_thresh, save_path):
565
  ax.set_xlim(0, maxv); ax.set_ylim(0, maxv)
566
  ax.set_xlabel('Expected βˆ’log₁₀(P)', fontsize=13, fontweight='bold', color=TEXT_C)
567
  ax.set_ylabel('Observed βˆ’log₁₀(P)', fontsize=13, fontweight='bold', color=TEXT_C)
568
- ax.legend(fontsize=9, loc='upper left',
569
- bbox_to_anchor=(0.0, 0.82))
570
  ax.grid(True, color=GRID_C, lw=0.6, alpha=0.7)
571
  ax.text(0.98, 0.04, f'n = {n:,} markers',
572
  transform=ax.transAxes, ha='right', fontsize=9, color=SUBTEXT)
@@ -578,147 +598,276 @@ def plot_qq_single(pv_raw, mname, bonf_thresh, save_path):
578
 
579
 
580
  # ══════════════════════════════════════════════════════════════
581
- # PLOT: LD DECAY (separate)
 
 
582
  # ══════════════════════════════════════════════════════════════
583
  def _compute_ld_pairs_bp(G, bp_pos, max_lag=30):
584
- m=G.shape[1]; G=G.astype(np.float32)
585
- ii,jj=np.triu_indices(m,k=1); lag=jj-ii; keep=lag<=max_lag
586
- ii,jj,lag=ii[keep],jj[keep],lag[keep]
587
- if len(ii)==0: return np.array([]),np.array([]),np.array([])
588
- X=G[:,ii]; Y=G[:,jj]
589
- Xm=X-X.mean(0); Ym=Y-Y.mean(0)
590
- num=(Xm*Ym).sum(0); den=np.sqrt((Xm**2).sum(0)*(Ym**2).sum(0))
591
- with np.errstate(invalid='ignore',divide='ignore'):
592
- r2=np.where(den>0,(num/den)**2,0.0).clip(0,1)
593
- p1=X.mean(0)/2.; p2=Y.mean(0)/2.
594
- p11=((X==2)&(Y==2)).mean(0)/2.
595
- D=p11-p1*p2
596
- with np.errstate(invalid='ignore',divide='ignore'):
597
- Dmax=np.where(D<0,np.minimum(p1*(1-p2),(1-p1)*p2),
598
- np.minimum(p1*p2,(1-p1)*(1-p2)))
599
- dp=np.where(Dmax>0,np.abs(D/Dmax),0.0)
600
- dist=np.abs(bp_pos[jj]-bp_pos[ii]).astype(float)
601
- return dist,r2.astype(float),dp.astype(float)
 
 
 
 
 
 
 
602
 
603
  def plot_ld_decay_bp(genotypes, chromosomes, positions, save_path, max_m=50):
604
- _style_dark()
605
- unique_chroms=sorted(set(chromosomes),
606
- key=lambda x:(int(x) if str(x).isdigit() else 999,str(x)))
607
- chrom_to_idx={}
608
- for gi,ch in enumerate(chromosomes): chrom_to_idx.setdefault(str(ch),[]).append(gi)
609
- bp_arr=np.array(positions,dtype=float)
610
- if bp_arr.max()==0: bp_arr=np.arange(len(positions),dtype=float)*1000
611
- all_dist,all_r2,all_dp,all_ch=[],[],[],[]
612
- chrom_stats={}; rng=np.random.default_rng(0)
 
 
 
 
 
 
 
 
 
 
 
 
 
613
  for ch in unique_chroms:
614
- idxs=chrom_to_idx.get(str(ch),[])
615
- if len(idxs)<4: continue
616
- if len(idxs)>max_m: idxs=sorted(rng.choice(idxs,max_m,replace=False).tolist())
617
- G_ch=genotypes[:,idxs].copy().astype(float); bp_ch=bp_arr[idxs]
618
- srt=np.argsort(bp_ch); G_ch=G_ch[:,srt]; bp_ch=bp_ch[srt]
619
- dist,r2,dp=_compute_ld_pairs_bp(G_ch,bp_ch,max_lag=30)
620
- if not len(dist): continue
 
 
 
 
 
621
  all_dist.extend(dist.tolist()); all_r2.extend(r2.tolist())
622
- all_dp.extend(dp.tolist()); all_ch.extend([str(ch)]*len(dist))
623
- chrom_stats[str(ch)]={'n_markers':len(idxs),'n_pairs':len(dist),
624
- 'mean_r2':float(np.mean(r2)),'mean_dprime':float(np.mean(dp)),
625
- 'max_r2':float(np.max(r2)),'max_dist_bp':float(dist.max()) if len(dist) else 0}
 
 
 
 
 
 
626
  if not all_dist:
627
- fig,ax=plt.subplots(figsize=(10,6),facecolor=BG)
628
- ax.set_facecolor(PANEL)
629
- ax.text(0.5,0.5,'No LD data available (need β‰₯4 markers/chr)',
630
- ha='center',va='center',transform=ax.transAxes,fontsize=13,color=TEXT_C)
631
- plt.savefig(save_path,dpi=110,bbox_inches='tight',facecolor=BG)
632
- plt.close(fig); return chrom_stats,"No LD data available."
633
- dist_arr=np.array(all_dist,dtype=float); r2_arr=np.array(all_r2,dtype=float)
634
- ch_arr=np.array(all_ch,dtype=str)
635
- max_bp=float(np.percentile(dist_arr,99)) or dist_arr.max()
636
- scale,unit_label=((1_000_000,'Mb') if max_bp>=1e6 else (1_000,'kb') if max_bp>=1000 else (1,'bp'))
637
- dist_scaled=dist_arr/scale; max_scaled=max_bp/scale
638
- mask=dist_arr<=max_bp; dv,rv=dist_scaled[mask],r2_arr[mask]
639
- bins=np.linspace(0,max_scaled,81); ctrs,meds=[],[]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
640
  for i in range(80):
641
- m=(dv>=bins[i])&(dv<bins[i+1])
642
- if m.sum()>=3: ctrs.append((bins[i]+bins[i+1])/2.); meds.append(np.median(rv[m]))
643
- ctrs=np.array(ctrs); meds=np.array(meds)
644
- xs_smooth=ys_smooth=None; ann={}
645
- if len(ctrs)>=5:
646
- k=min(3,len(ctrs)-1)
647
- xs_smooth=np.linspace(ctrs[0],ctrs[-1],2000)
648
- spl=make_interp_spline(ctrs,meds,k=k)
649
- ys_smooth=np.clip(spl(xs_smooth),0,1)
650
- r2_start=ys_smooth[0] if ys_smooth[0]>0 else (meds[0] if len(meds) else 0.5)
651
- for thr_name,thr_val in [('half',r2_start/2.),('r2_02',0.2),('r2_01',0.1)]:
652
- ix=np.where(ys_smooth<=thr_val)[0]
653
- if len(ix): ann[thr_name]=float(xs_smooth[ix[0]])
654
- def _fmt(v): return f"{v:.2f} {unit_label}"
655
- ilines=[]
 
 
 
 
 
 
 
 
656
  if 'half' in ann:
657
- speed="rapid" if ann['half']<0.5 else "moderate" if ann['half']<5 else "slow"
658
  ilines.append(f"β€’ LD half-decay: {_fmt(ann['half'])} [{speed} decay]")
659
- else: ilines.append("β€’ Half-decay not reached β€” LD persists across full range")
660
- if 'r2_02' in ann: ilines.append(f"β€’ rΒ²<0.2 (GWAS tagging threshold): {_fmt(ann['r2_02'])}")
661
- if 'r2_01' in ann: ilines.append(f"β€’ rΒ²<0.1 (near-independence): {_fmt(ann['r2_01'])}")
 
 
 
662
  ilines.append(f"β€’ Overall mean rΒ² = {np.mean(r2_arr):.3f} | Mean D' = {np.mean(all_dp):.3f}")
663
- ld_interp="\n".join(ilines)
664
- chrom_color={str(ch):CHROM_PALETTE[i%len(CHROM_PALETTE)]
665
- for i,ch in enumerate(unique_chroms)}
666
- fig=plt.figure(figsize=(14,9),facecolor=BG)
667
- gs=GridSpec(2,1,figure=fig,height_ratios=[3.8,1],hspace=0.08)
668
- ax=fig.add_subplot(gs[0]); axt=fig.add_subplot(gs[1]); axt.axis('off')
669
- ax.set_facecolor(PANEL)
670
- MAX_SCATTER=8000; total_vis=int(mask.sum()); ds_rate=max(1,total_vis//MAX_SCATTER)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
671
  for ch in unique_chroms:
672
- key=str(ch); idxs=np.where((ch_arr==key)&mask)[0]
673
- if not len(idxs): continue
674
- pts=idxs[::ds_rate]
675
- ax.scatter(dist_scaled[pts],r2_arr[pts],c=chrom_color[key],
676
- s=7,alpha=0.45,linewidths=0,zorder=2,label=key)
 
 
 
 
 
 
 
 
677
  if xs_smooth is not None:
678
- ax.fill_between(xs_smooth,0,ys_smooth,color=GREEN_C,alpha=0.18,zorder=3)
679
- ax.plot(xs_smooth,ys_smooth,color=GREEN_C,lw=2.5,zorder=4,label='Median rΒ²')
680
- ax.axhline(0.2,color=GOLD_C,ls='--',lw=1.8,alpha=0.85,zorder=5,label='rΒ²=0.2 (GWAS tag)')
681
- ann_styles={'half':(GOLD_C,'Β½ decay',0.50,0.10),
682
- 'r2_02':(RED_C,'rΒ²=0.2',0.20,0.08),
683
- 'r2_01':(TEAL_C,'rΒ²=0.1',0.10,0.06)}
684
- for akey,(col,lbl,r2ref,offy) in ann_styles.items():
685
- if akey not in ann: continue
686
- xv=ann[akey]
687
- ax.axvline(xv,color=col,ls=':',lw=1.9,alpha=0.88,zorder=6)
688
- ax.annotate(f'{lbl}\n{_fmt(xv)}',xy=(xv,r2ref),
689
- xytext=(xv+max_scaled*0.012,r2ref+offy),
690
- fontsize=8.5,fontweight='bold',color=col,
691
- arrowprops=dict(arrowstyle='->',color=col,lw=1.2),
692
- bbox=dict(boxstyle='round,pad=0.3',fc=BG,ec=col,alpha=0.92,lw=1.1),zorder=7)
693
- ax.set_xlim(0,max_scaled); ax.set_ylim(0,1.05)
694
- ax.set_xlabel(f'Physical distance ({unit_label})',fontsize=12,fontweight='bold',color=TEXT_C)
695
- ax.set_ylabel('LD (RΒ²)',fontsize=12,fontweight='bold',color=TEXT_C)
696
- ax.set_title('LD Decay by Chromosome (Physical Distance)',
697
- fontsize=14,fontweight='bold',color=TEXT_C,pad=10)
698
- ax.xaxis.grid(True,color=GRID_C,lw=0.6,alpha=0.7)
699
- ax.yaxis.grid(True,color=GRID_C,lw=0.6,alpha=0.7)
700
- handles,labels=ax.get_legend_handles_labels()
701
- special=[(h,l) for h,l in zip(handles,labels) if l in ('Median rΒ²','rΒ²=0.2 (GWAS tag)')]
702
- chrs=[(h,l) for h,l in zip(handles,labels) if l not in ('Median rΒ²','rΒ²=0.2 (GWAS tag)')]
703
- ncols_l=max(1,(len(chrs)+9)//10)
704
- leg_h=[h for h,_ in special]+[h for h,_ in chrs]
705
- leg_l=[l for _,l in special]+[f'Chr {l}' for _,l in chrs]
706
- ax.legend(leg_h,leg_l,title='Chr',title_fontsize=9,fontsize=7.5,
707
- loc='upper right',ncol=ncols_l,framealpha=0.93,
708
- markerscale=2.2,handlelength=1.3)
709
- axt.text(0.005,0.98,
710
- "LD DECAY INTERPRETATION\n"+"─"*72+"\n"+ld_interp,
711
- transform=axt.transAxes,va='top',ha='left',
712
- fontsize=9,color=TEXT_C,fontfamily='monospace',
713
- bbox=dict(boxstyle='round,pad=0.5',facecolor=PANEL,
714
- edgecolor=GRID_C,alpha=0.98))
715
- plt.savefig(save_path,dpi=110,bbox_inches='tight',facecolor=BG)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
716
  plt.close(fig)
717
- return chrom_stats,ld_interp
718
 
719
 
720
  # ══════════════════════════════════════════════════════════════
721
- # PLOT: MODEL COMPARISON (separate)
722
  # ══════════════════════════════════════════════════════════════
723
  def plot_model_comparison(model_pvals, save_path):
724
  _style_dark()
@@ -754,204 +903,255 @@ def plot_model_comparison(model_pvals, save_path):
754
 
755
 
756
  # ══════════════════════════════════════════════════════════════
757
- # PLOT: CIRCOS β€” all models, MTA detections, per-model colors
 
 
758
  # ══════════════════════════════════════════════════════════════
759
  def plot_circos(mn_q, ch_q, pos_q, model_pvals, bonf_thresh, lod_thresh_user, save_path):
760
  """
761
- Circos-style circular plot:
762
- - Outer ring: chromosomes (arc segments, alternating colors)
763
- - Inner tracks: one ring per model, height = βˆ’log10(P)
764
- - Significant SNPs (above Bonferroni): large colored dots on model ring
765
- - MTA consensus (significant in β‰₯2 models): inner hub markers
766
- - Color-coded per model with legend
767
- - Interpretation text below
768
  """
769
- _style_dark()
770
- LOD_FACTOR = np.log10(np.e) / 2.0
771
 
772
- unique_chroms = sorted(set(ch_q),
773
- key=lambda x: (int(x) if str(x).isdigit() else 999, str(x)))
 
 
774
  chrom_to_idx = {}
775
- for i, c in enumerate(ch_q): chrom_to_idx.setdefault(c, []).append(i)
 
776
  n_chr = len(unique_chroms)
777
 
778
- # Assign angular span per chromosome proportional to marker count
779
- chr_len = {ch: len(chrom_to_idx[ch]) for ch in unique_chroms}
780
- total_m = sum(chr_len.values())
781
- GAP_DEG = 1.5 # degrees gap between chromosomes
782
- total_gap = GAP_DEG * n_chr
783
- avail_deg = 360 - total_gap
784
- chr_deg = {ch: (chr_len[ch]/total_m)*avail_deg for ch in unique_chroms}
785
 
786
- # Build per-marker angle
787
- marker_angle = np.zeros(len(mn_q))
788
  chr_start_deg = {}
789
  cur = 0.0
790
  for ch in unique_chroms:
791
  chr_start_deg[ch] = cur
792
  idxs = chrom_to_idx[ch]
793
  for rank, idx in enumerate(idxs):
794
- marker_angle[idx] = cur + (rank/max(len(idxs)-1,1)) * chr_deg[ch]
795
  cur += chr_deg[ch] + GAP_DEG
796
 
797
  # Radii
798
- R_OUTER = 1.00 # outer chromosome ring
799
- R_CHR = 0.94 # chromosome arc inner edge
800
- R_TRACK_O = 0.90 # outermost model track
801
- TRACK_W = 0.09 # width per model track
802
- R_HUB = 0.30 # consensus MTA hub radius
803
- R_INNER = 0.25 # inner decorative circle
804
-
805
- models = list(model_pvals.keys())
806
  n_models = len(models)
807
-
808
  bonf_log = -np.log10(bonf_thresh)
809
 
810
- # Detect significant markers per model
811
- sig_per_model = {}
812
- for mname, pv in model_pvals.items():
813
- sig_per_model[mname] = set(np.where(pv < bonf_thresh)[0])
814
 
815
- # Consensus: significant in β‰₯ ceil(n_models/2) models
816
- consensus_threshold = max(1, int(np.ceil(n_models/2)))
817
  sig_counts = np.zeros(len(mn_q), dtype=int)
818
  for mname in models:
819
- for idx in sig_per_model[mname]: sig_counts[idx] += 1
 
820
  consensus_idx = set(np.where(sig_counts >= consensus_threshold)[0])
821
 
822
- fig = plt.figure(figsize=(14, 14), facecolor=BG)
823
- ax = fig.add_axes([0.05, 0.12, 0.90, 0.82], projection='polar')
824
- ax.set_facecolor(BG)
825
  ax.set_theta_zero_location('N')
826
  ax.set_theta_direction(-1)
827
- ax.set_ylim(0, 1.05)
828
  ax.axis('off')
829
 
830
- # ── Chromosome outer arcs ──────────────────────────────────────────
 
 
 
 
 
 
 
831
  for ci, ch in enumerate(unique_chroms):
832
  s_deg = chr_start_deg[ch]
833
  e_deg = s_deg + chr_deg[ch]
834
  s_rad = np.deg2rad(s_deg); e_rad = np.deg2rad(e_deg)
835
  theta_arc = np.linspace(s_rad, e_rad, 80)
836
 
837
- col = CHROM_PALETTE[ci % len(CHROM_PALETTE)]
838
- # Outer ring fill
839
- ax.fill_between(theta_arc, R_CHR, R_OUTER,
840
- color=col, alpha=0.75, zorder=3)
841
- # Chromosome label
842
- mid_rad = np.deg2rad((s_deg + e_deg)/2)
843
- label_r = (R_CHR + R_OUTER)/2 + 0.025
 
 
 
 
 
 
 
 
 
 
844
  ax.text(mid_rad, label_r, str(ch),
845
  ha='center', va='center', fontsize=7.5,
846
- fontweight='bold', color=BG, zorder=6,
847
- rotation=np.rad2deg(mid_rad)-90 if mid_rad < np.pi else np.rad2deg(mid_rad)+90)
 
 
 
 
 
 
 
848
 
849
  # ── Model tracks ───────────────────────────────────────────────────
850
  for mi, mname in enumerate(models):
851
- pv = model_pvals[mname]
852
  log_p = -np.log10(np.clip(pv, 1e-300, 1))
853
- mcol = MODEL_COLORS.get(mname, ACCENT)
854
- # Track radii
855
  r_out_track = R_TRACK_O - mi * TRACK_W
856
- r_in_track = r_out_track - TRACK_W + 0.01
857
 
858
- # Draw faint track background
859
- theta_full = np.linspace(0, 2*np.pi, 500)
860
- ax.fill_between(theta_full, r_in_track, r_out_track,
861
- color=mcol, alpha=0.06, zorder=1)
862
- ax.plot(theta_full, [r_out_track]*500,
863
- color=mcol, lw=0.5, alpha=0.3, zorder=2)
864
 
865
- # Normalize log_p to track height
866
- lp_max = max(bonf_log * 1.5, log_p.max(), 1.0)
867
  norm_h = (log_p / lp_max) * TRACK_W
868
 
869
- # Bonferroni ring
870
- bonf_r = r_in_track + (bonf_log/lp_max)*TRACK_W
871
- ax.plot(theta_full, [bonf_r]*500,
872
- color=RED_C, lw=0.8, ls='--', alpha=0.5, zorder=3)
873
 
874
- # Plot bars as radial lines (non-significant)
875
- for idx, angle_deg in enumerate(marker_angle):
876
- if idx in sig_per_model[mname]: continue
877
- theta = np.deg2rad(angle_deg)
 
878
  r_top = r_in_track + norm_h[idx]
879
  ax.plot([theta, theta], [r_in_track, r_top],
880
- color=mcol, lw=0.5, alpha=0.4, zorder=3)
881
 
882
- # Significant markers: large dots
883
  for idx in sig_per_model[mname]:
884
  theta = np.deg2rad(marker_angle[idx])
885
- r_top = min(r_in_track + norm_h[idx], r_out_track)
886
- ax.scatter(theta, r_top, s=45, c=mcol, alpha=1.0,
887
- edgecolors='white', lw=0.6, zorder=6,
888
- marker='o' if idx not in consensus_idx else 'D')
889
-
890
- # ── Consensus MTA hub ──────────────────────────────────────────────
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
891
  for idx in consensus_idx:
892
  theta = np.deg2rad(marker_angle[idx])
893
- n_models_sig = sig_counts[idx]
894
- hub_r = R_HUB + (n_models_sig / n_models) * 0.06
895
- ax.scatter(theta, hub_r, s=80, c=ORANGE_C,
896
- alpha=1.0, edgecolors='white', lw=0.8,
897
- marker='*', zorder=8)
898
-
899
- # ── Inner decorative circle ────────────────────────────────────────
900
- theta_full = np.linspace(0, 2*np.pi, 500)
901
- ax.plot(theta_full, [R_INNER]*500, color=GRID_C, lw=1.2, alpha=0.5, zorder=2)
902
- ax.fill_between(theta_full, 0, R_INNER,
903
- color='#1C2128', alpha=0.8, zorder=1)
904
-
905
- # ── Centre text ────────────────────────────────────────────────────
 
906
  n_consensus = len(consensus_idx)
907
  n_total_sig = sum(len(v) for v in sig_per_model.values())
908
- ax.text(np.pi/2, 0, f'{n_consensus}\nMTA',
909
- ha='center', va='center', fontsize=13,
910
- fontweight='bold', color=ORANGE_C, zorder=9,
 
911
  transform=ax.transData)
912
- ax.text(np.pi/2, 0.12, f'{n_total_sig} total\nsig.',
 
913
  ha='center', va='center', fontsize=8,
914
- color=SUBTEXT, zorder=9, transform=ax.transData)
 
915
 
916
  # ── Legend ────────────────────────────────────────────────────────
917
  legend_elements = [
918
- mpatches.Patch(facecolor=MODEL_COLORS.get(m, ACCENT), alpha=0.85,
919
- edgecolor='white', lw=0.5, label=m)
920
  for m in models
921
  ] + [
922
- plt.scatter([], [], marker='D', c=ACCENT, s=60,
923
- edgecolors='white', lw=0.6, label='Sig. (single model)'),
924
- plt.scatter([], [], marker='*', c=ORANGE_C, s=120,
925
- edgecolors='white', lw=0.8, label=f'MTA consensus (β‰₯{consensus_threshold} models)'),
926
- plt.Line2D([0],[0], color=RED_C, ls='--', lw=1.5, label='Bonferroni threshold'),
927
  ]
928
- fig.legend(handles=legend_elements, loc='lower center',
929
- ncol=min(4, len(legend_elements)),
930
- fontsize=9, framealpha=0.9,
931
- facecolor=PANEL, edgecolor=GRID_C,
932
- bbox_to_anchor=(0.5, 0.01))
933
-
934
- # ── Title & interpretation ─────────────────────────────────────────
935
- fig.text(0.5, 0.96, 'Circos Plot β€” Multi-Model GWAS Comparison',
936
- ha='center', fontsize=15, fontweight='bold', color=TEXT_C)
937
- fig.text(0.5, 0.935,
 
 
 
 
 
 
938
  f'{n_chr} chromosomes | {len(mn_q)} markers | '
939
  f'{len(models)} models | {n_consensus} MTA consensus loci',
940
- ha='center', fontsize=9, color=SUBTEXT)
941
 
942
- # Interpretation box
943
  interp_lines = [
944
- f"■ Each coloured ring = one GWAS model (outer→inner: {', '.join(models)})",
945
- f"β–  Bar height ∝ βˆ’log₁₀(P); red dashed ring = Bonferroni threshold",
946
- f"β–  Diamond markers (β—†) = significant in that model alone",
947
- f"β–  Star markers (β˜…) = MTA consensus: significant in β‰₯{consensus_threshold}/{n_models} models",
948
- f"β–  Total significant loci: {n_total_sig} across all models; {n_consensus} are MTA consensus",
 
949
  ]
950
- fig.text(0.04, 0.07, "\n".join(interp_lines),
951
- ha='left', fontsize=8, color=TEXT_C, fontfamily='monospace',
952
- bbox=dict(boxstyle='round,pad=0.6', fc=PANEL, ec=GRID_C, alpha=0.95))
 
 
953
 
954
- plt.savefig(save_path, dpi=110, bbox_inches='tight', facecolor=BG)
955
  plt.close(fig)
956
 
957
 
@@ -1064,7 +1264,7 @@ def run_analysis(input_file, miss_sample, miss_marker, maf_thresh,
1064
  df.to_csv(csv_path,index=False)
1065
  any_sig=df[sig_cols].sum(1)>0; df[any_sig].to_csv(top_path,index=False)
1066
 
1067
- # ── PLOTS (all separate) ────��──────────────────────────────────
1068
  progress(0.62, desc="Phenotype plot…")
1069
  ph_path=str(pdir/'phenotype_dist.png')
1070
  plot_phenotype(pheno_q, ph_path)
@@ -1171,7 +1371,6 @@ def run_analysis(input_file, miss_sample, miss_marker, maf_thresh,
1171
  """
1172
  progress(1.0, desc="Done βœ…")
1173
 
1174
- # Return: summary + first Manhattan, first QQ, PCA, LD, Circos, comparison, ZIP
1175
  first_man = list(man_paths.values())[0] if man_paths else None
1176
  first_qq = list(qq_paths.values())[0] if qq_paths else None
1177
 
@@ -1211,9 +1410,6 @@ h1, h2, h3, label {color: #58A6FF !important;}
1211
  .gr-box, .gr-panel {background: #161B22 !important; border-color: #21262D !important;}
1212
  """
1213
 
1214
- # Store plot paths between runs
1215
- _state = {"man_paths": {}, "qq_paths": {}}
1216
-
1217
  with gr.Blocks(css=CSS, title="MTA GWAS v9.0 | Dark Edition") as app:
1218
 
1219
  gr.Markdown("""
@@ -1262,7 +1458,6 @@ with gr.Blocks(css=CSS, title="MTA GWAS v9.0 | Dark Edition") as app:
1262
 
1263
  summary_out = gr.Markdown()
1264
 
1265
- # ── Per-model selectors ───────────────────────────────────────────
1266
  with gr.Row():
1267
  man_model_sel = gr.Dropdown(label="πŸ—ΊοΈ Manhattan β€” select model",
1268
  choices=[], value=None, interactive=True)
@@ -1278,20 +1473,18 @@ with gr.Blocks(css=CSS, title="MTA GWAS v9.0 | Dark Edition") as app:
1278
  circos_out = gr.Image(label="🌐 Circos β€” Multi-Model MTA Comparison")
1279
 
1280
  with gr.Row():
1281
- ld_out = gr.Image(label="🧬 LD Decay")
1282
  cmp_out = gr.Image(label="βš–οΈ Model Concordance")
1283
 
1284
  with gr.Row():
1285
  ph_out = gr.Image(label="πŸ“Š Phenotype Distribution")
1286
  dl_out = gr.File(label="πŸ“¦ Download All Results (ZIP)")
1287
 
1288
- gr.Markdown("---\n**MTA GWAS v9.0** β€” Dark Edition | Separate plots | Circos | PCA | LOD selector")
1289
 
1290
- # Hidden state for plot paths
1291
  man_paths_state = gr.State({})
1292
  qq_paths_state = gr.State({})
1293
 
1294
- # Run analysis
1295
  run_btn.click(
1296
  fn=run_analysis,
1297
  inputs=[input_file, miss_sample, miss_marker, maf_thr,
@@ -1306,7 +1499,6 @@ with gr.Blocks(css=CSS, title="MTA GWAS v9.0 | Dark Edition") as app:
1306
  show_progress="full",
1307
  )
1308
 
1309
- # Model selector callbacks
1310
  def switch_manhattan(model_name, paths):
1311
  if not model_name or not paths: return None
1312
  return paths.get(model_name)
 
1
  # -*- coding: utf-8 -*-
2
  """
3
+ MTA Analysis Tool v9.0 β€” UPDATED PLOTS:
4
+ βœ… LD Decay β€” white background, chr-coloured scatter, green curve (matches reference)
5
+ βœ… Circos β€” white background, classic bioinformatics style (matches reference)
6
  βœ… LOD threshold selector (user-configurable)
7
  βœ… PCA components selector + standalone PCA biplot/scree
8
  βœ… QQ plots: standard dark GWAS colors, proper null diagonal
9
  βœ… All plots rendered SEPARATELY (not combined into grids)
 
 
 
10
  βœ… BSLMM: Ridge fallback for speed
11
  βœ… FarmCPU: corrected vectorised scan
12
  """
 
34
  OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
35
 
36
  # ══════════════════════════════════════════════════════════════
37
+ # DARK GWAS THEME β€” used for Manhattan, QQ, PCA, Phenotype
38
  # ══════════════════════════════════════════════════════════════
39
+ BG = "#0D1117"
40
+ PANEL = "#161B22"
41
+ GRID_C = "#21262D"
42
+ TEXT_C = "#E6EDF3"
43
+ SUBTEXT = "#8B949E"
44
+ ACCENT = "#58A6FF"
45
+ RED_C = "#F85149"
46
+ GOLD_C = "#E3B341"
47
+ TEAL_C = "#39D353"
48
+ GREEN_C = "#3FB950"
49
+ ORANGE_C = "#F0883E"
50
+ CHR_EVEN = "#58A6FF"
51
+ CHR_ODD = "#3FB950"
 
 
52
 
53
  CHROM_PALETTE = [
54
  "#58A6FF","#3FB950","#F85149","#E3B341","#BC8CFF",
 
59
  ]
60
 
61
  MODEL_COLORS = {
62
+ 'GLM': '#58A6FF',
63
+ 'MLM': '#F85149',
64
+ 'CMLM': '#3FB950',
65
+ 'BSLMM': '#E3B341',
66
+ 'FarmCPU': '#BC8CFF',
67
  }
68
 
69
  def _style_dark():
 
87
  'legend.facecolor': PANEL,
88
  })
89
 
90
+ # ══════════════════════════════════════════════════════════════
91
+ # WHITE THEME β€” used for LD Decay and Circos
92
+ # ══════════════════════════════════════════════════════════════
93
+ WH_BG = "#FFFFFF"
94
+ WH_PANEL = "#F7F9FC"
95
+ WH_GRID = "#D0D7DE"
96
+ WH_TEXT = "#1B2A3B"
97
+ WH_SUBTEXT = "#5A6A7A"
98
+ WH_ACCENT = "#1F6FEB"
99
+ WH_RED = "#CF222E"
100
+ WH_GOLD = "#9A6700"
101
+ WH_GREEN = "#116329"
102
+ WH_ORANGE = "#BC4C00"
103
+
104
+ CHROM_PALETTE_LIGHT = [
105
+ "#1F77B4","#FF7F0E","#2CA02C","#D62728","#9467BD",
106
+ "#8C564B","#E377C2","#7F7F7F","#BCBD22","#17BECF",
107
+ "#AEC7E8","#FFBB78","#98DF8A","#FF9896","#C5B0D5",
108
+ "#1F77B4","#FF7F0E","#2CA02C","#D62728","#9467BD",
109
+ "#8C564B","#E377C2","#7F7F7F","#BCBD22","#17BECF",
110
+ ]
111
+
112
+ MODEL_COLORS_LIGHT = {
113
+ 'GLM': '#1F77B4',
114
+ 'MLM': '#D62728',
115
+ 'CMLM': '#2CA02C',
116
+ 'BSLMM': '#9A6700',
117
+ 'FarmCPU': '#9467BD',
118
+ }
119
+
120
+ def _style_white():
121
+ plt.rcParams.update({
122
+ 'figure.facecolor': WH_BG,
123
+ 'axes.facecolor': WH_PANEL,
124
+ 'axes.edgecolor': WH_GRID,
125
+ 'axes.labelcolor': WH_TEXT,
126
+ 'axes.titlecolor': WH_TEXT,
127
+ 'xtick.color': WH_TEXT,
128
+ 'ytick.color': WH_TEXT,
129
+ 'text.color': WH_TEXT,
130
+ 'grid.color': WH_GRID,
131
+ 'grid.linewidth': 0.6,
132
+ 'figure.dpi': 110,
133
+ 'font.family': 'DejaVu Sans',
134
+ 'axes.spines.top': False,
135
+ 'axes.spines.right': False,
136
+ 'legend.framealpha': 0.92,
137
+ 'legend.edgecolor': WH_GRID,
138
+ 'legend.facecolor': WH_BG,
139
+ })
140
+
141
 
142
  # ══════════════════════════════════════════════════════════════
143
  # CSV PARSER
 
299
 
300
 
301
  # ══════════════════════════════════════════════════════════════
302
+ # PLOT: PHENOTYPE DISTRIBUTION
303
  # ══════════════════════════════════════════════════════════════
304
  def plot_phenotype(phenotypes, save_path):
305
  _style_dark()
 
345
 
346
 
347
  # ══════════════════════════════════════════════════════════════
348
+ # PLOT: PCA
349
  # ══════════════════════════════════════════════════════════════
350
  def plot_pca(geno_q, pheno_q, n_components, save_path):
351
  _style_dark()
 
363
  fontsize=15, fontweight='bold', color=TEXT_C, y=1.01)
364
  gs = GridSpec(1, 3, figure=fig, wspace=0.32)
365
 
 
366
  ax0 = fig.add_subplot(gs[0]); ax0.set_facecolor(PANEL)
367
  pc_labels = [f'PC{i+1}' for i in range(n_comp)]
368
  bars = ax0.bar(pc_labels, evr, color=ACCENT, alpha=0.85, edgecolor=BG, lw=0.5, zorder=2)
 
378
  ax0.text(bar.get_x()+bar.get_width()/2, bar.get_height()+0.3,
379
  f'{pct:.1f}%', ha='center', va='bottom', fontsize=7, color=TEXT_C)
380
 
 
381
  ax1 = fig.add_subplot(gs[1]); ax1.set_facecolor(PANEL)
 
382
  cmap = plt.cm.plasma
383
  sc = ax1.scatter(scores[:,0], scores[:,1],
384
  c=pheno_q, cmap=cmap, s=35, alpha=0.85,
 
392
  cb.set_label('Phenotype', fontsize=9, color=TEXT_C); cb.ax.yaxis.set_tick_params(color=TEXT_C)
393
  ax1.grid(True, color=GRID_C, lw=0.5, alpha=0.7)
394
 
 
395
  ax2 = fig.add_subplot(gs[2]); ax2.set_facecolor(PANEL)
396
  if n_comp >= 3:
397
  sc2 = ax2.scatter(scores[:,1], scores[:,2],
 
417
 
418
 
419
  # ══════════════════════════════════════════════════════════════
420
+ # PLOT: MANHATTAN
421
  # ══════════════════════════════════════════════════════════════
422
  def _build_x_pos(mn, chroms, GAP=None):
423
  unique_chroms = sorted(set(chroms),
 
438
 
439
  def plot_manhattan_single(mn, ch_q, pv, mname, bonf_thresh, lod_thresh_user,
440
  save_path, lod_mode=False):
 
 
 
 
 
441
  _style_dark()
442
  LOD_FACTOR = np.log10(np.e) / 2.0
443
  GAP = max(8, len(mn)//150)
 
449
  sug_lod = sug_log * LOD_FACTOR
450
  mcol = MODEL_COLORS.get(mname, ACCENT)
451
 
 
452
  fig, (ax_p, ax_l) = plt.subplots(2, 1, figsize=(18, 9),
453
  facecolor=BG, sharex=True,
454
  gridspec_kw={'height_ratios':[3,2]})
 
486
  label=f'Bonferroni ({bonf_line:.2f})', zorder=5)
487
  ax.axhline(sug_line, color=GOLD_C, ls=':', lw=1.5, alpha=0.85,
488
  label=f'Suggestive ({sug_line:.2f})', zorder=5)
 
489
  if ax is ax_l and lod_thresh_user != bonf_lod:
490
  ax.axhline(lod_thresh_user, color=ORANGE_C, ls='-.', lw=1.8, alpha=0.9,
491
  label=f'User LOD ({lod_thresh_user:.1f})', zorder=5)
 
510
 
511
 
512
  # ══════════════════════════════════════════════════════════════
513
+ # PLOT: QQ
514
  # ══════════════════════════════════════════════════════════════
515
  def plot_qq_single(pv_raw, mname, bonf_thresh, save_path):
 
 
 
 
 
 
 
 
516
  _style_dark()
517
  mcol = MODEL_COLORS.get(mname, ACCENT)
518
  bonf_log = -np.log10(bonf_thresh)
 
535
  n = len(pv)
536
  ranks = np.arange(1, n+1)
537
  obs_sorted = np.sort(pv)
 
538
  exp_log = -np.log10(ranks / (n + 1))
539
  obs_log = -np.log10(obs_sorted)
 
540
  sort_idx = np.argsort(exp_log)[::-1]
541
  exp_log = exp_log[sort_idx]
542
  obs_log = obs_log[sort_idx]
543
 
 
544
  ci_hi = -np.log10(stats.beta.ppf(0.025, ranks, ranks[::-1]+1) + 1e-300)
545
  ci_lo = -np.log10(stats.beta.ppf(0.975, ranks, ranks[::-1]+1) + 1e-300)
546
  ci_hi = ci_hi[sort_idx]; ci_lo = ci_lo[sort_idx]
 
548
  ax.fill_between(exp_log, ci_lo, ci_hi,
549
  color=mcol, alpha=0.18, zorder=1, label='95% CI')
550
 
 
551
  above = obs_log >= bonf_log
552
  if (~above).any():
553
  ax.scatter(exp_log[~above], obs_log[~above],
 
559
  edgecolors='#FFD7D5', marker='D',
560
  zorder=3, label='p < Bonferroni')
561
 
 
562
  maxv = max(obs_log.max(), exp_log.max()) * 1.06
563
  ax.plot([0, maxv], [0, maxv],
564
  color='#FFFFFF', lw=1.8, ls='--', alpha=0.9,
565
  zorder=4, label='y = x (null)')
 
 
566
  ax.axhline(bonf_log, color=RED_C, ls=':', lw=1.4, alpha=0.8,
567
  zorder=5, label=f'Bonferroni ({bonf_log:.2f})')
568
 
 
569
  chi2_obs = stats.chi2.ppf(1 - pv, df=1)
570
  chi2_obs = chi2_obs[np.isfinite(chi2_obs) & (chi2_obs > 0)]
571
  lam = (np.median(chi2_obs) / stats.chi2.ppf(0.5, df=1)) if len(chi2_obs) else 1.0
 
586
  ax.set_xlim(0, maxv); ax.set_ylim(0, maxv)
587
  ax.set_xlabel('Expected βˆ’log₁₀(P)', fontsize=13, fontweight='bold', color=TEXT_C)
588
  ax.set_ylabel('Observed βˆ’log₁₀(P)', fontsize=13, fontweight='bold', color=TEXT_C)
589
+ ax.legend(fontsize=9, loc='upper left', bbox_to_anchor=(0.0, 0.82))
 
590
  ax.grid(True, color=GRID_C, lw=0.6, alpha=0.7)
591
  ax.text(0.98, 0.04, f'n = {n:,} markers',
592
  transform=ax.transAxes, ha='right', fontsize=9, color=SUBTEXT)
 
598
 
599
 
600
  # ══════════════════════════════════════════════════════════════
601
+ # PLOT: LD DECAY β€” WHITE BACKGROUND, CHR-COLOURED SCATTER
602
+ # matches reference image (white bg, coloured scatter by chr,
603
+ # green smooth curve, black dashed rΒ²=0.2 line)
604
  # ══════════════════════════════════════════════════════════════
605
  def _compute_ld_pairs_bp(G, bp_pos, max_lag=30):
606
+ m = G.shape[1]
607
+ G = G.astype(np.float32)
608
+ ii, jj = np.triu_indices(m, k=1)
609
+ lag = jj - ii
610
+ keep = lag <= max_lag
611
+ ii, jj, lag = ii[keep], jj[keep], lag[keep]
612
+ if len(ii) == 0:
613
+ return np.array([]), np.array([]), np.array([])
614
+ X = G[:, ii]; Y = G[:, jj]
615
+ Xm = X - X.mean(0); Ym = Y - Y.mean(0)
616
+ num = (Xm * Ym).sum(0)
617
+ den = np.sqrt((Xm ** 2).sum(0) * (Ym ** 2).sum(0))
618
+ with np.errstate(invalid='ignore', divide='ignore'):
619
+ r2 = np.where(den > 0, (num / den) ** 2, 0.0).clip(0, 1)
620
+ p1 = X.mean(0) / 2.; p2 = Y.mean(0) / 2.
621
+ p11 = ((X == 2) & (Y == 2)).mean(0) / 2.
622
+ D = p11 - p1 * p2
623
+ with np.errstate(invalid='ignore', divide='ignore'):
624
+ Dmax = np.where(D < 0,
625
+ np.minimum(p1 * (1 - p2), (1 - p1) * p2),
626
+ np.minimum(p1 * p2, (1 - p1) * (1 - p2)))
627
+ dp = np.where(Dmax > 0, np.abs(D / Dmax), 0.0)
628
+ dist = np.abs(bp_pos[jj] - bp_pos[ii]).astype(float)
629
+ return dist, r2.astype(float), dp.astype(float)
630
+
631
 
632
  def plot_ld_decay_bp(genotypes, chromosomes, positions, save_path, max_m=50):
633
+ """
634
+ LD decay β€” white background, chromosome-coloured scatter,
635
+ smooth green median curve + shaded band, black dashed rΒ²=0.2 line.
636
+ """
637
+ _style_white()
638
+
639
+ unique_chroms = sorted(
640
+ set(chromosomes),
641
+ key=lambda x: (int(x) if str(x).isdigit() else 999, str(x))
642
+ )
643
+ chrom_to_idx = {}
644
+ for gi, ch in enumerate(chromosomes):
645
+ chrom_to_idx.setdefault(str(ch), []).append(gi)
646
+
647
+ bp_arr = np.array(positions, dtype=float)
648
+ if bp_arr.max() == 0:
649
+ bp_arr = np.arange(len(positions), dtype=float) * 1000
650
+
651
+ all_dist, all_r2, all_dp, all_ch = [], [], [], []
652
+ chrom_stats = {}
653
+ rng = np.random.default_rng(0)
654
+
655
  for ch in unique_chroms:
656
+ idxs = chrom_to_idx.get(str(ch), [])
657
+ if len(idxs) < 4:
658
+ continue
659
+ if len(idxs) > max_m:
660
+ idxs = sorted(rng.choice(idxs, max_m, replace=False).tolist())
661
+ G_ch = genotypes[:, idxs].copy().astype(float)
662
+ bp_ch = bp_arr[idxs]
663
+ srt = np.argsort(bp_ch)
664
+ G_ch = G_ch[:, srt]; bp_ch = bp_ch[srt]
665
+ dist, r2, dp = _compute_ld_pairs_bp(G_ch, bp_ch, max_lag=30)
666
+ if not len(dist):
667
+ continue
668
  all_dist.extend(dist.tolist()); all_r2.extend(r2.tolist())
669
+ all_dp.extend(dp.tolist()); all_ch.extend([str(ch)] * len(dist))
670
+ chrom_stats[str(ch)] = {
671
+ 'n_markers': len(idxs),
672
+ 'n_pairs': len(dist),
673
+ 'mean_r2': float(np.mean(r2)),
674
+ 'mean_dprime': float(np.mean(dp)),
675
+ 'max_r2': float(np.max(r2)),
676
+ 'max_dist_bp': float(dist.max()) if len(dist) else 0,
677
+ }
678
+
679
  if not all_dist:
680
+ fig, ax = plt.subplots(figsize=(10, 6), facecolor=WH_BG)
681
+ ax.set_facecolor(WH_PANEL)
682
+ ax.text(0.5, 0.5, 'No LD data available (need β‰₯4 markers/chr)',
683
+ ha='center', va='center', transform=ax.transAxes,
684
+ fontsize=13, color=WH_TEXT)
685
+ plt.savefig(save_path, dpi=110, bbox_inches='tight', facecolor=WH_BG)
686
+ plt.close(fig)
687
+ return chrom_stats, "No LD data available."
688
+
689
+ dist_arr = np.array(all_dist, dtype=float)
690
+ r2_arr = np.array(all_r2, dtype=float)
691
+ ch_arr = np.array(all_ch, dtype=str)
692
+
693
+ max_bp = float(np.percentile(dist_arr, 99)) or dist_arr.max()
694
+ if max_bp >= 1_000_000:
695
+ scale, unit_label = 1_000_000, 'Mb'
696
+ elif max_bp >= 1_000:
697
+ scale, unit_label = 1_000, 'kb'
698
+ else:
699
+ scale, unit_label = 1, 'bp'
700
+
701
+ dist_scaled = dist_arr / scale
702
+ max_scaled = max_bp / scale
703
+ mask = dist_arr <= max_bp
704
+ dv, rv = dist_scaled[mask], r2_arr[mask]
705
+
706
+ # Binned median for smooth curve
707
+ bins = np.linspace(0, max_scaled, 81)
708
+ ctrs, meds = [], []
709
  for i in range(80):
710
+ m = (dv >= bins[i]) & (dv < bins[i + 1])
711
+ if m.sum() >= 3:
712
+ ctrs.append((bins[i] + bins[i + 1]) / 2.)
713
+ meds.append(np.median(rv[m]))
714
+ ctrs = np.array(ctrs); meds = np.array(meds)
715
+
716
+ xs_smooth = ys_smooth = None
717
+ ann = {}
718
+ if len(ctrs) >= 5:
719
+ k = min(3, len(ctrs) - 1)
720
+ xs_smooth = np.linspace(ctrs[0], ctrs[-1], 2000)
721
+ spl = make_interp_spline(ctrs, meds, k=k)
722
+ ys_smooth = np.clip(spl(xs_smooth), 0, 1)
723
+ r2_start = ys_smooth[0] if ys_smooth[0] > 0 else (meds[0] if len(meds) else 0.5)
724
+ for thr_name, thr_val in [('half', r2_start / 2.), ('r2_02', 0.2), ('r2_01', 0.1)]:
725
+ ix = np.where(ys_smooth <= thr_val)[0]
726
+ if len(ix):
727
+ ann[thr_name] = float(xs_smooth[ix[0]])
728
+
729
+ def _fmt(v):
730
+ return f"{v:.2f} {unit_label}"
731
+
732
+ ilines = []
733
  if 'half' in ann:
734
+ speed = "rapid" if ann['half'] < 0.5 else "moderate" if ann['half'] < 5 else "slow"
735
  ilines.append(f"β€’ LD half-decay: {_fmt(ann['half'])} [{speed} decay]")
736
+ else:
737
+ ilines.append("β€’ Half-decay not reached β€” LD persists across full range")
738
+ if 'r2_02' in ann:
739
+ ilines.append(f"β€’ rΒ²<0.2 (GWAS tagging threshold): {_fmt(ann['r2_02'])}")
740
+ if 'r2_01' in ann:
741
+ ilines.append(f"β€’ rΒ²<0.1 (near-independence): {_fmt(ann['r2_01'])}")
742
  ilines.append(f"β€’ Overall mean rΒ² = {np.mean(r2_arr):.3f} | Mean D' = {np.mean(all_dp):.3f}")
743
+ ld_interp = "\n".join(ilines)
744
+
745
+ chrom_color = {
746
+ str(ch): CHROM_PALETTE_LIGHT[i % len(CHROM_PALETTE_LIGHT)]
747
+ for i, ch in enumerate(unique_chroms)
748
+ }
749
+
750
+ # ── Figure ────────────────────────────────────────────────────────
751
+ fig = plt.figure(figsize=(12, 8), facecolor=WH_BG)
752
+ gs = GridSpec(2, 1, figure=fig, height_ratios=[4.2, 1], hspace=0.06)
753
+ ax = fig.add_subplot(gs[0])
754
+ axt = fig.add_subplot(gs[1])
755
+ axt.axis('off')
756
+
757
+ ax.set_facecolor(WH_BG)
758
+ ax.spines['top'].set_visible(False)
759
+ ax.spines['right'].set_visible(False)
760
+ ax.spines['left'].set_color(WH_GRID)
761
+ ax.spines['bottom'].set_color(WH_GRID)
762
+
763
+ # Scatter points β€” one colour per chromosome
764
+ MAX_SCATTER = 10_000
765
+ total_vis = int(mask.sum())
766
+ ds_rate = max(1, total_vis // MAX_SCATTER)
767
+
768
  for ch in unique_chroms:
769
+ key = str(ch)
770
+ idxs = np.where((ch_arr == key) & mask)[0]
771
+ if not len(idxs):
772
+ continue
773
+ pts = idxs[::ds_rate]
774
+ ax.scatter(
775
+ dist_scaled[pts], r2_arr[pts],
776
+ c=chrom_color[key],
777
+ s=6, alpha=0.55, linewidths=0,
778
+ zorder=2, label=key
779
+ )
780
+
781
+ # Green smooth median curve + shaded fill (matching reference)
782
  if xs_smooth is not None:
783
+ ax.fill_between(
784
+ xs_smooth, 0, ys_smooth,
785
+ color='#2CA02C', alpha=0.18, zorder=3
786
+ )
787
+ ax.plot(
788
+ xs_smooth, ys_smooth,
789
+ color='#2CA02C', lw=2.2, zorder=4, label='Median rΒ²'
790
+ )
791
+
792
+ # Black dashed horizontal line at rΒ²=0.2 (matching reference)
793
+ ax.axhline(
794
+ 0.2, color='black', ls='--', lw=1.6, alpha=0.80,
795
+ zorder=5, label='rΒ²= 0.2'
796
+ )
797
+
798
+ # Vertical annotation lines
799
+ ann_styles = {
800
+ 'half': ('#FF7F0E', 'Β½ decay', 0.50, 0.10),
801
+ 'r2_02': ('#D62728', 'rΒ²=0.2', 0.20, 0.08),
802
+ 'r2_01': ('#9467BD', 'rΒ²=0.1', 0.10, 0.06),
803
+ }
804
+ for akey, (col, lbl, r2ref, offy) in ann_styles.items():
805
+ if akey not in ann:
806
+ continue
807
+ xv = ann[akey]
808
+ ax.axvline(xv, color=col, ls=':', lw=1.6, alpha=0.80, zorder=6)
809
+ ax.annotate(
810
+ f'{lbl}\n{_fmt(xv)}',
811
+ xy=(xv, r2ref),
812
+ xytext=(xv + max_scaled * 0.015, r2ref + offy),
813
+ fontsize=8, fontweight='bold', color=col,
814
+ arrowprops=dict(arrowstyle='->', color=col, lw=1.1),
815
+ bbox=dict(boxstyle='round,pad=0.3', fc=WH_BG, ec=col, alpha=0.92, lw=1.0),
816
+ zorder=7
817
+ )
818
+
819
+ ax.set_xlim(0, max_scaled)
820
+ ax.set_ylim(0, 1.05)
821
+ ax.set_xlabel(
822
+ f'Genetic distance ({unit_label})',
823
+ fontsize=12, fontweight='bold', color=WH_TEXT
824
+ )
825
+ ax.set_ylabel(
826
+ 'LD estimate (RΒ²)',
827
+ fontsize=12, fontweight='bold', color=WH_TEXT
828
+ )
829
+ ax.set_title(
830
+ 'LD Decay by Chromosome',
831
+ fontsize=14, fontweight='bold', color=WH_ACCENT, pad=12
832
+ )
833
+ ax.xaxis.grid(True, color=WH_GRID, lw=0.5, alpha=0.8)
834
+ ax.yaxis.grid(True, color=WH_GRID, lw=0.5, alpha=0.8)
835
+ ax.tick_params(colors=WH_TEXT)
836
+
837
+ # Legend β€” chromosomes in columns
838
+ handles, labels = ax.get_legend_handles_labels()
839
+ special = [(h, l) for h, l in zip(handles, labels)
840
+ if l in ('Median rΒ²', 'rΒ²= 0.2')]
841
+ chrs = [(h, l) for h, l in zip(handles, labels)
842
+ if l not in ('Median rΒ²', 'rΒ²= 0.2')]
843
+ ncols_l = max(1, (len(chrs) + 9) // 10)
844
+ leg_h = [h for h, _ in special] + [h for h, _ in chrs]
845
+ leg_l = [l for _, l in special] + [f'Chr {l}' for _, l in chrs]
846
+ ax.legend(
847
+ leg_h, leg_l,
848
+ title='Chr', title_fontsize=8,
849
+ fontsize=7, loc='upper right',
850
+ ncol=max(2, ncols_l),
851
+ framealpha=0.92, markerscale=2.2, handlelength=1.2
852
+ )
853
+
854
+ # Interpretation panel
855
+ axt.text(
856
+ 0.005, 0.98,
857
+ "LD DECAY INTERPRETATION\n" + "─" * 68 + "\n" + ld_interp,
858
+ transform=axt.transAxes, va='top', ha='left',
859
+ fontsize=8.5, color=WH_TEXT, fontfamily='monospace',
860
+ bbox=dict(boxstyle='round,pad=0.5', facecolor=WH_PANEL,
861
+ edgecolor=WH_GRID, alpha=0.98)
862
+ )
863
+
864
+ plt.savefig(save_path, dpi=110, bbox_inches='tight', facecolor=WH_BG)
865
  plt.close(fig)
866
+ return chrom_stats, ld_interp
867
 
868
 
869
  # ══════════════════════════════════════════════════════════════
870
+ # PLOT: MODEL COMPARISON
871
  # ══════════════════════════════════════════════════════════════
872
  def plot_model_comparison(model_pvals, save_path):
873
  _style_dark()
 
903
 
904
 
905
  # ══════════════════════════════════════════════════════════════
906
+ # PLOT: CIRCOS β€” WHITE BACKGROUND, CLASSIC BIOINFORMATICS STYLE
907
+ # matches reference image 2 (light bg, coloured chr ring,
908
+ # green shaded track area, black tick markers for sig SNPs)
909
  # ══════════════════════════════════════════════════════════════
910
  def plot_circos(mn_q, ch_q, pos_q, model_pvals, bonf_thresh, lod_thresh_user, save_path):
911
  """
912
+ Circos-style circular GWAS plot β€” white background, classic style.
913
+ - Outermost ring : coloured chromosome arcs with labels
914
+ - Per-model tracks: radial bars, height ∝ βˆ’log10(P)
915
+ - Light-green shaded area fills the whole track zone
916
+ - Significant SNPs: solid black tick marks (classic bioinformatics style)
917
+ - Consensus MTA : red diamond markers in inner hub
918
+ - Clean white background, navy text
919
  """
920
+ _style_white()
 
921
 
922
+ unique_chroms = sorted(
923
+ set(ch_q),
924
+ key=lambda x: (int(x) if str(x).isdigit() else 999, str(x))
925
+ )
926
  chrom_to_idx = {}
927
+ for i, c in enumerate(ch_q):
928
+ chrom_to_idx.setdefault(c, []).append(i)
929
  n_chr = len(unique_chroms)
930
 
931
+ # Angular allocation proportional to marker count
932
+ chr_len = {ch: len(chrom_to_idx[ch]) for ch in unique_chroms}
933
+ total_m = sum(chr_len.values())
934
+ GAP_DEG = 2.0
935
+ avail_deg = 360 - GAP_DEG * n_chr
936
+ chr_deg = {ch: (chr_len[ch] / total_m) * avail_deg for ch in unique_chroms}
 
937
 
938
+ marker_angle = np.zeros(len(mn_q))
 
939
  chr_start_deg = {}
940
  cur = 0.0
941
  for ch in unique_chroms:
942
  chr_start_deg[ch] = cur
943
  idxs = chrom_to_idx[ch]
944
  for rank, idx in enumerate(idxs):
945
+ marker_angle[idx] = cur + (rank / max(len(idxs) - 1, 1)) * chr_deg[ch]
946
  cur += chr_deg[ch] + GAP_DEG
947
 
948
  # Radii
949
+ R_CHR_OUTER = 0.98
950
+ R_CHR_INNER = 0.90
951
+ R_TRACK_O = 0.88
952
+ TRACK_W = 0.10
953
+ R_HUB = 0.28
954
+ R_INNER_FILL = 0.20
955
+
956
+ models = list(model_pvals.keys())
957
  n_models = len(models)
 
958
  bonf_log = -np.log10(bonf_thresh)
959
 
960
+ sig_per_model = {
961
+ mname: set(np.where(pv < bonf_thresh)[0])
962
+ for mname, pv in model_pvals.items()
963
+ }
964
 
965
+ consensus_threshold = max(1, int(np.ceil(n_models / 2)))
 
966
  sig_counts = np.zeros(len(mn_q), dtype=int)
967
  for mname in models:
968
+ for idx in sig_per_model[mname]:
969
+ sig_counts[idx] += 1
970
  consensus_idx = set(np.where(sig_counts >= consensus_threshold)[0])
971
 
972
+ fig = plt.figure(figsize=(14, 14), facecolor=WH_BG)
973
+ ax = fig.add_axes([0.05, 0.10, 0.90, 0.84], projection='polar')
974
+ ax.set_facecolor(WH_BG)
975
  ax.set_theta_zero_location('N')
976
  ax.set_theta_direction(-1)
977
+ ax.set_ylim(0, 1.08)
978
  ax.axis('off')
979
 
980
+ theta_full = np.linspace(0, 2 * np.pi, 600)
981
+
982
+ # ── Light background fill for track zone ───────────────────────────
983
+ track_o_inner = R_TRACK_O - n_models * TRACK_W
984
+ ax.fill_between(theta_full, track_o_inner, R_TRACK_O,
985
+ color='#C8E6C9', alpha=0.35, zorder=1)
986
+
987
+ # ── Chromosome arcs ────────────────────────────────────────────────
988
  for ci, ch in enumerate(unique_chroms):
989
  s_deg = chr_start_deg[ch]
990
  e_deg = s_deg + chr_deg[ch]
991
  s_rad = np.deg2rad(s_deg); e_rad = np.deg2rad(e_deg)
992
  theta_arc = np.linspace(s_rad, e_rad, 80)
993
 
994
+ col = CHROM_PALETTE_LIGHT[ci % len(CHROM_PALETTE_LIGHT)]
995
+ ax.fill_between(theta_arc, R_CHR_INNER, R_CHR_OUTER,
996
+ color=col, alpha=0.80, zorder=3)
997
+ # White gap lines between chromosomes
998
+ ax.plot([s_rad, s_rad], [R_CHR_INNER, R_CHR_OUTER],
999
+ color='white', lw=2.0, zorder=4)
1000
+ ax.plot([e_rad, e_rad], [R_CHR_INNER, R_CHR_OUTER],
1001
+ color='white', lw=2.0, zorder=4)
1002
+ ax.plot(theta_arc, [R_CHR_OUTER] * 80, color='white', lw=0.8, zorder=4)
1003
+ ax.plot(theta_arc, [R_CHR_INNER] * 80, color='white', lw=0.5, zorder=4)
1004
+
1005
+ # Chromosome label outside the arc
1006
+ mid_rad = np.deg2rad((s_deg + e_deg) / 2)
1007
+ label_r = R_CHR_OUTER + 0.038
1008
+ rot_angle = np.rad2deg(mid_rad)
1009
+ if np.pi / 2 < mid_rad < 3 * np.pi / 2:
1010
+ rot_angle += 180
1011
  ax.text(mid_rad, label_r, str(ch),
1012
  ha='center', va='center', fontsize=7.5,
1013
+ fontweight='bold', color=WH_TEXT, zorder=6,
1014
+ rotation=rot_angle - 90)
1015
+
1016
+ # Small tick marks along the arc inner edge
1017
+ n_ticks = min(8, len(chrom_to_idx[ch]))
1018
+ for tick_rad in np.linspace(s_rad, e_rad, n_ticks):
1019
+ ax.plot([tick_rad, tick_rad],
1020
+ [R_CHR_INNER - 0.010, R_CHR_INNER],
1021
+ color='#888888', lw=0.5, zorder=3)
1022
 
1023
  # ── Model tracks ───────────────────────────────────────────────────
1024
  for mi, mname in enumerate(models):
1025
+ pv = model_pvals[mname]
1026
  log_p = -np.log10(np.clip(pv, 1e-300, 1))
1027
+ mcol = MODEL_COLORS_LIGHT.get(mname, WH_ACCENT)
1028
+
1029
  r_out_track = R_TRACK_O - mi * TRACK_W
1030
+ r_in_track = r_out_track - TRACK_W + 0.008
1031
 
1032
+ # Track ring divider
1033
+ ax.plot(theta_full, [r_out_track] * 600,
1034
+ color='#AAAAAA', lw=0.6, alpha=0.5, zorder=2)
 
 
 
1035
 
1036
+ # Normalize height within track
1037
+ lp_max = max(bonf_log * 1.5, float(log_p.max()), 1.0)
1038
  norm_h = (log_p / lp_max) * TRACK_W
1039
 
1040
+ # Bonferroni dashed arc
1041
+ bonf_r = r_in_track + (bonf_log / lp_max) * TRACK_W
1042
+ ax.plot(theta_full, [bonf_r] * 600,
1043
+ color=WH_RED, lw=0.9, ls='--', alpha=0.50, zorder=3)
1044
 
1045
+ # Non-significant radial bars (model colour, thin)
1046
+ for idx in range(len(mn_q)):
1047
+ if idx in sig_per_model[mname]:
1048
+ continue
1049
+ theta = np.deg2rad(marker_angle[idx])
1050
  r_top = r_in_track + norm_h[idx]
1051
  ax.plot([theta, theta], [r_in_track, r_top],
1052
+ color=mcol, lw=0.4, alpha=0.30, zorder=3)
1053
 
1054
+ # Significant: thick black ticks (classic bioinformatics style)
1055
  for idx in sig_per_model[mname]:
1056
  theta = np.deg2rad(marker_angle[idx])
1057
+ r_top = min(r_in_track + norm_h[idx], r_out_track - 0.003)
1058
+ ax.plot([theta, theta], [r_in_track, r_top],
1059
+ color='black', lw=1.4, alpha=0.95, zorder=5)
1060
+ # Small cap dot at top
1061
+ ax.scatter(theta, r_top,
1062
+ s=12, c='black', alpha=1.0,
1063
+ edgecolors='none', zorder=6)
1064
+
1065
+ # Model name label (near top of circle, just inside chr ring)
1066
+ label_theta = np.deg2rad(1.5)
1067
+ label_r_pos = (r_in_track + r_out_track) / 2
1068
+ ax.text(label_theta, label_r_pos, mname,
1069
+ ha='left', va='center', fontsize=7.5,
1070
+ fontweight='bold', color=mcol, zorder=8)
1071
+
1072
+ # ── Bottom ring border ─────────────────────────────────────────────
1073
+ r_inner_border = R_TRACK_O - n_models * TRACK_W
1074
+ ax.plot(theta_full, [r_inner_border] * 600,
1075
+ color='#999999', lw=1.0, alpha=0.7, zorder=4)
1076
+
1077
+ # ── Consensus MTA hub: red diamonds ───────────────────────────────
1078
  for idx in consensus_idx:
1079
  theta = np.deg2rad(marker_angle[idx])
1080
+ n_sig = sig_counts[idx]
1081
+ hub_r = R_HUB + (n_sig / n_models) * 0.05
1082
+ ax.scatter(theta, hub_r,
1083
+ s=75, c=WH_RED, alpha=1.0,
1084
+ edgecolors='white', lw=0.8,
1085
+ marker='D', zorder=8)
1086
+
1087
+ # ── Inner filled white circle (clean centre) ───────────────────────
1088
+ ax.fill_between(theta_full, 0, R_INNER_FILL,
1089
+ color=WH_BG, alpha=1.0, zorder=2)
1090
+ ax.plot(theta_full, [R_INNER_FILL] * 600,
1091
+ color='#CCCCCC', lw=0.8, alpha=0.6, zorder=3)
1092
+
1093
+ # ── Centre statistics text ─────────────────────────────────────────
1094
  n_consensus = len(consensus_idx)
1095
  n_total_sig = sum(len(v) for v in sig_per_model.values())
1096
+ ax.text(0, 0,
1097
+ f'{n_consensus}\nMTA',
1098
+ ha='center', va='center', fontsize=14,
1099
+ fontweight='bold', color=WH_RED, zorder=9,
1100
  transform=ax.transData)
1101
+ ax.text(0, 0.10,
1102
+ f'{n_total_sig} sig.\nloci total',
1103
  ha='center', va='center', fontsize=8,
1104
+ color=WH_SUBTEXT, zorder=9,
1105
+ transform=ax.transData)
1106
 
1107
  # ── Legend ────────────────────────────────────────────────────────
1108
  legend_elements = [
1109
+ mpatches.Patch(facecolor=MODEL_COLORS_LIGHT.get(m, WH_ACCENT),
1110
+ edgecolor='grey', lw=0.5, label=m, alpha=0.9)
1111
  for m in models
1112
  ] + [
1113
+ plt.Line2D([0], [0], color='black', lw=2.0, label='Significant SNP'),
1114
+ mpatches.Patch(facecolor=WH_RED, edgecolor='white', lw=0.8,
1115
+ label=f'MTA consensus (β‰₯{consensus_threshold} models)'),
1116
+ plt.Line2D([0], [0], color=WH_RED, ls='--', lw=1.5,
1117
+ label='Bonferroni threshold'),
1118
  ]
1119
+ fig.legend(
1120
+ handles=legend_elements,
1121
+ loc='lower center',
1122
+ ncol=min(4, len(legend_elements)),
1123
+ fontsize=9,
1124
+ framealpha=0.95,
1125
+ facecolor=WH_BG,
1126
+ edgecolor=WH_GRID,
1127
+ bbox_to_anchor=(0.5, 0.01)
1128
+ )
1129
+
1130
+ # ── Titles ────────────────────────────────────────────────────────
1131
+ fig.text(0.5, 0.97,
1132
+ 'Circos Plot β€” Multi-Model GWAS Comparison',
1133
+ ha='center', fontsize=15, fontweight='bold', color=WH_TEXT)
1134
+ fig.text(0.5, 0.945,
1135
  f'{n_chr} chromosomes | {len(mn_q)} markers | '
1136
  f'{len(models)} models | {n_consensus} MTA consensus loci',
1137
+ ha='center', fontsize=9, color=WH_SUBTEXT)
1138
 
1139
+ # ── Interpretation text ────────────────────────────────────────────
1140
  interp_lines = [
1141
+ f"β–  Outer coloured ring = chromosomes",
1142
+ f"■ Inner rings (outer→inner): {', '.join(models)}",
1143
+ f"β–  Bar height ∝ βˆ’log₁₀(P); red dashed arc = Bonferroni threshold",
1144
+ f"β–  Black ticks = significant SNPs within that model",
1145
+ f"β–  Red diamonds (β—†) = MTA consensus: significant in β‰₯{consensus_threshold}/{n_models} models",
1146
+ f"β–  {n_total_sig} total sig. loci across all models; {n_consensus} are MTA consensus",
1147
  ]
1148
+ fig.text(
1149
+ 0.04, 0.07, "\n".join(interp_lines),
1150
+ ha='left', fontsize=8, color=WH_TEXT, fontfamily='monospace',
1151
+ bbox=dict(boxstyle='round,pad=0.6', fc=WH_PANEL, ec=WH_GRID, alpha=0.95)
1152
+ )
1153
 
1154
+ plt.savefig(save_path, dpi=110, bbox_inches='tight', facecolor=WH_BG)
1155
  plt.close(fig)
1156
 
1157
 
 
1264
  df.to_csv(csv_path,index=False)
1265
  any_sig=df[sig_cols].sum(1)>0; df[any_sig].to_csv(top_path,index=False)
1266
 
1267
+ # ── PLOTS ──────────────────────────────────────────────────────
1268
  progress(0.62, desc="Phenotype plot…")
1269
  ph_path=str(pdir/'phenotype_dist.png')
1270
  plot_phenotype(pheno_q, ph_path)
 
1371
  """
1372
  progress(1.0, desc="Done βœ…")
1373
 
 
1374
  first_man = list(man_paths.values())[0] if man_paths else None
1375
  first_qq = list(qq_paths.values())[0] if qq_paths else None
1376
 
 
1410
  .gr-box, .gr-panel {background: #161B22 !important; border-color: #21262D !important;}
1411
  """
1412
 
 
 
 
1413
  with gr.Blocks(css=CSS, title="MTA GWAS v9.0 | Dark Edition") as app:
1414
 
1415
  gr.Markdown("""
 
1458
 
1459
  summary_out = gr.Markdown()
1460
 
 
1461
  with gr.Row():
1462
  man_model_sel = gr.Dropdown(label="πŸ—ΊοΈ Manhattan β€” select model",
1463
  choices=[], value=None, interactive=True)
 
1473
  circos_out = gr.Image(label="🌐 Circos β€” Multi-Model MTA Comparison")
1474
 
1475
  with gr.Row():
1476
+ ld_out = gr.Image(label="🧬 LD Decay (White Background)")
1477
  cmp_out = gr.Image(label="βš–οΈ Model Concordance")
1478
 
1479
  with gr.Row():
1480
  ph_out = gr.Image(label="πŸ“Š Phenotype Distribution")
1481
  dl_out = gr.File(label="πŸ“¦ Download All Results (ZIP)")
1482
 
1483
+ gr.Markdown("---\n**MTA GWAS v9.0** β€” LD Decay & Circos: white background | All other plots: dark theme")
1484
 
 
1485
  man_paths_state = gr.State({})
1486
  qq_paths_state = gr.State({})
1487
 
 
1488
  run_btn.click(
1489
  fn=run_analysis,
1490
  inputs=[input_file, miss_sample, miss_marker, maf_thr,
 
1499
  show_progress="full",
1500
  )
1501
 
 
1502
  def switch_manhattan(model_name, paths):
1503
  if not model_name or not paths: return None
1504
  return paths.get(model_name)