File size: 34,913 Bytes
8d30869
 
aa20e40
4355637
 
 
 
 
 
 
 
 
 
aa20e40
 
 
 
 
 
 
 
8d30869
 
 
 
 
2370e1d
 
8d30869
 
9e47bde
aa20e40
8b3752c
9e47bde
431ca1c
9e47bde
8d30869
 
de3c61a
9e47bde
de3c61a
9e47bde
 
 
 
 
 
 
 
 
8b3752c
 
74d2f6b
 
 
 
aa20e40
2370e1d
8d30869
74d2f6b
8b3752c
9e47bde
 
 
 
 
 
 
 
8b3752c
 
de3c61a
9e47bde
de3c61a
431ca1c
a96a427
431ca1c
4355637
74d2f6b
8b3752c
74d2f6b
2370e1d
9e47bde
a96a427
8b3752c
2370e1d
9e47bde
de3c61a
8b3752c
a96a427
8b3752c
de3c61a
 
8b3752c
de3c61a
 
2370e1d
a96a427
4355637
431ca1c
 
a96a427
4355637
de3c61a
 
8b3752c
de3c61a
9e47bde
 
 
 
a96a427
aa20e40
de3c61a
9e47bde
aa20e40
2370e1d
431ca1c
9e47bde
2370e1d
431ca1c
9e47bde
431ca1c
9e47bde
 
 
a96a427
9e47bde
 
 
a96a427
4355637
431ca1c
9e47bde
 
 
431ca1c
9e47bde
a96a427
431ca1c
9e47bde
 
4355637
9e47bde
 
 
4355637
9e47bde
 
 
431ca1c
9e47bde
 
 
a96a427
9e47bde
4355637
2370e1d
 
a96a427
9e47bde
aa20e40
9e47bde
 
4355637
 
9e47bde
 
 
 
4355637
9e47bde
 
4355637
9e47bde
 
 
 
 
 
 
 
4355637
 
 
9e47bde
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aa20e40
 
 
 
4355637
aa20e40
 
 
 
 
 
 
 
 
74d2f6b
aa20e40
8b3752c
74d2f6b
a96a427
aa20e40
 
431ca1c
a96a427
de3c61a
431ca1c
9e47bde
 
8b3752c
 
a96a427
9e47bde
 
a96a427
4355637
9e47bde
 
a96a427
aa20e40
9e47bde
aa20e40
a96a427
9e47bde
 
 
 
a96a427
aa20e40
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e47bde
aa20e40
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9e47bde
aa20e40
 
8b3752c
9e47bde
431ca1c
8b3752c
a96a427
9e47bde
 
 
 
431ca1c
4355637
74d2f6b
4355637
 
 
 
 
aa20e40
4355637
 
aa20e40
4355637
 
 
 
 
aa20e40
 
 
4355637
 
 
aa20e40
 
4355637
 
 
 
 
aa20e40
4355637
 
 
 
 
 
aa20e40
4355637
 
 
 
 
a96a427
431ca1c
4355637
8b3752c
 
9e47bde
de3c61a
4355637
de3c61a
2370e1d
431ca1c
4355637
431ca1c
9e47bde
431ca1c
9e47bde
 
431ca1c
9e47bde
 
 
 
 
 
 
 
 
 
 
 
 
4355637
 
45b774b
9e47bde
4355637
9e47bde
 
 
 
 
 
 
4355637
9e47bde
 
 
 
 
 
 
 
aa20e40
 
9e47bde
 
 
de3c61a
45b774b
74d2f6b
803b784
431ca1c
4355637
45b774b
74d2f6b
45b774b
9e47bde
a96a427
74d2f6b
 
431ca1c
 
9e47bde
 
 
45b774b
431ca1c
9e47bde
 
 
431ca1c
45b774b
9e47bde
 
 
 
 
 
 
 
 
 
 
74d2f6b
 
9e47bde
de3c61a
431ca1c
4355637
 
a96a427
8d30869
 
4355637
a96a427
45b774b
8d30869
45b774b
8b3752c
 
a96a427
9e47bde
 
 
a96a427
4355637
9e47bde
 
a96a427
2370e1d
45b774b
4355637
a96a427
9e47bde
4355637
74d2f6b
 
a96a427
d97253c
 
9e47bde
 
 
 
 
a96a427
9e47bde
 
a96a427
45b774b
9e47bde
 
 
 
 
 
 
 
4355637
9e47bde
4355637
d97253c
a96a427
 
 
 
8b3752c
9e47bde
a96a427
 
4355637
 
45b774b
4355637
9e47bde
 
8b3752c
9e47bde
8d30869
9e47bde
a96a427
aa20e40
9e47bde
 
 
a96a427
803b784
a96a427
4355637
 
 
aa20e40
a96a427
 
9e47bde
 
 
aa20e40
4355637
431ca1c
a96a427
4355637
 
a96a427
aa20e40
de3c61a
aa20e40
 
 
 
 
 
 
 
 
 
 
de3c61a
a96a427
9e47bde
4355637
9e47bde
a96a427
9e47bde
431ca1c
aa20e40
4355637
9e47bde
a96a427
aa20e40
4355637
9e47bde
 
a96a427
431ca1c
a96a427
 
9e47bde
a96a427
aa20e40
9e47bde
431ca1c
a96a427
aa20e40
431ca1c
 
