Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,6 +1,3 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
| 4 |
import gradio as gr
|
| 5 |
import pandas as pd
|
| 6 |
import numpy as np
|
|
@@ -608,10 +605,7 @@ def fig_to_png_bytes(fig):
|
|
| 608 |
return data
|
| 609 |
|
| 610 |
def _compute_x_coords(chroms, positions, chrom_list):
|
| 611 |
-
"""
|
| 612 |
-
FIX: Chromosome x-coords now start from chromosome 1 (not 0).
|
| 613 |
-
Each chromosome occupies its own x-axis segment with a small gap.
|
| 614 |
-
"""
|
| 615 |
x_coords = np.zeros(len(chroms))
|
| 616 |
x_offset = 0
|
| 617 |
max_pos = max(positions) if len(positions) > 0 else 1
|
|
@@ -620,9 +614,8 @@ def _compute_x_coords(chroms, positions, chrom_list):
|
|
| 620 |
if not mask.any():
|
| 621 |
continue
|
| 622 |
pos = positions[mask]
|
| 623 |
-
#
|
| 624 |
-
|
| 625 |
-
x_coords[mask] = pos - pos.min() + x_offset + 1 # +1 ensures start from 1
|
| 626 |
x_offset += pos.max() - pos.min() + max_pos * 0.02 + 1
|
| 627 |
return x_coords
|
| 628 |
|
|
@@ -642,7 +635,7 @@ def compute_lambda(pvals):
|
|
| 642 |
/ stats.chi2.ppf(0.5, df=1))
|
| 643 |
|
| 644 |
def select_best_models(all_results, n_best=4):
|
| 645 |
-
"""Select best-performing models based on lambda closest to 1.0
|
| 646 |
scores = {}
|
| 647 |
for mname, (pvals, betas, ses) in all_results.items():
|
| 648 |
lam = compute_lambda(pvals)
|
|
@@ -656,260 +649,13 @@ def select_best_models(all_results, n_best=4):
|
|
| 656 |
best = sorted(scores.keys(), key=lambda m: scores[m])[:n_best]
|
| 657 |
return best
|
| 658 |
|
| 659 |
-
# βββββββββββββββββββββββ
|
| 660 |
-
def plot_manhattan_interactive(pvals, chroms, positions, snp_names, title="Manhattan Plot", model_name=""):
|
| 661 |
-
"""
|
| 662 |
-
FIX: x-axis now starts from chromosome 1 (not 0).
|
| 663 |
-
Uses _compute_x_coords which adds +1 offset so no SNP lands at x=0.
|
| 664 |
-
"""
|
| 665 |
-
log_p = -np.log10(np.clip(pvals, 1e-300, 1))
|
| 666 |
-
sig_line = -np.log10(5e-8)
|
| 667 |
-
sug_line = -np.log10(1e-5)
|
| 668 |
-
chrom_list = sorted(set(chroms))
|
| 669 |
-
x_coords = _compute_x_coords(chroms, positions, chrom_list)
|
| 670 |
-
|
| 671 |
-
fig = go.Figure()
|
| 672 |
-
|
| 673 |
-
for ci, ch in enumerate(chrom_list):
|
| 674 |
-
mask = chroms == ch
|
| 675 |
-
col = CHR_PALETTE[ci % len(CHR_PALETTE)]
|
| 676 |
-
xc = x_coords[mask]
|
| 677 |
-
yc = log_p[mask]
|
| 678 |
-
nm = [str(snp_names[i]) for i in np.where(mask)[0]]
|
| 679 |
-
pc = [float(pvals[i]) for i in np.where(mask)[0]]
|
| 680 |
-
|
| 681 |
-
sig_m = yc >= sig_line
|
| 682 |
-
ns_m = ~sig_m
|
| 683 |
-
|
| 684 |
-
if ns_m.any():
|
| 685 |
-
fig.add_trace(go.Scatter(
|
| 686 |
-
x=xc[ns_m], y=yc[ns_m],
|
| 687 |
-
mode='markers',
|
| 688 |
-
marker=dict(color=col, size=5, opacity=0.75, line=dict(width=0)),
|
| 689 |
-
name=f"Chr{ch}",
|
| 690 |
-
text=[f"SNP: {nm[i]}<br>Chr: {ch}<br>p-value: {pc[i]:.3e}<br>-log10(p): {yc[ns_m][i]:.2f}"
|
| 691 |
-
for i in range(ns_m.sum())],
|
| 692 |
-
hovertemplate="%{text}<extra></extra>",
|
| 693 |
-
showlegend=(ci < 15),
|
| 694 |
-
))
|
| 695 |
-
if sig_m.any():
|
| 696 |
-
fig.add_trace(go.Scatter(
|
| 697 |
-
x=xc[sig_m], y=yc[sig_m],
|
| 698 |
-
mode='markers',
|
| 699 |
-
marker=dict(color='#FF1744', size=10, symbol='diamond',
|
| 700 |
-
line=dict(color='#7F0000', width=1)),
|
| 701 |
-
name=f"Sig (Chr{ch})",
|
| 702 |
-
text=[f"<b>SIGNIFICANT</b><br>SNP: {nm[i]}<br>Chr: {ch}<br>p-value: {pc[i]:.3e}<br>-log10(p): {yc[sig_m][i]:.2f}"
|
| 703 |
-
for i in range(sig_m.sum())],
|
| 704 |
-
hovertemplate="%{text}<extra></extra>",
|
| 705 |
-
showlegend=False,
|
| 706 |
-
))
|
| 707 |
-
|
| 708 |
-
x_max = x_coords.max() if len(x_coords) > 0 else 1
|
| 709 |
-
x_min = 1 # FIX: x-axis starts at 1
|
| 710 |
-
|
| 711 |
-
fig.add_shape(type="line", x0=x_min, x1=x_max, y0=sig_line, y1=sig_line,
|
| 712 |
-
line=dict(color="#FF4560", width=2, dash="dash"))
|
| 713 |
-
fig.add_shape(type="line", x0=x_min, x1=x_max, y0=sug_line, y1=sug_line,
|
| 714 |
-
line=dict(color="#00D9E9", width=1.5, dash="dot"))
|
| 715 |
-
fig.add_annotation(x=x_max*0.98, y=sig_line+0.3, text="GW significant (5Γ10β»βΈ)",
|
| 716 |
-
showarrow=False, font=dict(color="#FF4560", size=11),
|
| 717 |
-
xanchor="right")
|
| 718 |
-
fig.add_annotation(x=x_max*0.98, y=sug_line+0.3, text="Suggestive (1Γ10β»β΅)",
|
| 719 |
-
showarrow=False, font=dict(color="#00D9E9", size=11),
|
| 720 |
-
xanchor="right")
|
| 721 |
-
|
| 722 |
-
tick_pos, tick_lab = _compute_tick_positions(x_coords, chroms, chrom_list)
|
| 723 |
-
|
| 724 |
-
lam = compute_lambda(pvals)
|
| 725 |
-
n_sig = int((pvals < 5e-8).sum())
|
| 726 |
-
|
| 727 |
-
fig.update_layout(
|
| 728 |
-
title=dict(
|
| 729 |
-
text=f"<b>{title} β {model_name}</b><br><sup>Ξ» = {lam:.4f} | Significant SNPs: {n_sig} | Total: {len(pvals)}</sup>",
|
| 730 |
-
font=dict(size=16, color="#1E293B"),
|
| 731 |
-
),
|
| 732 |
-
xaxis=dict(
|
| 733 |
-
tickmode='array',
|
| 734 |
-
tickvals=tick_pos,
|
| 735 |
-
ticktext=tick_lab,
|
| 736 |
-
tickangle=45,
|
| 737 |
-
tickfont=dict(size=10),
|
| 738 |
-
showgrid=False,
|
| 739 |
-
zeroline=False,
|
| 740 |
-
title="Chromosome",
|
| 741 |
-
range=[0, x_max * 1.01], # FIX: start near 0 but data from 1
|
| 742 |
-
),
|
| 743 |
-
yaxis=dict(
|
| 744 |
-
title="-logββ(p-value)",
|
| 745 |
-
gridcolor="#E2E8F0",
|
| 746 |
-
gridwidth=0.5,
|
| 747 |
-
),
|
| 748 |
-
plot_bgcolor="white",
|
| 749 |
-
paper_bgcolor="white",
|
| 750 |
-
height=520,
|
| 751 |
-
legend=dict(
|
| 752 |
-
orientation="h",
|
| 753 |
-
yanchor="bottom",
|
| 754 |
-
y=1.02,
|
| 755 |
-
xanchor="right",
|
| 756 |
-
x=1,
|
| 757 |
-
font=dict(size=9),
|
| 758 |
-
),
|
| 759 |
-
hovermode="closest",
|
| 760 |
-
margin=dict(l=60, r=40, t=100, b=80),
|
| 761 |
-
)
|
| 762 |
-
return fig
|
| 763 |
-
|
| 764 |
-
# βββββββββββββββββββββββ INTERACTIVE QQ PLOT ββββββββββββββββββββββββββββββββββ
|
| 765 |
-
def plot_qq_interactive_single(pvals, model_name="", color=None):
|
| 766 |
-
"""Interactive QQ plot with confidence band."""
|
| 767 |
-
if color is None:
|
| 768 |
-
color = "#775DD0"
|
| 769 |
-
n = len(pvals)
|
| 770 |
-
obs_raw = -np.log10(np.clip(pvals, 1e-300, 1))
|
| 771 |
-
sort_i = np.argsort(obs_raw)[::-1]
|
| 772 |
-
obs = obs_raw[sort_i]
|
| 773 |
-
exp = -np.log10(np.arange(1, n + 1) / n)
|
| 774 |
-
|
| 775 |
-
ranks = np.arange(1, n + 1)
|
| 776 |
-
ci_lo = -np.log10(stats.beta.ppf(0.975, ranks, n - ranks + 1))
|
| 777 |
-
ci_hi = -np.log10(stats.beta.ppf(0.025, ranks, n - ranks + 1))
|
| 778 |
-
|
| 779 |
-
lam = compute_lambda(pvals)
|
| 780 |
-
lam_col = "green" if lam <= 1.05 else "orange" if lam <= 1.15 else "red"
|
| 781 |
-
sig_thr = -np.log10(5e-8)
|
| 782 |
-
|
| 783 |
-
fig = go.Figure()
|
| 784 |
-
|
| 785 |
-
fig.add_trace(go.Scatter(
|
| 786 |
-
x=np.concatenate([exp, exp[::-1]]),
|
| 787 |
-
y=np.concatenate([ci_hi, ci_lo[::-1]]),
|
| 788 |
-
fill='toself',
|
| 789 |
-
fillcolor='rgba(120,120,180,0.15)',
|
| 790 |
-
line=dict(color='rgba(0,0,0,0)'),
|
| 791 |
-
name='95% CI',
|
| 792 |
-
hoverinfo='skip',
|
| 793 |
-
))
|
| 794 |
-
|
| 795 |
-
xy_max = max(float(exp.max()), float(obs.max())) * 1.06
|
| 796 |
-
fig.add_trace(go.Scatter(
|
| 797 |
-
x=[0, xy_max], y=[0, xy_max],
|
| 798 |
-
mode='lines',
|
| 799 |
-
line=dict(color='#E8453C', width=2, dash='dash'),
|
| 800 |
-
name='Expected (y=x)',
|
| 801 |
-
hoverinfo='skip',
|
| 802 |
-
))
|
| 803 |
-
|
| 804 |
-
sig_mask = obs >= sig_thr
|
| 805 |
-
ns_mask = ~sig_mask
|
| 806 |
-
|
| 807 |
-
if ns_mask.any():
|
| 808 |
-
fig.add_trace(go.Scatter(
|
| 809 |
-
x=exp[ns_mask], y=obs[ns_mask],
|
| 810 |
-
mode='markers',
|
| 811 |
-
marker=dict(color=color, size=5, opacity=0.8),
|
| 812 |
-
name='Non-significant',
|
| 813 |
-
text=[f"Expected: {exp[ns_mask][i]:.3f}<br>Observed: {obs[ns_mask][i]:.3f}"
|
| 814 |
-
for i in range(ns_mask.sum())],
|
| 815 |
-
hovertemplate="%{text}<extra></extra>",
|
| 816 |
-
))
|
| 817 |
-
if sig_mask.any():
|
| 818 |
-
fig.add_trace(go.Scatter(
|
| 819 |
-
x=exp[sig_mask], y=obs[sig_mask],
|
| 820 |
-
mode='markers',
|
| 821 |
-
marker=dict(color='#FF1744', size=10, symbol='diamond',
|
| 822 |
-
line=dict(color='#7F0000', width=1)),
|
| 823 |
-
name=f'GW Significant ({sig_mask.sum()})',
|
| 824 |
-
text=[f"Expected: {exp[sig_mask][i]:.3f}<br>Observed: {obs[sig_mask][i]:.3f}"
|
| 825 |
-
for i in range(sig_mask.sum())],
|
| 826 |
-
hovertemplate="%{text}<extra></extra>",
|
| 827 |
-
))
|
| 828 |
-
|
| 829 |
-
fig.add_shape(type="line", x0=0, x1=xy_max, y0=sig_thr, y1=sig_thr,
|
| 830 |
-
line=dict(color="#FF4560", width=1, dash="dot"))
|
| 831 |
-
|
| 832 |
-
fig.add_annotation(
|
| 833 |
-
x=0.05, y=0.95, xref="paper", yref="paper",
|
| 834 |
-
text=f"Ξ» = {lam:.4f}",
|
| 835 |
-
showarrow=False,
|
| 836 |
-
font=dict(size=14, color=lam_col, family="monospace"),
|
| 837 |
-
bgcolor="white",
|
| 838 |
-
bordercolor=lam_col,
|
| 839 |
-
borderwidth=2,
|
| 840 |
-
borderpad=6,
|
| 841 |
-
)
|
| 842 |
-
|
| 843 |
-
fig.update_layout(
|
| 844 |
-
title=dict(
|
| 845 |
-
text=f"<b>QQ Plot β {model_name}</b>",
|
| 846 |
-
font=dict(size=15, color="#1E293B"),
|
| 847 |
-
),
|
| 848 |
-
xaxis=dict(title="Expected βlogββ(p)", gridcolor="#E2E8F0"),
|
| 849 |
-
yaxis=dict(title="Observed βlogββ(p)", gridcolor="#E2E8F0"),
|
| 850 |
-
plot_bgcolor="white",
|
| 851 |
-
paper_bgcolor="white",
|
| 852 |
-
height=500,
|
| 853 |
-
legend=dict(font=dict(size=10)),
|
| 854 |
-
hovermode="closest",
|
| 855 |
-
margin=dict(l=60, r=40, t=80, b=60),
|
| 856 |
-
)
|
| 857 |
-
return fig
|
| 858 |
-
|
| 859 |
-
def plot_qq_overlay_interactive(all_results):
|
| 860 |
-
"""Interactive QQ overlay for all models."""
|
| 861 |
-
fig = go.Figure()
|
| 862 |
-
exp_max = 0
|
| 863 |
-
for mname, (pvals, _, _) in all_results.items():
|
| 864 |
-
n = len(pvals)
|
| 865 |
-
obs_raw = -np.log10(np.clip(pvals, 1e-300, 1))
|
| 866 |
-
sort_i = np.argsort(obs_raw)[::-1]
|
| 867 |
-
obs = obs_raw[sort_i]
|
| 868 |
-
exp = -np.log10(np.arange(1, n + 1) / n)
|
| 869 |
-
exp_max = max(exp_max, exp.max())
|
| 870 |
-
lam = compute_lambda(pvals)
|
| 871 |
-
col = MODEL_COLORS.get(mname, ACCENT_BLUE)
|
| 872 |
-
fig.add_trace(go.Scatter(
|
| 873 |
-
x=exp, y=obs,
|
| 874 |
-
mode='lines',
|
| 875 |
-
line=dict(color=col, width=2.5),
|
| 876 |
-
name=f"{mname} (Ξ»={lam:.3f})",
|
| 877 |
-
))
|
| 878 |
-
fig.add_trace(go.Scatter(
|
| 879 |
-
x=[0, exp_max * 1.05], y=[0, exp_max * 1.05],
|
| 880 |
-
mode='lines',
|
| 881 |
-
line=dict(color='#333333', width=1.5),
|
| 882 |
-
name='y = x (expected)',
|
| 883 |
-
))
|
| 884 |
-
sig_thr = -np.log10(5e-8)
|
| 885 |
-
fig.add_shape(type="line", x0=0, x1=exp_max, y0=sig_thr, y1=sig_thr,
|
| 886 |
-
line=dict(color="#CC0000", width=1.5, dash="dash"))
|
| 887 |
-
fig.add_annotation(x=exp_max*0.98, y=sig_thr+0.2,
|
| 888 |
-
text="GW significant (5Γ10β»βΈ)",
|
| 889 |
-
showarrow=False, font=dict(color="#CC0000", size=10),
|
| 890 |
-
xanchor="right")
|
| 891 |
-
fig.update_layout(
|
| 892 |
-
title=dict(text="<b>QQ Plot Overlay β All Models</b>", font=dict(size=15)),
|
| 893 |
-
xaxis=dict(title="Expected βlogββ(p)", gridcolor="#E2E8F0"),
|
| 894 |
-
yaxis=dict(title="Observed βlogββ(p)", gridcolor="#E2E8F0"),
|
| 895 |
-
plot_bgcolor="white",
|
| 896 |
-
paper_bgcolor="white",
|
| 897 |
-
height=520,
|
| 898 |
-
legend=dict(font=dict(size=11)),
|
| 899 |
-
hovermode="x unified",
|
| 900 |
-
margin=dict(l=60, r=40, t=80, b=60),
|
| 901 |
-
)
|
| 902 |
-
return fig
|
| 903 |
-
|
| 904 |
-
# βββββββββββββββββββββββ IMPROVED CIRCOS PLOT βββββββββββββββββββββββββββββββββ
|
| 905 |
def plot_circos_interactive(all_results, chroms, positions, snp_names):
|
| 906 |
"""
|
| 907 |
-
|
| 908 |
-
-
|
| 909 |
-
|
| 910 |
-
-
|
| 911 |
-
- Color-coded rings + clean legend.
|
| 912 |
-
- Significant SNPs shown as red diamonds with labels only for top hits.
|
| 913 |
"""
|
| 914 |
best_models = select_best_models(all_results, n_best=min(4, len(all_results)))
|
| 915 |
selected_results = {m: all_results[m] for m in best_models if m in all_results}
|
|
@@ -921,24 +667,22 @@ def plot_circos_interactive(all_results, chroms, positions, snp_names):
|
|
| 921 |
total_snps = len(chroms_s)
|
| 922 |
chrom_list = sorted(set(chroms_s))
|
| 923 |
|
| 924 |
-
#
|
| 925 |
angles_deg = np.linspace(0, 360, total_snps, endpoint=False)
|
| 926 |
|
| 927 |
fig = go.Figure()
|
| 928 |
|
| 929 |
-
# ββ Ring layout parameters ββββββββββββββββββββββββββββββββββββββββββββββ
|
| 930 |
n_models = len(selected_results)
|
| 931 |
-
r_chr_band = 0.
|
| 932 |
-
|
| 933 |
-
|
| 934 |
-
|
| 935 |
-
ring_gap = 0.03 # gap between rings
|
| 936 |
total_ring_space = ring_outer - ring_inner
|
| 937 |
ring_width = (total_ring_space - ring_gap * (n_models - 1)) / max(n_models, 1)
|
| 938 |
|
| 939 |
sig_line = -np.log10(5e-8)
|
| 940 |
|
| 941 |
-
# ββ 1. Chromosome color arcs ββ
|
| 942 |
for ci, ch in enumerate(chrom_list):
|
| 943 |
mask = chroms_s == ch
|
| 944 |
idxs = np.where(mask)[0]
|
|
@@ -950,38 +694,59 @@ def plot_circos_interactive(all_results, chroms, positions, snp_names):
|
|
| 950 |
mid_a = (a_start + a_end) / 2
|
| 951 |
col = CHR_PALETTE[ci % len(CHR_PALETTE)]
|
| 952 |
|
| 953 |
-
# Colored arc
|
| 954 |
fig.add_trace(go.Barpolar(
|
| 955 |
-
r=[0.
|
| 956 |
theta=[mid_a],
|
| 957 |
width=[a_width + 1.5],
|
| 958 |
base=[r_chr_band],
|
| 959 |
marker_color=col,
|
| 960 |
marker_line_color="white",
|
| 961 |
-
marker_line_width=0.
|
| 962 |
-
opacity=0.
|
| 963 |
showlegend=False,
|
| 964 |
hoverinfo='skip',
|
| 965 |
-
name=f"Chr{ch}
|
| 966 |
))
|
| 967 |
|
| 968 |
-
# Chromosome label
|
| 969 |
-
|
| 970 |
-
|
| 971 |
-
|
| 972 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 973 |
fig.add_trace(go.Scatterpolar(
|
| 974 |
-
r=[
|
| 975 |
theta=[mid_a],
|
| 976 |
mode='text',
|
| 977 |
text=[f"<b>Chr{ch}</b>"],
|
| 978 |
-
textfont=dict(size=
|
| 979 |
showlegend=False,
|
| 980 |
hoverinfo='skip',
|
| 981 |
-
name=f"Chr{ch}_lbl",
|
| 982 |
))
|
| 983 |
|
| 984 |
-
# ββ 2. Model data rings ββ
|
| 985 |
for midx, (mname, (pvals, betas, _)) in enumerate(selected_results.items()):
|
| 986 |
pvals_s = pvals[sort_idx]
|
| 987 |
log_p_s = -np.log10(np.clip(pvals_s, 1e-300, 1))
|
|
@@ -989,7 +754,6 @@ def plot_circos_interactive(all_results, chroms, positions, snp_names):
|
|
| 989 |
r_base = ring_inner + midx * (ring_width + ring_gap)
|
| 990 |
r_top = r_base + ring_width
|
| 991 |
max_lp = max(log_p_s.max(), sig_line, 1.0)
|
| 992 |
-
# Normalize log_p to ring height
|
| 993 |
r_data = r_base + (log_p_s / max_lp) * ring_width * 0.9
|
| 994 |
col = MODEL_COLORS.get(mname, CHR_PALETTE[midx % len(CHR_PALETTE)])
|
| 995 |
|
|
@@ -1002,17 +766,17 @@ def plot_circos_interactive(all_results, chroms, positions, snp_names):
|
|
| 1002 |
r=r_data[ns_mask],
|
| 1003 |
theta=angles_deg[ns_mask],
|
| 1004 |
mode='markers',
|
| 1005 |
-
marker=dict(color=col, size=
|
| 1006 |
name=mname,
|
| 1007 |
legendgroup=mname,
|
| 1008 |
text=[f"Model: {mname}<br>SNP: {snp_s[i]}<br>Chr: {chroms_s[i]}<br>"
|
| 1009 |
f"p: {pvals_s[ns_mask][k]:.3e}<br>-log10(p): {log_p_s[ns_mask][k]:.2f}"
|
| 1010 |
for k, i in enumerate(np.where(ns_mask)[0])],
|
| 1011 |
hovertemplate="%{text}<extra></extra>",
|
| 1012 |
-
showlegend=
|
| 1013 |
))
|
| 1014 |
|
| 1015 |
-
# Significant SNPs
|
| 1016 |
if sig_mask.any():
|
| 1017 |
sig_idxs = np.where(sig_mask)[0]
|
| 1018 |
fig.add_trace(go.Scatterpolar(
|
|
@@ -1020,153 +784,247 @@ def plot_circos_interactive(all_results, chroms, positions, snp_names):
|
|
| 1020 |
theta=angles_deg[sig_mask],
|
| 1021 |
mode='markers',
|
| 1022 |
marker=dict(
|
| 1023 |
-
color='#FF1744', size=
|
| 1024 |
-
line=dict(color='#7F0000', width=
|
| 1025 |
),
|
| 1026 |
-
name=f"{mname} β
|
| 1027 |
legendgroup=f"{mname}_sig",
|
| 1028 |
text=[f"<b>β
GW SIGNIFICANT β
</b><br>Model: {mname}<br>SNP: {snp_s[i]}<br>"
|
| 1029 |
f"Chr: {chroms_s[i]}<br>p: {pvals_s[sig_mask][k]:.3e}"
|
| 1030 |
for k, i in enumerate(sig_idxs)],
|
| 1031 |
hovertemplate="%{text}<extra></extra>",
|
| 1032 |
-
showlegend=
|
| 1033 |
))
|
| 1034 |
|
| 1035 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1036 |
fig.add_trace(go.Scatterpolar(
|
| 1037 |
-
r=[
|
| 1038 |
-
theta=
|
| 1039 |
-
mode='
|
| 1040 |
-
|
| 1041 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1042 |
showlegend=False,
|
| 1043 |
hoverinfo='skip',
|
| 1044 |
-
name=f"{mname}_base",
|
| 1045 |
))
|
| 1046 |
|
| 1047 |
-
|
| 1048 |
-
|
| 1049 |
-
|
| 1050 |
-
|
| 1051 |
-
|
| 1052 |
-
|
| 1053 |
-
|
| 1054 |
-
|
| 1055 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1056 |
showlegend=False,
|
| 1057 |
-
hoverinfo='skip',
|
| 1058 |
-
name=f"{mname}_sig_circle",
|
| 1059 |
))
|
| 1060 |
|
| 1061 |
-
|
| 1062 |
-
|
| 1063 |
-
|
| 1064 |
-
|
| 1065 |
-
|
| 1066 |
-
|
| 1067 |
-
|
| 1068 |
-
|
| 1069 |
-
|
| 1070 |
-
|
| 1071 |
-
|
| 1072 |
-
showlegend=False,
|
| 1073 |
-
hoverinfo='skip',
|
| 1074 |
-
name=f"{mname}_label",
|
| 1075 |
-
))
|
| 1076 |
|
| 1077 |
-
|
| 1078 |
-
fig.add_trace(go.Scatterpolar(
|
| 1079 |
-
r=[ring_inner] * 361,
|
| 1080 |
-
theta=list(range(361)),
|
| 1081 |
-
mode='lines',
|
| 1082 |
-
line=dict(color='#CBD5E1', width=1.5),
|
| 1083 |
-
fill='toself',
|
| 1084 |
-
fillcolor='rgba(248,250,252,0.95)',
|
| 1085 |
-
showlegend=False,
|
| 1086 |
-
hoverinfo='skip',
|
| 1087 |
-
name='center_fill',
|
| 1088 |
-
))
|
| 1089 |
|
| 1090 |
-
|
| 1091 |
-
|
| 1092 |
-
f"{m} Ξ»={compute_lambda(all_results[m][0]):.3f}" for m in best_models
|
| 1093 |
-
])
|
| 1094 |
-
n_sig_total = sum(int((all_results[m][0] < 5e-8).sum()) for m in best_models)
|
| 1095 |
|
| 1096 |
fig.update_layout(
|
| 1097 |
title=dict(
|
| 1098 |
-
text=
|
| 1099 |
-
|
| 1100 |
-
f"<br><sup style='color:#FF4560;'>β
= Genome-wide significant (5Γ10β»βΈ) | Total sig hits: {n_sig_total}</sup>"),
|
| 1101 |
-
font=dict(size=14, color="#1E293B"),
|
| 1102 |
-
x=0.5,
|
| 1103 |
-
xanchor='center',
|
| 1104 |
),
|
| 1105 |
-
|
| 1106 |
-
|
| 1107 |
-
|
| 1108 |
-
|
| 1109 |
-
|
| 1110 |
-
|
| 1111 |
-
|
| 1112 |
-
|
| 1113 |
-
|
| 1114 |
-
|
| 1115 |
-
showline=False,
|
| 1116 |
-
direction="clockwise",
|
| 1117 |
-
rotation=90,
|
| 1118 |
-
),
|
| 1119 |
-
bgcolor="white",
|
| 1120 |
),
|
| 1121 |
-
|
| 1122 |
-
|
| 1123 |
-
|
| 1124 |
-
|
| 1125 |
-
y=0.5,
|
| 1126 |
-
xanchor="left",
|
| 1127 |
-
x=1.02,
|
| 1128 |
-
font=dict(size=11),
|
| 1129 |
-
itemsizing='constant',
|
| 1130 |
-
bordercolor="#E2E8F0",
|
| 1131 |
-
borderwidth=1,
|
| 1132 |
-
bgcolor="rgba(255,255,255,0.95)",
|
| 1133 |
),
|
|
|
|
| 1134 |
paper_bgcolor="white",
|
| 1135 |
-
height=
|
| 1136 |
-
|
| 1137 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1138 |
)
|
| 1139 |
return fig
|
| 1140 |
|
| 1141 |
-
|
| 1142 |
-
# βββββββββββββββββββββββ LD DECAY PLOT (REDESIGNED) ββββββββββββββββββββββββββ
|
| 1143 |
def plot_ld_decay_interactive(G, positions, chroms):
|
| 1144 |
"""
|
| 1145 |
-
|
| 1146 |
-
-
|
| 1147 |
-
-
|
| 1148 |
-
-
|
| 1149 |
-
-
|
| 1150 |
-
-
|
| 1151 |
-
- Chromosome-colored scatter points with legend
|
| 1152 |
-
- Clean white background, gridlines
|
| 1153 |
-
- Interpretation annotations: half-decay distance, plateau
|
| 1154 |
"""
|
| 1155 |
chrom_list = sorted(set(chroms))
|
| 1156 |
-
sample_per_chr =
|
| 1157 |
sampled_idx = []
|
| 1158 |
rng = np.random.default_rng(42)
|
| 1159 |
for ch in chrom_list:
|
| 1160 |
idx_ch = np.where(chroms == ch)[0]
|
| 1161 |
n_samp = min(sample_per_chr, len(idx_ch))
|
| 1162 |
-
|
|
|
|
| 1163 |
sampled_idx = sorted(set(sampled_idx))
|
| 1164 |
|
| 1165 |
dists_bp, r2s, chrom_pairs = [], [], []
|
| 1166 |
for ii, i in enumerate(sampled_idx):
|
| 1167 |
for j in sampled_idx[ii+1:]:
|
| 1168 |
if chroms[i] != chroms[j]:
|
| 1169 |
-
continue
|
| 1170 |
xi, xj = G[:, i], G[:, j]
|
| 1171 |
mask = ~(np.isnan(xi) | np.isnan(xj))
|
| 1172 |
if mask.sum() < 4:
|
|
@@ -1199,8 +1057,8 @@ def plot_ld_decay_interactive(G, positions, chroms):
|
|
| 1199 |
r2s = np.array(r2s)
|
| 1200 |
chrom_pairs = np.array(chrom_pairs)
|
| 1201 |
|
| 1202 |
-
# Convert bp β
|
| 1203 |
-
|
| 1204 |
|
| 1205 |
# ββ Scatter: color by chromosome ββ
|
| 1206 |
for ci, ch in enumerate(chrom_list):
|
|
@@ -1208,31 +1066,30 @@ def plot_ld_decay_interactive(G, positions, chroms):
|
|
| 1208 |
if not cmask.any():
|
| 1209 |
continue
|
| 1210 |
col = CHR_PALETTE[ci % len(CHR_PALETTE)]
|
| 1211 |
-
# Subsample for display performance
|
| 1212 |
idx_sub = np.where(cmask)[0]
|
| 1213 |
-
if len(idx_sub) >
|
| 1214 |
-
idx_sub = rng.choice(idx_sub,
|
| 1215 |
fig.add_trace(go.Scatter(
|
| 1216 |
-
x=
|
| 1217 |
y=r2s[idx_sub],
|
| 1218 |
mode='markers',
|
| 1219 |
marker=dict(
|
| 1220 |
-
color=col, size=
|
| 1221 |
line=dict(width=0),
|
| 1222 |
),
|
| 1223 |
name=f"Chr{ch}",
|
| 1224 |
legendgroup=f"chr{ch}",
|
| 1225 |
-
hovertemplate=f"
|
| 1226 |
))
|
| 1227 |
|
| 1228 |
-
# ββ Binned means for
|
| 1229 |
-
n_bins =
|
| 1230 |
-
pctiles = np.percentile(
|
| 1231 |
bin_centers, bin_means, bin_sems, bin_counts = [], [], [], []
|
| 1232 |
for k in range(len(pctiles) - 1):
|
| 1233 |
-
mask = (
|
| 1234 |
if mask.sum() >= 3:
|
| 1235 |
-
bin_centers.append(np.median(
|
| 1236 |
bin_means.append(np.mean(r2s[mask]))
|
| 1237 |
bin_sems.append(stats.sem(r2s[mask]) if mask.sum() > 1 else 0)
|
| 1238 |
bin_counts.append(mask.sum())
|
|
@@ -1241,140 +1098,195 @@ def plot_ld_decay_interactive(G, positions, chroms):
|
|
| 1241 |
bin_means = np.array(bin_means)
|
| 1242 |
bin_sems = np.array(bin_sems)
|
| 1243 |
|
| 1244 |
-
# Fit
|
| 1245 |
smooth_x = np.array([])
|
| 1246 |
smooth_y = np.array([])
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1247 |
if len(bin_centers) >= 4:
|
| 1248 |
try:
|
| 1249 |
from scipy.optimize import curve_fit
|
| 1250 |
def decay_func(d, a, b, c):
|
| 1251 |
return a * np.exp(-b * d) + c
|
| 1252 |
-
p0 = [0.8,
|
| 1253 |
-
bounds = ([0, 0, 0], [1.0, 100, 0.5])
|
| 1254 |
popt, _ = curve_fit(decay_func, bin_centers, bin_means,
|
| 1255 |
p0=p0, bounds=bounds, maxfev=5000)
|
| 1256 |
-
smooth_x = np.linspace(
|
| 1257 |
smooth_y = decay_func(smooth_x, *popt)
|
| 1258 |
smooth_y = np.clip(smooth_y, 0, 1)
|
| 1259 |
-
|
| 1260 |
-
#
|
| 1261 |
-
half_decay_d = None
|
| 1262 |
-
r2_at_zero = float(popt[0] + popt[2])
|
| 1263 |
r2_plateau = float(popt[2])
|
| 1264 |
-
|
|
|
|
|
|
|
|
|
|
| 1265 |
above_half = smooth_x[smooth_y >= r2_half]
|
| 1266 |
if len(above_half) > 0:
|
| 1267 |
-
|
|
|
|
| 1268 |
except Exception:
|
| 1269 |
smooth_x = bin_centers
|
| 1270 |
smooth_y = bin_means
|
| 1271 |
-
|
| 1272 |
else:
|
| 1273 |
smooth_x = bin_centers
|
| 1274 |
smooth_y = bin_means
|
| 1275 |
-
half_decay_d = None
|
| 1276 |
|
| 1277 |
-
# ββ Smooth decay curve
|
| 1278 |
if len(smooth_x) > 0:
|
| 1279 |
fig.add_trace(go.Scatter(
|
| 1280 |
x=smooth_x, y=smooth_y,
|
| 1281 |
mode='lines',
|
| 1282 |
line=dict(color='black', width=3),
|
| 1283 |
name='Fitted decay curve',
|
| 1284 |
-
hovertemplate="Distance: %{x:.3f}
|
| 1285 |
))
|
| 1286 |
|
| 1287 |
-
# ββ Binned mean points ββ
|
| 1288 |
if len(bin_centers) > 0:
|
| 1289 |
fig.add_trace(go.Scatter(
|
| 1290 |
x=bin_centers, y=bin_means,
|
| 1291 |
mode='markers',
|
| 1292 |
-
marker=dict(color='
|
| 1293 |
line=dict(color='white', width=1)),
|
| 1294 |
name='Binned mean rΒ²',
|
| 1295 |
error_y=dict(type='data', array=bin_sems, visible=True,
|
| 1296 |
-
color='rgba(0,0,0,0.4)', thickness=1.5),
|
| 1297 |
-
hovertemplate="Distance: %{x:.3f}
|
| 1298 |
))
|
| 1299 |
|
| 1300 |
-
# ββ Reference lines
|
| 1301 |
-
x_max_plot = float(np.percentile(
|
| 1302 |
|
| 1303 |
-
|
| 1304 |
-
|
| 1305 |
-
|
| 1306 |
-
|
| 1307 |
-
|
| 1308 |
-
|
| 1309 |
-
|
| 1310 |
-
)
|
| 1311 |
-
|
| 1312 |
-
|
| 1313 |
-
|
| 1314 |
-
|
| 1315 |
-
|
| 1316 |
-
|
| 1317 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1318 |
|
| 1319 |
# ββ Half-decay annotation ββ
|
| 1320 |
-
if
|
| 1321 |
fig.add_shape(
|
| 1322 |
-
type="line", x0=
|
| 1323 |
-
line=dict(color='#2ECC71', width=2, dash='dash'),
|
| 1324 |
)
|
| 1325 |
fig.add_annotation(
|
| 1326 |
-
x=
|
| 1327 |
-
text=f"Half-decay<br>{
|
| 1328 |
showarrow=True,
|
| 1329 |
arrowhead=2,
|
| 1330 |
arrowcolor='#2ECC71',
|
| 1331 |
-
font=dict(size=10, color='#2ECC71'),
|
| 1332 |
ax=30, ay=-30,
|
| 1333 |
)
|
| 1334 |
|
| 1335 |
-
# ββ
|
| 1336 |
overall_mean_r2 = float(np.mean(r2s)) if len(r2s) > 0 else 0
|
| 1337 |
-
n_pairs
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1338 |
interp_text = (
|
| 1339 |
-
f"<b>LD
|
| 1340 |
-
f"
|
| 1341 |
-
f"
|
| 1342 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1343 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1344 |
fig.add_annotation(
|
| 1345 |
-
x=0.
|
| 1346 |
text=interp_text,
|
| 1347 |
showarrow=False,
|
| 1348 |
-
font=dict(size=10, color="#2D3142"),
|
| 1349 |
bgcolor="rgba(255,255,255,0.92)",
|
| 1350 |
bordercolor="#CBD5E1",
|
| 1351 |
borderwidth=1.5,
|
| 1352 |
borderpad=8,
|
| 1353 |
align="left",
|
| 1354 |
-
xanchor="
|
| 1355 |
yanchor="top",
|
| 1356 |
)
|
| 1357 |
|
| 1358 |
fig.update_layout(
|
| 1359 |
title=dict(
|
| 1360 |
text=(
|
| 1361 |
-
"<b>Linkage Disequilibrium (LD) Decay</b>"
|
| 1362 |
-
"<br><sup>Intra-chromosomal pairwise rΒ² vs
|
| 1363 |
-
"Black curve = fitted exponential decay |
|
| 1364 |
),
|
| 1365 |
font=dict(size=14, color="#1E293B"),
|
| 1366 |
),
|
| 1367 |
xaxis=dict(
|
| 1368 |
-
title="
|
| 1369 |
gridcolor="#E2E8F0",
|
| 1370 |
gridwidth=0.8,
|
| 1371 |
zeroline=True,
|
| 1372 |
zerolinecolor="#CBD5E1",
|
| 1373 |
range=[0, x_max_plot],
|
| 1374 |
tickfont=dict(size=11),
|
|
|
|
| 1375 |
),
|
| 1376 |
yaxis=dict(
|
| 1377 |
-
title="
|
| 1378 |
gridcolor="#E2E8F0",
|
| 1379 |
gridwidth=0.8,
|
| 1380 |
range=[0, 1.05],
|
|
@@ -1383,23 +1295,163 @@ def plot_ld_decay_interactive(G, positions, chroms):
|
|
| 1383 |
),
|
| 1384 |
plot_bgcolor="white",
|
| 1385 |
paper_bgcolor="white",
|
| 1386 |
-
height=
|
| 1387 |
hovermode="closest",
|
| 1388 |
legend=dict(
|
| 1389 |
orientation="v",
|
| 1390 |
yanchor="top",
|
| 1391 |
-
y=0.
|
| 1392 |
-
xanchor="
|
| 1393 |
-
x=0.
|
| 1394 |
font=dict(size=9),
|
| 1395 |
bgcolor="rgba(255,255,255,0.85)",
|
| 1396 |
bordercolor="#E2E8F0",
|
| 1397 |
borderwidth=1,
|
| 1398 |
),
|
| 1399 |
-
margin=dict(l=
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1400 |
)
|
| 1401 |
return fig
|
| 1402 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1403 |
|
| 1404 |
# βββββββββββββββββββββββ INTERACTIVE PVE / EFFECT SIZE PLOT ββββββββββββββββββ
|
| 1405 |
def plot_effect_sizes_interactive(pvals, betas, ses, snp_names, model_name=""):
|
|
@@ -1713,10 +1765,7 @@ def plot_summary_dashboard_interactive(y, maf, all_results, G_filt):
|
|
| 1713 |
|
| 1714 |
# βββββββββββββββββββββββ INTERACTIVE ALL-MODELS MANHATTAN ββββββββββββββββββββ
|
| 1715 |
def plot_all_models_manhattan_interactive(all_results, chroms, positions, snp_names):
|
| 1716 |
-
"""
|
| 1717 |
-
FIX: x-axis starts from chromosome 1 (using updated _compute_x_coords).
|
| 1718 |
-
Interactive stacked Manhattan for all models.
|
| 1719 |
-
"""
|
| 1720 |
n_models = len(all_results)
|
| 1721 |
chrom_list = sorted(set(chroms))
|
| 1722 |
x_coords = _compute_x_coords(chroms, positions, chrom_list)
|
|
@@ -1772,13 +1821,12 @@ def plot_all_models_manhattan_interactive(all_results, chroms, positions, snp_na
|
|
| 1772 |
fig.update_yaxes(title_text=f"{mname}\n(Ξ»={lam:.3f})", row=midx, col=1,
|
| 1773 |
title_font=dict(size=9, color=col))
|
| 1774 |
|
| 1775 |
-
# Chromosome ticks on bottom axis β start from 1
|
| 1776 |
fig.update_xaxes(
|
| 1777 |
tickmode='array',
|
| 1778 |
tickvals=tick_pos,
|
| 1779 |
ticktext=tick_lab,
|
| 1780 |
tickangle=45,
|
| 1781 |
-
tickfont=dict(size=
|
| 1782 |
range=[0, x_coords.max() * 1.01],
|
| 1783 |
row=n_models, col=1,
|
| 1784 |
)
|
|
@@ -2008,7 +2056,7 @@ def plot_manhattan_static(pvals, chroms, positions, model_name):
|
|
| 2008 |
sig_line = -np.log10(5e-8)
|
| 2009 |
sug_line = -np.log10(1e-5)
|
| 2010 |
chrom_list = sorted(set(chroms))
|
| 2011 |
-
x_coords = _compute_x_coords(chroms, positions, chrom_list)
|
| 2012 |
tick_pos, tick_lab = _compute_tick_positions(x_coords, chroms, chrom_list)
|
| 2013 |
for ch in chrom_list:
|
| 2014 |
mask = chroms == ch
|
|
@@ -2026,7 +2074,7 @@ def plot_manhattan_static(pvals, chroms, positions, model_name):
|
|
| 2026 |
ax.set_ylabel("-logββ(p)")
|
| 2027 |
ax.set_title(f"Manhattan β {model_name}", fontweight='bold')
|
| 2028 |
x_max = x_coords.max() if len(x_coords) > 0 else 1
|
| 2029 |
-
ax.set_xlim(0, x_max * 1.01)
|
| 2030 |
fig.tight_layout()
|
| 2031 |
return fig
|
| 2032 |
|
|
@@ -2118,7 +2166,7 @@ def run_gwas(file_obj, text_input, selected_models, maf_threshold):
|
|
| 2118 |
|
| 2119 |
bonf = 0.05 / len(primary_p)
|
| 2120 |
|
| 2121 |
-
#
|
| 2122 |
fig_mh_primary = plot_manhattan_interactive(primary_p, chr_filt, pos_filt, snp_filt, "Manhattan", primary_model)
|
| 2123 |
fig_qq_primary = plot_qq_interactive_single(primary_p, primary_model, MODEL_COLORS.get(primary_model))
|
| 2124 |
fig_qq_overlay = plot_qq_overlay_interactive(all_results)
|
|
@@ -2130,7 +2178,7 @@ def run_gwas(file_obj, text_input, selected_models, maf_threshold):
|
|
| 2130 |
fig_all_mh = plot_all_models_manhattan_interactive(all_results, chr_filt, pos_filt, snp_filt)
|
| 2131 |
fig_dashboard = plot_summary_dashboard_interactive(y, maf_vals, all_results, G_filt)
|
| 2132 |
|
| 2133 |
-
#
|
| 2134 |
static_plots = {}
|
| 2135 |
try:
|
| 2136 |
for mname, (p, b, se) in all_results.items():
|
|
@@ -2427,11 +2475,11 @@ with gr.Blocks(css=PASTEL_CSS, title="𧬠GWAS Pipeline", theme=gr.themes.Base(
|
|
| 2427 |
plot3 = gr.Plot(label="QQ Overlay β All Models")
|
| 2428 |
|
| 2429 |
with gr.Tab("π΅ Circos (Best Models)"):
|
| 2430 |
-
gr.HTML('<p style="font-size:11px;color:#8892B0;padding:4px 0;">Shows top 4 best-controlled models (Ξ» closest to 1) Β· β = genome-wide significant Β· Chr labels outside
|
| 2431 |
plot4 = gr.Plot(label="Circos β Best Models")
|
| 2432 |
|
| 2433 |
with gr.Tab("π LD Decay"):
|
| 2434 |
-
gr.HTML('<p style="font-size:11px;color:#8892B0;padding:4px 0;">Colored scatter = pairwise rΒ² per chromosome Β· Black curve = fitted exponential decay Β·
|
| 2435 |
plot5 = gr.Plot(label="LD Decay")
|
| 2436 |
|
| 2437 |
with gr.Tab("π¬ PCA"):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
import pandas as pd
|
| 3 |
import numpy as np
|
|
|
|
| 605 |
return data
|
| 606 |
|
| 607 |
def _compute_x_coords(chroms, positions, chrom_list):
|
| 608 |
+
"""FIX: Chromosome x-coordinates start from chromosome 1 (not 0)."""
|
|
|
|
|
|
|
|
|
|
| 609 |
x_coords = np.zeros(len(chroms))
|
| 610 |
x_offset = 0
|
| 611 |
max_pos = max(positions) if len(positions) > 0 else 1
|
|
|
|
| 614 |
if not mask.any():
|
| 615 |
continue
|
| 616 |
pos = positions[mask]
|
| 617 |
+
# Start from 1 for chromosome 1
|
| 618 |
+
x_coords[mask] = pos - pos.min() + x_offset + 1
|
|
|
|
| 619 |
x_offset += pos.max() - pos.min() + max_pos * 0.02 + 1
|
| 620 |
return x_coords
|
| 621 |
|
|
|
|
| 635 |
/ stats.chi2.ppf(0.5, df=1))
|
| 636 |
|
| 637 |
def select_best_models(all_results, n_best=4):
|
| 638 |
+
"""Select best-performing models based on lambda closest to 1.0."""
|
| 639 |
scores = {}
|
| 640 |
for mname, (pvals, betas, ses) in all_results.items():
|
| 641 |
lam = compute_lambda(pvals)
|
|
|
|
| 649 |
best = sorted(scores.keys(), key=lambda m: scores[m])[:n_best]
|
| 650 |
return best
|
| 651 |
|
| 652 |
+
# βββββββββββββββββββββββ IMPROVED CIRCOS PLOT (NO OVERLAPPING LABELS) βββββββββ
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 653 |
def plot_circos_interactive(all_results, chroms, positions, snp_names):
|
| 654 |
"""
|
| 655 |
+
COMPLETELY REDESIGNED: No overlapping labels.
|
| 656 |
+
- Chromosome labels placed outside with radial lines pointing to arcs
|
| 657 |
+
- Model labels placed in dedicated sections around the circle
|
| 658 |
+
- Clean legend on the right
|
|
|
|
|
|
|
| 659 |
"""
|
| 660 |
best_models = select_best_models(all_results, n_best=min(4, len(all_results)))
|
| 661 |
selected_results = {m: all_results[m] for m in best_models if m in all_results}
|
|
|
|
| 667 |
total_snps = len(chroms_s)
|
| 668 |
chrom_list = sorted(set(chroms_s))
|
| 669 |
|
| 670 |
+
# Angular positions for each SNP
|
| 671 |
angles_deg = np.linspace(0, 360, total_snps, endpoint=False)
|
| 672 |
|
| 673 |
fig = go.Figure()
|
| 674 |
|
|
|
|
| 675 |
n_models = len(selected_results)
|
| 676 |
+
r_chr_band = 0.82
|
| 677 |
+
ring_outer = 0.78
|
| 678 |
+
ring_inner = 0.15
|
| 679 |
+
ring_gap = 0.02
|
|
|
|
| 680 |
total_ring_space = ring_outer - ring_inner
|
| 681 |
ring_width = (total_ring_space - ring_gap * (n_models - 1)) / max(n_models, 1)
|
| 682 |
|
| 683 |
sig_line = -np.log10(5e-8)
|
| 684 |
|
| 685 |
+
# ββ 1. Chromosome color arcs and labels (no overlap) ββ
|
| 686 |
for ci, ch in enumerate(chrom_list):
|
| 687 |
mask = chroms_s == ch
|
| 688 |
idxs = np.where(mask)[0]
|
|
|
|
| 694 |
mid_a = (a_start + a_end) / 2
|
| 695 |
col = CHR_PALETTE[ci % len(CHR_PALETTE)]
|
| 696 |
|
| 697 |
+
# Colored arc
|
| 698 |
fig.add_trace(go.Barpolar(
|
| 699 |
+
r=[0.05],
|
| 700 |
theta=[mid_a],
|
| 701 |
width=[a_width + 1.5],
|
| 702 |
base=[r_chr_band],
|
| 703 |
marker_color=col,
|
| 704 |
marker_line_color="white",
|
| 705 |
+
marker_line_width=0.3,
|
| 706 |
+
opacity=0.9,
|
| 707 |
showlegend=False,
|
| 708 |
hoverinfo='skip',
|
| 709 |
+
name=f"Chr{ch}",
|
| 710 |
))
|
| 711 |
|
| 712 |
+
# Chromosome label with connector line
|
| 713 |
+
label_radius = r_chr_band + 0.08
|
| 714 |
+
rad = mid_a * np.pi / 180
|
| 715 |
+
|
| 716 |
+
# Determine if label should be placed radially outward or inward
|
| 717 |
+
if mid_a > 90 and mid_a < 270:
|
| 718 |
+
# Bottom half - place labels inside
|
| 719 |
+
label_radius = r_chr_band - 0.05
|
| 720 |
+
text_angle = mid_a
|
| 721 |
+
else:
|
| 722 |
+
# Top half - place outside
|
| 723 |
+
label_radius = r_chr_band + 0.08
|
| 724 |
+
text_angle = mid_a
|
| 725 |
+
|
| 726 |
+
# Connector line
|
| 727 |
+
r_connector = [r_chr_band, label_radius]
|
| 728 |
+
theta_connector = [mid_a, mid_a]
|
| 729 |
+
fig.add_trace(go.Scatterpolar(
|
| 730 |
+
r=r_connector,
|
| 731 |
+
theta=theta_connector,
|
| 732 |
+
mode='lines',
|
| 733 |
+
line=dict(color=col, width=1.5),
|
| 734 |
+
showlegend=False,
|
| 735 |
+
hoverinfo='skip',
|
| 736 |
+
))
|
| 737 |
+
|
| 738 |
+
# Label text
|
| 739 |
fig.add_trace(go.Scatterpolar(
|
| 740 |
+
r=[label_radius - 0.02 if mid_a > 90 and mid_a < 270 else label_radius + 0.02],
|
| 741 |
theta=[mid_a],
|
| 742 |
mode='text',
|
| 743 |
text=[f"<b>Chr{ch}</b>"],
|
| 744 |
+
textfont=dict(size=9, color=col, weight='bold'),
|
| 745 |
showlegend=False,
|
| 746 |
hoverinfo='skip',
|
|
|
|
| 747 |
))
|
| 748 |
|
| 749 |
+
# ββ 2. Model data rings ββ
|
| 750 |
for midx, (mname, (pvals, betas, _)) in enumerate(selected_results.items()):
|
| 751 |
pvals_s = pvals[sort_idx]
|
| 752 |
log_p_s = -np.log10(np.clip(pvals_s, 1e-300, 1))
|
|
|
|
| 754 |
r_base = ring_inner + midx * (ring_width + ring_gap)
|
| 755 |
r_top = r_base + ring_width
|
| 756 |
max_lp = max(log_p_s.max(), sig_line, 1.0)
|
|
|
|
| 757 |
r_data = r_base + (log_p_s / max_lp) * ring_width * 0.9
|
| 758 |
col = MODEL_COLORS.get(mname, CHR_PALETTE[midx % len(CHR_PALETTE)])
|
| 759 |
|
|
|
|
| 766 |
r=r_data[ns_mask],
|
| 767 |
theta=angles_deg[ns_mask],
|
| 768 |
mode='markers',
|
| 769 |
+
marker=dict(color=col, size=2.5, opacity=0.6, line=dict(width=0)),
|
| 770 |
name=mname,
|
| 771 |
legendgroup=mname,
|
| 772 |
text=[f"Model: {mname}<br>SNP: {snp_s[i]}<br>Chr: {chroms_s[i]}<br>"
|
| 773 |
f"p: {pvals_s[ns_mask][k]:.3e}<br>-log10(p): {log_p_s[ns_mask][k]:.2f}"
|
| 774 |
for k, i in enumerate(np.where(ns_mask)[0])],
|
| 775 |
hovertemplate="%{text}<extra></extra>",
|
| 776 |
+
showlegend=(midx == 0),
|
| 777 |
))
|
| 778 |
|
| 779 |
+
# Significant SNPs
|
| 780 |
if sig_mask.any():
|
| 781 |
sig_idxs = np.where(sig_mask)[0]
|
| 782 |
fig.add_trace(go.Scatterpolar(
|
|
|
|
| 784 |
theta=angles_deg[sig_mask],
|
| 785 |
mode='markers',
|
| 786 |
marker=dict(
|
| 787 |
+
color='#FF1744', size=8, symbol='diamond',
|
| 788 |
+
line=dict(color='#7F0000', width=0.8)
|
| 789 |
),
|
| 790 |
+
name=f"{mname} β
",
|
| 791 |
legendgroup=f"{mname}_sig",
|
| 792 |
text=[f"<b>β
GW SIGNIFICANT β
</b><br>Model: {mname}<br>SNP: {snp_s[i]}<br>"
|
| 793 |
f"Chr: {chroms_s[i]}<br>p: {pvals_s[sig_mask][k]:.3e}"
|
| 794 |
for k, i in enumerate(sig_idxs)],
|
| 795 |
hovertemplate="%{text}<extra></extra>",
|
| 796 |
+
showlegend=(midx == 0 and len(sig_idxs) > 0),
|
| 797 |
))
|
| 798 |
|
| 799 |
+
# Model label - placed in dedicated corner (bottom left)
|
| 800 |
+
lam_val = compute_lambda(pvals)
|
| 801 |
+
label_angle = 270 - (midx * 15) # Spread labels around bottom
|
| 802 |
+
r_mid = (r_base + r_top) / 2
|
| 803 |
+
|
| 804 |
fig.add_trace(go.Scatterpolar(
|
| 805 |
+
r=[r_mid],
|
| 806 |
+
theta=[label_angle],
|
| 807 |
+
mode='text',
|
| 808 |
+
text=[f"<b>{mname}</b>"],
|
| 809 |
+
textfont=dict(size=8, color=col),
|
| 810 |
+
showlegend=False,
|
| 811 |
+
hoverinfo='skip',
|
| 812 |
+
))
|
| 813 |
+
|
| 814 |
+
# Lambda annotation near model label
|
| 815 |
+
fig.add_trace(go.Scatterpolar(
|
| 816 |
+
r=[r_mid - 0.02],
|
| 817 |
+
theta=[label_angle + 2],
|
| 818 |
+
mode='text',
|
| 819 |
+
text=[f"Ξ»={lam_val:.3f}"],
|
| 820 |
+
textfont=dict(size=6, color='gray'),
|
| 821 |
showlegend=False,
|
| 822 |
hoverinfo='skip',
|
|
|
|
| 823 |
))
|
| 824 |
|
| 825 |
+
# ββ 3. Center circle ββ
|
| 826 |
+
fig.add_trace(go.Scatterpolar(
|
| 827 |
+
r=[ring_inner] * 361,
|
| 828 |
+
theta=list(range(361)),
|
| 829 |
+
mode='lines',
|
| 830 |
+
line=dict(color='#CBD5E1', width=1),
|
| 831 |
+
fill='toself',
|
| 832 |
+
fillcolor='rgba(248,250,252,0.9)',
|
| 833 |
+
showlegend=False,
|
| 834 |
+
hoverinfo='skip',
|
| 835 |
+
))
|
| 836 |
+
|
| 837 |
+
# ββ 4. Inner circle text (GWAS title) ββ
|
| 838 |
+
fig.add_trace(go.Scatterpolar(
|
| 839 |
+
r=[ring_inner - 0.05],
|
| 840 |
+
theta=[0],
|
| 841 |
+
mode='text',
|
| 842 |
+
text=['<b>GWAS<br>Circos</b>'],
|
| 843 |
+
textfont=dict(size=11, color='#2C5F8A'),
|
| 844 |
+
showlegend=False,
|
| 845 |
+
hoverinfo='skip',
|
| 846 |
+
))
|
| 847 |
+
|
| 848 |
+
lam_str = " | ".join([
|
| 849 |
+
f"{m} Ξ»={compute_lambda(all_results[m][0]):.3f}" for m in best_models
|
| 850 |
+
])
|
| 851 |
+
n_sig_total = sum(int((all_results[m][0] < 5e-8).sum()) for m in best_models)
|
| 852 |
+
|
| 853 |
+
fig.update_layout(
|
| 854 |
+
title=dict(
|
| 855 |
+
text=(f"<b>Circos Plot β Best {n_models} Models</b>"
|
| 856 |
+
f"<br><sup style='font-size:10px;'>{lam_str}</sup>"
|
| 857 |
+
f"<br><sup style='font-size:9px;color:#FF4560;'>β
= Genome-wide significant (5Γ10β»βΈ) | Total sig hits: {n_sig_total}</sup>"),
|
| 858 |
+
font=dict(size=13, color="#1E293B"),
|
| 859 |
+
x=0.5,
|
| 860 |
+
xanchor='center',
|
| 861 |
+
),
|
| 862 |
+
polar=dict(
|
| 863 |
+
radialaxis=dict(
|
| 864 |
+
showticklabels=False,
|
| 865 |
+
showgrid=False,
|
| 866 |
+
showline=False,
|
| 867 |
+
range=[0, 1.0],
|
| 868 |
+
),
|
| 869 |
+
angularaxis=dict(
|
| 870 |
+
showticklabels=False,
|
| 871 |
+
showgrid=False,
|
| 872 |
+
showline=False,
|
| 873 |
+
direction="clockwise",
|
| 874 |
+
rotation=90,
|
| 875 |
+
),
|
| 876 |
+
bgcolor="white",
|
| 877 |
+
),
|
| 878 |
+
showlegend=True,
|
| 879 |
+
legend=dict(
|
| 880 |
+
orientation="v",
|
| 881 |
+
yanchor="middle",
|
| 882 |
+
y=0.5,
|
| 883 |
+
xanchor="left",
|
| 884 |
+
x=1.05,
|
| 885 |
+
font=dict(size=10),
|
| 886 |
+
itemsizing='constant',
|
| 887 |
+
bordercolor="#E2E8F0",
|
| 888 |
+
borderwidth=1,
|
| 889 |
+
bgcolor="rgba(255,255,255,0.95)",
|
| 890 |
+
),
|
| 891 |
+
paper_bgcolor="white",
|
| 892 |
+
height=700,
|
| 893 |
+
width=900,
|
| 894 |
+
margin=dict(l=50, r=180, t=120, b=50),
|
| 895 |
+
)
|
| 896 |
+
return fig
|
| 897 |
+
|
| 898 |
+
# βββββββββββββββββββββββ INTERACTIVE MANHATTAN PLOT (STARTS FROM CHR1) ββββββββ
|
| 899 |
+
def plot_manhattan_interactive(pvals, chroms, positions, snp_names, title="Manhattan Plot", model_name=""):
|
| 900 |
+
"""FIX: x-axis starts from chromosome 1 (not 0)."""
|
| 901 |
+
log_p = -np.log10(np.clip(pvals, 1e-300, 1))
|
| 902 |
+
sig_line = -np.log10(5e-8)
|
| 903 |
+
sug_line = -np.log10(1e-5)
|
| 904 |
+
chrom_list = sorted(set(chroms))
|
| 905 |
+
x_coords = _compute_x_coords(chroms, positions, chrom_list)
|
| 906 |
+
|
| 907 |
+
# Ensure x-axis starts at 1
|
| 908 |
+
x_min = 1
|
| 909 |
+
x_max = x_coords.max() if len(x_coords) > 0 else 100
|
| 910 |
+
|
| 911 |
+
fig = go.Figure()
|
| 912 |
+
|
| 913 |
+
for ci, ch in enumerate(chrom_list):
|
| 914 |
+
mask = chroms == ch
|
| 915 |
+
col = CHR_PALETTE[ci % len(CHR_PALETTE)]
|
| 916 |
+
xc = x_coords[mask]
|
| 917 |
+
yc = log_p[mask]
|
| 918 |
+
nm = [str(snp_names[i]) for i in np.where(mask)[0]]
|
| 919 |
+
pc = [float(pvals[i]) for i in np.where(mask)[0]]
|
| 920 |
+
|
| 921 |
+
sig_m = yc >= sig_line
|
| 922 |
+
ns_m = ~sig_m
|
| 923 |
+
|
| 924 |
+
if ns_m.any():
|
| 925 |
+
fig.add_trace(go.Scatter(
|
| 926 |
+
x=xc[ns_m], y=yc[ns_m],
|
| 927 |
+
mode='markers',
|
| 928 |
+
marker=dict(color=col, size=4, opacity=0.75, line=dict(width=0)),
|
| 929 |
+
name=f"Chr{ch}",
|
| 930 |
+
text=[f"SNP: {nm[i]}<br>Chr: {ch}<br>p-value: {pc[i]:.3e}<br>-log10(p): {yc[ns_m][i]:.2f}"
|
| 931 |
+
for i in range(ns_m.sum())],
|
| 932 |
+
hovertemplate="%{text}<extra></extra>",
|
| 933 |
+
showlegend=(ci < 10),
|
| 934 |
+
))
|
| 935 |
+
if sig_m.any():
|
| 936 |
+
fig.add_trace(go.Scatter(
|
| 937 |
+
x=xc[sig_m], y=yc[sig_m],
|
| 938 |
+
mode='markers',
|
| 939 |
+
marker=dict(color='#FF1744', size=10, symbol='diamond',
|
| 940 |
+
line=dict(color='#7F0000', width=1)),
|
| 941 |
+
name=f"Sig (Chr{ch})",
|
| 942 |
+
text=[f"<b>SIGNIFICANT</b><br>SNP: {nm[i]}<br>Chr: {ch}<br>p-value: {pc[i]:.3e}<br>-log10(p): {yc[sig_m][i]:.2f}"
|
| 943 |
+
for i in range(sig_m.sum())],
|
| 944 |
+
hovertemplate="%{text}<extra></extra>",
|
| 945 |
showlegend=False,
|
|
|
|
|
|
|
| 946 |
))
|
| 947 |
|
| 948 |
+
fig.add_shape(type="line", x0=x_min, x1=x_max, y0=sig_line, y1=sig_line,
|
| 949 |
+
line=dict(color="#FF4560", width=2, dash="dash"))
|
| 950 |
+
fig.add_shape(type="line", x0=x_min, x1=x_max, y0=sug_line, y1=sug_line,
|
| 951 |
+
line=dict(color="#00D9E9", width=1.5, dash="dot"))
|
| 952 |
+
|
| 953 |
+
fig.add_annotation(x=x_max*0.98, y=sig_line+0.3, text="GW significant (5Γ10β»βΈ)",
|
| 954 |
+
showarrow=False, font=dict(color="#FF4560", size=10),
|
| 955 |
+
xanchor="right")
|
| 956 |
+
fig.add_annotation(x=x_max*0.98, y=sug_line+0.3, text="Suggestive (1Γ10β»β΅)",
|
| 957 |
+
showarrow=False, font=dict(color="#00D9E9", size=10),
|
| 958 |
+
xanchor="right")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 959 |
|
| 960 |
+
tick_pos, tick_lab = _compute_tick_positions(x_coords, chroms, chrom_list)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 961 |
|
| 962 |
+
lam = compute_lambda(pvals)
|
| 963 |
+
n_sig = int((pvals < 5e-8).sum())
|
|
|
|
|
|
|
|
|
|
| 964 |
|
| 965 |
fig.update_layout(
|
| 966 |
title=dict(
|
| 967 |
+
text=f"<b>{title} β {model_name}</b><br><sup>Ξ» = {lam:.4f} | Significant SNPs: {n_sig} | Total: {len(pvals)}</sup>",
|
| 968 |
+
font=dict(size=15, color="#1E293B"),
|
|
|
|
|
|
|
|
|
|
|
|
|
| 969 |
),
|
| 970 |
+
xaxis=dict(
|
| 971 |
+
tickmode='array',
|
| 972 |
+
tickvals=tick_pos,
|
| 973 |
+
ticktext=tick_lab,
|
| 974 |
+
tickangle=45,
|
| 975 |
+
tickfont=dict(size=9),
|
| 976 |
+
showgrid=False,
|
| 977 |
+
zeroline=False,
|
| 978 |
+
title="Chromosome",
|
| 979 |
+
range=[x_min * 0.95, x_max * 1.01],
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 980 |
),
|
| 981 |
+
yaxis=dict(
|
| 982 |
+
title="-logββ(p-value)",
|
| 983 |
+
gridcolor="#E2E8F0",
|
| 984 |
+
gridwidth=0.5,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 985 |
),
|
| 986 |
+
plot_bgcolor="white",
|
| 987 |
paper_bgcolor="white",
|
| 988 |
+
height=520,
|
| 989 |
+
legend=dict(
|
| 990 |
+
orientation="h",
|
| 991 |
+
yanchor="bottom",
|
| 992 |
+
y=1.02,
|
| 993 |
+
xanchor="right",
|
| 994 |
+
x=1,
|
| 995 |
+
font=dict(size=9),
|
| 996 |
+
),
|
| 997 |
+
hovermode="closest",
|
| 998 |
+
margin=dict(l=60, r=40, t=100, b=80),
|
| 999 |
)
|
| 1000 |
return fig
|
| 1001 |
|
| 1002 |
+
# βββββββββββββββββββββββ IMPROVED LD DECAY PLOT (WITH FULL INTERPRETATION) βββββ
|
|
|
|
| 1003 |
def plot_ld_decay_interactive(G, positions, chroms):
|
| 1004 |
"""
|
| 1005 |
+
IMPROVED LD Decay plot (distance in Mb) with comprehensive interpretation:
|
| 1006 |
+
- x-axis: Physical distance (Megabases, Mb)
|
| 1007 |
+
- y-axis: LD estimate (rΒ²)
|
| 1008 |
+
- Shows where LD starts dropping significantly
|
| 1009 |
+
- Calculates half-decay distance
|
| 1010 |
+
- Adds interpretation annotations
|
|
|
|
|
|
|
|
|
|
| 1011 |
"""
|
| 1012 |
chrom_list = sorted(set(chroms))
|
| 1013 |
+
sample_per_chr = 100
|
| 1014 |
sampled_idx = []
|
| 1015 |
rng = np.random.default_rng(42)
|
| 1016 |
for ch in chrom_list:
|
| 1017 |
idx_ch = np.where(chroms == ch)[0]
|
| 1018 |
n_samp = min(sample_per_chr, len(idx_ch))
|
| 1019 |
+
if n_samp > 0:
|
| 1020 |
+
sampled_idx.extend(rng.choice(idx_ch, n_samp, replace=False).tolist())
|
| 1021 |
sampled_idx = sorted(set(sampled_idx))
|
| 1022 |
|
| 1023 |
dists_bp, r2s, chrom_pairs = [], [], []
|
| 1024 |
for ii, i in enumerate(sampled_idx):
|
| 1025 |
for j in sampled_idx[ii+1:]:
|
| 1026 |
if chroms[i] != chroms[j]:
|
| 1027 |
+
continue
|
| 1028 |
xi, xj = G[:, i], G[:, j]
|
| 1029 |
mask = ~(np.isnan(xi) | np.isnan(xj))
|
| 1030 |
if mask.sum() < 4:
|
|
|
|
| 1057 |
r2s = np.array(r2s)
|
| 1058 |
chrom_pairs = np.array(chrom_pairs)
|
| 1059 |
|
| 1060 |
+
# Convert bp β Mb
|
| 1061 |
+
dists_Mb = dists_bp / 1_000_000
|
| 1062 |
|
| 1063 |
# ββ Scatter: color by chromosome ββ
|
| 1064 |
for ci, ch in enumerate(chrom_list):
|
|
|
|
| 1066 |
if not cmask.any():
|
| 1067 |
continue
|
| 1068 |
col = CHR_PALETTE[ci % len(CHR_PALETTE)]
|
|
|
|
| 1069 |
idx_sub = np.where(cmask)[0]
|
| 1070 |
+
if len(idx_sub) > 800:
|
| 1071 |
+
idx_sub = rng.choice(idx_sub, 800, replace=False)
|
| 1072 |
fig.add_trace(go.Scatter(
|
| 1073 |
+
x=dists_Mb[idx_sub],
|
| 1074 |
y=r2s[idx_sub],
|
| 1075 |
mode='markers',
|
| 1076 |
marker=dict(
|
| 1077 |
+
color=col, size=3, opacity=0.35,
|
| 1078 |
line=dict(width=0),
|
| 1079 |
),
|
| 1080 |
name=f"Chr{ch}",
|
| 1081 |
legendgroup=f"chr{ch}",
|
| 1082 |
+
hovertemplate=f"<b>Chromosome {ch}</b><br>Distance: %{{x:.3f}} Mb<br>rΒ²: %{{y:.3f}}<extra></extra>",
|
| 1083 |
))
|
| 1084 |
|
| 1085 |
+
# ββ Binned means for decay curve ββ
|
| 1086 |
+
n_bins = 40
|
| 1087 |
+
pctiles = np.percentile(dists_Mb, np.linspace(0, 100, n_bins + 1))
|
| 1088 |
bin_centers, bin_means, bin_sems, bin_counts = [], [], [], []
|
| 1089 |
for k in range(len(pctiles) - 1):
|
| 1090 |
+
mask = (dists_Mb >= pctiles[k]) & (dists_Mb < pctiles[k + 1])
|
| 1091 |
if mask.sum() >= 3:
|
| 1092 |
+
bin_centers.append(np.median(dists_Mb[mask]))
|
| 1093 |
bin_means.append(np.mean(r2s[mask]))
|
| 1094 |
bin_sems.append(stats.sem(r2s[mask]) if mask.sum() > 1 else 0)
|
| 1095 |
bin_counts.append(mask.sum())
|
|
|
|
| 1098 |
bin_means = np.array(bin_means)
|
| 1099 |
bin_sems = np.array(bin_sems)
|
| 1100 |
|
| 1101 |
+
# Fit exponential decay curve
|
| 1102 |
smooth_x = np.array([])
|
| 1103 |
smooth_y = np.array([])
|
| 1104 |
+
half_decay_dist = None
|
| 1105 |
+
r2_plateau = None
|
| 1106 |
+
r2_initial = None
|
| 1107 |
+
|
| 1108 |
if len(bin_centers) >= 4:
|
| 1109 |
try:
|
| 1110 |
from scipy.optimize import curve_fit
|
| 1111 |
def decay_func(d, a, b, c):
|
| 1112 |
return a * np.exp(-b * d) + c
|
| 1113 |
+
p0 = [0.8, 0.5, 0.05]
|
| 1114 |
+
bounds = ([0, 0.01, 0], [1.0, 100, 0.5])
|
| 1115 |
popt, _ = curve_fit(decay_func, bin_centers, bin_means,
|
| 1116 |
p0=p0, bounds=bounds, maxfev=5000)
|
| 1117 |
+
smooth_x = np.linspace(dists_Mb.min(), dists_Mb.max(), 300)
|
| 1118 |
smooth_y = decay_func(smooth_x, *popt)
|
| 1119 |
smooth_y = np.clip(smooth_y, 0, 1)
|
| 1120 |
+
|
| 1121 |
+
# Calculate half-decay distance (where rΒ² drops to halfway between initial and plateau)
|
|
|
|
|
|
|
| 1122 |
r2_plateau = float(popt[2])
|
| 1123 |
+
r2_initial = float(popt[0] + popt[2])
|
| 1124 |
+
r2_half = (r2_initial + r2_plateau) / 2
|
| 1125 |
+
|
| 1126 |
+
# Find distance where rΒ² reaches half
|
| 1127 |
above_half = smooth_x[smooth_y >= r2_half]
|
| 1128 |
if len(above_half) > 0:
|
| 1129 |
+
half_decay_dist = above_half[-1]
|
| 1130 |
+
|
| 1131 |
except Exception:
|
| 1132 |
smooth_x = bin_centers
|
| 1133 |
smooth_y = bin_means
|
| 1134 |
+
half_decay_dist = None
|
| 1135 |
else:
|
| 1136 |
smooth_x = bin_centers
|
| 1137 |
smooth_y = bin_means
|
|
|
|
| 1138 |
|
| 1139 |
+
# ββ Smooth decay curve ββ
|
| 1140 |
if len(smooth_x) > 0:
|
| 1141 |
fig.add_trace(go.Scatter(
|
| 1142 |
x=smooth_x, y=smooth_y,
|
| 1143 |
mode='lines',
|
| 1144 |
line=dict(color='black', width=3),
|
| 1145 |
name='Fitted decay curve',
|
| 1146 |
+
hovertemplate="Distance: %{x:.3f} Mb<br>Fitted rΒ²: %{y:.3f}<extra></extra>",
|
| 1147 |
))
|
| 1148 |
|
| 1149 |
+
# ββ Binned mean points with error bars ββ
|
| 1150 |
if len(bin_centers) > 0:
|
| 1151 |
fig.add_trace(go.Scatter(
|
| 1152 |
x=bin_centers, y=bin_means,
|
| 1153 |
mode='markers',
|
| 1154 |
+
marker=dict(color='darkred', size=6, symbol='circle',
|
| 1155 |
line=dict(color='white', width=1)),
|
| 1156 |
name='Binned mean rΒ²',
|
| 1157 |
error_y=dict(type='data', array=bin_sems, visible=True,
|
| 1158 |
+
color='rgba(0,0,0,0.4)', thickness=1.5, width=3),
|
| 1159 |
+
hovertemplate="Distance: %{x:.3f} Mb<br>Mean rΒ²: %{y:.3f}<br>Β±SEM<extra></extra>",
|
| 1160 |
))
|
| 1161 |
|
| 1162 |
+
# ββ Reference lines ββ
|
| 1163 |
+
x_max_plot = float(np.percentile(dists_Mb, 98)) * 1.05 if len(dists_Mb) > 0 else 10
|
| 1164 |
|
| 1165 |
+
# rΒ² = 0.5 line (strong LD threshold)
|
| 1166 |
+
fig.add_shape(
|
| 1167 |
+
type="line", x0=0, x1=x_max_plot, y0=0.5, y1=0.5,
|
| 1168 |
+
line=dict(color="#E67E22", width=2, dash="dash"),
|
| 1169 |
+
)
|
| 1170 |
+
fig.add_annotation(
|
| 1171 |
+
x=x_max_plot * 0.98, y=0.52,
|
| 1172 |
+
text="rΒ² = 0.5 (Strong LD)",
|
| 1173 |
+
showarrow=False,
|
| 1174 |
+
font=dict(size=10, color="#E67E22", weight="bold"),
|
| 1175 |
+
xanchor="right",
|
| 1176 |
+
)
|
| 1177 |
+
|
| 1178 |
+
# rΒ² = 0.2 line (weak LD threshold)
|
| 1179 |
+
fig.add_shape(
|
| 1180 |
+
type="line", x0=0, x1=x_max_plot, y0=0.2, y1=0.2,
|
| 1181 |
+
line=dict(color="#3498DB", width=2, dash="dot"),
|
| 1182 |
+
)
|
| 1183 |
+
fig.add_annotation(
|
| 1184 |
+
x=x_max_plot * 0.98, y=0.22,
|
| 1185 |
+
text="rΒ² = 0.2 (Weak LD)",
|
| 1186 |
+
showarrow=False,
|
| 1187 |
+
font=dict(size=10, color="#3498DB"),
|
| 1188 |
+
xanchor="right",
|
| 1189 |
+
)
|
| 1190 |
|
| 1191 |
# ββ Half-decay annotation ββ
|
| 1192 |
+
if half_decay_dist is not None and half_decay_dist > 0:
|
| 1193 |
fig.add_shape(
|
| 1194 |
+
type="line", x0=half_decay_dist, x1=half_decay_dist, y0=0, y1=r2_half,
|
| 1195 |
+
line=dict(color='#2ECC71', width=2.5, dash='dash'),
|
| 1196 |
)
|
| 1197 |
fig.add_annotation(
|
| 1198 |
+
x=half_decay_dist + (x_max_plot * 0.02), y=r2_half + 0.05,
|
| 1199 |
+
text=f"<b>Half-decay distance</b><br>{half_decay_dist:.2f} Mb",
|
| 1200 |
showarrow=True,
|
| 1201 |
arrowhead=2,
|
| 1202 |
arrowcolor='#2ECC71',
|
| 1203 |
+
font=dict(size=10, color='#2ECC71', weight="bold"),
|
| 1204 |
ax=30, ay=-30,
|
| 1205 |
)
|
| 1206 |
|
| 1207 |
+
# ββ Comprehensive interpretation box ββ
|
| 1208 |
overall_mean_r2 = float(np.mean(r2s)) if len(r2s) > 0 else 0
|
| 1209 |
+
n_pairs = len(r2s)
|
| 1210 |
+
|
| 1211 |
+
# Calculate LD decay rate (percentage drop in first few Mb)
|
| 1212 |
+
early_bins = bin_centers[bin_centers <= 1] if len(bin_centers) > 0 else []
|
| 1213 |
+
early_means = bin_means[bin_centers <= 1] if len(bin_centers) > 0 else []
|
| 1214 |
+
decay_rate = None
|
| 1215 |
+
if len(early_bins) >= 2:
|
| 1216 |
+
slope, _ = np.polyfit(early_bins, early_means, 1)
|
| 1217 |
+
decay_rate = abs(slope * 100) # % drop per Mb
|
| 1218 |
+
|
| 1219 |
interp_text = (
|
| 1220 |
+
f"<b>π LD DECAY ANALYSIS</b><br>"
|
| 1221 |
+
f"ββββββββββββββββββββββ<br>"
|
| 1222 |
+
f"<b>Pairs analyzed:</b> {n_pairs:,}<br>"
|
| 1223 |
+
f"<b>Mean rΒ² overall:</b> {overall_mean_r2:.3f}<br>"
|
| 1224 |
+
)
|
| 1225 |
+
|
| 1226 |
+
if r2_initial is not None:
|
| 1227 |
+
interp_text += f"<b>Initial LD (0 Mb):</b> {r2_initial:.3f}<br>"
|
| 1228 |
+
if r2_plateau is not None:
|
| 1229 |
+
interp_text += f"<b>Plateau LD:</b> {r2_plateau:.3f}<br>"
|
| 1230 |
+
if half_decay_dist is not None:
|
| 1231 |
+
interp_text += f"<b>Half-decay distance:</b> {half_decay_dist:.2f} Mb<br>"
|
| 1232 |
+
if decay_rate is not None:
|
| 1233 |
+
interp_text += f"<b>Initial decay rate:</b> {decay_rate:.1f}% per Mb<br>"
|
| 1234 |
+
|
| 1235 |
+
interp_text += (
|
| 1236 |
+
f"ββββββββββββββββββββββ<br>"
|
| 1237 |
+
f"<span style='color:#2ECC71;'>βΌ INTERPRETATION</span><br>"
|
| 1238 |
)
|
| 1239 |
+
|
| 1240 |
+
if half_decay_dist is not None:
|
| 1241 |
+
if half_decay_dist < 0.1:
|
| 1242 |
+
interp_text += f"β’ <b>Very rapid LD decay</b> (half at {half_decay_dist*1000:.0f} kb)<br> β Suggests diverse germplasm / fine mapping feasible<br>"
|
| 1243 |
+
elif half_decay_dist < 0.5:
|
| 1244 |
+
interp_text += f"β’ <b>Moderate LD decay</b> (half at {half_decay_dist:.2f} Mb)<br> β Moderate genetic diversity<br>"
|
| 1245 |
+
else:
|
| 1246 |
+
interp_text += f"β’ <b>Slow LD decay</b> (half at {half_decay_dist:.2f} Mb)<br> β Narrow genetic base / linkage blocks large<br>"
|
| 1247 |
+
|
| 1248 |
+
if overall_mean_r2 > 0.4:
|
| 1249 |
+
interp_text += f"β’ <b>High overall LD</b> (mean rΒ²={overall_mean_r2:.2f})<br> β Fewer independent tests, lower mapping resolution<br>"
|
| 1250 |
+
elif overall_mean_r2 > 0.2:
|
| 1251 |
+
interp_text += f"β’ <b>Moderate overall LD</b> (mean rΒ²={overall_mean_r2:.2f})<br> β Balanced mapping resolution<br>"
|
| 1252 |
+
else:
|
| 1253 |
+
interp_text += f"β’ <b>Low overall LD</b> (mean rΒ²={overall_mean_r2:.2f})<br> β High mapping resolution, many independent tests<br>"
|
| 1254 |
+
|
| 1255 |
fig.add_annotation(
|
| 1256 |
+
x=0.02, y=0.98, xref="paper", yref="paper",
|
| 1257 |
text=interp_text,
|
| 1258 |
showarrow=False,
|
| 1259 |
+
font=dict(size=10, color="#2D3142", family="monospace"),
|
| 1260 |
bgcolor="rgba(255,255,255,0.92)",
|
| 1261 |
bordercolor="#CBD5E1",
|
| 1262 |
borderwidth=1.5,
|
| 1263 |
borderpad=8,
|
| 1264 |
align="left",
|
| 1265 |
+
xanchor="left",
|
| 1266 |
yanchor="top",
|
| 1267 |
)
|
| 1268 |
|
| 1269 |
fig.update_layout(
|
| 1270 |
title=dict(
|
| 1271 |
text=(
|
| 1272 |
+
"<b>π Linkage Disequilibrium (LD) Decay Analysis</b>"
|
| 1273 |
+
"<br><sup style='font-size:11px;'>Intra-chromosomal pairwise rΒ² vs physical distance (Mb) | "
|
| 1274 |
+
"Black curve = fitted exponential decay | Colored points = individual SNP pairs</sup>"
|
| 1275 |
),
|
| 1276 |
font=dict(size=14, color="#1E293B"),
|
| 1277 |
),
|
| 1278 |
xaxis=dict(
|
| 1279 |
+
title="<b>Physical distance (Megabases, Mb)</b>",
|
| 1280 |
gridcolor="#E2E8F0",
|
| 1281 |
gridwidth=0.8,
|
| 1282 |
zeroline=True,
|
| 1283 |
zerolinecolor="#CBD5E1",
|
| 1284 |
range=[0, x_max_plot],
|
| 1285 |
tickfont=dict(size=11),
|
| 1286 |
+
ticksuffix=" Mb",
|
| 1287 |
),
|
| 1288 |
yaxis=dict(
|
| 1289 |
+
title="<b>Linkage disequilibrium (rΒ²)</b>",
|
| 1290 |
gridcolor="#E2E8F0",
|
| 1291 |
gridwidth=0.8,
|
| 1292 |
range=[0, 1.05],
|
|
|
|
| 1295 |
),
|
| 1296 |
plot_bgcolor="white",
|
| 1297 |
paper_bgcolor="white",
|
| 1298 |
+
height=600,
|
| 1299 |
hovermode="closest",
|
| 1300 |
legend=dict(
|
| 1301 |
orientation="v",
|
| 1302 |
yanchor="top",
|
| 1303 |
+
y=0.99,
|
| 1304 |
+
xanchor="right",
|
| 1305 |
+
x=0.99,
|
| 1306 |
font=dict(size=9),
|
| 1307 |
bgcolor="rgba(255,255,255,0.85)",
|
| 1308 |
bordercolor="#E2E8F0",
|
| 1309 |
borderwidth=1,
|
| 1310 |
),
|
| 1311 |
+
margin=dict(l=80, r=220, t=100, b=70),
|
| 1312 |
+
)
|
| 1313 |
+
return fig
|
| 1314 |
+
|
| 1315 |
+
|
| 1316 |
+
# βββββββββββββββββββββββ INTERACTIVE QQ PLOT ββββββββββββββββββββββββββββββββββ
|
| 1317 |
+
def plot_qq_interactive_single(pvals, model_name="", color=None):
|
| 1318 |
+
"""Interactive QQ plot with confidence band."""
|
| 1319 |
+
if color is None:
|
| 1320 |
+
color = "#775DD0"
|
| 1321 |
+
n = len(pvals)
|
| 1322 |
+
obs_raw = -np.log10(np.clip(pvals, 1e-300, 1))
|
| 1323 |
+
sort_i = np.argsort(obs_raw)[::-1]
|
| 1324 |
+
obs = obs_raw[sort_i]
|
| 1325 |
+
exp = -np.log10(np.arange(1, n + 1) / n)
|
| 1326 |
+
|
| 1327 |
+
ranks = np.arange(1, n + 1)
|
| 1328 |
+
ci_lo = -np.log10(stats.beta.ppf(0.975, ranks, n - ranks + 1))
|
| 1329 |
+
ci_hi = -np.log10(stats.beta.ppf(0.025, ranks, n - ranks + 1))
|
| 1330 |
+
|
| 1331 |
+
lam = compute_lambda(pvals)
|
| 1332 |
+
lam_col = "green" if lam <= 1.05 else "orange" if lam <= 1.15 else "red"
|
| 1333 |
+
sig_thr = -np.log10(5e-8)
|
| 1334 |
+
|
| 1335 |
+
fig = go.Figure()
|
| 1336 |
+
|
| 1337 |
+
fig.add_trace(go.Scatter(
|
| 1338 |
+
x=np.concatenate([exp, exp[::-1]]),
|
| 1339 |
+
y=np.concatenate([ci_hi, ci_lo[::-1]]),
|
| 1340 |
+
fill='toself',
|
| 1341 |
+
fillcolor='rgba(120,120,180,0.15)',
|
| 1342 |
+
line=dict(color='rgba(0,0,0,0)'),
|
| 1343 |
+
name='95% CI',
|
| 1344 |
+
hoverinfo='skip',
|
| 1345 |
+
))
|
| 1346 |
+
|
| 1347 |
+
xy_max = max(float(exp.max()), float(obs.max())) * 1.06
|
| 1348 |
+
fig.add_trace(go.Scatter(
|
| 1349 |
+
x=[0, xy_max], y=[0, xy_max],
|
| 1350 |
+
mode='lines',
|
| 1351 |
+
line=dict(color='#E8453C', width=2, dash='dash'),
|
| 1352 |
+
name='Expected (y=x)',
|
| 1353 |
+
hoverinfo='skip',
|
| 1354 |
+
))
|
| 1355 |
+
|
| 1356 |
+
sig_mask = obs >= sig_thr
|
| 1357 |
+
ns_mask = ~sig_mask
|
| 1358 |
+
|
| 1359 |
+
if ns_mask.any():
|
| 1360 |
+
fig.add_trace(go.Scatter(
|
| 1361 |
+
x=exp[ns_mask], y=obs[ns_mask],
|
| 1362 |
+
mode='markers',
|
| 1363 |
+
marker=dict(color=color, size=5, opacity=0.8),
|
| 1364 |
+
name='Non-significant',
|
| 1365 |
+
text=[f"Expected: {exp[ns_mask][i]:.3f}<br>Observed: {obs[ns_mask][i]:.3f}"
|
| 1366 |
+
for i in range(ns_mask.sum())],
|
| 1367 |
+
hovertemplate="%{text}<extra></extra>",
|
| 1368 |
+
))
|
| 1369 |
+
if sig_mask.any():
|
| 1370 |
+
fig.add_trace(go.Scatter(
|
| 1371 |
+
x=exp[sig_mask], y=obs[sig_mask],
|
| 1372 |
+
mode='markers',
|
| 1373 |
+
marker=dict(color='#FF1744', size=10, symbol='diamond',
|
| 1374 |
+
line=dict(color='#7F0000', width=1)),
|
| 1375 |
+
name=f'GW Significant ({sig_mask.sum()})',
|
| 1376 |
+
text=[f"Expected: {exp[sig_mask][i]:.3f}<br>Observed: {obs[sig_mask][i]:.3f}"
|
| 1377 |
+
for i in range(sig_mask.sum())],
|
| 1378 |
+
hovertemplate="%{text}<extra></extra>",
|
| 1379 |
+
))
|
| 1380 |
+
|
| 1381 |
+
fig.add_shape(type="line", x0=0, x1=xy_max, y0=sig_thr, y1=sig_thr,
|
| 1382 |
+
line=dict(color="#FF4560", width=1, dash="dot"))
|
| 1383 |
+
|
| 1384 |
+
fig.add_annotation(
|
| 1385 |
+
x=0.05, y=0.95, xref="paper", yref="paper",
|
| 1386 |
+
text=f"Ξ» = {lam:.4f}",
|
| 1387 |
+
showarrow=False,
|
| 1388 |
+
font=dict(size=14, color=lam_col, family="monospace"),
|
| 1389 |
+
bgcolor="white",
|
| 1390 |
+
bordercolor=lam_col,
|
| 1391 |
+
borderwidth=2,
|
| 1392 |
+
borderpad=6,
|
| 1393 |
+
)
|
| 1394 |
+
|
| 1395 |
+
fig.update_layout(
|
| 1396 |
+
title=dict(
|
| 1397 |
+
text=f"<b>QQ Plot β {model_name}</b>",
|
| 1398 |
+
font=dict(size=15, color="#1E293B"),
|
| 1399 |
+
),
|
| 1400 |
+
xaxis=dict(title="Expected βlogββ(p)", gridcolor="#E2E8F0"),
|
| 1401 |
+
yaxis=dict(title="Observed βlogββ(p)", gridcolor="#E2E8F0"),
|
| 1402 |
+
plot_bgcolor="white",
|
| 1403 |
+
paper_bgcolor="white",
|
| 1404 |
+
height=500,
|
| 1405 |
+
legend=dict(font=dict(size=10)),
|
| 1406 |
+
hovermode="closest",
|
| 1407 |
+
margin=dict(l=60, r=40, t=80, b=60),
|
| 1408 |
)
|
| 1409 |
return fig
|
| 1410 |
|
| 1411 |
+
def plot_qq_overlay_interactive(all_results):
|
| 1412 |
+
"""Interactive QQ overlay for all models."""
|
| 1413 |
+
fig = go.Figure()
|
| 1414 |
+
exp_max = 0
|
| 1415 |
+
for mname, (pvals, _, _) in all_results.items():
|
| 1416 |
+
n = len(pvals)
|
| 1417 |
+
obs_raw = -np.log10(np.clip(pvals, 1e-300, 1))
|
| 1418 |
+
sort_i = np.argsort(obs_raw)[::-1]
|
| 1419 |
+
obs = obs_raw[sort_i]
|
| 1420 |
+
exp = -np.log10(np.arange(1, n + 1) / n)
|
| 1421 |
+
exp_max = max(exp_max, exp.max())
|
| 1422 |
+
lam = compute_lambda(pvals)
|
| 1423 |
+
col = MODEL_COLORS.get(mname, ACCENT_BLUE)
|
| 1424 |
+
fig.add_trace(go.Scatter(
|
| 1425 |
+
x=exp, y=obs,
|
| 1426 |
+
mode='lines',
|
| 1427 |
+
line=dict(color=col, width=2.5),
|
| 1428 |
+
name=f"{mname} (Ξ»={lam:.3f})",
|
| 1429 |
+
))
|
| 1430 |
+
fig.add_trace(go.Scatter(
|
| 1431 |
+
x=[0, exp_max * 1.05], y=[0, exp_max * 1.05],
|
| 1432 |
+
mode='lines',
|
| 1433 |
+
line=dict(color='#333333', width=1.5),
|
| 1434 |
+
name='y = x (expected)',
|
| 1435 |
+
))
|
| 1436 |
+
sig_thr = -np.log10(5e-8)
|
| 1437 |
+
fig.add_shape(type="line", x0=0, x1=exp_max, y0=sig_thr, y1=sig_thr,
|
| 1438 |
+
line=dict(color="#CC0000", width=1.5, dash="dash"))
|
| 1439 |
+
fig.add_annotation(x=exp_max*0.98, y=sig_thr+0.2,
|
| 1440 |
+
text="GW significant (5Γ10β»βΈ)",
|
| 1441 |
+
showarrow=False, font=dict(color="#CC0000", size=10),
|
| 1442 |
+
xanchor="right")
|
| 1443 |
+
fig.update_layout(
|
| 1444 |
+
title=dict(text="<b>QQ Plot Overlay β All Models</b>", font=dict(size=15)),
|
| 1445 |
+
xaxis=dict(title="Expected βlogββ(p)", gridcolor="#E2E8F0"),
|
| 1446 |
+
yaxis=dict(title="Observed βlogββ(p)", gridcolor="#E2E8F0"),
|
| 1447 |
+
plot_bgcolor="white",
|
| 1448 |
+
paper_bgcolor="white",
|
| 1449 |
+
height=520,
|
| 1450 |
+
legend=dict(font=dict(size=11)),
|
| 1451 |
+
hovermode="x unified",
|
| 1452 |
+
margin=dict(l=60, r=40, t=80, b=60),
|
| 1453 |
+
)
|
| 1454 |
+
return fig
|
| 1455 |
|
| 1456 |
# βββββββββββββββββββββββ INTERACTIVE PVE / EFFECT SIZE PLOT ββββββββββββββββββ
|
| 1457 |
def plot_effect_sizes_interactive(pvals, betas, ses, snp_names, model_name=""):
|
|
|
|
| 1765 |
|
| 1766 |
# βββββββββββββββββββββββ INTERACTIVE ALL-MODELS MANHATTAN ββββββββββββββββββββ
|
| 1767 |
def plot_all_models_manhattan_interactive(all_results, chroms, positions, snp_names):
|
| 1768 |
+
"""FIX: x-axis starts from chromosome 1. Interactive stacked Manhattan for all models."""
|
|
|
|
|
|
|
|
|
|
| 1769 |
n_models = len(all_results)
|
| 1770 |
chrom_list = sorted(set(chroms))
|
| 1771 |
x_coords = _compute_x_coords(chroms, positions, chrom_list)
|
|
|
|
| 1821 |
fig.update_yaxes(title_text=f"{mname}\n(Ξ»={lam:.3f})", row=midx, col=1,
|
| 1822 |
title_font=dict(size=9, color=col))
|
| 1823 |
|
|
|
|
| 1824 |
fig.update_xaxes(
|
| 1825 |
tickmode='array',
|
| 1826 |
tickvals=tick_pos,
|
| 1827 |
ticktext=tick_lab,
|
| 1828 |
tickangle=45,
|
| 1829 |
+
tickfont=dict(size=8),
|
| 1830 |
range=[0, x_coords.max() * 1.01],
|
| 1831 |
row=n_models, col=1,
|
| 1832 |
)
|
|
|
|
| 2056 |
sig_line = -np.log10(5e-8)
|
| 2057 |
sug_line = -np.log10(1e-5)
|
| 2058 |
chrom_list = sorted(set(chroms))
|
| 2059 |
+
x_coords = _compute_x_coords(chroms, positions, chrom_list)
|
| 2060 |
tick_pos, tick_lab = _compute_tick_positions(x_coords, chroms, chrom_list)
|
| 2061 |
for ch in chrom_list:
|
| 2062 |
mask = chroms == ch
|
|
|
|
| 2074 |
ax.set_ylabel("-logββ(p)")
|
| 2075 |
ax.set_title(f"Manhattan β {model_name}", fontweight='bold')
|
| 2076 |
x_max = x_coords.max() if len(x_coords) > 0 else 1
|
| 2077 |
+
ax.set_xlim(0, x_max * 1.01)
|
| 2078 |
fig.tight_layout()
|
| 2079 |
return fig
|
| 2080 |
|
|
|
|
| 2166 |
|
| 2167 |
bonf = 0.05 / len(primary_p)
|
| 2168 |
|
| 2169 |
+
# Build interactive Plotly figures
|
| 2170 |
fig_mh_primary = plot_manhattan_interactive(primary_p, chr_filt, pos_filt, snp_filt, "Manhattan", primary_model)
|
| 2171 |
fig_qq_primary = plot_qq_interactive_single(primary_p, primary_model, MODEL_COLORS.get(primary_model))
|
| 2172 |
fig_qq_overlay = plot_qq_overlay_interactive(all_results)
|
|
|
|
| 2178 |
fig_all_mh = plot_all_models_manhattan_interactive(all_results, chr_filt, pos_filt, snp_filt)
|
| 2179 |
fig_dashboard = plot_summary_dashboard_interactive(y, maf_vals, all_results, G_filt)
|
| 2180 |
|
| 2181 |
+
# Static plots for ZIP export
|
| 2182 |
static_plots = {}
|
| 2183 |
try:
|
| 2184 |
for mname, (p, b, se) in all_results.items():
|
|
|
|
| 2475 |
plot3 = gr.Plot(label="QQ Overlay β All Models")
|
| 2476 |
|
| 2477 |
with gr.Tab("π΅ Circos (Best Models)"):
|
| 2478 |
+
gr.HTML('<p style="font-size:11px;color:#8892B0;padding:4px 0;">Shows top 4 best-controlled models (Ξ» closest to 1) Β· β = genome-wide significant Β· Chr labels outside with connector lines Β· No overlapping text</p>')
|
| 2479 |
plot4 = gr.Plot(label="Circos β Best Models")
|
| 2480 |
|
| 2481 |
with gr.Tab("π LD Decay"):
|
| 2482 |
+
gr.HTML('<p style="font-size:11px;color:#8892B0;padding:4px 0;">Colored scatter = pairwise rΒ² per chromosome Β· Black curve = fitted exponential decay Β· Distance in Megabases (Mb) Β· Comprehensive interpretation box shows half-decay distance and LD structure</p>')
|
| 2483 |
plot5 = gr.Plot(label="LD Decay")
|
| 2484 |
|
| 2485 |
with gr.Tab("π¬ PCA"):
|