Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,3 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
import pandas as pd
|
| 3 |
import numpy as np
|
|
@@ -605,6 +608,10 @@ def fig_to_png_bytes(fig):
|
|
| 605 |
return data
|
| 606 |
|
| 607 |
def _compute_x_coords(chroms, positions, chrom_list):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 608 |
x_coords = np.zeros(len(chroms))
|
| 609 |
x_offset = 0
|
| 610 |
max_pos = max(positions) if len(positions) > 0 else 1
|
|
@@ -613,7 +620,9 @@ def _compute_x_coords(chroms, positions, chrom_list):
|
|
| 613 |
if not mask.any():
|
| 614 |
continue
|
| 615 |
pos = positions[mask]
|
| 616 |
-
|
|
|
|
|
|
|
| 617 |
x_offset += pos.max() - pos.min() + max_pos * 0.02 + 1
|
| 618 |
return x_coords
|
| 619 |
|
|
@@ -637,13 +646,10 @@ def select_best_models(all_results, n_best=4):
|
|
| 637 |
scores = {}
|
| 638 |
for mname, (pvals, betas, ses) in all_results.items():
|
| 639 |
lam = compute_lambda(pvals)
|
| 640 |
-
# Score: penalize inflation (lam >> 1) AND over-correction (lam << 1)
|
| 641 |
lam_score = abs(lam - 1.0)
|
| 642 |
-
# Also prefer models that find some but not excessive signals
|
| 643 |
n_sig = int((pvals < 5e-8).sum())
|
| 644 |
total = len(pvals)
|
| 645 |
sig_frac = n_sig / max(total, 1)
|
| 646 |
-
# Penalize models finding > 20% sig (likely inflated)
|
| 647 |
if sig_frac > 0.2:
|
| 648 |
lam_score += 2.0
|
| 649 |
scores[mname] = lam_score
|
|
@@ -652,7 +658,10 @@ def select_best_models(all_results, n_best=4):
|
|
| 652 |
|
| 653 |
# βββββββββββββββββββββββ INTERACTIVE MANHATTAN PLOT ββββββββββββββββββββββββββ
|
| 654 |
def plot_manhattan_interactive(pvals, chroms, positions, snp_names, title="Manhattan Plot", model_name=""):
|
| 655 |
-
"""
|
|
|
|
|
|
|
|
|
|
| 656 |
log_p = -np.log10(np.clip(pvals, 1e-300, 1))
|
| 657 |
sig_line = -np.log10(5e-8)
|
| 658 |
sug_line = -np.log10(1e-5)
|
|
@@ -669,7 +678,6 @@ def plot_manhattan_interactive(pvals, chroms, positions, snp_names, title="Manha
|
|
| 669 |
nm = [str(snp_names[i]) for i in np.where(mask)[0]]
|
| 670 |
pc = [float(pvals[i]) for i in np.where(mask)[0]]
|
| 671 |
|
| 672 |
-
# Separate significant and non-significant
|
| 673 |
sig_m = yc >= sig_line
|
| 674 |
ns_m = ~sig_m
|
| 675 |
|
|
@@ -697,11 +705,12 @@ def plot_manhattan_interactive(pvals, chroms, positions, snp_names, title="Manha
|
|
| 697 |
showlegend=False,
|
| 698 |
))
|
| 699 |
|
| 700 |
-
# Threshold lines
|
| 701 |
x_max = x_coords.max() if len(x_coords) > 0 else 1
|
| 702 |
-
|
|
|
|
|
|
|
| 703 |
line=dict(color="#FF4560", width=2, dash="dash"))
|
| 704 |
-
fig.add_shape(type="line", x0=
|
| 705 |
line=dict(color="#00D9E9", width=1.5, dash="dot"))
|
| 706 |
fig.add_annotation(x=x_max*0.98, y=sig_line+0.3, text="GW significant (5Γ10β»βΈ)",
|
| 707 |
showarrow=False, font=dict(color="#FF4560", size=11),
|
|
@@ -710,7 +719,6 @@ def plot_manhattan_interactive(pvals, chroms, positions, snp_names, title="Manha
|
|
| 710 |
showarrow=False, font=dict(color="#00D9E9", size=11),
|
| 711 |
xanchor="right")
|
| 712 |
|
| 713 |
-
# Chromosome tick positions
|
| 714 |
tick_pos, tick_lab = _compute_tick_positions(x_coords, chroms, chrom_list)
|
| 715 |
|
| 716 |
lam = compute_lambda(pvals)
|
|
@@ -730,6 +738,7 @@ def plot_manhattan_interactive(pvals, chroms, positions, snp_names, title="Manha
|
|
| 730 |
showgrid=False,
|
| 731 |
zeroline=False,
|
| 732 |
title="Chromosome",
|
|
|
|
| 733 |
),
|
| 734 |
yaxis=dict(
|
| 735 |
title="-logββ(p-value)",
|
|
@@ -773,7 +782,6 @@ def plot_qq_interactive_single(pvals, model_name="", color=None):
|
|
| 773 |
|
| 774 |
fig = go.Figure()
|
| 775 |
|
| 776 |
-
# CI band
|
| 777 |
fig.add_trace(go.Scatter(
|
| 778 |
x=np.concatenate([exp, exp[::-1]]),
|
| 779 |
y=np.concatenate([ci_hi, ci_lo[::-1]]),
|
|
@@ -784,7 +792,6 @@ def plot_qq_interactive_single(pvals, model_name="", color=None):
|
|
| 784 |
hoverinfo='skip',
|
| 785 |
))
|
| 786 |
|
| 787 |
-
# Expected line
|
| 788 |
xy_max = max(float(exp.max()), float(obs.max())) * 1.06
|
| 789 |
fig.add_trace(go.Scatter(
|
| 790 |
x=[0, xy_max], y=[0, xy_max],
|
|
@@ -819,7 +826,6 @@ def plot_qq_interactive_single(pvals, model_name="", color=None):
|
|
| 819 |
hovertemplate="%{text}<extra></extra>",
|
| 820 |
))
|
| 821 |
|
| 822 |
-
# GW line
|
| 823 |
fig.add_shape(type="line", x0=0, x1=xy_max, y0=sig_thr, y1=sig_thr,
|
| 824 |
line=dict(color="#FF4560", width=1, dash="dot"))
|
| 825 |
|
|
@@ -895,11 +901,15 @@ def plot_qq_overlay_interactive(all_results):
|
|
| 895 |
)
|
| 896 |
return fig
|
| 897 |
|
| 898 |
-
# βββββββββββββββββββββββ
|
| 899 |
def plot_circos_interactive(all_results, chroms, positions, snp_names):
|
| 900 |
"""
|
| 901 |
-
|
| 902 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 903 |
"""
|
| 904 |
best_models = select_best_models(all_results, n_best=min(4, len(all_results)))
|
| 905 |
selected_results = {m: all_results[m] for m in best_models if m in all_results}
|
|
@@ -909,20 +919,26 @@ def plot_circos_interactive(all_results, chroms, positions, snp_names):
|
|
| 909 |
positions_s = positions[sort_idx]
|
| 910 |
snp_s = [str(snp_names[i]) for i in sort_idx]
|
| 911 |
total_snps = len(chroms_s)
|
| 912 |
-
chrom_list = sorted(set(
|
| 913 |
|
| 914 |
-
|
| 915 |
-
angles_deg = np.
|
| 916 |
|
| 917 |
fig = go.Figure()
|
| 918 |
-
sig_line = -np.log10(5e-8)
|
| 919 |
|
|
|
|
| 920 |
n_models = len(selected_results)
|
| 921 |
-
|
| 922 |
-
|
| 923 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 924 |
|
| 925 |
-
|
|
|
|
|
|
|
| 926 |
for ci, ch in enumerate(chrom_list):
|
| 927 |
mask = chroms_s == ch
|
| 928 |
idxs = np.where(mask)[0]
|
|
@@ -930,119 +946,461 @@ def plot_circos_interactive(all_results, chroms, positions, snp_names):
|
|
| 930 |
continue
|
| 931 |
a_start = angles_deg[idxs[0]]
|
| 932 |
a_end = angles_deg[idxs[-1]]
|
| 933 |
-
|
| 934 |
mid_a = (a_start + a_end) / 2
|
| 935 |
-
|
| 936 |
|
|
|
|
| 937 |
fig.add_trace(go.Barpolar(
|
| 938 |
-
r=[0.
|
| 939 |
theta=[mid_a],
|
| 940 |
-
width=[
|
| 941 |
-
base=[
|
| 942 |
marker_color=col,
|
| 943 |
-
marker_line_color=
|
| 944 |
-
marker_line_width=0,
|
| 945 |
-
opacity=0.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 946 |
showlegend=False,
|
| 947 |
hoverinfo='skip',
|
|
|
|
| 948 |
))
|
| 949 |
|
| 950 |
-
# Model rings
|
| 951 |
for midx, (mname, (pvals, betas, _)) in enumerate(selected_results.items()):
|
| 952 |
pvals_s = pvals[sort_idx]
|
| 953 |
log_p_s = -np.log10(np.clip(pvals_s, 1e-300, 1))
|
| 954 |
-
|
| 955 |
-
|
| 956 |
-
|
|
|
|
|
|
|
|
|
|
| 957 |
col = MODEL_COLORS.get(mname, CHR_PALETTE[midx % len(CHR_PALETTE)])
|
| 958 |
|
| 959 |
sig_mask = log_p_s >= sig_line
|
| 960 |
ns_mask = ~sig_mask
|
| 961 |
|
| 962 |
-
# Non-significant
|
| 963 |
if ns_mask.any():
|
| 964 |
fig.add_trace(go.Scatterpolar(
|
| 965 |
-
r=
|
| 966 |
theta=angles_deg[ns_mask],
|
| 967 |
mode='markers',
|
| 968 |
-
marker=dict(color=col, size=3, opacity=0.55),
|
| 969 |
name=mname,
|
| 970 |
-
|
|
|
|
|
|
|
| 971 |
for k, i in enumerate(np.where(ns_mask)[0])],
|
| 972 |
hovertemplate="%{text}<extra></extra>",
|
| 973 |
-
showlegend=
|
| 974 |
))
|
| 975 |
|
| 976 |
-
# Significant
|
| 977 |
if sig_mask.any():
|
|
|
|
| 978 |
fig.add_trace(go.Scatterpolar(
|
| 979 |
-
r=
|
| 980 |
theta=angles_deg[sig_mask],
|
| 981 |
mode='markers',
|
| 982 |
-
marker=dict(
|
| 983 |
-
|
| 984 |
-
|
| 985 |
-
|
| 986 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 987 |
hovertemplate="%{text}<extra></extra>",
|
| 988 |
showlegend=False,
|
| 989 |
))
|
| 990 |
|
| 991 |
-
# Ring baseline
|
| 992 |
fig.add_trace(go.Scatterpolar(
|
| 993 |
-
r=[r_base] *
|
| 994 |
-
theta=list(range(
|
| 995 |
mode='lines',
|
| 996 |
-
line=dict(color=col, width=
|
| 997 |
-
opacity=0.
|
| 998 |
showlegend=False,
|
| 999 |
hoverinfo='skip',
|
|
|
|
| 1000 |
))
|
| 1001 |
|
| 1002 |
-
#
|
| 1003 |
-
|
| 1004 |
-
|
| 1005 |
-
|
| 1006 |
-
|
| 1007 |
-
|
| 1008 |
-
|
| 1009 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1010 |
|
| 1011 |
-
#
|
| 1012 |
-
|
| 1013 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1014 |
])
|
|
|
|
| 1015 |
|
| 1016 |
fig.update_layout(
|
| 1017 |
title=dict(
|
| 1018 |
-
text=f"<b>Circos Plot β Best Models</b>
|
| 1019 |
-
|
|
|
|
|
|
|
| 1020 |
x=0.5,
|
|
|
|
| 1021 |
),
|
| 1022 |
polar=dict(
|
| 1023 |
-
radialaxis=dict(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1024 |
angularaxis=dict(
|
| 1025 |
showticklabels=False,
|
| 1026 |
showgrid=False,
|
|
|
|
| 1027 |
direction="clockwise",
|
|
|
|
| 1028 |
),
|
| 1029 |
bgcolor="white",
|
| 1030 |
),
|
| 1031 |
showlegend=True,
|
| 1032 |
legend=dict(
|
| 1033 |
-
orientation="
|
| 1034 |
-
yanchor="
|
| 1035 |
-
y=
|
| 1036 |
-
xanchor="
|
| 1037 |
-
x=
|
| 1038 |
-
font=dict(size=
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1039 |
),
|
| 1040 |
paper_bgcolor="white",
|
| 1041 |
-
height=
|
| 1042 |
-
|
|
|
|
| 1043 |
)
|
| 1044 |
return fig
|
| 1045 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1046 |
# βββββββββββββββββββββββ INTERACTIVE PVE / EFFECT SIZE PLOT ββββββββββββββββββ
|
| 1047 |
def plot_effect_sizes_interactive(pvals, betas, ses, snp_names, model_name=""):
|
| 1048 |
"""Interactive volcano + effect size plots."""
|
|
@@ -1067,7 +1425,6 @@ def plot_effect_sizes_interactive(pvals, betas, ses, snp_names, model_name=""):
|
|
| 1067 |
fig = make_subplots(rows=1, cols=2,
|
| 1068 |
subplot_titles=["Volcano Plot", "Top 30 Effect Sizes"])
|
| 1069 |
|
| 1070 |
-
# Volcano
|
| 1071 |
fig.add_trace(go.Scatter(
|
| 1072 |
x=betas, y=log_p,
|
| 1073 |
mode='markers',
|
|
@@ -1087,7 +1444,6 @@ def plot_effect_sizes_interactive(pvals, betas, ses, snp_names, model_name=""):
|
|
| 1087 |
line=dict(color="#666", width=1),
|
| 1088 |
row=1, col=1)
|
| 1089 |
|
| 1090 |
-
# Top effect sizes
|
| 1091 |
top_idx = np.argsort(np.abs(betas))[-30:][::-1]
|
| 1092 |
top_betas = betas[top_idx]
|
| 1093 |
top_names = [snp_str[i][:20] for i in top_idx]
|
|
@@ -1123,126 +1479,6 @@ def plot_effect_sizes_interactive(pvals, betas, ses, snp_names, model_name=""):
|
|
| 1123 |
fig.update_yaxes(gridcolor="#E2E8F0", row=1, col=i)
|
| 1124 |
return fig
|
| 1125 |
|
| 1126 |
-
# βββββββββββββββββββββββ INTERACTIVE LD DECAY βββββββββββββββββββββββββββββββββ
|
| 1127 |
-
def plot_ld_decay_interactive(G, positions, chroms):
|
| 1128 |
-
"""Interactive LD decay using Plotly."""
|
| 1129 |
-
chrom_list = sorted(set(chroms))
|
| 1130 |
-
sample_per_chr = 100
|
| 1131 |
-
sampled_idx = []
|
| 1132 |
-
rng = np.random.default_rng(42)
|
| 1133 |
-
for ch in chrom_list:
|
| 1134 |
-
idx_ch = np.where(chroms == ch)[0]
|
| 1135 |
-
n_samp = min(sample_per_chr, len(idx_ch))
|
| 1136 |
-
sampled_idx.extend(rng.choice(idx_ch, n_samp, replace=False).tolist())
|
| 1137 |
-
sampled_idx = sorted(set(sampled_idx))
|
| 1138 |
-
|
| 1139 |
-
dists_bp, r2s = [], []
|
| 1140 |
-
for ii, i in enumerate(sampled_idx):
|
| 1141 |
-
for j in sampled_idx[ii+1:]:
|
| 1142 |
-
xi, xj = G[:, i], G[:, j]
|
| 1143 |
-
mask = ~(np.isnan(xi) | np.isnan(xj))
|
| 1144 |
-
if mask.sum() < 4:
|
| 1145 |
-
continue
|
| 1146 |
-
try:
|
| 1147 |
-
r, _ = stats.pearsonr(xi[mask], xj[mask])
|
| 1148 |
-
except Exception:
|
| 1149 |
-
continue
|
| 1150 |
-
d = abs(positions[j] - positions[i])
|
| 1151 |
-
if d > 0:
|
| 1152 |
-
dists_bp.append(d)
|
| 1153 |
-
r2s.append(r**2)
|
| 1154 |
-
|
| 1155 |
-
fig = make_subplots(rows=1, cols=2,
|
| 1156 |
-
subplot_titles=["LD Decay (bp)", "LD Decay (Mb)"])
|
| 1157 |
-
|
| 1158 |
-
if len(dists_bp) < 2:
|
| 1159 |
-
fig.add_annotation(text="Insufficient data", x=0.5, y=0.5,
|
| 1160 |
-
xref="paper", yref="paper", showarrow=False)
|
| 1161 |
-
return fig
|
| 1162 |
-
|
| 1163 |
-
dists_bp = np.array(dists_bp)
|
| 1164 |
-
dists_mb = dists_bp / 1_000_000
|
| 1165 |
-
r2s = np.array(r2s)
|
| 1166 |
-
|
| 1167 |
-
def bin_ld(dists, r2s, n_bins=25):
|
| 1168 |
-
bins = np.percentile(dists, np.linspace(0, 100, n_bins + 1))
|
| 1169 |
-
centers, means, sems = [], [], []
|
| 1170 |
-
for k in range(len(bins) - 1):
|
| 1171 |
-
mask = (dists >= bins[k]) & (dists < bins[k+1])
|
| 1172 |
-
if mask.sum() > 2:
|
| 1173 |
-
centers.append((bins[k] + bins[k+1]) / 2)
|
| 1174 |
-
means.append(np.mean(r2s[mask]))
|
| 1175 |
-
sems.append(stats.sem(r2s[mask]))
|
| 1176 |
-
return np.array(centers), np.array(means), np.array(sems)
|
| 1177 |
-
|
| 1178 |
-
for col_idx, (dists, unit, c1, c2) in enumerate([
|
| 1179 |
-
(dists_bp, "bp", ACCENT_TEAL, ACCENT_CORAL),
|
| 1180 |
-
(dists_mb, "Mb", ACCENT_PURP, ACCENT_GOLD),
|
| 1181 |
-
], 1):
|
| 1182 |
-
# Scatter (sampled)
|
| 1183 |
-
sample_n = min(2000, len(dists))
|
| 1184 |
-
idx_s = np.random.choice(len(dists), sample_n, replace=False)
|
| 1185 |
-
fig.add_trace(go.Scatter(
|
| 1186 |
-
x=dists[idx_s], y=r2s[idx_s],
|
| 1187 |
-
mode='markers',
|
| 1188 |
-
marker=dict(color=c1, size=3, opacity=0.3),
|
| 1189 |
-
name=f"Pairwise ({unit})",
|
| 1190 |
-
hovertemplate=f"Distance: %{{x:.1f}} {unit}<br>rΒ²: %{{y:.3f}}<extra></extra>",
|
| 1191 |
-
), row=1, col=col_idx)
|
| 1192 |
-
|
| 1193 |
-
bc, bm, bs = bin_ld(dists, r2s)
|
| 1194 |
-
if len(bc) > 0:
|
| 1195 |
-
fig.add_trace(go.Scatter(
|
| 1196 |
-
x=bc, y=bm,
|
| 1197 |
-
mode='lines+markers',
|
| 1198 |
-
line=dict(color=c2, width=3),
|
| 1199 |
-
marker=dict(size=6),
|
| 1200 |
-
name=f"Binned mean ({unit})",
|
| 1201 |
-
error_y=dict(type='data', array=bs, visible=True, color=c2),
|
| 1202 |
-
hovertemplate=f"Distance: %{{x:.1f}} {unit}<br>Mean rΒ²: %{{y:.3f}}<extra></extra>",
|
| 1203 |
-
), row=1, col=col_idx)
|
| 1204 |
-
|
| 1205 |
-
# Decay thresholds
|
| 1206 |
-
for thr, thr_col in [(0.5, 'orange'), (0.2, 'cyan')]:
|
| 1207 |
-
cross_idx = np.where(bm < thr)[0]
|
| 1208 |
-
if len(cross_idx) > 0:
|
| 1209 |
-
cd = bc[cross_idx[0]]
|
| 1210 |
-
fig.add_shape(type="line", x0=cd, x1=cd, y0=0, y1=thr,
|
| 1211 |
-
line=dict(color=thr_col, width=1, dash='dot'),
|
| 1212 |
-
row=1, col=col_idx)
|
| 1213 |
-
fig.add_annotation(
|
| 1214 |
-
x=cd, y=thr+0.05,
|
| 1215 |
-
text=f"rΒ²={thr} @ {cd:.1f}{unit}",
|
| 1216 |
-
showarrow=False,
|
| 1217 |
-
font=dict(size=9, color=thr_col),
|
| 1218 |
-
row=1, col=col_idx,
|
| 1219 |
-
)
|
| 1220 |
-
|
| 1221 |
-
# Reference lines
|
| 1222 |
-
fig.add_shape(type="line", x0=dists.min(), x1=dists.max(),
|
| 1223 |
-
y0=0.5, y1=0.5,
|
| 1224 |
-
line=dict(color='orange', width=1.5, dash='dash'),
|
| 1225 |
-
row=1, col=col_idx)
|
| 1226 |
-
fig.add_shape(type="line", x0=dists.min(), x1=dists.max(),
|
| 1227 |
-
y0=0.2, y1=0.2,
|
| 1228 |
-
line=dict(color='cyan', width=1.5, dash='dash'),
|
| 1229 |
-
row=1, col=col_idx)
|
| 1230 |
-
|
| 1231 |
-
fig.update_xaxes(title_text="Distance (bp)", gridcolor="#E2E8F0", row=1, col=1)
|
| 1232 |
-
fig.update_xaxes(title_text="Distance (Mb)", gridcolor="#E2E8F0", row=1, col=2)
|
| 1233 |
-
fig.update_yaxes(title_text="rΒ² (LD)", range=[0, 1.05], gridcolor="#E2E8F0", row=1, col=1)
|
| 1234 |
-
fig.update_yaxes(range=[0, 1.05], gridcolor="#E2E8F0", row=1, col=2)
|
| 1235 |
-
|
| 1236 |
-
fig.update_layout(
|
| 1237 |
-
title=dict(text="<b>Linkage Disequilibrium (LD) Decay</b>", font=dict(size=14)),
|
| 1238 |
-
plot_bgcolor="white",
|
| 1239 |
-
paper_bgcolor="white",
|
| 1240 |
-
height=480,
|
| 1241 |
-
hovermode="closest",
|
| 1242 |
-
margin=dict(l=60, r=40, t=80, b=60),
|
| 1243 |
-
)
|
| 1244 |
-
return fig
|
| 1245 |
-
|
| 1246 |
# βββββββββββββββββββββββ INTERACTIVE PCA PLOT βββββββββββββββββββββββββββββββββ
|
| 1247 |
def plot_pca_interactive(G, y, ids):
|
| 1248 |
"""Interactive PCA with Plotly."""
|
|
@@ -1315,7 +1551,7 @@ def plot_pca_interactive(G, y, ids):
|
|
| 1315 |
def plot_kinship_interactive(K, ids):
|
| 1316 |
"""Interactive kinship heatmap + distribution."""
|
| 1317 |
n_samples = len(ids)
|
| 1318 |
-
label_step = max(1, n_samples // 30)
|
| 1319 |
tick_labels = [str(ids[i]) if i % label_step == 0 else "" for i in range(n_samples)]
|
| 1320 |
|
| 1321 |
fig = make_subplots(rows=1, cols=2,
|
|
@@ -1324,7 +1560,6 @@ def plot_kinship_interactive(K, ids):
|
|
| 1324 |
"Pairwise Kinship Distribution"
|
| 1325 |
])
|
| 1326 |
|
| 1327 |
-
# Heatmap
|
| 1328 |
fig.add_trace(go.Heatmap(
|
| 1329 |
z=K,
|
| 1330 |
colorscale='RdYlBu_r',
|
|
@@ -1335,7 +1570,6 @@ def plot_kinship_interactive(K, ids):
|
|
| 1335 |
hovertemplate="Sample i: %{x}<br>Sample j: %{y}<br>K: %{z:.3f}<extra></extra>",
|
| 1336 |
), row=1, col=1)
|
| 1337 |
|
| 1338 |
-
# Distribution
|
| 1339 |
K_flat = K[np.triu_indices_from(K, k=1)]
|
| 1340 |
fig.add_trace(go.Histogram(
|
| 1341 |
x=K_flat,
|
|
@@ -1389,7 +1623,6 @@ def plot_summary_dashboard_interactive(y, maf, all_results, G_filt):
|
|
| 1389 |
]
|
| 1390 |
)
|
| 1391 |
|
| 1392 |
-
# Phenotype
|
| 1393 |
fig.add_trace(go.Histogram(
|
| 1394 |
x=y, nbinsx=20,
|
| 1395 |
marker_color=ACCENT_PURP, opacity=0.85,
|
|
@@ -1399,7 +1632,6 @@ def plot_summary_dashboard_interactive(y, maf, all_results, G_filt):
|
|
| 1399 |
fig.add_vline(x=float(y.mean()), line_color=ACCENT_CORAL, line_dash="dash",
|
| 1400 |
annotation_text=f"Mean={y.mean():.2f}", row=1, col=1)
|
| 1401 |
|
| 1402 |
-
# MAF
|
| 1403 |
fig.add_trace(go.Histogram(
|
| 1404 |
x=maf, nbinsx=20,
|
| 1405 |
marker_color=ACCENT_TEAL, opacity=0.85,
|
|
@@ -1409,7 +1641,6 @@ def plot_summary_dashboard_interactive(y, maf, all_results, G_filt):
|
|
| 1409 |
fig.add_vline(x=0.05, line_color=ACCENT_CORAL, line_dash="dash",
|
| 1410 |
annotation_text="MAF=0.05", row=1, col=2)
|
| 1411 |
|
| 1412 |
-
# Lambda
|
| 1413 |
lam_cols = [('#00C9A7' if v <= 1.05 else '#FFB300' if v <= 1.15 else '#FF4560')
|
| 1414 |
for v in lambdas.values()]
|
| 1415 |
fig.add_trace(go.Bar(
|
|
@@ -1423,7 +1654,6 @@ def plot_summary_dashboard_interactive(y, maf, all_results, G_filt):
|
|
| 1423 |
), row=1, col=3)
|
| 1424 |
fig.add_hline(y=1.0, line_color="#333", line_dash="dash", row=1, col=3)
|
| 1425 |
|
| 1426 |
-
# Sig SNPs Bonferroni
|
| 1427 |
cols_bar = [MODEL_COLORS.get(m, ACCENT_BLUE) for m in sig_bonf]
|
| 1428 |
fig.add_trace(go.Bar(
|
| 1429 |
x=list(sig_bonf.keys()),
|
|
@@ -1435,7 +1665,6 @@ def plot_summary_dashboard_interactive(y, maf, all_results, G_filt):
|
|
| 1435 |
hovertemplate="Model: %{x}<br>Sig SNPs: %{y}<extra></extra>",
|
| 1436 |
), row=2, col=1)
|
| 1437 |
|
| 1438 |
-
# Concordance heatmap
|
| 1439 |
model_names = list(all_results.keys())
|
| 1440 |
n_m = len(model_names)
|
| 1441 |
concordance = np.eye(n_m)
|
|
@@ -1456,7 +1685,6 @@ def plot_summary_dashboard_interactive(y, maf, all_results, G_filt):
|
|
| 1456 |
showscale=False,
|
| 1457 |
), row=2, col=2)
|
| 1458 |
|
| 1459 |
-
# Sig GW
|
| 1460 |
cols_gw = [MODEL_COLORS.get(m, ACCENT_BLUE) for m in sig_gw]
|
| 1461 |
fig.add_trace(go.Bar(
|
| 1462 |
x=list(sig_gw.keys()),
|
|
@@ -1485,7 +1713,10 @@ def plot_summary_dashboard_interactive(y, maf, all_results, G_filt):
|
|
| 1485 |
|
| 1486 |
# βββββββββββββββββββββββ INTERACTIVE ALL-MODELS MANHATTAN ββββββββββββββββββββ
|
| 1487 |
def plot_all_models_manhattan_interactive(all_results, chroms, positions, snp_names):
|
| 1488 |
-
"""
|
|
|
|
|
|
|
|
|
|
| 1489 |
n_models = len(all_results)
|
| 1490 |
chrom_list = sorted(set(chroms))
|
| 1491 |
x_coords = _compute_x_coords(chroms, positions, chrom_list)
|
|
@@ -1535,19 +1766,20 @@ def plot_all_models_manhattan_interactive(all_results, chroms, positions, snp_na
|
|
| 1535 |
), row=midx, col=1)
|
| 1536 |
|
| 1537 |
x_max = x_coords.max() if len(x_coords) > 0 else 1
|
| 1538 |
-
fig.add_shape(type="line", x0=
|
| 1539 |
line=dict(color="#FF4560", width=1, dash="dash"),
|
| 1540 |
row=midx, col=1)
|
| 1541 |
fig.update_yaxes(title_text=f"{mname}\n(Ξ»={lam:.3f})", row=midx, col=1,
|
| 1542 |
title_font=dict(size=9, color=col))
|
| 1543 |
|
| 1544 |
-
# Chromosome ticks on bottom axis
|
| 1545 |
fig.update_xaxes(
|
| 1546 |
tickmode='array',
|
| 1547 |
tickvals=tick_pos,
|
| 1548 |
ticktext=tick_lab,
|
| 1549 |
tickangle=45,
|
| 1550 |
tickfont=dict(size=9),
|
|
|
|
| 1551 |
row=n_models, col=1,
|
| 1552 |
)
|
| 1553 |
|
|
@@ -1769,14 +2001,14 @@ def plot_qq_static(pvals, model_name, color):
|
|
| 1769 |
return fig
|
| 1770 |
|
| 1771 |
def plot_manhattan_static(pvals, chroms, positions, model_name):
|
| 1772 |
-
"""Static matplotlib Manhattan
|
| 1773 |
fig, ax = plt.subplots(figsize=(16, 5), facecolor=BG_WHITE)
|
| 1774 |
ax.set_facecolor(PANEL_WHITE)
|
| 1775 |
log_p = -np.log10(np.clip(pvals, 1e-300, 1))
|
| 1776 |
sig_line = -np.log10(5e-8)
|
| 1777 |
sug_line = -np.log10(1e-5)
|
| 1778 |
chrom_list = sorted(set(chroms))
|
| 1779 |
-
x_coords = _compute_x_coords(chroms, positions, chrom_list)
|
| 1780 |
tick_pos, tick_lab = _compute_tick_positions(x_coords, chroms, chrom_list)
|
| 1781 |
for ch in chrom_list:
|
| 1782 |
mask = chroms == ch
|
|
@@ -1794,7 +2026,7 @@ def plot_manhattan_static(pvals, chroms, positions, model_name):
|
|
| 1794 |
ax.set_ylabel("-logββ(p)")
|
| 1795 |
ax.set_title(f"Manhattan β {model_name}", fontweight='bold')
|
| 1796 |
x_max = x_coords.max() if len(x_coords) > 0 else 1
|
| 1797 |
-
ax.set_xlim(
|
| 1798 |
fig.tight_layout()
|
| 1799 |
return fig
|
| 1800 |
|
|
@@ -2183,7 +2415,7 @@ with gr.Blocks(css=PASTEL_CSS, title="𧬠GWAS Pipeline", theme=gr.themes.Base(
|
|
| 2183 |
|
| 2184 |
with gr.Tabs():
|
| 2185 |
with gr.Tab("πΊ Manhattan (Primary)"):
|
| 2186 |
-
gr.HTML('<p style="font-size:11px;color:#8892B0;padding:4px 0;">Hover SNPs for details Β· Zoom with scroll Β· Click legend to toggle chromosomes</p>')
|
| 2187 |
plot1 = gr.Plot(label="Manhattan β Primary Model")
|
| 2188 |
|
| 2189 |
with gr.Tab("π QQ (Primary)"):
|
|
@@ -2195,11 +2427,11 @@ with gr.Blocks(css=PASTEL_CSS, title="𧬠GWAS Pipeline", theme=gr.themes.Base(
|
|
| 2195 |
plot3 = gr.Plot(label="QQ Overlay β All Models")
|
| 2196 |
|
| 2197 |
with gr.Tab("π΅ Circos (Best Models)"):
|
| 2198 |
-
gr.HTML('<p style="font-size:11px;color:#8892B0;padding:4px 0;">Shows top 4 best-controlled models (Ξ» closest to 1) Β· β = genome-wide significant</p>')
|
| 2199 |
plot4 = gr.Plot(label="Circos β Best Models")
|
| 2200 |
|
| 2201 |
with gr.Tab("π LD Decay"):
|
| 2202 |
-
gr.HTML('<p style="font-size:11px;color:#8892B0;padding:4px 0;">
|
| 2203 |
plot5 = gr.Plot(label="LD Decay")
|
| 2204 |
|
| 2205 |
with gr.Tab("π¬ PCA"):
|
|
@@ -2215,7 +2447,7 @@ with gr.Blocks(css=PASTEL_CSS, title="𧬠GWAS Pipeline", theme=gr.themes.Base(
|
|
| 2215 |
plot8 = gr.Plot(label="Effect Sizes & Volcano")
|
| 2216 |
|
| 2217 |
with gr.Tab("π All Models (Stacked)"):
|
| 2218 |
-
gr.HTML('<p style="font-size:11px;color:#8892B0;padding:4px 0;">All models stacked Β· Hover for SNP identity Β· Ξ» shown per panel</p>')
|
| 2219 |
plot9 = gr.Plot(label="Manhattan β All Models")
|
| 2220 |
|
| 2221 |
with gr.Tab("π Dashboard"):
|
|
@@ -2239,6 +2471,6 @@ with gr.Blocks(css=PASTEL_CSS, title="𧬠GWAS Pipeline", theme=gr.themes.Base(
|
|
| 2239 |
excel_out, zip_out, summary_out
|
| 2240 |
],
|
| 2241 |
)
|
| 2242 |
-
|
| 2243 |
if __name__ == "__main__":
|
| 2244 |
demo.launch(share=True, server_port=7860)
|
|
|
|
| 1 |
+
|
| 2 |
+
|
| 3 |
+
|
| 4 |
import gradio as gr
|
| 5 |
import pandas as pd
|
| 6 |
import numpy as np
|
|
|
|
| 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 |
if not mask.any():
|
| 621 |
continue
|
| 622 |
pos = positions[mask]
|
| 623 |
+
# Positions within chromosome start from 0 relative offset, but x_offset
|
| 624 |
+
# ensures the first chromosome starts at > 0 (chromosome 1 starts at 1).
|
| 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 |
|
|
|
|
| 646 |
scores = {}
|
| 647 |
for mname, (pvals, betas, ses) in all_results.items():
|
| 648 |
lam = compute_lambda(pvals)
|
|
|
|
| 649 |
lam_score = abs(lam - 1.0)
|
|
|
|
| 650 |
n_sig = int((pvals < 5e-8).sum())
|
| 651 |
total = len(pvals)
|
| 652 |
sig_frac = n_sig / max(total, 1)
|
|
|
|
| 653 |
if sig_frac > 0.2:
|
| 654 |
lam_score += 2.0
|
| 655 |
scores[mname] = lam_score
|
|
|
|
| 658 |
|
| 659 |
# βββββββββββββββββββββββ INTERACTIVE MANHATTAN PLOT ββββββββββββββββββββββββββ
|
| 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)
|
|
|
|
| 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 |
|
|
|
|
| 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),
|
|
|
|
| 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)
|
|
|
|
| 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)",
|
|
|
|
| 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]]),
|
|
|
|
| 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],
|
|
|
|
| 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 |
|
|
|
|
| 901 |
)
|
| 902 |
return fig
|
| 903 |
|
| 904 |
+
# βββββββββββββββββββββββ IMPROVED CIRCOS PLOT βββββββββββββββββββββββββββββββββ
|
| 905 |
def plot_circos_interactive(all_results, chroms, positions, snp_names):
|
| 906 |
"""
|
| 907 |
+
FIX: Completely redesigned circos plot.
|
| 908 |
+
- No overlapping labels: chromosome labels placed outside the outermost ring
|
| 909 |
+
with smart angular positioning and radial lines.
|
| 910 |
+
- Each model gets its own clearly separated ring with a named annotation.
|
| 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}
|
|
|
|
| 919 |
positions_s = positions[sort_idx]
|
| 920 |
snp_s = [str(snp_names[i]) for i in sort_idx]
|
| 921 |
total_snps = len(chroms_s)
|
| 922 |
+
chrom_list = sorted(set(chroms_s))
|
| 923 |
|
| 924 |
+
# Build angular positions: each SNP gets an angle in [0, 360)
|
| 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.88 # outer chromosome color band
|
| 932 |
+
r_chr_lbl = 1.00 # chromosome label radius
|
| 933 |
+
ring_outer = 0.84 # outermost data ring outer edge
|
| 934 |
+
ring_inner = 0.22 # innermost data ring inner edge
|
| 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]
|
|
|
|
| 946 |
continue
|
| 947 |
a_start = angles_deg[idxs[0]]
|
| 948 |
a_end = angles_deg[idxs[-1]]
|
| 949 |
+
a_width = max(a_end - a_start, 1.0)
|
| 950 |
mid_a = (a_start + a_end) / 2
|
| 951 |
+
col = CHR_PALETTE[ci % len(CHR_PALETTE)]
|
| 952 |
|
| 953 |
+
# Colored arc bar at outer rim
|
| 954 |
fig.add_trace(go.Barpolar(
|
| 955 |
+
r=[0.06],
|
| 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.5,
|
| 962 |
+
opacity=0.92,
|
| 963 |
+
showlegend=False,
|
| 964 |
+
hoverinfo='skip',
|
| 965 |
+
name=f"Chr{ch}_arc",
|
| 966 |
+
))
|
| 967 |
+
|
| 968 |
+
# Chromosome label β placed outside the arc with no overlap
|
| 969 |
+
# Use polar annotation-style via scatter at r_chr_lbl
|
| 970 |
+
mid_rad = mid_a * np.pi / 180
|
| 971 |
+
lx = (r_chr_lbl + 0.07) * np.cos(mid_rad - np.pi / 2)
|
| 972 |
+
ly = (r_chr_lbl + 0.07) * np.sin(mid_rad - np.pi / 2)
|
| 973 |
+
fig.add_trace(go.Scatterpolar(
|
| 974 |
+
r=[r_chr_lbl + 0.03],
|
| 975 |
+
theta=[mid_a],
|
| 976 |
+
mode='text',
|
| 977 |
+
text=[f"<b>Chr{ch}</b>"],
|
| 978 |
+
textfont=dict(size=8, color=col),
|
| 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))
|
| 988 |
+
|
| 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 |
|
| 996 |
sig_mask = log_p_s >= sig_line
|
| 997 |
ns_mask = ~sig_mask
|
| 998 |
|
| 999 |
+
# Non-significant SNPs
|
| 1000 |
if ns_mask.any():
|
| 1001 |
fig.add_trace(go.Scatterpolar(
|
| 1002 |
+
r=r_data[ns_mask],
|
| 1003 |
theta=angles_deg[ns_mask],
|
| 1004 |
mode='markers',
|
| 1005 |
+
marker=dict(color=col, size=3, opacity=0.55, line=dict(width=0)),
|
| 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=True,
|
| 1013 |
))
|
| 1014 |
|
| 1015 |
+
# Significant SNPs (highlighted)
|
| 1016 |
if sig_mask.any():
|
| 1017 |
+
sig_idxs = np.where(sig_mask)[0]
|
| 1018 |
fig.add_trace(go.Scatterpolar(
|
| 1019 |
+
r=r_data[sig_mask],
|
| 1020 |
theta=angles_deg[sig_mask],
|
| 1021 |
mode='markers',
|
| 1022 |
+
marker=dict(
|
| 1023 |
+
color='#FF1744', size=10, symbol='diamond',
|
| 1024 |
+
line=dict(color='#7F0000', width=1)
|
| 1025 |
+
),
|
| 1026 |
+
name=f"{mname} β
Sig",
|
| 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=False,
|
| 1033 |
))
|
| 1034 |
|
| 1035 |
+
# Ring baseline circle (dashed)
|
| 1036 |
fig.add_trace(go.Scatterpolar(
|
| 1037 |
+
r=[r_base] * 361,
|
| 1038 |
+
theta=list(range(361)),
|
| 1039 |
mode='lines',
|
| 1040 |
+
line=dict(color=col, width=1.0, dash='dot'),
|
| 1041 |
+
opacity=0.4,
|
| 1042 |
showlegend=False,
|
| 1043 |
hoverinfo='skip',
|
| 1044 |
+
name=f"{mname}_base",
|
| 1045 |
))
|
| 1046 |
|
| 1047 |
+
# Significance threshold circle within ring
|
| 1048 |
+
sig_r = r_base + (sig_line / max_lp) * ring_width * 0.9
|
| 1049 |
+
if sig_r <= r_top:
|
| 1050 |
+
fig.add_trace(go.Scatterpolar(
|
| 1051 |
+
r=[sig_r] * 361,
|
| 1052 |
+
theta=list(range(361)),
|
| 1053 |
+
mode='lines',
|
| 1054 |
+
line=dict(color='#FF4560', width=1.0, dash='dash'),
|
| 1055 |
+
opacity=0.6,
|
| 1056 |
+
showlegend=False,
|
| 1057 |
+
hoverinfo='skip',
|
| 1058 |
+
name=f"{mname}_sig_circle",
|
| 1059 |
+
))
|
| 1060 |
+
|
| 1061 |
+
# Model name label β place at fixed angle (270Β°, bottom of circle)
|
| 1062 |
+
# to avoid any overlap with chromosome labels (which are at the top outer rim)
|
| 1063 |
+
label_angle = 270.0
|
| 1064 |
+
lam_val = compute_lambda(pvals)
|
| 1065 |
+
r_mid = (r_base + r_top) / 2
|
| 1066 |
+
fig.add_trace(go.Scatterpolar(
|
| 1067 |
+
r=[r_mid],
|
| 1068 |
+
theta=[label_angle],
|
| 1069 |
+
mode='text',
|
| 1070 |
+
text=[f"<b>{mname}</b><br>Ξ»={lam_val:.3f}"],
|
| 1071 |
+
textfont=dict(size=9, color=col),
|
| 1072 |
+
showlegend=False,
|
| 1073 |
+
hoverinfo='skip',
|
| 1074 |
+
name=f"{mname}_label",
|
| 1075 |
+
))
|
| 1076 |
|
| 1077 |
+
# ββ 3. Centre circle (decorative) ββββββββββββββββββββββββββββββββββββββ
|
| 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 |
+
# ββ Layout ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1091 |
+
lam_str = " | ".join([
|
| 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=(f"<b>Circos Plot β Best {n_models} Models</b>"
|
| 1099 |
+
f"<br><sup>{lam_str}</sup>"
|
| 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 |
polar=dict(
|
| 1106 |
+
radialaxis=dict(
|
| 1107 |
+
showticklabels=False,
|
| 1108 |
+
showgrid=False,
|
| 1109 |
+
showline=False,
|
| 1110 |
+
range=[0, 1.15],
|
| 1111 |
+
),
|
| 1112 |
angularaxis=dict(
|
| 1113 |
showticklabels=False,
|
| 1114 |
showgrid=False,
|
| 1115 |
+
showline=False,
|
| 1116 |
direction="clockwise",
|
| 1117 |
+
rotation=90,
|
| 1118 |
),
|
| 1119 |
bgcolor="white",
|
| 1120 |
),
|
| 1121 |
showlegend=True,
|
| 1122 |
legend=dict(
|
| 1123 |
+
orientation="v",
|
| 1124 |
+
yanchor="middle",
|
| 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=750,
|
| 1136 |
+
width=900,
|
| 1137 |
+
margin=dict(l=60, r=180, t=130, b=60),
|
| 1138 |
)
|
| 1139 |
return fig
|
| 1140 |
|
| 1141 |
+
|
| 1142 |
+
# βββββββββββββββββββββββ LD DECAY PLOT (REDESIGNED) ββββββββββββββββββββββββββ
|
| 1143 |
+
def plot_ld_decay_interactive(G, positions, chroms):
|
| 1144 |
+
"""
|
| 1145 |
+
REDESIGNED: LD decay plot matching the reference image style.
|
| 1146 |
+
- Scatter of all pairwise rΒ² values (multi-color by chromosome, semi-transparent)
|
| 1147 |
+
- Smooth nonlinear decay curve fitted through binned means
|
| 1148 |
+
- Dashed horizontal reference lines at rΒ²=0.5 and rΒ²=0.2
|
| 1149 |
+
- x-axis: genetic distance in cM (approximated from bp using 1 cM β 1 Mb)
|
| 1150 |
+
- y-axis: LD estimate (rΒ²) from 0 to 1
|
| 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 = 80
|
| 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 |
+
sampled_idx.extend(rng.choice(idx_ch, n_samp, replace=False).tolist())
|
| 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 # only intra-chromosomal LD
|
| 1170 |
+
xi, xj = G[:, i], G[:, j]
|
| 1171 |
+
mask = ~(np.isnan(xi) | np.isnan(xj))
|
| 1172 |
+
if mask.sum() < 4:
|
| 1173 |
+
continue
|
| 1174 |
+
try:
|
| 1175 |
+
r, _ = stats.pearsonr(xi[mask], xj[mask])
|
| 1176 |
+
except Exception:
|
| 1177 |
+
continue
|
| 1178 |
+
d = abs(positions[j] - positions[i])
|
| 1179 |
+
if d > 0:
|
| 1180 |
+
dists_bp.append(d)
|
| 1181 |
+
r2s.append(r**2)
|
| 1182 |
+
chrom_pairs.append(chroms[i])
|
| 1183 |
+
|
| 1184 |
+
fig = go.Figure()
|
| 1185 |
+
|
| 1186 |
+
if len(dists_bp) < 5:
|
| 1187 |
+
fig.add_annotation(
|
| 1188 |
+
text="Insufficient pairwise data for LD decay<br>(need more SNPs on same chromosome)",
|
| 1189 |
+
x=0.5, y=0.5, xref="paper", yref="paper",
|
| 1190 |
+
showarrow=False, font=dict(size=14, color="#666"),
|
| 1191 |
+
)
|
| 1192 |
+
fig.update_layout(
|
| 1193 |
+
title=dict(text="<b>Linkage Disequilibrium (LD) Decay</b>", font=dict(size=14)),
|
| 1194 |
+
plot_bgcolor="white", paper_bgcolor="white", height=550,
|
| 1195 |
+
)
|
| 1196 |
+
return fig
|
| 1197 |
+
|
| 1198 |
+
dists_bp = np.array(dists_bp)
|
| 1199 |
+
r2s = np.array(r2s)
|
| 1200 |
+
chrom_pairs = np.array(chrom_pairs)
|
| 1201 |
+
|
| 1202 |
+
# Convert bp β cM (approximate: 1 Mb = 1 cM)
|
| 1203 |
+
dists_cM = dists_bp / 1_000_000
|
| 1204 |
+
|
| 1205 |
+
# ββ Scatter: color by chromosome ββ
|
| 1206 |
+
for ci, ch in enumerate(chrom_list):
|
| 1207 |
+
cmask = chrom_pairs == ch
|
| 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) > 500:
|
| 1214 |
+
idx_sub = rng.choice(idx_sub, 500, replace=False)
|
| 1215 |
+
fig.add_trace(go.Scatter(
|
| 1216 |
+
x=dists_cM[idx_sub],
|
| 1217 |
+
y=r2s[idx_sub],
|
| 1218 |
+
mode='markers',
|
| 1219 |
+
marker=dict(
|
| 1220 |
+
color=col, size=4, opacity=0.40,
|
| 1221 |
+
line=dict(width=0),
|
| 1222 |
+
),
|
| 1223 |
+
name=f"Chr{ch}",
|
| 1224 |
+
legendgroup=f"chr{ch}",
|
| 1225 |
+
hovertemplate=f"Chr{ch}<br>Distance: %{{x:.3f}} cM<br>rΒ²: %{{y:.3f}}<extra></extra>",
|
| 1226 |
+
))
|
| 1227 |
+
|
| 1228 |
+
# ββ Binned means for smooth decay curve ββ
|
| 1229 |
+
n_bins = 30
|
| 1230 |
+
pctiles = np.percentile(dists_cM, np.linspace(0, 100, n_bins + 1))
|
| 1231 |
+
bin_centers, bin_means, bin_sems, bin_counts = [], [], [], []
|
| 1232 |
+
for k in range(len(pctiles) - 1):
|
| 1233 |
+
mask = (dists_cM >= pctiles[k]) & (dists_cM < pctiles[k + 1])
|
| 1234 |
+
if mask.sum() >= 3:
|
| 1235 |
+
bin_centers.append(np.median(dists_cM[mask]))
|
| 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())
|
| 1239 |
+
|
| 1240 |
+
bin_centers = np.array(bin_centers)
|
| 1241 |
+
bin_means = np.array(bin_means)
|
| 1242 |
+
bin_sems = np.array(bin_sems)
|
| 1243 |
+
|
| 1244 |
+
# Fit a smooth nonlinear decay: rΒ² ~ a * exp(-b * d) + c (Hill-like approximation)
|
| 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, 1.0, 0.05]
|
| 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(dists_cM.min(), dists_cM.max(), 300)
|
| 1257 |
+
smooth_y = decay_func(smooth_x, *popt)
|
| 1258 |
+
smooth_y = np.clip(smooth_y, 0, 1)
|
| 1259 |
+
|
| 1260 |
+
# Find half-decay distance (rΒ² = 0.5)
|
| 1261 |
+
half_decay_d = None
|
| 1262 |
+
r2_at_zero = float(popt[0] + popt[2])
|
| 1263 |
+
r2_plateau = float(popt[2])
|
| 1264 |
+
r2_half = (r2_at_zero + r2_plateau) / 2
|
| 1265 |
+
above_half = smooth_x[smooth_y >= r2_half]
|
| 1266 |
+
if len(above_half) > 0:
|
| 1267 |
+
half_decay_d = above_half[-1]
|
| 1268 |
+
except Exception:
|
| 1269 |
+
smooth_x = bin_centers
|
| 1270 |
+
smooth_y = bin_means
|
| 1271 |
+
half_decay_d = None
|
| 1272 |
+
else:
|
| 1273 |
+
smooth_x = bin_centers
|
| 1274 |
+
smooth_y = bin_means
|
| 1275 |
+
half_decay_d = None
|
| 1276 |
+
|
| 1277 |
+
# ββ Smooth decay curve (thick black line like the reference) ββ
|
| 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} cM<br>Fitted rΒ²: %{y:.3f}<extra></extra>",
|
| 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='black', size=5, symbol='circle',
|
| 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} cM<br>Mean rΒ²: %{y:.3f}<extra></extra>",
|
| 1298 |
+
))
|
| 1299 |
+
|
| 1300 |
+
# ββ Reference lines at rΒ²=0.5 and rΒ²=0.2 ββ
|
| 1301 |
+
x_max_plot = float(np.percentile(dists_cM, 98)) * 1.05 if len(dists_cM) > 0 else 1
|
| 1302 |
+
|
| 1303 |
+
for thr, thr_col, thr_dash, thr_name in [
|
| 1304 |
+
(0.5, '#E67E22', 'dash', 'rΒ² = 0.5 (strong LD)'),
|
| 1305 |
+
(0.2, '#3498DB', 'dot', 'rΒ² = 0.2 (weak LD)'),
|
| 1306 |
+
]:
|
| 1307 |
+
fig.add_shape(
|
| 1308 |
+
type="line", x0=0, x1=x_max_plot, y0=thr, y1=thr,
|
| 1309 |
+
line=dict(color=thr_col, width=2, dash=thr_dash),
|
| 1310 |
+
)
|
| 1311 |
+
fig.add_annotation(
|
| 1312 |
+
x=x_max_plot * 0.98, y=thr + 0.03,
|
| 1313 |
+
text=thr_name,
|
| 1314 |
+
showarrow=False,
|
| 1315 |
+
font=dict(size=10, color=thr_col),
|
| 1316 |
+
xanchor="right",
|
| 1317 |
+
)
|
| 1318 |
+
|
| 1319 |
+
# ββ Half-decay annotation ββ
|
| 1320 |
+
if half_decay_d is not None:
|
| 1321 |
+
fig.add_shape(
|
| 1322 |
+
type="line", x0=half_decay_d, x1=half_decay_d, y0=0, y1=r2_half,
|
| 1323 |
+
line=dict(color='#2ECC71', width=2, dash='dash'),
|
| 1324 |
+
)
|
| 1325 |
+
fig.add_annotation(
|
| 1326 |
+
x=half_decay_d, y=r2_half + 0.05,
|
| 1327 |
+
text=f"Half-decay<br>{half_decay_d:.2f} cM",
|
| 1328 |
+
showarrow=True,
|
| 1329 |
+
arrowhead=2,
|
| 1330 |
+
arrowcolor='#2ECC71',
|
| 1331 |
+
font=dict(size=10, color='#2ECC71'),
|
| 1332 |
+
ax=30, ay=-30,
|
| 1333 |
+
)
|
| 1334 |
+
|
| 1335 |
+
# ββ Interpretation box ββ
|
| 1336 |
+
overall_mean_r2 = float(np.mean(r2s)) if len(r2s) > 0 else 0
|
| 1337 |
+
n_pairs = len(r2s)
|
| 1338 |
+
interp_text = (
|
| 1339 |
+
f"<b>LD Summary</b><br>"
|
| 1340 |
+
f"Pairs: {n_pairs:,}<br>"
|
| 1341 |
+
f"Mean rΒ²: {overall_mean_r2:.3f}<br>"
|
| 1342 |
+
+ (f"Half-decay: {half_decay_d:.2f} cM" if half_decay_d else "")
|
| 1343 |
+
)
|
| 1344 |
+
fig.add_annotation(
|
| 1345 |
+
x=0.98, y=0.98, xref="paper", yref="paper",
|
| 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="right",
|
| 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 genetic distance (cM) | "
|
| 1363 |
+
"Black curve = fitted exponential decay | Colors = chromosomes</sup>"
|
| 1364 |
+
),
|
| 1365 |
+
font=dict(size=14, color="#1E293B"),
|
| 1366 |
+
),
|
| 1367 |
+
xaxis=dict(
|
| 1368 |
+
title="Genetic distance (cM)",
|
| 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="LD estimate (rΒ²)",
|
| 1378 |
+
gridcolor="#E2E8F0",
|
| 1379 |
+
gridwidth=0.8,
|
| 1380 |
+
range=[0, 1.05],
|
| 1381 |
+
tickfont=dict(size=11),
|
| 1382 |
+
dtick=0.2,
|
| 1383 |
+
),
|
| 1384 |
+
plot_bgcolor="white",
|
| 1385 |
+
paper_bgcolor="white",
|
| 1386 |
+
height=560,
|
| 1387 |
+
hovermode="closest",
|
| 1388 |
+
legend=dict(
|
| 1389 |
+
orientation="v",
|
| 1390 |
+
yanchor="top",
|
| 1391 |
+
y=0.97,
|
| 1392 |
+
xanchor="left",
|
| 1393 |
+
x=0.70,
|
| 1394 |
+
font=dict(size=9),
|
| 1395 |
+
bgcolor="rgba(255,255,255,0.85)",
|
| 1396 |
+
bordercolor="#E2E8F0",
|
| 1397 |
+
borderwidth=1,
|
| 1398 |
+
),
|
| 1399 |
+
margin=dict(l=70, r=40, t=100, b=70),
|
| 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=""):
|
| 1406 |
"""Interactive volcano + effect size plots."""
|
|
|
|
| 1425 |
fig = make_subplots(rows=1, cols=2,
|
| 1426 |
subplot_titles=["Volcano Plot", "Top 30 Effect Sizes"])
|
| 1427 |
|
|
|
|
| 1428 |
fig.add_trace(go.Scatter(
|
| 1429 |
x=betas, y=log_p,
|
| 1430 |
mode='markers',
|
|
|
|
| 1444 |
line=dict(color="#666", width=1),
|
| 1445 |
row=1, col=1)
|
| 1446 |
|
|
|
|
| 1447 |
top_idx = np.argsort(np.abs(betas))[-30:][::-1]
|
| 1448 |
top_betas = betas[top_idx]
|
| 1449 |
top_names = [snp_str[i][:20] for i in top_idx]
|
|
|
|
| 1479 |
fig.update_yaxes(gridcolor="#E2E8F0", row=1, col=i)
|
| 1480 |
return fig
|
| 1481 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1482 |
# βββββββββββββββββββββββ INTERACTIVE PCA PLOT βββββββββββββββββββββββββββββββββ
|
| 1483 |
def plot_pca_interactive(G, y, ids):
|
| 1484 |
"""Interactive PCA with Plotly."""
|
|
|
|
| 1551 |
def plot_kinship_interactive(K, ids):
|
| 1552 |
"""Interactive kinship heatmap + distribution."""
|
| 1553 |
n_samples = len(ids)
|
| 1554 |
+
label_step = max(1, n_samples // 30)
|
| 1555 |
tick_labels = [str(ids[i]) if i % label_step == 0 else "" for i in range(n_samples)]
|
| 1556 |
|
| 1557 |
fig = make_subplots(rows=1, cols=2,
|
|
|
|
| 1560 |
"Pairwise Kinship Distribution"
|
| 1561 |
])
|
| 1562 |
|
|
|
|
| 1563 |
fig.add_trace(go.Heatmap(
|
| 1564 |
z=K,
|
| 1565 |
colorscale='RdYlBu_r',
|
|
|
|
| 1570 |
hovertemplate="Sample i: %{x}<br>Sample j: %{y}<br>K: %{z:.3f}<extra></extra>",
|
| 1571 |
), row=1, col=1)
|
| 1572 |
|
|
|
|
| 1573 |
K_flat = K[np.triu_indices_from(K, k=1)]
|
| 1574 |
fig.add_trace(go.Histogram(
|
| 1575 |
x=K_flat,
|
|
|
|
| 1623 |
]
|
| 1624 |
)
|
| 1625 |
|
|
|
|
| 1626 |
fig.add_trace(go.Histogram(
|
| 1627 |
x=y, nbinsx=20,
|
| 1628 |
marker_color=ACCENT_PURP, opacity=0.85,
|
|
|
|
| 1632 |
fig.add_vline(x=float(y.mean()), line_color=ACCENT_CORAL, line_dash="dash",
|
| 1633 |
annotation_text=f"Mean={y.mean():.2f}", row=1, col=1)
|
| 1634 |
|
|
|
|
| 1635 |
fig.add_trace(go.Histogram(
|
| 1636 |
x=maf, nbinsx=20,
|
| 1637 |
marker_color=ACCENT_TEAL, opacity=0.85,
|
|
|
|
| 1641 |
fig.add_vline(x=0.05, line_color=ACCENT_CORAL, line_dash="dash",
|
| 1642 |
annotation_text="MAF=0.05", row=1, col=2)
|
| 1643 |
|
|
|
|
| 1644 |
lam_cols = [('#00C9A7' if v <= 1.05 else '#FFB300' if v <= 1.15 else '#FF4560')
|
| 1645 |
for v in lambdas.values()]
|
| 1646 |
fig.add_trace(go.Bar(
|
|
|
|
| 1654 |
), row=1, col=3)
|
| 1655 |
fig.add_hline(y=1.0, line_color="#333", line_dash="dash", row=1, col=3)
|
| 1656 |
|
|
|
|
| 1657 |
cols_bar = [MODEL_COLORS.get(m, ACCENT_BLUE) for m in sig_bonf]
|
| 1658 |
fig.add_trace(go.Bar(
|
| 1659 |
x=list(sig_bonf.keys()),
|
|
|
|
| 1665 |
hovertemplate="Model: %{x}<br>Sig SNPs: %{y}<extra></extra>",
|
| 1666 |
), row=2, col=1)
|
| 1667 |
|
|
|
|
| 1668 |
model_names = list(all_results.keys())
|
| 1669 |
n_m = len(model_names)
|
| 1670 |
concordance = np.eye(n_m)
|
|
|
|
| 1685 |
showscale=False,
|
| 1686 |
), row=2, col=2)
|
| 1687 |
|
|
|
|
| 1688 |
cols_gw = [MODEL_COLORS.get(m, ACCENT_BLUE) for m in sig_gw]
|
| 1689 |
fig.add_trace(go.Bar(
|
| 1690 |
x=list(sig_gw.keys()),
|
|
|
|
| 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)
|
|
|
|
| 1766 |
), row=midx, col=1)
|
| 1767 |
|
| 1768 |
x_max = x_coords.max() if len(x_coords) > 0 else 1
|
| 1769 |
+
fig.add_shape(type="line", x0=1, x1=x_max, y0=sig_line, y1=sig_line,
|
| 1770 |
line=dict(color="#FF4560", width=1, dash="dash"),
|
| 1771 |
row=midx, col=1)
|
| 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=9),
|
| 1782 |
+
range=[0, x_coords.max() * 1.01],
|
| 1783 |
row=n_models, col=1,
|
| 1784 |
)
|
| 1785 |
|
|
|
|
| 2001 |
return fig
|
| 2002 |
|
| 2003 |
def plot_manhattan_static(pvals, chroms, positions, model_name):
|
| 2004 |
+
"""Static matplotlib Manhattan β FIX: x-axis starts from 1 (not 0)."""
|
| 2005 |
fig, ax = plt.subplots(figsize=(16, 5), facecolor=BG_WHITE)
|
| 2006 |
ax.set_facecolor(PANEL_WHITE)
|
| 2007 |
log_p = -np.log10(np.clip(pvals, 1e-300, 1))
|
| 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) # Now starts from 1
|
| 2012 |
tick_pos, tick_lab = _compute_tick_positions(x_coords, chroms, chrom_list)
|
| 2013 |
for ch in chrom_list:
|
| 2014 |
mask = chroms == ch
|
|
|
|
| 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) # Starts from 0 but data from 1
|
| 2030 |
fig.tight_layout()
|
| 2031 |
return fig
|
| 2032 |
|
|
|
|
| 2415 |
|
| 2416 |
with gr.Tabs():
|
| 2417 |
with gr.Tab("πΊ Manhattan (Primary)"):
|
| 2418 |
+
gr.HTML('<p style="font-size:11px;color:#8892B0;padding:4px 0;">Hover SNPs for details Β· Zoom with scroll Β· Click legend to toggle chromosomes Β· X-axis starts from Chr1</p>')
|
| 2419 |
plot1 = gr.Plot(label="Manhattan β Primary Model")
|
| 2420 |
|
| 2421 |
with gr.Tab("π QQ (Primary)"):
|
|
|
|
| 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 outermost ring Β· Model labels at bottom</p>')
|
| 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 Β· Dashed lines = rΒ²=0.5 (strong) and rΒ²=0.2 (weak) thresholds Β· x-axis in cM</p>')
|
| 2435 |
plot5 = gr.Plot(label="LD Decay")
|
| 2436 |
|
| 2437 |
with gr.Tab("π¬ PCA"):
|
|
|
|
| 2447 |
plot8 = gr.Plot(label="Effect Sizes & Volcano")
|
| 2448 |
|
| 2449 |
with gr.Tab("π All Models (Stacked)"):
|
| 2450 |
+
gr.HTML('<p style="font-size:11px;color:#8892B0;padding:4px 0;">All models stacked Β· Hover for SNP identity Β· Ξ» shown per panel Β· X-axis starts from Chr1</p>')
|
| 2451 |
plot9 = gr.Plot(label="Manhattan β All Models")
|
| 2452 |
|
| 2453 |
with gr.Tab("π Dashboard"):
|
|
|
|
| 2471 |
excel_out, zip_out, summary_out
|
| 2472 |
],
|
| 2473 |
)
|
| 2474 |
+
|
| 2475 |
if __name__ == "__main__":
|
| 2476 |
demo.launch(share=True, server_port=7860)
|