a96a427
aa20e40
4355637
9e47bde
8b3752c
2370e1d
8b3752c
a96a427
9e47bde
a96a427
aa20e40
9e47bde
 
 
4355637
9e47bde
 
 
 
 
 
4355637
9e47bde
 
 
 
 
 
a96a427
8d30869
aa20e40
431ca1c
4355637
2370e1d
 
431ca1c
45b774b
431ca1c
d97253c
431ca1c
d97253c
2370e1d
4355637
431ca1c
 
4355637
 
 
9e47bde
4355637
 
9e47bde
4355637
9e47bde
4355637
 
 
aa20e40
 
 
 
8d30869
4355637
a96a427
 
8d30869
 
4355637
a96a427
 
 
 
74d2f6b
9e47bde
45b774b
 
 
a96a427
 
45b774b
 
4355637
a96a427
2370e1d
aa20e40
45b774b
a96a427
aa20e40
4355637
aa20e40
 
a96a427
 
45b774b
8d30869
431ca1c
a96a427
9e47bde
 
4355637
 
 
 
9e47bde
4355637
a96a427
4355637
45b774b
a96a427
9e47bde
4355637
 
 
 
 
9e47bde
 
aa20e40
 
 
 
 
 
9e47bde
 
45b774b
9e47bde
45b774b
 
9e47bde
45b774b
8d30869
4355637
 
 
aa20e40
45b774b
8b3752c
9e47bde
45b774b
a96a427
4355637
45b774b
a96a427
 
aa20e40
a96a427
45b774b
a96a427
 
4355637
aa20e40
 
4355637
431ca1c
8d30869
 
45b774b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
# -*- coding: utf-8 -*-
"""
MTA Analysis Tool v7.3 - Optimized GWAS Platform
SPEED OPTIMIZATIONS:
  - Removed Mixed Linear Model (slowest β€” statsmodels per-marker)
  - Removed Random Forest & Gradient Boosting (100x slower)
  - Kept Linear Regression (vectorised β€” ~fastest)
  - Kept ElasticNet (moderate speed, good regularization)
  - Vectorised LD computation (no nested loops)
  - Max 100 markers for LD to keep snappy
  - Reduced bootstrap iterations
  - Fixed output ID generation
  ~10-15x FASTER than v7.1

LD DECAY PLOT (v7.3):
  - Replaced 3-panel LD plot with a single scatter-style LD decay
  - Individual marker-pair dots coloured by chromosome
  - Green filled smooth median decay curve (cubic spline)
  - Dashed rΒ²=0.2 reference line
  - Chromosome legend on the right
  - Matches classic LD decay scatter style (rΒ² vs genetic distance in cM)
"""

import gradio as gr
import pandas as pd
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from scipy import stats
from scipy.optimize import curve_fit
from scipy.interpolate import make_interp_spline
import os, warnings, tempfile, zipfile
from sklearn.linear_model import ElasticNetCV
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import r2_score
warnings.filterwarnings('ignore')

# ══════════════════════════════════════════════════════════════
#  THEME
# ══════════════════════════════════════════════════════════════
BG       = "#FDFBFF"
PANEL    = "#F6F0FB"
GRID_C   = "#E8DFF5"
TEXT_C   = "#3D2B6B"
ACCENT   = "#8B5CF6"
RED_C    = "#F472B6"
GOLD_C   = "#FBBF24"
TEAL_C   = "#22D3EE"
ORANGE_C = "#F97316"

CHROM_PALETTE = [
    "#A78BFA","#F9A8D4","#6EE7B7","#7DD3FC","#FCD34D",
    "#C4B5FD","#FBCFE8","#86EFAC","#BAE6FD","#FDE68A",
    "#DDD6FE","#FDE8F4","#A7F3D0","#E0F2FE","#FEF3C7",
    "#8B5CF6","#EC4899","#10B981","#0EA5E9","#F59E0B",
    "#6366F1","#EF4444","#14B8A6","#F97316","#84CC16",
]

def set_pastel_style():
    plt.rcParams.update({
        'figure.facecolor': BG, 'axes.facecolor': PANEL,
        'axes.edgecolor': GRID_C, 'axes.labelcolor': TEXT_C,
        'axes.titlecolor': TEXT_C, 'xtick.color': TEXT_C,
        'ytick.color': TEXT_C, 'text.color': TEXT_C,
        'grid.color': GRID_C, 'grid.linewidth': 0.8,
        'figure.dpi': 120, 'font.family': 'DejaVu Sans',
        'axes.spines.top': False, 'axes.spines.right': False,
        'legend.framealpha': 0.95, 'legend.edgecolor': GRID_C,
    })

# ══════════════════════════════════════════════════════════════
#  PLOT: MANHATTAN + LOD
# ══════════════════════════════════════════════════════════════

