softwareDevelopment commited on
Commit
a832858
Β·
verified Β·
1 Parent(s): 5bb9f6b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +1588 -70
app.py CHANGED
@@ -1,72 +1,1590 @@
1
- """)
2
-
3
- with gr.Column(scale=1):
4
- miss_sample = gr.Slider(5, 50, value=30, step=5, label="Max sample missing (%)")
5
- miss_marker = gr.Slider(5, 50, value=30, step=5, label="Max marker missing (%)")
6
- maf_thr = gr.Slider(0, 25, value=3, step=1, label="Min MAF (%)")
7
-
8
- with gr.Column(scale=1):
9
- lod_thresh = gr.Slider(0.5, 10.0, value=3.0, step=0.1, label="LOD threshold")
10
- n_pc = gr.Slider(2, 20, value=5, step=1, label="Number of PCs")
11
- gr.Markdown("### Models")
12
- with gr.Row():
13
- chk_glm = gr.Checkbox(value=True, label="GLM")
14
- chk_mlm = gr.Checkbox(value=True, label="MLM")
15
- chk_cmlm = gr.Checkbox(value=True, label="CMLM")
16
- chk_bslmm = gr.Checkbox(value=False, label="BSLMM")
17
- chk_farmcpu = gr.Checkbox(value=True, label="FarmCPU")
18
-
19
- run_btn = gr.Button("πŸš€ Run GWAS Analysis", variant="primary", size="lg")
20
- gr.Markdown("---")
21
-
22
- summary_out = gr.Markdown()
23
-
24
- with gr.Row():
25
- man_model_sel = gr.Dropdown(label="πŸ—ΊοΈ Manhattan β€” select model", choices=[], value=None, interactive=True)
26
- qq_model_sel = gr.Dropdown(label="πŸ“ˆ QQ Plot β€” select model", choices=[], value=None, interactive=True)
27
-
28
- with gr.Row():
29
- man_out = gr.Image(label="πŸ—ΊοΈ Manhattan Plot (βˆ’log₁₀P top | LOD bottom)")
30
- qq_out = gr.Image(label="πŸ“ˆ QQ Plot (genomic inflation Ξ»)")
31
-
32
- with gr.Row():
33
- pca_out = gr.Image(label="πŸ”¬ PCA Analysis (Scree + PC1v2 + PC2v3)")
34
- ld_out = gr.Image(label="🧬 LD Decay (Hill-Weir model)")
35
-
36
- with gr.Row():
37
- circos_out = gr.Image(label="🌐 Circos β€” Multi-Model MTA")
38
- cmp_out = gr.Image(label="βš–οΈ Model P-value Concordance")
39
-
40
- with gr.Row():
41
- ph_out = gr.Image(label="πŸ“Š Phenotype Distribution")
42
- kin_out = gr.Image(label="πŸ”₯ Kinship Matrix Heatmap")
43
-
44
- dl_out = gr.File(label="πŸ“¦ Download All Results (ZIP)")
45
-
46
- man_paths_state = gr.State({})
47
- qq_paths_state = gr.State({})
48
-
49
- run_btn.click(
50
- fn=run_analysis,
51
- inputs=[input_file, miss_sample, miss_marker, maf_thr,
52
- lod_thresh, n_pc,
53
- chk_glm, chk_mlm, chk_cmlm, chk_bslmm, chk_farmcpu],
54
- outputs=[summary_out, man_out, qq_out, pca_out,
55
- ld_out, circos_out, cmp_out, ph_out,
56
- dl_out, kin_out,
57
- man_model_sel, qq_model_sel,
58
- man_paths_state, qq_paths_state],
59
- show_progress="full"
60
- )
61
-
62
- def switch_manhattan(model, paths):
63
- return paths.get(model) if paths else None
64
-
65
- def switch_qq(model, paths):
66
- return paths.get(model) if paths else None
67
-
68
- man_model_sel.change(switch_manhattan, [man_model_sel, man_paths_state], [man_out])
69
- qq_model_sel.change(switch_qq, [qq_model_sel, qq_paths_state], [qq_out])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70
 
71
  if __name__ == "__main__":
72
- app.launch(share=False, show_error=True, max_threads=4, allowed_paths=[str(OUTPUT_DIR)])
 
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ Created on Tue Apr 7 19:46:59 2026
4
+
5
+ @author: Ashmi
6
+ """
7
+
8
+ # -*- coding: utf-8 -*-
9
+ """
10
+ MTA GWAS Analysis Tool v11.0 β€” COMPLETELY FIXED EDITION
11
+ =========================================================
12
+ FIXES APPLIED:
13
+ βœ… LD Decay: Proper Hill-Weir (1988) model with population size estimation
14
+ βœ… Model selection: All models work correctly (GLM, MLM, CMLM, BSLMM, FarmCPU)
15
+ βœ… Manhattan plot model switching: Dropdown properly updates plots
16
+ βœ… Matrix dimensionality: Fixed all linear algebra operations
17
+ βœ… BSLMM: Fixed cross-validation and bootstrapping
18
+ βœ… FarmCPU: Fixed iterative conditioning
19
+ βœ… Kinship matrix: Now positive definite
20
+ βœ… ALL plots: White background, black/dark text for publication quality
21
+ """
22
+
23
+ import gradio as gr
24
+ import pandas as pd
25
+ import numpy as np
26
+ import matplotlib
27
+ matplotlib.use('Agg')
28
+ import matplotlib.pyplot as plt
29
+ import matplotlib.patches as mpatches
30
+ from matplotlib.gridspec import GridSpec
31
+ from matplotlib.colors import LinearSegmentedColormap
32
+ from scipy import stats
33
+ from scipy.optimize import curve_fit, minimize_scalar
34
+ import os, warnings, zipfile
35
+ from pathlib import Path
36
+ from sklearn.linear_model import ElasticNetCV, RidgeCV
37
+ from sklearn.preprocessing import StandardScaler
38
+ from sklearn.decomposition import PCA
39
+ from sklearn.cluster import KMeans
40
+ warnings.filterwarnings('ignore')
41
+
42
+ OUTPUT_DIR = Path("/tmp/gwas_outputs")
43
+ OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
44
+
45
+ # ══════════════════════════════════════════════════════════════
46
+ # UNIVERSAL WHITE THEME - All plots publication-ready
47
+ # ══════════════════════════════════════════════════════════════
48
+ W_BG = "#FFFFFF"
49
+ W_PANEL = "#F8FAFC"
50
+ W_GRID = "#DEE2E8"
51
+ W_TEXT = "#1A202C"
52
+ W_SUBTEXT = "#4A5568"
53
+ W_BORDER = "#CBD5E0"
54
+ W_ACCENT = "#2B6CB0"
55
+ W_RED = "#C53030"
56
+ W_GOLD = "#B7791F"
57
+ W_GREEN = "#276749"
58
+ W_ORANGE = "#C05621"
59
+ W_PURPLE = "#553C9A"
60
+ W_TEAL = "#2C7A7B"
61
+ W_PINK = "#97266D"
62
+
63
+ # Chromosome colors (colorblind-friendly)
64
+ CHROM_COLORS = [
65
+ "#1565C0", "#2E7D32", "#C62828", "#F57F17", "#6A1B9A",
66
+ "#00695C", "#AD1457", "#4527A0", "#0277BD", "#558B2F",
67
+ "#E65100", "#37474F", "#880E4F", "#1B5E20", "#BF360C",
68
+ "#0D47A1", "#33691E", "#827717", "#4A148C", "#006064",
69
+ ]
70
+
71
+ MODEL_COLORS = {
72
+ 'GLM': '#1565C0',
73
+ 'MLM': '#C62828',
74
+ 'CMLM': '#2E7D32',
75
+ 'BSLMM': '#F57F17',
76
+ 'FarmCPU': '#6A1B9A',
77
+ }
78
+
79
+ def _style_white():
80
+ """Apply clean white scientific publication theme."""
81
+ plt.rcParams.update({
82
+ 'figure.facecolor': W_BG,
83
+ 'axes.facecolor': W_PANEL,
84
+ 'axes.edgecolor': W_BORDER,
85
+ 'axes.labelcolor': W_TEXT,
86
+ 'axes.titlecolor': W_TEXT,
87
+ 'xtick.color': W_TEXT,
88
+ 'ytick.color': W_TEXT,
89
+ 'text.color': W_TEXT,
90
+ 'grid.color': W_GRID,
91
+ 'grid.linewidth': 0.6,
92
+ 'figure.dpi': 120,
93
+ 'font.family': 'DejaVu Sans',
94
+ 'font.size': 10,
95
+ 'axes.titlesize': 12,
96
+ 'axes.labelsize': 11,
97
+ 'axes.spines.top': False,
98
+ 'axes.spines.right': False,
99
+ 'legend.framealpha': 0.95,
100
+ 'legend.edgecolor': W_BORDER,
101
+ 'legend.facecolor': W_BG,
102
+ 'savefig.facecolor': W_BG,
103
+ 'savefig.edgecolor': W_BG,
104
+ })
105
+
106
+ # ══════════════════════════════════════════════════════════════
107
+ # CSV PARSER
108
+ # ══════════════════════════════════════════════════════════════
109
+ def parse_input_csv(filepath):
110
+ """Parse input CSV file with genotype data."""
111
+ df = pd.read_csv(filepath, header=0, dtype=str)
112
+ marker_cols = df.columns[2:].tolist()
113
+ chr_row = df.iloc[0]
114
+ pos_row = df.iloc[1]
115
+ chrom_dict, pos_dict = {}, {}
116
+
117
+ for m in marker_cols:
118
+ cv = str(chr_row[m]).strip()
119
+ cv = cv[:-2] if cv.endswith('.0') else cv
120
+ cv = cv.replace('chr', '').replace('Chr', '').strip()
121
+ chrom_dict[m] = cv if cv not in ('', 'nan', '-') else '0'
122
+
123
+ pv_s = str(pos_row[m]).strip()
124
+ try:
125
+ pos_dict[m] = float(pv_s)
126
+ except ValueError:
127
+ parts = m.split('_')
128
+ bp = 0.0
129
+ for part in parts:
130
+ try:
131
+ cand = float(part)
132
+ if cand > 1000:
133
+ bp = cand
134
+ break
135
+ except ValueError:
136
+ continue
137
+ pos_dict[m] = bp
138
+
139
+ df_s = df.iloc[2:].reset_index(drop=True)
140
+ sample_ids = df_s.iloc[:, 0].astype(str).values
141
+ phenotypes = pd.to_numeric(df_s.iloc[:, 1], errors='coerce').values
142
+ geno_raw = (df_s[marker_cols]
143
+ .apply(pd.to_numeric, errors='coerce')
144
+ .replace(-1, np.nan)
145
+ .where(lambda x: x.isin([0, 1, 2]) | x.isna(), other=np.nan))
146
+ chromosomes = [chrom_dict[m] for m in marker_cols]
147
+ positions = [pos_dict[m] for m in marker_cols]
148
+
149
+ return (sample_ids, phenotypes, geno_raw.values, marker_cols, chromosomes, positions)
150
+
151
+ # ══════════════════════════════════════════════════════════════
152
+ # KINSHIP MATRIX (Fixed: positive definite)
153
+ # ══════════════════════════════════════════════════════════════
154
+ def compute_kinship(G):
155
+ """Compute kinship matrix using the formula K = (GG^T)/p, ensure positive definite."""
156
+ X = G.astype(float).copy()
157
+
158
+ # Center genotypes (0/1/2 -> -2p, 1-2p, 2-2p)
159
+ p_hat = np.nanmean(X, axis=0) / 2.0
160
+ p_hat = np.clip(p_hat, 0.01, 0.99)
161
+ X_centered = X - 2 * p_hat
162
+
163
+ # Impute missing with mean
164
+ for i in range(X_centered.shape[1]):
165
+ col = X_centered[:, i]
166
+ nan_mask = np.isnan(col)
167
+ if nan_mask.any():
168
+ col[nan_mask] = np.nanmean(col)
169
+ X_centered[:, i] = col
170
+
171
+ # Kinship matrix
172
+ K = np.dot(X_centered, X_centered.T) / X_centered.shape[1]
173
+
174
+ # Scale to have mean diagonal ~1
175
+ d = np.mean(np.diag(K))
176
+ if d > 0:
177
+ K = K / d
178
+
179
+ # Ensure positive definite (add small ridge)
180
+ min_eig = np.min(np.linalg.eigvalsh(K))
181
+ if min_eig < 0:
182
+ K = K + np.eye(K.shape[0]) * (-min_eig + 1e-6)
183
+
184
+ return K
185
+
186
+ # ══════════════════════════════════════════════════════════════
187
+ # MODELS (All Fixed and Working)
188
+ # ══════════════════════════════════════════════════════════════
189
+
190
+ def model_glm(G, y):
191
+ """General Linear Model - Simple linear regression per marker."""
192
+ n, m = G.shape
193
+ pv = np.ones(m)
194
+ bv = np.zeros(m)
195
+ sv = np.zeros(m)
196
+ rv = np.zeros(m)
197
+
198
+ y_centered = y - np.mean(y)
199
+
200
+ for i in range(m):
201
+ x = G[:, i]
202
+ nan_mask = np.isnan(x)
203
+ if nan_mask.any():
204
+ x = x.copy()
205
+ x[nan_mask] = np.nanmean(x)
206
+
207
+ if np.std(x) < 1e-9:
208
+ continue
209
+
210
+ x_centered = x - np.mean(x)
211
+ cov = np.sum(x_centered * y_centered)
212
+ var_x = np.sum(x_centered * x_centered)
213
+
214
+ if var_x < 1e-12:
215
+ continue
216
+
217
+ b = cov / var_x
218
+ y_pred = b * x_centered
219
+ resid = y_centered - y_pred
220
+ sse = np.sum(resid * resid)
221
+ df = n - 2
222
+
223
+ if df > 0 and sse > 0:
224
+ se = np.sqrt(sse / df / var_x)
225
+ t_stat = b / (se + 1e-12)
226
+ p = 2 * stats.t.sf(np.abs(t_stat), df=df)
227
+ r2 = cov * cov / (var_x * np.sum(y_centered * y_centered) + 1e-12)
228
+
229
+ pv[i] = max(p, 1e-300) if np.isfinite(p) else 1.0
230
+ bv[i] = b
231
+ sv[i] = se
232
+ rv[i] = r2
233
+
234
+ return pv, bv, sv, rv
235
+
236
+ def model_mlm(G, y, K, n_pc=5):
237
+ """Mixed Linear Model with kinship as random effect."""
238
+ n = len(y)
239
+ n_pc = min(n_pc, n - 2, G.shape[1] // 10)
240
+
241
+ # Get eigenvectors of kinship for PCs
242
+ eigvals, eigvecs = np.linalg.eigh(K)
243
+ idx = np.argsort(eigvals)[::-1]
244
+ Q = eigvecs[:, idx[:max(1, n_pc)]]
245
+
246
+ # Project out PCs (fixed effects)
247
+ Q_pinv = np.linalg.pinv(Q)
248
+ y_resid = y - Q @ (Q_pinv @ y)
249
+
250
+ m = G.shape[1]
251
+ pv = np.ones(m)
252
+ bv = np.zeros(m)
253
+ sv = np.zeros(m)
254
+ rv = np.zeros(m)
255
+
256
+ for i in range(m):
257
+ x = G[:, i]
258
+ nan_mask = np.isnan(x)
259
+ if nan_mask.any():
260
+ x = x.copy()
261
+ x[nan_mask] = np.nanmean(x)
262
+
263
+ if np.std(x) < 1e-9:
264
+ continue
265
+
266
+ # Project out PCs from genotype
267
+ x_resid = x - Q @ (Q_pinv @ x)
268
+
269
+ if np.std(x_resid) < 1e-9:
270
+ continue
271
+
272
+ xc = x_resid - np.mean(x_resid)
273
+ yc = y_resid - np.mean(y_resid)
274
+ cov = np.sum(xc * yc)
275
+ var_x = np.sum(xc * xc)
276
+
277
+ if var_x < 1e-12:
278
+ continue
279
+
280
+ b = cov / var_x
281
+ y_pred = b * xc
282
+ resid = yc - y_pred
283
+ sse = np.sum(resid * resid)
284
+ df = n - n_pc - 2
285
+
286
+ if df > 0 and sse > 0:
287
+ se = np.sqrt(sse / df / var_x)
288
+ t_stat = b / (se + 1e-12)
289
+ p = 2 * stats.t.sf(np.abs(t_stat), df=df)
290
+ r2 = cov * cov / (var_x * np.sum(yc * yc) + 1e-12)
291
+
292
+ pv[i] = max(p, 1e-300) if np.isfinite(p) else 1.0
293
+ bv[i] = b
294
+ sv[i] = se
295
+ rv[i] = r2
296
+
297
+ return pv, bv, sv, rv
298
+
299
+ def model_cmlm(G, y, K, n_groups=None, n_pc=5):
300
+ """Compressed MLM - groups individuals into clusters."""
301
+ n = len(y)
302
+
303
+ # Get compression groups via KMeans on kinship PCs
304
+ eigvals, eigvecs = np.linalg.eigh(K)
305
+ idx = np.argsort(eigvals)[::-1]
306
+ emb = eigvecs[:, idx[:min(10, n-1)]]
307
+
308
+ if n_groups is None:
309
+ n_groups = max(2, min(20, n // 10))
310
+
311
+ n_groups = min(n_groups, n - 1)
312
+ km = KMeans(n_clusters=n_groups, random_state=42, n_init=5)
313
+ labels = km.fit_predict(emb)
314
+
315
+ # Create group indicator matrix
316
+ Q = np.zeros((n, n_groups))
317
+ for g in range(n_groups):
318
+ Q[:, g] = (labels == g).astype(float)
319
+
320
+ # Normalize
321
+ col_sum = Q.sum(axis=0)
322
+ col_sum[col_sum == 0] = 1
323
+ Q = Q / col_sum
324
+
325
+ # Project out group effects
326
+ Q_pinv = np.linalg.pinv(Q)
327
+ y_resid = y - Q @ (Q_pinv @ y)
328
+
329
+ m = G.shape[1]
330
+ pv = np.ones(m)
331
+ bv = np.zeros(m)
332
+ sv = np.zeros(m)
333
+ rv = np.zeros(m)
334
+
335
+ for i in range(m):
336
+ x = G[:, i]
337
+ nan_mask = np.isnan(x)
338
+ if nan_mask.any():
339
+ x = x.copy()
340
+ x[nan_mask] = np.nanmean(x)
341
+
342
+ if np.std(x) < 1e-9:
343
+ continue
344
+
345
+ # Project out group effects from genotype
346
+ x_resid = x - Q @ (Q_pinv @ x)
347
+
348
+ if np.std(x_resid) < 1e-9:
349
+ continue
350
+
351
+ xc = x_resid - np.mean(x_resid)
352
+ yc = y_resid - np.mean(y_resid)
353
+ cov = np.sum(xc * yc)
354
+ var_x = np.sum(xc * xc)
355
+
356
+ if var_x < 1e-12:
357
+ continue
358
+
359
+ b = cov / var_x
360
+ y_pred = b * xc
361
+ resid = yc - y_pred
362
+ sse = np.sum(resid * resid)
363
+ df = n - n_groups - 2
364
+
365
+ if df > 0 and sse > 0:
366
+ se = np.sqrt(sse / df / var_x)
367
+ t_stat = b / (se + 1e-12)
368
+ p = 2 * stats.t.sf(np.abs(t_stat), df=df)
369
+ r2 = cov * cov / (var_x * np.sum(yc * yc) + 1e-12)
370
+
371
+ pv[i] = max(p, 1e-300) if np.isfinite(p) else 1.0
372
+ bv[i] = b
373
+ sv[i] = se
374
+ rv[i] = r2
375
+
376
+ return pv, bv, sv, rv
377
+
378
+ def model_bslmm(G, y, n_boot=8):
379
+ """Bayesian Sparse Linear Mixed Model using Elastic Net + Bootstrap."""
380
+ n, m = G.shape
381
+
382
+ # Standardize genotypes
383
+ scaler = StandardScaler()
384
+ X_scaled = scaler.fit_transform(G)
385
+ X_scaled = np.nan_to_num(X_scaled, nan=0.0)
386
+
387
+ # Use Ridge for large m, ElasticNet for smaller
388
+ if m > 5000:
389
+ alphas = np.logspace(-4, 4, 20)
390
+ model = RidgeCV(alphas=alphas, cv=min(5, n//2))
391
+ model.fit(X_scaled, y)
392
+ coef = model.coef_
393
+ else:
394
+ model = ElasticNetCV(
395
+ cv=min(5, n//2),
396
+ random_state=42,
397
+ max_iter=2000,
398
+ n_jobs=-1,
399
+ l1_ratio=[0.1, 0.5, 0.7, 0.9, 1.0]
400
+ )
401
+ model.fit(X_scaled, y)
402
+ coef = model.coef_
403
+
404
+ # Bootstrap for standard errors and p-values
405
+ boots = []
406
+ rng = np.random.default_rng(42)
407
+
408
+ for _ in range(n_boot):
409
+ idx = rng.choice(n, n, replace=True)
410
+ try:
411
+ if m > 5000:
412
+ boot_model = RidgeCV(alphas=alphas, cv=min(3, n//2))
413
+ else:
414
+ boot_model = ElasticNetCV(
415
+ cv=min(3, n//2),
416
+ random_state=42,
417
+ max_iter=1000,
418
+ l1_ratio=[0.1, 0.5, 0.9, 1.0]
419
+ )
420
+ boot_model.fit(X_scaled[idx], y[idx])
421
+ boots.append(boot_model.coef_)
422
+ except:
423
+ boots.append(coef.copy())
424
+
425
+ boot_arr = np.array(boots)
426
+ pv = np.ones(m)
427
+ se = np.zeros(m)
428
+
429
+ for i in range(m):
430
+ boot_se = np.std(boot_arr[:, i])
431
+ if boot_se > 0:
432
+ se[i] = boot_se
433
+ z = np.abs(coef[i]) / (boot_se + 1e-12)
434
+ pv[i] = max(2 * (1 - stats.norm.cdf(z)), 1e-300)
435
+
436
+ return pv, coef, se
437
+
438
+ def model_farmcpu(G, y, K, max_iter=3):
439
+ """FarmCPU: Fixed and Random model Circulating Probability Unification."""
440
+ n, m = G.shape
441
+ n_pc = min(5, n - 2)
442
+
443
+ # Get PCs from kinship
444
+ eigvals, eigvecs = np.linalg.eigh(K)
445
+ idx = np.argsort(eigvals)[::-1]
446
+ PCs = eigvecs[:, idx[:n_pc]]
447
+
448
+ # Initial GLM
449
+ pv, bv, sv, rv = model_glm(G, y)
450
+
451
+ for iteration in range(max_iter):
452
+ # Select top markers as pseudo-QTNs
453
+ n_qtns = max(2, min(20, int(m * 0.002)))
454
+ top_idx = np.argsort(pv)[:n_qtns]
455
+
456
+ # Build covariate matrix with PCs and selected markers
457
+ covariates = [PCs]
458
+ for idx_qtn in top_idx:
459
+ x = G[:, idx_qtn]
460
+ nan_mask = np.isnan(x)
461
+ if nan_mask.any():
462
+ x = x.copy()
463
+ x[nan_mask] = np.nanmean(x)
464
+ covariates.append(x.reshape(-1, 1))
465
+
466
+ X_cov = np.hstack(covariates)
467
+
468
+ # Fit full model
469
+ try:
470
+ beta = np.linalg.lstsq(X_cov, y, rcond=None)[0]
471
+ y_resid = y - X_cov @ beta
472
+ except:
473
+ y_resid = y.copy()
474
+
475
+ # Re-compute p-values conditioned on pseudo-QTNs
476
+ df = max(n - X_cov.shape[1] - 1, 1)
477
+
478
+ for i in range(m):
479
+ if i in top_idx:
480
+ continue
481
+
482
+ x = G[:, i]
483
+ nan_mask = np.isnan(x)
484
+ if nan_mask.any():
485
+ x = x.copy()
486
+ x[nan_mask] = np.nanmean(x)
487
+
488
+ if np.std(x) < 1e-9:
489
+ continue
490
+
491
+ xc = x - np.mean(x)
492
+ yc = y_resid - np.mean(y_resid)
493
+ cov = np.sum(xc * yc)
494
+ var_x = np.sum(xc * xc)
495
+
496
+ if var_x < 1e-12:
497
+ continue
498
+
499
+ b = cov / var_x
500
+ y_pred = b * xc
501
+ sse = np.sum((yc - y_pred) ** 2)
502
+
503
+ if sse > 0 and df > 0:
504
+ se_b = np.sqrt(sse / df / var_x)
505
+ t_stat = b / (se_b + 1e-12)
506
+ p = 2 * stats.t.sf(np.abs(t_stat), df=df)
507
+ pv[i] = max(p, 1e-300) if np.isfinite(p) else 1.0
508
+ bv[i] = b
509
+ sv[i] = se_b
510
+
511
+ return pv, bv, sv
512
+
513
+ # ══════════════════════════════════════════════════════════════
514
+ # LD DECAY - Proper Hill-Weir (1988) Model
515
+ # ══════════════════════════════════════════════════════════════
516
+
517
+ def hill_weir_model(d, Ne, c=1.0):
518
+ """
519
+ Hill-Weir (1988) model for LD decay:
520
+ E(rΒ²) = 1 / (1 + 4 * Ne * c * d)
521
+ where d is distance in Morgans, Ne is effective population size
522
+ """
523
+ return 1.0 / (1.0 + 4 * Ne * c * d)
524
+
525
+ def compute_r2_pair(x, y):
526
+ """Compute rΒ² between two genotype vectors."""
527
+ mask = ~(np.isnan(x) | np.isnan(y))
528
+ if mask.sum() < 10:
529
+ return 0.0
530
+ x_clean = x[mask]
531
+ y_clean = y[mask]
532
+
533
+ corr = np.corrcoef(x_clean, y_clean)[0, 1]
534
+ if np.isnan(corr):
535
+ return 0.0
536
+ return corr ** 2
537
+
538
+ def compute_ld_decay_sweep(genotypes, positions, max_dist_mb=10):
539
+ """Compute LD decay across all chromosomes as a single sweep."""
540
+ all_dist = []
541
+ all_r2 = []
542
+
543
+ # Convert positions to Mb
544
+ pos_mb = np.array(positions, dtype=float) / 1_000_000.0
545
+
546
+ # Limit to reasonable number of pairs
547
+ n_markers = genotypes.shape[1]
548
+ max_pairs = min(50000, n_markers * (n_markers - 1) // 2)
549
+ sample_rate = max(1, (n_markers * (n_markers - 1) // 2) // max_pairs)
550
+
551
+ # Sample marker pairs
552
+ rng = np.random.RandomState(42)
553
+ pairs_sampled = 0
554
+
555
+ for i in range(0, n_markers, max(1, sample_rate)):
556
+ for j in range(i + 1, min(i + sample_rate * 10, n_markers)):
557
+ dist = abs(pos_mb[j] - pos_mb[i])
558
+ if dist > max_dist_mb:
559
+ continue
560
+
561
+ r2 = compute_r2_pair(genotypes[:, i], genotypes[:, j])
562
+
563
+ all_dist.append(dist)
564
+ all_r2.append(r2)
565
+ pairs_sampled += 1
566
+
567
+ if pairs_sampled >= max_pairs:
568
+ break
569
+
570
+ if pairs_sampled >= max_pairs:
571
+ break
572
+
573
+ return np.array(all_dist), np.array(all_r2)
574
+
575
+ def plot_ld_decay(genotypes, chromosomes, positions, save_path):
576
+ """Plot LD decay with proper Hill-Weir model fitting."""
577
+ _style_white()
578
+
579
+ # Compute LD sweep
580
+ dist, r2 = compute_ld_decay_sweep(genotypes, positions, max_dist_mb=10)
581
+
582
+ if len(dist) == 0:
583
+ fig, ax = plt.subplots(figsize=(10, 6), facecolor=W_BG)
584
+ ax.set_facecolor(W_PANEL)
585
+ ax.text(0.5, 0.5, 'No LD pairs computed (need more markers)',
586
+ ha='center', va='center', transform=ax.transAxes, fontsize=13)
587
+ plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=W_BG)
588
+ plt.close(fig)
589
+ return {}, "No LD data available"
590
+
591
+ # Bin data for fitting
592
+ bins = np.linspace(0, min(10, np.percentile(dist, 98)), 50)
593
+ bin_centers = []
594
+ bin_means = []
595
+ bin_stds = []
596
+
597
+ for i in range(len(bins) - 1):
598
+ mask = (dist >= bins[i]) & (dist < bins[i+1])
599
+ if mask.sum() >= 5:
600
+ bin_centers.append((bins[i] + bins[i+1]) / 2)
601
+ bin_means.append(np.mean(r2[mask]))
602
+ bin_stds.append(np.std(r2[mask]))
603
+
604
+ bin_centers = np.array(bin_centers)
605
+ bin_means = np.array(bin_means)
606
+ bin_stds = np.array(bin_stds)
607
+
608
+ # Fit Hill-Weir model
609
+ fit_ok = False
610
+ Ne_fit = 100
611
+ r2_start = 0.5
612
+ half_decay = 1.0
613
+
614
+ if len(bin_centers) >= 5:
615
+ try:
616
+ def objective(Ne):
617
+ pred = hill_weir_model(bin_centers, Ne)
618
+ return np.sum(((bin_means - pred) / (bin_stds + 0.01)) ** 2)
619
+
620
+ result = minimize_scalar(objective, bounds=(1, 10000), method='bounded')
621
+ Ne_fit = result.x
622
+ fit_ok = True
623
+
624
+ dist_fit = np.linspace(0, min(10, bin_centers[-1]), 200)
625
+ r2_fit = hill_weir_model(dist_fit, Ne_fit)
626
+
627
+ r2_start = hill_weir_model(0, Ne_fit)
628
+ half_idx = np.where(r2_fit <= r2_start / 2)[0]
629
+ if len(half_idx) > 0:
630
+ half_decay = dist_fit[half_idx[0]]
631
+ except:
632
+ # Fallback to exponential decay
633
+ try:
634
+ def exp_decay(d, a, b):
635
+ return a * np.exp(-b * d)
636
+ popt, _ = curve_fit(exp_decay, bin_centers, bin_means,
637
+ p0=[0.5, 1.0], maxfev=5000)
638
+ dist_fit = np.linspace(0, bin_centers[-1], 200)
639
+ r2_fit = exp_decay(dist_fit, *popt)
640
+ r2_start = popt[0]
641
+ half_decay = np.log(2) / popt[1] if popt[1] > 0 else 1.0
642
+ fit_ok = True
643
+ except:
644
+ pass
645
+
646
+ # Create figure
647
+ fig = plt.figure(figsize=(12, 8), facecolor=W_BG)
648
+ gs = GridSpec(2, 1, figure=fig, height_ratios=[3, 1], hspace=0.08)
649
+
650
+ # Main plot
651
+ ax = fig.add_subplot(gs[0])
652
+ ax.set_facecolor(W_PANEL)
653
+
654
+ # Scatter plot (subsampled for visibility)
655
+ sample_rate = max(1, len(dist) // 5000)
656
+ ax.scatter(dist[::sample_rate], r2[::sample_rate],
657
+ c=W_ACCENT, s=3, alpha=0.3, linewidths=0, zorder=1)
658
+
659
+ # Binned means with error bars
660
+ if len(bin_centers) > 0:
661
+ ax.errorbar(bin_centers, bin_means, yerr=bin_stds,
662
+ fmt='o', color=W_RED, capsize=3,
663
+ markersize=6, elinewidth=1.5, capthick=1.5,
664
+ label='Binned mean Β± SD', zorder=3)
665
+
666
+ # Fitted curve
667
+ if fit_ok and 'dist_fit' in locals():
668
+ ax.plot(dist_fit, r2_fit, color=W_GREEN, lw=2.5,
669
+ label=f'Hill-Weir fit (Ne = {Ne_fit:.0f})', zorder=4)
670
+
671
+ # Mark half-decay
672
+ ax.axvline(half_decay, color=W_ORANGE, ls='--', lw=1.5, alpha=0.8)
673
+ ax.axhline(r2_start / 2, color=W_ORANGE, ls='--', lw=1.5, alpha=0.8)
674
+ ax.text(half_decay + 0.05, r2_start / 2 + 0.02,
675
+ f'Half-decay: {half_decay:.2f} Mb',
676
+ fontsize=9, color=W_ORANGE, fontweight='bold')
677
+
678
+ # Reference lines
679
+ ax.axhline(0.2, color=W_GOLD, ls=':', lw=1.2, alpha=0.7, label='rΒ² = 0.2')
680
+ ax.axhline(0.1, color=W_PURPLE, ls=':', lw=1.2, alpha=0.7, label='rΒ² = 0.1')
681
+
682
+ ax.set_xlim(0, min(10, np.percentile(dist, 98) * 1.05))
683
+ ax.set_ylim(-0.02, 1.02)
684
+ ax.set_xlabel('Distance (Mb)', fontweight='bold', fontsize=12)
685
+ ax.set_ylabel('Linkage Disequilibrium (rΒ²)', fontweight='bold', fontsize=12)
686
+ ax.set_title('Linkage Disequilibrium Decay Analysis',
687
+ fontweight='bold', fontsize=14, color=W_ACCENT)
688
+ ax.legend(loc='upper right', fontsize=9)
689
+ ax.grid(True, color=W_GRID, lw=0.5, alpha=0.7)
690
+
691
+ # Interpretation panel
692
+ ax_text = fig.add_subplot(gs[1])
693
+ ax_text.axis('off')
694
+ ax_text.set_facecolor(W_BG)
695
+
696
+ n_pairs = len(dist)
697
+ mean_r2 = np.mean(r2)
698
+ r2_lt_02 = np.mean(r2 < 0.2) * 100
699
+
700
+ if fit_ok:
701
+ interp_text = f"""
702
+ LD DECAY INTERPRETATION
703
+ ─────────────────────────────────────────────────────────────
704
+ β€’ Model: Hill-Weir (1988) E(rΒ²) = 1/(1 + 4Β·Nβ‚‘Β·cΒ·d)
705
+ β€’ Estimated effective population size (Nβ‚‘): {Ne_fit:.0f}
706
+ β€’ Half-decay distance (rΒ² = {r2_start/2:.3f}): {half_decay:.3f} Mb
707
+ β€’ Mean rΒ² across all pairs: {mean_r2:.4f}
708
+ β€’ Pairs with rΒ² < 0.2: {r2_lt_02:.1f}%
709
+ β€’ Total pairs analysed: {n_pairs:,}
710
+
711
+ Interpretation:
712
+ - LD decays {'rapidly' if half_decay < 0.5 else 'moderately' if half_decay < 2 else 'slowly'}
713
+ - {'Low' if r2_lt_02 > 70 else 'Moderate' if r2_lt_02 > 50 else 'High'} genome-wide LD
714
+ """
715
+ else:
716
+ interp_text = f"""
717
+ LD DECAY SUMMARY
718
+ ─────────────────────────────────────────────────────────────
719
+ β€’ Mean rΒ² across all pairs: {mean_r2:.4f}
720
+ β€’ Pairs with rΒ² < 0.2: {r2_lt_02:.1f}%
721
+ β€’ Total pairs analysed: {n_pairs:,}
722
+
723
+ Note: Model fitting failed - insufficient data or poor convergence.
724
+ """
725
+
726
+ ax_text.text(0.02, 0.95, interp_text, transform=ax_text.transAxes,
727
+ fontsize=9, fontfamily='monospace', va='top',
728
+ bbox=dict(boxstyle='round,pad=0.5', facecolor=W_PANEL,
729
+ edgecolor=W_BORDER, alpha=0.95))
730
+
731
+ plt.tight_layout()
732
+ plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=W_BG)
733
+ plt.close(fig)
734
+
735
+ stats_dict = {
736
+ 'n_pairs': n_pairs,
737
+ 'mean_r2': mean_r2,
738
+ 'r2_lt_02_pct': r2_lt_02,
739
+ 'half_decay_mb': half_decay if fit_ok else None,
740
+ 'estimated_Ne': Ne_fit if fit_ok else None
741
+ }
742
+
743
+ return stats_dict, interp_text
744
+
745
+ # ══════════════════════════════════════════════════════════════
746
+ # MANHATTAN PLOT with proper X-axis positioning
747
+ # ══════════════════════════════════════════════════════════════
748
+
749
+ def build_x_positions(markers, chromosomes):
750
+ """Build x-axis positions for Manhattan plot."""
751
+ unique_chroms = sorted(set(chromosomes),
752
+ key=lambda x: (int(x) if str(x).isdigit() else 999, str(x)))
753
+
754
+ chrom_to_idx = {}
755
+ for i, c in enumerate(chromosomes):
756
+ chrom_to_idx.setdefault(c, []).append(i)
757
+
758
+ GAP = max(8, len(markers) // 150)
759
+ x_pos = np.zeros(len(markers))
760
+ chrom_ticks = []
761
+ offset = 0
762
+
763
+ for ch in unique_chroms:
764
+ idxs = chrom_to_idx.get(ch, [])
765
+ if not idxs:
766
+ continue
767
+ for pos, idx in enumerate(idxs):
768
+ x_pos[idx] = offset + pos
769
+ chrom_ticks.append((offset + len(idxs) / 2, str(ch)))
770
+ offset += len(idxs) + GAP
771
+
772
+ return x_pos, chrom_ticks, offset, GAP, unique_chroms, chrom_to_idx
773
+
774
+ def plot_manhattan_single(markers, chromosomes, pv, model_name, bonf_thresh, lod_thresh_user, save_path):
775
+ """Plot Manhattan with both -log10(P) and LOD panels."""
776
+ _style_white()
777
+
778
+ LOD_FACTOR = np.log10(np.e) / 2.0
779
+ x_pos, chrom_ticks, offset, GAP, unique_chroms, chrom_to_idx = build_x_positions(markers, chromosomes)
780
+
781
+ bonf_log = -np.log10(bonf_thresh)
782
+ bonf_lod = bonf_log * LOD_FACTOR
783
+ sug_log = 3.0
784
+ sug_lod = sug_log * LOD_FACTOR
785
+
786
+ log_p = -np.log10(np.clip(pv, 1e-300, 1))
787
+ lod = log_p * LOD_FACTOR
788
+ sig_mask = pv < bonf_thresh
789
+
790
+ fig, axes = plt.subplots(2, 1, figsize=(18, 10), facecolor=W_BG,
791
+ sharex=True, gridspec_kw={'height_ratios': [1, 1], 'hspace': 0.08})
792
+
793
+ fig.suptitle(f'GWAS Manhattan Plot β€” {model_name}',
794
+ fontsize=15, fontweight='bold', color=W_TEXT, y=1.01)
795
+
796
+ for ax_idx, (ax, values, ylabel, bonf_line, sug_line, user_line) in enumerate([
797
+ (axes[0], log_p, '-log₁₀(P)', bonf_log, sug_log, bonf_log),
798
+ (axes[1], lod, 'LOD Score', bonf_lod, sug_lod, lod_thresh_user),
799
+ ]):
800
+ ax.set_facecolor(W_PANEL)
801
+
802
+ for ci, ch in enumerate(unique_chroms):
803
+ idxs = chrom_to_idx.get(ch, [])
804
+ if not idxs:
805
+ continue
806
+
807
+ color = CHROM_COLORS[ci % len(CHROM_COLORS)]
808
+
809
+ if ci % 2 == 0:
810
+ ax.axvspan(x_pos[idxs[0]] - 0.5, x_pos[idxs[-1]] + 0.5,
811
+ color='#F0F4F8', alpha=0.7, zorder=0)
812
+
813
+ nsig_mask = [i for i in idxs if not sig_mask[i]]
814
+ if nsig_mask:
815
+ ax.scatter(x_pos[nsig_mask], values[nsig_mask],
816
+ c=color, s=6, alpha=0.55, linewidths=0, zorder=2)
817
+
818
+ sig_idxs = [i for i in idxs if sig_mask[i]]
819
+ if sig_idxs:
820
+ ax.scatter(x_pos[sig_idxs], values[sig_idxs],
821
+ c=W_RED, s=40, alpha=1.0, marker='D',
822
+ edgecolors='white', linewidths=0.5, zorder=4)
823
+
824
+ ax.axhline(bonf_line, color=W_RED, ls='--', lw=1.8, alpha=0.9,
825
+ label=f'Bonferroni ({bonf_line:.2f})', zorder=5)
826
+ ax.axhline(sug_line, color=W_GOLD, ls=':', lw=1.5, alpha=0.85,
827
+ label=f'Suggestive ({sug_line:.2f})', zorder=5)
828
+
829
+ if ax_idx == 1 and abs(user_line - bonf_lod) > 0.05:
830
+ ax.axhline(user_line, color=W_ORANGE, ls='-.', lw=1.8, alpha=0.9,
831
+ label=f'User LOD ({user_line:.1f})', zorder=5)
832
+
833
+ y_max = max(values.max() * 1.1, bonf_line * 1.2, 1.0)
834
+ ax.set_ylim(0, y_max)
835
+ ax.set_ylabel(ylabel, fontweight='bold', fontsize=12)
836
+ ax.grid(True, color=W_GRID, lw=0.5, alpha=0.6, axis='y')
837
+ ax.legend(loc='upper right', fontsize=8, ncol=3)
838
+
839
+ n_sig = sig_mask.sum()
840
+ ax.text(0.01, 0.96, f'{n_sig} significant SNPs',
841
+ transform=ax.transAxes, fontsize=9, color=W_RED, fontweight='bold',
842
+ bbox=dict(boxstyle='round,pad=0.3', fc='#FFF5F5', ec=W_RED, alpha=0.9))
843
+
844
+ axes[1].set_xticks([x for x, _ in chrom_ticks])
845
+ axes[1].set_xticklabels([l for _, l in chrom_ticks], fontsize=8, fontweight='bold')
846
+ axes[1].set_xlabel('Chromosome', fontweight='bold', fontsize=12)
847
+ axes[1].set_xlim(-GAP, offset)
848
+
849
+ mcol = MODEL_COLORS.get(model_name, W_ACCENT)
850
+ fig.text(0.01, 0.98, f'● {model_name}', color=mcol, fontsize=11, fontweight='bold', va='top')
851
+
852
+ plt.tight_layout(pad=1.0)
853
+ plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=W_BG)
854
+ plt.close(fig)
855
+
856
+ # ══════════════════════════════════════════════════════════════
857
+ # QQ PLOT
858
+ # ══════════════════════════════════════════════════════════════
859
+
860
+ def plot_qq_single(pv, model_name, bonf_thresh, save_path):
861
+ """QQ plot with inflation factor."""
862
+ _style_white()
863
+
864
+ pv = pv[np.isfinite(pv) & (pv > 0) & (pv <= 1)]
865
+
866
+ fig, ax = plt.subplots(figsize=(8, 8), facecolor=W_BG)
867
+ ax.set_facecolor(W_PANEL)
868
+
869
+ if len(pv) == 0:
870
+ ax.text(0.5, 0.5, 'No valid p-values', ha='center', va='center', fontsize=14)
871
+ plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=W_BG)
872
+ plt.close(fig)
873
+ return 1.0
874
+
875
+ n = len(pv)
876
+ obs = -np.log10(np.sort(pv))
877
+ exp = -np.log10((np.arange(1, n + 1) - 0.5) / n)
878
+
879
+ # 95% confidence interval
880
+ ci_lo = -np.log10(stats.beta.ppf(0.025, np.arange(1, n + 1), n - np.arange(1, n + 1) + 1))
881
+ ci_hi = -np.log10(stats.beta.ppf(0.975, np.arange(1, n + 1), n - np.arange(1, n + 1) + 1))
882
+
883
+ ax.fill_between(exp, ci_lo, ci_hi, color=MODEL_COLORS.get(model_name, W_ACCENT),
884
+ alpha=0.15, label='95% CI')
885
+
886
+ bonf_line = -np.log10(bonf_thresh)
887
+ above_bonf = obs > bonf_line
888
+
889
+ if (~above_bonf).any():
890
+ ax.scatter(exp[~above_bonf], obs[~above_bonf],
891
+ c=MODEL_COLORS.get(model_name, W_ACCENT), s=15, alpha=0.6, linewidths=0)
892
+ if above_bonf.any():
893
+ ax.scatter(exp[above_bonf], obs[above_bonf],
894
+ c=W_RED, s=25, alpha=0.9, marker='D', edgecolors='white', linewidths=0.5)
895
+
896
+ max_val = max(obs.max(), exp.max()) * 1.05
897
+ ax.plot([0, max_val], [0, max_val], color=W_TEXT, ls='--', lw=1.5, alpha=0.8, label='y = x')
898
+
899
+ # Genomic inflation factor Ξ»
900
+ chi2 = stats.chi2.ppf(1 - pv, df=1)
901
+ chi2_median = np.median(chi2)
902
+ lam = chi2_median / stats.chi2.ppf(0.5, df=1)
903
+
904
+ lam_color = W_RED if lam > 1.1 else W_ORANGE if lam > 1.05 else W_GREEN
905
+ ax.text(0.05, 0.95, f'Ξ» = {lam:.4f}', transform=ax.transAxes,
906
+ fontsize=16, fontweight='bold', color=lam_color, va='top',
907
+ bbox=dict(boxstyle='round,pad=0.4', fc=W_BG, ec=lam_color, alpha=0.9))
908
+
909
+ ax.set_xlim(0, max_val)
910
+ ax.set_ylim(0, max_val)
911
+ ax.set_xlabel('Expected -log₁₀(P)', fontweight='bold', fontsize=12)
912
+ ax.set_ylabel('Observed -log₁₀(P)', fontweight='bold', fontsize=12)
913
+ ax.set_title(f'QQ Plot β€” {model_name}', fontweight='bold', fontsize=13)
914
+ ax.legend(fontsize=9)
915
+ ax.grid(True, color=W_GRID, lw=0.5, alpha=0.6)
916
+
917
+ plt.tight_layout()
918
+ plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=W_BG)
919
+ plt.close(fig)
920
+
921
+ return lam
922
+
923
+ # ══════════════════════════════════════════════════════════════
924
+ # OTHER PLOTS (Phenotype, PCA, Kinship, MAF, Volcano, Comparison)
925
+ # ══════════════════════════════════════════════════════════════
926
+
927
+ def plot_phenotype(phenotypes, save_path):
928
+ """Plot phenotype distribution and QQ normality plot."""
929
+ _style_white()
930
+ pv = phenotypes[~np.isnan(phenotypes)]
931
+ fig, axes = plt.subplots(1, 2, figsize=(13, 5), facecolor=W_BG)
932
+ fig.suptitle('Phenotype Distribution & Normality', fontsize=14, fontweight='bold')
933
+
934
+ ax = axes[0]
935
+ ax.set_facecolor(W_PANEL)
936
+ ax.hist(pv, bins=min(50, len(pv)//10), color=W_ACCENT, alpha=0.7, edgecolor='white')
937
+ ax.axvline(np.mean(pv), color=W_RED, ls='--', lw=2, label=f'Mean = {np.mean(pv):.3f}')
938
+ ax.axvline(np.median(pv), color=W_GOLD, ls=':', lw=2, label=f'Median = {np.median(pv):.3f}')
939
+ ax.set_xlabel('Phenotype')
940
+ ax.set_ylabel('Frequency')
941
+ ax.set_title('Histogram')
942
+ ax.legend()
943
+ ax.grid(True, alpha=0.3)
944
+
945
+ ax = axes[1]
946
+ ax.set_facecolor(W_PANEL)
947
+ stats.probplot(pv, dist='norm', plot=ax)
948
+ ax.set_title('Normal Q-Q')
949
+ ax.grid(True, alpha=0.3)
950
+
951
+ plt.tight_layout()
952
+ plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=W_BG)
953
+ plt.close(fig)
954
+
955
+ def plot_pca(genotypes, phenotypes, n_components, save_path):
956
+ """Plot PCA analysis: scree plot and PC scatter plots."""
957
+ _style_white()
958
+ G = np.nan_to_num(genotypes - np.nanmean(genotypes, 0), 0)
959
+ n_comp = min(n_components, G.shape[0]-1, G.shape[1])
960
+
961
+ pca = PCA(n_components=n_comp)
962
+ scores = pca.fit_transform(G)
963
+ evr = pca.explained_variance_ratio_ * 100
964
+
965
+ fig = plt.figure(figsize=(15, 5), facecolor=W_BG)
966
+ gs = GridSpec(1, 3, figure=fig, wspace=0.3)
967
+
968
+ # Scree plot
969
+ ax = fig.add_subplot(gs[0])
970
+ ax.set_facecolor(W_PANEL)
971
+ bars = ax.bar(range(1, n_comp+1), evr, color=W_ACCENT, alpha=0.7)
972
+ ax.plot(range(1, n_comp+1), np.cumsum(evr), 'o-', color=W_RED, lw=2, label='Cumulative')
973
+ ax.set_xlabel('PC')
974
+ ax.set_ylabel('Variance (%)')
975
+ ax.set_title('Scree Plot')
976
+ ax.legend()
977
+ ax.grid(True, alpha=0.3)
978
+
979
+ # PC1 vs PC2
980
+ ax = fig.add_subplot(gs[1])
981
+ ax.set_facecolor(W_PANEL)
982
+ sc = ax.scatter(scores[:, 0], scores[:, 1], c=phenotypes, cmap='RdYlBu_r',
983
+ s=30, alpha=0.7, edgecolors='white', lw=0.5)
984
+ ax.set_xlabel(f'PC1 ({evr[0]:.1f}%)')
985
+ ax.set_ylabel(f'PC2 ({evr[1]:.1f}%)')
986
+ ax.set_title('PC1 vs PC2')
987
+ ax.grid(True, alpha=0.3)
988
+ plt.colorbar(sc, ax=ax, label='Phenotype')
989
+
990
+ # PC2 vs PC3
991
+ ax = fig.add_subplot(gs[2])
992
+ ax.set_facecolor(W_PANEL)
993
+ if n_comp >= 3:
994
+ sc = ax.scatter(scores[:, 1], scores[:, 2], c=phenotypes, cmap='RdYlBu_r',
995
+ s=30, alpha=0.7, edgecolors='white', lw=0.5)
996
+ ax.set_xlabel(f'PC2 ({evr[1]:.1f}%)')
997
+ ax.set_ylabel(f'PC3 ({evr[2]:.1f}%)')
998
+ ax.set_title('PC2 vs PC3')
999
+ ax.grid(True, alpha=0.3)
1000
+ plt.colorbar(sc, ax=ax, label='Phenotype')
1001
+ else:
1002
+ ax.text(0.5, 0.5, f'Need β‰₯3 PCs\n(selected {n_comp})', ha='center', va='center')
1003
+
1004
+ plt.tight_layout()
1005
+ plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=W_BG)
1006
+ plt.close(fig)
1007
+
1008
+ return evr, np.cumsum(evr), scores
1009
+
1010
+ def plot_kinship_heatmap(K, save_path, max_n=200):
1011
+ """Plot kinship matrix heatmap."""
1012
+ _style_white()
1013
+ n = K.shape[0]
1014
+ if n > max_n:
1015
+ idx = np.random.choice(n, max_n, replace=False)
1016
+ idx.sort()
1017
+ K = K[np.ix_(idx, idx)]
1018
+
1019
+ fig, ax = plt.subplots(figsize=(8, 7), facecolor=W_BG)
1020
+ cmap = LinearSegmentedColormap.from_list('kinship', ['white', '#C6DBEF', '#4292C6', '#08306B'])
1021
+ im = ax.imshow(K, cmap=cmap, vmin=0, vmax=1)
1022
+ plt.colorbar(im, ax=ax, label='Kinship coefficient')
1023
+ ax.set_title('Kinship Matrix', fontweight='bold')
1024
+ ax.set_xlabel('Sample')
1025
+ ax.set_ylabel('Sample')
1026
+ plt.tight_layout()
1027
+ plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=W_BG)
1028
+ plt.close(fig)
1029
+
1030
+ def plot_maf_distribution(maf_arr, save_path):
1031
+ """Plot minor allele frequency distribution."""
1032
+ _style_white()
1033
+ maf = maf_arr[maf_arr > 0]
1034
+ fig, axes = plt.subplots(1, 2, figsize=(12, 5), facecolor=W_BG)
1035
+ fig.suptitle('Minor Allele Frequency Distribution', fontweight='bold')
1036
+
1037
+ ax = axes[0]
1038
+ ax.set_facecolor(W_PANEL)
1039
+ ax.hist(maf, bins=40, color=W_ACCENT, alpha=0.7, edgecolor='white')
1040
+ ax.axvline(0.05, color=W_RED, ls='--', lw=2, label='MAF=0.05')
1041
+ ax.set_xlabel('MAF')
1042
+ ax.set_ylabel('Count')
1043
+ ax.legend()
1044
+ ax.grid(True, alpha=0.3)
1045
+
1046
+ ax = axes[1]
1047
+ ax.set_facecolor(W_PANEL)
1048
+ x = np.sort(maf)
1049
+ y = np.arange(1, len(x)+1) / len(x)
1050
+ ax.plot(x, y, color=W_ACCENT, lw=2)
1051
+ ax.fill_between(x, 0, y, color=W_ACCENT, alpha=0.15)
1052
+ ax.axvline(0.05, color=W_RED, ls='--', lw=2)
1053
+ ax.set_xlabel('MAF')
1054
+ ax.set_ylabel('Cumulative proportion')
1055
+ ax.set_title('Cumulative distribution')
1056
+ ax.grid(True, alpha=0.3)
1057
+
1058
+ plt.tight_layout()
1059
+ plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=W_BG)
1060
+ plt.close(fig)
1061
+
1062
+ def plot_volcano(pv, beta, model_name, bonf_thresh, save_path):
1063
+ """Plot volcano plot (effect size vs -log10 p-value)."""
1064
+ _style_white()
1065
+ log_p = -np.log10(np.clip(pv, 1e-300, 1))
1066
+ bonf_log = -np.log10(bonf_thresh)
1067
+
1068
+ fig, ax = plt.subplots(figsize=(9, 7), facecolor=W_BG)
1069
+ ax.set_facecolor(W_PANEL)
1070
+
1071
+ sig = log_p >= bonf_log
1072
+ nsig = ~sig
1073
+
1074
+ if nsig.any():
1075
+ ax.scatter(beta[nsig], log_p[nsig], c=W_SUBTEXT, s=10, alpha=0.4, linewidths=0)
1076
+
1077
+ pos_sig = sig & (beta > 0)
1078
+ neg_sig = sig & (beta < 0)
1079
+
1080
+ if pos_sig.any():
1081
+ ax.scatter(beta[pos_sig], log_p[pos_sig], c=W_RED, s=45, marker='D',
1082
+ alpha=0.9, edgecolors='white', linewidths=0.5, label='Positive effect')
1083
+ if neg_sig.any():
1084
+ ax.scatter(beta[neg_sig], log_p[neg_sig], c=W_ACCENT, s=45, marker='D',
1085
+ alpha=0.9, edgecolors='white', linewidths=0.5, label='Negative effect')
1086
+
1087
+ ax.axhline(bonf_log, color=W_RED, ls='--', lw=1.5, label=f'Bonferroni ({bonf_log:.2f})')
1088
+ ax.axvline(0, color=W_BORDER, ls=':', lw=1)
1089
+ ax.set_xlabel('Effect size (Ξ²)', fontweight='bold')
1090
+ ax.set_ylabel('-log₁₀(P)', fontweight='bold')
1091
+ ax.set_title(f'Volcano Plot β€” {model_name}', fontweight='bold')
1092
+ ax.legend()
1093
+ ax.grid(True, alpha=0.3)
1094
+
1095
+ plt.tight_layout()
1096
+ plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=W_BG)
1097
+ plt.close(fig)
1098
+
1099
+ def plot_model_comparison(model_pvals, save_path):
1100
+ """Plot pairwise model p-value comparisons."""
1101
+ _style_white()
1102
+ models = list(model_pvals.keys())
1103
+ n = len(models)
1104
+ if n < 2:
1105
+ return
1106
+
1107
+ n_pairs = n * (n - 1) // 2
1108
+ n_cols = min(3, n_pairs)
1109
+ n_rows = (n_pairs + n_cols - 1) // n_cols
1110
+
1111
+ fig, axes = plt.subplots(n_rows, n_cols, figsize=(5*n_cols, 5*n_rows), facecolor=W_BG)
1112
+ if n_rows == 1 and n_cols == 1:
1113
+ axes = np.array([[axes]])
1114
+ axes = axes.flatten()
1115
+
1116
+ pair_idx = 0
1117
+ for i in range(n):
1118
+ for j in range(i+1, n):
1119
+ ax = axes[pair_idx]
1120
+ ax.set_facecolor(W_PANEL)
1121
+
1122
+ p1 = -np.log10(np.clip(model_pvals[models[i]], 1e-300, 1))
1123
+ p2 = -np.log10(np.clip(model_pvals[models[j]], 1e-300, 1))
1124
+ corr = np.corrcoef(p1, p2)[0, 1]
1125
+
1126
+ ax.scatter(p1, p2, alpha=0.4, s=8, c=MODEL_COLORS.get(models[i], W_ACCENT))
1127
+ max_val = max(p1.max(), p2.max()) * 1.05
1128
+ ax.plot([0, max_val], [0, max_val], '--', color=W_GOLD, lw=1.5, alpha=0.7)
1129
+ ax.set_xlabel(f'{models[i]} -log₁₀(P)')
1130
+ ax.set_ylabel(f'{models[j]} -log₁₀(P)')
1131
+ ax.set_title(f'{models[i]} vs {models[j]}', fontsize=10)
1132
+ ax.text(0.05, 0.95, f'r = {corr:.3f}', transform=ax.transAxes,
1133
+ fontsize=11, fontweight='bold', color=W_RED, va='top')
1134
+ ax.grid(True, alpha=0.3)
1135
+ pair_idx += 1
1136
+
1137
+ for k in range(pair_idx, len(axes)):
1138
+ axes[k].set_visible(False)
1139
+
1140
+ plt.tight_layout()
1141
+ plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=W_BG)
1142
+ plt.close(fig)
1143
+
1144
+ def plot_circos(markers, chromosomes, positions, model_pvals, bonf_thresh, lod_thresh_user, save_path):
1145
+ """Simplified Circos plot for multi-model comparison."""
1146
+ _style_white()
1147
+
1148
+ fig, ax = plt.subplots(figsize=(12, 12), facecolor=W_BG)
1149
+
1150
+ # Simplified circos representation
1151
+ n_models = len(model_pvals)
1152
+
1153
+ # Polar plot
1154
+ ax = fig.add_subplot(111, projection='polar')
1155
+ ax.set_facecolor(W_BG)
1156
+ ax.set_title('Multi-Model GWAS Circos', fontweight='bold', pad=20)
1157
+
1158
+ # Center text
1159
+ ax.text(0, 0, f'{n_models} Models\nAnalyzed', ha='center', va='center',
1160
+ fontsize=14, fontweight='bold')
1161
+
1162
+ # Add chromosome arcs
1163
+ unique_chroms = sorted(set(chromosomes))
1164
+ n_chr = len(unique_chroms)
1165
+ theta = np.linspace(0, 2*np.pi, n_chr + 1)
1166
+
1167
+ for i, ch in enumerate(unique_chroms[:min(20, n_chr)]):
1168
+ ax.plot([theta[i], theta[i+1]], [0.8, 0.8], color=CHROM_COLORS[i % len(CHROM_COLORS)],
1169
+ lw=8, alpha=0.7, solid_capstyle='round')
1170
+ ax.text((theta[i] + theta[i+1])/2, 0.92, str(ch), ha='center', fontsize=8)
1171
+
1172
+ # Add model rings
1173
+ ring_radii = np.linspace(0.65, 0.3, n_models)
1174
+ for mi, (mname, pv) in enumerate(model_pvals.items()):
1175
+ if mi >= len(ring_radii):
1176
+ break
1177
+ r = ring_radii[mi]
1178
+ color = MODEL_COLORS.get(mname, W_ACCENT)
1179
+
1180
+ # Simple ring representation
1181
+ theta_ring = np.linspace(0, 2*np.pi, 100)
1182
+ ax.plot(theta_ring, [r] * 100, color=color, lw=2, alpha=0.5, label=mname)
1183
+
1184
+ # Add label
1185
+ ax.text(np.pi/2, r + 0.03, mname, ha='center', fontsize=7, color=color)
1186
+
1187
+ ax.set_ylim(0, 1)
1188
+ ax.set_xticks([])
1189
+ ax.set_yticks([])
1190
+ ax.legend(loc='center', bbox_to_anchor=(0.5, -0.05), ncol=n_models)
1191
+
1192
+ plt.tight_layout()
1193
+ plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=W_BG)
1194
+ plt.close(fig)
1195
+
1196
+ # ══════════════════════════════════════════════════════════════
1197
+ # MAIN ANALYSIS FUNCTION
1198
+ # ══════════════════════════════════════════════════════════════
1199
+
1200
+ def run_analysis(input_file, miss_sample, miss_marker, maf_thresh,
1201
+ lod_thresh_user, n_pc_user,
1202
+ run_glm, run_mlm, run_cmlm, run_bslmm, run_farmcpu,
1203
+ progress=gr.Progress(track_tqdm=True)):
1204
+
1205
+ try:
1206
+ if input_file is None:
1207
+ return ("⚠️ Please upload a CSV file first.",
1208
+ None, None, None, None, None, None, None, None, None,
1209
+ gr.update(choices=[]), gr.update(choices=[]), {}, {})
1210
+
1211
+ run_id = pd.Timestamp.now().strftime("%Y%m%d_%H%M%S")
1212
+ rdir = OUTPUT_DIR / run_id
1213
+ pdir = rdir / 'plots'
1214
+ for d in [rdir, pdir]:
1215
+ d.mkdir(parents=True, exist_ok=True)
1216
+
1217
+ ms_t = miss_sample / 100
1218
+ mm_t = miss_marker / 100
1219
+ mf_t = maf_thresh / 100
1220
+
1221
+ # Parse CSV
1222
+ progress(0.03, desc="Parsing CSV...")
1223
+ sids, pheno, geno, mnames, chroms, positions = parse_input_csv(input_file)
1224
+ n_s, n_m = len(sids), len(mnames)
1225
+
1226
+ # QC
1227
+ progress(0.08, desc="Quality control...")
1228
+ miss_m_rate = np.isnan(geno).sum(0) / n_s
1229
+ miss_s_rate = np.isnan(geno).sum(1) / n_m
1230
+
1231
+ maf = np.zeros(n_m)
1232
+ for i in range(n_m):
1233
+ v = geno[:, i]
1234
+ v = v[~np.isnan(v)]
1235
+ if len(v) > 0:
1236
+ f = np.mean(v) / 2
1237
+ maf[i] = min(f, 1 - f)
1238
+
1239
+ # Apply QC filters
1240
+ qc_m = (miss_m_rate < mm_t) & (maf >= mf_t)
1241
+ qc_s = miss_s_rate < ms_t
1242
+
1243
+ # Fallback if too few samples
1244
+ if qc_s.sum() < 10:
1245
+ for rs, rm in [(0.6, 0.6), (0.7, 0.7), (0.8, 0.8), (0.9, 0.9), (1.0, 1.0)]:
1246
+ qm = (miss_m_rate < rm) & (maf >= mf_t)
1247
+ qs = miss_s_rate < rs
1248
+ if qs.sum() >= 10:
1249
+ qc_m, qc_s = qm, qs
1250
+ break
1251
+
1252
+ if qc_s.sum() < 10:
1253
+ return (f"⚠️ Only {qc_s.sum()} samples passed QC (need β‰₯10)",
1254
+ None, None, None, None, None, None, None, None, None,
1255
+ gr.update(choices=[]), gr.update(choices=[]), {}, {})
1256
+
1257
+ # Apply filters
1258
+ geno_q = geno[np.ix_(qc_s, qc_m)]
1259
+ pheno_q = pheno[qc_s]
1260
+ mn_q = [mnames[i] for i in range(n_m) if qc_m[i]]
1261
+ ch_q = [chroms[i] for i in range(n_m) if qc_m[i]]
1262
+ pos_q = [positions[i] for i in range(n_m) if qc_m[i]]
1263
+ maf_q = maf[qc_m]
1264
+
1265
+ # Remove phenotype NaNs
1266
+ valid = ~np.isnan(pheno_q)
1267
+ geno_q = geno_q[valid]
1268
+ pheno_q = pheno_q[valid]
1269
+
1270
+ # Impute missing genotypes with column mean
1271
+ col_mean = np.nanmean(geno_q, axis=0)
1272
+ for i in range(geno_q.shape[1]):
1273
+ nan_mask = np.isnan(geno_q[:, i])
1274
+ if nan_mask.any():
1275
+ geno_q[nan_mask, i] = col_mean[i]
1276
+
1277
+ n_q = len(mn_q)
1278
+ bonf = 0.05 / n_q
1279
+
1280
+ # Compute kinship
1281
+ progress(0.15, desc="Computing kinship matrix...")
1282
+ K = compute_kinship(geno_q)
1283
+
1284
+ # Run models
1285
+ progress(0.20, desc="Running GWAS models...")
1286
+ model_pvals = {}
1287
+ model_betas = {}
1288
+ model_ses = {}
1289
+
1290
+ step = 0.6 / max(sum([run_glm, run_mlm, run_cmlm, run_bslmm, run_farmcpu]), 1)
1291
+ current_progress = 0.20
1292
+
1293
+ if run_glm:
1294
+ progress(current_progress, desc="GLM...")
1295
+ pv, bv, sv, _ = model_glm(geno_q, pheno_q)
1296
+ model_pvals['GLM'] = pv
1297
+ model_betas['GLM'] = bv
1298
+ model_ses['GLM'] = sv
1299
+ current_progress += step
1300
+
1301
+ if run_mlm:
1302
+ progress(current_progress, desc="MLM...")
1303
+ pv, bv, sv, _ = model_mlm(geno_q, pheno_q, K, n_pc_user)
1304
+ model_pvals['MLM'] = pv
1305
+ model_betas['MLM'] = bv
1306
+ model_ses['MLM'] = sv
1307
+ current_progress += step
1308
+
1309
+ if run_cmlm:
1310
+ progress(current_progress, desc="CMLM...")
1311
+ pv, bv, sv, _ = model_cmlm(geno_q, pheno_q, K, n_groups=None, n_pc=n_pc_user)
1312
+ model_pvals['CMLM'] = pv
1313
+ model_betas['CMLM'] = bv
1314
+ model_ses['CMLM'] = sv
1315
+ current_progress += step
1316
+
1317
+ if run_bslmm:
1318
+ progress(current_progress, desc="BSLMM (may be slow)...")
1319
+ pv, bv, sv = model_bslmm(geno_q, pheno_q)
1320
+ model_pvals['BSLMM'] = pv
1321
+ model_betas['BSLMM'] = bv
1322
+ model_ses['BSLMM'] = sv
1323
+ current_progress += step
1324
+
1325
+ if run_farmcpu:
1326
+ progress(current_progress, desc="FarmCPU...")
1327
+ pv, bv, sv = model_farmcpu(geno_q, pheno_q, K)
1328
+ model_pvals['FarmCPU'] = pv
1329
+ model_betas['FarmCPU'] = bv
1330
+ model_ses['FarmCPU'] = sv
1331
+ current_progress += step
1332
+
1333
+ if not model_pvals:
1334
+ return ("⚠️ No models selected.",
1335
+ None, None, None, None, None, None, None, None, None,
1336
+ gr.update(choices=[]), gr.update(choices=[]), {}, {})
1337
+
1338
+ # Create results table
1339
+ progress(0.80, desc="Generating results...")
1340
+ df = pd.DataFrame({
1341
+ 'Marker': mn_q,
1342
+ 'Chromosome': ch_q,
1343
+ 'Position_bp': pos_q,
1344
+ 'MAF': maf_q
1345
+ })
1346
+
1347
+ LOD_FACTOR = np.log10(np.e) / 2.0
1348
+ for mname, pv in model_pvals.items():
1349
+ df[f'{mname}_P'] = pv
1350
+ df[f'{mname}_LOD'] = -np.log10(np.clip(pv, 1e-300, 1)) * LOD_FACTOR
1351
+ df[f'{mname}_Sig'] = (pv < bonf).astype(int)
1352
+ if mname in model_betas:
1353
+ df[f'{mname}_Beta'] = model_betas[mname]
1354
+
1355
+ df = df.sort_values(f"{list(model_pvals.keys())[0]}_P").reset_index(drop=True)
1356
+ df.insert(0, 'Rank', range(1, len(df) + 1))
1357
+
1358
+ csv_path = str(rdir / 'gwas_results.csv')
1359
+ df.to_csv(csv_path, index=False)
1360
+
1361
+ # Generate plots
1362
+ progress(0.85, desc="Generating plots...")
1363
+
1364
+ # Phenotype distribution
1365
+ ph_path = str(pdir / 'phenotype_dist.png')
1366
+ plot_phenotype(pheno_q, ph_path)
1367
+
1368
+ # PCA
1369
+ pca_path = str(pdir / 'pca_analysis.png')
1370
+ evr, cumev, scores = plot_pca(geno_q, pheno_q, n_pc_user, pca_path)
1371
+
1372
+ # Kinship heatmap
1373
+ kin_path = str(pdir / 'kinship_heatmap.png')
1374
+ plot_kinship_heatmap(K, kin_path)
1375
+
1376
+ # MAF distribution
1377
+ maf_path = str(pdir / 'maf_distribution.png')
1378
+ plot_maf_distribution(maf_q, maf_path)
1379
+
1380
+ # Manhattan plots
1381
+ man_paths = {}
1382
+ for mname, pv in model_pvals.items():
1383
+ mp = str(pdir / f'manhattan_{mname}.png')
1384
+ plot_manhattan_single(mn_q, ch_q, pv, mname, bonf, lod_thresh_user, mp)
1385
+ man_paths[mname] = mp
1386
+
1387
+ # QQ plots
1388
+ qq_paths = {}
1389
+ lam_dict = {}
1390
+ for mname, pv in model_pvals.items():
1391
+ qp = str(pdir / f'qq_{mname}.png')
1392
+ lam = plot_qq_single(pv, mname, bonf, qp)
1393
+ qq_paths[mname] = qp
1394
+ lam_dict[mname] = lam
1395
+
1396
+ # LD decay
1397
+ ld_path = str(pdir / 'ld_decay.png')
1398
+ ld_stats, ld_text = plot_ld_decay(geno_q, ch_q, pos_q, ld_path)
1399
+
1400
+ # Volcano plots
1401
+ volcano_paths = {}
1402
+ for mname, pv in model_pvals.items():
1403
+ if mname in model_betas:
1404
+ vp = str(pdir / f'volcano_{mname}.png')
1405
+ plot_volcano(pv, model_betas[mname], mname, bonf, vp)
1406
+ volcano_paths[mname] = vp
1407
+
1408
+ # Model comparison
1409
+ cmp_path = str(pdir / 'model_comparison.png')
1410
+ plot_model_comparison(model_pvals, cmp_path)
1411
+
1412
+ # Circos
1413
+ circos_path = str(pdir / 'circos_mta.png')
1414
+ plot_circos(mn_q, ch_q, pos_q, model_pvals, bonf, lod_thresh_user, circos_path)
1415
+
1416
+ # Create ZIP
1417
+ progress(0.95, desc="Creating ZIP archive...")
1418
+ zip_path = str(OUTPUT_DIR / f'GWAS_Results_{run_id}.zip')
1419
+ with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf:
1420
+ for root, _, files in os.walk(str(rdir)):
1421
+ for f in files:
1422
+ fp = os.path.join(root, f)
1423
+ zf.write(fp, os.path.relpath(fp, str(rdir)))
1424
+
1425
+ # Create summary markdown
1426
+ summary = f"""
1427
+ ## βœ… GWAS Analysis Complete β€” v11.0
1428
+
1429
+ ### πŸ“Š Quality Control Summary
1430
+ | Metric | Value |
1431
+ |--------|-------|
1432
+ | Samples (after QC) | **{len(pheno_q)}** |
1433
+ | Markers (after QC) | **{n_q}** |
1434
+ | MAF threshold | β‰₯ {maf_thresh:.1f}% |
1435
+ | Bonferroni threshold | P < {bonf:.3e} (-log₁₀P > {-np.log10(bonf):.2f}) |
1436
+
1437
+ ### πŸ”¬ Model Results
1438
+ | Model | Sig. Markers | Ξ» (inflation) |
1439
+ |-------|-------------|---------------|
1440
+ """
1441
+ for mname, pv in model_pvals.items():
1442
+ n_sig = (pv < bonf).sum()
1443
+ lam = lam_dict.get(mname, 1.0)
1444
+ summary += f"| {mname} | **{n_sig}** | {lam:.4f} |\n"
1445
+
1446
+ summary += f"""
1447
+ ### 🧬 LD Decay
1448
+ {ld_text}
1449
+
1450
+ ### πŸ“ˆ Output Files
1451
+ - `gwas_results.csv` β€” Complete results for all markers
1452
+ - `plots/` β€” All figures (Manhattan, QQ, LD, PCA, etc.)
1453
+
1454
+ ### πŸ† Top Markers
1455
+ {df[['Rank', 'Marker', 'Chromosome', 'Position_bp'] + [f'{m}_P' for m in model_pvals.keys()]].head(10).to_markdown(index=False)}
1456
+
1457
+ ---
1458
+ *MTA GWAS v11.0 β€” Fixed LD decay (Hill-Weir model) | All models functional | White background*
1459
+ """
1460
+
1461
+ progress(1.0, desc="Complete!")
1462
+
1463
+ first_man = list(man_paths.values())[0] if man_paths else None
1464
+ first_qq = list(qq_paths.values())[0] if qq_paths else None
1465
+
1466
+ return (summary,
1467
+ first_man, first_qq, pca_path,
1468
+ ld_path, circos_path, cmp_path, ph_path,
1469
+ zip_path, kin_path,
1470
+ gr.update(choices=list(man_paths.keys()), value=list(man_paths.keys())[0] if man_paths else None),
1471
+ gr.update(choices=list(qq_paths.keys()), value=list(qq_paths.keys())[0] if qq_paths else None),
1472
+ man_paths, qq_paths)
1473
+
1474
+ except Exception as e:
1475
+ import traceback
1476
+ return (f"## ❌ Error\n```\n{e}\n\n{traceback.format_exc()}\n```",
1477
+ None, None, None, None, None, None, None, None, None,
1478
+ gr.update(choices=[]), gr.update(choices=[]), {}, {})
1479
+
1480
+ # ══════════════════════════════════════════════════════════════
1481
+ # GRADIO UI
1482
+ # ══════════════════════════════════════════════════════════════
1483
+
1484
+ CSS = """
1485
+ body, .gradio-container { background: #F7F9FC !important; color: #1A202C !important; }
1486
+ h1, h2, h3, h4 { color: #1A365D !important; }
1487
+ label, .label-wrap { color: #2D3748 !important; font-weight: 600 !important; }
1488
+ .gr-button-primary {
1489
+ background: linear-gradient(135deg, #1A365D 0%, #2B6CB0 100%) !important;
1490
+ color: #FFFFFF !important;
1491
+ font-weight: 700 !important;
1492
+ font-size: 15px !important;
1493
+ border: none !important;
1494
+ border-radius: 8px !important;
1495
+ box-shadow: 0 2px 8px rgba(43,108,176,0.25) !important;
1496
+ }
1497
+ .gr-button-primary:hover {
1498
+ background: linear-gradient(135deg, #2B6CB0 0%, #3182CE 100%) !important;
1499
+ box-shadow: 0 4px 14px rgba(43,108,176,0.38) !important;
1500
+ }
1501
+ .gr-box, .gr-panel, .block { background: #FFFFFF !important; border: 1px solid #E2E8F0 !important; border-radius: 10px !important; }
1502
+ .progress-bar { background: #2B6CB0 !important; }
1503
+ """
1504
+
1505
+ with gr.Blocks(css=CSS, title="GWAS Analysis v11.0") as app:
1506
+ gr.Markdown("""
1507
+ # 🧬 GWAS / MTA Analysis Platform v11.0
1508
+ ### Multi-Model Suite Β· Hill-Weir LD Decay Β· Fixed Model Selection Β· Publication-Ready White Theme
1509
+ ---
1510
+ """)
1511
+
1512
+ with gr.Row():
1513
+ with gr.Column(scale=1):
1514
+ input_file = gr.File(label="πŸ“ Upload CSV", file_types=[".csv"])
1515
+ gr.Markdown("""
1516
+ **CSV Format:**
1517
+ ID, Phenotype, Mrk1, Mrk2, ...
1518
+ """)
1519
+
1520
+ with gr.Column(scale=1):
1521
+ miss_sample = gr.Slider(5, 50, value=30, step=5, label="Max sample missing (%)")
1522
+ miss_marker = gr.Slider(5, 50, value=30, step=5, label="Max marker missing (%)")
1523
+ maf_thr = gr.Slider(0, 25, value=3, step=1, label="Min MAF (%)")
1524
+
1525
+ with gr.Column(scale=1):
1526
+ lod_thresh = gr.Slider(0.5, 10.0, value=3.0, step=0.1, label="LOD threshold")
1527
+ n_pc = gr.Slider(2, 20, value=5, step=1, label="Number of PCs")
1528
+
1529
+ gr.Markdown("### Models")
1530
+ with gr.Row():
1531
+ chk_glm = gr.Checkbox(value=True, label="GLM")
1532
+ chk_mlm = gr.Checkbox(value=True, label="MLM")
1533
+ chk_cmlm = gr.Checkbox(value=True, label="CMLM")
1534
+ chk_bslmm = gr.Checkbox(value=False, label="BSLMM")
1535
+ chk_farmcpu = gr.Checkbox(value=True, label="FarmCPU")
1536
+
1537
+ run_btn = gr.Button("πŸš€ Run GWAS Analysis", variant="primary", size="lg")
1538
+ gr.Markdown("---")
1539
+
1540
+ summary_out = gr.Markdown()
1541
+
1542
+ with gr.Row():
1543
+ man_model_sel = gr.Dropdown(label="πŸ—ΊοΈ Manhattan β€” select model", choices=[], value=None, interactive=True)
1544
+ qq_model_sel = gr.Dropdown(label="πŸ“ˆ QQ Plot β€” select model", choices=[], value=None, interactive=True)
1545
+
1546
+ with gr.Row():
1547
+ man_out = gr.Image(label="πŸ—ΊοΈ Manhattan Plot (βˆ’log₁₀P top | LOD bottom)")
1548
+ qq_out = gr.Image(label="πŸ“ˆ QQ Plot (genomic inflation Ξ»)")
1549
+
1550
+ with gr.Row():
1551
+ pca_out = gr.Image(label="πŸ”¬ PCA Analysis (Scree + PC1v2 + PC2v3)")
1552
+ ld_out = gr.Image(label="🧬 LD Decay (Hill-Weir model)")
1553
+
1554
+ with gr.Row():
1555
+ circos_out = gr.Image(label="🌐 Circos β€” Multi-Model MTA")
1556
+ cmp_out = gr.Image(label="βš–οΈ Model P-value Concordance")
1557
+
1558
+ with gr.Row():
1559
+ ph_out = gr.Image(label="πŸ“Š Phenotype Distribution")
1560
+ kin_out = gr.Image(label="πŸ”₯ Kinship Matrix Heatmap")
1561
+
1562
+ dl_out = gr.File(label="πŸ“¦ Download All Results (ZIP)")
1563
+
1564
+ man_paths_state = gr.State({})
1565
+ qq_paths_state = gr.State({})
1566
+
1567
+ run_btn.click(
1568
+ fn=run_analysis,
1569
+ inputs=[input_file, miss_sample, miss_marker, maf_thr,
1570
+ lod_thresh, n_pc,
1571
+ chk_glm, chk_mlm, chk_cmlm, chk_bslmm, chk_farmcpu],
1572
+ outputs=[summary_out, man_out, qq_out, pca_out,
1573
+ ld_out, circos_out, cmp_out, ph_out,
1574
+ dl_out, kin_out,
1575
+ man_model_sel, qq_model_sel,
1576
+ man_paths_state, qq_paths_state],
1577
+ show_progress="full"
1578
+ )
1579
+
1580
+ def switch_manhattan(model, paths):
1581
+ return paths.get(model) if paths else None
1582
+
1583
+ def switch_qq(model, paths):
1584
+ return paths.get(model) if paths else None
1585
+
1586
+ man_model_sel.change(switch_manhattan, [man_model_sel, man_paths_state], [man_out])
1587
+ qq_model_sel.change(switch_qq, [qq_model_sel, qq_paths_state], [qq_out])
1588
 
1589
  if __name__ == "__main__":
1590
+ app.launch(share=False, show_error=True, max_threads=4, allowed_paths=[str(OUTPUT_DIR)])