Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,911 +1,929 @@
|
|
| 1 |
-
# -*- coding: utf-8 -*-
|
| 2 |
"""
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
|
|
|
| 6 |
"""
|
| 7 |
|
| 8 |
import gradio as gr
|
| 9 |
import pandas as pd
|
| 10 |
import numpy as np
|
| 11 |
import matplotlib
|
| 12 |
-
matplotlib.use(
|
| 13 |
import matplotlib.pyplot as plt
|
| 14 |
-
from matplotlib.patches import Circle
|
| 15 |
import matplotlib.patches as mpatches
|
| 16 |
from matplotlib.gridspec import GridSpec
|
| 17 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
from scipy import stats
|
| 19 |
-
from scipy.
|
| 20 |
-
from scipy.cluster.hierarchy import dendrogram, linkage
|
| 21 |
-
import os, warnings, tempfile, zipfile, io
|
| 22 |
-
from sklearn.linear_model import (LinearRegression, Ridge, Lasso, ElasticNet,
|
| 23 |
-
BayesianRidge, RidgeCV, LassoCV)
|
| 24 |
-
from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor
|
| 25 |
-
from sklearn.preprocessing import StandardScaler
|
| 26 |
-
from sklearn.impute import SimpleImputer
|
| 27 |
from sklearn.decomposition import PCA
|
| 28 |
-
from sklearn.
|
| 29 |
-
from sklearn.
|
| 30 |
-
import
|
| 31 |
-
from
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
|
| 55 |
-
CSS = """
|
| 56 |
-
<style>
|
| 57 |
-
* { font-family: 'Times New Roman', Times, serif !important; }
|
| 58 |
-
.gradio-container { background: linear-gradient(135deg, #FDF8F0 0%, #F5F0E8 100%) !important; padding: 20px !important; }
|
| 59 |
-
.main-header { background: linear-gradient(135deg, #E8D5F5 0%, #D4F1F9 100%); padding: 30px; border-radius: 20px; text-align: center; margin-bottom: 25px; }
|
| 60 |
-
.main-header h1 { color: #4A4A4A; font-size: 2.2em; margin: 0; }
|
| 61 |
-
.section-header { background: linear-gradient(135deg, #C5A3FF 0%, #B8D4E3 100%); padding: 10px 18px; border-radius: 12px; margin: 15px 0 12px 0; font-weight: 600; }
|
| 62 |
-
.card { background: #FFFEF8; border-radius: 12px; padding: 15px; margin: 10px 0; border: 1px solid #E8DCC8; }
|
| 63 |
-
.run-btn { background: linear-gradient(135deg, #C5A3FF 0%, #A8E6CF 100%); border: none; padding: 12px 35px; border-radius: 25px; font-weight: 600; cursor: pointer; font-size: 1.1em; }
|
| 64 |
-
.run-btn:hover { transform: scale(1.02); }
|
| 65 |
-
footer { text-align: center; padding: 20px; margin-top: 25px; background: #FFFEF8; border-radius: 12px; border: 1px solid #E8DCC8; }
|
| 66 |
-
</style>
|
| 67 |
-
"""
|
| 68 |
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
"""Process data with proper imputation for NaN values"""
|
| 75 |
-
|
| 76 |
-
# Read data
|
| 77 |
-
df = pd.read_csv(filepath, header=0)
|
| 78 |
-
|
| 79 |
-
# Limit samples for speed
|
| 80 |
-
max_samples = min(500, len(df) - 1)
|
| 81 |
-
df = df.iloc[:max_samples + 1]
|
| 82 |
-
|
| 83 |
-
marker_cols = df.columns[2:].tolist()
|
| 84 |
-
|
| 85 |
-
# Parse chromosomes from first row
|
| 86 |
-
first_row = df.iloc[0]
|
| 87 |
-
chromosomes = []
|
| 88 |
-
positions = []
|
| 89 |
-
for m in marker_cols:
|
| 90 |
-
val = str(first_row[m]).strip()
|
| 91 |
-
if ':' in val:
|
| 92 |
-
chrom, pos = val.split(':')[:2]
|
| 93 |
-
chromosomes.append(chrom)
|
| 94 |
-
try:
|
| 95 |
-
positions.append(float(pos))
|
| 96 |
-
except:
|
| 97 |
-
positions.append(0)
|
| 98 |
-
else:
|
| 99 |
-
chromosomes.append(val)
|
| 100 |
-
positions.append(0)
|
| 101 |
-
|
| 102 |
-
# Sample data
|
| 103 |
-
sample_data = df.iloc[1:].reset_index(drop=True)
|
| 104 |
-
sample_ids = sample_data.iloc[:, 0].astype(str).values
|
| 105 |
-
phenotypes = pd.to_numeric(sample_data.iloc[:, 1], errors='coerce').values
|
| 106 |
-
|
| 107 |
-
# Genotype matrix
|
| 108 |
-
genotypes = sample_data[marker_cols].apply(pd.to_numeric, errors='coerce').values
|
| 109 |
-
|
| 110 |
-
# Remove columns with all NaN
|
| 111 |
-
col_not_all_nan = ~np.all(np.isnan(genotypes), axis=0)
|
| 112 |
-
genotypes = genotypes[:, col_not_all_nan]
|
| 113 |
-
chromosomes = [chromosomes[i] for i in range(len(chromosomes)) if col_not_all_nan[i]]
|
| 114 |
-
positions = [positions[i] for i in range(len(positions)) if col_not_all_nan[i]]
|
| 115 |
-
|
| 116 |
-
# Remove rows with all NaN
|
| 117 |
-
row_not_all_nan = ~np.all(np.isnan(genotypes), axis=1)
|
| 118 |
-
genotypes = genotypes[row_not_all_nan]
|
| 119 |
-
phenotypes = phenotypes[row_not_all_nan]
|
| 120 |
-
sample_ids = sample_ids[row_not_all_nan]
|
| 121 |
-
|
| 122 |
-
# Filter by missing rate
|
| 123 |
-
marker_missing_rate = np.isnan(genotypes).sum(axis=0) / genotypes.shape[0]
|
| 124 |
-
keep_markers = marker_missing_rate < marker_missing
|
| 125 |
-
genotypes = genotypes[:, keep_markers]
|
| 126 |
-
chromosomes = [chromosomes[i] for i in range(len(chromosomes)) if keep_markers[i]]
|
| 127 |
-
positions = [positions[i] for i in range(len(positions)) if keep_markers[i]]
|
| 128 |
-
|
| 129 |
-
sample_missing_rate = np.isnan(genotypes).sum(axis=1) / genotypes.shape[1]
|
| 130 |
-
keep_samples = sample_missing_rate < sample_missing
|
| 131 |
-
genotypes = genotypes[keep_samples]
|
| 132 |
-
phenotypes = phenotypes[keep_samples]
|
| 133 |
-
sample_ids = sample_ids[keep_samples]
|
| 134 |
-
|
| 135 |
-
# Calculate MAF and filter
|
| 136 |
-
maf = np.zeros(genotypes.shape[1])
|
| 137 |
-
for i in range(genotypes.shape[1]):
|
| 138 |
-
col = genotypes[:, i]
|
| 139 |
-
valid = col[~np.isnan(col)]
|
| 140 |
-
if len(valid) > 0:
|
| 141 |
-
freq = np.mean(valid) / 2.0
|
| 142 |
-
maf[i] = min(freq, 1.0 - freq)
|
| 143 |
-
else:
|
| 144 |
-
maf[i] = 0
|
| 145 |
-
|
| 146 |
-
keep_maf = maf >= maf_thresh
|
| 147 |
-
genotypes = genotypes[:, keep_maf]
|
| 148 |
-
chromosomes = [chromosomes[i] for i in range(len(chromosomes)) if keep_maf[i]]
|
| 149 |
-
positions = [positions[i] for i in range(len(positions)) if keep_maf[i]]
|
| 150 |
-
|
| 151 |
-
# IMPUTE MISSING VALUES - Critical step!
|
| 152 |
-
imputer = SimpleImputer(strategy='mean')
|
| 153 |
-
genotypes_imputed = imputer.fit_transform(genotypes)
|
| 154 |
-
|
| 155 |
-
# Remove NaN phenotypes
|
| 156 |
-
valid_pheno = ~np.isnan(phenotypes)
|
| 157 |
-
genotypes_final = genotypes_imputed[valid_pheno]
|
| 158 |
-
phenotypes_final = phenotypes[valid_pheno]
|
| 159 |
-
sample_ids_final = sample_ids[valid_pheno]
|
| 160 |
-
|
| 161 |
-
# Standardize
|
| 162 |
scaler = StandardScaler()
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 197 |
# Highlight significant
|
| 198 |
-
sig_mask =
|
| 199 |
if sig_mask.any():
|
| 200 |
-
ax.scatter(
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
ax.axhline(
|
| 205 |
-
ax.axhline(
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
ax.
|
| 214 |
-
ax.
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
ax
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
ax.
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
for ch in unique_chroms:
|
| 291 |
-
mask = np.array(chromosomes) == ch
|
| 292 |
-
idxs = np.where(mask)[0]
|
| 293 |
-
if len(idxs) < 10:
|
| 294 |
-
continue
|
| 295 |
-
|
| 296 |
-
if len(idxs) > 100:
|
| 297 |
-
idxs = np.random.choice(idxs, 100, replace=False)
|
| 298 |
-
|
| 299 |
-
G = genotypes[:, idxs]
|
| 300 |
-
pos_mb = np.array([positions[i] for i in idxs]) / 1_000_000
|
| 301 |
-
|
| 302 |
-
n_pairs = min(800, len(idxs) * 15)
|
| 303 |
-
for _ in range(n_pairs):
|
| 304 |
-
i, j = np.random.choice(len(idxs), 2, replace=False)
|
| 305 |
-
dist = abs(pos_mb[j] - pos_mb[i])
|
| 306 |
-
if dist <= max_dist_mb and dist > 0:
|
| 307 |
-
r = np.corrcoef(G[:, i], G[:, j])[0, 1]
|
| 308 |
-
if not np.isnan(r):
|
| 309 |
-
distances.append(dist)
|
| 310 |
-
r2_values.append(r**2)
|
| 311 |
-
|
| 312 |
-
if len(distances) > 2000:
|
| 313 |
-
break
|
| 314 |
-
|
| 315 |
-
if distances:
|
| 316 |
-
bins = np.linspace(0, max_dist_mb, 25)
|
| 317 |
-
bin_centers, bin_means, bin_stds = [], [], []
|
| 318 |
-
|
| 319 |
-
for i in range(len(bins)-1):
|
| 320 |
-
mask = (np.array(distances) >= bins[i]) & (np.array(distances) < bins[i+1])
|
| 321 |
-
if mask.sum() > 5:
|
| 322 |
-
bin_centers.append((bins[i] + bins[i+1]) / 2)
|
| 323 |
-
bin_means.append(np.mean(np.array(r2_values)[mask]))
|
| 324 |
-
bin_stds.append(np.std(np.array(r2_values)[mask]) / np.sqrt(mask.sum()))
|
| 325 |
-
|
| 326 |
-
ax.errorbar(bin_centers, bin_means, yerr=bin_stds, fmt='o-',
|
| 327 |
-
color=COLORS['primary'], capsize=3, markersize=6, linewidth=2, alpha=0.8)
|
| 328 |
-
|
| 329 |
-
# Exponential decay fit
|
| 330 |
-
try:
|
| 331 |
-
def decay_func(x, a, b):
|
| 332 |
-
return a * np.exp(-b * x)
|
| 333 |
-
popt, _ = curve_fit(decay_func, bin_centers, bin_means, p0=[1, 1], maxfev=1000)
|
| 334 |
-
x_fit = np.linspace(0, max_dist_mb, 100)
|
| 335 |
-
ax.plot(x_fit, decay_func(x_fit, *popt), '--', color=COLORS['lod'], linewidth=2, label=f'Decay: {popt[1]:.2f}')
|
| 336 |
-
|
| 337 |
-
half_decay = np.log(2) / popt[1] if popt[1] > 0 else 0
|
| 338 |
-
if half_decay <= max_dist_mb:
|
| 339 |
-
ax.axvline(half_decay, color=COLORS['significant'], linestyle='--', alpha=0.7, label=f'Half-decay: {half_decay:.2f} Mb')
|
| 340 |
-
except:
|
| 341 |
-
pass
|
| 342 |
-
|
| 343 |
-
ax.axhline(0.2, color=COLORS['secondary'], linestyle=':', alpha=0.7, label='rΒ² = 0.2')
|
| 344 |
-
|
| 345 |
-
ax.set_xlabel('Distance (Megabases)', fontsize=12, fontweight='bold')
|
| 346 |
-
ax.set_ylabel('Linkage Disequilibrium (rΒ²)', fontsize=12, fontweight='bold')
|
| 347 |
-
ax.set_title('LD Decay Analysis', fontsize=15, fontweight='bold')
|
| 348 |
-
ax.set_ylim(0, 1)
|
| 349 |
-
ax.legend(loc='upper right', fontsize=10)
|
| 350 |
-
ax.grid(True, alpha=0.3)
|
| 351 |
-
|
| 352 |
-
plt.tight_layout()
|
| 353 |
-
plt.savefig(save_path, dpi=200, bbox_inches='tight')
|
| 354 |
-
plt.close()
|
| 355 |
-
|
| 356 |
-
return np.mean(r2_values) if r2_values else 0
|
| 357 |
-
|
| 358 |
-
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 359 |
-
# PLOT 4: PCA PLOT
|
| 360 |
-
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 361 |
-
|
| 362 |
-
def plot_pca(genotypes_scaled, phenotypes, save_path):
|
| 363 |
-
"""PCA visualization for population structure"""
|
| 364 |
-
pca = PCA(n_components=5)
|
| 365 |
-
pca_result = pca.fit_transform(genotypes_scaled)
|
| 366 |
-
|
| 367 |
-
fig, axes = plt.subplots(1, 3, figsize=(15, 5), facecolor=BG_PASTEL)
|
| 368 |
-
|
| 369 |
# Scree plot
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
|
| 380 |
-
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
|
| 395 |
-
|
| 396 |
-
ax3.plot(range(1, 6), cumulative, 'o-', color=COLORS['secondary'], linewidth=2, markersize=8)
|
| 397 |
-
ax3.axhline(y=80, color=COLORS['significant'], linestyle='--', alpha=0.7, label='80% threshold')
|
| 398 |
-
ax3.set_xlabel('Number of Components', fontsize=11, fontweight='bold')
|
| 399 |
-
ax3.set_ylabel('Cumulative Variance (%)', fontsize=11, fontweight='bold')
|
| 400 |
-
ax3.set_title('Cumulative Variance', fontsize=12, fontweight='bold')
|
| 401 |
-
ax3.legend(loc='lower right', fontsize=9)
|
| 402 |
-
ax3.grid(True, alpha=0.3)
|
| 403 |
-
|
| 404 |
-
plt.tight_layout()
|
| 405 |
-
plt.savefig(save_path, dpi=200, bbox_inches='tight')
|
| 406 |
-
plt.close()
|
| 407 |
-
|
| 408 |
-
return pca_result, var_ratio
|
| 409 |
-
|
| 410 |
-
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 411 |
-
# PLOT 5: KINSHIP HEATMAP
|
| 412 |
-
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 413 |
-
|
| 414 |
-
def plot_kinship(genotypes_scaled, save_path):
|
| 415 |
-
"""Kinship matrix heatmap"""
|
| 416 |
-
# Calculate kinship using subset for speed
|
| 417 |
-
n_markers = min(500, genotypes_scaled.shape[1])
|
| 418 |
-
idx = np.random.choice(genotypes_scaled.shape[1], n_markers, replace=False)
|
| 419 |
-
genotypes_subset = genotypes_scaled[:, idx]
|
| 420 |
-
kinship = np.corrcoef(genotypes_subset)
|
| 421 |
-
kinship = (kinship + 1) / 2 # Scale to 0-1
|
| 422 |
-
|
| 423 |
-
# Downsample if too large
|
| 424 |
-
if kinship.shape[0] > 100:
|
| 425 |
-
idx_samples = np.linspace(0, kinship.shape[0]-1, 100, dtype=int)
|
| 426 |
-
kinship = kinship[np.ix_(idx_samples, idx_samples)]
|
| 427 |
-
|
| 428 |
-
fig, ax = plt.subplots(figsize=(10, 8), facecolor=BG_PASTEL)
|
| 429 |
-
ax.set_facecolor(PANEL_PASTEL)
|
| 430 |
-
|
| 431 |
-
im = ax.imshow(kinship, cmap='RdYlBu_r', aspect='auto', vmin=0, vmax=1)
|
| 432 |
-
ax.set_title('Kinship Matrix', fontsize=14, fontweight='bold')
|
| 433 |
-
ax.set_xlabel('Samples', fontsize=11, fontweight='bold')
|
| 434 |
-
ax.set_ylabel('Samples', fontsize=11, fontweight='bold')
|
| 435 |
-
|
| 436 |
-
cbar = plt.colorbar(im, ax=ax, shrink=0.8)
|
| 437 |
-
cbar.set_label('Kinship Coefficient', fontsize=11, fontweight='bold')
|
| 438 |
-
|
| 439 |
-
plt.tight_layout()
|
| 440 |
-
plt.savefig(save_path, dpi=200, bbox_inches='tight')
|
| 441 |
-
plt.close()
|
| 442 |
-
|
| 443 |
-
return kinship.mean(), kinship.max()
|
| 444 |
-
|
| 445 |
-
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 446 |
-
# PLOT 6: VOLCANO PLOT
|
| 447 |
-
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 448 |
-
|
| 449 |
-
def plot_volcano(p_values, effects, sig_threshold, save_path):
|
| 450 |
-
"""Volcano plot for effect size vs significance"""
|
| 451 |
-
plt.figure(figsize=(10, 8), facecolor=BG_PASTEL)
|
| 452 |
-
ax = plt.gca()
|
| 453 |
-
ax.set_facecolor(PANEL_PASTEL)
|
| 454 |
-
|
| 455 |
-
log_p = -np.log10(p_values + 1e-300)
|
| 456 |
-
sig_mask = p_values < sig_threshold
|
| 457 |
-
|
| 458 |
-
# Non-significant
|
| 459 |
-
ax.scatter(effects[~sig_mask], log_p[~sig_mask], c=COLORS['primary'],
|
| 460 |
-
s=20, alpha=0.5, label='Non-significant')
|
| 461 |
-
|
| 462 |
-
# Significant
|
| 463 |
-
if sig_mask.any():
|
| 464 |
-
ax.scatter(effects[sig_mask], log_p[sig_mask], c=COLORS['significant'],
|
| 465 |
-
s=50, alpha=0.8, edgecolors='white', linewidth=0.5, label='Significant')
|
| 466 |
-
|
| 467 |
-
ax.axhline(-np.log10(sig_threshold), color=COLORS['significant'], linestyle='--', linewidth=1.5)
|
| 468 |
-
ax.axvline(0, color='gray', linestyle='-', linewidth=1, alpha=0.5)
|
| 469 |
-
|
| 470 |
-
ax.set_xlabel('Effect Size', fontsize=12, fontweight='bold')
|
| 471 |
-
ax.set_ylabel('-logββ(P-value)', fontsize=12, fontweight='bold')
|
| 472 |
-
ax.set_title('Volcano Plot', fontsize=15, fontweight='bold')
|
| 473 |
-
ax.legend(loc='upper left', fontsize=10)
|
| 474 |
-
ax.grid(True, alpha=0.3)
|
| 475 |
-
|
| 476 |
-
plt.tight_layout()
|
| 477 |
-
plt.savefig(save_path, dpi=200, bbox_inches='tight')
|
| 478 |
-
plt.close()
|
| 479 |
-
|
| 480 |
-
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 481 |
-
# PLOT 7: CHROMOSOME-WIDE DISTRIBUTION
|
| 482 |
-
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 483 |
-
|
| 484 |
-
def plot_chromosome_distribution(p_values, chromosomes, lod_scores, save_path):
|
| 485 |
-
"""Distribution of significant markers across chromosomes"""
|
| 486 |
-
plt.figure(figsize=(14, 6), facecolor=BG_PASTEL)
|
| 487 |
-
ax = plt.gca()
|
| 488 |
-
ax.set_facecolor(PANEL_PASTEL)
|
| 489 |
-
|
| 490 |
-
unique_chroms = np.unique(chromosomes)
|
| 491 |
-
chrom_means = []
|
| 492 |
-
chrom_max = []
|
| 493 |
-
|
| 494 |
-
for ch in unique_chroms:
|
| 495 |
-
mask = np.array(chromosomes) == ch
|
| 496 |
-
if mask.any():
|
| 497 |
-
chrom_means.append(-np.log10(p_values[mask] + 1e-300).mean())
|
| 498 |
-
chrom_max.append(lod_scores[mask].max())
|
| 499 |
-
|
| 500 |
-
x = np.arange(len(unique_chroms))
|
| 501 |
-
width = 0.35
|
| 502 |
-
|
| 503 |
-
bars1 = ax.bar(x - width/2, chrom_means, width, label='Mean -logββ(P)',
|
| 504 |
-
color=COLORS['primary'], alpha=0.7, edgecolor='white')
|
| 505 |
-
bars2 = ax.bar(x + width/2, chrom_max, width, label='Max LOD',
|
| 506 |
-
color=COLORS['lod'], alpha=0.7, edgecolor='white')
|
| 507 |
-
|
| 508 |
-
ax.set_xlabel('Chromosome', fontsize=12, fontweight='bold')
|
| 509 |
-
ax.set_ylabel('Score', fontsize=12, fontweight='bold')
|
| 510 |
-
ax.set_title('Chromosome-wise Distribution', fontsize=15, fontweight='bold')
|
| 511 |
-
ax.set_xticks(x)
|
| 512 |
-
ax.set_xticklabels(unique_chroms, rotation=45, ha='right')
|
| 513 |
-
ax.legend(loc='upper right', fontsize=10)
|
| 514 |
-
ax.grid(True, alpha=0.3, axis='y')
|
| 515 |
-
|
| 516 |
-
plt.tight_layout()
|
| 517 |
-
plt.savefig(save_path, dpi=200, bbox_inches='tight')
|
| 518 |
-
plt.close()
|
| 519 |
-
|
| 520 |
-
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 521 |
-
# PLOT 8: CIRCOS PLOT
|
| 522 |
-
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 523 |
-
|
| 524 |
-
def plot_circos(chromosomes, p_values, lod_scores, sig_threshold, save_path):
|
| 525 |
-
"""Circos-style circular plot"""
|
| 526 |
-
plt.figure(figsize=(10, 10), facecolor=BG_PASTEL)
|
| 527 |
-
ax = plt.subplot(111, projection='polar')
|
| 528 |
-
ax.set_facecolor(BG_PASTEL)
|
| 529 |
-
|
| 530 |
-
unique_chroms = np.unique(chromosomes)
|
| 531 |
-
n_chroms = len(unique_chroms)
|
| 532 |
-
angles = np.linspace(0, 2*np.pi, n_chroms + 1)
|
| 533 |
-
|
| 534 |
-
# Chromosome arcs
|
| 535 |
-
for i, ch in enumerate(unique_chroms):
|
| 536 |
-
theta_mid = (angles[i] + angles[i+1]) / 2
|
| 537 |
-
ax.bar(theta_mid, 0.15, width=2*np.pi/n_chroms - 0.03,
|
| 538 |
-
bottom=0.85, color=COLORS['chromosome'][i % len(COLORS['chromosome'])],
|
| 539 |
-
alpha=0.8, edgecolor='white')
|
| 540 |
-
ax.text(theta_mid, 0.93, str(ch), ha='center', va='center', fontsize=9, fontweight='bold')
|
| 541 |
-
|
| 542 |
-
# Markers
|
| 543 |
-
log_p = -np.log10(p_values + 1e-300)
|
| 544 |
-
max_p = log_p.max() if log_p.max() > 0 else 5
|
| 545 |
-
|
| 546 |
-
for i, ch in enumerate(unique_chroms):
|
| 547 |
-
mask = np.array(chromosomes) == ch
|
| 548 |
-
if mask.sum() == 0:
|
| 549 |
continue
|
| 550 |
-
|
| 551 |
-
|
| 552 |
-
|
| 553 |
-
|
| 554 |
-
|
| 555 |
-
|
| 556 |
-
|
| 557 |
-
|
| 558 |
-
|
| 559 |
-
|
| 560 |
-
|
| 561 |
-
|
| 562 |
-
|
| 563 |
-
|
| 564 |
-
|
| 565 |
-
|
| 566 |
-
|
| 567 |
-
|
| 568 |
-
|
| 569 |
-
|
| 570 |
-
|
| 571 |
-
|
| 572 |
-
|
| 573 |
-
|
| 574 |
-
|
| 575 |
-
|
| 576 |
-
|
| 577 |
-
|
| 578 |
-
|
| 579 |
-
|
| 580 |
-
|
| 581 |
-
|
| 582 |
-
|
| 583 |
-
|
| 584 |
-
|
| 585 |
-
|
| 586 |
-
|
| 587 |
-
|
| 588 |
-
|
| 589 |
-
|
| 590 |
-
|
| 591 |
-
|
| 592 |
-
|
| 593 |
-
|
| 594 |
-
|
| 595 |
-
|
| 596 |
-
|
| 597 |
-
|
| 598 |
-
|
| 599 |
-
|
| 600 |
-
|
| 601 |
-
|
| 602 |
-
|
| 603 |
-
|
| 604 |
-
|
| 605 |
-
|
| 606 |
-
|
| 607 |
-
|
| 608 |
-
|
| 609 |
-
|
| 610 |
-
|
| 611 |
-
|
| 612 |
-
|
| 613 |
-
|
| 614 |
-
"
|
| 615 |
-
|
| 616 |
-
|
| 617 |
-
|
| 618 |
-
|
| 619 |
-
|
| 620 |
-
|
| 621 |
-
|
| 622 |
-
|
| 623 |
-
|
| 624 |
-
|
| 625 |
-
|
| 626 |
-
|
| 627 |
-
|
| 628 |
-
|
| 629 |
-
|
| 630 |
-
|
| 631 |
-
|
| 632 |
-
|
| 633 |
-
|
| 634 |
-
|
| 635 |
-
|
| 636 |
-
|
| 637 |
-
|
| 638 |
-
|
| 639 |
-
|
| 640 |
-
|
| 641 |
-
|
| 642 |
-
|
| 643 |
-
|
| 644 |
-
|
| 645 |
-
|
| 646 |
-
|
| 647 |
-
|
| 648 |
-
|
| 649 |
-
|
| 650 |
-
|
| 651 |
-
|
| 652 |
-
|
| 653 |
-
|
| 654 |
-
|
| 655 |
-
|
| 656 |
-
|
| 657 |
-
|
| 658 |
-
|
| 659 |
-
|
| 660 |
-
|
| 661 |
-
|
| 662 |
-
|
| 663 |
-
|
| 664 |
-
|
| 665 |
-
def
|
| 666 |
-
|
| 667 |
-
|
| 668 |
-
|
| 669 |
-
|
| 670 |
-
|
| 671 |
-
|
| 672 |
-
|
| 673 |
-
|
| 674 |
-
|
| 675 |
-
|
| 676 |
-
|
| 677 |
-
|
| 678 |
-
|
| 679 |
-
|
| 680 |
-
|
| 681 |
-
|
| 682 |
-
|
| 683 |
-
|
| 684 |
-
|
| 685 |
-
|
| 686 |
-
|
| 687 |
-
|
| 688 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 689 |
try:
|
| 690 |
-
|
| 691 |
-
temp_dir = tempfile.mkdtemp()
|
| 692 |
-
results_dir = os.path.join(temp_dir, 'results')
|
| 693 |
-
plots_dir = os.path.join(results_dir, 'plots')
|
| 694 |
-
os.makedirs(plots_dir, exist_ok=True)
|
| 695 |
-
|
| 696 |
-
# Process data with proper imputation
|
| 697 |
-
genotypes, genotypes_scaled, phenotypes, sample_ids, chromosomes, positions = process_data(
|
| 698 |
-
input_file.name, sample_missing/100, marker_missing/100, maf_threshold/100
|
| 699 |
-
)
|
| 700 |
-
|
| 701 |
-
n_samples, n_markers = genotypes.shape
|
| 702 |
-
bonf_threshold = 0.05 / n_markers
|
| 703 |
-
|
| 704 |
-
# Run GWAS models
|
| 705 |
-
print("Running Linear Regression...")
|
| 706 |
-
pvals, effects, lod = run_linear_regression(genotypes, phenotypes)
|
| 707 |
-
|
| 708 |
-
print("Running Random Forest...")
|
| 709 |
-
rf_pvals, rf_importance, rf_lod, rf_score = run_random_forest(genotypes_scaled, phenotypes)
|
| 710 |
-
|
| 711 |
-
# Generate all 10 plots
|
| 712 |
-
plots = {}
|
| 713 |
-
|
| 714 |
-
# Plot 1: Manhattan
|
| 715 |
-
plots['manhattan'] = os.path.join(plots_dir, 'manhattan.png')
|
| 716 |
-
n_sig = plot_manhattan(pvals, chromosomes, lod, bonf_threshold, plots['manhattan'])
|
| 717 |
-
|
| 718 |
-
# Plot 2: QQ
|
| 719 |
-
plots['qq'] = os.path.join(plots_dir, 'qq.png')
|
| 720 |
-
lambda_gc = plot_qq(pvals, plots['qq'])
|
| 721 |
-
|
| 722 |
-
# Plot 3: LD Decay
|
| 723 |
-
plots['ld'] = os.path.join(plots_dir, 'ld_decay.png')
|
| 724 |
-
mean_ld = plot_ld_decay(genotypes, chromosomes, positions, plots['ld'])
|
| 725 |
-
|
| 726 |
-
# Plot 4: PCA
|
| 727 |
-
plots['pca'] = os.path.join(plots_dir, 'pca.png')
|
| 728 |
-
pca_result, var_ratio = plot_pca(genotypes_scaled, phenotypes, plots['pca'])
|
| 729 |
-
|
| 730 |
-
# Plot 5: Kinship
|
| 731 |
-
plots['kinship'] = os.path.join(plots_dir, 'kinship.png')
|
| 732 |
-
mean_kinship, max_kinship = plot_kinship(genotypes_scaled, plots['kinship'])
|
| 733 |
-
|
| 734 |
-
# Plot 6: Volcano
|
| 735 |
-
plots['volcano'] = os.path.join(plots_dir, 'volcano.png')
|
| 736 |
-
plot_volcano(pvals, effects, bonf_threshold, plots['volcano'])
|
| 737 |
-
|
| 738 |
-
# Plot 7: Chromosome Distribution
|
| 739 |
-
plots['chrom_dist'] = os.path.join(plots_dir, 'chromosome_distribution.png')
|
| 740 |
-
plot_chromosome_distribution(pvals, chromosomes, lod, plots['chrom_dist'])
|
| 741 |
-
|
| 742 |
-
# Plot 8: Circos
|
| 743 |
-
plots['circos'] = os.path.join(plots_dir, 'circos.png')
|
| 744 |
-
plot_circos(chromosomes, pvals, lod, bonf_threshold, plots['circos'])
|
| 745 |
-
|
| 746 |
-
# Plot 9: P-value Distribution
|
| 747 |
-
plots['pval_dist'] = os.path.join(plots_dir, 'pvalue_distribution.png')
|
| 748 |
-
plot_pvalue_distribution(pvals, plots['pval_dist'])
|
| 749 |
-
|
| 750 |
-
# Plot 10: Effect Distribution
|
| 751 |
-
plots['effect_dist'] = os.path.join(plots_dir, 'effect_distribution.png')
|
| 752 |
-
plot_effect_distribution(effects, plots['effect_dist'])
|
| 753 |
-
|
| 754 |
-
# Create results DataFrame
|
| 755 |
-
results_df = pd.DataFrame({
|
| 756 |
-
'Marker': [f'M{i+1}' for i in range(n_markers)],
|
| 757 |
-
'Chromosome': chromosomes,
|
| 758 |
-
'Position': positions,
|
| 759 |
-
'P-value': pvals,
|
| 760 |
-
'LOD': lod,
|
| 761 |
-
'Effect_Size': effects,
|
| 762 |
-
'RF_Importance': rf_importance,
|
| 763 |
-
'Significant': pvals < bonf_threshold
|
| 764 |
-
})
|
| 765 |
-
results_df = results_df.sort_values('P-value')
|
| 766 |
-
results_df.to_csv(os.path.join(results_dir, 'gwas_results.csv'), index=False)
|
| 767 |
-
|
| 768 |
-
# Create ZIP file
|
| 769 |
-
zip_path = os.path.join(temp_dir, 'GWAS_Complete_Results.zip')
|
| 770 |
-
with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf:
|
| 771 |
-
for root, _, files in os.walk(results_dir):
|
| 772 |
-
for f in files:
|
| 773 |
-
zf.write(os.path.join(root, f), os.path.relpath(os.path.join(root, f), temp_dir))
|
| 774 |
-
|
| 775 |
-
# Generate summary
|
| 776 |
-
summary = f"""
|
| 777 |
-
## β
GWAS Analysis Complete!
|
| 778 |
-
|
| 779 |
-
### π Dataset Summary
|
| 780 |
-
| Metric | Value |
|
| 781 |
-
|--------|-------|
|
| 782 |
-
| Samples | **{n_samples}** |
|
| 783 |
-
| Markers | **{n_markers:,}** |
|
| 784 |
-
| Chromosomes | **{len(np.unique(chromosomes))}** |
|
| 785 |
-
|
| 786 |
-
### π¬ Key Findings
|
| 787 |
-
| Metric | Value |
|
| 788 |
-
|--------|-------|
|
| 789 |
-
| Significant Markers (Bonferroni) | **{n_sig}** |
|
| 790 |
-
| Genomic Inflation Factor (Ξ») | **{lambda_gc:.3f}** |
|
| 791 |
-
| Mean LD (rΒ²) | **{mean_ld:.3f}** |
|
| 792 |
-
| Mean Kinship | **{mean_kinship:.3f}** |
|
| 793 |
-
|
| 794 |
-
### π Model Performance
|
| 795 |
-
| Model | RΒ² Score |
|
| 796 |
-
|-------|----------|
|
| 797 |
-
| Linear Regression | {r2_score(phenotypes, np.dot(genotypes, effects)):.3f} |
|
| 798 |
-
| Random Forest | {rf_score:.3f} |
|
| 799 |
-
|
| 800 |
-
### π Top 5 Associated Markers
|
| 801 |
-
{results_df.head(5)[['Marker', 'Chromosome', 'LOD', 'Effect_Size']].to_markdown(index=False)}
|
| 802 |
-
|
| 803 |
-
### π Output Files (ZIP Archive)
|
| 804 |
-
- `gwas_results.csv` - Complete association results
|
| 805 |
-
- `plots/manhattan.png` - Manhattan plot with LOD scores
|
| 806 |
-
- `plots/qq.png` - Q-Q plot with genomic inflation
|
| 807 |
-
- `plots/ld_decay.png` - LD decay analysis
|
| 808 |
-
- `plots/pca.png` - Population structure PCA
|
| 809 |
-
- `plots/kinship.png` - Kinship matrix heatmap
|
| 810 |
-
- `plots/volcano.png` - Volcano plot
|
| 811 |
-
- `plots/chromosome_distribution.png` - Chromosome-wise distribution
|
| 812 |
-
- `plots/circos.png` - Circular visualization
|
| 813 |
-
- `plots/pvalue_distribution.png` - P-value histogram
|
| 814 |
-
- `plots/effect_distribution.png` - Effect size distribution
|
| 815 |
-
|
| 816 |
-
### π Interpretation
|
| 817 |
-
- **Population Structure**: {'Well-controlled' if lambda_gc < 1.05 else 'Consider including more PCs'}
|
| 818 |
-
- **LD Decay**: {'Fast decay indicates diverse germplasm' if mean_ld < 0.3 else 'Slow decay suggests related individuals'}
|
| 819 |
-
- **Significant Associations**: {n_sig} markers show strong association with the trait
|
| 820 |
-
"""
|
| 821 |
-
|
| 822 |
-
return (summary,
|
| 823 |
-
plots['manhattan'], plots['qq'], plots['ld'], plots['pca'],
|
| 824 |
-
plots['kinship'], plots['volcano'], plots['chrom_dist'],
|
| 825 |
-
plots['circos'], plots['pval_dist'], plots['effect_dist'], zip_path)
|
| 826 |
-
|
| 827 |
except Exception as e:
|
| 828 |
-
|
| 829 |
-
|
| 830 |
-
|
| 831 |
-
|
| 832 |
-
|
| 833 |
-
|
| 834 |
-
|
| 835 |
-
|
| 836 |
-
|
| 837 |
-
|
| 838 |
-
|
| 839 |
-
|
| 840 |
-
|
| 841 |
-
|
| 842 |
-
<
|
| 843 |
-
|
| 844 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 845 |
with gr.Row():
|
| 846 |
with gr.Column(scale=1):
|
| 847 |
-
gr.
|
| 848 |
-
|
| 849 |
-
|
| 850 |
-
|
| 851 |
-
|
| 852 |
-
|
| 853 |
-
|
| 854 |
-
|
| 855 |
-
|
| 856 |
-
|
| 857 |
-
gr.
|
| 858 |
-
|
| 859 |
-
|
| 860 |
-
|
| 861 |
-
|
| 862 |
-
|
| 863 |
-
|
| 864 |
-
|
| 865 |
-
""
|
| 866 |
-
|
| 867 |
-
|
| 868 |
-
|
| 869 |
-
|
| 870 |
-
|
| 871 |
-
|
| 872 |
-
|
| 873 |
-
|
| 874 |
-
|
| 875 |
-
|
| 876 |
-
|
| 877 |
-
|
| 878 |
-
|
| 879 |
-
|
| 880 |
-
|
| 881 |
-
|
| 882 |
-
|
| 883 |
-
|
| 884 |
-
|
| 885 |
-
|
| 886 |
-
|
| 887 |
-
|
| 888 |
-
|
| 889 |
-
|
| 890 |
-
|
| 891 |
-
|
| 892 |
-
|
| 893 |
-
|
| 894 |
-
|
|
|
|
|
|
|
|
|
|
| 895 |
run_btn.click(
|
| 896 |
-
fn=
|
| 897 |
-
inputs=[
|
| 898 |
-
outputs=[
|
| 899 |
-
|
| 900 |
-
|
| 901 |
)
|
| 902 |
-
|
| 903 |
-
|
| 904 |
-
|
| 905 |
-
|
| 906 |
-
|
| 907 |
-
|
| 908 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 909 |
|
| 910 |
if __name__ == "__main__":
|
| 911 |
-
|
|
|
|
|
|
|
| 1 |
"""
|
| 2 |
+
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 3 |
+
β GWAS PIPELINE β Genome-Wide Association Study Suite β
|
| 4 |
+
β Full statistical analysis with interactive Gradio UI β
|
| 5 |
+
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 6 |
"""
|
| 7 |
|
| 8 |
import gradio as gr
|
| 9 |
import pandas as pd
|
| 10 |
import numpy as np
|
| 11 |
import matplotlib
|
| 12 |
+
matplotlib.use("Agg")
|
| 13 |
import matplotlib.pyplot as plt
|
|
|
|
| 14 |
import matplotlib.patches as mpatches
|
| 15 |
from matplotlib.gridspec import GridSpec
|
| 16 |
+
from matplotlib.colors import LinearSegmentedColormap
|
| 17 |
+
import matplotlib.ticker as ticker
|
| 18 |
+
import warnings
|
| 19 |
+
warnings.filterwarnings("ignore")
|
| 20 |
+
|
| 21 |
from scipy import stats
|
| 22 |
+
from scipy.spatial.distance import pdist, squareform
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
from sklearn.decomposition import PCA
|
| 24 |
+
from sklearn.preprocessing import StandardScaler
|
| 25 |
+
from sklearn.linear_model import LinearRegression
|
| 26 |
+
import io, os, re, itertools
|
| 27 |
+
from io import StringIO
|
| 28 |
+
|
| 29 |
+
# βββββββββββββββββββββββββββ THEME PALETTE ββββββββββββββββββββββββββββ
|
| 30 |
+
DARK = "#0d0f1a"
|
| 31 |
+
PANEL = "#131626"
|
| 32 |
+
ACCENT1 = "#00e5ff" # cyan
|
| 33 |
+
ACCENT2 = "#ff4081" # pink
|
| 34 |
+
ACCENT3 = "#b2ff59" # lime
|
| 35 |
+
GOLD = "#ffd740"
|
| 36 |
+
MUTED = "#8892b0"
|
| 37 |
+
TEXT = "#ccd6f6"
|
| 38 |
+
GRID_COL = "#1e2340"
|
| 39 |
+
|
| 40 |
+
def style_fig(fig):
|
| 41 |
+
fig.patch.set_facecolor(DARK)
|
| 42 |
+
for ax in fig.get_axes():
|
| 43 |
+
ax.set_facecolor(PANEL)
|
| 44 |
+
ax.tick_params(colors=TEXT, labelsize=9)
|
| 45 |
+
ax.xaxis.label.set_color(TEXT)
|
| 46 |
+
ax.yaxis.label.set_color(TEXT)
|
| 47 |
+
ax.title.set_color(ACCENT1)
|
| 48 |
+
for spine in ax.spines.values():
|
| 49 |
+
spine.set_edgecolor(GRID_COL)
|
| 50 |
+
ax.grid(color=GRID_COL, linewidth=0.5, linestyle="--", alpha=0.7)
|
| 51 |
+
return fig
|
| 52 |
+
|
| 53 |
+
# βββββββββββββββββββββββββββ DATA PARSING βββββββββββββββββββββββββββββ
|
| 54 |
+
|
| 55 |
+
def parse_data(file_obj=None, text_input=None):
|
| 56 |
+
"""Parse uploaded CSV / pasted text β clean DataFrame."""
|
| 57 |
+
raw = None
|
| 58 |
+
if file_obj is not None:
|
| 59 |
+
try:
|
| 60 |
+
raw = pd.read_csv(file_obj.name, sep=None, engine="python")
|
| 61 |
+
except Exception:
|
| 62 |
+
raw = pd.read_csv(file_obj.name, sep="\t")
|
| 63 |
+
elif text_input and text_input.strip():
|
| 64 |
+
try:
|
| 65 |
+
raw = pd.read_csv(StringIO(text_input), sep=None, engine="python")
|
| 66 |
+
except Exception:
|
| 67 |
+
raw = pd.read_csv(StringIO(text_input), sep="\t")
|
| 68 |
+
else:
|
| 69 |
+
raise ValueError("No data provided.")
|
| 70 |
+
|
| 71 |
+
# Identify ID and phenotype columns
|
| 72 |
+
cols = list(raw.columns)
|
| 73 |
+
id_col = cols[0]
|
| 74 |
+
phen_col = cols[1]
|
| 75 |
+
|
| 76 |
+
snp_cols = cols[2:]
|
| 77 |
+
|
| 78 |
+
# Drop rows where phenotype is missing / header artefacts
|
| 79 |
+
raw = raw[pd.to_numeric(raw[phen_col], errors="coerce").notna()].copy()
|
| 80 |
+
raw[phen_col] = raw[phen_col].astype(float)
|
| 81 |
+
|
| 82 |
+
# Replace missing genotype codes (-1, -9, 'NA') β NaN
|
| 83 |
+
geno = raw[snp_cols].apply(pd.to_numeric, errors="coerce")
|
| 84 |
+
geno = geno.where(~geno.isin([-1, -9]), np.nan)
|
| 85 |
+
|
| 86 |
+
df = pd.DataFrame()
|
| 87 |
+
df["ID"] = raw[id_col].values
|
| 88 |
+
df["Phenotype"] = raw[phen_col].values
|
| 89 |
+
for c in snp_cols:
|
| 90 |
+
df[c] = geno[c].values
|
| 91 |
+
|
| 92 |
+
return df, snp_cols
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def parse_marker_info(snp_cols):
|
| 96 |
+
"""
|
| 97 |
+
Extract chromosome and position from marker names like
|
| 98 |
+
'chr1_134521_LOC_Os01g01280' β chrom=1, pos=134521
|
| 99 |
+
Falls back to sequential numbering.
|
| 100 |
+
"""
|
| 101 |
+
chroms, positions = [], []
|
| 102 |
+
for m in snp_cols:
|
| 103 |
+
m_clean = str(m).strip()
|
| 104 |
+
mat = re.match(r"[Cc]hr(\d+)[_\-](\d+)", m_clean)
|
| 105 |
+
if mat:
|
| 106 |
+
chroms.append(int(mat.group(1)))
|
| 107 |
+
positions.append(int(mat.group(2)))
|
| 108 |
+
else:
|
| 109 |
+
num = re.findall(r"\d+", m_clean)
|
| 110 |
+
chroms.append(int(num[0]) if num else 1)
|
| 111 |
+
positions.append(int(num[1]) if len(num) > 1 else len(positions) + 1)
|
| 112 |
+
return np.array(chroms), np.array(positions)
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
# βββββββββββββββββββββββββββ STATISTICAL MODELS βββββββββββββββββββββββ
|
| 116 |
+
|
| 117 |
+
def impute_genotypes(geno_matrix):
|
| 118 |
+
"""Mean imputation for missing genotype values."""
|
| 119 |
+
mat = geno_matrix.copy().astype(float)
|
| 120 |
+
for j in range(mat.shape[1]):
|
| 121 |
+
col = mat[:, j]
|
| 122 |
+
m = np.nanmean(col)
|
| 123 |
+
col[np.isnan(col)] = m if not np.isnan(m) else 0
|
| 124 |
+
mat[:, j] = col
|
| 125 |
+
return mat
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def compute_maf(G):
|
| 129 |
+
"""Minor Allele Frequency per SNP."""
|
| 130 |
+
freqs = np.nanmean(G, axis=0) / 2
|
| 131 |
+
maf = np.where(freqs > 0.5, 1 - freqs, freqs)
|
| 132 |
+
return maf
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def build_kinship(G):
|
| 136 |
+
"""VanRaden (2008) genomic relationship matrix."""
|
| 137 |
+
p = np.nanmean(G, axis=0) / 2
|
| 138 |
+
Z = G - 2 * p
|
| 139 |
+
denom = 2 * np.sum(p * (1 - p))
|
| 140 |
+
if denom == 0:
|
| 141 |
+
denom = 1
|
| 142 |
+
K = Z @ Z.T / denom
|
| 143 |
+
return K
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def ols_gwas(y, G):
|
| 147 |
+
"""Model 1 β Ordinary Least Squares (simple linear regression)."""
|
| 148 |
+
n, m = G.shape
|
| 149 |
+
pvals = np.ones(m)
|
| 150 |
+
betas = np.zeros(m)
|
| 151 |
+
for j in range(m):
|
| 152 |
+
x = G[:, j]
|
| 153 |
+
x = (x - x.mean())
|
| 154 |
+
if x.std() < 1e-8:
|
| 155 |
+
continue
|
| 156 |
+
slope, intercept, r, p, se = stats.linregress(x, y)
|
| 157 |
+
pvals[j] = p
|
| 158 |
+
betas[j] = slope
|
| 159 |
+
return pvals, betas
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def mlm_gwas(y, G, K):
|
| 163 |
+
"""Model 2 β Mixed Linear Model (EMMA-like, PC correction as K proxy)."""
|
| 164 |
+
n, m = G.shape
|
| 165 |
+
pvals = np.ones(m)
|
| 166 |
+
betas = np.zeros(m)
|
| 167 |
+
# Use top PCs of K as random-effect covariates
|
| 168 |
+
eigvals, eigvecs = np.linalg.eigh(K + np.eye(n) * 1e-6)
|
| 169 |
+
idx = np.argsort(eigvals)[::-1]
|
| 170 |
+
n_pcs = min(3, n - 2)
|
| 171 |
+
Q = eigvecs[:, idx[:n_pcs]]
|
| 172 |
+
# Regress y on Q to get residuals
|
| 173 |
+
reg = LinearRegression().fit(Q, y)
|
| 174 |
+
y_res = y - reg.predict(Q)
|
| 175 |
+
for j in range(m):
|
| 176 |
+
x = G[:, j]
|
| 177 |
+
x_res = x - LinearRegression().fit(Q, x).predict(Q)
|
| 178 |
+
if x_res.std() < 1e-8:
|
| 179 |
+
continue
|
| 180 |
+
slope, intercept, r, p, se = stats.linregress(x_res, y_res)
|
| 181 |
+
pvals[j] = p
|
| 182 |
+
betas[j] = slope
|
| 183 |
+
return pvals, betas
|
| 184 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 185 |
|
| 186 |
+
def glm_gwas(y, G):
|
| 187 |
+
"""Model 3 β General Linear Model with population structure (PCA correction)."""
|
| 188 |
+
n, m = G.shape
|
| 189 |
+
pvals = np.ones(m)
|
| 190 |
+
betas = np.zeros(m)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 191 |
scaler = StandardScaler()
|
| 192 |
+
G_sc = scaler.fit_transform(G)
|
| 193 |
+
pca = PCA(n_components=min(3, n - 2))
|
| 194 |
+
PCs = pca.fit_transform(G_sc)
|
| 195 |
+
reg = LinearRegression().fit(PCs, y)
|
| 196 |
+
y_adj = y - reg.predict(PCs)
|
| 197 |
+
for j in range(m):
|
| 198 |
+
x = G[:, j]
|
| 199 |
+
if x.std() < 1e-8:
|
| 200 |
+
continue
|
| 201 |
+
x_adj = x - LinearRegression().fit(PCs, x).predict(PCs)
|
| 202 |
+
slope, intercept, r, p, se = stats.linregress(x_adj, y_adj)
|
| 203 |
+
pvals[j] = p
|
| 204 |
+
betas[j] = slope
|
| 205 |
+
return pvals, betas
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
def compressed_mlm_gwas(y, G, K):
|
| 209 |
+
"""Model 4 β Compressed MLM (group-based K compression)."""
|
| 210 |
+
n, m = G.shape
|
| 211 |
+
pvals = np.ones(m)
|
| 212 |
+
betas = np.zeros(m)
|
| 213 |
+
# Cluster individuals using K diagonal
|
| 214 |
+
k_diag = np.diag(K)
|
| 215 |
+
groups = pd.qcut(k_diag, q=min(3, n), labels=False, duplicates="drop")
|
| 216 |
+
g_means = np.zeros((n, groups.max() + 1))
|
| 217 |
+
for g in range(groups.max() + 1):
|
| 218 |
+
idx = np.where(groups == g)[0]
|
| 219 |
+
if len(idx):
|
| 220 |
+
g_means[:, g] = K[:, idx].mean(axis=1)
|
| 221 |
+
reg = LinearRegression().fit(g_means, y)
|
| 222 |
+
y_res = y - reg.predict(g_means)
|
| 223 |
+
for j in range(m):
|
| 224 |
+
x = G[:, j]
|
| 225 |
+
x_res = x - LinearRegression().fit(g_means, x).predict(g_means)
|
| 226 |
+
if x_res.std() < 1e-8:
|
| 227 |
+
continue
|
| 228 |
+
slope, intercept, r, p, se = stats.linregress(x_res, y_res)
|
| 229 |
+
pvals[j] = p
|
| 230 |
+
betas[j] = slope
|
| 231 |
+
return pvals, betas
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
def blink_gwas(y, G):
|
| 235 |
+
"""Model 5 β BLINK-inspired (Bayesian-Likelihood iterative, simplified)."""
|
| 236 |
+
n, m = G.shape
|
| 237 |
+
pvals = np.ones(m)
|
| 238 |
+
betas = np.zeros(m)
|
| 239 |
+
# Iterative: start with OLS, then add top hits as covariates
|
| 240 |
+
ols_p, ols_b = ols_gwas(y, G)
|
| 241 |
+
# Use top 2 hits as fixed covariates
|
| 242 |
+
top_idx = np.argsort(ols_p)[:min(2, m)]
|
| 243 |
+
covars = G[:, top_idx] if len(top_idx) > 0 else np.ones((n, 1))
|
| 244 |
+
reg = LinearRegression().fit(covars, y)
|
| 245 |
+
y_adj = y - reg.predict(covars)
|
| 246 |
+
for j in range(m):
|
| 247 |
+
x = G[:, j]
|
| 248 |
+
if x.std() < 1e-8:
|
| 249 |
+
continue
|
| 250 |
+
slope, intercept, r, p, se = stats.linregress(x, y_adj)
|
| 251 |
+
pvals[j] = p
|
| 252 |
+
betas[j] = slope
|
| 253 |
+
return pvals, betas
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
def farm_cpu_gwas(y, G, K):
|
| 257 |
+
"""Model 6 β FarmCPU-inspired (Fixed & Random Model Circulating Probability Unification)."""
|
| 258 |
+
n, m = G.shape
|
| 259 |
+
pvals = np.ones(m)
|
| 260 |
+
betas = np.zeros(m)
|
| 261 |
+
# Step 1: MLM step
|
| 262 |
+
mlm_p, mlm_b = mlm_gwas(y, G, K)
|
| 263 |
+
# Step 2: Top signals as pseudo-QTNs
|
| 264 |
+
sig_idx = np.argsort(mlm_p)[:min(3, m)]
|
| 265 |
+
pseudo = G[:, sig_idx] if len(sig_idx) else np.ones((n, 1))
|
| 266 |
+
# Step 3: Fixed-effect model using pseudo-QTNs
|
| 267 |
+
reg = LinearRegression().fit(pseudo, y)
|
| 268 |
+
y_adj = y - reg.predict(pseudo)
|
| 269 |
+
for j in range(m):
|
| 270 |
+
x = G[:, j]
|
| 271 |
+
if x.std() < 1e-8:
|
| 272 |
+
continue
|
| 273 |
+
slope, intercept, r, p, se = stats.linregress(x, y_adj)
|
| 274 |
+
pvals[j] = p
|
| 275 |
+
betas[j] = slope
|
| 276 |
+
return pvals, betas
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
# βββββββββββββββββββββββββββ PLOTTING FUNCTIONS βββββββββββββββββββββββ
|
| 280 |
+
|
| 281 |
+
def fig_to_pil(fig):
|
| 282 |
+
buf = io.BytesIO()
|
| 283 |
+
fig.savefig(buf, format="png", dpi=150, bbox_inches="tight",
|
| 284 |
+
facecolor=fig.get_facecolor())
|
| 285 |
+
buf.seek(0)
|
| 286 |
+
from PIL import Image
|
| 287 |
+
return Image.open(buf).copy()
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
# ββ 1. Manhattan Plot ββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 291 |
+
def plot_manhattan(pvals, chroms, positions, title="Manhattan Plot"):
|
| 292 |
+
fig, ax = plt.subplots(figsize=(14, 5))
|
| 293 |
+
style_fig(fig)
|
| 294 |
+
ax = fig.axes[0]
|
| 295 |
+
|
| 296 |
+
sig_line = -np.log10(5e-8)
|
| 297 |
+
sug_line = -np.log10(1e-5)
|
| 298 |
+
log_p = -np.log10(np.clip(pvals, 1e-300, 1))
|
| 299 |
+
|
| 300 |
+
chrom_list = sorted(set(chroms))
|
| 301 |
+
palette = [ACCENT1, ACCENT2, ACCENT3, GOLD, "#ff9100", "#e040fb",
|
| 302 |
+
"#64ffda", "#ff6d00", "#40c4ff", "#69f0ae",
|
| 303 |
+
"#ffab40", "#ea80fc"]
|
| 304 |
+
chrom_colors = {c: palette[i % len(palette)] for i, c in enumerate(chrom_list)}
|
| 305 |
+
|
| 306 |
+
x_offset = 0
|
| 307 |
+
tick_pos = []
|
| 308 |
+
tick_lab = []
|
| 309 |
+
x_coords = np.zeros(len(pvals))
|
| 310 |
+
|
| 311 |
+
for ch in chrom_list:
|
| 312 |
+
mask = chroms == ch
|
| 313 |
+
pos = positions[mask]
|
| 314 |
+
order = np.argsort(pos)
|
| 315 |
+
x_vals = pos[order] - pos.min() + x_offset
|
| 316 |
+
x_coords[np.where(mask)[0][order]] = x_vals
|
| 317 |
+
mid = x_vals.mean() if len(x_vals) > 1 else x_vals[0]
|
| 318 |
+
tick_pos.append(mid)
|
| 319 |
+
tick_lab.append(f"Chr{ch}")
|
| 320 |
+
# shade alternate chromosomes
|
| 321 |
+
ax.axvspan(x_offset, x_offset + pos.max() - pos.min(),
|
| 322 |
+
alpha=0.05, color=chrom_colors[ch])
|
| 323 |
+
x_offset += (pos.max() - pos.min()) + max(positions) * 0.01
|
| 324 |
+
|
| 325 |
+
# Scatter
|
| 326 |
+
for ch in chrom_list:
|
| 327 |
+
mask = chroms == ch
|
| 328 |
+
ax.scatter(x_coords[mask], log_p[mask],
|
| 329 |
+
c=chrom_colors[ch], s=22, alpha=0.85,
|
| 330 |
+
edgecolors="none", zorder=3)
|
| 331 |
+
|
| 332 |
# Highlight significant
|
| 333 |
+
sig_mask = log_p >= sig_line
|
| 334 |
if sig_mask.any():
|
| 335 |
+
ax.scatter(x_coords[sig_mask], log_p[sig_mask],
|
| 336 |
+
c=GOLD, s=55, zorder=5, edgecolors="white",
|
| 337 |
+
linewidths=0.5, marker="*", label="Genome-wide significant")
|
| 338 |
+
|
| 339 |
+
ax.axhline(sig_line, color=ACCENT2, lw=1.2, ls="--", label="p = 5Γ10β»βΈ")
|
| 340 |
+
ax.axhline(sug_line, color=GOLD, lw=1.0, ls=":", label="p = 1Γ10β»β΅")
|
| 341 |
+
|
| 342 |
+
ax.set_xticks(tick_pos)
|
| 343 |
+
ax.set_xticklabels(tick_lab, fontsize=8, rotation=45)
|
| 344 |
+
ax.set_ylabel("βlogββ(p-value)", color=TEXT)
|
| 345 |
+
ax.set_title(title, fontsize=13, fontweight="bold", color=ACCENT1, pad=12)
|
| 346 |
+
ax.legend(fontsize=8, facecolor=PANEL, edgecolor=GRID_COL,
|
| 347 |
+
labelcolor=TEXT, loc="upper right")
|
| 348 |
+
ax.set_xlim(0, x_offset)
|
| 349 |
+
ax.set_ylim(0, max(log_p.max() + 0.5, sig_line + 1))
|
| 350 |
+
fig.tight_layout()
|
| 351 |
+
return fig
|
| 352 |
+
|
| 353 |
+
|
| 354 |
+
# ββ 2. QQ Plot ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 355 |
+
def plot_qq(pvals, title="QQ Plot"):
|
| 356 |
+
fig, ax = plt.subplots(figsize=(6, 6))
|
| 357 |
+
style_fig(fig)
|
| 358 |
+
ax = fig.axes[0]
|
| 359 |
+
|
| 360 |
+
n = len(pvals)
|
| 361 |
+
obs = np.sort(-np.log10(np.clip(pvals, 1e-300, 1)))[::-1]
|
| 362 |
+
exp = -np.log10(np.linspace(1/n, 1, n)[::-1])
|
| 363 |
+
|
| 364 |
+
# Confidence band
|
| 365 |
+
ci_lower = -np.log10(stats.beta.ppf(0.975, np.arange(1, n + 1),
|
| 366 |
+
np.arange(n, 0, -1)))
|
| 367 |
+
ci_upper = -np.log10(stats.beta.ppf(0.025, np.arange(1, n + 1),
|
| 368 |
+
np.arange(n, 0, -1)))
|
| 369 |
+
idx = np.argsort(exp)
|
| 370 |
+
ax.fill_between(exp[idx], ci_lower[idx], ci_upper[idx],
|
| 371 |
+
alpha=0.25, color=ACCENT1, label="95% CI")
|
| 372 |
+
|
| 373 |
+
ax.scatter(exp, obs, c=ACCENT1, s=30, edgecolors="none",
|
| 374 |
+
alpha=0.9, zorder=4)
|
| 375 |
+
max_val = max(exp.max(), obs.max()) + 0.3
|
| 376 |
+
ax.plot([0, max_val], [0, max_val], color=ACCENT2,
|
| 377 |
+
lw=1.5, ls="--", label="Expected")
|
| 378 |
+
|
| 379 |
+
lam = np.median(stats.chi2.ppf(1 - pvals, df=1)) / stats.chi2.ppf(0.5, df=1)
|
| 380 |
+
ax.text(0.05, 0.92, f"Ξ» (GC) = {lam:.4f}",
|
| 381 |
+
transform=ax.transAxes, color=GOLD, fontsize=11,
|
| 382 |
+
fontweight="bold")
|
| 383 |
+
|
| 384 |
+
ax.set_xlabel("Expected βlogββ(p)", color=TEXT)
|
| 385 |
+
ax.set_ylabel("Observed βlogββ(p)", color=TEXT)
|
| 386 |
+
ax.set_title(title, fontsize=13, fontweight="bold", color=ACCENT1, pad=10)
|
| 387 |
+
ax.legend(fontsize=9, facecolor=PANEL, edgecolor=GRID_COL, labelcolor=TEXT)
|
| 388 |
+
fig.tight_layout()
|
| 389 |
+
return fig
|
| 390 |
+
|
| 391 |
+
|
| 392 |
+
# ββ 3. PCA Plot βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 393 |
+
def plot_pca(G, y, sample_ids=None):
|
| 394 |
+
fig, axes = plt.subplots(1, 2, figsize=(13, 5))
|
| 395 |
+
style_fig(fig)
|
| 396 |
+
|
| 397 |
+
scaler = StandardScaler()
|
| 398 |
+
G_sc = scaler.fit_transform(G)
|
| 399 |
+
n_comp = min(5, G_sc.shape[0] - 1, G_sc.shape[1])
|
| 400 |
+
pca = PCA(n_components=n_comp)
|
| 401 |
+
pcs = pca.fit_transform(G_sc)
|
| 402 |
+
var_exp = pca.explained_variance_ratio_ * 100
|
| 403 |
+
|
| 404 |
+
# Scatter PC1 vs PC2
|
| 405 |
+
sc = axes[0].scatter(pcs[:, 0], pcs[:, 1], c=y,
|
| 406 |
+
cmap=LinearSegmentedColormap.from_list(
|
| 407 |
+
"gwas", [ACCENT2, ACCENT1, ACCENT3]),
|
| 408 |
+
s=80, edgecolors="white", linewidths=0.4, zorder=4)
|
| 409 |
+
cbar = fig.colorbar(sc, ax=axes[0], pad=0.02)
|
| 410 |
+
cbar.set_label("Phenotype", color=TEXT, fontsize=9)
|
| 411 |
+
cbar.ax.yaxis.set_tick_params(color=TEXT)
|
| 412 |
+
plt.setp(cbar.ax.yaxis.get_ticklabels(), color=TEXT)
|
| 413 |
+
|
| 414 |
+
if sample_ids is not None:
|
| 415 |
+
for i, sid in enumerate(sample_ids):
|
| 416 |
+
axes[0].annotate(str(sid), (pcs[i, 0], pcs[i, 1]),
|
| 417 |
+
textcoords="offset points", xytext=(4, 3),
|
| 418 |
+
fontsize=6, color=MUTED)
|
| 419 |
+
|
| 420 |
+
axes[0].set_xlabel(f"PC1 ({var_exp[0]:.1f}%)", color=TEXT)
|
| 421 |
+
axes[0].set_ylabel(f"PC2 ({var_exp[1]:.1f}%)" if n_comp > 1 else "PC2", color=TEXT)
|
| 422 |
+
axes[0].set_title("PCA β Population Structure", fontsize=12,
|
| 423 |
+
fontweight="bold", color=ACCENT1)
|
| 424 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 425 |
# Scree plot
|
| 426 |
+
axes[1].bar(range(1, n_comp + 1), var_exp,
|
| 427 |
+
color=[ACCENT1, ACCENT2, ACCENT3, GOLD, "#ff9100"][:n_comp],
|
| 428 |
+
edgecolor=DARK, linewidth=0.5, zorder=3)
|
| 429 |
+
axes[1].plot(range(1, n_comp + 1), np.cumsum(var_exp),
|
| 430 |
+
color=GOLD, marker="o", ms=5, lw=1.5, label="Cumulative")
|
| 431 |
+
axes[1].set_xlabel("Principal Component", color=TEXT)
|
| 432 |
+
axes[1].set_ylabel("Variance Explained (%)", color=TEXT)
|
| 433 |
+
axes[1].set_title("Scree Plot", fontsize=12, fontweight="bold", color=ACCENT1)
|
| 434 |
+
axes[1].legend(fontsize=9, facecolor=PANEL, edgecolor=GRID_COL, labelcolor=TEXT)
|
| 435 |
+
|
| 436 |
+
fig.tight_layout()
|
| 437 |
+
return fig
|
| 438 |
+
|
| 439 |
+
|
| 440 |
+
# ββ 4. LD Decay Plot ββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 441 |
+
def plot_ld_decay(G, positions, chroms, max_dist=None):
|
| 442 |
+
fig, axes = plt.subplots(1, 2, figsize=(13, 5))
|
| 443 |
+
style_fig(fig)
|
| 444 |
+
|
| 445 |
+
m = G.shape[1]
|
| 446 |
+
dists, r2s = [], []
|
| 447 |
+
chrom_list = sorted(set(chroms))
|
| 448 |
+
|
| 449 |
+
for ch in chrom_list:
|
| 450 |
+
idx = np.where(chroms == ch)[0]
|
| 451 |
+
if len(idx) < 2:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 452 |
continue
|
| 453 |
+
for i, j in itertools.combinations(idx, 2):
|
| 454 |
+
xi = G[:, i]; xj = G[:, j]
|
| 455 |
+
mask = ~(np.isnan(xi) | np.isnan(xj))
|
| 456 |
+
if mask.sum() < 4:
|
| 457 |
+
continue
|
| 458 |
+
r, p = stats.pearsonr(xi[mask], xj[mask])
|
| 459 |
+
d = abs(positions[j] - positions[i])
|
| 460 |
+
dists.append(d)
|
| 461 |
+
r2s.append(r ** 2)
|
| 462 |
+
|
| 463 |
+
dists = np.array(dists)
|
| 464 |
+
r2s = np.array(r2s)
|
| 465 |
+
|
| 466 |
+
if len(dists) == 0:
|
| 467 |
+
axes[0].text(0.5, 0.5, "Insufficient data for LD", transform=axes[0].transAxes,
|
| 468 |
+
ha="center", color=TEXT)
|
| 469 |
+
axes[1].text(0.5, 0.5, "Insufficient data for LD", transform=axes[1].transAxes,
|
| 470 |
+
ha="center", color=TEXT)
|
| 471 |
+
fig.tight_layout()
|
| 472 |
+
return fig
|
| 473 |
+
|
| 474 |
+
# Scatter + decay curve
|
| 475 |
+
axes[0].scatter(dists / 1000, r2s, alpha=0.4, s=18, color=ACCENT1,
|
| 476 |
+
edgecolors="none", zorder=3)
|
| 477 |
+
|
| 478 |
+
# Bin-based decay
|
| 479 |
+
n_bins = min(15, len(dists))
|
| 480 |
+
bin_edges = np.quantile(dists, np.linspace(0, 1, n_bins + 1))
|
| 481 |
+
bin_mid, bin_r2 = [], []
|
| 482 |
+
for k in range(n_bins):
|
| 483 |
+
mask = (dists >= bin_edges[k]) & (dists < bin_edges[k + 1])
|
| 484 |
+
if mask.sum() > 0:
|
| 485 |
+
bin_mid.append(np.mean(dists[mask]) / 1000)
|
| 486 |
+
bin_r2.append(np.mean(r2s[mask]))
|
| 487 |
+
|
| 488 |
+
axes[0].plot(bin_mid, bin_r2, color=ACCENT2, lw=2.5, zorder=5, label="Mean rΒ²")
|
| 489 |
+
axes[0].axhline(0.1, color=GOLD, ls=":", lw=1.2, label="rΒ² = 0.1 threshold")
|
| 490 |
+
axes[0].set_xlabel("Distance (kb)", color=TEXT)
|
| 491 |
+
axes[0].set_ylabel("rΒ² (LD)", color=TEXT)
|
| 492 |
+
axes[0].set_title("LD Decay", fontsize=12, fontweight="bold", color=ACCENT1)
|
| 493 |
+
axes[0].set_ylim(0, 1.05)
|
| 494 |
+
axes[0].legend(fontsize=9, facecolor=PANEL, edgecolor=GRID_COL, labelcolor=TEXT)
|
| 495 |
+
|
| 496 |
+
# LD heatmap
|
| 497 |
+
m2 = min(m, 20)
|
| 498 |
+
R = np.zeros((m2, m2))
|
| 499 |
+
for i in range(m2):
|
| 500 |
+
for j in range(m2):
|
| 501 |
+
if i == j:
|
| 502 |
+
R[i, j] = 1.0
|
| 503 |
+
continue
|
| 504 |
+
xi = G[:, i]; xj = G[:, j]
|
| 505 |
+
mask = ~(np.isnan(xi) | np.isnan(xj))
|
| 506 |
+
if mask.sum() < 3:
|
| 507 |
+
continue
|
| 508 |
+
r, _ = stats.pearsonr(xi[mask], xj[mask])
|
| 509 |
+
R[i, j] = r ** 2
|
| 510 |
+
|
| 511 |
+
cmap = LinearSegmentedColormap.from_list("ld", [DARK, ACCENT1, GOLD, ACCENT2])
|
| 512 |
+
im = axes[1].imshow(R, cmap=cmap, vmin=0, vmax=1, aspect="auto")
|
| 513 |
+
cbar = fig.colorbar(im, ax=axes[1], pad=0.02)
|
| 514 |
+
cbar.set_label("rΒ²", color=TEXT)
|
| 515 |
+
cbar.ax.yaxis.set_tick_params(color=TEXT)
|
| 516 |
+
plt.setp(cbar.ax.yaxis.get_ticklabels(), color=TEXT)
|
| 517 |
+
axes[1].set_title("LD Heatmap (first 20 SNPs)", fontsize=12,
|
| 518 |
+
fontweight="bold", color=ACCENT1)
|
| 519 |
+
axes[1].set_xlabel("SNP index", color=TEXT)
|
| 520 |
+
axes[1].set_ylabel("SNP index", color=TEXT)
|
| 521 |
+
|
| 522 |
+
fig.tight_layout()
|
| 523 |
+
return fig
|
| 524 |
+
|
| 525 |
+
|
| 526 |
+
# ββ 5. Effect Size / Beta Plot ββββββββββββββββββββββββββββββββββββββββ
|
| 527 |
+
def plot_effect_sizes(results_df, model_name):
|
| 528 |
+
fig, axes = plt.subplots(1, 2, figsize=(13, 5))
|
| 529 |
+
style_fig(fig)
|
| 530 |
+
|
| 531 |
+
df = results_df.sort_values("Beta", ascending=True).reset_index(drop=True)
|
| 532 |
+
colors = [ACCENT2 if b < 0 else ACCENT1 for b in df["Beta"]]
|
| 533 |
+
|
| 534 |
+
axes[0].barh(range(len(df)), df["Beta"], color=colors,
|
| 535 |
+
edgecolor=DARK, linewidth=0.3, zorder=3)
|
| 536 |
+
axes[0].axvline(0, color=TEXT, lw=0.8)
|
| 537 |
+
axes[0].set_yticks(range(len(df)))
|
| 538 |
+
axes[0].set_yticklabels([s[:18] for s in df["SNP"]], fontsize=7)
|
| 539 |
+
axes[0].set_xlabel("Effect Size (Ξ²)", color=TEXT)
|
| 540 |
+
axes[0].set_title(f"Effect Sizes β {model_name}", fontsize=11,
|
| 541 |
+
fontweight="bold", color=ACCENT1)
|
| 542 |
+
neg_p = mpatches.Patch(color=ACCENT2, label="Negative effect")
|
| 543 |
+
pos_p = mpatches.Patch(color=ACCENT1, label="Positive effect")
|
| 544 |
+
axes[0].legend(handles=[pos_p, neg_p], fontsize=8,
|
| 545 |
+
facecolor=PANEL, edgecolor=GRID_COL, labelcolor=TEXT)
|
| 546 |
+
|
| 547 |
+
# Volcano plot
|
| 548 |
+
log_p = -np.log10(np.clip(results_df["P_value"].values, 1e-300, 1))
|
| 549 |
+
betas = results_df["Beta"].values
|
| 550 |
+
sig_thr = -np.log10(0.05 / len(results_df))
|
| 551 |
+
colors2 = np.where(log_p >= sig_thr, GOLD,
|
| 552 |
+
np.where(betas > 0, ACCENT1, ACCENT2))
|
| 553 |
+
axes[1].scatter(betas, log_p, c=colors2, s=35, edgecolors="none",
|
| 554 |
+
alpha=0.85, zorder=4)
|
| 555 |
+
axes[1].axhline(sig_thr, color=GOLD, lw=1.2, ls="--",
|
| 556 |
+
label=f"Bonferroni (Ξ±=0.05)")
|
| 557 |
+
axes[1].axvline(0, color=TEXT, lw=0.7, ls=":")
|
| 558 |
+
axes[1].set_xlabel("Effect Size (Ξ²)", color=TEXT)
|
| 559 |
+
axes[1].set_ylabel("βlogββ(p)", color=TEXT)
|
| 560 |
+
axes[1].set_title("Volcano Plot", fontsize=11, fontweight="bold", color=ACCENT1)
|
| 561 |
+
axes[1].legend(fontsize=9, facecolor=PANEL, edgecolor=GRID_COL, labelcolor=TEXT)
|
| 562 |
+
|
| 563 |
+
fig.tight_layout()
|
| 564 |
+
return fig
|
| 565 |
+
|
| 566 |
+
|
| 567 |
+
# ββ 6. MAF Distribution βββββββββββββββββββββββββββββββββββββββββββββββ
|
| 568 |
+
def plot_maf(maf, snp_names):
|
| 569 |
+
fig, axes = plt.subplots(1, 2, figsize=(12, 5))
|
| 570 |
+
style_fig(fig)
|
| 571 |
+
|
| 572 |
+
axes[0].hist(maf, bins=20, color=ACCENT1, edgecolor=DARK,
|
| 573 |
+
linewidth=0.5, zorder=3)
|
| 574 |
+
axes[0].axvline(0.05, color=ACCENT2, lw=1.5, ls="--", label="MAF = 0.05")
|
| 575 |
+
axes[0].set_xlabel("Minor Allele Frequency", color=TEXT)
|
| 576 |
+
axes[0].set_ylabel("Count", color=TEXT)
|
| 577 |
+
axes[0].set_title("MAF Distribution", fontsize=12, fontweight="bold", color=ACCENT1)
|
| 578 |
+
axes[0].legend(fontsize=9, facecolor=PANEL, edgecolor=GRID_COL, labelcolor=TEXT)
|
| 579 |
+
|
| 580 |
+
# Bar per SNP
|
| 581 |
+
order = np.argsort(maf)[::-1]
|
| 582 |
+
bar_c = [ACCENT1 if m >= 0.05 else ACCENT2 for m in maf[order]]
|
| 583 |
+
axes[1].bar(range(len(maf)), maf[order], color=bar_c,
|
| 584 |
+
edgecolor=DARK, linewidth=0.3, zorder=3)
|
| 585 |
+
axes[1].axhline(0.05, color=GOLD, lw=1.2, ls=":", label="MAF threshold 0.05")
|
| 586 |
+
axes[1].set_xticks(range(len(maf)))
|
| 587 |
+
axes[1].set_xticklabels([snp_names[i][:12] for i in order],
|
| 588 |
+
rotation=90, fontsize=6)
|
| 589 |
+
axes[1].set_ylabel("MAF", color=TEXT)
|
| 590 |
+
axes[1].set_title("Per-SNP MAF", fontsize=12, fontweight="bold", color=ACCENT1)
|
| 591 |
+
axes[1].legend(fontsize=9, facecolor=PANEL, edgecolor=GRID_COL, labelcolor=TEXT)
|
| 592 |
+
|
| 593 |
+
fig.tight_layout()
|
| 594 |
+
return fig
|
| 595 |
+
|
| 596 |
+
|
| 597 |
+
# ββ 7. Phenotype Distribution βββββββββββββββββββββββββββββββββββββββββ
|
| 598 |
+
def plot_phenotype(y, sample_ids=None):
|
| 599 |
+
fig, axes = plt.subplots(1, 2, figsize=(12, 5))
|
| 600 |
+
style_fig(fig)
|
| 601 |
+
|
| 602 |
+
axes[0].hist(y, bins=15, color=ACCENT1, edgecolor=DARK,
|
| 603 |
+
linewidth=0.5, zorder=3, alpha=0.85)
|
| 604 |
+
mn, sd = y.mean(), y.std()
|
| 605 |
+
axes[0].axvline(mn, color=ACCENT2, lw=1.5, ls="--", label=f"Mean={mn:.2f}")
|
| 606 |
+
axes[0].axvline(mn - sd, color=GOLD, lw=1.0, ls=":", label=f"Β±1SD")
|
| 607 |
+
axes[0].axvline(mn + sd, color=GOLD, lw=1.0, ls=":")
|
| 608 |
+
axes[0].set_xlabel("Phenotype Value", color=TEXT)
|
| 609 |
+
axes[0].set_ylabel("Frequency", color=TEXT)
|
| 610 |
+
axes[0].set_title("Phenotype Distribution", fontsize=12, fontweight="bold", color=ACCENT1)
|
| 611 |
+
axes[0].legend(fontsize=9, facecolor=PANEL, edgecolor=GRID_COL, labelcolor=TEXT)
|
| 612 |
+
|
| 613 |
+
# Box + scatter
|
| 614 |
+
bp = axes[1].boxplot(y, vert=True, patch_artist=True,
|
| 615 |
+
medianprops=dict(color=ACCENT2, lw=2))
|
| 616 |
+
for patch in bp["boxes"]:
|
| 617 |
+
patch.set_facecolor(ACCENT1 + "55")
|
| 618 |
+
patch.set_edgecolor(ACCENT1)
|
| 619 |
+
jitter = np.random.uniform(-0.1, 0.1, size=len(y))
|
| 620 |
+
axes[1].scatter(1 + jitter, y, color=GOLD, s=30,
|
| 621 |
+
alpha=0.8, zorder=5, edgecolors="none")
|
| 622 |
+
axes[1].set_xticks([1])
|
| 623 |
+
axes[1].set_xticklabels(["Phenotype"])
|
| 624 |
+
axes[1].set_ylabel("Value", color=TEXT)
|
| 625 |
+
axes[1].set_title("Box Plot", fontsize=12, fontweight="bold", color=ACCENT1)
|
| 626 |
+
fig.tight_layout()
|
| 627 |
+
return fig
|
| 628 |
+
|
| 629 |
+
|
| 630 |
+
# ββ 8. Results Summary Table ββββββββββββββββββββββββββββββββββββββββββ
|
| 631 |
+
def make_results_table(pvals, betas, snp_names, chroms, positions, model_name):
|
| 632 |
+
bonferroni = 0.05 / len(pvals)
|
| 633 |
+
df = pd.DataFrame({
|
| 634 |
+
"SNP" : snp_names,
|
| 635 |
+
"Chr" : chroms,
|
| 636 |
+
"Pos" : positions,
|
| 637 |
+
"Beta" : np.round(betas, 5),
|
| 638 |
+
"P_value" : pvals,
|
| 639 |
+
"-log10P" : np.round(-np.log10(np.clip(pvals, 1e-300, 1)), 4),
|
| 640 |
+
"Sig" : ["***" if p < bonferroni else ("**" if p < 0.001 else
|
| 641 |
+
("*" if p < 0.05 else "")) for p in pvals],
|
| 642 |
+
}).sort_values("P_value").reset_index(drop=True)
|
| 643 |
+
return df
|
| 644 |
+
|
| 645 |
+
|
| 646 |
+
# βββββββββββββββββββββββββββ MAIN PIPELINE ββββββββββββββββββββββββββββ
|
| 647 |
+
|
| 648 |
+
def run_gwas(file_obj, text_input, selected_models, maf_threshold):
|
| 649 |
+
"""Master function called by Gradio."""
|
| 650 |
try:
|
| 651 |
+
df, snp_cols = parse_data(file_obj, text_input)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 652 |
except Exception as e:
|
| 653 |
+
return [None] * 12 + [f"β Data parsing error: {e}"]
|
| 654 |
+
|
| 655 |
+
y = df["Phenotype"].values.astype(float)
|
| 656 |
+
ids = df["ID"].values
|
| 657 |
+
G_raw = df[snp_cols].values.astype(float)
|
| 658 |
+
G = impute_genotypes(G_raw)
|
| 659 |
+
n, m = G.shape
|
| 660 |
+
|
| 661 |
+
chroms, positions = parse_marker_info(snp_cols)
|
| 662 |
+
maf_vals = compute_maf(G)
|
| 663 |
+
|
| 664 |
+
# MAF filter
|
| 665 |
+
maf_thr = float(maf_threshold)
|
| 666 |
+
keep = maf_vals >= maf_thr
|
| 667 |
+
if keep.sum() < 2:
|
| 668 |
+
keep = np.ones(m, dtype=bool)
|
| 669 |
+
G_filt = G[:, keep]
|
| 670 |
+
maf_filt = maf_vals[keep]
|
| 671 |
+
snp_filt = np.array(snp_cols)[keep]
|
| 672 |
+
chr_filt = chroms[keep]
|
| 673 |
+
pos_filt = positions[keep]
|
| 674 |
+
|
| 675 |
+
# Kinship
|
| 676 |
+
K = build_kinship(G_filt)
|
| 677 |
+
|
| 678 |
+
# ββ Run selected models
|
| 679 |
+
model_funcs = {
|
| 680 |
+
"OLS (Simple Linear Regression)": lambda: ols_gwas(y, G_filt),
|
| 681 |
+
"MLM (Mixed Linear Model)": lambda: mlm_gwas(y, G_filt, K),
|
| 682 |
+
"GLM (PCA-corrected)": lambda: glm_gwas(y, G_filt),
|
| 683 |
+
"Compressed MLM": lambda: compressed_mlm_gwas(y, G_filt, K),
|
| 684 |
+
"BLINK": lambda: blink_gwas(y, G_filt),
|
| 685 |
+
"FarmCPU": lambda: farm_cpu_gwas(y, G_filt, K),
|
| 686 |
+
}
|
| 687 |
+
|
| 688 |
+
# Default: run all if none selected
|
| 689 |
+
models_to_run = selected_models if selected_models else list(model_funcs.keys())
|
| 690 |
+
|
| 691 |
+
all_results = {}
|
| 692 |
+
primary_p = None
|
| 693 |
+
primary_b = None
|
| 694 |
+
primary_name = None
|
| 695 |
+
|
| 696 |
+
for mname in models_to_run:
|
| 697 |
+
if mname in model_funcs:
|
| 698 |
+
p, b = model_funcs[mname]()
|
| 699 |
+
all_results[mname] = (p, b)
|
| 700 |
+
if primary_p is None:
|
| 701 |
+
primary_p = p; primary_b = b; primary_name = mname
|
| 702 |
+
|
| 703 |
+
if primary_p is None:
|
| 704 |
+
return [None] * 12 + ["β No models selected or run."]
|
| 705 |
+
|
| 706 |
+
# ββ Build plots
|
| 707 |
+
fig_pheno = plot_phenotype(y, ids)
|
| 708 |
+
fig_maf = plot_maf(maf_vals, snp_cols)
|
| 709 |
+
fig_pca = plot_pca(G_filt, y, ids)
|
| 710 |
+
fig_ld = plot_ld_decay(G_filt, pos_filt, chr_filt)
|
| 711 |
+
fig_manh = plot_manhattan(primary_p, chr_filt, pos_filt,
|
| 712 |
+
title=f"Manhattan β {primary_name}")
|
| 713 |
+
fig_qq = plot_qq(primary_p, title=f"QQ Plot β {primary_name}")
|
| 714 |
+
|
| 715 |
+
res_df = make_results_table(primary_p, primary_b, snp_filt,
|
| 716 |
+
chr_filt, pos_filt, primary_name)
|
| 717 |
+
fig_eff = plot_effect_sizes(res_df, primary_name)
|
| 718 |
+
|
| 719 |
+
# Multi-model comparison QQ
|
| 720 |
+
fig_multi = None
|
| 721 |
+
if len(all_results) > 1:
|
| 722 |
+
fig_multi, ax = plt.subplots(figsize=(8, 6))
|
| 723 |
+
style_fig(fig_multi)
|
| 724 |
+
ax = fig_multi.axes[0]
|
| 725 |
+
colors_m = [ACCENT1, ACCENT2, ACCENT3, GOLD, "#ff9100", "#e040fb"]
|
| 726 |
+
for idx2, (mn, (p2, _)) in enumerate(all_results.items()):
|
| 727 |
+
n2 = len(p2)
|
| 728 |
+
obs2 = np.sort(-np.log10(np.clip(p2, 1e-300, 1)))[::-1]
|
| 729 |
+
exp2 = -np.log10(np.linspace(1/n2, 1, n2)[::-1])
|
| 730 |
+
ax.plot(np.sort(exp2), np.sort(obs2),
|
| 731 |
+
color=colors_m[idx2 % len(colors_m)], lw=1.8,
|
| 732 |
+
label=mn[:28], alpha=0.9)
|
| 733 |
+
ax.plot([0, obs2.max()], [0, obs2.max()],
|
| 734 |
+
color=TEXT, lw=1, ls="--")
|
| 735 |
+
ax.set_xlabel("Expected βlogββ(p)", color=TEXT)
|
| 736 |
+
ax.set_ylabel("Observed βlogββ(p)", color=TEXT)
|
| 737 |
+
ax.set_title("Multi-Model QQ Comparison", fontsize=12,
|
| 738 |
+
fontweight="bold", color=ACCENT1)
|
| 739 |
+
ax.legend(fontsize=7, facecolor=PANEL, edgecolor=GRID_COL, labelcolor=TEXT)
|
| 740 |
+
fig_multi.tight_layout()
|
| 741 |
+
|
| 742 |
+
# ββ Summary text
|
| 743 |
+
bonf = 0.05 / len(primary_p)
|
| 744 |
+
n_sig = (primary_p < bonf).sum()
|
| 745 |
+
n_sug = ((primary_p < 1e-5) & (primary_p >= bonf)).sum()
|
| 746 |
+
lam = np.median(stats.chi2.ppf(1 - np.clip(primary_p, 1e-10, 1), df=1)) / stats.chi2.ppf(0.5, df=1)
|
| 747 |
+
|
| 748 |
+
summary = f"""
|
| 749 |
+
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 750 |
+
β GWAS ANALYSIS SUMMARY β
|
| 751 |
+
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ£
|
| 752 |
+
Samples : {n}
|
| 753 |
+
SNPs (raw) : {m}
|
| 754 |
+
SNPs (after MAFβ₯{maf_thr:.2f}) : {G_filt.shape[1]}
|
| 755 |
+
Models run : {', '.join(all_results.keys())}
|
| 756 |
+
Primary model : {primary_name}
|
| 757 |
+
|
| 758 |
+
Bonferroni threshold : {bonf:.2e}
|
| 759 |
+
Genome-wide sig hits : {n_sig}
|
| 760 |
+
Suggestive hits : {n_sug}
|
| 761 |
+
Genomic inflation Ξ» : {lam:.4f}
|
| 762 |
+
|
| 763 |
+
Top 5 SNPs ({primary_name}):
|
| 764 |
+
{res_df[['SNP','Chr','Pos','Beta','P_value','Sig']].head(5).to_string(index=False)}
|
| 765 |
+
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 766 |
+
""".strip()
|
| 767 |
+
|
| 768 |
+
img_pheno = fig_to_pil(fig_pheno)
|
| 769 |
+
img_maf = fig_to_pil(fig_maf)
|
| 770 |
+
img_pca = fig_to_pil(fig_pca)
|
| 771 |
+
img_ld = fig_to_pil(fig_ld)
|
| 772 |
+
img_manh = fig_to_pil(fig_manh)
|
| 773 |
+
img_qq = fig_to_pil(fig_qq)
|
| 774 |
+
img_eff = fig_to_pil(fig_eff)
|
| 775 |
+
img_multi = fig_to_pil(fig_multi) if fig_multi else None
|
| 776 |
+
|
| 777 |
+
plt.close("all")
|
| 778 |
+
|
| 779 |
+
return (img_pheno, img_maf, img_pca, img_ld,
|
| 780 |
+
img_manh, img_qq, img_eff, img_multi,
|
| 781 |
+
res_df, summary)
|
| 782 |
+
|
| 783 |
+
|
| 784 |
+
# βββββββββββββββββββββββββββ GRADIO UI βββββββββββββββββββββββββββββββ
|
| 785 |
+
|
| 786 |
+
SAMPLE_DATA = """\
|
| 787 |
+
ID,Phenotype,chr1_134521_LOC_Os01g01280,chr1_134810_LOC_Os01g01280,chr1_178766_LOC_Os01g01360,chr1_210328_LOC_Os01g01420,chr1_216213_LOC_Os01g01430,chr1_216683_LOC_Os01g01430,chr1_216716_LOC_Os01g01430,chr1_216965_LOC_Os01g01430
|
| 788 |
+
IRRI-1,25.34,0,0,0,2,2,-1,0,0
|
| 789 |
+
IRRI-75,23.34,0,0,0,0,0,-1,-1,0
|
| 790 |
+
IRRI-84,26.67,2,0,2,0,0,-1,-1,0
|
| 791 |
+
IRRI-93,23,0,0,0,1,0,-1,0,2
|
| 792 |
+
IRRI-9,28.34,0,0,0,0,0,2,0,0
|
| 793 |
+
IRRI-17,18.67,0,0,0,0,0,2,0,0
|
| 794 |
+
IRRI-25,20,2,0,2,0,0,-1,-1,0
|
| 795 |
+
IRRI-34,37,0,0,0,0,0,2,0,0
|
| 796 |
+
IRRI-42,30.67,0,0,0,0,0,2,0,0
|
| 797 |
+
IRRI-50,22,0,0,0,2,2,-1,0,0
|
| 798 |
+
"""
|
| 799 |
+
|
| 800 |
+
CSS = """
|
| 801 |
+
body, .gradio-container {
|
| 802 |
+
background: #0d0f1a !important;
|
| 803 |
+
font-family: 'JetBrains Mono', 'Fira Code', monospace !important;
|
| 804 |
+
color: #ccd6f6 !important;
|
| 805 |
+
}
|
| 806 |
+
.gr-panel, .gr-box, .gr-form {
|
| 807 |
+
background: #131626 !important;
|
| 808 |
+
border: 1px solid #1e2340 !important;
|
| 809 |
+
border-radius: 8px !important;
|
| 810 |
+
}
|
| 811 |
+
h1, h2, h3 { color: #00e5ff !important; }
|
| 812 |
+
label { color: #8892b0 !important; font-size: 0.85rem !important; }
|
| 813 |
+
.gr-button-primary {
|
| 814 |
+
background: linear-gradient(135deg, #00e5ff, #b2ff59) !important;
|
| 815 |
+
color: #0d0f1a !important;
|
| 816 |
+
font-weight: 700 !important;
|
| 817 |
+
border: none !important;
|
| 818 |
+
border-radius: 6px !important;
|
| 819 |
+
}
|
| 820 |
+
.gr-button-secondary {
|
| 821 |
+
background: #1e2340 !important;
|
| 822 |
+
color: #ccd6f6 !important;
|
| 823 |
+
border: 1px solid #00e5ff44 !important;
|
| 824 |
+
border-radius: 6px !important;
|
| 825 |
+
}
|
| 826 |
+
textarea, input[type=text], input[type=number] {
|
| 827 |
+
background: #0d0f1a !important;
|
| 828 |
+
color: #ccd6f6 !important;
|
| 829 |
+
border: 1px solid #1e2340 !important;
|
| 830 |
+
border-radius: 4px !important;
|
| 831 |
+
}
|
| 832 |
+
.gr-check-radio { accent-color: #00e5ff !important; }
|
| 833 |
+
"""
|
| 834 |
+
|
| 835 |
+
MODELS = [
|
| 836 |
+
"OLS (Simple Linear Regression)",
|
| 837 |
+
"MLM (Mixed Linear Model)",
|
| 838 |
+
"GLM (PCA-corrected)",
|
| 839 |
+
"Compressed MLM",
|
| 840 |
+
"BLINK",
|
| 841 |
+
"FarmCPU",
|
| 842 |
+
]
|
| 843 |
+
|
| 844 |
+
with gr.Blocks(css=CSS, title="GWAS Pipeline") as demo:
|
| 845 |
+
|
| 846 |
+
gr.Markdown("""
|
| 847 |
+
# 𧬠GWAS Analysis Pipeline
|
| 848 |
+
### Genome-Wide Association Study β Full Statistical Suite
|
| 849 |
+
*Supports CSV/TSV genotype matrices Β· 6 statistical models Β· Publication-quality plots*
|
| 850 |
+
---
|
| 851 |
+
""")
|
| 852 |
+
|
| 853 |
with gr.Row():
|
| 854 |
with gr.Column(scale=1):
|
| 855 |
+
gr.Markdown("### β Input Data")
|
| 856 |
+
file_in = gr.File(label="Upload CSV/TSV file", file_types=[".csv", ".tsv", ".txt"])
|
| 857 |
+
text_in = gr.Textbox(label="Or paste CSV data here",
|
| 858 |
+
placeholder="Paste your CSVβ¦",
|
| 859 |
+
lines=6, value=SAMPLE_DATA)
|
| 860 |
+
|
| 861 |
+
gr.Markdown("### β‘ Models to Run")
|
| 862 |
+
model_sel = gr.CheckboxGroup(choices=MODELS, value=MODELS,
|
| 863 |
+
label="Select statistical models")
|
| 864 |
+
|
| 865 |
+
gr.Markdown("### β’ Filters")
|
| 866 |
+
maf_thr = gr.Slider(minimum=0.0, maximum=0.5, value=0.0, step=0.01,
|
| 867 |
+
label="MAF threshold")
|
| 868 |
+
|
| 869 |
+
run_btn = gr.Button("π Run GWAS", variant="primary")
|
| 870 |
+
clr_btn = gr.Button("π Clear", variant="secondary")
|
| 871 |
+
|
| 872 |
+
with gr.Column(scale=3):
|
| 873 |
+
gr.Markdown("### π Results")
|
| 874 |
+
summary_out = gr.Textbox(label="Summary", lines=20, interactive=False)
|
| 875 |
+
|
| 876 |
+
gr.Markdown("---")
|
| 877 |
+
|
| 878 |
+
with gr.Tabs():
|
| 879 |
+
with gr.Tab("π§ͺ Phenotype"):
|
| 880 |
+
img_pheno = gr.Image(label="Phenotype Distribution", type="pil")
|
| 881 |
+
with gr.Tab("π MAF"):
|
| 882 |
+
img_maf = gr.Image(label="Minor Allele Frequency", type="pil")
|
| 883 |
+
with gr.Tab("π΅ PCA"):
|
| 884 |
+
img_pca = gr.Image(label="Principal Component Analysis", type="pil")
|
| 885 |
+
with gr.Tab("π LD"):
|
| 886 |
+
img_ld = gr.Image(label="Linkage Disequilibrium", type="pil")
|
| 887 |
+
with gr.Tab("π Manhattan"):
|
| 888 |
+
img_manh = gr.Image(label="Manhattan Plot", type="pil")
|
| 889 |
+
with gr.Tab("π QQ Plot"):
|
| 890 |
+
img_qq = gr.Image(label="QQ Plot", type="pil")
|
| 891 |
+
with gr.Tab("β Effect Sizes"):
|
| 892 |
+
img_eff = gr.Image(label="Effect Sizes & Volcano", type="pil")
|
| 893 |
+
with gr.Tab("π Multi-Model QQ"):
|
| 894 |
+
img_multi = gr.Image(label="Multi-Model Comparison", type="pil")
|
| 895 |
+
with gr.Tab("π Top Hits Table"):
|
| 896 |
+
results_tbl = gr.Dataframe(label="GWAS Results (sorted by p-value)",
|
| 897 |
+
interactive=False)
|
| 898 |
+
|
| 899 |
+
def run_wrapper(f, t, m, maf):
|
| 900 |
+
out = run_gwas(f, t, m, maf)
|
| 901 |
+
if isinstance(out[-1], str) and out[-1].startswith("β"):
|
| 902 |
+
return [None]*8 + [None, out[-1]]
|
| 903 |
+
(ph, mf, pc, ld, mn, qq, ef, mu, df, summ) = out
|
| 904 |
+
return ph, mf, pc, ld, mn, qq, ef, mu, df, summ
|
| 905 |
+
|
| 906 |
run_btn.click(
|
| 907 |
+
fn=run_wrapper,
|
| 908 |
+
inputs=[file_in, text_in, model_sel, maf_thr],
|
| 909 |
+
outputs=[img_pheno, img_maf, img_pca, img_ld,
|
| 910 |
+
img_manh, img_qq, img_eff, img_multi,
|
| 911 |
+
results_tbl, summary_out],
|
| 912 |
)
|
| 913 |
+
|
| 914 |
+
def clear_all():
|
| 915 |
+
return [None]*9 + [""]
|
| 916 |
+
|
| 917 |
+
clr_btn.click(fn=clear_all,
|
| 918 |
+
outputs=[img_pheno, img_maf, img_pca, img_ld,
|
| 919 |
+
img_manh, img_qq, img_eff, img_multi,
|
| 920 |
+
results_tbl, summary_out])
|
| 921 |
+
|
| 922 |
+
gr.Markdown("""
|
| 923 |
+
---
|
| 924 |
+
**Models implemented:** OLS Β· Mixed Linear Model (MLM) Β· PCA-corrected GLM Β· Compressed MLM Β· BLINK Β· FarmCPU
|
| 925 |
+
**Plots:** Phenotype distribution Β· MAF Β· PCA + Scree Β· LD Decay + Heatmap Β· Manhattan Β· QQ Β· Effect sizes Β· Volcano Β· Multi-model QQ
|
| 926 |
+
""")
|
| 927 |
|
| 928 |
if __name__ == "__main__":
|
| 929 |
+
demo.launch(share=False, server_port=7860)
|