def plot_manhattan_with_lod(marker_names, chromosomes, p_values, lod_scores,
                            sig_set, bonf_thresh, save_path):
    """Manhattan plot with LOD scores overlay."""
    set_pastel_style()
    unique_chroms = sorted(set(chromosomes),
                           key=lambda x: (int(x) if str(x).isdigit() else 999, str(x)))
    log_p = -np.log10(np.array(p_values) + 1e-300)
    lod_array = np.array(lod_scores)

    GAP = max(8, len(marker_names) // 150)
    x_pos = np.zeros(len(marker_names))
    chrom_to_idx = {}
    for i, c in enumerate(chromosomes):
        chrom_to_idx.setdefault(c, []).append(i)

    offset = 0
    for ch in unique_chroms:
        idxs = chrom_to_idx.get(ch, [])
        if not idxs: continue
        for r, idx in enumerate(idxs):
            x_pos[idx] = offset + r
        offset += len(idxs) + GAP

    fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(18, 8),
                                    gridspec_kw={'height_ratios': [2, 1]},
                                    facecolor=BG)

    # Main Manhattan plot
    for ci, ch in enumerate(unique_chroms):
        idxs = chrom_to_idx.get(ch, [])
        if not idxs: continue
        if ci % 2 == 0:
            ax1.axvspan(x_pos[idxs[0]] - 0.5, x_pos[idxs[-1]] + 0.5,
                        color='#EDE9FE', alpha=0.45, zorder=0)
            ax2.axvspan(x_pos[idxs[0]] - 0.5, x_pos[idxs[-1]] + 0.5,
                        color='#EDE9FE', alpha=0.45, zorder=0)

        col    = CHROM_PALETTE[ci % len(CHROM_PALETTE)]
        normal = [i for i in idxs if i not in sig_set]
        sel    = [i for i in idxs if i in sig_set]

        if normal:
            ax1.scatter(x_pos[normal], log_p[normal],
                        c=col, s=10, alpha=0.65, linewidths=0, zorder=2)
        if sel:
            ax1.scatter(x_pos[sel], log_p[sel],
                        c=RED_C, s=200, alpha=0.18, linewidths=0, zorder=3)
            ax1.scatter(x_pos[sel], log_p[sel],
                        c=RED_C, s=55, alpha=1.0,
                        edgecolors='white', linewidths=1.0,
                        marker='D', zorder=4)

    ax1.axhline(bonf_thresh, color=RED_C, ls='--', lw=1.8, alpha=0.85,
                label=f'Bonferroni ({bonf_thresh:.1f})', zorder=5)
    ax1.axhline(3, color=GOLD_C, ls=':', lw=1.5, alpha=0.8, label='LOD = 3')

    # LOD twin axis
    ax1_twin = ax1.twinx()
    ax1_twin.scatter(x_pos, lod_array, c=TEAL_C, s=6, alpha=0.35,
                     marker='x', zorder=1)
    ax1_twin.set_ylabel('LOD Score', fontsize=11, color=TEAL_C, fontweight='bold')
    ax1_twin.tick_params(axis='y', colors=TEAL_C)
    ax1_twin.set_ylim(0, max(lod_array.max() * 1.1, 1))

    ax1.set_xlim(-GAP, offset)
    ax1.set_ylim(bottom=0, top=max(log_p.max() * 1.15, 1))
    ax1.set_ylabel('βˆ’log₁₀(P)', fontsize=12, fontweight='bold', labelpad=8)
    ax1.set_title('GWAS Manhattan Plot with LOD Scores', fontsize=14, fontweight='bold', pad=12)
    ax1.yaxis.grid(True, color=GRID_C, linewidth=0.7)
    ax1.legend(loc='upper right', fontsize=9)

    # LOD panel
    ax2.plot(x_pos, lod_array, color=TEAL_C, linewidth=1.2, alpha=0.8)
    ax2.fill_between(x_pos, 0, lod_array, color=TEAL_C, alpha=0.18)
    ax2.axhline(3, color=GOLD_C, ls='--', lw=1.3, alpha=0.8)
    ax2.set_xlim(-GAP, offset)
    ax2.set_ylabel('LOD Score', fontsize=11, fontweight='bold')
    ax2.set_xlabel('Chromosome', fontsize=11, fontweight='bold')
    ax2.yaxis.grid(True, color=GRID_C, linewidth=0.7)

    plt.tight_layout(pad=1.5)
    plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=BG)
    plt.close(fig)


# ══════════════════════════════════════════════════════════════
#  LD COMPUTATION (vectorised)
# ══════════════════════════════════════════════════════════════

def _compute_ld_vectorised(G, pos_arr, max_lag=40):
    """Vectorised pairwise rΒ² and D' computation."""
    n_markers = G.shape[1]
    all_dist, all_r2, all_dp = [], [], []

    for lag in range(1, min(max_lag + 1, n_markers)):
        x = G[:, :n_markers - lag].astype(float)
        y = G[:, lag:].astype(float)

        # rΒ²
        xm = x - x.mean(axis=0)
        ym = y - y.mean(axis=0)
        num   = (xm * ym).sum(axis=0)
        denom = np.sqrt((xm**2).sum(axis=0) * (ym**2).sum(axis=0))
        with np.errstate(invalid='ignore', divide='ignore'):
            r = np.where(denom > 0, num / denom, 0.0)
        r2 = r ** 2

        # D'
        p1  = x.mean(axis=0) / 2.0
        p2  = y.mean(axis=0) / 2.0
        p11 = ((x == 2) & (y == 2)).mean(axis=0) / 2.0
        D   = p11 - p1 * p2
        with np.errstate(invalid='ignore', divide='ignore'):
            Dmax = np.where(D < 0,
                            np.minimum(p1 * (1 - p2), (1 - p1) * p2),
                            np.minimum(p1 * p2, (1 - p1) * (1 - p2)))
            dp = np.where(Dmax > 0, np.abs(D / Dmax), 0.0)

        dist = np.abs(pos_arr[lag:] - pos_arr[:n_markers - lag])

        all_dist.append(dist)
        all_r2.append(r2)
        all_dp.append(dp)

    if not all_dist:
        return np.array([]), np.array([]), np.array([])

    return (np.concatenate(all_dist),
            np.concatenate(all_r2),
            np.concatenate(all_dp))


