Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,1801 +1,71 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
===
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
"#E65100","#37474F","#880E4F","#1B5E20","#BF360C",
|
| 70 |
-
"#0D47A1","#33691E","#827717","#4A148C","#006064",
|
| 71 |
-
"#3E2723","#263238","#FF6F00","#1A237E",
|
| 72 |
-
]
|
| 73 |
-
|
| 74 |
-
MODEL_COLORS = {
|
| 75 |
-
'GLM': '#1565C0',
|
| 76 |
-
'MLM': '#C62828',
|
| 77 |
-
'CMLM': '#2E7D32',
|
| 78 |
-
'BSLMM': '#F57F17',
|
| 79 |
-
'FarmCPU': '#6A1B9A',
|
| 80 |
-
}
|
| 81 |
-
|
| 82 |
-
def _style_white():
|
| 83 |
-
"""Apply clean white scientific publication theme."""
|
| 84 |
-
plt.rcParams.update({
|
| 85 |
-
'figure.facecolor': W_BG,
|
| 86 |
-
'axes.facecolor': W_PANEL,
|
| 87 |
-
'axes.edgecolor': W_BORDER,
|
| 88 |
-
'axes.labelcolor': W_TEXT,
|
| 89 |
-
'axes.titlecolor': W_TEXT,
|
| 90 |
-
'xtick.color': W_TEXT,
|
| 91 |
-
'ytick.color': W_TEXT,
|
| 92 |
-
'text.color': W_TEXT,
|
| 93 |
-
'grid.color': W_GRID,
|
| 94 |
-
'grid.linewidth': 0.6,
|
| 95 |
-
'figure.dpi': 120,
|
| 96 |
-
'font.family': 'DejaVu Sans',
|
| 97 |
-
'font.size': 10,
|
| 98 |
-
'axes.titlesize': 12,
|
| 99 |
-
'axes.labelsize': 11,
|
| 100 |
-
'axes.spines.top': False,
|
| 101 |
-
'axes.spines.right': False,
|
| 102 |
-
'legend.framealpha': 0.95,
|
| 103 |
-
'legend.edgecolor': W_BORDER,
|
| 104 |
-
'legend.facecolor': W_BG,
|
| 105 |
-
'legend.fontsize': 9,
|
| 106 |
-
'savefig.facecolor': W_BG,
|
| 107 |
-
'savefig.edgecolor': W_BG,
|
| 108 |
-
})
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
# ══════════════════════════════════════════════════════════════
|
| 112 |
-
# CSV PARSER
|
| 113 |
-
# ══════════════════════════════════════════════════════════════
|
| 114 |
-
def parse_input_csv(filepath):
|
| 115 |
-
df = pd.read_csv(filepath, header=0, dtype=str)
|
| 116 |
-
marker_cols = df.columns[2:].tolist()
|
| 117 |
-
chr_row = df.iloc[0]
|
| 118 |
-
pos_row = df.iloc[1]
|
| 119 |
-
chrom_dict, pos_dict = {}, {}
|
| 120 |
-
for m in marker_cols:
|
| 121 |
-
cv = str(chr_row[m]).strip()
|
| 122 |
-
cv = cv[:-2] if cv.endswith('.0') else cv
|
| 123 |
-
cv = cv.replace('chr','').replace('Chr','').strip()
|
| 124 |
-
chrom_dict[m] = cv if cv not in ('', 'nan', '-') else '0'
|
| 125 |
-
pv_s = str(pos_row[m]).strip()
|
| 126 |
-
try:
|
| 127 |
-
pos_dict[m] = float(pv_s)
|
| 128 |
-
except ValueError:
|
| 129 |
-
parts = m.split('_')
|
| 130 |
-
bp = 0.0
|
| 131 |
-
for part in parts:
|
| 132 |
-
try:
|
| 133 |
-
cand = float(part)
|
| 134 |
-
if cand > 1000:
|
| 135 |
-
bp = cand
|
| 136 |
-
break
|
| 137 |
-
except ValueError:
|
| 138 |
-
continue
|
| 139 |
-
pos_dict[m] = bp
|
| 140 |
-
|
| 141 |
-
df_s = df.iloc[2:].reset_index(drop=True)
|
| 142 |
-
sample_ids = df_s.iloc[:, 0].astype(str).values
|
| 143 |
-
phenotypes = pd.to_numeric(df_s.iloc[:, 1], errors='coerce').values
|
| 144 |
-
geno_raw = (df_s[marker_cols]
|
| 145 |
-
.apply(pd.to_numeric, errors='coerce')
|
| 146 |
-
.replace(-1, np.nan)
|
| 147 |
-
.where(lambda x: x.isin([0, 1, 2]) | x.isna(), other=np.nan))
|
| 148 |
-
chromosomes = [chrom_dict[m] for m in marker_cols]
|
| 149 |
-
positions = [pos_dict[m] for m in marker_cols]
|
| 150 |
-
return (sample_ids, phenotypes,
|
| 151 |
-
geno_raw.values, marker_cols, chromosomes, positions)
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
# ══════════════════════════════════════════════════════════════
|
| 155 |
-
# KINSHIP
|
| 156 |
-
# ══════════════════════════════════════════════════════════════
|
| 157 |
-
def compute_kinship(G):
|
| 158 |
-
X = G.astype(float).copy()
|
| 159 |
-
mu = np.nanmean(X, 0)
|
| 160 |
-
std = np.nanstd(X, 0)
|
| 161 |
-
std[std < 1e-9] = 1.0
|
| 162 |
-
X = (X - mu) / std
|
| 163 |
-
X = np.nan_to_num(X, 0)
|
| 164 |
-
K = (X @ X.T) / X.shape[1]
|
| 165 |
-
d = np.diag(K).mean()
|
| 166 |
-
if d > 0:
|
| 167 |
-
K /= d
|
| 168 |
-
return K
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
# ══════════════════════════════════════════════════════════════
|
| 172 |
-
# MODELS
|
| 173 |
-
# ══════════════════════════════════════════════════════════════
|
| 174 |
-
def model_glm(G, y):
|
| 175 |
-
n, m = G.shape
|
| 176 |
-
pv = np.ones(m); bv = np.zeros(m); sv = np.zeros(m); rv = np.zeros(m)
|
| 177 |
-
for i in range(m):
|
| 178 |
-
x = G[:, i]
|
| 179 |
-
if x.std() < 1e-9:
|
| 180 |
-
continue
|
| 181 |
-
sl, _, r, p, se = stats.linregress(x, y)
|
| 182 |
-
pv[i] = max(p, 1e-300) if np.isfinite(p) else 1.0
|
| 183 |
-
bv[i] = sl; sv[i] = se; rv[i] = r**2
|
| 184 |
-
return pv, bv, sv, rv
|
| 185 |
-
|
| 186 |
-
def model_mlm(G, y, K, n_pc=5):
|
| 187 |
-
n = len(y)
|
| 188 |
-
n_pc = min(n_pc, n - 2)
|
| 189 |
-
eigvals, eigvecs = np.linalg.eigh(K)
|
| 190 |
-
idx = np.argsort(eigvals)[::-1]
|
| 191 |
-
Q = eigvecs[:, idx[:n_pc]]
|
| 192 |
-
Qy = Q @ np.linalg.lstsq(Q, y, rcond=None)[0]
|
| 193 |
-
y_r = y - Qy
|
| 194 |
-
m = G.shape[1]
|
| 195 |
-
pv = np.ones(m); bv = np.zeros(m); sv = np.zeros(m); rv = np.zeros(m)
|
| 196 |
-
for i in range(m):
|
| 197 |
-
x = G[:, i]
|
| 198 |
-
if x.std() < 1e-9:
|
| 199 |
-
continue
|
| 200 |
-
Qx = Q @ np.linalg.lstsq(Q, x, rcond=None)[0]
|
| 201 |
-
xr = x - Qx
|
| 202 |
-
if xr.std() < 1e-9:
|
| 203 |
-
continue
|
| 204 |
-
sl, _, r, p, se = stats.linregress(xr, y_r)
|
| 205 |
-
pv[i] = max(p, 1e-300) if np.isfinite(p) else 1.0
|
| 206 |
-
bv[i] = sl; sv[i] = se; rv[i] = r**2
|
| 207 |
-
return pv, bv, sv, rv
|
| 208 |
-
|
| 209 |
-
def model_cmlm(G, y, K, n_groups=None, n_pc=5):
|
| 210 |
-
n = len(y)
|
| 211 |
-
if n_groups is None:
|
| 212 |
-
n_groups = max(2, min(20, n // 10))
|
| 213 |
-
eigvals, eigvecs = np.linalg.eigh(K)
|
| 214 |
-
idx = np.argsort(eigvals)[::-1]
|
| 215 |
-
emb = eigvecs[:, idx[:min(10, n-1)]]
|
| 216 |
-
km = KMeans(n_clusters=n_groups, random_state=42, n_init=5)
|
| 217 |
-
labs = km.fit_predict(emb)
|
| 218 |
-
Q = np.zeros((n, n_groups))
|
| 219 |
-
for g in range(n_groups):
|
| 220 |
-
Q[:, g] = (labs == g).astype(float)
|
| 221 |
-
col_sum = Q.sum(0); col_sum[col_sum == 0] = 1; Q = Q / col_sum
|
| 222 |
-
Qy = Q @ np.linalg.lstsq(Q, y, rcond=None)[0]
|
| 223 |
-
y_r = y - Qy
|
| 224 |
-
m = G.shape[1]
|
| 225 |
-
pv = np.ones(m); bv = np.zeros(m); sv = np.zeros(m); rv = np.zeros(m)
|
| 226 |
-
for i in range(m):
|
| 227 |
-
x = G[:, i]
|
| 228 |
-
if x.std() < 1e-9:
|
| 229 |
-
continue
|
| 230 |
-
Qx = Q @ np.linalg.lstsq(Q, x, rcond=None)[0]
|
| 231 |
-
xr = x - Qx
|
| 232 |
-
if xr.std() < 1e-9:
|
| 233 |
-
continue
|
| 234 |
-
sl, _, r, p, se = stats.linregress(xr, y_r)
|
| 235 |
-
pv[i] = max(p, 1e-300) if np.isfinite(p) else 1.0
|
| 236 |
-
bv[i] = sl; sv[i] = se; rv[i] = r**2
|
| 237 |
-
return pv, bv, sv, rv
|
| 238 |
-
|
| 239 |
-
def model_bslmm(G, y, n_boot=8):
|
| 240 |
-
sc = StandardScaler()
|
| 241 |
-
Xs = sc.fit_transform(G)
|
| 242 |
-
n, m = Xs.shape
|
| 243 |
-
if m > 2000:
|
| 244 |
-
mdl = RidgeCV(alphas=np.logspace(-3, 3, 20), cv=3)
|
| 245 |
-
mdl.fit(Xs, y); coef = mdl.coef_
|
| 246 |
-
else:
|
| 247 |
-
en = ElasticNetCV(cv=3, random_state=42, max_iter=1000,
|
| 248 |
-
n_jobs=-1, l1_ratio=[.1,.5,.9,1])
|
| 249 |
-
en.fit(Xs, y); coef = en.coef_
|
| 250 |
-
boots = []; rng = np.random.default_rng(42)
|
| 251 |
-
for _ in range(n_boot):
|
| 252 |
-
idx = rng.integers(0, n, n)
|
| 253 |
-
try:
|
| 254 |
-
eb = (RidgeCV(alphas=[0.1,1,10], cv=3) if m > 2000
|
| 255 |
-
else ElasticNetCV(cv=3, random_state=42, max_iter=500,
|
| 256 |
-
l1_ratio=[.1,.5,.9,1]))
|
| 257 |
-
eb.fit(Xs[idx], y[idx]); boots.append(eb.coef_)
|
| 258 |
-
except:
|
| 259 |
-
boots.append(coef.copy())
|
| 260 |
-
boot_arr = np.array(boots); pv = np.ones(m)
|
| 261 |
-
for i in range(m):
|
| 262 |
-
sd = boot_arr[:, i].std()
|
| 263 |
-
if sd > 0:
|
| 264 |
-
z = abs(coef[i]) / (sd + 1e-12)
|
| 265 |
-
pv[i] = max(2 * (1 - stats.norm.cdf(z)), 1e-300)
|
| 266 |
-
return pv, coef
|
| 267 |
-
|
| 268 |
-
def model_farmcpu(G, y, K, max_iter=3):
|
| 269 |
-
n, m = G.shape
|
| 270 |
-
pv_cur, bv, sv, rv = model_glm(G, y)
|
| 271 |
-
for iteration in range(max_iter):
|
| 272 |
-
n_qtns = max(1, min(10, int(m * 0.001)))
|
| 273 |
-
top_idx = np.argsort(pv_cur)[:n_qtns]
|
| 274 |
-
covs = G[:, top_idx]
|
| 275 |
-
try:
|
| 276 |
-
coef_c, _, _, _ = np.linalg.lstsq(
|
| 277 |
-
np.column_stack([np.ones(n), covs]), y, rcond=None)
|
| 278 |
-
y_cond = y - np.column_stack([np.ones(n), covs]) @ coef_c
|
| 279 |
-
except:
|
| 280 |
-
y_cond = y.copy()
|
| 281 |
-
q = covs.shape[1]; df = max(n - q - 2, 1)
|
| 282 |
-
pv_new = np.ones(m); bv_new = np.zeros(m); sv_new = np.zeros(m)
|
| 283 |
-
for i in range(m):
|
| 284 |
-
x = G[:, i]
|
| 285 |
-
if x.std() < 1e-9:
|
| 286 |
-
continue
|
| 287 |
-
X2 = np.column_stack([np.ones(n), x])
|
| 288 |
-
try:
|
| 289 |
-
b, res, _, _ = np.linalg.lstsq(X2, y_cond, rcond=None)
|
| 290 |
-
except:
|
| 291 |
-
continue
|
| 292 |
-
fitted = X2 @ b; sse = float(np.sum((y_cond - fitted)**2))
|
| 293 |
-
ssx = float(np.sum((x - x.mean())**2))
|
| 294 |
-
if ssx < 1e-12 or sse < 1e-300:
|
| 295 |
-
continue
|
| 296 |
-
se_b = np.sqrt(sse / df / ssx); t_stat = b[1] / (se_b + 1e-300)
|
| 297 |
-
p = 2 * stats.t.sf(abs(t_stat), df=df)
|
| 298 |
-
pv_new[i] = max(float(p), 1e-300) if np.isfinite(p) else 1.0
|
| 299 |
-
bv_new[i] = float(b[1]); sv_new[i] = se_b
|
| 300 |
-
pv_cur = pv_new.copy()
|
| 301 |
-
return pv_cur, bv_new, sv_new
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
# ══════════════════════════════════════════════════════════════
|
| 305 |
-
# HELPER: build X-axis positions for Manhattan-style plots
|
| 306 |
-
# ══════════════════════════════════════════════════════════════
|
| 307 |
-
def _build_x_pos(mn, chroms, GAP=None):
|
| 308 |
-
unique_chroms = sorted(set(chroms),
|
| 309 |
-
key=lambda x: (int(x) if str(x).isdigit() else 999, str(x)))
|
| 310 |
-
if GAP is None:
|
| 311 |
-
GAP = max(8, len(mn) // 150)
|
| 312 |
-
chrom_to_idx = {}
|
| 313 |
-
for i, c in enumerate(chroms):
|
| 314 |
-
chrom_to_idx.setdefault(c, []).append(i)
|
| 315 |
-
x_pos = np.zeros(len(mn))
|
| 316 |
-
chrom_xticks = []
|
| 317 |
-
offset = 0
|
| 318 |
-
for ch in unique_chroms:
|
| 319 |
-
idxs = chrom_to_idx.get(ch, [])
|
| 320 |
-
if not idxs:
|
| 321 |
-
continue
|
| 322 |
-
for r, idx in enumerate(idxs):
|
| 323 |
-
x_pos[idx] = offset + r
|
| 324 |
-
chrom_xticks.append((offset + len(idxs) / 2, str(ch)))
|
| 325 |
-
offset += len(idxs) + GAP
|
| 326 |
-
return x_pos, chrom_xticks, offset, GAP, unique_chroms, chrom_to_idx
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
# ══════════════════════════════════════════════════════════════
|
| 330 |
-
# PLOT 1: PHENOTYPE DISTRIBUTION — white
|
| 331 |
-
# ══════════════════════════════════════════════════════════════
|
| 332 |
-
def plot_phenotype(phenotypes, save_path):
|
| 333 |
-
_style_white()
|
| 334 |
-
pv = phenotypes[~np.isnan(phenotypes)]
|
| 335 |
-
fig, axes = plt.subplots(1, 2, figsize=(13, 5.5), facecolor=W_BG)
|
| 336 |
-
fig.suptitle('Phenotype Distribution & Normality Assessment',
|
| 337 |
-
fontsize=14, fontweight='bold', color=W_TEXT, y=1.02)
|
| 338 |
-
|
| 339 |
-
# Histogram
|
| 340 |
-
ax = axes[0]; ax.set_facecolor(W_PANEL)
|
| 341 |
-
n_bins = min(50, max(15, len(pv) // 10))
|
| 342 |
-
ax.hist(pv, bins=n_bins, color=W_ACCENT, alpha=0.75,
|
| 343 |
-
edgecolor='white', lw=0.6, zorder=2)
|
| 344 |
-
ax.axvline(np.mean(pv), color=W_RED, ls='--', lw=2.0, zorder=3,
|
| 345 |
-
label=f'Mean = {np.mean(pv):.3f}')
|
| 346 |
-
ax.axvline(np.median(pv), color=W_GOLD, ls=':', lw=2.0, zorder=3,
|
| 347 |
-
label=f'Median = {np.median(pv):.3f}')
|
| 348 |
-
ax.set_xlabel('Phenotype Value', fontweight='bold')
|
| 349 |
-
ax.set_ylabel('Frequency', fontweight='bold')
|
| 350 |
-
ax.set_title('Phenotype Histogram', fontweight='bold', color=W_ACCENT)
|
| 351 |
-
ax.legend(); ax.grid(True, color=W_GRID, lw=0.6, alpha=0.8)
|
| 352 |
-
sw_s, sw_p = stats.shapiro(pv[:5000])
|
| 353 |
-
skew = stats.skew(pv); kurt = stats.kurtosis(pv)
|
| 354 |
-
ax.text(0.04, 0.96,
|
| 355 |
-
f'Shapiro-Wilk p = {sw_p:.3e}\nSkewness = {skew:.3f}\nKurtosis = {kurt:.3f}',
|
| 356 |
-
transform=ax.transAxes, va='top', fontsize=9, color=W_SUBTEXT,
|
| 357 |
-
bbox=dict(boxstyle='round,pad=0.4', fc=W_BG, ec=W_BORDER, alpha=0.95))
|
| 358 |
-
|
| 359 |
-
# QQ plot
|
| 360 |
-
ax = axes[1]; ax.set_facecolor(W_PANEL)
|
| 361 |
-
(osm, osr), (slope, intercept, r) = stats.probplot(pv, dist='norm')
|
| 362 |
-
ax.scatter(osm, osr, color=W_ACCENT, s=14, alpha=0.65, zorder=2, label='Observed')
|
| 363 |
-
line_x = np.array([osm.min(), osm.max()])
|
| 364 |
-
ax.plot(line_x, slope * line_x + intercept, color=W_RED, lw=2.0,
|
| 365 |
-
zorder=3, label=f'Expected (r={r:.4f})')
|
| 366 |
-
ax.set_xlabel('Theoretical Quantiles', fontweight='bold')
|
| 367 |
-
ax.set_ylabel('Sample Quantiles', fontweight='bold')
|
| 368 |
-
ax.set_title('Normal Q-Q Plot', fontweight='bold', color=W_ACCENT)
|
| 369 |
-
ax.legend(); ax.grid(True, color=W_GRID, lw=0.6, alpha=0.8)
|
| 370 |
-
|
| 371 |
-
plt.tight_layout(pad=1.5)
|
| 372 |
-
plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=W_BG)
|
| 373 |
-
plt.close(fig)
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
# ══════════════════════════════════════════════════════════════
|
| 377 |
-
# PLOT 2: PCA — white
|
| 378 |
-
# ══════════════════════════════════════════════════════════════
|
| 379 |
-
def plot_pca(geno_q, pheno_q, n_components, save_path):
|
| 380 |
-
_style_white()
|
| 381 |
-
G = geno_q.astype(float).copy()
|
| 382 |
-
G = np.nan_to_num(G - np.nanmean(G, 0), 0)
|
| 383 |
-
n_comp = min(n_components, G.shape[0] - 1, G.shape[1])
|
| 384 |
-
|
| 385 |
-
pca = PCA(n_components=n_comp)
|
| 386 |
-
scores = pca.fit_transform(G)
|
| 387 |
-
evr = pca.explained_variance_ratio_ * 100
|
| 388 |
-
cumev = np.cumsum(evr)
|
| 389 |
-
|
| 390 |
-
fig = plt.figure(figsize=(18, 6), facecolor=W_BG)
|
| 391 |
-
fig.suptitle(f'Principal Component Analysis — Top {n_comp} PCs',
|
| 392 |
-
fontsize=14, fontweight='bold', color=W_TEXT, y=1.02)
|
| 393 |
-
gs = GridSpec(1, 3, figure=fig, wspace=0.32)
|
| 394 |
-
|
| 395 |
-
# Scree
|
| 396 |
-
ax0 = fig.add_subplot(gs[0]); ax0.set_facecolor(W_PANEL)
|
| 397 |
-
pc_labels = [f'PC{i+1}' for i in range(n_comp)]
|
| 398 |
-
bars = ax0.bar(pc_labels, evr, color=W_ACCENT, alpha=0.75,
|
| 399 |
-
edgecolor=W_BORDER, lw=0.8, zorder=2)
|
| 400 |
-
ax0.plot(range(n_comp), cumev, 'o-', color=W_RED, lw=2, ms=5,
|
| 401 |
-
zorder=3, label='Cumulative %')
|
| 402 |
-
ax0.axhline(80, color=W_GOLD, ls='--', lw=1.2, alpha=0.8, label='80% line')
|
| 403 |
-
ax0.set_xlabel('Principal Component', fontweight='bold')
|
| 404 |
-
ax0.set_ylabel('Variance Explained (%)', fontweight='bold')
|
| 405 |
-
ax0.set_title('Scree Plot', fontweight='bold', color=W_ACCENT)
|
| 406 |
-
ax0.tick_params(axis='x', rotation=45, labelsize=7)
|
| 407 |
-
ax0.legend(fontsize=8); ax0.grid(True, color=W_GRID, lw=0.5)
|
| 408 |
-
for bar, pct in zip(bars, evr):
|
| 409 |
-
if pct > 1.0:
|
| 410 |
-
ax0.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 0.3,
|
| 411 |
-
f'{pct:.1f}%', ha='center', va='bottom', fontsize=7, color=W_TEXT)
|
| 412 |
-
|
| 413 |
-
# PC1 vs PC2
|
| 414 |
-
ax1 = fig.add_subplot(gs[1]); ax1.set_facecolor(W_PANEL)
|
| 415 |
-
sc = ax1.scatter(scores[:, 0], scores[:, 1],
|
| 416 |
-
c=pheno_q, cmap='RdYlBu_r', s=40, alpha=0.80,
|
| 417 |
-
edgecolors=W_BORDER, lw=0.3, zorder=3)
|
| 418 |
-
ax1.axhline(0, color=W_BORDER, lw=0.8, ls='--'); ax1.axvline(0, color=W_BORDER, lw=0.8, ls='--')
|
| 419 |
-
ax1.set_xlabel(f'PC1 ({evr[0]:.2f}%)', fontweight='bold')
|
| 420 |
-
ax1.set_ylabel(f'PC2 ({evr[1]:.2f}%)' if n_comp > 1 else 'PC2', fontweight='bold')
|
| 421 |
-
ax1.set_title('PC1 vs PC2 (coloured by phenotype)', fontweight='bold', color=W_ACCENT)
|
| 422 |
-
cb = plt.colorbar(sc, ax=ax1, pad=0.02)
|
| 423 |
-
cb.set_label('Phenotype', fontsize=9); ax1.grid(True, color=W_GRID, lw=0.5)
|
| 424 |
-
|
| 425 |
-
# PC2 vs PC3
|
| 426 |
-
ax2 = fig.add_subplot(gs[2]); ax2.set_facecolor(W_PANEL)
|
| 427 |
-
if n_comp >= 3:
|
| 428 |
-
sc2 = ax2.scatter(scores[:, 1], scores[:, 2],
|
| 429 |
-
c=pheno_q, cmap='RdYlBu_r', s=40, alpha=0.80,
|
| 430 |
-
edgecolors=W_BORDER, lw=0.3, zorder=3)
|
| 431 |
-
ax2.set_xlabel(f'PC2 ({evr[1]:.2f}%)', fontweight='bold')
|
| 432 |
-
ax2.set_ylabel(f'PC3 ({evr[2]:.2f}%)', fontweight='bold')
|
| 433 |
-
ax2.set_title('PC2 vs PC3', fontweight='bold', color=W_ACCENT)
|
| 434 |
-
cb2 = plt.colorbar(sc2, ax=ax2, pad=0.02)
|
| 435 |
-
cb2.set_label('Phenotype', fontsize=9)
|
| 436 |
-
else:
|
| 437 |
-
ax2.text(0.5, 0.5, f'Need ≥3 PCs\n(selected {n_comp})',
|
| 438 |
-
ha='center', va='center', transform=ax2.transAxes, fontsize=13, color=W_SUBTEXT)
|
| 439 |
-
ax2.axhline(0, color=W_BORDER, lw=0.8, ls='--'); ax2.axvline(0, color=W_BORDER, lw=0.8, ls='--')
|
| 440 |
-
ax2.grid(True, color=W_GRID, lw=0.5)
|
| 441 |
-
|
| 442 |
-
plt.tight_layout()
|
| 443 |
-
plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=W_BG)
|
| 444 |
-
plt.close(fig)
|
| 445 |
-
return evr, cumev, scores
|
| 446 |
-
|
| 447 |
-
|
| 448 |
-
# ══════════════════════════════════════════════════════════════
|
| 449 |
-
# PLOT 3: MANHATTAN + LOD vs CHROMOSOME — white, TWO PANELS
|
| 450 |
-
# Panel 1: -log10(P) vs Chromosome
|
| 451 |
-
# Panel 2: LOD Score vs Chromosome (standalone)
|
| 452 |
-
# ══════════════════════════════════════════════════════════════
|
| 453 |
-
def plot_manhattan_single(mn, ch_q, pv, mname, bonf_thresh, lod_thresh_user, save_path):
|
| 454 |
-
_style_white()
|
| 455 |
-
LOD_FACTOR = np.log10(np.e) / 2.0
|
| 456 |
-
GAP = max(8, len(mn) // 150)
|
| 457 |
-
x_pos, chrom_xticks, offset, GAP, unique_chroms, chrom_to_idx = _build_x_pos(mn, ch_q, GAP)
|
| 458 |
-
|
| 459 |
-
bonf_log = -np.log10(bonf_thresh)
|
| 460 |
-
bonf_lod = bonf_log * LOD_FACTOR
|
| 461 |
-
sug_log = 3.0
|
| 462 |
-
sug_lod = sug_log * LOD_FACTOR
|
| 463 |
-
mcol = MODEL_COLORS.get(mname, W_ACCENT)
|
| 464 |
-
log_p = -np.log10(np.clip(pv, 1e-300, 1))
|
| 465 |
-
lod = log_p * LOD_FACTOR
|
| 466 |
-
sig_set = set(np.where(pv < bonf_thresh)[0])
|
| 467 |
-
n_sig = len(sig_set)
|
| 468 |
-
|
| 469 |
-
fig, axes = plt.subplots(2, 1, figsize=(18, 10), facecolor=W_BG,
|
| 470 |
-
sharex=True, gridspec_kw={'height_ratios': [1, 1], 'hspace': 0.06})
|
| 471 |
-
fig.suptitle(f'GWAS Manhattan Plot — {mname}',
|
| 472 |
-
fontsize=15, fontweight='bold', color=W_TEXT, y=1.01)
|
| 473 |
-
|
| 474 |
-
for ax_idx, (ax, vals, ylabel, bonf_line, sug_line, user_line, user_label) in enumerate([
|
| 475 |
-
(axes[0], log_p, '−log₁₀(P)', bonf_log, sug_log, bonf_log, f'Bonferroni ({bonf_log:.2f})'),
|
| 476 |
-
(axes[1], lod, 'LOD Score', bonf_lod, sug_lod, lod_thresh_user, f'LOD threshold ({lod_thresh_user:.1f})'),
|
| 477 |
-
]):
|
| 478 |
-
ax.set_facecolor(W_PANEL)
|
| 479 |
-
|
| 480 |
-
# Alternating chromosome shading
|
| 481 |
-
for ci, ch in enumerate(unique_chroms):
|
| 482 |
-
idxs = chrom_to_idx.get(ch, [])
|
| 483 |
-
if not idxs:
|
| 484 |
-
continue
|
| 485 |
-
shade = CHROM_COLORS[ci % len(CHROM_COLORS)]
|
| 486 |
-
# Alternate background band
|
| 487 |
-
if ci % 2 == 0:
|
| 488 |
-
ax.axvspan(x_pos[idxs[0]] - 0.5, x_pos[idxs[-1]] + 0.5,
|
| 489 |
-
color='#F0F4F8', alpha=0.7, zorder=0)
|
| 490 |
-
norm = [i for i in idxs if i not in sig_set]
|
| 491 |
-
sel = [i for i in idxs if i in sig_set]
|
| 492 |
-
if norm:
|
| 493 |
-
ax.scatter(x_pos[norm], vals[norm], c=shade,
|
| 494 |
-
s=8, alpha=0.60, linewidths=0, zorder=2)
|
| 495 |
-
if sel:
|
| 496 |
-
ax.scatter(x_pos[sel], vals[sel], c=W_RED,
|
| 497 |
-
s=60, alpha=1.0, edgecolors='#8B0000',
|
| 498 |
-
linewidths=0.8, marker='D', zorder=4)
|
| 499 |
-
|
| 500 |
-
# Threshold lines
|
| 501 |
-
ax.axhline(bonf_line, color=W_RED, ls='--', lw=1.8, alpha=0.9,
|
| 502 |
-
label=f'Bonferroni ({bonf_line:.2f})', zorder=5)
|
| 503 |
-
ax.axhline(sug_line, color=W_GOLD, ls=':', lw=1.5, alpha=0.85,
|
| 504 |
-
label=f'Suggestive ({sug_line:.2f})', zorder=5)
|
| 505 |
-
if ax_idx == 1 and abs(user_line - bonf_lod) > 0.05:
|
| 506 |
-
ax.axhline(user_line, color=W_ORANGE, ls='-.', lw=1.8, alpha=0.9,
|
| 507 |
-
label=f'User LOD ({user_line:.1f})', zorder=5)
|
| 508 |
-
|
| 509 |
-
peak = float(vals.max())
|
| 510 |
-
ylim_top = max(peak * 1.12, bonf_line * 1.18, 1.0)
|
| 511 |
-
ax.set_ylim(0, ylim_top)
|
| 512 |
-
ax.set_ylabel(ylabel, fontweight='bold', fontsize=12)
|
| 513 |
-
ax.yaxis.grid(True, color=W_GRID, lw=0.5, alpha=0.8)
|
| 514 |
-
ax.legend(loc='upper right', fontsize=8, ncol=3,
|
| 515 |
-
framealpha=0.95, edgecolor=W_BORDER)
|
| 516 |
-
ax.text(0.005, 0.94, f'{n_sig} significant SNPs (Bonferroni)',
|
| 517 |
-
transform=ax.transAxes, fontsize=9, color=W_RED, fontweight='bold',
|
| 518 |
-
bbox=dict(boxstyle='round,pad=0.3', fc='#FFF5F5', ec=W_RED, alpha=0.9))
|
| 519 |
-
|
| 520 |
-
axes[1].set_xticks([x for x, _ in chrom_xticks])
|
| 521 |
-
axes[1].set_xticklabels([l for _, l in chrom_xticks], fontsize=8, color=W_TEXT, fontweight='bold')
|
| 522 |
-
axes[1].set_xlabel('Chromosome', fontweight='bold', fontsize=12)
|
| 523 |
-
axes[1].set_xlim(-GAP, offset)
|
| 524 |
-
|
| 525 |
-
# Add model colour indicator
|
| 526 |
-
fig.text(0.01, 0.98, f'● {mname}', color=mcol, fontsize=11, fontweight='bold', va='top')
|
| 527 |
-
|
| 528 |
-
plt.tight_layout(pad=1.0, h_pad=0.2)
|
| 529 |
-
plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=W_BG)
|
| 530 |
-
plt.close(fig)
|
| 531 |
-
|
| 532 |
-
|
| 533 |
-
# ══════════════════════════════════════════════════════════════
|
| 534 |
-
# PLOT 4: QQ PLOT — white background
|
| 535 |
-
# ══════════════════════════════════════════════════════════════
|
| 536 |
-
def plot_qq_single(pv_raw, mname, bonf_thresh, save_path):
|
| 537 |
-
_style_white()
|
| 538 |
-
mcol = MODEL_COLORS.get(mname, W_ACCENT)
|
| 539 |
-
bonf_log = -np.log10(bonf_thresh)
|
| 540 |
-
|
| 541 |
-
pv = np.array(pv_raw, dtype=float)
|
| 542 |
-
pv = pv[np.isfinite(pv) & (pv > 0) & (pv <= 1)]
|
| 543 |
-
|
| 544 |
-
fig, ax = plt.subplots(figsize=(8, 8), facecolor=W_BG)
|
| 545 |
-
ax.set_facecolor(W_PANEL)
|
| 546 |
-
fig.suptitle(f'QQ Plot — {mname}', fontsize=14, fontweight='bold', color=W_TEXT, y=1.01)
|
| 547 |
-
|
| 548 |
-
if not len(pv):
|
| 549 |
-
ax.text(0.5, 0.5, 'No valid p-values', ha='center', va='center',
|
| 550 |
-
transform=ax.transAxes, fontsize=14, color=W_SUBTEXT)
|
| 551 |
-
plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=W_BG)
|
| 552 |
-
plt.close(fig)
|
| 553 |
-
return 1.0
|
| 554 |
-
|
| 555 |
-
n = len(pv)
|
| 556 |
-
ranks = np.arange(1, n + 1)
|
| 557 |
-
obs_sorted = np.sort(pv)
|
| 558 |
-
exp_log = -np.log10(ranks / (n + 1))
|
| 559 |
-
obs_log = -np.log10(obs_sorted)
|
| 560 |
-
sort_idx = np.argsort(exp_log)[::-1]
|
| 561 |
-
exp_log = exp_log[sort_idx]
|
| 562 |
-
obs_log = obs_log[sort_idx]
|
| 563 |
-
|
| 564 |
-
# 95% CI band
|
| 565 |
-
ci_hi = -np.log10(stats.beta.ppf(0.025, ranks, ranks[::-1] + 1) + 1e-300)
|
| 566 |
-
ci_lo = -np.log10(stats.beta.ppf(0.975, ranks, ranks[::-1] + 1) + 1e-300)
|
| 567 |
-
ci_hi = ci_hi[sort_idx]; ci_lo = ci_lo[sort_idx]
|
| 568 |
-
ax.fill_between(exp_log, ci_lo, ci_hi,
|
| 569 |
-
color=mcol, alpha=0.15, zorder=1, label='95% CI')
|
| 570 |
-
|
| 571 |
-
above = obs_log >= bonf_log
|
| 572 |
-
if (~above).any():
|
| 573 |
-
ax.scatter(exp_log[~above], obs_log[~above],
|
| 574 |
-
c=mcol, s=16, alpha=0.70, linewidths=0,
|
| 575 |
-
zorder=2, label='p > Bonferroni')
|
| 576 |
-
if above.any():
|
| 577 |
-
ax.scatter(exp_log[above], obs_log[above],
|
| 578 |
-
c=W_RED, s=25, alpha=1.0, linewidths=0.5,
|
| 579 |
-
edgecolors='#8B0000', marker='D', zorder=3, label='p < Bonferroni')
|
| 580 |
-
|
| 581 |
-
maxv = max(obs_log.max(), exp_log.max()) * 1.06
|
| 582 |
-
ax.plot([0, maxv], [0, maxv], color=W_TEXT, lw=1.8, ls='--',
|
| 583 |
-
alpha=0.85, zorder=4, label='y = x (null)')
|
| 584 |
-
ax.axhline(bonf_log, color=W_RED, ls=':', lw=1.4, alpha=0.8,
|
| 585 |
-
zorder=5, label=f'Bonferroni ({bonf_log:.2f})')
|
| 586 |
-
|
| 587 |
-
chi2_obs = stats.chi2.ppf(1 - pv, df=1)
|
| 588 |
-
chi2_obs = chi2_obs[np.isfinite(chi2_obs) & (chi2_obs > 0)]
|
| 589 |
-
lam = (np.median(chi2_obs) / stats.chi2.ppf(0.5, df=1)) if len(chi2_obs) else 1.0
|
| 590 |
-
|
| 591 |
-
lam_color = W_RED if lam > 1.10 else W_GOLD if lam > 1.05 else W_GREEN
|
| 592 |
-
ax.text(0.04, 0.96, f'λ = {lam:.4f}',
|
| 593 |
-
transform=ax.transAxes, fontsize=16, fontweight='bold',
|
| 594 |
-
color=lam_color, va='top',
|
| 595 |
-
bbox=dict(boxstyle='round,pad=0.5', fc=W_BG, ec=lam_color, alpha=0.95, lw=1.5))
|
| 596 |
-
|
| 597 |
-
inflation_note = ("✅ No inflation" if lam < 1.05
|
| 598 |
-
else "⚠️ Mild inflation" if lam < 1.10
|
| 599 |
-
else "❌ Significant inflation")
|
| 600 |
-
ax.text(0.04, 0.87, inflation_note,
|
| 601 |
-
transform=ax.transAxes, fontsize=10, color=lam_color, va='top')
|
| 602 |
-
|
| 603 |
-
ax.set_xlim(0, maxv); ax.set_ylim(0, maxv)
|
| 604 |
-
ax.set_xlabel('Expected −log₁₀(P)', fontweight='bold', fontsize=12)
|
| 605 |
-
ax.set_ylabel('Observed −log₁₀(P)', fontweight='bold', fontsize=12)
|
| 606 |
-
ax.legend(fontsize=9, loc='upper left', bbox_to_anchor=(0.0, 0.82))
|
| 607 |
-
ax.grid(True, color=W_GRID, lw=0.6, alpha=0.7)
|
| 608 |
-
ax.text(0.98, 0.04, f'n = {n:,} markers',
|
| 609 |
-
transform=ax.transAxes, ha='right', fontsize=9, color=W_SUBTEXT)
|
| 610 |
-
|
| 611 |
-
plt.tight_layout()
|
| 612 |
-
plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=W_BG)
|
| 613 |
-
plt.close(fig)
|
| 614 |
-
return lam
|
| 615 |
-
|
| 616 |
-
|
| 617 |
-
# ══════════════════════════════════════════════════════════════
|
| 618 |
-
# PLOT 5: LD DECAY — CORRECTED
|
| 619 |
-
# Uses Hill (1975) nonlinear model: E(r²) = f(c, n)
|
| 620 |
-
# Proper per-chromosome r² from raw genotype dosages
|
| 621 |
-
# ══════════════════════════════════════════════════════════════
|
| 622 |
-
def _r2_from_dosage(xi, xj):
|
| 623 |
-
"""
|
| 624 |
-
Compute r² (squared Pearson correlation of dosage vectors).
|
| 625 |
-
xi, xj: 1-D float arrays of dosage (0/1/2), NaN-free.
|
| 626 |
-
"""
|
| 627 |
-
n = len(xi)
|
| 628 |
-
if n < 4:
|
| 629 |
-
return 0.0
|
| 630 |
-
mi = xi.mean(); mj = xj.mean()
|
| 631 |
-
di = xi - mi; dj = xj - mj
|
| 632 |
-
cov = (di * dj).mean()
|
| 633 |
-
vi = (di * di).mean(); vj = (dj * dj).mean()
|
| 634 |
-
if vi < 1e-12 or vj < 1e-12:
|
| 635 |
-
return 0.0
|
| 636 |
-
r = cov / np.sqrt(vi * vj)
|
| 637 |
-
return float(np.clip(r**2, 0.0, 1.0))
|
| 638 |
-
|
| 639 |
-
|
| 640 |
-
def _hill1975(d, n, c=1.0):
|
| 641 |
-
"""
|
| 642 |
-
Expected r² under Hill & Weir (1988) approximation.
|
| 643 |
-
E(r²) ≈ (1/(n·c·d+1)) · [1 + (c·d)²·... ] simplified form.
|
| 644 |
-
Practical approximation used in PopLDdecay / Haploview:
|
| 645 |
-
E(r²) = 1 / (1 + 4·N·c·d) [c absorbed into scale parameter]
|
| 646 |
-
We fit: E(r²) = (1 + a·d)^{-1} + b (plateau b ≥ 0)
|
| 647 |
-
"""
|
| 648 |
-
a, b = c, 0.0 # initial; curve_fit will optimise
|
| 649 |
-
return 1.0 / (1.0 + a * d) + b
|
| 650 |
-
|
| 651 |
-
|
| 652 |
-
def _ld_decay_model(d, a, b):
|
| 653 |
-
"""Hill model: r² = 1/(1 + a·d) + b. a > 0, b ≥ 0."""
|
| 654 |
-
with np.errstate(all='ignore'):
|
| 655 |
-
return np.clip(1.0 / (1.0 + np.maximum(a, 1e-10) * d) + b, 0.0, 1.0)
|
| 656 |
-
|
| 657 |
-
|
| 658 |
-
def compute_ld_chromosome(G_ch, bp_ch, max_lag=100):
|
| 659 |
-
"""
|
| 660 |
-
Compute pairwise r² for one chromosome.
|
| 661 |
-
Returns (dist_bp, r2_values) arrays.
|
| 662 |
-
"""
|
| 663 |
-
m = G_ch.shape[1]
|
| 664 |
-
# Fill NaN with column mean for LD computation only
|
| 665 |
-
Gf = G_ch.copy().astype(float)
|
| 666 |
-
for j in range(m):
|
| 667 |
-
col = Gf[:, j]
|
| 668 |
-
nanm = np.isnan(col)
|
| 669 |
-
if nanm.any():
|
| 670 |
-
col[nanm] = np.nanmean(col) if not np.all(nanm) else 0.0
|
| 671 |
-
Gf[:, j] = col
|
| 672 |
-
|
| 673 |
-
ii, jj = np.triu_indices(m, k=1)
|
| 674 |
-
lag = jj - ii
|
| 675 |
-
keep = lag <= max_lag
|
| 676 |
-
ii, jj = ii[keep], jj[keep]
|
| 677 |
-
|
| 678 |
-
dist = np.abs(bp_ch[jj] - bp_ch[ii]).astype(float)
|
| 679 |
-
r2 = np.zeros(len(ii), dtype=float)
|
| 680 |
-
for k in range(len(ii)):
|
| 681 |
-
r2[k] = _r2_from_dosage(Gf[:, ii[k]], Gf[:, jj[k]])
|
| 682 |
-
return dist, r2
|
| 683 |
-
|
| 684 |
-
|
| 685 |
-
def plot_ld_decay(genotypes, chromosomes, positions, save_path, max_m=60):
|
| 686 |
-
_style_white()
|
| 687 |
-
|
| 688 |
-
unique_chroms = sorted(set(chromosomes),
|
| 689 |
-
key=lambda x: (int(x) if str(x).isdigit() else 999, str(x)))
|
| 690 |
-
chrom_to_idx = {}
|
| 691 |
-
for gi, ch in enumerate(chromosomes):
|
| 692 |
-
chrom_to_idx.setdefault(str(ch), []).append(gi)
|
| 693 |
-
|
| 694 |
-
bp_arr = np.array(positions, dtype=float)
|
| 695 |
-
if bp_arr.max() < 1:
|
| 696 |
-
bp_arr = np.arange(len(positions), dtype=float) * 1000
|
| 697 |
-
|
| 698 |
-
all_dist, all_r2, all_ch = [], [], []
|
| 699 |
-
chrom_stats = {}
|
| 700 |
-
rng = np.random.default_rng(42)
|
| 701 |
-
|
| 702 |
-
for ch in unique_chroms:
|
| 703 |
-
idxs = chrom_to_idx.get(str(ch), [])
|
| 704 |
-
if len(idxs) < 4:
|
| 705 |
-
continue
|
| 706 |
-
if len(idxs) > max_m:
|
| 707 |
-
idxs = sorted(rng.choice(idxs, max_m, replace=False).tolist())
|
| 708 |
-
G_ch = genotypes[:, idxs].copy().astype(float)
|
| 709 |
-
bp_ch = bp_arr[idxs]
|
| 710 |
-
srt = np.argsort(bp_ch)
|
| 711 |
-
G_ch = G_ch[:, srt]; bp_ch = bp_ch[srt]
|
| 712 |
-
dist, r2 = compute_ld_chromosome(G_ch, bp_ch, max_lag=60)
|
| 713 |
-
if len(dist) == 0:
|
| 714 |
-
continue
|
| 715 |
-
all_dist.extend(dist.tolist()); all_r2.extend(r2.tolist())
|
| 716 |
-
all_ch.extend([str(ch)] * len(dist))
|
| 717 |
-
chrom_stats[str(ch)] = {
|
| 718 |
-
'n_markers': len(idxs), 'n_pairs': len(dist),
|
| 719 |
-
'mean_r2': float(np.mean(r2)), 'max_r2': float(np.max(r2)),
|
| 720 |
-
'max_dist': float(dist.max()) if len(dist) else 0,
|
| 721 |
-
}
|
| 722 |
-
|
| 723 |
-
if not all_dist:
|
| 724 |
-
fig, ax = plt.subplots(figsize=(10, 6), facecolor=W_BG)
|
| 725 |
-
ax.set_facecolor(W_PANEL)
|
| 726 |
-
ax.text(0.5, 0.5, 'No LD data (need ≥4 markers per chr)',
|
| 727 |
-
ha='center', va='center', transform=ax.transAxes, fontsize=13)
|
| 728 |
-
plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=W_BG)
|
| 729 |
-
plt.close(fig)
|
| 730 |
-
return chrom_stats, "No LD data available."
|
| 731 |
-
|
| 732 |
-
dist_arr = np.array(all_dist, dtype=float)
|
| 733 |
-
r2_arr = np.array(all_r2, dtype=float)
|
| 734 |
-
ch_arr = np.array(all_ch, dtype=str)
|
| 735 |
-
|
| 736 |
-
# Scale selection
|
| 737 |
-
p99 = float(np.percentile(dist_arr, 99)) or dist_arr.max()
|
| 738 |
-
if p99 >= 1_000_000:
|
| 739 |
-
scale, unit_label = 1_000_000, 'Mb'
|
| 740 |
-
elif p99 >= 1_000:
|
| 741 |
-
scale, unit_label = 1_000, 'kb'
|
| 742 |
-
else:
|
| 743 |
-
scale, unit_label = 1, 'bp'
|
| 744 |
-
|
| 745 |
-
dist_s = dist_arr / scale
|
| 746 |
-
max_s = p99 / scale
|
| 747 |
-
mask = dist_arr <= p99
|
| 748 |
-
dv, rv = dist_s[mask], r2_arr[mask]
|
| 749 |
-
|
| 750 |
-
# ── Hill model fitting ────────────────────────────────────────────
|
| 751 |
-
# Bin data for robust fitting
|
| 752 |
-
n_bins = 80
|
| 753 |
-
bins = np.linspace(0, max_s, n_bins + 1)
|
| 754 |
-
ctrs, meds, q25, q75 = [], [], [], []
|
| 755 |
-
for i in range(n_bins):
|
| 756 |
-
m = (dv >= bins[i]) & (dv < bins[i + 1])
|
| 757 |
-
if m.sum() >= 3:
|
| 758 |
-
ctrs.append((bins[i] + bins[i + 1]) / 2.)
|
| 759 |
-
meds.append(np.median(rv[m]))
|
| 760 |
-
q25.append(np.percentile(rv[m], 25))
|
| 761 |
-
q75.append(np.percentile(rv[m], 75))
|
| 762 |
-
ctrs = np.array(ctrs); meds = np.array(meds)
|
| 763 |
-
q25 = np.array(q25); q75 = np.array(q75)
|
| 764 |
-
|
| 765 |
-
# Fit Hill model to binned medians
|
| 766 |
-
fit_ok = False; a_fit = 1.0; b_fit = 0.0
|
| 767 |
-
xs_fit = ys_fit = None
|
| 768 |
-
ann = {}
|
| 769 |
-
if len(ctrs) >= 5:
|
| 770 |
-
try:
|
| 771 |
-
p0 = [1.0 / (max_s + 0.1), 0.05]
|
| 772 |
-
bounds = ([0, 0], [1e6, 0.5])
|
| 773 |
-
popt, _ = curve_fit(_ld_decay_model, ctrs, meds,
|
| 774 |
-
p0=p0, bounds=bounds, maxfev=5000)
|
| 775 |
-
a_fit, b_fit = popt
|
| 776 |
-
fit_ok = True
|
| 777 |
-
xs_fit = np.linspace(0, max_s, 2000)
|
| 778 |
-
ys_fit = _ld_decay_model(xs_fit, a_fit, b_fit)
|
| 779 |
-
# Find decay distances
|
| 780 |
-
r2_start = float(_ld_decay_model(0, a_fit, b_fit))
|
| 781 |
-
for thr_name, thr_val in [('half', r2_start / 2.), ('r2_02', 0.2), ('r2_01', 0.1)]:
|
| 782 |
-
ix = np.where(ys_fit <= thr_val)[0]
|
| 783 |
-
if len(ix):
|
| 784 |
-
ann[thr_name] = float(xs_fit[ix[0]])
|
| 785 |
-
except Exception:
|
| 786 |
-
# Fall back to smoothing spline
|
| 787 |
-
if len(ctrs) >= 5:
|
| 788 |
-
k = min(3, len(ctrs) - 1)
|
| 789 |
-
xs_fit = np.linspace(ctrs[0], ctrs[-1], 2000)
|
| 790 |
-
spl = make_interp_spline(ctrs, meds, k=k)
|
| 791 |
-
ys_fit = np.clip(spl(xs_fit), 0, 1)
|
| 792 |
-
r2_start = ys_fit[0] if ys_fit[0] > 0 else (meds[0] if len(meds) else 0.5)
|
| 793 |
-
for thr_name, thr_val in [('half', r2_start / 2.), ('r2_02', 0.2), ('r2_01', 0.1)]:
|
| 794 |
-
ix = np.where(ys_fit <= thr_val)[0]
|
| 795 |
-
if len(ix):
|
| 796 |
-
ann[thr_name] = float(xs_fit[ix[0]])
|
| 797 |
-
|
| 798 |
-
def _fmt(v):
|
| 799 |
-
return f"{v:.3f} {unit_label}"
|
| 800 |
-
|
| 801 |
-
ilines = []
|
| 802 |
-
model_desc = f"Hill (1975) model: r²=1/(1+{a_fit:.4f}·d)+{b_fit:.4f}" if fit_ok else "Spline smoothing"
|
| 803 |
-
ilines.append(f"• Decay model: {model_desc}")
|
| 804 |
-
if 'half' in ann:
|
| 805 |
-
speed = "rapid" if ann['half'] < 0.5 else "moderate" if ann['half'] < 5 else "slow"
|
| 806 |
-
ilines.append(f"• LD half-decay distance: {_fmt(ann['half'])} [{speed} decay]")
|
| 807 |
-
if 'r2_02' in ann:
|
| 808 |
-
ilines.append(f"• r²<0.2 (GWAS tagging threshold): {_fmt(ann['r2_02'])}")
|
| 809 |
-
if 'r2_01' in ann:
|
| 810 |
-
ilines.append(f"• r²<0.1 (near-independence): {_fmt(ann['r2_01'])}")
|
| 811 |
-
ilines.append(f"• Overall mean r² = {np.mean(r2_arr):.4f}")
|
| 812 |
-
ilines.append(f"• Total pairs analysed: {len(r2_arr):,}")
|
| 813 |
-
ld_interp = "\n".join(ilines)
|
| 814 |
-
|
| 815 |
-
chrom_color = {
|
| 816 |
-
str(ch): CHROM_COLORS[i % len(CHROM_COLORS)]
|
| 817 |
-
for i, ch in enumerate(unique_chroms)
|
| 818 |
-
}
|
| 819 |
-
|
| 820 |
-
# ── FIGURE ────────────────────────────────────────────────────────
|
| 821 |
-
fig = plt.figure(figsize=(13, 9), facecolor=W_BG)
|
| 822 |
-
gs = GridSpec(2, 1, figure=fig, height_ratios=[4.0, 0.9], hspace=0.05)
|
| 823 |
-
ax = fig.add_subplot(gs[0])
|
| 824 |
-
axt = fig.add_subplot(gs[1])
|
| 825 |
-
axt.axis('off')
|
| 826 |
-
|
| 827 |
-
ax.set_facecolor(W_BG)
|
| 828 |
-
for sp in ['top', 'right']:
|
| 829 |
-
ax.spines[sp].set_visible(False)
|
| 830 |
-
ax.spines['left'].set_color(W_BORDER)
|
| 831 |
-
ax.spines['bottom'].set_color(W_BORDER)
|
| 832 |
-
|
| 833 |
-
# Scatter — per-chromosome colour
|
| 834 |
-
MAX_SCATTER = 12_000
|
| 835 |
-
total_vis = int(mask.sum())
|
| 836 |
-
ds_rate = max(1, total_vis // MAX_SCATTER)
|
| 837 |
-
|
| 838 |
-
for ch in unique_chroms:
|
| 839 |
-
key = str(ch)
|
| 840 |
-
idxs = np.where((ch_arr == key) & mask)[0]
|
| 841 |
-
if not len(idxs):
|
| 842 |
-
continue
|
| 843 |
-
pts = idxs[::ds_rate]
|
| 844 |
-
ax.scatter(dist_s[pts], r2_arr[pts],
|
| 845 |
-
c=chrom_color[key], s=5, alpha=0.45,
|
| 846 |
-
linewidths=0, zorder=2, label=key)
|
| 847 |
-
|
| 848 |
-
# IQR shaded band
|
| 849 |
-
if len(ctrs) >= 3:
|
| 850 |
-
ax.fill_between(ctrs, q25, q75,
|
| 851 |
-
color='#2E7D32', alpha=0.12, zorder=3, label='IQR band')
|
| 852 |
-
|
| 853 |
-
# Fitted curve
|
| 854 |
-
if xs_fit is not None:
|
| 855 |
-
lbl = f"{'Hill model' if fit_ok else 'Median curve'}"
|
| 856 |
-
ax.plot(xs_fit, ys_fit, color='#2E7D32', lw=2.5,
|
| 857 |
-
zorder=5, label=lbl, solid_capstyle='round')
|
| 858 |
-
|
| 859 |
-
# r²=0.2 reference line (black dashed)
|
| 860 |
-
ax.axhline(0.2, color='black', ls='--', lw=1.6, alpha=0.75,
|
| 861 |
-
zorder=4, label='r² = 0.2')
|
| 862 |
-
ax.axhline(0.1, color='#555555', ls=':', lw=1.2, alpha=0.60,
|
| 863 |
-
zorder=4, label='r² = 0.1')
|
| 864 |
-
|
| 865 |
-
# Annotation vertical lines
|
| 866 |
-
ann_cfg = {
|
| 867 |
-
'half': ('#E65100', '½ decay'),
|
| 868 |
-
'r2_02': ('#C62828', 'r²=0.2'),
|
| 869 |
-
'r2_01': ('#6A1B9A', 'r²=0.1'),
|
| 870 |
-
}
|
| 871 |
-
for akey, (col, lbl) in ann_cfg.items():
|
| 872 |
-
if akey not in ann:
|
| 873 |
-
continue
|
| 874 |
-
xv = ann[akey]
|
| 875 |
-
ax.axvline(xv, color=col, ls=':', lw=1.5, alpha=0.75, zorder=6)
|
| 876 |
-
ax.text(xv, 0.97, f'{lbl}\n{_fmt(xv)}',
|
| 877 |
-
ha='center', va='top', fontsize=8, fontweight='bold',
|
| 878 |
-
color=col, transform=ax.get_xaxis_transform(),
|
| 879 |
-
bbox=dict(boxstyle='round,pad=0.3', fc=W_BG, ec=col, alpha=0.90, lw=1.0))
|
| 880 |
-
|
| 881 |
-
ax.set_xlim(0, max_s)
|
| 882 |
-
ax.set_ylim(-0.02, 1.06)
|
| 883 |
-
ax.set_xlabel(f'Physical distance ({unit_label})', fontweight='bold', fontsize=12)
|
| 884 |
-
ax.set_ylabel('LD estimate (r²)', fontweight='bold', fontsize=12)
|
| 885 |
-
ax.set_title('Linkage Disequilibrium Decay by Chromosome',
|
| 886 |
-
fontweight='bold', fontsize=14, color=W_ACCENT, pad=10)
|
| 887 |
-
ax.xaxis.grid(True, color=W_GRID, lw=0.5, alpha=0.7)
|
| 888 |
-
ax.yaxis.grid(True, color=W_GRID, lw=0.5, alpha=0.7)
|
| 889 |
-
ax.tick_params(colors=W_TEXT, which='both')
|
| 890 |
-
|
| 891 |
-
# Legend — chromosomes in columns
|
| 892 |
-
handles, labels = ax.get_legend_handles_labels()
|
| 893 |
-
special = [(h, l) for h, l in zip(handles, labels)
|
| 894 |
-
if l not in [str(c) for c in unique_chroms]]
|
| 895 |
-
chrs = [(h, l) for h, l in zip(handles, labels)
|
| 896 |
-
if l in [str(c) for c in unique_chroms]]
|
| 897 |
-
ncols_l = max(2, (len(chrs) + 9) // 10)
|
| 898 |
-
leg_h = [h for h, _ in special] + [h for h, _ in chrs]
|
| 899 |
-
leg_l = [l for _, l in special] + [f'Chr {l}' for _, l in chrs]
|
| 900 |
-
ax.legend(leg_h, leg_l, title='Legend', title_fontsize=8,
|
| 901 |
-
fontsize=7.5, loc='upper right', ncol=max(2, ncols_l),
|
| 902 |
-
framealpha=0.95, markerscale=2.0)
|
| 903 |
-
|
| 904 |
-
# Interpretation panel
|
| 905 |
-
axt.text(0.005, 0.97,
|
| 906 |
-
"LD DECAY INTERPRETATION\n" + "─" * 72 + "\n" + ld_interp,
|
| 907 |
-
transform=axt.transAxes, va='top', ha='left',
|
| 908 |
-
fontsize=8.5, color=W_TEXT, fontfamily='monospace',
|
| 909 |
-
bbox=dict(boxstyle='round,pad=0.5', facecolor=W_PANEL,
|
| 910 |
-
edgecolor=W_BORDER, alpha=0.98))
|
| 911 |
-
|
| 912 |
-
plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=W_BG)
|
| 913 |
-
plt.close(fig)
|
| 914 |
-
return chrom_stats, ld_interp
|
| 915 |
-
|
| 916 |
-
|
| 917 |
-
# ══════════════════════════════════════════════════════════════
|
| 918 |
-
# PLOT 6: MODEL COMPARISON — white
|
| 919 |
-
# ══════════════════════════════════════════════════════════════
|
| 920 |
-
def plot_model_comparison(model_pvals, save_path):
|
| 921 |
-
_style_white()
|
| 922 |
-
models = list(model_pvals.keys()); n = len(models)
|
| 923 |
-
pairs = [(models[i], models[j]) for i in range(n) for j in range(i+1, n)]
|
| 924 |
-
if not pairs:
|
| 925 |
-
return
|
| 926 |
-
ncols = min(3, len(pairs)); nrows = (len(pairs) + ncols - 1) // ncols
|
| 927 |
-
fig, axes = plt.subplots(nrows, ncols, figsize=(6 * ncols, 5.5 * nrows),
|
| 928 |
-
facecolor=W_BG, squeeze=False)
|
| 929 |
-
fig.suptitle('Model P-value Concordance', fontsize=14, fontweight='bold',
|
| 930 |
-
color=W_TEXT, y=1.01)
|
| 931 |
-
for idx, (ma, mb) in enumerate(pairs):
|
| 932 |
-
r, c = divmod(idx, ncols); ax = axes[r][c]; ax.set_facecolor(W_PANEL)
|
| 933 |
-
pa = -np.log10(np.clip(model_pvals[ma], 1e-300, 1))
|
| 934 |
-
pb = -np.log10(np.clip(model_pvals[mb], 1e-300, 1))
|
| 935 |
-
corr = np.corrcoef(pa, pb)[0, 1]
|
| 936 |
-
ax.scatter(pa, pb, alpha=0.45, s=12,
|
| 937 |
-
color=MODEL_COLORS.get(ma, W_ACCENT), edgecolors='none', zorder=2)
|
| 938 |
-
mx = max(pa.max(), pb.max()) * 1.05
|
| 939 |
-
ax.plot([0, mx], [0, mx], color=W_GOLD, ls='--', lw=1.5, zorder=3, label='y=x')
|
| 940 |
-
ax.set_xlabel(f'{ma} −log₁₀(P)', fontweight='bold', fontsize=10)
|
| 941 |
-
ax.set_ylabel(f'{mb} −log₁₀(P)', fontweight='bold', fontsize=10)
|
| 942 |
-
ax.set_title(f'{ma} vs {mb}', fontweight='bold',
|
| 943 |
-
color=MODEL_COLORS.get(ma, W_ACCENT), fontsize=11)
|
| 944 |
-
ax.text(0.04, 0.96, f'r = {corr:.3f}', transform=ax.transAxes,
|
| 945 |
-
fontsize=12, fontweight='bold', color=W_RED, va='top')
|
| 946 |
-
ax.grid(True, color=W_GRID, lw=0.6, alpha=0.6); ax.legend(fontsize=8)
|
| 947 |
-
for extra in range(len(pairs), nrows * ncols):
|
| 948 |
-
r, c = divmod(extra, ncols); axes[r][c].set_visible(False)
|
| 949 |
-
plt.tight_layout(pad=1.5)
|
| 950 |
-
plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=W_BG)
|
| 951 |
-
plt.close(fig)
|
| 952 |
-
|
| 953 |
-
|
| 954 |
-
# ══════════════════════════════════════════════════════════════
|
| 955 |
-
# PLOT 7: CIRCOS — IMPROVED bioinformatics style, white bg
|
| 956 |
-
# Concentric ring tracks, each model its own ring with
|
| 957 |
-
# proper radial bar heights, colour-coded sig loci,
|
| 958 |
-
# chromosome labels, MTA consensus diamonds in hub
|
| 959 |
-
# ══════════════════════════════════════════════════════════════
|
| 960 |
-
def plot_circos(mn_q, ch_q, pos_q, model_pvals, bonf_thresh, lod_thresh_user, save_path):
|
| 961 |
-
_style_white()
|
| 962 |
-
|
| 963 |
-
unique_chroms = sorted(set(ch_q),
|
| 964 |
-
key=lambda x: (int(x) if str(x).isdigit() else 999, str(x)))
|
| 965 |
-
chrom_to_idx = {}
|
| 966 |
-
for i, c in enumerate(ch_q):
|
| 967 |
-
chrom_to_idx.setdefault(c, []).append(i)
|
| 968 |
-
n_chr = len(unique_chroms)
|
| 969 |
-
|
| 970 |
-
# Angular allocation proportional to marker count
|
| 971 |
-
chr_len = {ch: len(chrom_to_idx[ch]) for ch in unique_chroms}
|
| 972 |
-
total_m = sum(chr_len.values())
|
| 973 |
-
GAP_DEG = max(1.0, 360. / (n_chr * 12))
|
| 974 |
-
avail_deg = 360. - GAP_DEG * n_chr
|
| 975 |
-
chr_deg = {ch: (chr_len[ch] / total_m) * avail_deg for ch in unique_chroms}
|
| 976 |
-
|
| 977 |
-
marker_angle = np.zeros(len(mn_q))
|
| 978 |
-
chr_start_deg = {}
|
| 979 |
-
cur = 0.0
|
| 980 |
-
for ch in unique_chroms:
|
| 981 |
-
chr_start_deg[ch] = cur
|
| 982 |
-
idxs = chrom_to_idx[ch]
|
| 983 |
-
for rank, idx in enumerate(idxs):
|
| 984 |
-
marker_angle[idx] = cur + (rank / max(len(idxs) - 1, 1)) * chr_deg[ch]
|
| 985 |
-
cur += chr_deg[ch] + GAP_DEG
|
| 986 |
-
|
| 987 |
-
models = list(model_pvals.keys())
|
| 988 |
-
n_models = len(models)
|
| 989 |
-
bonf_log = -np.log10(bonf_thresh)
|
| 990 |
-
|
| 991 |
-
# Radii geometry — allocate equal track width per model
|
| 992 |
-
R_CHR_O = 0.975
|
| 993 |
-
R_CHR_I = 0.895
|
| 994 |
-
TRACK_W = min(0.080, (R_CHR_I - 0.20) / max(n_models, 1))
|
| 995 |
-
R_HUB = 0.20
|
| 996 |
-
|
| 997 |
-
# Precompute significant sets and consensus
|
| 998 |
-
sig_per_model = {
|
| 999 |
-
mn: set(np.where(pv < bonf_thresh)[0])
|
| 1000 |
-
for mn, pv in model_pvals.items()
|
| 1001 |
-
}
|
| 1002 |
-
consensus_threshold = max(1, int(np.ceil(n_models / 2)))
|
| 1003 |
-
sig_counts = np.zeros(len(mn_q), dtype=int)
|
| 1004 |
-
for mn_k in models:
|
| 1005 |
-
for idx in sig_per_model[mn_k]:
|
| 1006 |
-
sig_counts[idx] += 1
|
| 1007 |
-
consensus_idx = set(np.where(sig_counts >= consensus_threshold)[0])
|
| 1008 |
-
|
| 1009 |
-
fig = plt.figure(figsize=(15, 15), facecolor=W_BG)
|
| 1010 |
-
ax = fig.add_axes([0.04, 0.09, 0.92, 0.87], projection='polar')
|
| 1011 |
-
ax.set_facecolor(W_BG)
|
| 1012 |
-
ax.set_theta_zero_location('N')
|
| 1013 |
-
ax.set_theta_direction(-1)
|
| 1014 |
-
ax.set_ylim(0, 1.08)
|
| 1015 |
-
ax.axis('off')
|
| 1016 |
-
|
| 1017 |
-
theta_full = np.linspace(0, 2 * np.pi, 1000)
|
| 1018 |
-
|
| 1019 |
-
# ── 1. Light fill for the entire track region ───────────────────
|
| 1020 |
-
r_track_outer = R_CHR_I - 0.008
|
| 1021 |
-
r_track_inner = r_track_outer - n_models * TRACK_W
|
| 1022 |
-
ax.fill_between(theta_full, r_track_inner, r_track_outer,
|
| 1023 |
-
color='#E8F5E9', alpha=0.50, zorder=1)
|
| 1024 |
-
|
| 1025 |
-
# ── 2. Chromosome arcs ──────────────────────────────────────────
|
| 1026 |
-
for ci, ch in enumerate(unique_chroms):
|
| 1027 |
-
s_deg = chr_start_deg[ch]; e_deg = s_deg + chr_deg[ch]
|
| 1028 |
-
s_rad = np.deg2rad(s_deg); e_rad = np.deg2rad(e_deg)
|
| 1029 |
-
theta_arc = np.linspace(s_rad, e_rad, max(30, int(chr_deg[ch] * 5)))
|
| 1030 |
-
col = CHROM_COLORS[ci % len(CHROM_COLORS)]
|
| 1031 |
-
|
| 1032 |
-
ax.fill_between(theta_arc, R_CHR_I, R_CHR_O, color=col, alpha=0.85, zorder=3)
|
| 1033 |
-
ax.plot([s_rad, s_rad], [R_CHR_I, R_CHR_O], color='white', lw=2.2, zorder=4)
|
| 1034 |
-
ax.plot([e_rad, e_rad], [R_CHR_I, R_CHR_O], color='white', lw=2.2, zorder=4)
|
| 1035 |
-
ax.plot(theta_arc, [R_CHR_O] * len(theta_arc), color='white', lw=0.8, zorder=4)
|
| 1036 |
-
ax.plot(theta_arc, [R_CHR_I] * len(theta_arc), color='white', lw=0.5, zorder=4)
|
| 1037 |
-
|
| 1038 |
-
mid_rad = np.deg2rad((s_deg + e_deg) / 2.)
|
| 1039 |
-
label_r = R_CHR_O + 0.035
|
| 1040 |
-
rot_angle = np.rad2deg(mid_rad)
|
| 1041 |
-
if np.pi / 2 < mid_rad < 3 * np.pi / 2:
|
| 1042 |
-
rot_angle += 180
|
| 1043 |
-
ax.text(mid_rad, label_r, str(ch),
|
| 1044 |
-
ha='center', va='center', fontsize=8, fontweight='bold',
|
| 1045 |
-
color=W_TEXT, zorder=6, rotation=rot_angle - 90)
|
| 1046 |
-
|
| 1047 |
-
# ── 3. Model tracks (outer → inner) ────────────────────────────
|
| 1048 |
-
for mi, mname in enumerate(models):
|
| 1049 |
-
pv = model_pvals[mname]
|
| 1050 |
-
log_p = -np.log10(np.clip(pv, 1e-300, 1))
|
| 1051 |
-
mcol = MODEL_COLORS.get(mname, W_ACCENT)
|
| 1052 |
-
|
| 1053 |
-
r_out = r_track_outer - mi * TRACK_W
|
| 1054 |
-
r_in = r_out - TRACK_W + 0.004
|
| 1055 |
-
|
| 1056 |
-
# Track boundary ring
|
| 1057 |
-
ax.plot(theta_full, [r_out] * 1000, color=W_BORDER, lw=0.8, alpha=0.6, zorder=2)
|
| 1058 |
-
ax.plot(theta_full, [r_in] * 1000, color=W_BORDER, lw=0.5, alpha=0.4, zorder=2)
|
| 1059 |
-
|
| 1060 |
-
lp_max = max(bonf_log * 1.5, float(log_p.max()), 1.0)
|
| 1061 |
-
norm_h = (log_p / lp_max) * TRACK_W * 0.9 # 90% fill
|
| 1062 |
-
|
| 1063 |
-
# Bonferroni arc inside track
|
| 1064 |
-
bonf_r = r_in + (bonf_log / lp_max) * TRACK_W * 0.9
|
| 1065 |
-
ax.plot(theta_full, [bonf_r] * 1000,
|
| 1066 |
-
color=W_RED, lw=0.9, ls='--', alpha=0.45, zorder=3)
|
| 1067 |
-
|
| 1068 |
-
# Batch non-significant bars (thin, model colour)
|
| 1069 |
-
non_sig_idx = [i for i in range(len(mn_q)) if i not in sig_per_model[mname]]
|
| 1070 |
-
for idx in non_sig_idx:
|
| 1071 |
-
theta = np.deg2rad(marker_angle[idx])
|
| 1072 |
-
r_top = min(r_in + norm_h[idx], r_out - 0.002)
|
| 1073 |
-
if norm_h[idx] > 0.001:
|
| 1074 |
-
ax.plot([theta, theta], [r_in, r_top],
|
| 1075 |
-
color=mcol, lw=0.35, alpha=0.28, zorder=3)
|
| 1076 |
-
|
| 1077 |
-
# Significant: thick coloured bars + dot
|
| 1078 |
-
for idx in sig_per_model[mname]:
|
| 1079 |
-
theta = np.deg2rad(marker_angle[idx])
|
| 1080 |
-
r_top = min(r_in + norm_h[idx], r_out - 0.002)
|
| 1081 |
-
ax.plot([theta, theta], [r_in, r_top],
|
| 1082 |
-
color=mcol, lw=2.2, alpha=1.0, zorder=5,
|
| 1083 |
-
solid_capstyle='round')
|
| 1084 |
-
ax.scatter(theta, r_top, s=18, c=mcol, alpha=1.0,
|
| 1085 |
-
edgecolors='white', lw=0.6, zorder=6)
|
| 1086 |
-
|
| 1087 |
-
# Model label
|
| 1088 |
-
ax.text(np.deg2rad(2.0), (r_in + r_out) / 2., mname,
|
| 1089 |
-
ha='left', va='center', fontsize=8, fontweight='bold',
|
| 1090 |
-
color=mcol, zorder=8)
|
| 1091 |
-
|
| 1092 |
-
# ── 4. Consensus MTA: red diamonds in hub ───────────────────────
|
| 1093 |
-
for idx in consensus_idx:
|
| 1094 |
-
theta = np.deg2rad(marker_angle[idx])
|
| 1095 |
-
n_sig = sig_counts[idx]
|
| 1096 |
-
hub_r = R_HUB * 0.6 + (n_sig / max(n_models, 1)) * R_HUB * 0.35
|
| 1097 |
-
ax.scatter(theta, hub_r, s=90, c=W_RED, alpha=0.95,
|
| 1098 |
-
edgecolors='white', lw=0.9, marker='D', zorder=8)
|
| 1099 |
-
|
| 1100 |
-
# ── 5. Inner white hub ──────────────────────────────────────────
|
| 1101 |
-
ax.fill_between(theta_full, 0, R_HUB * 0.55,
|
| 1102 |
-
color=W_BG, alpha=1.0, zorder=2)
|
| 1103 |
-
ax.plot(theta_full, [R_HUB * 0.55] * 1000,
|
| 1104 |
-
color=W_BORDER, lw=1.0, alpha=0.5, zorder=3)
|
| 1105 |
-
|
| 1106 |
-
# ── 6. Track outer boundary ─────────────────────────────────────
|
| 1107 |
-
ax.plot(theta_full, [r_track_inner] * 1000,
|
| 1108 |
-
color='#777777', lw=1.2, alpha=0.7, zorder=4)
|
| 1109 |
-
|
| 1110 |
-
# ── 7. Centre text ──────────────────────────────────────────────
|
| 1111 |
-
n_consensus = len(consensus_idx)
|
| 1112 |
-
n_total_sig = sum(len(v) for v in sig_per_model.values())
|
| 1113 |
-
ax.text(0, 0, f'{n_consensus}\nMTA',
|
| 1114 |
-
ha='center', va='center', fontsize=15, fontweight='bold',
|
| 1115 |
-
color=W_RED, zorder=9, transform=ax.transData)
|
| 1116 |
-
ax.text(0, 0.095,
|
| 1117 |
-
f'{n_total_sig} sig.\nloci total',
|
| 1118 |
-
ha='center', va='center', fontsize=8.5,
|
| 1119 |
-
color=W_SUBTEXT, zorder=9, transform=ax.transData)
|
| 1120 |
-
|
| 1121 |
-
# ── 8. Title & subtitle ─────────────────────────────────────────
|
| 1122 |
-
fig.text(0.5, 0.97, 'Circos GWAS — Multi-Model Comparison',
|
| 1123 |
-
ha='center', fontsize=15, fontweight='bold', color=W_TEXT)
|
| 1124 |
-
fig.text(0.5, 0.945,
|
| 1125 |
-
f'{n_chr} chromosomes | {len(mn_q)} markers | '
|
| 1126 |
-
f'{len(models)} models | {n_consensus} MTA consensus loci',
|
| 1127 |
-
ha='center', fontsize=9, color=W_SUBTEXT)
|
| 1128 |
-
|
| 1129 |
-
# ── 9. Legend ───────────────────────────────────────────────────
|
| 1130 |
-
legend_elements = [
|
| 1131 |
-
mpatches.Patch(facecolor=MODEL_COLORS.get(m, W_ACCENT),
|
| 1132 |
-
edgecolor='grey', lw=0.5, label=m, alpha=0.9)
|
| 1133 |
-
for m in models
|
| 1134 |
-
] + [
|
| 1135 |
-
plt.Line2D([0], [0], color=W_RED, marker='D', ms=7,
|
| 1136 |
-
lw=0, label=f'MTA consensus (≥{consensus_threshold} models)'),
|
| 1137 |
-
plt.Line2D([0], [0], color=W_RED, ls='--', lw=1.5,
|
| 1138 |
-
label='Bonferroni threshold'),
|
| 1139 |
-
]
|
| 1140 |
-
fig.legend(handles=legend_elements, loc='lower center',
|
| 1141 |
-
ncol=min(4, len(legend_elements)), fontsize=9,
|
| 1142 |
-
framealpha=0.96, facecolor=W_BG, edgecolor=W_BORDER,
|
| 1143 |
-
bbox_to_anchor=(0.5, 0.01))
|
| 1144 |
-
|
| 1145 |
-
# ── 10. Interpretation ──────────────────────────────────────────
|
| 1146 |
-
interp = [
|
| 1147 |
-
f"■ Outer coloured arcs = chromosomes",
|
| 1148 |
-
f"■ Concentric tracks (outer→inner): {', '.join(models)}",
|
| 1149 |
-
f"■ Bar height ∝ −log₁₀(P); red dashed arc = Bonferroni",
|
| 1150 |
-
f"■ Thick bars = significant SNPs per model",
|
| 1151 |
-
f"■ Red diamonds ◆ = MTA consensus loci (≥{consensus_threshold}/{n_models} models)",
|
| 1152 |
-
]
|
| 1153 |
-
fig.text(0.02, 0.07, "\n".join(interp), ha='left',
|
| 1154 |
-
fontsize=8, color=W_TEXT, fontfamily='monospace',
|
| 1155 |
-
bbox=dict(boxstyle='round,pad=0.5', fc=W_PANEL, ec=W_BORDER, alpha=0.95))
|
| 1156 |
-
|
| 1157 |
-
plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=W_BG)
|
| 1158 |
-
plt.close(fig)
|
| 1159 |
-
|
| 1160 |
-
|
| 1161 |
-
# ══════════════════════════════════════════════════════════════
|
| 1162 |
-
# PLOT 8: KINSHIP HEATMAP — white
|
| 1163 |
-
# ══════════════════════════════════════════════════════════════
|
| 1164 |
-
def plot_kinship_heatmap(K, save_path, max_n=200):
|
| 1165 |
-
_style_white()
|
| 1166 |
-
n = K.shape[0]
|
| 1167 |
-
if n > max_n:
|
| 1168 |
-
idx = np.random.choice(n, max_n, replace=False)
|
| 1169 |
-
idx.sort(); K = K[np.ix_(idx, idx)]
|
| 1170 |
-
title_sfx = f' (random {max_n}/{n} samples)'
|
| 1171 |
-
else:
|
| 1172 |
-
title_sfx = ''
|
| 1173 |
-
|
| 1174 |
-
fig, ax = plt.subplots(figsize=(8, 7), facecolor=W_BG)
|
| 1175 |
-
cmap = LinearSegmentedColormap.from_list(
|
| 1176 |
-
'kinship', ['#FFFFFF', '#C6DBEF', '#4292C6', '#08306B'])
|
| 1177 |
-
im = ax.imshow(K, cmap=cmap, aspect='auto', vmin=0)
|
| 1178 |
-
cb = plt.colorbar(im, ax=ax, fraction=0.04, pad=0.02)
|
| 1179 |
-
cb.set_label('Kinship coefficient', fontsize=9)
|
| 1180 |
-
ax.set_title(f'Kinship Matrix{title_sfx}', fontweight='bold',
|
| 1181 |
-
fontsize=13, color=W_ACCENT)
|
| 1182 |
-
ax.set_xlabel('Sample index', fontweight='bold')
|
| 1183 |
-
ax.set_ylabel('Sample index', fontweight='bold')
|
| 1184 |
-
ax.tick_params(labelsize=7)
|
| 1185 |
-
plt.tight_layout()
|
| 1186 |
-
plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=W_BG)
|
| 1187 |
-
plt.close(fig)
|
| 1188 |
-
|
| 1189 |
-
|
| 1190 |
-
# ══════════════════════════════════════════════════════════════
|
| 1191 |
-
# PLOT 9: ALLELE FREQUENCY DISTRIBUTION — white
|
| 1192 |
-
# ══════════════════════════════════════════════════════════════
|
| 1193 |
-
def plot_maf_distribution(maf_arr, save_path):
|
| 1194 |
-
_style_white()
|
| 1195 |
-
maf = maf_arr[maf_arr > 0]
|
| 1196 |
-
fig, axes = plt.subplots(1, 2, figsize=(12, 5), facecolor=W_BG)
|
| 1197 |
-
fig.suptitle('Minor Allele Frequency Distribution', fontsize=13,
|
| 1198 |
-
fontweight='bold', color=W_TEXT, y=1.02)
|
| 1199 |
-
|
| 1200 |
-
ax = axes[0]; ax.set_facecolor(W_PANEL)
|
| 1201 |
-
ax.hist(maf, bins=40, color=W_ACCENT, alpha=0.75, edgecolor='white', lw=0.5)
|
| 1202 |
-
ax.axvline(0.05, color=W_RED, ls='--', lw=1.8, label='MAF=0.05')
|
| 1203 |
-
ax.set_xlabel('MAF', fontweight='bold'); ax.set_ylabel('Count', fontweight='bold')
|
| 1204 |
-
ax.set_title('MAF Histogram', fontweight='bold', color=W_ACCENT)
|
| 1205 |
-
ax.legend(); ax.grid(True, color=W_GRID, lw=0.5)
|
| 1206 |
-
|
| 1207 |
-
ax = axes[1]; ax.set_facecolor(W_PANEL)
|
| 1208 |
-
# Cumulative distribution
|
| 1209 |
-
x_s = np.sort(maf); y_s = np.arange(1, len(x_s)+1) / len(x_s)
|
| 1210 |
-
ax.plot(x_s, y_s, color=W_ACCENT, lw=2)
|
| 1211 |
-
ax.fill_between(x_s, 0, y_s, color=W_ACCENT, alpha=0.15)
|
| 1212 |
-
ax.axvline(0.05, color=W_RED, ls='--', lw=1.8, label='MAF=0.05')
|
| 1213 |
-
ax.set_xlabel('MAF', fontweight='bold')
|
| 1214 |
-
ax.set_ylabel('Cumulative proportion', fontweight='bold')
|
| 1215 |
-
ax.set_title('MAF Cumulative Distribution', fontweight='bold', color=W_ACCENT)
|
| 1216 |
-
ax.legend(); ax.grid(True, color=W_GRID, lw=0.5)
|
| 1217 |
-
ax.text(0.55, 0.35,
|
| 1218 |
-
f'Total markers: {len(maf_arr):,}\nMAF<0.05: {(maf_arr<0.05).sum():,}\n'
|
| 1219 |
-
f'MAF>0.05: {(maf_arr>=0.05).sum():,}',
|
| 1220 |
-
transform=ax.transAxes, fontsize=9, color=W_SUBTEXT,
|
| 1221 |
-
bbox=dict(boxstyle='round,pad=0.4', fc=W_BG, ec=W_BORDER))
|
| 1222 |
-
|
| 1223 |
-
plt.tight_layout()
|
| 1224 |
-
plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=W_BG)
|
| 1225 |
-
plt.close(fig)
|
| 1226 |
-
|
| 1227 |
-
|
| 1228 |
-
# ══════════════════════════════════════════════════════════════
|
| 1229 |
-
# PLOT 10: EFFECT SIZE VOLCANO PLOT — white
|
| 1230 |
-
# ══════════════════════════════════════════════════════════════
|
| 1231 |
-
def plot_volcano(pv, beta, mname, bonf_thresh, save_path):
|
| 1232 |
-
_style_white()
|
| 1233 |
-
mcol = MODEL_COLORS.get(mname, W_ACCENT)
|
| 1234 |
-
bonf_log = -np.log10(bonf_thresh)
|
| 1235 |
-
log_p = -np.log10(np.clip(pv, 1e-300, 1))
|
| 1236 |
-
|
| 1237 |
-
fig, ax = plt.subplots(figsize=(9, 7), facecolor=W_BG)
|
| 1238 |
-
ax.set_facecolor(W_PANEL)
|
| 1239 |
-
fig.suptitle(f'Volcano Plot — {mname}', fontsize=13, fontweight='bold',
|
| 1240 |
-
color=W_TEXT, y=1.01)
|
| 1241 |
-
|
| 1242 |
-
sig = log_p >= bonf_log
|
| 1243 |
-
nsig = ~sig
|
| 1244 |
-
if nsig.any():
|
| 1245 |
-
ax.scatter(beta[nsig], log_p[nsig], c=W_SUBTEXT, s=10,
|
| 1246 |
-
alpha=0.45, linewidths=0, zorder=2, label='Non-significant')
|
| 1247 |
-
up = sig & (beta > 0)
|
| 1248 |
-
down = sig & (beta < 0)
|
| 1249 |
-
if up.any():
|
| 1250 |
-
ax.scatter(beta[up], log_p[up], c=W_RED, s=40, alpha=0.9,
|
| 1251 |
-
marker='D', linewidths=0, zorder=4, label='Sig positive effect')
|
| 1252 |
-
if down.any():
|
| 1253 |
-
ax.scatter(beta[down], log_p[down], c=W_ACCENT, s=40, alpha=0.9,
|
| 1254 |
-
marker='D', linewidths=0, zorder=4, label='Sig negative effect')
|
| 1255 |
-
|
| 1256 |
-
ax.axhline(bonf_log, color=W_RED, ls='--', lw=1.5, alpha=0.8,
|
| 1257 |
-
label=f'Bonferroni ({bonf_log:.2f})', zorder=5)
|
| 1258 |
-
ax.axvline(0, color=W_BORDER, lw=1.0, ls=':', alpha=0.7, zorder=3)
|
| 1259 |
-
ax.set_xlabel('Effect size (β)', fontweight='bold', fontsize=12)
|
| 1260 |
-
ax.set_ylabel('−log₁₀(P)', fontweight='bold', fontsize=12)
|
| 1261 |
-
ax.legend(fontsize=9); ax.grid(True, color=W_GRID, lw=0.5)
|
| 1262 |
-
ax.text(0.02, 0.96, f'{sig.sum()} significant SNPs',
|
| 1263 |
-
transform=ax.transAxes, fontsize=9, color=W_RED, fontweight='bold', va='top')
|
| 1264 |
-
|
| 1265 |
-
plt.tight_layout()
|
| 1266 |
-
plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=W_BG)
|
| 1267 |
-
plt.close(fig)
|
| 1268 |
-
|
| 1269 |
-
|
| 1270 |
-
# ══════════════════════════════════════════════════════════════
|
| 1271 |
-
# PLOT 11: MULTI-MODEL MANHATTAN OVERLAY — white
|
| 1272 |
-
# All models on same axis, different colours
|
| 1273 |
-
# ══════════════════════════════════════════════════════════════
|
| 1274 |
-
def plot_multi_model_manhattan(mn, ch_q, model_pvals, bonf_thresh, save_path):
|
| 1275 |
-
_style_white()
|
| 1276 |
-
GAP = max(8, len(mn) // 150)
|
| 1277 |
-
x_pos, chrom_xticks, offset, GAP, unique_chroms, chrom_to_idx = _build_x_pos(mn, ch_q, GAP)
|
| 1278 |
-
bonf_log = -np.log10(bonf_thresh)
|
| 1279 |
-
|
| 1280 |
-
fig, ax = plt.subplots(figsize=(18, 6), facecolor=W_BG)
|
| 1281 |
-
ax.set_facecolor(W_PANEL)
|
| 1282 |
-
fig.suptitle('Multi-Model Manhattan Comparison', fontsize=14,
|
| 1283 |
-
fontweight='bold', color=W_TEXT, y=1.01)
|
| 1284 |
-
|
| 1285 |
-
for ci, ch in enumerate(unique_chroms):
|
| 1286 |
-
if ci % 2 == 0:
|
| 1287 |
-
idxs = chrom_to_idx.get(ch, [])
|
| 1288 |
-
if idxs:
|
| 1289 |
-
ax.axvspan(x_pos[idxs[0]] - 0.5, x_pos[idxs[-1]] + 0.5,
|
| 1290 |
-
color='#F0F4F8', alpha=0.7, zorder=0)
|
| 1291 |
-
|
| 1292 |
-
for mname, pv in model_pvals.items():
|
| 1293 |
-
log_p = -np.log10(np.clip(pv, 1e-300, 1))
|
| 1294 |
-
mcol = MODEL_COLORS.get(mname, W_ACCENT)
|
| 1295 |
-
ax.scatter(x_pos, log_p, c=mcol, s=6, alpha=0.40,
|
| 1296 |
-
linewidths=0, zorder=2, label=mname)
|
| 1297 |
-
sig_idx = np.where(pv < bonf_thresh)[0]
|
| 1298 |
-
if len(sig_idx):
|
| 1299 |
-
ax.scatter(x_pos[sig_idx], log_p[sig_idx], c=mcol, s=50,
|
| 1300 |
-
alpha=0.95, marker='D', linewidths=0.8,
|
| 1301 |
-
edgecolors=mcol, zorder=4)
|
| 1302 |
-
|
| 1303 |
-
ax.axhline(bonf_log, color=W_RED, ls='--', lw=1.8, alpha=0.9,
|
| 1304 |
-
label=f'Bonferroni ({bonf_log:.2f})', zorder=5)
|
| 1305 |
-
ax.axhline(3.0, color=W_GOLD, ls=':', lw=1.4, alpha=0.8,
|
| 1306 |
-
label='Suggestive (3.0)', zorder=5)
|
| 1307 |
-
ax.set_xticks([x for x, _ in chrom_xticks])
|
| 1308 |
-
ax.set_xticklabels([l for _, l in chrom_xticks], fontsize=8, fontweight='bold')
|
| 1309 |
-
ax.set_xlabel('Chromosome', fontweight='bold', fontsize=12)
|
| 1310 |
-
ax.set_ylabel('−log₁₀(P)', fontweight='bold', fontsize=12)
|
| 1311 |
-
ax.set_xlim(-GAP, offset)
|
| 1312 |
-
ax.set_ylim(0, max(bonf_log * 1.2, ax.get_ylim()[1]))
|
| 1313 |
-
ax.legend(loc='upper right', fontsize=9, ncol=len(model_pvals) + 2)
|
| 1314 |
-
ax.grid(True, color=W_GRID, lw=0.5, alpha=0.6, axis='y')
|
| 1315 |
-
ax.yaxis.set_major_locator(plt.MaxNLocator(8))
|
| 1316 |
-
|
| 1317 |
-
plt.tight_layout()
|
| 1318 |
-
plt.savefig(save_path, dpi=120, bbox_inches='tight', facecolor=W_BG)
|
| 1319 |
-
plt.close(fig)
|
| 1320 |
-
|
| 1321 |
-
|
| 1322 |
-
# ══════════════════════════════════════════════════════════════
|
| 1323 |
-
# MAIN ANALYSIS
|
| 1324 |
-
# ══════════════════════════════════════════════════════════════
|
| 1325 |
-
def run_analysis(input_file, miss_sample, miss_marker, maf_thresh,
|
| 1326 |
-
lod_thresh_user, n_pc_user,
|
| 1327 |
-
run_glm, run_mlm, run_cmlm, run_bslmm, run_farmcpu,
|
| 1328 |
-
progress=gr.Progress(track_tqdm=True)):
|
| 1329 |
-
try:
|
| 1330 |
-
if input_file is None:
|
| 1331 |
-
return ("⚠️ Please upload a CSV file first.",
|
| 1332 |
-
None,None,None,None,None,None,None,None,None,
|
| 1333 |
-
gr.update(choices=[]),gr.update(choices=[]),{},{})
|
| 1334 |
-
|
| 1335 |
-
run_id = pd.Timestamp.now().strftime("%Y%m%d_%H%M%S")
|
| 1336 |
-
rdir = OUTPUT_DIR / run_id
|
| 1337 |
-
pdir = rdir / 'plots'
|
| 1338 |
-
for d in [rdir, pdir]:
|
| 1339 |
-
d.mkdir(parents=True, exist_ok=True)
|
| 1340 |
-
|
| 1341 |
-
ms_t = miss_sample / 100.
|
| 1342 |
-
mm_t = miss_marker / 100.
|
| 1343 |
-
mf_t = maf_thresh / 100.
|
| 1344 |
-
|
| 1345 |
-
# ── PARSE ────────────────────────────────────────────────────
|
| 1346 |
-
progress(0.03, desc="Parsing CSV…")
|
| 1347 |
-
(sids, pheno, geno, mnames, chroms, positions) = parse_input_csv(input_file)
|
| 1348 |
-
n_s, n_m = len(sids), len(mnames)
|
| 1349 |
-
|
| 1350 |
-
# ── QC ───────────────────────────────────────────────────────
|
| 1351 |
-
progress(0.09, desc="Quality control…")
|
| 1352 |
-
miss_m_r = np.isnan(geno).sum(0) / max(n_s, 1)
|
| 1353 |
-
miss_s_r = np.isnan(geno).sum(1) / max(n_m, 1)
|
| 1354 |
-
maf_raw = np.zeros(n_m)
|
| 1355 |
-
for i in range(n_m):
|
| 1356 |
-
v = geno[:, i]; v = v[~np.isnan(v)]
|
| 1357 |
-
if len(v):
|
| 1358 |
-
f = np.mean(v) / 2.; maf_raw[i] = min(f, 1 - f)
|
| 1359 |
-
|
| 1360 |
-
qc_m = (miss_m_r < mm_t) & (maf_raw >= mf_t)
|
| 1361 |
-
qc_s = miss_s_r < ms_t
|
| 1362 |
-
fallback = ""
|
| 1363 |
-
for rs, rm in [(ms_t, mm_t), (.6,.6), (.7,.7), (.8,.8), (.9,.9), (1.,1.)]:
|
| 1364 |
-
qm = (miss_m_r < rm) & (maf_raw >= mf_t); qs = miss_s_r < rs
|
| 1365 |
-
if qs.sum() >= 10:
|
| 1366 |
-
qc_m, qc_s = qm, qs
|
| 1367 |
-
if rs > ms_t or rm > mm_t:
|
| 1368 |
-
fallback = (f"\n⚠️ QC relaxed → sample<{rs*100:.0f}% / marker<{rm*100:.0f}%\n")
|
| 1369 |
-
break
|
| 1370 |
-
|
| 1371 |
-
geno_q = geno[np.ix_(qc_s, qc_m)].copy()
|
| 1372 |
-
pheno_q = pheno[qc_s]; sids_q = sids[qc_s]
|
| 1373 |
-
mn_q = [mnames[i] for i in range(n_m) if qc_m[i]]
|
| 1374 |
-
ch_q = [chroms[i] for i in range(n_m) if qc_m[i]]
|
| 1375 |
-
pos_q = [positions[i] for i in range(n_m) if qc_m[i]]
|
| 1376 |
-
maf_q = maf_raw[qc_m]
|
| 1377 |
-
n_q = len(mn_q)
|
| 1378 |
-
|
| 1379 |
-
# Impute missing with column mean
|
| 1380 |
-
col_mu = np.nanmean(geno_q, 0)
|
| 1381 |
-
col_mu = np.where(np.isnan(col_mu), 0, col_mu)
|
| 1382 |
-
for i in range(geno_q.shape[1]):
|
| 1383 |
-
mk = np.isnan(geno_q[:, i])
|
| 1384 |
-
if mk.any(): geno_q[mk, i] = col_mu[i]
|
| 1385 |
-
|
| 1386 |
-
valid = ~np.isnan(pheno_q)
|
| 1387 |
-
geno_q = geno_q[valid]; pheno_q = pheno_q[valid]; sids_q = sids_q[valid]
|
| 1388 |
-
|
| 1389 |
-
if len(sids_q) < 10:
|
| 1390 |
-
return (f"## ⚠️ Only {len(sids_q)} samples passed QC — need at least 10.",
|
| 1391 |
-
None,None,None,None,None,None,None,None,None,
|
| 1392 |
-
gr.update(choices=[]),gr.update(choices=[]),{},{})
|
| 1393 |
-
|
| 1394 |
-
bonf = 0.05 / n_q; bonf_log = -np.log10(bonf)
|
| 1395 |
-
|
| 1396 |
-
# ── KINSHIP ──────────────────────────────────────────────────
|
| 1397 |
-
progress(0.15, desc="Computing kinship matrix…")
|
| 1398 |
-
K = compute_kinship(geno_q)
|
| 1399 |
-
|
| 1400 |
-
# ── MODELS ───────────────────────────────────────────────────
|
| 1401 |
-
model_pvals = {}; model_betas = {}; model_ses = {}
|
| 1402 |
-
step_base = 0.17
|
| 1403 |
-
n_models_sel = sum([run_glm, run_mlm, run_cmlm, run_bslmm, run_farmcpu])
|
| 1404 |
-
step_size = 0.38 / max(n_models_sel, 1); step_i = 0
|
| 1405 |
-
|
| 1406 |
-
if run_glm:
|
| 1407 |
-
progress(step_base + step_i * step_size, desc="Running GLM…")
|
| 1408 |
-
pv,bv,sv,rv = model_glm(geno_q, pheno_q)
|
| 1409 |
-
model_pvals['GLM'] = pv; model_betas['GLM'] = bv; model_ses['GLM'] = sv; step_i += 1
|
| 1410 |
-
if run_mlm:
|
| 1411 |
-
progress(step_base + step_i * step_size, desc="Running MLM…")
|
| 1412 |
-
pv,bv,sv,rv = model_mlm(geno_q, pheno_q, K, n_pc=n_pc_user)
|
| 1413 |
-
model_pvals['MLM'] = pv; model_betas['MLM'] = bv; model_ses['MLM'] = sv; step_i += 1
|
| 1414 |
-
if run_cmlm:
|
| 1415 |
-
progress(step_base + step_i * step_size, desc="Running CMLM…")
|
| 1416 |
-
pv,bv,sv,rv = model_cmlm(geno_q, pheno_q, K, n_pc=n_pc_user)
|
| 1417 |
-
model_pvals['CMLM'] = pv; model_betas['CMLM'] = bv; model_ses['CMLM'] = sv; step_i += 1
|
| 1418 |
-
if run_bslmm:
|
| 1419 |
-
progress(step_base + step_i * step_size, desc="Running BSLMM (slow)…")
|
| 1420 |
-
pv,bv = model_bslmm(geno_q, pheno_q)
|
| 1421 |
-
model_pvals['BSLMM'] = pv; model_betas['BSLMM'] = bv; step_i += 1
|
| 1422 |
-
if run_farmcpu:
|
| 1423 |
-
progress(step_base + step_i * step_size, desc="Running FarmCPU…")
|
| 1424 |
-
pv,bv,sv = model_farmcpu(geno_q, pheno_q, K)
|
| 1425 |
-
model_pvals['FarmCPU'] = pv; model_betas['FarmCPU'] = bv; model_ses['FarmCPU'] = sv
|
| 1426 |
-
|
| 1427 |
-
if not model_pvals:
|
| 1428 |
-
return ("## ⚠️ No models selected.",
|
| 1429 |
-
None,None,None,None,None,None,None,None,None,
|
| 1430 |
-
gr.update(choices=[]),gr.update(choices=[]),{},{})
|
| 1431 |
-
|
| 1432 |
-
# ── RESULTS CSV ──────────────────────────────────────────────
|
| 1433 |
-
progress(0.57, desc="Building results table…")
|
| 1434 |
-
LOD_FACTOR = np.log10(np.e) / 2.0
|
| 1435 |
-
df = pd.DataFrame({'Marker': mn_q, 'Chromosome': ch_q, 'Position_bp': pos_q, 'MAF': maf_q})
|
| 1436 |
-
for mname, pv in model_pvals.items():
|
| 1437 |
-
df[f'{mname}_P'] = pv
|
| 1438 |
-
df[f'{mname}_LOD'] = -np.log10(np.clip(pv, 1e-300, 1)) * LOD_FACTOR
|
| 1439 |
-
df[f'{mname}_Sig'] = (pv < bonf).astype(int)
|
| 1440 |
-
if mname in model_betas:
|
| 1441 |
-
df[f'{mname}_Beta'] = model_betas[mname]
|
| 1442 |
-
if mname in model_ses:
|
| 1443 |
-
df[f'{mname}_SE'] = model_ses[mname]
|
| 1444 |
-
sig_cols = [f'{m}_Sig' for m in model_pvals]
|
| 1445 |
-
df['Consensus_Sig'] = (df[sig_cols].sum(1) >= max(1, len(sig_cols) // 2)).astype(int)
|
| 1446 |
-
df = df.sort_values(f"{list(model_pvals.keys())[0]}_P").reset_index(drop=True)
|
| 1447 |
-
df.insert(0, 'Rank', range(1, len(df) + 1))
|
| 1448 |
-
csv_path = str(rdir / 'gwas_results.csv')
|
| 1449 |
-
top_path = str(rdir / 'top_significant.csv')
|
| 1450 |
-
df.to_csv(csv_path, index=False)
|
| 1451 |
-
any_sig = df[sig_cols].sum(1) > 0
|
| 1452 |
-
df[any_sig].to_csv(top_path, index=False)
|
| 1453 |
-
|
| 1454 |
-
# Stats summary
|
| 1455 |
-
stats_data = {
|
| 1456 |
-
'n_samples': len(sids_q), 'n_markers': n_q,
|
| 1457 |
-
'n_chrom': len(set(ch_q)), 'bonf_thresh': bonf,
|
| 1458 |
-
'mean_maf': float(np.mean(maf_q)), 'maf_cutoff': maf_thresh,
|
| 1459 |
-
}
|
| 1460 |
-
for mname, pv in model_pvals.items():
|
| 1461 |
-
stats_data[f'{mname}_n_sig'] = int((pv < bonf).sum())
|
| 1462 |
-
pd.DataFrame([stats_data]).to_csv(str(rdir / 'gwas_summary_stats.csv'), index=False)
|
| 1463 |
-
|
| 1464 |
-
# ── PLOTS ────────────────────────────────────────────────────
|
| 1465 |
-
progress(0.60, desc="Phenotype distribution…")
|
| 1466 |
-
ph_path = str(pdir / 'phenotype_dist.png')
|
| 1467 |
-
plot_phenotype(pheno_q, ph_path)
|
| 1468 |
-
|
| 1469 |
-
progress(0.63, desc="PCA analysis…")
|
| 1470 |
-
pca_path = str(pdir / 'pca_analysis.png')
|
| 1471 |
-
evr, cumev, scores = plot_pca(geno_q, pheno_q, n_pc_user, pca_path)
|
| 1472 |
-
|
| 1473 |
-
progress(0.66, desc="Kinship heatmap…")
|
| 1474 |
-
kin_path = str(pdir / 'kinship_heatmap.png')
|
| 1475 |
-
plot_kinship_heatmap(K, kin_path)
|
| 1476 |
-
|
| 1477 |
-
progress(0.68, desc="MAF distribution…")
|
| 1478 |
-
maf_path = str(pdir / 'maf_distribution.png')
|
| 1479 |
-
plot_maf_distribution(maf_q, maf_path)
|
| 1480 |
-
|
| 1481 |
-
progress(0.71, desc="Manhattan + LOD plots…")
|
| 1482 |
-
man_paths = {}
|
| 1483 |
-
for mname, pv in model_pvals.items():
|
| 1484 |
-
mp = str(pdir / f'manhattan_{mname}.png')
|
| 1485 |
-
plot_manhattan_single(mn_q, ch_q, pv, mname, bonf, lod_thresh_user, mp)
|
| 1486 |
-
man_paths[mname] = mp
|
| 1487 |
-
|
| 1488 |
-
progress(0.76, desc="Multi-model Manhattan…")
|
| 1489 |
-
multi_man_path = str(pdir / 'manhattan_multi_model.png')
|
| 1490 |
-
plot_multi_model_manhattan(mn_q, ch_q, model_pvals, bonf, multi_man_path)
|
| 1491 |
-
|
| 1492 |
-
progress(0.79, desc="QQ plots…")
|
| 1493 |
-
qq_paths = {}; lam_dict = {}
|
| 1494 |
-
for mname, pv in model_pvals.items():
|
| 1495 |
-
qp = str(pdir / f'qq_{mname}.png')
|
| 1496 |
-
lam = plot_qq_single(pv, mname, bonf, qp)
|
| 1497 |
-
qq_paths[mname] = qp; lam_dict[mname] = lam
|
| 1498 |
-
|
| 1499 |
-
progress(0.83, desc="Volcano plots…")
|
| 1500 |
-
volcano_paths = {}
|
| 1501 |
-
for mname, pv in model_pvals.items():
|
| 1502 |
-
if mname in model_betas:
|
| 1503 |
-
vp = str(pdir / f'volcano_{mname}.png')
|
| 1504 |
-
plot_volcano(pv, model_betas[mname], mname, bonf, vp)
|
| 1505 |
-
volcano_paths[mname] = vp
|
| 1506 |
-
|
| 1507 |
-
progress(0.86, desc="LD decay (Hill model)…")
|
| 1508 |
-
ld_path = str(pdir / 'ld_decay.png')
|
| 1509 |
-
ld_stats, ld_interp = plot_ld_decay(geno_q, ch_q, pos_q, ld_path)
|
| 1510 |
-
ld_df = pd.DataFrame([{'Chromosome': k, **v} for k, v in ld_stats.items()])
|
| 1511 |
-
ld_df.to_csv(str(rdir / 'ld_decay_stats.csv'), index=False)
|
| 1512 |
-
|
| 1513 |
-
progress(0.89, desc="Model comparison…")
|
| 1514 |
-
cmp_path = str(pdir / 'model_comparison.png')
|
| 1515 |
-
plot_model_comparison(model_pvals, cmp_path)
|
| 1516 |
-
|
| 1517 |
-
progress(0.93, desc="Circos plot…")
|
| 1518 |
-
circos_path = str(pdir / 'circos_mta.png')
|
| 1519 |
-
plot_circos(mn_q, ch_q, pos_q, model_pvals, bonf, lod_thresh_user, circos_path)
|
| 1520 |
-
|
| 1521 |
-
# ── ZIP ──────────────────────────────────────────────────────
|
| 1522 |
-
progress(0.97, desc="Packaging ZIP…")
|
| 1523 |
-
zip_path = str(OUTPUT_DIR / f'GWAS_Results_{run_id}.zip')
|
| 1524 |
-
with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf:
|
| 1525 |
-
for root, _, files in os.walk(str(rdir)):
|
| 1526 |
-
for f in files:
|
| 1527 |
-
fp = os.path.join(root, f)
|
| 1528 |
-
zf.write(fp, os.path.relpath(fp, str(rdir)))
|
| 1529 |
-
|
| 1530 |
-
# ── SUMMARY MARKDOWN ─────────────────────────────────────────
|
| 1531 |
-
def _mdt(d, n=15):
|
| 1532 |
-
sub = d.head(n); cols = sub.columns.tolist()
|
| 1533 |
-
def _f(v):
|
| 1534 |
-
if isinstance(v, float):
|
| 1535 |
-
return f"{v:.3e}" if (v != 0 and abs(v) < 0.001) else f"{v:.4f}"
|
| 1536 |
-
return str(v)
|
| 1537 |
-
sep = "| " + " | ".join(["---"] * len(cols)) + " |"
|
| 1538 |
-
rows = ["| " + " | ".join(_f(row[c]) for c in cols) + " |"
|
| 1539 |
-
for _, row in sub.iterrows()]
|
| 1540 |
-
return "\n".join(["| " + " | ".join(cols) + " |", sep] + rows)
|
| 1541 |
-
|
| 1542 |
-
model_summary_rows = "\n".join(
|
| 1543 |
-
f"| {m} | **{int((pv < bonf).sum())}** | λ={lam_dict.get(m, 0):.4f} | "
|
| 1544 |
-
f"{'⚠️ inflation' if lam_dict.get(m, 1) > 1.05 else '✅ ok'} |"
|
| 1545 |
-
for m, pv in model_pvals.items())
|
| 1546 |
-
|
| 1547 |
-
pca_rows = "\n".join(
|
| 1548 |
-
f"| PC{i+1} | {evr[i]:.2f}% | {cumev[i]:.2f}% |"
|
| 1549 |
-
for i in range(min(n_pc_user, len(evr))))
|
| 1550 |
-
|
| 1551 |
-
top_cols = (['Rank','Marker','Chromosome','Position_bp','MAF'] +
|
| 1552 |
-
[f'{m}_P' for m in model_pvals] +
|
| 1553 |
-
[f'{m}_LOD' for m in model_pvals] +
|
| 1554 |
-
['Consensus_Sig'])
|
| 1555 |
-
top_cols = [c for c in top_cols if c in df.columns]
|
| 1556 |
-
|
| 1557 |
-
summary = f"""
|
| 1558 |
-
## ✅ GWAS Analysis Complete — v10.0
|
| 1559 |
-
|
| 1560 |
-
### 📊 Quality Control Summary
|
| 1561 |
-
| Metric | Value |
|
| 1562 |
-
|---|---|
|
| 1563 |
-
| Samples (raw → QC) | {n_s} → **{len(sids_q)}** |
|
| 1564 |
-
| Markers (raw → QC) | {n_m} → **{n_q}** |
|
| 1565 |
-
| Chromosomes | **{len(set(ch_q))}** |
|
| 1566 |
-
| MAF threshold | ≥ {maf_thresh:.1f}% |
|
| 1567 |
-
| PCs used | {n_pc_user} |
|
| 1568 |
-
| LOD threshold | {lod_thresh_user:.2f} |
|
| 1569 |
-
| Bonferroni threshold | P < {bonf:.3e} (−log₁₀P > {bonf_log:.2f}) |
|
| 1570 |
-
{fallback}
|
| 1571 |
-
|
| 1572 |
-
### 🧬 PCA Variance Explained
|
| 1573 |
-
| PC | % Variance | Cumulative |
|
| 1574 |
-
|---|---|---|
|
| 1575 |
-
{pca_rows}
|
| 1576 |
-
|
| 1577 |
-
### 🔬 Model Results
|
| 1578 |
-
| Model | Sig. Markers | λ (genomic inflation) | Status |
|
| 1579 |
-
|---|---|---|---|
|
| 1580 |
-
{model_summary_rows}
|
| 1581 |
-
|
| 1582 |
-
### 🧬 LD Decay (Hill 1975 model)
|
| 1583 |
-
{ld_interp}
|
| 1584 |
-
|
| 1585 |
-
### 📈 Output Files
|
| 1586 |
-
- `gwas_results.csv` — full results for all markers and models
|
| 1587 |
-
- `top_significant.csv` — only markers significant in ≥1 model
|
| 1588 |
-
- `gwas_summary_stats.csv` — summary statistics
|
| 1589 |
-
- `ld_decay_stats.csv` — per-chromosome LD statistics
|
| 1590 |
-
- `plots/` — all figures (Manhattan, LOD, QQ, Circos, LD, PCA, Kinship, MAF, Volcano, Comparison)
|
| 1591 |
-
|
| 1592 |
-
### 🏆 Top 15 Markers
|
| 1593 |
-
{_mdt(df[top_cols])}
|
| 1594 |
-
|
| 1595 |
-
---
|
| 1596 |
-
*MTA GWAS v10.0 — All plots: white background | Hill (1975) LD model | Dual-panel Manhattan+LOD*
|
| 1597 |
-
"""
|
| 1598 |
-
progress(1.0, desc="Done ✅")
|
| 1599 |
-
|
| 1600 |
-
first_man = list(man_paths.values())[0] if man_paths else None
|
| 1601 |
-
first_qq = list(qq_paths.values())[0] if qq_paths else None
|
| 1602 |
-
|
| 1603 |
-
return (summary,
|
| 1604 |
-
first_man, first_qq, pca_path,
|
| 1605 |
-
ld_path, circos_path, cmp_path, ph_path,
|
| 1606 |
-
zip_path,
|
| 1607 |
-
kin_path,
|
| 1608 |
-
gr.update(choices=list(man_paths.keys()),
|
| 1609 |
-
value=list(man_paths.keys())[0] if man_paths else None),
|
| 1610 |
-
gr.update(choices=list(qq_paths.keys()),
|
| 1611 |
-
value=list(qq_paths.keys())[0] if qq_paths else None),
|
| 1612 |
-
man_paths, qq_paths)
|
| 1613 |
-
|
| 1614 |
-
except Exception as e:
|
| 1615 |
-
import traceback
|
| 1616 |
-
return (f"## ❌ Error\n```\n{e}\n\n{traceback.format_exc()}\n```",
|
| 1617 |
-
None,None,None,None,None,None,None,None,None,
|
| 1618 |
-
gr.update(choices=[]),gr.update(choices=[]),{},{})
|
| 1619 |
-
|
| 1620 |
-
|
| 1621 |
-
# ══════════════════════════════════════════════════════════════
|
| 1622 |
-
# GRADIO UI — clean white/light scientific style
|
| 1623 |
-
# ══════════════════════════════════════════════════════════════
|
| 1624 |
-
CSS = """
|
| 1625 |
-
/* ── Base ────────────────���─────────── */
|
| 1626 |
-
body, .gradio-container {
|
| 1627 |
-
background: #F7F9FC !important;
|
| 1628 |
-
color: #1A202C !important;
|
| 1629 |
-
font-family: 'Segoe UI', 'Helvetica Neue', Arial, sans-serif !important;
|
| 1630 |
-
}
|
| 1631 |
-
/* ── Headings ──────────────────────── */
|
| 1632 |
-
h1, h2, h3, h4 { color: #1A365D !important; }
|
| 1633 |
-
label, .label-wrap { color: #2D3748 !important; font-weight: 600 !important; }
|
| 1634 |
-
/* ── Primary button ────────────────── */
|
| 1635 |
-
.gr-button-primary {
|
| 1636 |
-
background: linear-gradient(135deg, #1A365D 0%, #2B6CB0 100%) !important;
|
| 1637 |
-
color: #FFFFFF !important;
|
| 1638 |
-
font-weight: 700 !important;
|
| 1639 |
-
font-size: 15px !important;
|
| 1640 |
-
border: none !important;
|
| 1641 |
-
border-radius: 8px !important;
|
| 1642 |
-
box-shadow: 0 2px 8px rgba(43,108,176,0.25) !important;
|
| 1643 |
-
}
|
| 1644 |
-
.gr-button-primary:hover {
|
| 1645 |
-
background: linear-gradient(135deg, #2B6CB0 0%, #3182CE 100%) !important;
|
| 1646 |
-
box-shadow: 0 4px 14px rgba(43,108,176,0.38) !important;
|
| 1647 |
-
}
|
| 1648 |
-
/* ── Panels ────────────────────────── */
|
| 1649 |
-
.gr-box, .gr-panel, .block {
|
| 1650 |
-
background: #FFFFFF !important;
|
| 1651 |
-
border: 1px solid #E2E8F0 !important;
|
| 1652 |
-
border-radius: 10px !important;
|
| 1653 |
-
}
|
| 1654 |
-
/* ── Progress ──────────────────────── */
|
| 1655 |
-
.progress-bar { background: #2B6CB0 !important; }
|
| 1656 |
-
/* ── Markdown ──────────────────────── */
|
| 1657 |
-
.prose, .markdown-body {
|
| 1658 |
-
color: #1A202C !important;
|
| 1659 |
-
background: transparent !important;
|
| 1660 |
-
}
|
| 1661 |
-
/* ── Input elements ────────────────── */
|
| 1662 |
-
input, select, textarea {
|
| 1663 |
-
background: #FFFFFF !important;
|
| 1664 |
-
color: #1A202C !important;
|
| 1665 |
-
border-color: #CBD5E0 !important;
|
| 1666 |
-
}
|
| 1667 |
-
/* ── Tabs ──────────────────────────── */
|
| 1668 |
-
.tab-nav button { color: #2D3748 !important; }
|
| 1669 |
-
.tab-nav button.selected {
|
| 1670 |
-
color: #1A365D !important;
|
| 1671 |
-
border-bottom: 3px solid #2B6CB0 !important;
|
| 1672 |
-
font-weight: 700 !important;
|
| 1673 |
-
}
|
| 1674 |
-
"""
|
| 1675 |
-
|
| 1676 |
-
with gr.Blocks(css=CSS, title="GWAS Analysis v10.0 | White Edition") as app:
|
| 1677 |
-
|
| 1678 |
-
gr.Markdown("""
|
| 1679 |
-
# 🧬 GWAS / MTA Analysis Platform v10.0
|
| 1680 |
-
### Multi-Model Suite · Hill LD Decay · Dual Manhattan+LOD · Improved Circos · Full White Theme
|
| 1681 |
-
---
|
| 1682 |
-
""")
|
| 1683 |
-
|
| 1684 |
-
with gr.Row():
|
| 1685 |
-
with gr.Column(scale=1):
|
| 1686 |
-
gr.Markdown("""
|
| 1687 |
-
### 📋 Input CSV Format
|
| 1688 |
-
```
|
| 1689 |
-
ID, Phenotype, Mrk1, Mrk2, ...
|
| 1690 |
-
-, Chr, 1, 2, ...
|
| 1691 |
-
-, Pos, 134521, 200000, ...
|
| 1692 |
-
Sample1, 25.34, 0, 2, ...
|
| 1693 |
-
Sample2, 18.72, 1, 0, ...
|
| 1694 |
-
```
|
| 1695 |
-
**Genotype codes:** 0 / 1 / 2
|
| 1696 |
-
**Missing:** −1 or blank
|
| 1697 |
-
""")
|
| 1698 |
-
input_file = gr.File(label="📁 Upload CSV", file_types=[".csv"])
|
| 1699 |
-
|
| 1700 |
-
with gr.Column(scale=1):
|
| 1701 |
-
gr.Markdown("### ⚙️ Quality Control")
|
| 1702 |
-
miss_sample = gr.Slider(5, 100, value=30, step=5,
|
| 1703 |
-
label="Max sample missing rate (%)")
|
| 1704 |
-
miss_marker = gr.Slider(5, 100, value=30, step=5,
|
| 1705 |
-
label="Max marker missing rate (%)")
|
| 1706 |
-
maf_thr = gr.Slider(0, 25, value=3, step=1,
|
| 1707 |
-
label="Min MAF (%)")
|
| 1708 |
-
|
| 1709 |
-
with gr.Column(scale=1):
|
| 1710 |
-
gr.Markdown("### 📐 Analysis Settings")
|
| 1711 |
-
lod_thresh = gr.Slider(0.5, 10.0, value=3.0, step=0.1,
|
| 1712 |
-
label="LOD threshold (user-defined line on LOD panel)")
|
| 1713 |
-
n_pc = gr.Slider(2, 20, value=5, step=1,
|
| 1714 |
-
label="Number of PCs (MLM/CMLM control + PCA plot)")
|
| 1715 |
-
gr.Markdown("### 🔬 Models to Run")
|
| 1716 |
-
chk_glm = gr.Checkbox(value=True, label="GLM — General Linear Model")
|
| 1717 |
-
chk_mlm = gr.Checkbox(value=True, label="MLM — Mixed Linear Model")
|
| 1718 |
-
chk_cmlm = gr.Checkbox(value=True, label="CMLM — Compressed MLM")
|
| 1719 |
-
chk_bslmm = gr.Checkbox(value=False, label="BSLMM — Bayesian Sparse LMM ⚠️ slow")
|
| 1720 |
-
chk_farmcpu = gr.Checkbox(value=True, label="FarmCPU — Fixed & Random Circulating")
|
| 1721 |
-
|
| 1722 |
-
gr.Markdown("""
|
| 1723 |
-
> **ℹ️ About the analysis:**
|
| 1724 |
-
> **Manhattan panels** show both −log₁₀(P) and LOD Score vs chromosome in a dual layout.
|
| 1725 |
-
> **LD Decay** uses the Hill (1975) nonlinear model: E(r²) = 1/(1 + a·d) + b.
|
| 1726 |
-
> **Circos** shows concentric per-model tracks with thick bars for significant SNPs.
|
| 1727 |
-
> ⏱️ Speed: GLM/MLM/CMLM/FarmCPU ~1–3 min for 3000 markers. BSLMM adds ~2–4 min.
|
| 1728 |
-
""")
|
| 1729 |
-
|
| 1730 |
-
run_btn = gr.Button("🚀 Run GWAS Analysis", variant="primary", size="lg")
|
| 1731 |
-
gr.Markdown("---")
|
| 1732 |
-
|
| 1733 |
-
summary_out = gr.Markdown()
|
| 1734 |
-
|
| 1735 |
-
with gr.Row():
|
| 1736 |
-
man_model_sel = gr.Dropdown(label="🗺️ Manhattan — select model",
|
| 1737 |
-
choices=[], value=None, interactive=True)
|
| 1738 |
-
qq_model_sel = gr.Dropdown(label="📈 QQ Plot — select model",
|
| 1739 |
-
choices=[], value=None, interactive=True)
|
| 1740 |
-
|
| 1741 |
-
with gr.Row():
|
| 1742 |
-
man_out = gr.Image(label="🗺️ Manhattan Plot (−log₁₀P top | LOD bottom)")
|
| 1743 |
-
qq_out = gr.Image(label="📈 QQ Plot (genomic inflation λ)")
|
| 1744 |
-
|
| 1745 |
-
with gr.Row():
|
| 1746 |
-
pca_out = gr.Image(label="🔬 PCA Analysis (Scree + PC1v2 + PC2v3)")
|
| 1747 |
-
circos_out = gr.Image(label="🌐 Circos — Multi-Model MTA")
|
| 1748 |
-
|
| 1749 |
-
with gr.Row():
|
| 1750 |
-
ld_out = gr.Image(label="🧬 LD Decay (Hill 1975 model, white bg)")
|
| 1751 |
-
cmp_out = gr.Image(label="⚖️ Model P-value Concordance")
|
| 1752 |
-
|
| 1753 |
-
with gr.Row():
|
| 1754 |
-
ph_out = gr.Image(label="📊 Phenotype Distribution")
|
| 1755 |
-
kin_out = gr.Image(label="🔥 Kinship Matrix Heatmap")
|
| 1756 |
-
|
| 1757 |
-
dl_out = gr.File(label="📦 Download All Results (ZIP)")
|
| 1758 |
-
|
| 1759 |
-
gr.Markdown("""
|
| 1760 |
-
---
|
| 1761 |
-
**MTA GWAS v10.0** — All plots use white background & black text for publication quality.
|
| 1762 |
-
LD Decay: Hill (1975) model | Manhattan: dual −log₁₀P + LOD panels | Circos: concentric tracks
|
| 1763 |
-
""")
|
| 1764 |
-
|
| 1765 |
-
man_paths_state = gr.State({})
|
| 1766 |
-
qq_paths_state = gr.State({})
|
| 1767 |
-
|
| 1768 |
-
run_btn.click(
|
| 1769 |
-
fn=run_analysis,
|
| 1770 |
-
inputs=[input_file, miss_sample, miss_marker, maf_thr,
|
| 1771 |
-
lod_thresh, n_pc,
|
| 1772 |
-
chk_glm, chk_mlm, chk_cmlm, chk_bslmm, chk_farmcpu],
|
| 1773 |
-
outputs=[summary_out,
|
| 1774 |
-
man_out, qq_out, pca_out,
|
| 1775 |
-
ld_out, circos_out, cmp_out, ph_out,
|
| 1776 |
-
dl_out, kin_out,
|
| 1777 |
-
man_model_sel, qq_model_sel,
|
| 1778 |
-
man_paths_state, qq_paths_state],
|
| 1779 |
-
show_progress="full",
|
| 1780 |
-
)
|
| 1781 |
-
|
| 1782 |
-
def switch_manhattan(model_name, paths):
|
| 1783 |
-
if not model_name or not paths: return None
|
| 1784 |
-
return paths.get(model_name)
|
| 1785 |
-
|
| 1786 |
-
def switch_qq(model_name, paths):
|
| 1787 |
-
if not model_name or not paths: return None
|
| 1788 |
-
return paths.get(model_name)
|
| 1789 |
-
|
| 1790 |
-
man_model_sel.change(fn=switch_manhattan,
|
| 1791 |
-
inputs=[man_model_sel, man_paths_state],
|
| 1792 |
-
outputs=[man_out])
|
| 1793 |
-
qq_model_sel.change(fn=switch_qq,
|
| 1794 |
-
inputs=[qq_model_sel, qq_paths_state],
|
| 1795 |
-
outputs=[qq_out])
|
| 1796 |
-
|
| 1797 |
|
| 1798 |
if __name__ == "__main__":
|
| 1799 |
-
|
| 1800 |
-
max_threads=4,
|
| 1801 |
-
allowed_paths=[str(OUTPUT_DIR)])
|
|
|
|
| 1 |
+
""")
|
| 2 |
+
|
| 3 |
+
with gr.Column(scale=1):
|
| 4 |
+
miss_sample = gr.Slider(5, 50, value=30, label="Max sample missing (%)")
|
| 5 |
+
miss_marker = gr.Slider(5, 50, value=30, label="Max marker missing (%)")
|
| 6 |
+
maf_thr = gr.Slider(0, 25, value=3, label="Min MAF (%)")
|
| 7 |
+
|
| 8 |
+
with gr.Column(scale=1):
|
| 9 |
+
lod_thresh = gr.Slider(0.5, 10.0, value=3.0, label="LOD threshold")
|
| 10 |
+
n_pc = gr.Slider(2, 20, value=5, 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 |
+
|
| 21 |
+
summary_out = gr.Markdown()
|
| 22 |
+
|
| 23 |
+
with gr.Row():
|
| 24 |
+
man_model_sel = gr.Dropdown(label="Manhattan Model", choices=[], value=None, interactive=True)
|
| 25 |
+
qq_model_sel = gr.Dropdown(label="QQ Plot Model", choices=[], value=None, interactive=True)
|
| 26 |
+
|
| 27 |
+
with gr.Row():
|
| 28 |
+
man_out = gr.Image(label="Manhattan Plot")
|
| 29 |
+
qq_out = gr.Image(label="QQ Plot")
|
| 30 |
+
|
| 31 |
+
with gr.Row():
|
| 32 |
+
pca_out = gr.Image(label="PCA Analysis")
|
| 33 |
+
ld_out = gr.Image(label="LD Decay")
|
| 34 |
+
|
| 35 |
+
with gr.Row():
|
| 36 |
+
circos_out = gr.Image(label="Circos Plot")
|
| 37 |
+
cmp_out = gr.Image(label="Model Comparison")
|
| 38 |
+
|
| 39 |
+
with gr.Row():
|
| 40 |
+
ph_out = gr.Image(label="Phenotype Distribution")
|
| 41 |
+
kin_out = gr.Image(label="Kinship Matrix")
|
| 42 |
+
|
| 43 |
+
dl_out = gr.File(label="📦 Download ZIP")
|
| 44 |
+
|
| 45 |
+
man_paths_state = gr.State({})
|
| 46 |
+
qq_paths_state = gr.State({})
|
| 47 |
+
|
| 48 |
+
run_btn.click(
|
| 49 |
+
fn=run_analysis,
|
| 50 |
+
inputs=[input_file, miss_sample, miss_marker, maf_thr,
|
| 51 |
+
lod_thresh, n_pc,
|
| 52 |
+
chk_glm, chk_mlm, chk_cmlm, chk_bslmm, chk_farmcpu],
|
| 53 |
+
outputs=[summary_out, man_out, qq_out, pca_out,
|
| 54 |
+
ld_out, circos_out, cmp_out, ph_out,
|
| 55 |
+
dl_out, kin_out,
|
| 56 |
+
man_model_sel, qq_model_sel,
|
| 57 |
+
man_paths_state, qq_paths_state],
|
| 58 |
+
show_progress="full"
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
def switch_manhattan(model, paths):
|
| 62 |
+
return paths.get(model) if paths else None
|
| 63 |
+
|
| 64 |
+
def switch_qq(model, paths):
|
| 65 |
+
return paths.get(model) if paths else None
|
| 66 |
+
|
| 67 |
+
man_model_sel.change(switch_manhattan, [man_model_sel, man_paths_state], [man_out])
|
| 68 |
+
qq_model_sel.change(switch_qq, [qq_model_sel, qq_paths_state], [qq_out])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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