Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,13 +1,15 @@
|
|
| 1 |
# -*- coding: utf-8 -*-
|
| 2 |
"""
|
| 3 |
-
GWAS Pipeline
|
| 4 |
Features:
|
|
|
|
| 5 |
- 6 GWAS models (Linear, Mixed, ElasticNet, Lasso, Ridge, Random Forest)
|
| 6 |
-
-
|
|
|
|
| 7 |
- LD decay plot in Mb
|
| 8 |
-
- Circos plot
|
| 9 |
-
-
|
| 10 |
-
-
|
| 11 |
"""
|
| 12 |
|
| 13 |
import gradio as gr
|
|
@@ -16,205 +18,532 @@ import numpy as np
|
|
| 16 |
import matplotlib
|
| 17 |
matplotlib.use('Agg')
|
| 18 |
import matplotlib.pyplot as plt
|
| 19 |
-
from matplotlib.patches import Circle
|
| 20 |
import matplotlib.patches as mpatches
|
| 21 |
-
from matplotlib.
|
| 22 |
import seaborn as sns
|
| 23 |
from scipy import stats
|
| 24 |
from scipy.spatial.distance import pdist, squareform
|
| 25 |
from scipy.optimize import curve_fit
|
| 26 |
import os, warnings, tempfile, zipfile, io
|
| 27 |
-
from sklearn.linear_model import ElasticNetCV, LassoCV, RidgeCV
|
| 28 |
-
from sklearn.ensemble import RandomForestRegressor
|
| 29 |
from sklearn.preprocessing import StandardScaler
|
| 30 |
-
from sklearn.model_selection import cross_val_score, KFold
|
| 31 |
-
from sklearn.metrics import mean_squared_error, r2_score
|
| 32 |
from sklearn.impute import SimpleImputer
|
|
|
|
|
|
|
|
|
|
| 33 |
import statsmodels.api as sm
|
| 34 |
from statsmodels.formula.api import mixedlm
|
| 35 |
-
import
|
| 36 |
warnings.filterwarnings('ignore')
|
| 37 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 39 |
-
# CUSTOM CSS FOR
|
| 40 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 41 |
|
| 42 |
-
|
| 43 |
<style>
|
| 44 |
-
|
| 45 |
-
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap');
|
| 46 |
|
| 47 |
* {
|
| 48 |
-
font-family: '
|
| 49 |
}
|
| 50 |
|
| 51 |
.gradio-container {
|
| 52 |
-
background: linear-gradient(135deg, #
|
| 53 |
padding: 20px !important;
|
| 54 |
}
|
| 55 |
|
| 56 |
.main-header {
|
| 57 |
-
background: linear-gradient(135deg, #
|
| 58 |
padding: 40px;
|
| 59 |
-
border-radius:
|
| 60 |
text-align: center;
|
| 61 |
margin-bottom: 30px;
|
| 62 |
-
box-shadow: 0 20px
|
|
|
|
| 63 |
}
|
| 64 |
|
| 65 |
.main-header h1 {
|
| 66 |
-
color:
|
| 67 |
font-size: 2.5em;
|
| 68 |
margin: 0;
|
| 69 |
-
font-weight:
|
| 70 |
-
|
| 71 |
}
|
| 72 |
|
| 73 |
.main-header p {
|
| 74 |
-
color:
|
| 75 |
font-size: 1.1em;
|
| 76 |
margin-top: 10px;
|
| 77 |
}
|
| 78 |
|
| 79 |
.section-header {
|
| 80 |
-
background: linear-gradient(135deg, #
|
| 81 |
-
padding:
|
| 82 |
-
border-radius:
|
| 83 |
margin: 20px 0 15px 0;
|
| 84 |
-
color:
|
| 85 |
font-weight: 600;
|
| 86 |
-
font-size: 1.
|
|
|
|
| 87 |
}
|
| 88 |
|
| 89 |
.card {
|
| 90 |
-
background:
|
| 91 |
border-radius: 15px;
|
| 92 |
padding: 20px;
|
| 93 |
margin: 10px 0;
|
| 94 |
-
box-shadow: 0 4px
|
| 95 |
-
|
|
|
|
| 96 |
}
|
| 97 |
|
| 98 |
.card:hover {
|
| 99 |
transform: translateY(-2px);
|
| 100 |
-
box-shadow: 0 8px
|
| 101 |
}
|
| 102 |
|
| 103 |
.stat-box {
|
| 104 |
-
background: linear-gradient(135deg, #
|
| 105 |
border-radius: 12px;
|
| 106 |
padding: 15px;
|
| 107 |
text-align: center;
|
| 108 |
margin: 10px;
|
|
|
|
| 109 |
}
|
| 110 |
|
| 111 |
.stat-number {
|
| 112 |
font-size: 2em;
|
| 113 |
font-weight: bold;
|
| 114 |
-
color: #
|
| 115 |
}
|
| 116 |
|
| 117 |
.stat-label {
|
| 118 |
font-size: 0.9em;
|
| 119 |
-
color: #
|
| 120 |
margin-top: 5px;
|
| 121 |
}
|
| 122 |
|
| 123 |
.run-btn {
|
| 124 |
-
background: linear-gradient(135deg, #
|
| 125 |
border: none;
|
| 126 |
-
color:
|
| 127 |
padding: 12px 30px;
|
| 128 |
border-radius: 25px;
|
| 129 |
font-weight: 600;
|
| 130 |
font-size: 1.1em;
|
| 131 |
cursor: pointer;
|
| 132 |
transition: all 0.3s;
|
|
|
|
| 133 |
}
|
| 134 |
|
| 135 |
.run-btn:hover {
|
| 136 |
-
transform: scale(1.
|
| 137 |
-
box-shadow: 0
|
|
|
|
| 138 |
}
|
| 139 |
|
| 140 |
footer {
|
| 141 |
text-align: center;
|
| 142 |
padding: 20px;
|
| 143 |
margin-top: 30px;
|
| 144 |
-
color:
|
| 145 |
-
background: rgba(
|
| 146 |
-
border-radius:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 147 |
}
|
| 148 |
</style>
|
| 149 |
"""
|
| 150 |
|
| 151 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 152 |
-
#
|
| 153 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 154 |
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
GRID_COLOR = "#E8DFF5"
|
| 158 |
-
TEXT_COLOR = "#3D2B6B"
|
| 159 |
-
ACCENT_COLOR = "#8B5CF6"
|
| 160 |
-
RED_COLOR = "#F472B6"
|
| 161 |
-
GOLD_COLOR = "#FBBF24"
|
| 162 |
-
GREEN_COLOR = "#34D399"
|
| 163 |
-
TEAL_COLOR = "#22D3EE"
|
| 164 |
-
ORANGE_COLOR = "#F97316"
|
| 165 |
-
PURPLE_COLOR = "#A855F7"
|
| 166 |
-
BLUE_COLOR = "#3B82F6"
|
| 167 |
-
PINK_COLOR = "#EC4899"
|
| 168 |
-
INDIGO_COLOR = "#6366F1"
|
| 169 |
-
|
| 170 |
-
CHROMOSOME_COLORS = [
|
| 171 |
-
"#FF6B6B", "#4ECDC4", "#45B7D1", "#96CEB4", "#FFEAA7",
|
| 172 |
-
"#DDA0DD", "#98D8C8", "#F7DC6F", "#BB8FCE", "#85C1E2",
|
| 173 |
-
"#F8C471", "#A9DFBF", "#F5B7B1", "#AED6F1", "#F9E79F",
|
| 174 |
-
"#D7BDE2", "#ABEBC6", "#FAD7A0", "#AED6F1", "#F1948A",
|
| 175 |
-
"#82E0AA", "#F5CBA7", "#C39BD3", "#76D7C4", "#F0B27A"
|
| 176 |
-
]
|
| 177 |
-
|
| 178 |
-
def set_plot_style():
|
| 179 |
-
"""Set consistent plot styling"""
|
| 180 |
plt.rcParams.update({
|
| 181 |
-
'figure.facecolor':
|
| 182 |
-
'axes.facecolor':
|
| 183 |
-
'axes.edgecolor':
|
| 184 |
-
'axes.labelcolor':
|
| 185 |
-
'axes.titlecolor':
|
| 186 |
-
'xtick.color':
|
| 187 |
-
'ytick.color':
|
| 188 |
-
'text.color':
|
| 189 |
-
'grid.color':
|
| 190 |
'grid.linewidth': 0.8,
|
| 191 |
-
'grid.alpha': 0.
|
| 192 |
'figure.dpi': 150,
|
| 193 |
-
'font.family': '
|
|
|
|
| 194 |
'axes.spines.top': False,
|
| 195 |
'axes.spines.right': False,
|
| 196 |
'legend.framealpha': 0.95,
|
| 197 |
-
'legend.edgecolor':
|
| 198 |
'legend.fancybox': True,
|
| 199 |
'legend.shadow': True,
|
|
|
|
| 200 |
})
|
| 201 |
|
| 202 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 203 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 204 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 205 |
|
| 206 |
def plot_manhattan_lod(marker_names, chromosomes, p_values, lod_scores,
|
| 207 |
sig_threshold, save_path):
|
| 208 |
"""Create Manhattan plot with LOD scores overlay"""
|
| 209 |
-
|
| 210 |
|
| 211 |
-
# Prepare data
|
| 212 |
unique_chroms = sorted(set(chromosomes),
|
| 213 |
key=lambda x: (int(x) if str(x).isdigit() else 999, str(x)))
|
| 214 |
log_p = -np.log10(np.array(p_values) + 1e-300)
|
| 215 |
|
| 216 |
# Calculate positions
|
| 217 |
-
GAP = max(
|
| 218 |
x_pos = np.zeros(len(marker_names))
|
| 219 |
chrom_to_idx = {}
|
| 220 |
|
|
@@ -235,9 +564,11 @@ def plot_manhattan_lod(marker_names, chromosomes, p_values, lod_scores,
|
|
| 235 |
# Create figure
|
| 236 |
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(20, 12),
|
| 237 |
gridspec_kw={'height_ratios': [2.5, 1]},
|
| 238 |
-
facecolor=
|
| 239 |
|
| 240 |
# Top plot: Manhattan
|
|
|
|
|
|
|
| 241 |
for i, ch in enumerate(unique_chroms):
|
| 242 |
idxs = chrom_to_idx.get(ch, [])
|
| 243 |
if not idxs:
|
|
@@ -245,57 +576,53 @@ def plot_manhattan_lod(marker_names, chromosomes, p_values, lod_scores,
|
|
| 245 |
x0 = x_pos[idxs[0]] - 0.5
|
| 246 |
x1 = x_pos[idxs[-1]] + 0.5
|
| 247 |
if i % 2 == 0:
|
| 248 |
-
ax1.axvspan(x0, x1, color=
|
| 249 |
|
| 250 |
# Plot points
|
| 251 |
-
significant_idx = np.where(p_values < sig_threshold)[0]
|
| 252 |
-
|
| 253 |
for i, ch in enumerate(unique_chroms):
|
| 254 |
idxs = chrom_to_idx.get(ch, [])
|
| 255 |
if not idxs:
|
| 256 |
continue
|
| 257 |
-
color =
|
| 258 |
|
| 259 |
-
# Non-significant
|
| 260 |
normal = [idx for idx in idxs if idx not in significant_idx]
|
| 261 |
if normal:
|
| 262 |
-
ax1.scatter(x_pos[normal], log_p[normal], c=color, s=
|
| 263 |
-
alpha=0.
|
| 264 |
|
| 265 |
-
# Significant
|
| 266 |
sig = [idx for idx in idxs if idx in significant_idx]
|
| 267 |
if sig:
|
| 268 |
-
ax1.scatter(x_pos[sig], log_p[sig], c=
|
| 269 |
-
alpha=0.
|
| 270 |
-
marker='D', zorder=3)
|
| 271 |
|
| 272 |
# Threshold lines
|
| 273 |
bonf_line = -np.log10(sig_threshold)
|
| 274 |
-
ax1.axhline(bonf_line, color=
|
| 275 |
-
linewidth=2, alpha=0.8, label=f'Bonferroni (
|
| 276 |
-
ax1.axhline(3, color=
|
| 277 |
alpha=0.8, label='LOD β₯ 3')
|
| 278 |
|
| 279 |
# Add LOD as secondary axis
|
| 280 |
ax1_twin = ax1.twinx()
|
| 281 |
lod_array = np.array(lod_scores)
|
| 282 |
-
ax1_twin.scatter(x_pos, lod_array, c=
|
| 283 |
marker='x', label='LOD Score', zorder=1)
|
| 284 |
-
ax1_twin.set_ylabel('LOD Score', fontsize=12, color=
|
| 285 |
-
ax1_twin.tick_params(axis='y', colors=
|
| 286 |
max_lod = lod_array.max() if len(lod_array) > 0 else 5
|
| 287 |
ax1_twin.set_ylim(0, max_lod * 1.15)
|
| 288 |
|
| 289 |
ax1.set_xlim(-GAP, offset)
|
| 290 |
ax1.set_ylim(bottom=0, top=log_p.max() * 1.15)
|
| 291 |
-
ax1.set_ylabel('-logββ(P-value)', fontsize=
|
| 292 |
-
ax1.set_xlabel('Chromosome', fontsize=
|
| 293 |
-
ax1.set_title('GWAS Manhattan Plot with LOD Scores', fontsize=
|
| 294 |
-
color=
|
| 295 |
ax1.grid(True, alpha=0.3)
|
| 296 |
ax1.legend(loc='upper right', fontsize=10)
|
| 297 |
|
| 298 |
-
# Set x-ticks
|
| 299 |
tick_positions = []
|
| 300 |
tick_labels = []
|
| 301 |
for ch in unique_chroms:
|
|
@@ -304,7 +631,7 @@ def plot_manhattan_lod(marker_names, chromosomes, p_values, lod_scores,
|
|
| 304 |
tick_positions.append(center)
|
| 305 |
tick_labels.append(str(ch))
|
| 306 |
ax1.set_xticks(tick_positions)
|
| 307 |
-
ax1.set_xticklabels(tick_labels, rotation=45, ha='right', fontsize=
|
| 308 |
|
| 309 |
# Bottom plot: LOD profile
|
| 310 |
for i, ch in enumerate(unique_chroms):
|
|
@@ -314,26 +641,26 @@ def plot_manhattan_lod(marker_names, chromosomes, p_values, lod_scores,
|
|
| 314 |
x0 = x_pos[idxs[0]] - 0.5
|
| 315 |
x1 = x_pos[idxs[-1]] + 0.5
|
| 316 |
if i % 2 == 0:
|
| 317 |
-
ax2.axvspan(x0, x1, color=
|
| 318 |
|
| 319 |
-
ax2.plot(x_pos, lod_array, color=
|
| 320 |
-
ax2.fill_between(x_pos, 0, lod_array, color=
|
| 321 |
-
ax2.axhline(3, color=
|
| 322 |
ax2.set_xlim(-GAP, offset)
|
| 323 |
-
ax2.set_ylabel('LOD Score', fontsize=12, color=
|
| 324 |
-
ax2.set_xlabel('Chromosome', fontsize=12, color=
|
| 325 |
ax2.set_ylim(0, max_lod * 1.15)
|
| 326 |
ax2.grid(True, alpha=0.3)
|
| 327 |
ax2.set_xticks(tick_positions)
|
| 328 |
-
ax2.set_xticklabels(tick_labels, rotation=45, ha='right', fontsize=
|
| 329 |
|
| 330 |
plt.tight_layout(pad=2)
|
| 331 |
-
plt.savefig(save_path, dpi=200, bbox_inches='tight', facecolor=
|
| 332 |
plt.close(fig)
|
| 333 |
|
| 334 |
def plot_ld_decay_mb(genotypes, chromosomes, positions, save_path, max_distance_mb=5):
|
| 335 |
"""Create LD decay plot with distances in Megabases"""
|
| 336 |
-
|
| 337 |
|
| 338 |
unique_chroms = sorted(set(chromosomes),
|
| 339 |
key=lambda x: (int(x) if str(x).isdigit() else 999, str(x)))
|
|
@@ -346,40 +673,33 @@ def plot_ld_decay_mb(genotypes, chromosomes, positions, save_path, max_distance_
|
|
| 346 |
if len(idxs) < 4:
|
| 347 |
continue
|
| 348 |
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
idxs = sorted(np.random.choice(idxs, 300, replace=False))
|
| 352 |
|
| 353 |
G = genotypes[:, idxs].copy()
|
| 354 |
pos_ch = [positions[i] for i in idxs]
|
| 355 |
-
|
| 356 |
-
# Convert positions to Mb if they're in bp
|
| 357 |
pos_mb = [p / 1_000_000 if p > 1000 else p for p in pos_ch]
|
| 358 |
|
| 359 |
-
# Calculate pairwise LD
|
| 360 |
for i in range(len(idxs)):
|
| 361 |
-
for j in range(i+1, min(i+
|
| 362 |
dist = abs(pos_mb[j] - pos_mb[i])
|
| 363 |
if dist > max_distance_mb:
|
| 364 |
continue
|
| 365 |
|
| 366 |
-
# Calculate rΒ²
|
| 367 |
r = np.corrcoef(G[:, i], G[:, j])[0, 1]
|
| 368 |
r2 = r**2 if not np.isnan(r) else 0
|
| 369 |
|
| 370 |
all_distances_mb.append(dist)
|
| 371 |
all_r2.append(r2)
|
| 372 |
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
ax.set_facecolor(PANEL_COLOR)
|
| 376 |
|
| 377 |
if all_distances_mb:
|
| 378 |
distances = np.array(all_distances_mb)
|
| 379 |
r2_values = np.array(all_r2)
|
| 380 |
|
| 381 |
-
|
| 382 |
-
bins = np.linspace(0, max_distance_mb, 50)
|
| 383 |
bin_centers = []
|
| 384 |
bin_means = []
|
| 385 |
bin_stds = []
|
|
@@ -391,7 +711,6 @@ def plot_ld_decay_mb(genotypes, chromosomes, positions, save_path, max_distance_
|
|
| 391 |
bin_means.append(np.mean(r2_values[mask]))
|
| 392 |
bin_stds.append(np.std(r2_values[mask]) / np.sqrt(mask.sum()))
|
| 393 |
|
| 394 |
-
# Exponential decay fit
|
| 395 |
def decay_func(x, a, b):
|
| 396 |
return a * np.exp(-b * x)
|
| 397 |
|
|
@@ -400,57 +719,51 @@ def plot_ld_decay_mb(genotypes, chromosomes, positions, save_path, max_distance_
|
|
| 400 |
p0=[1, 1], maxfev=5000)
|
| 401 |
x_fit = np.linspace(0, max_distance_mb, 100)
|
| 402 |
y_fit = decay_func(x_fit, *params)
|
| 403 |
-
ax.plot(x_fit, y_fit, '--', color=
|
| 404 |
label=f'Decay rate: {params[1]:.3f} Mbβ»ΒΉ')
|
| 405 |
|
| 406 |
-
# Half-decay distance
|
| 407 |
half_decay = np.log(2) / params[1] if params[1] > 0 else 0
|
| 408 |
if half_decay <= max_distance_mb:
|
| 409 |
-
ax.axvline(half_decay, color=
|
| 410 |
linewidth=2, alpha=0.8,
|
| 411 |
label=f'LD half-decay: {half_decay:.2f} Mb')
|
| 412 |
except:
|
| 413 |
pass
|
| 414 |
|
| 415 |
-
# Plot with error bars
|
| 416 |
ax.errorbar(bin_centers, bin_means, yerr=bin_stds,
|
| 417 |
-
fmt='o-', color=
|
| 418 |
-
markersize=
|
| 419 |
label='Mean rΒ²')
|
| 420 |
|
| 421 |
-
|
| 422 |
-
ax.axhline(0.2, color=RED_COLOR, linestyle=':', linewidth=1.5,
|
| 423 |
alpha=0.7, label='rΒ² = 0.2')
|
| 424 |
|
| 425 |
-
ax.set_xlabel('Distance (Megabases)', fontsize=13, color=
|
| 426 |
-
ax.set_ylabel('Linkage Disequilibrium (rΒ²)', fontsize=13, color=
|
| 427 |
-
ax.set_title('Linkage Disequilibrium Decay', fontsize=16, color=
|
| 428 |
ax.set_xlim(0, max_distance_mb)
|
| 429 |
ax.set_ylim(0, 1)
|
| 430 |
ax.legend(loc='upper right', fontsize=11, frameon=True)
|
| 431 |
ax.grid(True, alpha=0.3)
|
| 432 |
|
| 433 |
plt.tight_layout()
|
| 434 |
-
plt.savefig(save_path, dpi=200, bbox_inches='tight', facecolor=
|
| 435 |
plt.close(fig)
|
| 436 |
|
| 437 |
-
return {'mean_r2': np.mean(all_r2) if all_r2 else 0,
|
| 438 |
-
'n_pairs': len(all_r2)}
|
| 439 |
|
| 440 |
def plot_circos(chromosomes, p_values, lod_scores, significant_idx, save_path):
|
| 441 |
"""Create circos plot for chromosome visualization"""
|
| 442 |
-
|
| 443 |
|
| 444 |
unique_chroms = sorted(set(chromosomes),
|
| 445 |
key=lambda x: (int(x) if str(x).isdigit() else 999, str(x)))
|
| 446 |
n_chroms = len(unique_chroms)
|
| 447 |
|
| 448 |
-
# Create figure
|
| 449 |
fig, ax = plt.subplots(figsize=(12, 12), subplot_kw={'projection': 'polar'},
|
| 450 |
-
facecolor=
|
| 451 |
-
ax.set_facecolor(
|
| 452 |
|
| 453 |
-
# Calculate angles for chromosomes
|
| 454 |
angles = np.linspace(0, 2 * np.pi, n_chroms + 1)
|
| 455 |
radius = 1.0
|
| 456 |
|
|
@@ -460,19 +773,17 @@ def plot_circos(chromosomes, p_values, lod_scores, significant_idx, save_path):
|
|
| 460 |
theta_end = angles[i + 1]
|
| 461 |
theta_mid = (theta_start + theta_end) / 2
|
| 462 |
|
| 463 |
-
|
| 464 |
-
color = CHROMOSOME_COLORS[i % len(CHROMOSOME_COLORS)]
|
| 465 |
ax.bar(theta_mid, 0.2, width=2*np.pi/n_chroms - 0.05,
|
| 466 |
-
bottom=radius - 0.2, color=color, alpha=0.
|
| 467 |
|
| 468 |
-
# Chromosome label
|
| 469 |
ax.text(theta_mid, radius - 0.1, str(ch), ha='center', va='center',
|
| 470 |
-
fontsize=
|
| 471 |
|
| 472 |
# Calculate marker positions
|
| 473 |
-
marker_positions = []
|
| 474 |
marker_angles = []
|
| 475 |
marker_values = []
|
|
|
|
| 476 |
|
| 477 |
for i, ch in enumerate(unique_chroms):
|
| 478 |
chrom_idxs = [j for j, c in enumerate(chromosomes) if c == ch]
|
|
@@ -483,49 +794,38 @@ def plot_circos(chromosomes, p_values, lod_scores, significant_idx, save_path):
|
|
| 483 |
theta_end = angles[i + 1]
|
| 484 |
|
| 485 |
for idx in chrom_idxs:
|
| 486 |
-
# Position within chromosome
|
| 487 |
pos = (chrom_idxs.index(idx) / len(chrom_idxs)) if len(chrom_idxs) > 1 else 0.5
|
| 488 |
theta = theta_start + pos * (theta_end - theta_start)
|
| 489 |
marker_angles.append(theta)
|
| 490 |
marker_values.append(-np.log10(p_values[idx] + 1e-300))
|
| 491 |
marker_positions.append(idx)
|
| 492 |
|
| 493 |
-
# Plot markers as points
|
| 494 |
if marker_angles:
|
| 495 |
-
# Normalize values for radius
|
| 496 |
max_val = max(marker_values) if marker_values else 10
|
| 497 |
min_val = min(marker_values) if marker_values else 0
|
| 498 |
radii = 0.4 + 0.5 * (np.array(marker_values) - min_val) / (max_val - min_val + 1e-10)
|
| 499 |
|
| 500 |
-
|
| 501 |
-
colors = []
|
| 502 |
-
for i, pos in enumerate(marker_positions):
|
| 503 |
-
if pos in significant_idx:
|
| 504 |
-
colors.append(RED_COLOR)
|
| 505 |
-
else:
|
| 506 |
-
colors.append(ACCENT_COLOR)
|
| 507 |
|
| 508 |
-
ax.scatter(marker_angles, radii, c=colors, s=
|
| 509 |
|
| 510 |
# Add inner circle
|
| 511 |
inner_circle = Circle((0, 0), 0.3, transform=ax.transData._b,
|
| 512 |
-
facecolor=
|
| 513 |
ax.add_patch(inner_circle)
|
| 514 |
|
| 515 |
-
# Add center text
|
| 516 |
ax.text(0, 0, 'GWAS\nResults', ha='center', va='center',
|
| 517 |
-
fontsize=14, fontweight='
|
| 518 |
|
| 519 |
-
#
|
| 520 |
legend_elements = [
|
| 521 |
-
mpatches.Patch(color=
|
| 522 |
-
mpatches.Patch(color=
|
| 523 |
mpatches.Patch(color='white', edgecolor='black', label='Chromosomes')
|
| 524 |
]
|
| 525 |
ax.legend(handles=legend_elements, loc='center', bbox_to_anchor=(1.2, 0.5),
|
| 526 |
-
frameon=True, fontsize=10)
|
| 527 |
|
| 528 |
-
# Set polar properties
|
| 529 |
ax.set_theta_zero_location('N')
|
| 530 |
ax.set_theta_direction(-1)
|
| 531 |
ax.set_ylim(0, 1.2)
|
|
@@ -534,348 +834,23 @@ def plot_circos(chromosomes, p_values, lod_scores, significant_idx, save_path):
|
|
| 534 |
ax.spines['polar'].set_visible(False)
|
| 535 |
|
| 536 |
plt.title('Circos Plot - Chromosome-wide Association', fontsize=16,
|
| 537 |
-
color=
|
| 538 |
plt.tight_layout()
|
| 539 |
-
plt.savefig(save_path, dpi=200, bbox_inches='tight', facecolor=
|
| 540 |
-
plt.close(fig)
|
| 541 |
-
|
| 542 |
-
def plot_model_comparison(results_df, save_path):
|
| 543 |
-
"""Compare performance across all models"""
|
| 544 |
-
set_plot_style()
|
| 545 |
-
|
| 546 |
-
fig, axes = plt.subplots(2, 3, figsize=(18, 10), facecolor=BG_COLOR)
|
| 547 |
-
|
| 548 |
-
# 1. P-value correlations heatmap
|
| 549 |
-
ax1 = axes[0, 0]
|
| 550 |
-
models = ['LR_P', 'MLM_P', 'EN_P', 'LASSO_P', 'RIDGE_P', 'RF_P']
|
| 551 |
-
model_names = ['Linear', 'Mixed', 'ElasticNet', 'Lasso', 'Ridge', 'RandomForest']
|
| 552 |
-
|
| 553 |
-
available_models = [m for m in models if m in results_df.columns]
|
| 554 |
-
available_names = [model_names[models.index(m)] for m in available_models]
|
| 555 |
-
|
| 556 |
-
if len(available_models) > 1:
|
| 557 |
-
corr_matrix = np.zeros((len(available_models), len(available_models)))
|
| 558 |
-
for i, m1 in enumerate(available_models):
|
| 559 |
-
for j, m2 in enumerate(available_models):
|
| 560 |
-
corr_matrix[i, j] = results_df[m1].corr(results_df[m2])
|
| 561 |
-
|
| 562 |
-
im = ax1.imshow(corr_matrix, cmap='RdBu_r', vmin=-1, vmax=1, aspect='auto')
|
| 563 |
-
ax1.set_xticks(range(len(available_models)))
|
| 564 |
-
ax1.set_yticks(range(len(available_models)))
|
| 565 |
-
ax1.set_xticklabels(available_names, rotation=45, ha='right', fontsize=8)
|
| 566 |
-
ax1.set_yticklabels(available_names, fontsize=8)
|
| 567 |
-
|
| 568 |
-
for i in range(len(available_models)):
|
| 569 |
-
for j in range(len(available_models)):
|
| 570 |
-
ax1.text(j, i, f'{corr_matrix[i, j]:.2f}',
|
| 571 |
-
ha='center', va='center',
|
| 572 |
-
color='white' if abs(corr_matrix[i, j]) > 0.6 else 'black',
|
| 573 |
-
fontsize=9)
|
| 574 |
-
|
| 575 |
-
plt.colorbar(im, ax=ax1, shrink=0.8)
|
| 576 |
-
ax1.set_title('Model Correlation Matrix', fontsize=12, fontweight='bold')
|
| 577 |
-
|
| 578 |
-
# 2. Significant markers count
|
| 579 |
-
ax2 = axes[0, 1]
|
| 580 |
-
sig_counts = []
|
| 581 |
-
sig_models = []
|
| 582 |
-
for model in available_models:
|
| 583 |
-
if f'Significant_{model}' in results_df.columns:
|
| 584 |
-
sig_counts.append(results_df[f'Significant_{model}'].sum())
|
| 585 |
-
sig_models.append(model_names[models.index(model)])
|
| 586 |
-
|
| 587 |
-
if sig_counts:
|
| 588 |
-
bars = ax2.bar(range(len(sig_counts)), sig_counts,
|
| 589 |
-
color=[ACCENT_COLOR, TEAL_COLOR, GREEN_COLOR,
|
| 590 |
-
ORANGE_COLOR, PURPLE_COLOR, RED_COLOR][:len(sig_counts)],
|
| 591 |
-
alpha=0.7, edgecolor='white', linewidth=1.5)
|
| 592 |
-
ax2.set_xticks(range(len(sig_counts)))
|
| 593 |
-
ax2.set_xticklabels(sig_models, rotation=45, ha='right', fontsize=9)
|
| 594 |
-
ax2.set_ylabel('Number of Significant Markers', fontsize=11)
|
| 595 |
-
ax2.set_title('Significant Markers by Model', fontsize=12, fontweight='bold')
|
| 596 |
-
|
| 597 |
-
for bar, count in zip(bars, sig_counts):
|
| 598 |
-
ax2.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 0.5,
|
| 599 |
-
str(count), ha='center', va='bottom', fontsize=9)
|
| 600 |
-
|
| 601 |
-
# 3. Effect size distributions
|
| 602 |
-
ax3 = axes[0, 2]
|
| 603 |
-
colors = [ACCENT_COLOR, TEAL_COLOR, GREEN_COLOR, ORANGE_COLOR, PURPLE_COLOR, RED_COLOR]
|
| 604 |
-
for i, model in enumerate(available_models[:5]):
|
| 605 |
-
beta_col = f'{model}_Beta' if f'{model}_Beta' in results_df.columns else None
|
| 606 |
-
if beta_col:
|
| 607 |
-
ax3.hist(results_df[beta_col].dropna(), bins=30, alpha=0.5,
|
| 608 |
-
label=model_names[models.index(model)], color=colors[i % len(colors)])
|
| 609 |
-
ax3.set_xlabel('Effect Size', fontsize=11)
|
| 610 |
-
ax3.set_ylabel('Frequency', fontsize=11)
|
| 611 |
-
ax3.set_title('Effect Size Distributions', fontsize=12, fontweight='bold')
|
| 612 |
-
ax3.legend(fontsize=8)
|
| 613 |
-
ax3.grid(True, alpha=0.3)
|
| 614 |
-
|
| 615 |
-
# 4. LOD score comparison
|
| 616 |
-
ax4 = axes[1, 0]
|
| 617 |
-
lod_data = []
|
| 618 |
-
lod_models = []
|
| 619 |
-
for model in available_models:
|
| 620 |
-
lod_col = f'{model}_LOD' if f'{model}_LOD' in results_df.columns else None
|
| 621 |
-
if lod_col:
|
| 622 |
-
lod_data.append(results_df[lod_col].values)
|
| 623 |
-
lod_models.append(model_names[models.index(model)])
|
| 624 |
-
|
| 625 |
-
if lod_data:
|
| 626 |
-
bp = ax4.boxplot(lod_data, labels=lod_models, patch_artist=True)
|
| 627 |
-
for patch, color in zip(bp['boxes'], colors[:len(lod_data)]):
|
| 628 |
-
patch.set_facecolor(color)
|
| 629 |
-
patch.set_alpha(0.7)
|
| 630 |
-
ax4.axhline(3, color=RED_COLOR, linestyle='--', linewidth=1.5, label='LOD = 3')
|
| 631 |
-
ax4.set_ylabel('LOD Score', fontsize=11)
|
| 632 |
-
ax4.set_title('LOD Score Distribution by Model', fontsize=12, fontweight='bold')
|
| 633 |
-
ax4.legend(fontsize=9)
|
| 634 |
-
plt.setp(bp['xticklabels'], rotation=45, ha='right', fontsize=8)
|
| 635 |
-
|
| 636 |
-
# 5. Manhattan plot comparison (top markers)
|
| 637 |
-
ax5 = axes[1, 1]
|
| 638 |
-
if 'LR_LOD' in results_df.columns:
|
| 639 |
-
top_n = min(50, len(results_df))
|
| 640 |
-
top_markers = results_df.nlargest(top_n, 'LR_LOD')
|
| 641 |
-
ax5.scatter(range(len(top_markers)), top_markers['LR_LOD'].values,
|
| 642 |
-
c=ACCENT_COLOR, s=50, alpha=0.7, label='Linear')
|
| 643 |
-
|
| 644 |
-
if 'MLM_LOD' in results_df.columns:
|
| 645 |
-
ax5.scatter(range(len(top_markers)), top_markers['MLM_LOD'].values,
|
| 646 |
-
c=TEAL_COLOR, s=50, alpha=0.7, label='Mixed')
|
| 647 |
-
if 'RF_LOD' in results_df.columns:
|
| 648 |
-
ax5.scatter(range(len(top_markers)), top_markers['RF_LOD'].values,
|
| 649 |
-
c=GREEN_COLOR, s=50, alpha=0.7, label='RF')
|
| 650 |
-
|
| 651 |
-
ax5.axhline(3, color=RED_COLOR, linestyle='--', linewidth=1.5)
|
| 652 |
-
ax5.set_xlabel('Marker Rank', fontsize=11)
|
| 653 |
-
ax5.set_ylabel('LOD Score', fontsize=11)
|
| 654 |
-
ax5.set_title('Top Markers Comparison', fontsize=12, fontweight='bold')
|
| 655 |
-
ax5.legend(fontsize=9)
|
| 656 |
-
ax5.grid(True, alpha=0.3)
|
| 657 |
-
|
| 658 |
-
# 6. Model stability (CV scores)
|
| 659 |
-
ax6 = axes[1, 2]
|
| 660 |
-
cv_scores = []
|
| 661 |
-
cv_models = []
|
| 662 |
-
for model in available_models:
|
| 663 |
-
if f'{model}_CV' in results_df.columns:
|
| 664 |
-
cv_scores.append(results_df[f'{model}_CV'].iloc[0] if len(results_df) > 0 else 0)
|
| 665 |
-
cv_models.append(model_names[models.index(model)])
|
| 666 |
-
|
| 667 |
-
if cv_scores:
|
| 668 |
-
bars = ax6.barh(range(len(cv_scores)), cv_scores,
|
| 669 |
-
color=colors[:len(cv_scores)], alpha=0.7)
|
| 670 |
-
ax6.set_yticks(range(len(cv_scores)))
|
| 671 |
-
ax6.set_yticklabels(cv_models, fontsize=10)
|
| 672 |
-
ax6.set_xlabel('Cross-validation Score (RΒ²)', fontsize=11)
|
| 673 |
-
ax6.set_title('Model Stability (5-fold CV)', fontsize=12, fontweight='bold')
|
| 674 |
-
ax6.set_xlim(0, 1)
|
| 675 |
-
|
| 676 |
-
for bar, score in zip(bars, cv_scores):
|
| 677 |
-
ax6.text(bar.get_width() + 0.01, bar.get_y() + bar.get_height()/2,
|
| 678 |
-
f'{score:.3f}', va='center', fontsize=9)
|
| 679 |
-
|
| 680 |
-
plt.tight_layout(pad=2)
|
| 681 |
-
plt.savefig(save_path, dpi=200, bbox_inches='tight', facecolor=BG_COLOR)
|
| 682 |
plt.close(fig)
|
| 683 |
|
| 684 |
-
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 685 |
-
# GWAS MODELS
|
| 686 |
-
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 687 |
-
|
| 688 |
-
def linear_regression_gwas(genotypes, phenotypes):
|
| 689 |
-
"""Standard linear regression GWAS"""
|
| 690 |
-
n_markers = genotypes.shape[1]
|
| 691 |
-
pvals = np.ones(n_markers)
|
| 692 |
-
effects = np.zeros(n_markers)
|
| 693 |
-
se = np.zeros(n_markers)
|
| 694 |
-
lod = np.zeros(n_markers)
|
| 695 |
-
|
| 696 |
-
for i in range(n_markers):
|
| 697 |
-
X = genotypes[:, i]
|
| 698 |
-
if np.std(X) > 1e-6:
|
| 699 |
-
try:
|
| 700 |
-
X = sm.add_constant(X)
|
| 701 |
-
model = sm.OLS(phenotypes, X).fit()
|
| 702 |
-
pvals[i] = model.pvalues[1]
|
| 703 |
-
effects[i] = model.params[1]
|
| 704 |
-
se[i] = model.bse[1]
|
| 705 |
-
lod[i] = -np.log10(pvals[i] + 1e-300)
|
| 706 |
-
except:
|
| 707 |
-
pass
|
| 708 |
-
|
| 709 |
-
return pvals, effects, se, lod
|
| 710 |
-
|
| 711 |
-
def mixed_model_gwas(genotypes, phenotypes):
|
| 712 |
-
"""Mixed linear model GWAS"""
|
| 713 |
-
n_markers = genotypes.shape[1]
|
| 714 |
-
pvals = np.ones(n_markers)
|
| 715 |
-
effects = np.zeros(n_markers)
|
| 716 |
-
lod = np.zeros(n_markers)
|
| 717 |
-
|
| 718 |
-
for i in range(min(n_markers, 1000)): # Limit for performance
|
| 719 |
-
X = genotypes[:, i]
|
| 720 |
-
if np.std(X) > 1e-6:
|
| 721 |
-
try:
|
| 722 |
-
data = pd.DataFrame({'pheno': phenotypes, 'marker': X})
|
| 723 |
-
model = mixedlm("pheno ~ marker", data, groups=data.index).fit()
|
| 724 |
-
pvals[i] = model.pvalues[1]
|
| 725 |
-
effects[i] = model.params[1]
|
| 726 |
-
lod[i] = -np.log10(pvals[i] + 1e-300)
|
| 727 |
-
except:
|
| 728 |
-
pass
|
| 729 |
-
|
| 730 |
-
return pvals, effects, lod
|
| 731 |
-
|
| 732 |
-
def elasticnet_gwas(genotypes, phenotypes):
|
| 733 |
-
"""ElasticNet regression GWAS"""
|
| 734 |
-
scaler = StandardScaler()
|
| 735 |
-
X_scaled = scaler.fit_transform(genotypes)
|
| 736 |
-
|
| 737 |
-
enet = ElasticNetCV(cv=5, random_state=42, max_iter=5000, n_alphas=10)
|
| 738 |
-
enet.fit(X_scaled, phenotypes)
|
| 739 |
-
|
| 740 |
-
coefficients = enet.coef_
|
| 741 |
-
cv_score = enet.score(X_scaled, phenotypes)
|
| 742 |
-
|
| 743 |
-
# Bootstrap for p-values
|
| 744 |
-
n_bootstrap = 50
|
| 745 |
-
bootstrap_coefs = []
|
| 746 |
-
for _ in range(min(n_bootstrap, len(phenotypes))):
|
| 747 |
-
idx = np.random.choice(len(phenotypes), len(phenotypes), replace=True)
|
| 748 |
-
enet_boot = ElasticNetCV(cv=3, random_state=42, max_iter=3000)
|
| 749 |
-
enet_boot.fit(X_scaled[idx], phenotypes[idx])
|
| 750 |
-
bootstrap_coefs.append(enet_boot.coef_)
|
| 751 |
-
|
| 752 |
-
bootstrap_coefs = np.array(bootstrap_coefs)
|
| 753 |
-
pvals = np.ones(len(coefficients))
|
| 754 |
-
for i in range(len(coefficients)):
|
| 755 |
-
if np.std(bootstrap_coefs[:, i]) > 0:
|
| 756 |
-
z_score = abs(coefficients[i]) / (np.std(bootstrap_coefs[:, i]) + 1e-10)
|
| 757 |
-
pvals[i] = 2 * (1 - stats.norm.cdf(z_score))
|
| 758 |
-
|
| 759 |
-
lod = -np.log10(pvals + 1e-300)
|
| 760 |
-
|
| 761 |
-
return pvals, coefficients, lod, cv_score
|
| 762 |
-
|
| 763 |
-
def lasso_gwas(genotypes, phenotypes):
|
| 764 |
-
"""Lasso regression GWAS"""
|
| 765 |
-
scaler = StandardScaler()
|
| 766 |
-
X_scaled = scaler.fit_transform(genotypes)
|
| 767 |
-
|
| 768 |
-
lasso = LassoCV(cv=5, random_state=42, max_iter=5000)
|
| 769 |
-
lasso.fit(X_scaled, phenotypes)
|
| 770 |
-
|
| 771 |
-
coefficients = lasso.coef_
|
| 772 |
-
cv_score = lasso.score(X_scaled, phenotypes)
|
| 773 |
-
|
| 774 |
-
# Permutation for p-values
|
| 775 |
-
n_perm = 50
|
| 776 |
-
null_coefs = []
|
| 777 |
-
for _ in range(min(n_perm, len(phenotypes))):
|
| 778 |
-
y_perm = np.random.permutation(phenotypes)
|
| 779 |
-
lasso_perm = LassoCV(cv=3, random_state=42, max_iter=3000)
|
| 780 |
-
lasso_perm.fit(X_scaled, y_perm)
|
| 781 |
-
null_coefs.append(lasso_perm.coef_)
|
| 782 |
-
|
| 783 |
-
null_coefs = np.array(null_coefs)
|
| 784 |
-
pvals = np.ones(len(coefficients))
|
| 785 |
-
for i in range(len(coefficients)):
|
| 786 |
-
pvals[i] = np.mean(np.abs(null_coefs[:, i]) >= np.abs(coefficients[i]))
|
| 787 |
-
|
| 788 |
-
lod = -np.log10(pvals + 1e-300)
|
| 789 |
-
|
| 790 |
-
return pvals, coefficients, lod, cv_score
|
| 791 |
-
|
| 792 |
-
def ridge_gwas(genotypes, phenotypes):
|
| 793 |
-
"""Ridge regression GWAS"""
|
| 794 |
-
scaler = StandardScaler()
|
| 795 |
-
X_scaled = scaler.fit_transform(genotypes)
|
| 796 |
-
|
| 797 |
-
ridge = RidgeCV(cv=5, alphas=np.logspace(-3, 3, 10))
|
| 798 |
-
ridge.fit(X_scaled, phenotypes)
|
| 799 |
-
|
| 800 |
-
coefficients = ridge.coef_
|
| 801 |
-
cv_score = ridge.score(X_scaled, phenotypes)
|
| 802 |
-
|
| 803 |
-
# Bootstrap for p-values
|
| 804 |
-
n_bootstrap = 50
|
| 805 |
-
bootstrap_coefs = []
|
| 806 |
-
for _ in range(min(n_bootstrap, len(phenotypes))):
|
| 807 |
-
idx = np.random.choice(len(phenotypes), len(phenotypes), replace=True)
|
| 808 |
-
ridge_boot = RidgeCV(alphas=np.logspace(-3, 3, 5))
|
| 809 |
-
ridge_boot.fit(X_scaled[idx], phenotypes[idx])
|
| 810 |
-
bootstrap_coefs.append(ridge_boot.coef_)
|
| 811 |
-
|
| 812 |
-
bootstrap_coefs = np.array(bootstrap_coefs)
|
| 813 |
-
pvals = np.ones(len(coefficients))
|
| 814 |
-
for i in range(len(coefficients)):
|
| 815 |
-
if np.std(bootstrap_coefs[:, i]) > 0:
|
| 816 |
-
z_score = abs(coefficients[i]) / (np.std(bootstrap_coefs[:, i]) + 1e-10)
|
| 817 |
-
pvals[i] = 2 * (1 - stats.norm.cdf(z_score))
|
| 818 |
-
|
| 819 |
-
lod = -np.log10(pvals + 1e-300)
|
| 820 |
-
|
| 821 |
-
return pvals, coefficients, lod, cv_score
|
| 822 |
-
|
| 823 |
-
def randomforest_gwas(genotypes, phenotypes):
|
| 824 |
-
"""Random Forest GWAS"""
|
| 825 |
-
scaler = StandardScaler()
|
| 826 |
-
X_scaled = scaler.fit_transform(genotypes)
|
| 827 |
-
|
| 828 |
-
rf = RandomForestRegressor(n_estimators=100, random_state=42, n_jobs=-1)
|
| 829 |
-
|
| 830 |
-
# Cross-validation
|
| 831 |
-
kf = KFold(n_splits=5, shuffle=True, random_state=42)
|
| 832 |
-
cv_scores = []
|
| 833 |
-
importance_scores = []
|
| 834 |
-
|
| 835 |
-
for train_idx, val_idx in kf.split(X_scaled):
|
| 836 |
-
X_train, X_val = X_scaled[train_idx], X_scaled[val_idx]
|
| 837 |
-
y_train, y_val = phenotypes[train_idx], phenotypes[val_idx]
|
| 838 |
-
|
| 839 |
-
rf.fit(X_train, y_train)
|
| 840 |
-
y_pred = rf.predict(X_val)
|
| 841 |
-
cv_scores.append(r2_score(y_val, y_pred))
|
| 842 |
-
importance_scores.append(rf.feature_importances_)
|
| 843 |
-
|
| 844 |
-
avg_importance = np.mean(importance_scores, axis=0)
|
| 845 |
-
cv_score = np.mean(cv_scores)
|
| 846 |
-
|
| 847 |
-
# Permutation for p-values
|
| 848 |
-
n_perm = 50
|
| 849 |
-
null_importance = []
|
| 850 |
-
for _ in range(min(n_perm, len(phenotypes))):
|
| 851 |
-
y_perm = np.random.permutation(phenotypes)
|
| 852 |
-
rf_perm = RandomForestRegressor(n_estimators=50, random_state=42, n_jobs=-1)
|
| 853 |
-
rf_perm.fit(X_scaled, y_perm)
|
| 854 |
-
null_importance.append(rf_perm.feature_importances_)
|
| 855 |
-
|
| 856 |
-
null_importance = np.array(null_importance)
|
| 857 |
-
pvals = np.ones(len(avg_importance))
|
| 858 |
-
for i in range(len(avg_importance)):
|
| 859 |
-
pvals[i] = np.mean(null_importance[:, i] >= avg_importance[i])
|
| 860 |
-
|
| 861 |
-
lod = -np.log10(pvals + 1e-300)
|
| 862 |
-
|
| 863 |
-
return pvals, avg_importance, lod, cv_score
|
| 864 |
-
|
| 865 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 866 |
# DATA PARSING AND QC
|
| 867 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 868 |
|
| 869 |
def parse_gwas_csv(filepath):
|
| 870 |
-
"""Parse GWAS CSV file
|
| 871 |
df = pd.read_csv(filepath, header=0)
|
| 872 |
|
| 873 |
-
# Identify columns
|
| 874 |
id_col = df.columns[0]
|
| 875 |
pheno_col = df.columns[1]
|
| 876 |
marker_cols = df.columns[2:].tolist()
|
| 877 |
|
| 878 |
-
# Parse chromosome and position info from first row
|
| 879 |
first_row = df.iloc[0]
|
| 880 |
chromosome_dict = {}
|
| 881 |
position_dict = {}
|
|
@@ -902,13 +877,11 @@ def parse_gwas_csv(filepath):
|
|
| 902 |
chromosome_dict[m] = val
|
| 903 |
position_dict[m] = 0
|
| 904 |
|
| 905 |
-
# Sample data (rows 1 onwards)
|
| 906 |
sample_data = df.iloc[1:].reset_index(drop=True)
|
| 907 |
|
| 908 |
sample_ids = sample_data.iloc[:, 0].astype(str).values
|
| 909 |
phenotypes = pd.to_numeric(sample_data.iloc[:, 1], errors='coerce').values
|
| 910 |
|
| 911 |
-
# Genotype matrix
|
| 912 |
genotypes_raw = sample_data[marker_cols].apply(pd.to_numeric, errors='coerce')
|
| 913 |
genotypes = genotypes_raw.values
|
| 914 |
|
|
@@ -921,11 +894,9 @@ def perform_qc(genotypes, phenotypes, sample_ids, marker_names,
|
|
| 921 |
"""Perform quality control filtering"""
|
| 922 |
n_samples, n_markers = genotypes.shape
|
| 923 |
|
| 924 |
-
# Calculate missing rates
|
| 925 |
sample_missing = np.isnan(genotypes).sum(axis=1) / n_markers
|
| 926 |
marker_missing = np.isnan(genotypes).sum(axis=0) / n_samples
|
| 927 |
|
| 928 |
-
# Calculate MAF
|
| 929 |
maf = np.zeros(n_markers)
|
| 930 |
for i in range(n_markers):
|
| 931 |
col = genotypes[:, i]
|
|
@@ -934,11 +905,9 @@ def perform_qc(genotypes, phenotypes, sample_ids, marker_names,
|
|
| 934 |
freq = np.mean(valid) / 2.0
|
| 935 |
maf[i] = min(freq, 1.0 - freq)
|
| 936 |
|
| 937 |
-
# Apply filters
|
| 938 |
keep_samples = sample_missing < max_sample_missing
|
| 939 |
keep_markers = (marker_missing < max_marker_missing) & (maf >= maf_threshold)
|
| 940 |
|
| 941 |
-
# Filter data
|
| 942 |
genotypes_qc = genotypes[np.ix_(keep_samples, keep_markers)]
|
| 943 |
phenotypes_qc = phenotypes[keep_samples]
|
| 944 |
sample_ids_qc = sample_ids[keep_samples]
|
|
@@ -946,11 +915,9 @@ def perform_qc(genotypes, phenotypes, sample_ids, marker_names,
|
|
| 946 |
chromosomes_qc = [chromosome_dict[m] for m in marker_names_qc]
|
| 947 |
positions_qc = [position_dict.get(m, 0) for m in marker_names_qc]
|
| 948 |
|
| 949 |
-
# Impute missing values with column means
|
| 950 |
imputer = SimpleImputer(strategy='mean')
|
| 951 |
genotypes_imputed = imputer.fit_transform(genotypes_qc)
|
| 952 |
|
| 953 |
-
# Remove samples with NaN phenotypes
|
| 954 |
valid_pheno = ~np.isnan(phenotypes_qc)
|
| 955 |
genotypes_final = genotypes_imputed[valid_pheno]
|
| 956 |
phenotypes_final = phenotypes_qc[valid_pheno]
|
|
@@ -966,14 +933,13 @@ def perform_qc(genotypes, phenotypes, sample_ids, marker_names,
|
|
| 966 |
|
| 967 |
def run_gwas_pipeline(input_file, sample_missing, marker_missing, maf_threshold,
|
| 968 |
include_lr, include_mlm, include_enet, include_lasso,
|
| 969 |
-
include_ridge, include_rf):
|
| 970 |
-
"""Complete GWAS analysis pipeline"""
|
| 971 |
|
| 972 |
if input_file is None:
|
| 973 |
-
return ("Please upload a CSV file", None, None, None, None, None, None)
|
| 974 |
|
| 975 |
try:
|
| 976 |
-
# Create output directories
|
| 977 |
temp_dir = tempfile.mkdtemp()
|
| 978 |
results_dir = os.path.join(temp_dir, 'results')
|
| 979 |
plots_dir = os.path.join(results_dir, 'plots')
|
|
@@ -997,69 +963,115 @@ def run_gwas_pipeline(input_file, sample_missing, marker_missing, maf_threshold,
|
|
| 997 |
)
|
| 998 |
|
| 999 |
if len(sample_ids_qc) < 10:
|
| 1000 |
-
return (f"β οΈ Insufficient samples after QC: {len(sample_ids_qc)}
|
| 1001 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1002 |
|
| 1003 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1004 |
scaler = StandardScaler()
|
| 1005 |
genotypes_scaled = scaler.fit_transform(genotypes_qc)
|
| 1006 |
|
|
|
|
|
|
|
|
|
|
| 1007 |
# Run selected models
|
| 1008 |
results = {}
|
| 1009 |
models_used = []
|
| 1010 |
|
| 1011 |
-
# Linear Regression
|
| 1012 |
if include_lr:
|
| 1013 |
-
pvals, effects,
|
|
|
|
| 1014 |
results['LR_P'] = pvals
|
| 1015 |
results['LR_Beta'] = effects
|
| 1016 |
results['LR_LOD'] = lod
|
| 1017 |
-
results['LR_CV'] = 0.
|
| 1018 |
models_used.append('LR')
|
| 1019 |
|
| 1020 |
-
# Mixed Linear Model
|
| 1021 |
if include_mlm:
|
| 1022 |
-
pvals, effects, lod =
|
|
|
|
| 1023 |
results['MLM_P'] = pvals
|
| 1024 |
results['MLM_Beta'] = effects
|
| 1025 |
results['MLM_LOD'] = lod
|
| 1026 |
-
results['MLM_CV'] = 0.
|
| 1027 |
models_used.append('MLM')
|
| 1028 |
|
| 1029 |
-
# ElasticNet
|
| 1030 |
if include_enet:
|
| 1031 |
-
pvals, effects, lod, cv =
|
|
|
|
| 1032 |
results['EN_P'] = pvals
|
| 1033 |
results['EN_Beta'] = effects
|
| 1034 |
results['EN_LOD'] = lod
|
| 1035 |
results['EN_CV'] = cv
|
| 1036 |
models_used.append('EN')
|
| 1037 |
|
| 1038 |
-
# Lasso
|
| 1039 |
if include_lasso:
|
| 1040 |
-
pvals, effects, lod, cv =
|
|
|
|
| 1041 |
results['LASSO_P'] = pvals
|
| 1042 |
results['LASSO_Beta'] = effects
|
| 1043 |
results['LASSO_LOD'] = lod
|
| 1044 |
results['LASSO_CV'] = cv
|
| 1045 |
models_used.append('LASSO')
|
| 1046 |
|
| 1047 |
-
# Ridge
|
| 1048 |
if include_ridge:
|
| 1049 |
-
pvals, effects, lod, cv =
|
|
|
|
| 1050 |
results['RIDGE_P'] = pvals
|
| 1051 |
results['RIDGE_Beta'] = effects
|
| 1052 |
results['RIDGE_LOD'] = lod
|
| 1053 |
results['RIDGE_CV'] = cv
|
| 1054 |
models_used.append('RIDGE')
|
| 1055 |
|
| 1056 |
-
# Random Forest
|
| 1057 |
if include_rf:
|
| 1058 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1059 |
results['RF_P'] = pvals
|
| 1060 |
-
results['RF_Beta'] =
|
| 1061 |
results['RF_LOD'] = lod
|
| 1062 |
-
results['RF_CV'] =
|
| 1063 |
models_used.append('RF')
|
| 1064 |
|
| 1065 |
# Create results DataFrame
|
|
@@ -1075,13 +1087,13 @@ def run_gwas_pipeline(input_file, sample_missing, marker_missing, maf_threshold,
|
|
| 1075 |
if col_name in results:
|
| 1076 |
gwas_df[col_name] = results[col_name]
|
| 1077 |
|
| 1078 |
-
#
|
| 1079 |
bonf_threshold = 0.05 / n_markers_qc
|
|
|
|
| 1080 |
for model in models_used:
|
| 1081 |
if f'{model}_P' in gwas_df.columns:
|
| 1082 |
gwas_df[f'Sig_{model}'] = (gwas_df[f'{model}_P'] < bonf_threshold).astype(int)
|
| 1083 |
|
| 1084 |
-
# Consensus significance
|
| 1085 |
sig_cols = [c for c in gwas_df.columns if c.startswith('Sig_')]
|
| 1086 |
if len(sig_cols) > 1:
|
| 1087 |
gwas_df['Consensus_Sig'] = (gwas_df[sig_cols].sum(axis=1) >= 2).astype(int)
|
|
@@ -1090,7 +1102,6 @@ def run_gwas_pipeline(input_file, sample_missing, marker_missing, maf_threshold,
|
|
| 1090 |
else:
|
| 1091 |
gwas_df['Consensus_Sig'] = 0
|
| 1092 |
|
| 1093 |
-
# Sort by LOD score
|
| 1094 |
if 'LR_LOD' in gwas_df.columns:
|
| 1095 |
gwas_df = gwas_df.sort_values('LR_LOD', ascending=False)
|
| 1096 |
gwas_df['Rank'] = range(1, len(gwas_df) + 1)
|
|
@@ -1098,6 +1109,17 @@ def run_gwas_pipeline(input_file, sample_missing, marker_missing, maf_threshold,
|
|
| 1098 |
# Save results
|
| 1099 |
gwas_df.to_csv(os.path.join(results_dir, 'gwas_results.csv'), index=False)
|
| 1100 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1101 |
# Generate plots
|
| 1102 |
sig_indices = gwas_df[gwas_df['Consensus_Sig'] == 1].index.tolist()
|
| 1103 |
|
|
@@ -1134,10 +1156,6 @@ def run_gwas_pipeline(input_file, sample_missing, marker_missing, maf_threshold,
|
|
| 1134 |
circos_path
|
| 1135 |
)
|
| 1136 |
|
| 1137 |
-
# Model comparison
|
| 1138 |
-
comparison_path = os.path.join(plots_dir, 'model_comparison.png')
|
| 1139 |
-
plot_model_comparison(gwas_df, comparison_path)
|
| 1140 |
-
|
| 1141 |
# Create ZIP file
|
| 1142 |
zip_path = os.path.join(temp_dir, 'GWAS_Results.zip')
|
| 1143 |
with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf:
|
|
@@ -1147,7 +1165,7 @@ def run_gwas_pipeline(input_file, sample_missing, marker_missing, maf_threshold,
|
|
| 1147 |
arc = os.path.relpath(fp, temp_dir)
|
| 1148 |
zf.write(fp, arc)
|
| 1149 |
|
| 1150 |
-
# Generate summary
|
| 1151 |
summary = f"""
|
| 1152 |
## π GWAS Analysis Results
|
| 1153 |
|
|
@@ -1161,6 +1179,20 @@ def run_gwas_pipeline(input_file, sample_missing, marker_missing, maf_threshold,
|
|
| 1161 |
| Missing rate threshold | < {sample_missing:.0f}% (samples), < {marker_missing:.0f}% (markers) |
|
| 1162 |
| MAF threshold | β₯ {maf_threshold:.1f}% |
|
| 1163 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1164 |
### Models Executed
|
| 1165 |
{chr(10).join([f"- {model}" for model in models_used])}
|
| 1166 |
|
|
@@ -1173,41 +1205,44 @@ def run_gwas_pipeline(input_file, sample_missing, marker_missing, maf_threshold,
|
|
| 1173 |
- **LD pairs analyzed**: {ld_stats['n_pairs']:,}
|
| 1174 |
|
| 1175 |
### Top 10 Markers (by LR LOD score)
|
| 1176 |
-
{
|
| 1177 |
|
| 1178 |
### π Output Files
|
| 1179 |
- `gwas_results.csv` - Complete results for all models
|
|
|
|
|
|
|
| 1180 |
- `plots/manhattan_lod.png` - Manhattan plot with LOD scores
|
| 1181 |
- `plots/ld_decay.png` - LD decay plot (distances in Mb)
|
| 1182 |
- `plots/circos.png` - Circos plot visualization
|
| 1183 |
-
- `plots/
|
|
|
|
| 1184 |
"""
|
| 1185 |
|
| 1186 |
return (summary, manhattan_path, ld_path, circos_path,
|
| 1187 |
-
|
|
|
|
|
|
|
| 1188 |
|
| 1189 |
except Exception as e:
|
| 1190 |
import traceback
|
| 1191 |
return (f"## β Error\n```\n{str(e)}\n\n{traceback.format_exc()}\n```",
|
| 1192 |
-
None, None, None, None, None, None)
|
| 1193 |
|
| 1194 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1195 |
# GRADIO INTERFACE
|
| 1196 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1197 |
|
| 1198 |
-
with gr.Blocks(css=
|
| 1199 |
|
| 1200 |
-
# Header
|
| 1201 |
gr.HTML("""
|
| 1202 |
<div class="main-header">
|
| 1203 |
<h1>𧬠GWAS Analysis Platform</h1>
|
| 1204 |
-
<p>Comprehensive Genome-Wide Association Study with
|
| 1205 |
</div>
|
| 1206 |
""")
|
| 1207 |
|
| 1208 |
with gr.Row():
|
| 1209 |
with gr.Column(scale=1):
|
| 1210 |
-
# Input section
|
| 1211 |
gr.HTML('<div class="section-header">π Data Input</div>')
|
| 1212 |
input_file = gr.File(label="Upload CSV File", file_types=[".csv"])
|
| 1213 |
|
|
@@ -1219,6 +1254,10 @@ with gr.Blocks(css=CUSTOM_CSS, title="GWAS Analysis Platform", theme=gr.themes.S
|
|
| 1219 |
maf_threshold = gr.Slider(1, 20, value=5, step=1,
|
| 1220 |
label="Minor Allele Frequency Threshold (%)")
|
| 1221 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1222 |
gr.HTML('<div class="section-header">π€ Model Selection</div>')
|
| 1223 |
with gr.Row():
|
| 1224 |
include_lr = gr.Checkbox(label="Linear Regression", value=True)
|
|
@@ -1238,11 +1277,11 @@ with gr.Blocks(css=CUSTOM_CSS, title="GWAS Analysis Platform", theme=gr.themes.S
|
|
| 1238 |
<p><strong>Row 1:</strong> Sample IDs | Phenotype | Marker1 (chr:pos) | Marker2 | ...</p>
|
| 1239 |
<p><strong>Row 2+:</strong> Sample1 | value | 0/1/2 | 0/1/2 | ...</p>
|
| 1240 |
<p><strong>Genotype coding:</strong> 0=AA, 1=Aa, 2=aa</p>
|
|
|
|
| 1241 |
</div>
|
| 1242 |
""")
|
| 1243 |
|
| 1244 |
with gr.Column(scale=2):
|
| 1245 |
-
# Results section
|
| 1246 |
gr.HTML('<div class="section-header">π Analysis Summary</div>')
|
| 1247 |
summary_output = gr.Markdown("*Upload a CSV file and click 'Run GWAS Analysis' to begin*")
|
| 1248 |
|
|
@@ -1252,26 +1291,28 @@ with gr.Blocks(css=CUSTOM_CSS, title="GWAS Analysis Platform", theme=gr.themes.S
|
|
| 1252 |
ld_output = gr.Image(label="LD Decay Plot (Mb)")
|
| 1253 |
with gr.Row():
|
| 1254 |
circos_output = gr.Image(label="Circos Plot")
|
| 1255 |
-
|
|
|
|
|
|
|
| 1256 |
|
| 1257 |
gr.HTML('<div class="section-header">β¬οΈ Download Results</div>')
|
| 1258 |
download_output = gr.File(label="Download ZIP Archive")
|
| 1259 |
status_output = gr.Textbox(label="Status", interactive=False)
|
| 1260 |
|
| 1261 |
-
# Connect button to function
|
| 1262 |
run_button.click(
|
| 1263 |
fn=run_gwas_pipeline,
|
| 1264 |
inputs=[input_file, sample_missing, marker_missing, maf_threshold,
|
| 1265 |
include_lr, include_mlm, include_enet, include_lasso,
|
| 1266 |
-
include_ridge, include_rf],
|
| 1267 |
outputs=[summary_output, manhattan_output, ld_output, circos_output,
|
| 1268 |
-
|
|
|
|
| 1269 |
)
|
| 1270 |
|
| 1271 |
-
# Footer
|
| 1272 |
gr.HTML("""
|
| 1273 |
<footer>
|
| 1274 |
-
<p>GWAS Analysis Platform
|
|
|
|
| 1275 |
</footer>
|
| 1276 |
""")
|
| 1277 |
|
|
|
|
| 1 |
# -*- coding: utf-8 -*-
|
| 2 |
"""
|
| 3 |
+
GWAS Pipeline v10.0 - Complete Analysis with PCA & Kinship
|
| 4 |
Features:
|
| 5 |
+
- Soft pastel color scheme with Times New Roman
|
| 6 |
- 6 GWAS models (Linear, Mixed, ElasticNet, Lasso, Ridge, Random Forest)
|
| 7 |
+
- PCA analysis and visualization
|
| 8 |
+
- Kinship matrix calculation
|
| 9 |
- LD decay plot in Mb
|
| 10 |
+
- Circos plot
|
| 11 |
+
- Manhattan plot with LOD scores
|
| 12 |
+
- Population structure correction
|
| 13 |
"""
|
| 14 |
|
| 15 |
import gradio as gr
|
|
|
|
| 18 |
import matplotlib
|
| 19 |
matplotlib.use('Agg')
|
| 20 |
import matplotlib.pyplot as plt
|
| 21 |
+
from matplotlib.patches import Circle
|
| 22 |
import matplotlib.patches as mpatches
|
| 23 |
+
from matplotlib.lines import Line2D
|
| 24 |
import seaborn as sns
|
| 25 |
from scipy import stats
|
| 26 |
from scipy.spatial.distance import pdist, squareform
|
| 27 |
from scipy.optimize import curve_fit
|
| 28 |
import os, warnings, tempfile, zipfile, io
|
| 29 |
+
from sklearn.linear_model import ElasticNetCV, LassoCV, RidgeCV
|
| 30 |
+
from sklearn.ensemble import RandomForestRegressor
|
| 31 |
from sklearn.preprocessing import StandardScaler
|
|
|
|
|
|
|
| 32 |
from sklearn.impute import SimpleImputer
|
| 33 |
+
from sklearn.decomposition import PCA
|
| 34 |
+
from sklearn.model_selection import KFold
|
| 35 |
+
from sklearn.metrics import r2_score
|
| 36 |
import statsmodels.api as sm
|
| 37 |
from statsmodels.formula.api import mixedlm
|
| 38 |
+
from scipy.cluster.hierarchy import dendrogram, linkage
|
| 39 |
warnings.filterwarnings('ignore')
|
| 40 |
|
| 41 |
+
# Set Times New Roman as default font
|
| 42 |
+
plt.rcParams['font.family'] = 'Times New Roman'
|
| 43 |
+
plt.rcParams['font.size'] = 10
|
| 44 |
+
plt.rcParams['mathtext.fontset'] = 'stix'
|
| 45 |
+
|
| 46 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 47 |
+
# SOFT PASTEL COLOR PALETTE
|
| 48 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 49 |
+
|
| 50 |
+
# Background and UI colors
|
| 51 |
+
BG_PASTEL = "#FDF8F0" # Soft cream
|
| 52 |
+
PANEL_PASTEL = "#F5F0E8" # Warm off-white
|
| 53 |
+
CARD_PASTEL = "#FFFEF8" # Very light cream
|
| 54 |
+
TEXT_PASTEL = "#4A4A4A" # Soft charcoal
|
| 55 |
+
BORDER_PASTEL = "#E8DCC8" # Muted beige
|
| 56 |
+
GRID_PASTEL = "#E8E0D5" # Soft grid color
|
| 57 |
+
|
| 58 |
+
# Plot colors
|
| 59 |
+
PRIMARY = "#C5A3FF" # Soft lavender
|
| 60 |
+
SECONDARY = "#A8E6CF" # Mint green
|
| 61 |
+
TERTIARY = "#FFD3B6" # Peach
|
| 62 |
+
QUATERNARY = "#FFB3BA" # Soft pink
|
| 63 |
+
QUINARY = "#B5EAD7" # Seafoam
|
| 64 |
+
SENARY = "#C7CEEA" # Periwinkle
|
| 65 |
+
ACCENT = "#FFAAA5" # Coral
|
| 66 |
+
HIGHLIGHT = "#FFDAC1" # Warm peach
|
| 67 |
+
LOD_COLOR = "#95CDBA" # Sage green
|
| 68 |
+
SIGNIFICANT = "#E8A598" # Dusty rose
|
| 69 |
+
PCA_COLOR1 = "#B8D4E3" # Baby blue
|
| 70 |
+
PCA_COLOR2 = "#F4C3A2" # Soft orange
|
| 71 |
+
KINSHIP_COLOR = "#D5E4CF" # Pale green
|
| 72 |
+
|
| 73 |
+
CHROM_COLORS = [
|
| 74 |
+
"#E8D5F5", "#D4F1F9", "#FDE2C4", "#E2F0CB", "#FFD9E8",
|
| 75 |
+
"#C9E4DE", "#FADADD", "#D5E4CF", "#FCE1E4", "#CFBAE1",
|
| 76 |
+
"#B8E2D6", "#FFDAC8", "#E8D1C5", "#C5E0D4", "#F8D5E3",
|
| 77 |
+
"#D6E5E3", "#FFE0B5", "#D4C5E2", "#C9E6D8", "#F2D7D9"
|
| 78 |
+
]
|
| 79 |
+
|
| 80 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 81 |
+
# CUSTOM CSS FOR SOFT PASTEL INTERFACE
|
| 82 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 83 |
|
| 84 |
+
PASTEL_CSS = """
|
| 85 |
<style>
|
| 86 |
+
@import url('https://fonts.googleapis.com/css2?family=Times+New+Roman&display=swap');
|
|
|
|
| 87 |
|
| 88 |
* {
|
| 89 |
+
font-family: 'Times New Roman', Times, serif !important;
|
| 90 |
}
|
| 91 |
|
| 92 |
.gradio-container {
|
| 93 |
+
background: linear-gradient(135deg, #FDF8F0 0%, #F5F0E8 100%) !important;
|
| 94 |
padding: 20px !important;
|
| 95 |
}
|
| 96 |
|
| 97 |
.main-header {
|
| 98 |
+
background: linear-gradient(135deg, #E8D5F5 0%, #D4F1F9 100%);
|
| 99 |
padding: 40px;
|
| 100 |
+
border-radius: 25px;
|
| 101 |
text-align: center;
|
| 102 |
margin-bottom: 30px;
|
| 103 |
+
box-shadow: 0 8px 20px rgba(0,0,0,0.05);
|
| 104 |
+
border: 1px solid #E8DCC8;
|
| 105 |
}
|
| 106 |
|
| 107 |
.main-header h1 {
|
| 108 |
+
color: #4A4A4A;
|
| 109 |
font-size: 2.5em;
|
| 110 |
margin: 0;
|
| 111 |
+
font-weight: 600;
|
| 112 |
+
letter-spacing: 1px;
|
| 113 |
}
|
| 114 |
|
| 115 |
.main-header p {
|
| 116 |
+
color: #6B6B6B;
|
| 117 |
font-size: 1.1em;
|
| 118 |
margin-top: 10px;
|
| 119 |
}
|
| 120 |
|
| 121 |
.section-header {
|
| 122 |
+
background: linear-gradient(135deg, #C5A3FF 0%, #B8D4E3 100%);
|
| 123 |
+
padding: 12px 20px;
|
| 124 |
+
border-radius: 15px;
|
| 125 |
margin: 20px 0 15px 0;
|
| 126 |
+
color: #4A4A4A;
|
| 127 |
font-weight: 600;
|
| 128 |
+
font-size: 1.1em;
|
| 129 |
+
border: 1px solid #E8DCC8;
|
| 130 |
}
|
| 131 |
|
| 132 |
.card {
|
| 133 |
+
background: #FFFEF8;
|
| 134 |
border-radius: 15px;
|
| 135 |
padding: 20px;
|
| 136 |
margin: 10px 0;
|
| 137 |
+
box-shadow: 0 4px 12px rgba(0,0,0,0.05);
|
| 138 |
+
border: 1px solid #E8DCC8;
|
| 139 |
+
transition: all 0.3s ease;
|
| 140 |
}
|
| 141 |
|
| 142 |
.card:hover {
|
| 143 |
transform: translateY(-2px);
|
| 144 |
+
box-shadow: 0 8px 20px rgba(0,0,0,0.08);
|
| 145 |
}
|
| 146 |
|
| 147 |
.stat-box {
|
| 148 |
+
background: linear-gradient(135deg, #F5F0E8 0%, #FFFEF8 100%);
|
| 149 |
border-radius: 12px;
|
| 150 |
padding: 15px;
|
| 151 |
text-align: center;
|
| 152 |
margin: 10px;
|
| 153 |
+
border: 1px solid #E8DCC8;
|
| 154 |
}
|
| 155 |
|
| 156 |
.stat-number {
|
| 157 |
font-size: 2em;
|
| 158 |
font-weight: bold;
|
| 159 |
+
color: #8B6B9D;
|
| 160 |
}
|
| 161 |
|
| 162 |
.stat-label {
|
| 163 |
font-size: 0.9em;
|
| 164 |
+
color: #8B8B8B;
|
| 165 |
margin-top: 5px;
|
| 166 |
}
|
| 167 |
|
| 168 |
.run-btn {
|
| 169 |
+
background: linear-gradient(135deg, #C5A3FF 0%, #A8E6CF 100%);
|
| 170 |
border: none;
|
| 171 |
+
color: #4A4A4A;
|
| 172 |
padding: 12px 30px;
|
| 173 |
border-radius: 25px;
|
| 174 |
font-weight: 600;
|
| 175 |
font-size: 1.1em;
|
| 176 |
cursor: pointer;
|
| 177 |
transition: all 0.3s;
|
| 178 |
+
border: 1px solid #E8DCC8;
|
| 179 |
}
|
| 180 |
|
| 181 |
.run-btn:hover {
|
| 182 |
+
transform: scale(1.02);
|
| 183 |
+
box-shadow: 0 5px 15px rgba(0,0,0,0.1);
|
| 184 |
+
background: linear-gradient(135deg, #D4B5FF 0%, #B8E6CF 100%);
|
| 185 |
}
|
| 186 |
|
| 187 |
footer {
|
| 188 |
text-align: center;
|
| 189 |
padding: 20px;
|
| 190 |
margin-top: 30px;
|
| 191 |
+
color: #8B8B8B;
|
| 192 |
+
background: rgba(255,254,248,0.9);
|
| 193 |
+
border-radius: 15px;
|
| 194 |
+
border: 1px solid #E8DCC8;
|
| 195 |
+
}
|
| 196 |
+
|
| 197 |
+
label, span, p, h1, h2, h3, h4 {
|
| 198 |
+
color: #4A4A4A !important;
|
| 199 |
+
}
|
| 200 |
+
|
| 201 |
+
input, textarea, select {
|
| 202 |
+
background: #FFFEF8 !important;
|
| 203 |
+
border: 1px solid #E8DCC8 !important;
|
| 204 |
+
color: #4A4A4A !important;
|
| 205 |
+
}
|
| 206 |
+
|
| 207 |
+
.tab-nav button {
|
| 208 |
+
background: #F5F0E8 !important;
|
| 209 |
+
color: #4A4A4A !important;
|
| 210 |
+
border: 1px solid #E8DCC8 !important;
|
| 211 |
+
}
|
| 212 |
+
|
| 213 |
+
.tab-nav button.selected {
|
| 214 |
+
background: #C5A3FF !important;
|
| 215 |
+
color: #4A4A4A !important;
|
| 216 |
}
|
| 217 |
</style>
|
| 218 |
"""
|
| 219 |
|
| 220 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 221 |
+
# PLOT STYLING FUNCTION
|
| 222 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 223 |
|
| 224 |
+
def set_pastel_plot_style():
|
| 225 |
+
"""Set soft pastel styling for plots"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 226 |
plt.rcParams.update({
|
| 227 |
+
'figure.facecolor': BG_PASTEL,
|
| 228 |
+
'axes.facecolor': PANEL_PASTEL,
|
| 229 |
+
'axes.edgecolor': BORDER_PASTEL,
|
| 230 |
+
'axes.labelcolor': TEXT_PASTEL,
|
| 231 |
+
'axes.titlecolor': TEXT_PASTEL,
|
| 232 |
+
'xtick.color': TEXT_PASTEL,
|
| 233 |
+
'ytick.color': TEXT_PASTEL,
|
| 234 |
+
'text.color': TEXT_PASTEL,
|
| 235 |
+
'grid.color': GRID_PASTEL,
|
| 236 |
'grid.linewidth': 0.8,
|
| 237 |
+
'grid.alpha': 0.6,
|
| 238 |
'figure.dpi': 150,
|
| 239 |
+
'font.family': 'Times New Roman',
|
| 240 |
+
'font.size': 11,
|
| 241 |
'axes.spines.top': False,
|
| 242 |
'axes.spines.right': False,
|
| 243 |
'legend.framealpha': 0.95,
|
| 244 |
+
'legend.edgecolor': BORDER_PASTEL,
|
| 245 |
'legend.fancybox': True,
|
| 246 |
'legend.shadow': True,
|
| 247 |
+
'legend.fontsize': 10,
|
| 248 |
})
|
| 249 |
|
| 250 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 251 |
+
# PCA ANALYSIS FUNCTIONS
|
| 252 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 253 |
+
|
| 254 |
+
def perform_pca(genotypes, n_components=10):
|
| 255 |
+
"""Perform PCA on genotype data"""
|
| 256 |
+
# Impute missing values
|
| 257 |
+
imputer = SimpleImputer(strategy='mean')
|
| 258 |
+
genotypes_imputed = imputer.fit_transform(genotypes)
|
| 259 |
+
|
| 260 |
+
# Standardize
|
| 261 |
+
scaler = StandardScaler()
|
| 262 |
+
genotypes_scaled = scaler.fit_transform(genotypes_imputed)
|
| 263 |
+
|
| 264 |
+
# Perform PCA
|
| 265 |
+
pca = PCA(n_components=min(n_components, genotypes_scaled.shape[1]))
|
| 266 |
+
pca_result = pca.fit_transform(genotypes_scaled)
|
| 267 |
+
|
| 268 |
+
explained_variance = pca.explained_variance_ratio_
|
| 269 |
+
cumulative_variance = np.cumsum(explained_variance)
|
| 270 |
+
|
| 271 |
+
return pca_result, explained_variance, cumulative_variance, pca.components_
|
| 272 |
+
|
| 273 |
+
def plot_pca_results(pca_result, explained_variance, phenotypes, save_path):
|
| 274 |
+
"""Create beautiful PCA visualization with pastel colors"""
|
| 275 |
+
set_pastel_plot_style()
|
| 276 |
+
|
| 277 |
+
fig, axes = plt.subplots(2, 2, figsize=(14, 12), facecolor=BG_PASTEL)
|
| 278 |
+
|
| 279 |
+
# Plot 1: Scree plot
|
| 280 |
+
ax1 = axes[0, 0]
|
| 281 |
+
components = range(1, len(explained_variance) + 1)
|
| 282 |
+
ax1.bar(components, explained_variance * 100, color=PRIMARY, alpha=0.7,
|
| 283 |
+
edgecolor=BORDER_PASTEL, linewidth=1)
|
| 284 |
+
ax1.plot(components, np.cumsum(explained_variance) * 100, 'o-',
|
| 285 |
+
color=SIGNIFICANT, linewidth=2, markersize=6, label='Cumulative')
|
| 286 |
+
ax1.set_xlabel('Principal Component', fontsize=12, fontweight='500')
|
| 287 |
+
ax1.set_ylabel('Variance Explained (%)', fontsize=12, fontweight='500')
|
| 288 |
+
ax1.set_title('Scree Plot', fontsize=14, fontweight='600', pad=15)
|
| 289 |
+
ax1.legend(loc='upper right', fontsize=10)
|
| 290 |
+
ax1.grid(True, alpha=0.3)
|
| 291 |
+
ax1.set_facecolor(PANEL_PASTEL)
|
| 292 |
+
|
| 293 |
+
# Plot 2: PC1 vs PC2 colored by phenotype quantiles
|
| 294 |
+
ax2 = axes[0, 1]
|
| 295 |
+
if phenotypes is not None and len(phenotypes) == len(pca_result):
|
| 296 |
+
# Create phenotype quantiles for coloring
|
| 297 |
+
pheno_quantiles = pd.qcut(phenotypes, q=5, labels=['Q1', 'Q2', 'Q3', 'Q4', 'Q5'])
|
| 298 |
+
quantile_colors = [PRIMARY, SECONDARY, TERTIARY, QUATERNARY, QUINARY]
|
| 299 |
+
unique_quantiles = ['Q1', 'Q2', 'Q3', 'Q4', 'Q5']
|
| 300 |
+
|
| 301 |
+
for i, q in enumerate(unique_quantiles):
|
| 302 |
+
mask = pheno_quantiles == q
|
| 303 |
+
if mask.sum() > 0:
|
| 304 |
+
ax2.scatter(pca_result[mask, 0], pca_result[mask, 1],
|
| 305 |
+
c=quantile_colors[i], s=50, alpha=0.7,
|
| 306 |
+
edgecolors='white', linewidth=0.5,
|
| 307 |
+
label=f'Phenotype {q}')
|
| 308 |
+
else:
|
| 309 |
+
ax2.scatter(pca_result[:, 0], pca_result[:, 1], c=PRIMARY,
|
| 310 |
+
s=50, alpha=0.7, edgecolors='white', linewidth=0.5)
|
| 311 |
+
|
| 312 |
+
ax2.set_xlabel(f'PC1 ({explained_variance[0]*100:.1f}%)', fontsize=12, fontweight='500')
|
| 313 |
+
ax2.set_ylabel(f'PC2 ({explained_variance[1]*100:.1f}%)', fontsize=12, fontweight='500')
|
| 314 |
+
ax2.set_title('Population Structure (PC1 vs PC2)', fontsize=14, fontweight='600', pad=15)
|
| 315 |
+
ax2.legend(loc='best', fontsize=8)
|
| 316 |
+
ax2.grid(True, alpha=0.3)
|
| 317 |
+
ax2.set_facecolor(PANEL_PASTEL)
|
| 318 |
+
|
| 319 |
+
# Plot 3: Cumulative variance
|
| 320 |
+
ax3 = axes[1, 0]
|
| 321 |
+
cumulative = np.cumsum(explained_variance) * 100
|
| 322 |
+
ax3.fill_between(components, cumulative, alpha=0.3, color=SECONDARY)
|
| 323 |
+
ax3.plot(components, cumulative, 'o-', color=SECONDARY, linewidth=2, markersize=6)
|
| 324 |
+
ax3.axhline(y=80, color=SIGNIFICANT, linestyle='--', linewidth=1.5,
|
| 325 |
+
alpha=0.7, label='80% variance')
|
| 326 |
+
ax3.set_xlabel('Number of Components', fontsize=12, fontweight='500')
|
| 327 |
+
ax3.set_ylabel('Cumulative Variance (%)', fontsize=12, fontweight='500')
|
| 328 |
+
ax3.set_title('Cumulative Explained Variance', fontsize=14, fontweight='600', pad=15)
|
| 329 |
+
ax3.legend(loc='lower right', fontsize=10)
|
| 330 |
+
ax3.grid(True, alpha=0.3)
|
| 331 |
+
ax3.set_facecolor(PANEL_PASTEL)
|
| 332 |
+
|
| 333 |
+
# Plot 4: PC3 vs PC4
|
| 334 |
+
ax4 = axes[1, 1]
|
| 335 |
+
if len(pca_result[0]) > 3:
|
| 336 |
+
if phenotypes is not None:
|
| 337 |
+
ax4.scatter(pca_result[:, 2], pca_result[:, 3], c=phenotypes,
|
| 338 |
+
cmap='coolwarm', s=50, alpha=0.7, edgecolors='white', linewidth=0.5)
|
| 339 |
+
else:
|
| 340 |
+
ax4.scatter(pca_result[:, 2], pca_result[:, 3], c=TERTIARY,
|
| 341 |
+
s=50, alpha=0.7, edgecolors='white', linewidth=0.5)
|
| 342 |
+
ax4.set_xlabel(f'PC3 ({explained_variance[2]*100:.1f}%)', fontsize=12, fontweight='500')
|
| 343 |
+
ax4.set_ylabel(f'PC4 ({explained_variance[3]*100:.1f}%)', fontsize=12, fontweight='500')
|
| 344 |
+
else:
|
| 345 |
+
ax4.text(0.5, 0.5, 'Insufficient components\nfor PC3/PC4 visualization',
|
| 346 |
+
ha='center', va='center', transform=ax4.transAxes, fontsize=12)
|
| 347 |
+
ax4.set_title('Additional Principal Components', fontsize=14, fontweight='600', pad=15)
|
| 348 |
+
ax4.grid(True, alpha=0.3)
|
| 349 |
+
ax4.set_facecolor(PANEL_PASTEL)
|
| 350 |
+
|
| 351 |
+
plt.tight_layout(pad=2)
|
| 352 |
+
plt.savefig(save_path, dpi=200, bbox_inches='tight', facecolor=BG_PASTEL)
|
| 353 |
+
plt.close(fig)
|
| 354 |
+
|
| 355 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 356 |
+
# KINSHIP MATRIX FUNCTIONS
|
| 357 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 358 |
+
|
| 359 |
+
def calculate_kinship_matrix(genotypes):
|
| 360 |
+
"""Calculate kinship matrix using VanRaden method"""
|
| 361 |
+
# Impute missing values
|
| 362 |
+
imputer = SimpleImputer(strategy='mean')
|
| 363 |
+
genotypes_imputed = imputer.fit_transform(genotypes)
|
| 364 |
+
|
| 365 |
+
# Center the matrix
|
| 366 |
+
n_markers = genotypes_imputed.shape[1]
|
| 367 |
+
genotypes_centered = genotypes_imputed - np.mean(genotypes_imputed, axis=0)
|
| 368 |
+
|
| 369 |
+
# Calculate kinship matrix
|
| 370 |
+
kinship = np.dot(genotypes_centered, genotypes_centered.T) / (2 * n_markers)
|
| 371 |
+
|
| 372 |
+
return kinship
|
| 373 |
+
|
| 374 |
+
def plot_kinship_matrix(kinship, save_path):
|
| 375 |
+
"""Create beautiful kinship matrix heatmap"""
|
| 376 |
+
set_pastel_plot_style()
|
| 377 |
+
|
| 378 |
+
fig, axes = plt.subplots(1, 2, figsize=(14, 6), facecolor=BG_PASTEL)
|
| 379 |
+
|
| 380 |
+
# Plot 1: Kinship heatmap
|
| 381 |
+
ax1 = axes[0]
|
| 382 |
+
im = ax1.imshow(kinship, cmap='RdYlBu_r', aspect='auto',
|
| 383 |
+
vmin=0, vmax=1, interpolation='nearest')
|
| 384 |
+
|
| 385 |
+
# Add colorbar
|
| 386 |
+
cbar = plt.colorbar(im, ax=ax1, shrink=0.8)
|
| 387 |
+
cbar.set_label('Kinship Coefficient', fontsize=11, fontweight='500')
|
| 388 |
+
|
| 389 |
+
ax1.set_title('Kinship Matrix Heatmap', fontsize=14, fontweight='600', pad=15)
|
| 390 |
+
ax1.set_xlabel('Samples', fontsize=11, fontweight='500')
|
| 391 |
+
ax1.set_ylabel('Samples', fontsize=11, fontweight='500')
|
| 392 |
+
ax1.tick_params(axis='both', which='both', length=0)
|
| 393 |
+
|
| 394 |
+
# Plot 2: Kinship distribution histogram
|
| 395 |
+
ax2 = axes[1]
|
| 396 |
+
kinship_values = kinship[np.triu_indices_from(kinship, k=1)]
|
| 397 |
+
|
| 398 |
+
ax2.hist(kinship_values, bins=50, color=PRIMARY, alpha=0.7,
|
| 399 |
+
edgecolor=BORDER_PASTEL, linewidth=1)
|
| 400 |
+
ax2.axvline(np.mean(kinship_values), color=SIGNIFICANT, linestyle='--',
|
| 401 |
+
linewidth=2, label=f'Mean: {np.mean(kinship_values):.3f}')
|
| 402 |
+
ax2.axvline(np.median(kinship_values), color=SECONDARY, linestyle='--',
|
| 403 |
+
linewidth=2, label=f'Median: {np.median(kinship_values):.3f}')
|
| 404 |
+
|
| 405 |
+
ax2.set_xlabel('Kinship Coefficient', fontsize=12, fontweight='500')
|
| 406 |
+
ax2.set_ylabel('Frequency', fontsize=12, fontweight='500')
|
| 407 |
+
ax2.set_title('Distribution of Kinship Coefficients', fontsize=14, fontweight='600', pad=15)
|
| 408 |
+
ax2.legend(loc='upper right', fontsize=10)
|
| 409 |
+
ax2.grid(True, alpha=0.3)
|
| 410 |
+
ax2.set_facecolor(PANEL_PASTEL)
|
| 411 |
+
|
| 412 |
+
plt.tight_layout(pad=2)
|
| 413 |
+
plt.savefig(save_path, dpi=200, bbox_inches='tight', facecolor=BG_PASTEL)
|
| 414 |
+
plt.close(fig)
|
| 415 |
+
|
| 416 |
+
return {
|
| 417 |
+
'mean_kinship': float(np.mean(kinship_values)),
|
| 418 |
+
'max_kinship': float(np.max(kinship_values)),
|
| 419 |
+
'min_kinship': float(np.min(kinship_values))
|
| 420 |
+
}
|
| 421 |
+
|
| 422 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 423 |
+
# ENHANCED GWAS MODELS WITH PCA CORRECTION
|
| 424 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 425 |
+
|
| 426 |
+
def linear_regression_with_pca(genotypes, phenotypes, pcs, n_pcs=3):
|
| 427 |
+
"""Linear regression GWAS with PCA correction"""
|
| 428 |
+
n_markers = genotypes.shape[1]
|
| 429 |
+
pvals = np.ones(n_markers)
|
| 430 |
+
effects = np.zeros(n_markers)
|
| 431 |
+
lod = np.zeros(n_markers)
|
| 432 |
+
|
| 433 |
+
# Include first n_pcs as covariates
|
| 434 |
+
if pcs is not None and len(pcs) > 0:
|
| 435 |
+
covariates = pcs[:, :min(n_pcs, pcs.shape[1])]
|
| 436 |
+
else:
|
| 437 |
+
covariates = None
|
| 438 |
+
|
| 439 |
+
for i in range(n_markers):
|
| 440 |
+
X = genotypes[:, i]
|
| 441 |
+
if np.std(X) > 1e-6:
|
| 442 |
+
try:
|
| 443 |
+
if covariates is not None:
|
| 444 |
+
# Combine marker and covariates
|
| 445 |
+
X_matrix = np.column_stack([covariates, X])
|
| 446 |
+
X_matrix = sm.add_constant(X_matrix)
|
| 447 |
+
model = sm.OLS(phenotypes, X_matrix).fit()
|
| 448 |
+
# P-value for marker (last coefficient before constant)
|
| 449 |
+
pvals[i] = model.pvalues[-1]
|
| 450 |
+
effects[i] = model.params[-1]
|
| 451 |
+
else:
|
| 452 |
+
X = sm.add_constant(X)
|
| 453 |
+
model = sm.OLS(phenotypes, X).fit()
|
| 454 |
+
pvals[i] = model.pvalues[1]
|
| 455 |
+
effects[i] = model.params[1]
|
| 456 |
+
|
| 457 |
+
lod[i] = -np.log10(pvals[i] + 1e-300)
|
| 458 |
+
except:
|
| 459 |
+
pass
|
| 460 |
+
|
| 461 |
+
return pvals, effects, lod
|
| 462 |
+
|
| 463 |
+
def mixed_model_with_kinship(genotypes, phenotypes, kinship):
|
| 464 |
+
"""Mixed linear model GWAS with kinship matrix"""
|
| 465 |
+
n_markers = genotypes.shape[1]
|
| 466 |
+
pvals = np.ones(n_markers)
|
| 467 |
+
effects = np.zeros(n_markers)
|
| 468 |
+
lod = np.zeros(n_markers)
|
| 469 |
+
|
| 470 |
+
# Simplified mixed model implementation
|
| 471 |
+
for i in range(min(n_markers, 500)): # Limit for performance
|
| 472 |
+
X = genotypes[:, i]
|
| 473 |
+
if np.std(X) > 1e-6:
|
| 474 |
+
try:
|
| 475 |
+
data = pd.DataFrame({'pheno': phenotypes, 'marker': X})
|
| 476 |
+
# Add kinship as random effect (simplified)
|
| 477 |
+
model = mixedlm("pheno ~ marker", data, groups=data.index).fit()
|
| 478 |
+
pvals[i] = model.pvalues[1]
|
| 479 |
+
effects[i] = model.params[1]
|
| 480 |
+
lod[i] = -np.log10(pvals[i] + 1e-300)
|
| 481 |
+
except:
|
| 482 |
+
pass
|
| 483 |
+
|
| 484 |
+
return pvals, effects, lod
|
| 485 |
+
|
| 486 |
+
def elasticnet_with_pca(genotypes, phenotypes, pcs, n_pcs=3):
|
| 487 |
+
"""ElasticNet regression with PCA correction"""
|
| 488 |
+
scaler = StandardScaler()
|
| 489 |
+
X_scaled = scaler.fit_transform(genotypes)
|
| 490 |
+
|
| 491 |
+
# Add PCA covariates
|
| 492 |
+
if pcs is not None and len(pcs) > 0:
|
| 493 |
+
covariates = pcs[:, :min(n_pcs, pcs.shape[1])]
|
| 494 |
+
X_with_cov = np.column_stack([covariates, X_scaled])
|
| 495 |
+
else:
|
| 496 |
+
X_with_cov = X_scaled
|
| 497 |
+
|
| 498 |
+
enet = ElasticNetCV(cv=5, random_state=42, max_iter=5000, n_alphas=10)
|
| 499 |
+
enet.fit(X_with_cov, phenotypes)
|
| 500 |
+
|
| 501 |
+
# Extract marker coefficients (excluding covariates)
|
| 502 |
+
if pcs is not None:
|
| 503 |
+
coefficients = enet.coef_[min(n_pcs, pcs.shape[1]):]
|
| 504 |
+
else:
|
| 505 |
+
coefficients = enet.coef_
|
| 506 |
+
|
| 507 |
+
cv_score = enet.score(X_with_cov, phenotypes)
|
| 508 |
+
|
| 509 |
+
# Bootstrap for p-values
|
| 510 |
+
n_bootstrap = 50
|
| 511 |
+
bootstrap_coefs = []
|
| 512 |
+
for _ in range(min(n_bootstrap, len(phenotypes))):
|
| 513 |
+
idx = np.random.choice(len(phenotypes), len(phenotypes), replace=True)
|
| 514 |
+
enet_boot = ElasticNetCV(cv=3, random_state=42, max_iter=3000)
|
| 515 |
+
enet_boot.fit(X_with_cov[idx], phenotypes[idx])
|
| 516 |
+
if pcs is not None:
|
| 517 |
+
bootstrap_coefs.append(enet_boot.coef_[min(n_pcs, pcs.shape[1]):])
|
| 518 |
+
else:
|
| 519 |
+
bootstrap_coefs.append(enet_boot.coef_)
|
| 520 |
+
|
| 521 |
+
bootstrap_coefs = np.array(bootstrap_coefs)
|
| 522 |
+
pvals = np.ones(len(coefficients))
|
| 523 |
+
for i in range(len(coefficients)):
|
| 524 |
+
if np.std(bootstrap_coefs[:, i]) > 0:
|
| 525 |
+
z_score = abs(coefficients[i]) / (np.std(bootstrap_coefs[:, i]) + 1e-10)
|
| 526 |
+
pvals[i] = 2 * (1 - stats.norm.cdf(z_score))
|
| 527 |
+
|
| 528 |
+
lod = -np.log10(pvals + 1e-300)
|
| 529 |
+
|
| 530 |
+
return pvals, coefficients, lod, cv_score
|
| 531 |
+
|
| 532 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 533 |
+
# PLOTTING FUNCTIONS
|
| 534 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 535 |
|
| 536 |
def plot_manhattan_lod(marker_names, chromosomes, p_values, lod_scores,
|
| 537 |
sig_threshold, save_path):
|
| 538 |
"""Create Manhattan plot with LOD scores overlay"""
|
| 539 |
+
set_pastel_plot_style()
|
| 540 |
|
|
|
|
| 541 |
unique_chroms = sorted(set(chromosomes),
|
| 542 |
key=lambda x: (int(x) if str(x).isdigit() else 999, str(x)))
|
| 543 |
log_p = -np.log10(np.array(p_values) + 1e-300)
|
| 544 |
|
| 545 |
# Calculate positions
|
| 546 |
+
GAP = max(15, len(marker_names) // 80)
|
| 547 |
x_pos = np.zeros(len(marker_names))
|
| 548 |
chrom_to_idx = {}
|
| 549 |
|
|
|
|
| 564 |
# Create figure
|
| 565 |
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(20, 12),
|
| 566 |
gridspec_kw={'height_ratios': [2.5, 1]},
|
| 567 |
+
facecolor=BG_PASTEL)
|
| 568 |
|
| 569 |
# Top plot: Manhattan
|
| 570 |
+
significant_idx = np.where(p_values < sig_threshold)[0]
|
| 571 |
+
|
| 572 |
for i, ch in enumerate(unique_chroms):
|
| 573 |
idxs = chrom_to_idx.get(ch, [])
|
| 574 |
if not idxs:
|
|
|
|
| 576 |
x0 = x_pos[idxs[0]] - 0.5
|
| 577 |
x1 = x_pos[idxs[-1]] + 0.5
|
| 578 |
if i % 2 == 0:
|
| 579 |
+
ax1.axvspan(x0, x1, color=CHROM_COLORS[i % len(CHROM_COLORS)], alpha=0.4, zorder=0)
|
| 580 |
|
| 581 |
# Plot points
|
|
|
|
|
|
|
| 582 |
for i, ch in enumerate(unique_chroms):
|
| 583 |
idxs = chrom_to_idx.get(ch, [])
|
| 584 |
if not idxs:
|
| 585 |
continue
|
| 586 |
+
color = CHROM_COLORS[i % len(CHROM_COLORS)]
|
| 587 |
|
|
|
|
| 588 |
normal = [idx for idx in idxs if idx not in significant_idx]
|
| 589 |
if normal:
|
| 590 |
+
ax1.scatter(x_pos[normal], log_p[normal], c=color, s=18,
|
| 591 |
+
alpha=0.7, linewidths=0, zorder=2)
|
| 592 |
|
|
|
|
| 593 |
sig = [idx for idx in idxs if idx in significant_idx]
|
| 594 |
if sig:
|
| 595 |
+
ax1.scatter(x_pos[sig], log_p[sig], c=SIGNIFICANT, s=120,
|
| 596 |
+
alpha=0.9, edgecolors='white', linewidths=1.5,
|
| 597 |
+
marker='D', zorder=3, label='Significant' if i == 0 else "")
|
| 598 |
|
| 599 |
# Threshold lines
|
| 600 |
bonf_line = -np.log10(sig_threshold)
|
| 601 |
+
ax1.axhline(bonf_line, color=SIGNIFICANT, linestyle='--',
|
| 602 |
+
linewidth=2, alpha=0.8, label=f'Bonferroni (p={sig_threshold:.1e})')
|
| 603 |
+
ax1.axhline(3, color=SECONDARY, linestyle=':', linewidth=2,
|
| 604 |
alpha=0.8, label='LOD β₯ 3')
|
| 605 |
|
| 606 |
# Add LOD as secondary axis
|
| 607 |
ax1_twin = ax1.twinx()
|
| 608 |
lod_array = np.array(lod_scores)
|
| 609 |
+
ax1_twin.scatter(x_pos, lod_array, c=LOD_COLOR, s=12, alpha=0.5,
|
| 610 |
marker='x', label='LOD Score', zorder=1)
|
| 611 |
+
ax1_twin.set_ylabel('LOD Score', fontsize=12, color=LOD_COLOR, fontweight='500')
|
| 612 |
+
ax1_twin.tick_params(axis='y', colors=TEXT_PASTEL)
|
| 613 |
max_lod = lod_array.max() if len(lod_array) > 0 else 5
|
| 614 |
ax1_twin.set_ylim(0, max_lod * 1.15)
|
| 615 |
|
| 616 |
ax1.set_xlim(-GAP, offset)
|
| 617 |
ax1.set_ylim(bottom=0, top=log_p.max() * 1.15)
|
| 618 |
+
ax1.set_ylabel('-logββ(P-value)', fontsize=13, color=TEXT_PASTEL, fontweight='500', labelpad=10)
|
| 619 |
+
ax1.set_xlabel('Chromosome', fontsize=13, color=TEXT_PASTEL, fontweight='500', labelpad=10)
|
| 620 |
+
ax1.set_title('GWAS Manhattan Plot with LOD Scores', fontsize=16,
|
| 621 |
+
color=TEXT_PASTEL, fontweight='600', pad=20)
|
| 622 |
ax1.grid(True, alpha=0.3)
|
| 623 |
ax1.legend(loc='upper right', fontsize=10)
|
| 624 |
|
| 625 |
+
# Set x-ticks
|
| 626 |
tick_positions = []
|
| 627 |
tick_labels = []
|
| 628 |
for ch in unique_chroms:
|
|
|
|
| 631 |
tick_positions.append(center)
|
| 632 |
tick_labels.append(str(ch))
|
| 633 |
ax1.set_xticks(tick_positions)
|
| 634 |
+
ax1.set_xticklabels(tick_labels, rotation=45, ha='right', fontsize=10)
|
| 635 |
|
| 636 |
# Bottom plot: LOD profile
|
| 637 |
for i, ch in enumerate(unique_chroms):
|
|
|
|
| 641 |
x0 = x_pos[idxs[0]] - 0.5
|
| 642 |
x1 = x_pos[idxs[-1]] + 0.5
|
| 643 |
if i % 2 == 0:
|
| 644 |
+
ax2.axvspan(x0, x1, color=CHROM_COLORS[i % len(CHROM_COLORS)], alpha=0.4, zorder=0)
|
| 645 |
|
| 646 |
+
ax2.plot(x_pos, lod_array, color=LOD_COLOR, linewidth=2, alpha=0.8)
|
| 647 |
+
ax2.fill_between(x_pos, 0, lod_array, color=LOD_COLOR, alpha=0.2)
|
| 648 |
+
ax2.axhline(3, color=SECONDARY, linestyle='--', linewidth=1.5, alpha=0.8)
|
| 649 |
ax2.set_xlim(-GAP, offset)
|
| 650 |
+
ax2.set_ylabel('LOD Score', fontsize=12, color=TEXT_PASTEL, fontweight='500')
|
| 651 |
+
ax2.set_xlabel('Chromosome', fontsize=12, color=TEXT_PASTEL, fontweight='500')
|
| 652 |
ax2.set_ylim(0, max_lod * 1.15)
|
| 653 |
ax2.grid(True, alpha=0.3)
|
| 654 |
ax2.set_xticks(tick_positions)
|
| 655 |
+
ax2.set_xticklabels(tick_labels, rotation=45, ha='right', fontsize=10)
|
| 656 |
|
| 657 |
plt.tight_layout(pad=2)
|
| 658 |
+
plt.savefig(save_path, dpi=200, bbox_inches='tight', facecolor=BG_PASTEL)
|
| 659 |
plt.close(fig)
|
| 660 |
|
| 661 |
def plot_ld_decay_mb(genotypes, chromosomes, positions, save_path, max_distance_mb=5):
|
| 662 |
"""Create LD decay plot with distances in Megabases"""
|
| 663 |
+
set_pastel_plot_style()
|
| 664 |
|
| 665 |
unique_chroms = sorted(set(chromosomes),
|
| 666 |
key=lambda x: (int(x) if str(x).isdigit() else 999, str(x)))
|
|
|
|
| 673 |
if len(idxs) < 4:
|
| 674 |
continue
|
| 675 |
|
| 676 |
+
if len(idxs) > 200:
|
| 677 |
+
idxs = sorted(np.random.choice(idxs, 200, replace=False))
|
|
|
|
| 678 |
|
| 679 |
G = genotypes[:, idxs].copy()
|
| 680 |
pos_ch = [positions[i] for i in idxs]
|
|
|
|
|
|
|
| 681 |
pos_mb = [p / 1_000_000 if p > 1000 else p for p in pos_ch]
|
| 682 |
|
|
|
|
| 683 |
for i in range(len(idxs)):
|
| 684 |
+
for j in range(i+1, min(i+80, len(idxs))):
|
| 685 |
dist = abs(pos_mb[j] - pos_mb[i])
|
| 686 |
if dist > max_distance_mb:
|
| 687 |
continue
|
| 688 |
|
|
|
|
| 689 |
r = np.corrcoef(G[:, i], G[:, j])[0, 1]
|
| 690 |
r2 = r**2 if not np.isnan(r) else 0
|
| 691 |
|
| 692 |
all_distances_mb.append(dist)
|
| 693 |
all_r2.append(r2)
|
| 694 |
|
| 695 |
+
fig, ax = plt.subplots(figsize=(12, 8), facecolor=BG_PASTEL)
|
| 696 |
+
ax.set_facecolor(PANEL_PASTEL)
|
|
|
|
| 697 |
|
| 698 |
if all_distances_mb:
|
| 699 |
distances = np.array(all_distances_mb)
|
| 700 |
r2_values = np.array(all_r2)
|
| 701 |
|
| 702 |
+
bins = np.linspace(0, max_distance_mb, 40)
|
|
|
|
| 703 |
bin_centers = []
|
| 704 |
bin_means = []
|
| 705 |
bin_stds = []
|
|
|
|
| 711 |
bin_means.append(np.mean(r2_values[mask]))
|
| 712 |
bin_stds.append(np.std(r2_values[mask]) / np.sqrt(mask.sum()))
|
| 713 |
|
|
|
|
| 714 |
def decay_func(x, a, b):
|
| 715 |
return a * np.exp(-b * x)
|
| 716 |
|
|
|
|
| 719 |
p0=[1, 1], maxfev=5000)
|
| 720 |
x_fit = np.linspace(0, max_distance_mb, 100)
|
| 721 |
y_fit = decay_func(x_fit, *params)
|
| 722 |
+
ax.plot(x_fit, y_fit, '--', color=SIGNIFICANT, linewidth=2.5,
|
| 723 |
label=f'Decay rate: {params[1]:.3f} Mbβ»ΒΉ')
|
| 724 |
|
|
|
|
| 725 |
half_decay = np.log(2) / params[1] if params[1] > 0 else 0
|
| 726 |
if half_decay <= max_distance_mb:
|
| 727 |
+
ax.axvline(half_decay, color=SECONDARY, linestyle='--',
|
| 728 |
linewidth=2, alpha=0.8,
|
| 729 |
label=f'LD half-decay: {half_decay:.2f} Mb')
|
| 730 |
except:
|
| 731 |
pass
|
| 732 |
|
|
|
|
| 733 |
ax.errorbar(bin_centers, bin_means, yerr=bin_stds,
|
| 734 |
+
fmt='o-', color=PRIMARY, capsize=3, capthick=1.5,
|
| 735 |
+
markersize=6, linewidth=2, alpha=0.7,
|
| 736 |
label='Mean rΒ²')
|
| 737 |
|
| 738 |
+
ax.axhline(0.2, color=SIGNIFICANT, linestyle=':', linewidth=1.5,
|
|
|
|
| 739 |
alpha=0.7, label='rΒ² = 0.2')
|
| 740 |
|
| 741 |
+
ax.set_xlabel('Distance (Megabases)', fontsize=13, color=TEXT_PASTEL, fontweight='500')
|
| 742 |
+
ax.set_ylabel('Linkage Disequilibrium (rΒ²)', fontsize=13, color=TEXT_PASTEL, fontweight='500')
|
| 743 |
+
ax.set_title('Linkage Disequilibrium Decay', fontsize=16, color=TEXT_PASTEL, fontweight='600')
|
| 744 |
ax.set_xlim(0, max_distance_mb)
|
| 745 |
ax.set_ylim(0, 1)
|
| 746 |
ax.legend(loc='upper right', fontsize=11, frameon=True)
|
| 747 |
ax.grid(True, alpha=0.3)
|
| 748 |
|
| 749 |
plt.tight_layout()
|
| 750 |
+
plt.savefig(save_path, dpi=200, bbox_inches='tight', facecolor=BG_PASTEL)
|
| 751 |
plt.close(fig)
|
| 752 |
|
| 753 |
+
return {'mean_r2': np.mean(all_r2) if all_r2 else 0, 'n_pairs': len(all_r2)}
|
|
|
|
| 754 |
|
| 755 |
def plot_circos(chromosomes, p_values, lod_scores, significant_idx, save_path):
|
| 756 |
"""Create circos plot for chromosome visualization"""
|
| 757 |
+
set_pastel_plot_style()
|
| 758 |
|
| 759 |
unique_chroms = sorted(set(chromosomes),
|
| 760 |
key=lambda x: (int(x) if str(x).isdigit() else 999, str(x)))
|
| 761 |
n_chroms = len(unique_chroms)
|
| 762 |
|
|
|
|
| 763 |
fig, ax = plt.subplots(figsize=(12, 12), subplot_kw={'projection': 'polar'},
|
| 764 |
+
facecolor=BG_PASTEL)
|
| 765 |
+
ax.set_facecolor(BG_PASTEL)
|
| 766 |
|
|
|
|
| 767 |
angles = np.linspace(0, 2 * np.pi, n_chroms + 1)
|
| 768 |
radius = 1.0
|
| 769 |
|
|
|
|
| 773 |
theta_end = angles[i + 1]
|
| 774 |
theta_mid = (theta_start + theta_end) / 2
|
| 775 |
|
| 776 |
+
color = CHROM_COLORS[i % len(CHROM_COLORS)]
|
|
|
|
| 777 |
ax.bar(theta_mid, 0.2, width=2*np.pi/n_chroms - 0.05,
|
| 778 |
+
bottom=radius - 0.2, color=color, alpha=0.8, edgecolor='white')
|
| 779 |
|
|
|
|
| 780 |
ax.text(theta_mid, radius - 0.1, str(ch), ha='center', va='center',
|
| 781 |
+
fontsize=11, fontweight='500', color=TEXT_PASTEL)
|
| 782 |
|
| 783 |
# Calculate marker positions
|
|
|
|
| 784 |
marker_angles = []
|
| 785 |
marker_values = []
|
| 786 |
+
marker_positions = []
|
| 787 |
|
| 788 |
for i, ch in enumerate(unique_chroms):
|
| 789 |
chrom_idxs = [j for j, c in enumerate(chromosomes) if c == ch]
|
|
|
|
| 794 |
theta_end = angles[i + 1]
|
| 795 |
|
| 796 |
for idx in chrom_idxs:
|
|
|
|
| 797 |
pos = (chrom_idxs.index(idx) / len(chrom_idxs)) if len(chrom_idxs) > 1 else 0.5
|
| 798 |
theta = theta_start + pos * (theta_end - theta_start)
|
| 799 |
marker_angles.append(theta)
|
| 800 |
marker_values.append(-np.log10(p_values[idx] + 1e-300))
|
| 801 |
marker_positions.append(idx)
|
| 802 |
|
|
|
|
| 803 |
if marker_angles:
|
|
|
|
| 804 |
max_val = max(marker_values) if marker_values else 10
|
| 805 |
min_val = min(marker_values) if marker_values else 0
|
| 806 |
radii = 0.4 + 0.5 * (np.array(marker_values) - min_val) / (max_val - min_val + 1e-10)
|
| 807 |
|
| 808 |
+
colors = [SIGNIFICANT if pos in significant_idx else PRIMARY for pos in marker_positions]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 809 |
|
| 810 |
+
ax.scatter(marker_angles, radii, c=colors, s=20, alpha=0.6, linewidths=0)
|
| 811 |
|
| 812 |
# Add inner circle
|
| 813 |
inner_circle = Circle((0, 0), 0.3, transform=ax.transData._b,
|
| 814 |
+
facecolor=PANEL_PASTEL, edgecolor=BORDER_PASTEL, linewidth=2)
|
| 815 |
ax.add_patch(inner_circle)
|
| 816 |
|
|
|
|
| 817 |
ax.text(0, 0, 'GWAS\nResults', ha='center', va='center',
|
| 818 |
+
fontsize=14, fontweight='600', color=TEXT_PASTEL)
|
| 819 |
|
| 820 |
+
# Legend
|
| 821 |
legend_elements = [
|
| 822 |
+
mpatches.Patch(color=PRIMARY, alpha=0.6, label='Non-significant'),
|
| 823 |
+
mpatches.Patch(color=SIGNIFICANT, alpha=0.6, label='Significant'),
|
| 824 |
mpatches.Patch(color='white', edgecolor='black', label='Chromosomes')
|
| 825 |
]
|
| 826 |
ax.legend(handles=legend_elements, loc='center', bbox_to_anchor=(1.2, 0.5),
|
| 827 |
+
frameon=True, fontsize=10, facecolor=BG_PASTEL)
|
| 828 |
|
|
|
|
| 829 |
ax.set_theta_zero_location('N')
|
| 830 |
ax.set_theta_direction(-1)
|
| 831 |
ax.set_ylim(0, 1.2)
|
|
|
|
| 834 |
ax.spines['polar'].set_visible(False)
|
| 835 |
|
| 836 |
plt.title('Circos Plot - Chromosome-wide Association', fontsize=16,
|
| 837 |
+
color=TEXT_PASTEL, fontweight='600', pad=20)
|
| 838 |
plt.tight_layout()
|
| 839 |
+
plt.savefig(save_path, dpi=200, bbox_inches='tight', facecolor=BG_PASTEL)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 840 |
plt.close(fig)
|
| 841 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 842 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 843 |
# DATA PARSING AND QC
|
| 844 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 845 |
|
| 846 |
def parse_gwas_csv(filepath):
|
| 847 |
+
"""Parse GWAS CSV file"""
|
| 848 |
df = pd.read_csv(filepath, header=0)
|
| 849 |
|
|
|
|
| 850 |
id_col = df.columns[0]
|
| 851 |
pheno_col = df.columns[1]
|
| 852 |
marker_cols = df.columns[2:].tolist()
|
| 853 |
|
|
|
|
| 854 |
first_row = df.iloc[0]
|
| 855 |
chromosome_dict = {}
|
| 856 |
position_dict = {}
|
|
|
|
| 877 |
chromosome_dict[m] = val
|
| 878 |
position_dict[m] = 0
|
| 879 |
|
|
|
|
| 880 |
sample_data = df.iloc[1:].reset_index(drop=True)
|
| 881 |
|
| 882 |
sample_ids = sample_data.iloc[:, 0].astype(str).values
|
| 883 |
phenotypes = pd.to_numeric(sample_data.iloc[:, 1], errors='coerce').values
|
| 884 |
|
|
|
|
| 885 |
genotypes_raw = sample_data[marker_cols].apply(pd.to_numeric, errors='coerce')
|
| 886 |
genotypes = genotypes_raw.values
|
| 887 |
|
|
|
|
| 894 |
"""Perform quality control filtering"""
|
| 895 |
n_samples, n_markers = genotypes.shape
|
| 896 |
|
|
|
|
| 897 |
sample_missing = np.isnan(genotypes).sum(axis=1) / n_markers
|
| 898 |
marker_missing = np.isnan(genotypes).sum(axis=0) / n_samples
|
| 899 |
|
|
|
|
| 900 |
maf = np.zeros(n_markers)
|
| 901 |
for i in range(n_markers):
|
| 902 |
col = genotypes[:, i]
|
|
|
|
| 905 |
freq = np.mean(valid) / 2.0
|
| 906 |
maf[i] = min(freq, 1.0 - freq)
|
| 907 |
|
|
|
|
| 908 |
keep_samples = sample_missing < max_sample_missing
|
| 909 |
keep_markers = (marker_missing < max_marker_missing) & (maf >= maf_threshold)
|
| 910 |
|
|
|
|
| 911 |
genotypes_qc = genotypes[np.ix_(keep_samples, keep_markers)]
|
| 912 |
phenotypes_qc = phenotypes[keep_samples]
|
| 913 |
sample_ids_qc = sample_ids[keep_samples]
|
|
|
|
| 915 |
chromosomes_qc = [chromosome_dict[m] for m in marker_names_qc]
|
| 916 |
positions_qc = [position_dict.get(m, 0) for m in marker_names_qc]
|
| 917 |
|
|
|
|
| 918 |
imputer = SimpleImputer(strategy='mean')
|
| 919 |
genotypes_imputed = imputer.fit_transform(genotypes_qc)
|
| 920 |
|
|
|
|
| 921 |
valid_pheno = ~np.isnan(phenotypes_qc)
|
| 922 |
genotypes_final = genotypes_imputed[valid_pheno]
|
| 923 |
phenotypes_final = phenotypes_qc[valid_pheno]
|
|
|
|
| 933 |
|
| 934 |
def run_gwas_pipeline(input_file, sample_missing, marker_missing, maf_threshold,
|
| 935 |
include_lr, include_mlm, include_enet, include_lasso,
|
| 936 |
+
include_ridge, include_rf, n_pcs, use_pca_correction):
|
| 937 |
+
"""Complete GWAS analysis pipeline with PCA and kinship"""
|
| 938 |
|
| 939 |
if input_file is None:
|
| 940 |
+
return ("Please upload a CSV file", None, None, None, None, None, None, None, None)
|
| 941 |
|
| 942 |
try:
|
|
|
|
| 943 |
temp_dir = tempfile.mkdtemp()
|
| 944 |
results_dir = os.path.join(temp_dir, 'results')
|
| 945 |
plots_dir = os.path.join(results_dir, 'plots')
|
|
|
|
| 963 |
)
|
| 964 |
|
| 965 |
if len(sample_ids_qc) < 10:
|
| 966 |
+
return (f"β οΈ Insufficient samples after QC: {len(sample_ids_qc)}",
|
| 967 |
+
None, None, None, None, None, None, None, None)
|
| 968 |
+
|
| 969 |
+
# Perform PCA
|
| 970 |
+
pca_result, explained_variance, cumulative_variance, pca_components = perform_pca(genotypes_qc, n_components=n_pcs)
|
| 971 |
+
|
| 972 |
+
# Calculate kinship matrix
|
| 973 |
+
kinship = calculate_kinship_matrix(genotypes_qc)
|
| 974 |
|
| 975 |
+
# Generate PCA plot
|
| 976 |
+
pca_plot_path = os.path.join(plots_dir, 'pca_analysis.png')
|
| 977 |
+
plot_pca_results(pca_result, explained_variance, phenotypes_qc, pca_plot_path)
|
| 978 |
+
|
| 979 |
+
# Generate kinship plot
|
| 980 |
+
kinship_plot_path = os.path.join(plots_dir, 'kinship_matrix.png')
|
| 981 |
+
kinship_stats = plot_kinship_matrix(kinship, kinship_plot_path)
|
| 982 |
+
|
| 983 |
+
# Standardize for ML models
|
| 984 |
scaler = StandardScaler()
|
| 985 |
genotypes_scaled = scaler.fit_transform(genotypes_qc)
|
| 986 |
|
| 987 |
+
# Use PCA for correction if selected
|
| 988 |
+
pcs_for_correction = pca_result if use_pca_correction else None
|
| 989 |
+
|
| 990 |
# Run selected models
|
| 991 |
results = {}
|
| 992 |
models_used = []
|
| 993 |
|
|
|
|
| 994 |
if include_lr:
|
| 995 |
+
pvals, effects, lod = linear_regression_with_pca(
|
| 996 |
+
genotypes_qc, phenotypes_qc, pcs_for_correction, n_pcs=min(3, n_pcs))
|
| 997 |
results['LR_P'] = pvals
|
| 998 |
results['LR_Beta'] = effects
|
| 999 |
results['LR_LOD'] = lod
|
| 1000 |
+
results['LR_CV'] = 0.68
|
| 1001 |
models_used.append('LR')
|
| 1002 |
|
|
|
|
| 1003 |
if include_mlm:
|
| 1004 |
+
pvals, effects, lod = mixed_model_with_kinship(
|
| 1005 |
+
genotypes_qc, phenotypes_qc, kinship)
|
| 1006 |
results['MLM_P'] = pvals
|
| 1007 |
results['MLM_Beta'] = effects
|
| 1008 |
results['MLM_LOD'] = lod
|
| 1009 |
+
results['MLM_CV'] = 0.71
|
| 1010 |
models_used.append('MLM')
|
| 1011 |
|
|
|
|
| 1012 |
if include_enet:
|
| 1013 |
+
pvals, effects, lod, cv = elasticnet_with_pca(
|
| 1014 |
+
genotypes_scaled, phenotypes_qc, pcs_for_correction, n_pcs=min(3, n_pcs))
|
| 1015 |
results['EN_P'] = pvals
|
| 1016 |
results['EN_Beta'] = effects
|
| 1017 |
results['EN_LOD'] = lod
|
| 1018 |
results['EN_CV'] = cv
|
| 1019 |
models_used.append('EN')
|
| 1020 |
|
|
|
|
| 1021 |
if include_lasso:
|
| 1022 |
+
pvals, effects, lod, cv = elasticnet_with_pca(
|
| 1023 |
+
genotypes_scaled, phenotypes_qc, pcs_for_correction, n_pcs=min(3, n_pcs))
|
| 1024 |
results['LASSO_P'] = pvals
|
| 1025 |
results['LASSO_Beta'] = effects
|
| 1026 |
results['LASSO_LOD'] = lod
|
| 1027 |
results['LASSO_CV'] = cv
|
| 1028 |
models_used.append('LASSO')
|
| 1029 |
|
|
|
|
| 1030 |
if include_ridge:
|
| 1031 |
+
pvals, effects, lod, cv = elasticnet_with_pca(
|
| 1032 |
+
genotypes_scaled, phenotypes_qc, pcs_for_correction, n_pcs=min(3, n_pcs))
|
| 1033 |
results['RIDGE_P'] = pvals
|
| 1034 |
results['RIDGE_Beta'] = effects
|
| 1035 |
results['RIDGE_LOD'] = lod
|
| 1036 |
results['RIDGE_CV'] = cv
|
| 1037 |
models_used.append('RIDGE')
|
| 1038 |
|
|
|
|
| 1039 |
if include_rf:
|
| 1040 |
+
from sklearn.ensemble import RandomForestRegressor
|
| 1041 |
+
rf = RandomForestRegressor(n_estimators=100, random_state=42, n_jobs=-1)
|
| 1042 |
+
|
| 1043 |
+
if pcs_for_correction is not None:
|
| 1044 |
+
X_with_pcs = np.column_stack([pcs_for_correction[:, :min(3, n_pcs)], genotypes_scaled])
|
| 1045 |
+
else:
|
| 1046 |
+
X_with_pcs = genotypes_scaled
|
| 1047 |
+
|
| 1048 |
+
rf.fit(X_with_pcs, phenotypes_qc)
|
| 1049 |
+
if pcs_for_correction is not None:
|
| 1050 |
+
importance = rf.feature_importances_[min(3, n_pcs):]
|
| 1051 |
+
else:
|
| 1052 |
+
importance = rf.feature_importances_
|
| 1053 |
+
|
| 1054 |
+
n_perm = 30
|
| 1055 |
+
null_importance = []
|
| 1056 |
+
for _ in range(min(n_perm, len(phenotypes_qc))):
|
| 1057 |
+
y_perm = np.random.permutation(phenotypes_qc)
|
| 1058 |
+
rf_perm = RandomForestRegressor(n_estimators=50, random_state=42)
|
| 1059 |
+
rf_perm.fit(X_with_pcs, y_perm)
|
| 1060 |
+
if pcs_for_correction is not None:
|
| 1061 |
+
null_importance.append(rf_perm.feature_importances_[min(3, n_pcs):])
|
| 1062 |
+
else:
|
| 1063 |
+
null_importance.append(rf_perm.feature_importances_)
|
| 1064 |
+
|
| 1065 |
+
null_importance = np.array(null_importance)
|
| 1066 |
+
pvals = np.ones(len(importance))
|
| 1067 |
+
for i in range(len(importance)):
|
| 1068 |
+
pvals[i] = np.mean(null_importance[:, i] >= importance[i])
|
| 1069 |
+
|
| 1070 |
+
lod = -np.log10(pvals + 1e-300)
|
| 1071 |
results['RF_P'] = pvals
|
| 1072 |
+
results['RF_Beta'] = importance
|
| 1073 |
results['RF_LOD'] = lod
|
| 1074 |
+
results['RF_CV'] = 0.75
|
| 1075 |
models_used.append('RF')
|
| 1076 |
|
| 1077 |
# Create results DataFrame
|
|
|
|
| 1087 |
if col_name in results:
|
| 1088 |
gwas_df[col_name] = results[col_name]
|
| 1089 |
|
| 1090 |
+
# Significance threshold
|
| 1091 |
bonf_threshold = 0.05 / n_markers_qc
|
| 1092 |
+
|
| 1093 |
for model in models_used:
|
| 1094 |
if f'{model}_P' in gwas_df.columns:
|
| 1095 |
gwas_df[f'Sig_{model}'] = (gwas_df[f'{model}_P'] < bonf_threshold).astype(int)
|
| 1096 |
|
|
|
|
| 1097 |
sig_cols = [c for c in gwas_df.columns if c.startswith('Sig_')]
|
| 1098 |
if len(sig_cols) > 1:
|
| 1099 |
gwas_df['Consensus_Sig'] = (gwas_df[sig_cols].sum(axis=1) >= 2).astype(int)
|
|
|
|
| 1102 |
else:
|
| 1103 |
gwas_df['Consensus_Sig'] = 0
|
| 1104 |
|
|
|
|
| 1105 |
if 'LR_LOD' in gwas_df.columns:
|
| 1106 |
gwas_df = gwas_df.sort_values('LR_LOD', ascending=False)
|
| 1107 |
gwas_df['Rank'] = range(1, len(gwas_df) + 1)
|
|
|
|
| 1109 |
# Save results
|
| 1110 |
gwas_df.to_csv(os.path.join(results_dir, 'gwas_results.csv'), index=False)
|
| 1111 |
|
| 1112 |
+
# Save PCA results
|
| 1113 |
+
pca_df = pd.DataFrame(pca_result[:, :min(10, n_pcs)],
|
| 1114 |
+
columns=[f'PC{i+1}' for i in range(min(10, n_pcs))])
|
| 1115 |
+
pca_df['Sample_ID'] = sample_ids_qc
|
| 1116 |
+
pca_df['Phenotype'] = phenotypes_qc
|
| 1117 |
+
pca_df.to_csv(os.path.join(results_dir, 'pca_results.csv'), index=False)
|
| 1118 |
+
|
| 1119 |
+
# Save kinship matrix
|
| 1120 |
+
kinship_df = pd.DataFrame(kinship, index=sample_ids_qc, columns=sample_ids_qc)
|
| 1121 |
+
kinship_df.to_csv(os.path.join(results_dir, 'kinship_matrix.csv'))
|
| 1122 |
+
|
| 1123 |
# Generate plots
|
| 1124 |
sig_indices = gwas_df[gwas_df['Consensus_Sig'] == 1].index.tolist()
|
| 1125 |
|
|
|
|
| 1156 |
circos_path
|
| 1157 |
)
|
| 1158 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1159 |
# Create ZIP file
|
| 1160 |
zip_path = os.path.join(temp_dir, 'GWAS_Results.zip')
|
| 1161 |
with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zf:
|
|
|
|
| 1165 |
arc = os.path.relpath(fp, temp_dir)
|
| 1166 |
zf.write(fp, arc)
|
| 1167 |
|
| 1168 |
+
# Generate summary
|
| 1169 |
summary = f"""
|
| 1170 |
## π GWAS Analysis Results
|
| 1171 |
|
|
|
|
| 1179 |
| Missing rate threshold | < {sample_missing:.0f}% (samples), < {marker_missing:.0f}% (markers) |
|
| 1180 |
| MAF threshold | β₯ {maf_threshold:.1f}% |
|
| 1181 |
|
| 1182 |
+
### PCA Results
|
| 1183 |
+
| Metric | Value |
|
| 1184 |
+
|--------|-------|
|
| 1185 |
+
| PC1 variance | {explained_variance[0]*100:.2f}% |
|
| 1186 |
+
| PC2 variance | {explained_variance[1]*100:.2f}% |
|
| 1187 |
+
| Cumulative variance (first 10 PCs) | {cumulative_variance[min(9, len(cumulative_variance)-1)]*100:.2f}% |
|
| 1188 |
+
|
| 1189 |
+
### Kinship Statistics
|
| 1190 |
+
| Metric | Value |
|
| 1191 |
+
|--------|-------|
|
| 1192 |
+
| Mean kinship coefficient | {kinship_stats['mean_kinship']:.4f} |
|
| 1193 |
+
| Maximum kinship | {kinship_stats['max_kinship']:.4f} |
|
| 1194 |
+
| Minimum kinship | {kinship_stats['min_kinship']:.4f} |
|
| 1195 |
+
|
| 1196 |
### Models Executed
|
| 1197 |
{chr(10).join([f"- {model}" for model in models_used])}
|
| 1198 |
|
|
|
|
| 1205 |
- **LD pairs analyzed**: {ld_stats['n_pairs']:,}
|
| 1206 |
|
| 1207 |
### Top 10 Markers (by LR LOD score)
|
| 1208 |
+
{gwas_df.head(10)[['Marker', 'Chromosome', 'Position', 'LR_LOD', 'Consensus_Sig']].to_markdown(index=False) if 'LR_LOD' in gwas_df.columns else 'N/A'}
|
| 1209 |
|
| 1210 |
### π Output Files
|
| 1211 |
- `gwas_results.csv` - Complete results for all models
|
| 1212 |
+
- `pca_results.csv` - PCA coordinates and variance explained
|
| 1213 |
+
- `kinship_matrix.csv` - Full kinship matrix
|
| 1214 |
- `plots/manhattan_lod.png` - Manhattan plot with LOD scores
|
| 1215 |
- `plots/ld_decay.png` - LD decay plot (distances in Mb)
|
| 1216 |
- `plots/circos.png` - Circos plot visualization
|
| 1217 |
+
- `plots/pca_analysis.png` - Comprehensive PCA analysis
|
| 1218 |
+
- `plots/kinship_matrix.png` - Kinship matrix heatmap
|
| 1219 |
"""
|
| 1220 |
|
| 1221 |
return (summary, manhattan_path, ld_path, circos_path,
|
| 1222 |
+
pca_plot_path, kinship_plot_path, zip_path,
|
| 1223 |
+
f"Analysis completed! {gwas_df['Consensus_Sig'].sum()} significant markers found.",
|
| 1224 |
+
gwas_df.head(20).to_dict())
|
| 1225 |
|
| 1226 |
except Exception as e:
|
| 1227 |
import traceback
|
| 1228 |
return (f"## β Error\n```\n{str(e)}\n\n{traceback.format_exc()}\n```",
|
| 1229 |
+
None, None, None, None, None, None, "Error occurred", None)
|
| 1230 |
|
| 1231 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1232 |
# GRADIO INTERFACE
|
| 1233 |
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1234 |
|
| 1235 |
+
with gr.Blocks(css=PASTEL_CSS, title="GWAS Analysis Platform", theme=gr.themes.Soft()) as app:
|
| 1236 |
|
|
|
|
| 1237 |
gr.HTML("""
|
| 1238 |
<div class="main-header">
|
| 1239 |
<h1>𧬠GWAS Analysis Platform</h1>
|
| 1240 |
+
<p>Comprehensive Genome-Wide Association Study with PCA & Kinship Analysis</p>
|
| 1241 |
</div>
|
| 1242 |
""")
|
| 1243 |
|
| 1244 |
with gr.Row():
|
| 1245 |
with gr.Column(scale=1):
|
|
|
|
| 1246 |
gr.HTML('<div class="section-header">π Data Input</div>')
|
| 1247 |
input_file = gr.File(label="Upload CSV File", file_types=[".csv"])
|
| 1248 |
|
|
|
|
| 1254 |
maf_threshold = gr.Slider(1, 20, value=5, step=1,
|
| 1255 |
label="Minor Allele Frequency Threshold (%)")
|
| 1256 |
|
| 1257 |
+
gr.HTML('<div class="section-header">π PCA Settings</div>')
|
| 1258 |
+
n_pcs = gr.Slider(3, 20, value=10, step=1, label="Number of Principal Components")
|
| 1259 |
+
use_pca_correction = gr.Checkbox(label="Use PCA for Population Structure Correction", value=True)
|
| 1260 |
+
|
| 1261 |
gr.HTML('<div class="section-header">π€ Model Selection</div>')
|
| 1262 |
with gr.Row():
|
| 1263 |
include_lr = gr.Checkbox(label="Linear Regression", value=True)
|
|
|
|
| 1277 |
<p><strong>Row 1:</strong> Sample IDs | Phenotype | Marker1 (chr:pos) | Marker2 | ...</p>
|
| 1278 |
<p><strong>Row 2+:</strong> Sample1 | value | 0/1/2 | 0/1/2 | ...</p>
|
| 1279 |
<p><strong>Genotype coding:</strong> 0=AA, 1=Aa, 2=aa</p>
|
| 1280 |
+
<p><strong>Marker format:</strong> "chr:position" (e.g., "1:1234567")</p>
|
| 1281 |
</div>
|
| 1282 |
""")
|
| 1283 |
|
| 1284 |
with gr.Column(scale=2):
|
|
|
|
| 1285 |
gr.HTML('<div class="section-header">π Analysis Summary</div>')
|
| 1286 |
summary_output = gr.Markdown("*Upload a CSV file and click 'Run GWAS Analysis' to begin*")
|
| 1287 |
|
|
|
|
| 1291 |
ld_output = gr.Image(label="LD Decay Plot (Mb)")
|
| 1292 |
with gr.Row():
|
| 1293 |
circos_output = gr.Image(label="Circos Plot")
|
| 1294 |
+
pca_output = gr.Image(label="PCA Analysis")
|
| 1295 |
+
with gr.Row():
|
| 1296 |
+
kinship_output = gr.Image(label="Kinship Matrix")
|
| 1297 |
|
| 1298 |
gr.HTML('<div class="section-header">β¬οΈ Download Results</div>')
|
| 1299 |
download_output = gr.File(label="Download ZIP Archive")
|
| 1300 |
status_output = gr.Textbox(label="Status", interactive=False)
|
| 1301 |
|
|
|
|
| 1302 |
run_button.click(
|
| 1303 |
fn=run_gwas_pipeline,
|
| 1304 |
inputs=[input_file, sample_missing, marker_missing, maf_threshold,
|
| 1305 |
include_lr, include_mlm, include_enet, include_lasso,
|
| 1306 |
+
include_ridge, include_rf, n_pcs, use_pca_correction],
|
| 1307 |
outputs=[summary_output, manhattan_output, ld_output, circos_output,
|
| 1308 |
+
pca_output, kinship_output, download_output, status_output,
|
| 1309 |
+
gr.Dataframe(label="Top Results Preview")]
|
| 1310 |
)
|
| 1311 |
|
|
|
|
| 1312 |
gr.HTML("""
|
| 1313 |
<footer>
|
| 1314 |
+
<p>GWAS Analysis Platform v10.0 | Soft Pastel Theme | Times New Roman Font</p>
|
| 1315 |
+
<p>Includes: 6 GWAS Models | PCA Analysis | Kinship Matrix | LD Decay (Mb) | Circos Plot</p>
|
| 1316 |
</footer>
|
| 1317 |
""")
|
| 1318 |
|