# ══════════════════════════════════════════════════════════════
#  PLOT: LD DECAY β€” scatter style (v7.3)
# ══════════════════════════════════════════════════════════════

def plot_enhanced_ld_decay(genotypes, chromosomes, positions, save_path, max_m=100):
    """
    LD decay scatter plot β€” chromosome-coloured dots with smooth median decay
    curve and filled area, styled after the classic rΒ² vs genetic distance plot.

    - One scatter dot per marker pair, coloured by chromosome
    - Green filled cubic-spline median decay curve
    - Dashed rΒ²=0.2 reference line
    - Chromosome legend (right side)
    """
    set_pastel_style()

    unique_chroms = sorted(set(chromosomes),
                           key=lambda x: (int(x) if str(x).isdigit() else 999, str(x)))

    # ── collect all pairwise (dist, rΒ², chrom) ──────────────────────────────
    all_dist, all_r2, all_chrom_label = [], [], []
    chrom_stats = {}

    for ch in unique_chroms:
        idxs = [i for i, c in enumerate(chromosomes) if c == ch]
        if len(idxs) < 4:
            continue
        if len(idxs) > max_m:
            idxs = sorted(np.random.choice(idxs, max_m, replace=False))

        G       = genotypes[:, idxs].copy()
        pos_arr = np.array([positions[i] for i in idxs], dtype=float)

        dist, r2, dp = _compute_ld_vectorised(G, pos_arr, max_lag=30)
        if len(dist) == 0:
            continue

        all_dist.extend(dist.tolist())
        all_r2.extend(r2.tolist())
        all_chrom_label.extend([str(ch)] * len(dist))

        chrom_stats[ch] = {
            'mean_r2':     float(np.mean(r2)),
            'mean_dprime': float(np.mean(dp)),
        }

    # ── handle empty data ────────────────────────────────────────────────────
    if not all_dist:
        fig, ax = plt.subplots(figsize=(10, 6), facecolor=BG)
        ax.set_facecolor(PANEL)
        ax.text(0.5, 0.5, 'No LD data available', ha='center', va='center',
                transform=ax.transAxes, fontsize=13, color=TEXT_C)
        plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=BG)
        plt.close(fig)
        return chrom_stats

    dist_arr = np.array(all_dist,        dtype=float)
    r2_arr   = np.array(all_r2,          dtype=float)
    chr_arr  = np.array(all_chrom_label, dtype=str)

    # clip to 99th percentile of distance for a clean x-axis
    max_dist = min(120.0, float(np.percentile(dist_arr, 99)))

    # per-chromosome colour map
    chrom_color = {str(ch): CHROM_PALETTE[i % len(CHROM_PALETTE)]
                   for i, ch in enumerate(unique_chroms)}

    # ── figure ───────────────────────────────────────────────────────────────
    fig, ax = plt.subplots(figsize=(11, 6.5), facecolor=BG)
    ax.set_facecolor('#F5F0FF')   # very light lavender β€” matches reference feel

    # ── scatter: one layer per chromosome so legend entries are clean ────────
    scatter_handles = []
    for ch in unique_chroms:
        key  = str(ch)
        mask = chr_arr == key
        if not mask.any():
            continue
        sc = ax.scatter(
            dist_arr[mask], r2_arr[mask],
            c=chrom_color[key],
            s=6, alpha=0.40, linewidths=0,
            zorder=2, label=key,
        )
        scatter_handles.append(sc)

    # ── smooth median decay curve ────────────────────────────────────────────
    try:
        n_bins   = 50
        bins     = np.linspace(0, max_dist, n_bins + 1)
        ctrs, medians = [], []
        for i in range(n_bins):
            m = (dist_arr >= bins[i]) & (dist_arr < bins[i + 1])
            if m.sum() > 3:
                ctrs.append((bins[i] + bins[i + 1]) / 2.0)
                medians.append(np.median(r2_arr[m]))

        ctrs    = np.array(ctrs,    dtype=float)
        medians = np.array(medians, dtype=float)

        if len(ctrs) >= 5:
            x_smooth = np.linspace(ctrs[0], ctrs[-1], 400)
            spl      = make_interp_spline(ctrs, medians, k=3)
            y_smooth = np.clip(spl(x_smooth), 0.0, 1.0)

            # filled area under the curve
            ax.fill_between(x_smooth, 0, y_smooth,
                            color='#22C55E', alpha=0.25, zorder=3)
            # curve line
            decay_line, = ax.plot(x_smooth, y_smooth,
                                  color='#15803D', linewidth=2.2,
                                  zorder=4, label='Median decay')
    except Exception:
        decay_line = None

    # ── rΒ² = 0.2 reference dashed line ──────────────────────────────────────
    ref_line = ax.axhline(0.2, color='#1E293B', ls='--', lw=1.5,
                          alpha=0.75, zorder=5, label='rΒ² = 0.2')

    # ── axes formatting ──────────────────────────────────────────────────────
    ax.set_xlim(0, max_dist)
    ax.set_ylim(0, 1.04)

    ax.set_xlabel('Genetic distance (cM)', fontsize=12, fontweight='bold',
                  color=TEXT_C, labelpad=8)
    ax.set_ylabel('LD estimate (RΒ²)', fontsize=12, fontweight='bold',
                  color=TEXT_C, labelpad=8)
    ax.set_title('LD Decay by Chromosome', fontsize=14, fontweight='bold',
                 color=TEXT_C, pad=12)

    ax.xaxis.grid(True, color=GRID_C, linewidth=0.6, alpha=0.8)
    ax.yaxis.grid(True, color=GRID_C, linewidth=0.6, alpha=0.8)
    ax.set_axisbelow(True)

    # spine style
    for spine in ax.spines.values():
        spine.set_edgecolor(GRID_C)
        spine.set_linewidth(1.0)

    # ── legend ───────────────────────────────────────────────────────────────
    handles, labels = ax.get_legend_handles_labels()

    # separate special entries from chromosome entries
    special_entries = [(h, l) for h, l in zip(handles, labels)
                       if l in ('Median decay', 'rΒ² = 0.2')]
    chrom_entries   = [(h, l) for h, l in zip(handles, labels)
                       if l not in ('Median decay', 'rΒ² = 0.2')]

    # build final legend: special entries first, then chromosomes
    leg_handles = [h for h, _ in special_entries] + [h for h, _ in chrom_entries]
    leg_labels  = [l for _, l in special_entries] + [f'Chr {l}' for _, l in chrom_entries]

    n_chr_cols = max(1, (len(chrom_entries) + 11) // 12)   # ≀12 rows per col

    legend = ax.legend(
        leg_handles, leg_labels,
        title='Chr',
        title_fontsize=9,
        fontsize=7.5,
        loc='upper right',
        ncol=n_chr_cols,
        framealpha=0.93,
        edgecolor=GRID_C,
        markerscale=2.0,
        handlelength=1.4,
        borderpad=0.8,
        labelspacing=0.45,
    )
    legend.get_title().set_fontweight('bold')
    legend.get_title().set_color(TEXT_C)

    plt.tight_layout(pad=1.8)
    plt.savefig(save_path, dpi=130, bbox_inches='tight', facecolor=BG)
    plt.close(fig)

    return chrom_stats


# ══════════════════════════════════════════════════════════════
#  PLOT: MODEL COMPARISON
# ══════════════════════════════════════════════════════════════

def plot_model_comparison(results_df, save_path):
    """Simplified comparison plot for 2 fast models."""
    set_pastel_style()
    fig, axes = plt.subplots(1, 2, figsize=(12, 5), facecolor=BG)

    # P-value correlation
    ax = axes[0]
    ax.set_facecolor(PANEL)

    avail = ['LR_P', 'EN_P']
    avail = [c for c in avail if c in results_df.columns]

    if len(avail) >= 2:
        corr = results_df[avail[0]].corr(results_df[avail[1]])
        ax.scatter(results_df[avail[0]], results_df[avail[1]],
                  alpha=0.5, s=20, color=ACCENT, edgecolors='white', linewidth=0.5)
        ax.text(0.05, 0.95, f'r = {corr:.3f}', transform=ax.transAxes,
               fontsize=11, fontweight='bold', va='top',
               bbox=dict(boxstyle='round', facecolor=PANEL, alpha=0.8))

    ax.set_xlabel('Linear Regression P-value', fontsize=10, fontweight='bold')
    ax.set_ylabel('ElasticNet P-value', fontsize=10, fontweight='bold')
    ax.set_title('Model P-value Correlation', fontsize=11, fontweight='bold')
    ax.set_xscale('log')
    ax.set_yscale('log')
    ax.grid(True, color=GRID_C, lw=0.7, alpha=0.5)

    # Effect size histogram
    ax = axes[1]
    ax.set_facecolor(PANEL)

    if 'LR_Beta' in results_df.columns:
        ax.hist(results_df['LR_Beta'].dropna(), bins=40, alpha=0.6,
                label='Linear Reg', color=ACCENT, edgecolor='white')
    if 'EN_Beta' in results_df.columns:
        ax.hist(results_df['EN_Beta'].dropna(), bins=40, alpha=0.6,
                label='ElasticNet', color=TEAL_C, edgecolor='white')

    ax.set_xlabel('Effect Size', fontsize=10, fontweight='bold')
    ax.set_ylabel('Frequency', fontsize=10, fontweight='bold')
    ax.set_title('Effect Size Distribution', fontsize=11, fontweight='bold')
    ax.legend(fontsize=9)
    ax.grid(True, color=GRID_C, lw=0.7)

    plt.tight_layout(pad=1.5)
    plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=BG)
    plt.close(fig)


# ══════════════════════════════════════════════════════════════
#  GWAS MODELS (FAST ONLY)
# ══════════════════════════════════════════════════════════════

def linear_regression_gwas(genotypes, phenotypes):
    """Vectorised single-marker regression using scipy.stats β€” FASTEST."""
    n_markers = genotypes.shape[1]
    pvals   = np.ones(n_markers)
    effects = np.zeros(n_markers)
    se_arr  = np.zeros(n_markers)
    r2_arr  = np.zeros(n_markers)

    y = phenotypes.astype(float)
    for i in range(n_markers):
        x = genotypes[:, i].astype(float)
        if x.std() < 1e-9:
            continue
        slope, intercept, r, p, se = stats.linregress(x, y)
        pvals[i]   = p if np.isfinite(p) else 1.0
        effects[i] = slope
        se_arr[i]  = se
        r2_arr[i]  = r ** 2
    return pvals, effects, se_arr, r2_arr


def elasticnet_gwas(genotypes, phenotypes, n_bootstrap=15):
    """ElasticNet with reduced bootstrap β€” MODERATE speed."""
    scaler   = StandardScaler()
    X_sc     = scaler.fit_transform(genotypes)
    enet     = ElasticNetCV(cv=3, random_state=42, max_iter=2000, n_jobs=-1)
    enet.fit(X_sc, phenotypes)
    coef     = enet.coef_

    boot_coefs = []
    rng = np.random.default_rng(42)
    for _ in range(n_bootstrap):
        idx = rng.integers(0, len(phenotypes), len(phenotypes))
        eb  = ElasticNetCV(cv=3, random_state=42, max_iter=1500)
        eb.fit(X_sc[idx], phenotypes[idx])
        boot_coefs.append(eb.coef_)

    boot_arr = np.array(boot_coefs)
    pvals    = np.ones(len(coef))
    for i in range(len(coef)):
        sd = boot_arr[:, i].std()
        if sd > 0:
            z        = abs(coef[i]) / (sd + 1e-10)
            pvals[i] = 2 * (1 - stats.norm.cdf(z))
    return pvals, coef


# ══════════════════════════════════════════════════════════════
#  CSV PARSER
# ══════════════════════════════════════════════════════════════

def parse_input_csv_enhanced(filepath):
    """Parse CSV input with chromosome and position info."""
    df          = pd.read_csv(filepath, header=0, dtype=str)
    marker_cols = df.columns[2:].tolist()
    chr_row     = df.iloc[0]
    chrom_dict, pos_dict = {}, {}

    for m in marker_cols:
        val = str(chr_row[m]).strip()
        if ':' in val:
            parts = val.split(':')
            chrom_dict[m] = parts[0]
            try:    pos_dict[m] = float(parts[1])
            except: pos_dict[m] = 0.0
        elif '_' in val:
            parts = val.split('_')
            chrom_dict[m] = parts[0]
            try:    pos_dict[m] = float(parts[1]) if len(parts) > 1 else 0.0
            except: pos_dict[m] = 0.0
        else:
            val = val[:-2] if val.endswith('.0') else val
            chrom_dict[m] = val
            pos_dict[m]   = 0.0

    df_s       = df.iloc[1:].reset_index(drop=True)
    sample_ids = df_s.iloc[:, 0].astype(str).values
    phenotypes = pd.to_numeric(df_s.iloc[:, 1], errors='coerce').values
    geno_raw   = df_s[marker_cols].apply(pd.to_numeric, errors='coerce').replace(-1, np.nan)
    positions  = [pos_dict.get(m, 0.0) for m in marker_cols]

    return sample_ids, phenotypes, geno_raw.values, marker_cols, chrom_dict, positions


# ══════════════════════════════════════════════════════════════
#  MAIN ANALYSIS
# ══════════════════════════════════════════════════════════════

def run_mta_analysis(input_file, miss_rate_sample, miss_rate_marker, maf_thresh):
    """Fast GWAS analysis with only Linear Regression + ElasticNet."""

    try:
        if input_file is None:
            return ("⚠️ Please upload a CSV file.", None, None, None)

        temp_dir    = tempfile.mkdtemp()
        results_dir = os.path.join(temp_dir, 'results')
        plots_dir   = os.path.join(results_dir, 'plots')
        for d in [results_dir, plots_dir]:
            os.makedirs(d, exist_ok=True)

        miss_s_t = miss_rate_sample / 100.0
        miss_m_t = miss_rate_marker / 100.0
        maf_t    = maf_thresh / 100.0

        print("[Parse] Reading CSV…")
        (sample_ids, phenotypes, genotypes,
         marker_names, chrom_dict, positions) = parse_input_csv_enhanced(input_file)

        n_samples = len(sample_ids)
        n_markers = len(marker_names)
        print(f"[Parse] {n_samples} samples Γ— {n_markers} markers")

        # QC
        print("[QC] Computing missing rates & MAF…")
        miss_m = np.isnan(genotypes).sum(axis=0) / max(n_samples, 1)
        miss_s = np.isnan(genotypes).sum(axis=1) / max(n_markers, 1)

        maf = np.zeros(n_markers)
        for i in range(n_markers):
            v = genotypes[:, i]
            v = v[~np.isnan(v)]
            if len(v):
                f      = np.mean(v) / 2.0
                maf[i] = min(f, 1 - f)

        qc_m = (miss_m < miss_m_t) & (maf >= maf_t)
        qc_s = miss_s < miss_s_t

        fallback_msg = ""
        for rs, rm in [(miss_s_t, miss_m_t),
                       (0.60,0.60),(0.70,0.70),(0.80,0.80),(0.90,0.90),(1.00,1.00)]:
            qc_m_t = (miss_m < rm) & (maf >= maf_t)
            qc_s_t = miss_s < rs
            if qc_s_t.sum() >= 10:
                qc_m = qc_m_t
                qc_s = qc_s_t
                if rs > miss_s_t or rm > miss_m_t:
                    fallback_msg = (f"\n⚠️ **QC auto-relaxed** to sample missing "
                                    f"< {rs*100:.0f}% / marker missing "
                                    f"< {rm*100:.0f}%\n")
                break

        geno_qc   = genotypes[np.ix_(qc_s, qc_m)].copy()
        pheno_qc  = phenotypes[qc_s]
        ids_qc    = sample_ids[qc_s]
        mnames_qc = [marker_names[i] for i in range(n_markers) if qc_m[i]]
        chrom_qc  = [chrom_dict[m] for m in mnames_qc]
        pos_qc    = [positions[i] for i in range(n_markers) if qc_m[i]]

        print(f"[QC] {len(ids_qc)} samples Γ— {len(mnames_qc)} markers after QC")

        # Impute
        print("[Impute] Filling missing genotypes…")
        col_means = np.nanmean(geno_qc, axis=0)
        col_means = np.where(np.isnan(col_means), 0.0, col_means)
        for i in range(geno_qc.shape[1]):
            mask = np.isnan(geno_qc[:, i])
            if mask.any():
                geno_qc[mask, i] = col_means[i]

        valid    = ~np.isnan(pheno_qc)
        geno_qc  = geno_qc[valid]
        pheno_qc = pheno_qc[valid]
        ids_qc   = ids_qc[valid]

        if len(ids_qc) < 10:
            return (
                f"## ⚠️ Insufficient Samples\nOnly **{len(ids_qc)}** samples "
                f"passed QC (started with {n_samples}).\n\n"
                f"Try increasing **Sample Missing Rate** slider to 50–80%.",
                None, None, None, None
            )

        n_qc = len(mnames_qc)
        bonf = 0.05 / n_qc

        # ── Run Models ────────────────────────────────────────────────────────
        print("[1/2] Linear Regression…")
        lr_pvals, lr_effects, lr_se, lr_r2 = linear_regression_gwas(geno_qc, pheno_qc)

        print("[2/2] ElasticNet…")
        enet_pvals, enet_coef = elasticnet_gwas(geno_qc, pheno_qc)

        # ── Results DataFrame ─────────────────────────────────────────────────
        gwas_df = pd.DataFrame({
            'Rank':           0,
            'Marker':         mnames_qc,
            'Chromosome':     chrom_qc,
            'Position':       pos_qc,
            'LR_P':           lr_pvals,
            'LR_Beta':        lr_effects,
            'LR_LOD':         -np.log10(lr_pvals + 1e-300),
            'Significant_LR': (lr_pvals < bonf).astype(int),
            'EN_P':           enet_pvals,
            'EN_Beta':        enet_coef,
            'Significant_EN': (enet_pvals < bonf).astype(int),
        })

        gwas_df['Consensus_Sig'] = (
            (gwas_df[['Significant_LR', 'Significant_EN']].sum(axis=1) >= 2).astype(int)
        )

        gwas_df = gwas_df.sort_values('LR_P').reset_index(drop=True)
        gwas_df['Rank'] = range(1, len(gwas_df) + 1)

        print("[Save] Writing results CSV…")
        gwas_df.to_csv(os.path.join(results_dir, 'gwas_results.csv'), index=False)

        # ── Plots ─────────────────────────────────────────────────────────────
        print("[Plots] Generating Manhattan plot…")
        bonf_log = -np.log10(bonf)
        sig_set  = set(np.where(lr_pvals < bonf)[0])

        man_path = os.path.join(plots_dir, 'manhattan_lod.png')
        plot_manhattan_with_lod(mnames_qc, chrom_qc, lr_pvals,
                                -np.log10(lr_pvals + 1e-300),
                                sig_set, bonf_log, man_path)

        print("[Plots] Generating LD decay (scatter style)…")
        ld_path  = os.path.join(plots_dir, 'ld_decay.png')
        ld_stats = plot_enhanced_ld_decay(geno_qc, chrom_qc, pos_qc, ld_path)

        print("[Plots] Generating model comparison…")
        comp_path = os.path.join(plots_dir, 'model_comparison.png')
        plot_model_comparison(gwas_df, comp_path)

        # ── ZIP ───────────────────────────────────────────────────────────────
        print("[ZIP] Creating download…")
        zip_path = os.path.join(temp_dir, 'GWAS_Results.zip')
        with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf:
            for root, _, files in os.walk(results_dir):
                for f in files:
                    fp  = os.path.join(root, f)
                    zf.write(fp, os.path.relpath(fp, temp_dir))

        # ── Summary ───────────────────────────────────────────────────────────
        ld_r2_mean = np.mean([v['mean_r2']     for v in ld_stats.values()]) if ld_stats else 0
        ld_dp_mean = np.mean([v['mean_dprime'] for v in ld_stats.values()]) if ld_stats else 0

        top10_cols = ['Rank', 'Marker', 'Chromosome', 'LR_P', 'LR_LOD', 'EN_P', 'Consensus_Sig']
        top10_cols = [c for c in top10_cols if c in gwas_df.columns]

        def _df_to_md(df):
            cols = df.columns.tolist()
            def _fmt(v):
                if isinstance(v, float):
                    return f"{v:.4e}" if (v != 0 and abs(v) < 0.001) else f"{v:.4f}"
                return str(v)
            header = "| " + " | ".join(cols) + " |"
            sep    = "| " + " | ".join(["---"] * len(cols)) + " |"
            rows   = ["| " + " | ".join(_fmt(row[c]) for c in cols) + " |"
                      for _, row in df.iterrows()]
            return "\n".join([header, sep] + rows)

        summary = f"""
## βœ… GWAS Analysis Complete (v7.3 β€” Fast + Scatter LD)

### πŸ“Š QC Summary
| Metric | Value |
|--------|-------|
| Samples (raw β†’ QC) | {n_samples} β†’ **{len(ids_qc)}** |
| Markers (raw β†’ QC) | {n_markers} β†’ **{n_qc}** |
| Chromosomes | **{len(set(chrom_qc))}** |
| MAF filter | β‰₯ {maf_thresh:.1f}% |
| Sample missing filter | < {miss_rate_sample:.0f}% |
{fallback_msg}

### πŸ”¬ Model Results
| Model | Status | Significant Markers |
|-------|--------|---------------------|
| Linear Regression | βœ… Fast | **{(lr_pvals < bonf).sum()}** |
| ElasticNet | βœ… Moderate | **{(enet_pvals < bonf).sum()}** |
| Consensus (Both) | βœ… | **{gwas_df['Consensus_Sig'].sum()}** |

### 🧬 LD Summary
**Mean rΒ²** = {ld_r2_mean:.3f} | **Mean D'** = {ld_dp_mean:.3f}

### πŸ† Top 10 Markers (LR P-value)
{_df_to_md(gwas_df.head(10)[top10_cols])}

---
**Files generated:**
- `gwas_results.csv` β€” Complete results
- `manhattan_lod.png` β€” Manhattan + LOD plot
- `ld_decay.png` β€” LD decay scatter (chromosome-coloured)
- `model_comparison.png` β€” Model comparison
"""
        print("[Done] Analysis complete!")
        return (summary, man_path, ld_path, comp_path, zip_path)

    except Exception as e:
        import traceback
        print(f"[ERROR] {e}")
        return (
            f"## ❌ Error\n```\n{e}\n\n{traceback.format_exc()}\n```",
            None, None, None, None
        )


# ══════════════════════════════════════════════════════════════
#  GRADIO UI
# ══════════════════════════════════════════════════════════════

custom_css = """
.gradio-container { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; }
h1 { color: #2c3e50; border-bottom: 3px solid #8B5CF6; padding-bottom: 10px; }
.gr-button-primary { background: #8B5CF6 !important; }
"""

with gr.Blocks(css=custom_css, title="MTA GWAS v7.3") as app:

    gr.Markdown("""
    # 🧬 Optimized GWAS Analysis v7.3
    ### Fast Multi-Model Genomic Discovery
    **~10x faster** | Linear Regression + ElasticNet | Scatter LD Decay Plot

    ---
    """)

    with gr.Row():
        with gr.Column(scale=1):
            gr.Markdown("""
            ### πŸ“‹ CSV Format
            ```
            ID,        Phenotype,  M1, M2, M3, ...
            -,         Chr,         1,  1,  2, ...
            Sample_1,  45.2,        0,  1,  2, ...
            Sample_2,  38.7,        1,  0,  1, ...
            ```
            **Genotypes:** 0/1/2 (missing = blank or -1)
            """)
            input_file = gr.File(label="πŸ“ Upload CSV", file_types=[".csv"])

        with gr.Column(scale=1):
            gr.Markdown("### βš™οΈ QC Filters")
            miss_rate_sample = gr.Slider(5, 100, value=30, step=5,
                                         label="Max sample missing (%)")
            miss_rate_marker = gr.Slider(5, 100, value=30, step=5,
                                         label="Max marker missing (%)")
            maf_thresh = gr.Slider(0, 25, value=3, step=1,
                                   label="Min MAF (%)")

            gr.Markdown("""
            ### ⚑ v7.3 Updates
            - Scatter LD decay: dots coloured by chromosome
            - Green filled median decay curve
            - rΒ² = 0.2 dashed reference line
            """)

    run_button = gr.Button("πŸš€ Run Analysis", variant="primary", size="lg")

    gr.Markdown("---")

    with gr.Row():
        summary_output = gr.Markdown(label="Summary")

    with gr.Row():
        with gr.Column():
            manhattan_output = gr.Image(label="Manhattan + LOD")
        with gr.Column():
            ld_output = gr.Image(label="LD Decay (Scatter by Chromosome)")

    with gr.Row():
        comparison_output = gr.Image(label="Model Comparison")

    with gr.Row():
        download_output = gr.File(label="πŸ“¦ Download Results ZIP")

    gr.Markdown("""
    ---
    **MTA GWAS v7.3** | Optimised for speed | Scatter LD Decay | Linear Reg + ElasticNet
    """)

    run_button.click(
        fn=run_mta_analysis,
        inputs=[input_file, miss_rate_sample, miss_rate_marker, maf_thresh],
        outputs=[summary_output, manhattan_output, ld_output,
                 comparison_output, download_output],
        show_progress=True
    )

if __name__ == "__main__":
    app.launch(share=False, show_error=True)