Spaces:
Sleeping
Sleeping
Update app.R
Browse files
app.R
CHANGED
|
@@ -1,32 +1,11 @@
|
|
| 1 |
# ============================================================
|
| 2 |
# QTL-Mapper v6 β Multi-Model QTL Mapping
|
|
|
|
| 3 |
#
|
| 4 |
-
#
|
| 5 |
-
#
|
| 6 |
-
#
|
| 7 |
-
#
|
| 8 |
-
#
|
| 9 |
-
# 2. MULTIPLE MAPPING MODELS:
|
| 10 |
-
# - Simple Interval Mapping (SIM) β lm per marker, no cofactors
|
| 11 |
-
# - Composite Interval Mapping (CIM) β cofactor-controlled scan
|
| 12 |
-
# - Multiple QTL Model (MQM) β stepwise model selection
|
| 13 |
-
# - LASSO-based QTL β penalized regression
|
| 14 |
-
# - Ridge Regression QTL β all markers simultaneously
|
| 15 |
-
#
|
| 16 |
-
# 3. MODEL SELECTOR UI β dropdown to choose mapping method
|
| 17 |
-
#
|
| 18 |
-
# 4. PROPER MULTI-CHROMOSOME MANHATTAN β plotly with correct offsets
|
| 19 |
-
#
|
| 20 |
-
# 5. CHROMOSOME IDIOGRAM PLOT β replicates the reference image style:
|
| 21 |
-
# colored symbols (circles, triangles) per trait on chromosome bars
|
| 22 |
-
# with cM scale, multiple traits overlaid, publication-ready
|
| 23 |
-
#
|
| 24 |
-
# 6. PVE FORMULA (v5 semi-partial R2 kept, applied to all models)
|
| 25 |
-
#
|
| 26 |
-
# 7. GENOTYPE CODING: 0/1/2 input β -1/0/+1 internal (AA/Aa/aa)
|
| 27 |
-
#
|
| 28 |
-
# 8. ROBUST DATA LOADING β handles \r\n, quoted fields, mismatched rows
|
| 29 |
-
#
|
| 30 |
# ============================================================
|
| 31 |
|
| 32 |
options(repos = c(CRAN = "https://cloud.r-project.org"))
|
|
@@ -68,36 +47,35 @@ model_choices_ai <- setNames(
|
|
| 68 |
# ============================================================
|
| 69 |
MAPPING_MODELS <- list(
|
| 70 |
"SIM" = list(label = "Simple Interval Mapping (SIM)", desc = "Single-marker regression; LOD = -log10(p); no cofactors"),
|
| 71 |
-
"CIM" = list(label = "Composite Interval Mapping (CIM)", desc = "CIM with RF-selected cofactors; semi-partial
|
| 72 |
"MQM" = list(label = "Multiple QTL Model (MQM / stepwise)", desc = "Forward stepwise selection across all markers"),
|
| 73 |
"LASSO" = list(label = "LASSO QTL (penalized)", desc = "L1 penalized regression; lambda by cross-validation"),
|
| 74 |
"RIDGE" = list(label = "Ridge Regression QTL", desc = "L2 penalized regression; shrinks all marker effects")
|
| 75 |
)
|
| 76 |
|
| 77 |
# ============================================================
|
| 78 |
-
# CLEAN COLUMN NAMES
|
| 79 |
# ============================================================
|
| 80 |
cn <- function(x) trimws(gsub('[\r\n\"]', '', as.character(x)))
|
| 81 |
|
| 82 |
# ============================================================
|
| 83 |
-
# GENOTYPE LOADER
|
| 84 |
# ============================================================
|
| 85 |
load_genotype_file <- function(filepath) {
|
| 86 |
lines <- readLines(filepath, warn = FALSE)
|
| 87 |
lines <- gsub("\r", "", lines)
|
| 88 |
lines <- lines[nchar(trimws(lines)) > 0]
|
| 89 |
-
if (length(lines) < 4) stop("Need
|
| 90 |
|
| 91 |
-
header
|
| 92 |
-
chr_row
|
| 93 |
-
pos_row
|
| 94 |
-
data_lines
|
| 95 |
|
| 96 |
gd <- read.csv(text = paste(data_lines, collapse = "\n"),
|
| 97 |
header = FALSE, stringsAsFactors = FALSE, quote = '"',
|
| 98 |
fill = TRUE)
|
| 99 |
|
| 100 |
-
# Pad or trim to match header length
|
| 101 |
if (ncol(gd) < length(header)) {
|
| 102 |
for (k in (ncol(gd)+1):length(header))
|
| 103 |
gd[[paste0("V",k)]] <- NA
|
|
@@ -108,7 +86,6 @@ load_genotype_file <- function(filepath) {
|
|
| 108 |
rownames(gd) <- cn(as.character(gd[, 1]))
|
| 109 |
gd <- gd[, -1, drop = FALSE]
|
| 110 |
|
| 111 |
-
# Coerce to numeric (0/1/2 coding)
|
| 112 |
for (col in colnames(gd))
|
| 113 |
gd[[col]] <- suppressWarnings(as.numeric(as.character(gd[[col]])))
|
| 114 |
|
|
@@ -120,7 +97,6 @@ load_genotype_file <- function(filepath) {
|
|
| 120 |
)
|
| 121 |
marker_info <- marker_info[!is.na(marker_info$Position) & marker_info$Chromosome != "", ]
|
| 122 |
|
| 123 |
-
# Only keep markers with valid map info
|
| 124 |
valid_cols <- colnames(gd)[colnames(gd) %in% marker_info$Marker]
|
| 125 |
gd <- gd[, valid_cols, drop = FALSE]
|
| 126 |
|
|
@@ -134,7 +110,7 @@ load_genotype_file <- function(filepath) {
|
|
| 134 |
}
|
| 135 |
|
| 136 |
# ============================================================
|
| 137 |
-
# CORE QTL SCAN
|
| 138 |
# ============================================================
|
| 139 |
qtl_scan <- function(genotype_matrix, phenotype_vector, marker_info,
|
| 140 |
method = "CIM", n_cofactors = 10, window_size = 10) {
|
|
@@ -149,11 +125,10 @@ qtl_scan <- function(genotype_matrix, phenotype_vector, marker_info,
|
|
| 149 |
cat("Chromosomes in marker_info:",
|
| 150 |
paste(sort(unique(marker_info$Chromosome)), collapse=", "), "\n")
|
| 151 |
|
| 152 |
-
valid_rows
|
| 153 |
-
X_valid
|
| 154 |
-
y_valid
|
| 155 |
|
| 156 |
-
# Remove zero-variance markers
|
| 157 |
nzv <- apply(X_valid, 2, function(x) length(unique(na.omit(x))) < 2)
|
| 158 |
X_valid <- X_valid[, !nzv, drop = FALSE]
|
| 159 |
cat("Markers after NZV removal:", ncol(X_valid), "\n")
|
|
@@ -162,7 +137,6 @@ qtl_scan <- function(genotype_matrix, phenotype_vector, marker_info,
|
|
| 162 |
if (method == "RIDGE") return(qtl_scan_lasso(X_valid, y_valid, marker_info, alpha = 0))
|
| 163 |
if (method == "MQM") return(qtl_scan_mqm(X_valid, y_valid, marker_info))
|
| 164 |
|
| 165 |
-
# Select cofactors for CIM
|
| 166 |
cofactors <- character(0)
|
| 167 |
if (method == "CIM" && n_cofactors > 0) {
|
| 168 |
max_cof <- max(3, floor(sqrt(n_samples)))
|
|
@@ -182,7 +156,6 @@ qtl_scan <- function(genotype_matrix, phenotype_vector, marker_info,
|
|
| 182 |
cat("CIM cofactors selected:", length(cofactors), "\n")
|
| 183 |
}
|
| 184 |
|
| 185 |
-
# Per-marker scan (SIM or CIM)
|
| 186 |
results_list <- list()
|
| 187 |
chr_counts <- table(marker_info$Chromosome[marker_info$Marker %in% colnames(X_valid)])
|
| 188 |
cat("Markers per chr:\n"); print(chr_counts)
|
|
@@ -196,14 +169,12 @@ qtl_scan <- function(genotype_matrix, phenotype_vector, marker_info,
|
|
| 196 |
pheno_v <- y_valid[valid_idx]
|
| 197 |
if (length(unique(geno_v)) < 2 || length(pheno_v) < 8) next
|
| 198 |
|
| 199 |
-
# Get map info
|
| 200 |
m_info <- marker_info[marker_info$Marker == m, ]
|
| 201 |
if (nrow(m_info) == 0) next
|
| 202 |
m_chr <- as.character(m_info$Chromosome[1])
|
| 203 |
m_pos <- m_info$Position[1]
|
| 204 |
if (is.na(m_pos)) next
|
| 205 |
|
| 206 |
-
# Build CIM cofactor set (exclude window around focal marker)
|
| 207 |
active_cof <- character(0)
|
| 208 |
if (method == "CIM" && length(cofactors) > 0) {
|
| 209 |
chr_mk <- marker_info[marker_info$Chromosome == m_chr, ]
|
|
@@ -221,7 +192,6 @@ qtl_scan <- function(genotype_matrix, phenotype_vector, marker_info,
|
|
| 221 |
active_cof <- head(active_cof, n_cofactors)
|
| 222 |
}
|
| 223 |
|
| 224 |
-
# Fit model
|
| 225 |
tryCatch({
|
| 226 |
df <- data.frame(y = pheno_v, focal = geno_v)
|
| 227 |
if (length(active_cof) > 0) {
|
|
@@ -250,7 +220,6 @@ qtl_scan <- function(genotype_matrix, phenotype_vector, marker_info,
|
|
| 250 |
SS_marker <- RSS_reduced - RSS_full
|
| 251 |
pve_cim <- if (RSS_reduced > 0) max(0, SS_marker / RSS_reduced * 100) else NA
|
| 252 |
|
| 253 |
-
# Additive/dominance effects (-1/0/+1 coding)
|
| 254 |
a_code <- df$focal - 1
|
| 255 |
d_code <- as.numeric(df$focal == 1)
|
| 256 |
has_het <- length(unique(d_code)) > 1
|
|
@@ -311,25 +280,23 @@ qtl_scan_lasso <- function(X, y, marker_info, alpha = 1) {
|
|
| 311 |
if (is.null(cv)) return(data.frame(Message="LASSO/Ridge failed"))
|
| 312 |
|
| 313 |
best_lam <- cv$lambda.1se
|
| 314 |
-
coefs <- coef(cv, s=best_lam)[-1]
|
| 315 |
coef_df <- data.frame(Marker=rownames(coef(cv,s=best_lam))[-1], Effect=as.numeric(coefs))
|
| 316 |
coef_df <- coef_df[abs(coef_df$Effect) > 0, ]
|
| 317 |
if (nrow(coef_df) == 0) return(data.frame(Message="No non-zero effects"))
|
| 318 |
|
| 319 |
-
# Compute LOD-like score: |effect| / max(|effect|) * 10
|
| 320 |
coef_df <- merge(coef_df, marker_info, by="Marker", all.x=TRUE)
|
| 321 |
coef_df <- coef_df[!is.na(coef_df$Position), ]
|
| 322 |
max_eff <- max(abs(coef_df$Effect))
|
| 323 |
coef_df$LOD <- abs(coef_df$Effect) / max_eff * 10
|
| 324 |
|
| 325 |
-
# Compute R2 from simple regression of each marker on phenotype
|
| 326 |
r2_vec <- sapply(coef_df$Marker, function(m) {
|
| 327 |
g <- X_v[, m]; v <- !is.na(g)
|
| 328 |
if (sum(v)<5) return(NA)
|
| 329 |
summary(lm(y_v[v] ~ g[v]))$r.squared * 100
|
| 330 |
})
|
| 331 |
coef_df$PVE_Marker_Percent <- r2_vec
|
| 332 |
-
coef_df$PVE_CIM_Percent <- r2_vec
|
| 333 |
coef_df$Additive_Effect <- coef_df$Effect
|
| 334 |
coef_df$P_Value <- 10^(-coef_df$LOD)
|
| 335 |
coef_df$SE_Additive <- NA
|
|
@@ -355,14 +322,12 @@ qtl_scan_mqm <- function(X, y, marker_info) {
|
|
| 355 |
valid <- !is.na(y)
|
| 356 |
X_v <- X[valid, , drop=FALSE]; y_v <- y[valid]
|
| 357 |
|
| 358 |
-
# Step 1: SIM scan
|
| 359 |
p_vals <- sapply(colnames(X_v), function(m) {
|
| 360 |
g <- X_v[,m]; v2 <- !is.na(g)
|
| 361 |
if (length(unique(g[v2])) < 2 || sum(v2) < 8) return(1)
|
| 362 |
tryCatch(coef(summary(lm(y_v[v2] ~ g[v2])))[2,4], error=function(e) 1)
|
| 363 |
})
|
| 364 |
|
| 365 |
-
# Step 2: iterative forward inclusion
|
| 366 |
selected <- character(0)
|
| 367 |
remaining <- names(sort(p_vals))
|
| 368 |
threshold <- 0.01
|
|
@@ -381,7 +346,6 @@ qtl_scan_mqm <- function(X, y, marker_info) {
|
|
| 381 |
}
|
| 382 |
if (length(selected)==0) selected <- names(sort(p_vals))[1:min(5,length(p_vals))]
|
| 383 |
|
| 384 |
-
# Step 3: final LOD scores
|
| 385 |
results_list <- list()
|
| 386 |
for (m in colnames(X_v)) {
|
| 387 |
g <- X_v[,m]; v2 <- !is.na(g) & !is.na(y_v)
|
|
@@ -437,12 +401,12 @@ add_lod_support_interval <- function(sig_df, all_df, lod_drop=1.5) {
|
|
| 437 |
sig_df$Interval_Start <- sig_df$Interval_End <- sig_df$Interval_Size_cM <- NA_real_
|
| 438 |
|
| 439 |
for (i in 1:nrow(sig_df)) {
|
| 440 |
-
m
|
| 441 |
-
cd
|
| 442 |
-
cd
|
| 443 |
if (nrow(cd)==0) next
|
| 444 |
-
inc
|
| 445 |
-
fp
|
| 446 |
if (nrow(inc)>0 && length(fp)>0) {
|
| 447 |
s <- min(inc$Position, fp); e <- max(inc$Position, fp)
|
| 448 |
sig_df$Interval_Start[i] <- s
|
|
@@ -466,31 +430,25 @@ add_lod_support_interval <- function(sig_df, all_df, lod_drop=1.5) {
|
|
| 466 |
}
|
| 467 |
|
| 468 |
# ============================================================
|
| 469 |
-
# CHROMOSOME IDIOGRAM PLOT
|
| 470 |
-
# Multiple traits, colored symbols on chromosome bars
|
| 471 |
# ============================================================
|
| 472 |
make_chromosome_idiogram <- function(qtl_list, all_markers_df,
|
| 473 |
lod_threshold = 2.0,
|
| 474 |
trait_colors = NULL) {
|
| 475 |
-
# qtl_list: named list of QTL result data.frames (one per trait/method)
|
| 476 |
if (is.null(all_markers_df) || nrow(all_markers_df)==0) return(NULL)
|
| 477 |
|
| 478 |
-
# Default color palette (Nature-style)
|
| 479 |
default_colors <- c("#C0392B","#2166AC","#1A7A4A","#E67E22","#8E44AD","#17A589","#F39C12","#2980B9")
|
| 480 |
trait_names <- names(qtl_list)
|
| 481 |
if (is.null(trait_colors))
|
| 482 |
trait_colors <- setNames(default_colors[seq_along(trait_names)], trait_names)
|
| 483 |
|
| 484 |
-
|
| 485 |
-
shapes <- c(16, 17, 18, 15, 3, 4, 8, 9) # pch values
|
| 486 |
|
| 487 |
-
# Get all chromosomes
|
| 488 |
chroms <- sort(unique(as.character(all_markers_df$Chromosome)))
|
| 489 |
n_chr <- length(chroms)
|
| 490 |
-
bar_height <- 0.35
|
| 491 |
-
x_gap <- 1.2
|
| 492 |
|
| 493 |
-
# Setup plot
|
| 494 |
par(mar=c(4,2,3,1), bg="white")
|
| 495 |
plot(0, 0, type="n",
|
| 496 |
xlim = c(0, n_chr * x_gap + 0.5),
|
|
@@ -499,28 +457,24 @@ make_chromosome_idiogram <- function(qtl_list, all_markers_df,
|
|
| 499 |
xlab="", ylab="cM", main="",
|
| 500 |
frame.plot=FALSE)
|
| 501 |
|
| 502 |
-
# Y axis
|
| 503 |
max_pos <- max(all_markers_df$Position, na.rm=TRUE)
|
| 504 |
y_ticks <- pretty(c(0, max_pos), n=6)
|
| 505 |
axis(2, at=y_ticks, labels=y_ticks, cex.axis=0.75, col="grey60", col.axis="grey30", las=1)
|
| 506 |
mtext("cM", side=2, line=2.5, cex=0.8, col="grey40")
|
| 507 |
|
| 508 |
for (ci in seq_along(chroms)) {
|
| 509 |
-
chr
|
| 510 |
-
x_cen
|
| 511 |
|
| 512 |
-
# Chromosome bar
|
| 513 |
chr_mk <- all_markers_df[as.character(all_markers_df$Chromosome)==as.character(chr),]
|
| 514 |
if (nrow(chr_mk)==0) next
|
| 515 |
chr_len <- max(chr_mk$Position, na.rm=TRUE)
|
| 516 |
chr_min <- min(chr_mk$Position, na.rm=TRUE)
|
| 517 |
|
| 518 |
-
# Draw chromosome body (gradient effect via rect)
|
| 519 |
rect(x_cen - bar_height*0.6, chr_min,
|
| 520 |
x_cen + bar_height*0.6, chr_len,
|
| 521 |
col = "grey88", border = "grey60", lwd=1.2)
|
| 522 |
|
| 523 |
-
# Rounded caps (approximate via ellipse-like polygon)
|
| 524 |
cap_h <- chr_len * 0.02
|
| 525 |
rect(x_cen - bar_height*0.6, chr_min - cap_h,
|
| 526 |
x_cen + bar_height*0.6, chr_min,
|
|
@@ -529,46 +483,39 @@ make_chromosome_idiogram <- function(qtl_list, all_markers_df,
|
|
| 529 |
x_cen + bar_height*0.6, chr_len + cap_h,
|
| 530 |
col="grey75", border="grey60", lwd=0.8)
|
| 531 |
|
| 532 |
-
# Centromere band (approximate at 40%)
|
| 533 |
cen_pos <- chr_min + (chr_len - chr_min) * 0.4
|
| 534 |
rect(x_cen - bar_height*0.6, cen_pos - chr_len*0.04,
|
| 535 |
x_cen + bar_height*0.6, cen_pos + chr_len*0.04,
|
| 536 |
col="grey50", border="grey40", lwd=0.5)
|
| 537 |
|
| 538 |
-
# All marker ticks (subtle)
|
| 539 |
for (mk_pos in chr_mk$Position) {
|
| 540 |
segments(x_cen - bar_height*0.55, mk_pos,
|
| 541 |
x_cen + bar_height*0.55, mk_pos,
|
| 542 |
col="grey70", lwd=0.4)
|
| 543 |
}
|
| 544 |
|
| 545 |
-
# QTL symbols per trait
|
| 546 |
for (ti in seq_along(trait_names)) {
|
| 547 |
-
tr
|
| 548 |
-
qdf
|
| 549 |
if (is.null(qdf) || "Message" %in% colnames(qdf)) next
|
| 550 |
-
sig
|
| 551 |
-
|
| 552 |
if (nrow(sig)==0) next
|
| 553 |
|
| 554 |
col_ti <- trait_colors[[tr]]
|
| 555 |
pch_ti <- shapes[((ti-1) %% length(shapes)) + 1]
|
| 556 |
cex_fun <- function(lod) pmax(0.7, pmin(2.2, 0.5 + lod/4))
|
| 557 |
|
| 558 |
-
# Alternate left/right to avoid overlap
|
| 559 |
x_off <- if (ti %% 2 == 1) x_cen + bar_height * 0.75 else x_cen - bar_height * 0.75
|
| 560 |
|
| 561 |
for (ri in 1:nrow(sig)) {
|
| 562 |
pos <- sig$Position[ri]
|
| 563 |
-
# Horizontal connector line
|
| 564 |
if (ti %% 2 == 1)
|
| 565 |
segments(x_cen + bar_height*0.6, pos, x_off, pos, col=col_ti, lwd=0.8, lty=2)
|
| 566 |
else
|
| 567 |
segments(x_cen - bar_height*0.6, pos, x_off, pos, col=col_ti, lwd=0.8, lty=2)
|
| 568 |
-
# Symbol
|
| 569 |
points(x_off, pos, pch=pch_ti, col=col_ti, bg=col_ti,
|
| 570 |
cex=cex_fun(sig$LOD[ri]))
|
| 571 |
-
# LOD label for large effects
|
| 572 |
if (sig$LOD[ri] >= lod_threshold * 1.5) {
|
| 573 |
text(x_off + ifelse(ti%%2==1, 0.15, -0.15), pos,
|
| 574 |
round(sig$LOD[ri], 1), cex=0.55, col=col_ti, font=2)
|
|
@@ -576,12 +523,10 @@ make_chromosome_idiogram <- function(qtl_list, all_markers_df,
|
|
| 576 |
}
|
| 577 |
}
|
| 578 |
|
| 579 |
-
# Chromosome label at top
|
| 580 |
text(x_cen, chr_len + cap_h + chr_len*0.04, paste0("Chr", chr),
|
| 581 |
cex=0.72, font=2, col="grey20")
|
| 582 |
}
|
| 583 |
|
| 584 |
-
# Legend
|
| 585 |
if (length(trait_names) > 0) {
|
| 586 |
legend_x <- 0.1
|
| 587 |
legend_y <- max_pos * 0.98
|
|
@@ -601,7 +546,7 @@ make_chromosome_idiogram <- function(qtl_list, all_markers_df,
|
|
| 601 |
title.col = "grey30")
|
| 602 |
}
|
| 603 |
|
| 604 |
-
title(main = paste0("QTL Chromosome Map β LOD
|
| 605 |
" | Method: ", paste(unique(unlist(lapply(qtl_list, function(q)
|
| 606 |
if (!is.null(q) && !"Message" %in% colnames(q) && "Method" %in% colnames(q))
|
| 607 |
unique(q$Method) else NULL))), collapse="/")),
|
|
@@ -609,7 +554,7 @@ make_chromosome_idiogram <- function(qtl_list, all_markers_df,
|
|
| 609 |
}
|
| 610 |
|
| 611 |
# ============================================================
|
| 612 |
-
# PLOTLY MANHATTAN
|
| 613 |
# ============================================================
|
| 614 |
make_plotly_manhattan <- function(scan_all, lod_threshold=2.0, title="QTL Manhattan Plot") {
|
| 615 |
blank <- plot_ly() %>% layout(title=title, plot_bgcolor="#FFFFFF", paper_bgcolor="#FFFFFF")
|
|
@@ -620,7 +565,6 @@ make_plotly_manhattan <- function(scan_all, lod_threshold=2.0, title="QTL Manhat
|
|
| 620 |
pd$Chromosome <- as.character(pd$Chromosome)
|
| 621 |
chroms <- sort(unique(pd$Chromosome), method="radix")
|
| 622 |
|
| 623 |
-
# Build cumulative offsets
|
| 624 |
offsets <- numeric(length(chroms)); names(offsets) <- chroms
|
| 625 |
for (i in seq_along(chroms)) {
|
| 626 |
if (i==1) { offsets[chroms[1]] <- 0; next }
|
|
@@ -646,7 +590,6 @@ make_plotly_manhattan <- function(scan_all, lod_threshold=2.0, title="QTL Manhat
|
|
| 646 |
text=~paste0("Marker: ",Marker,"<br>Chr: ",Chromosome,"<br>Pos: ",round(Position,1)," cM<br>LOD: ",round(LOD,2),"<br>PVE: ",round(PVE_Marker_Percent,1),"%"),
|
| 647 |
hoverinfo="text", showlegend=FALSE)
|
| 648 |
}
|
| 649 |
-
# Significant markers
|
| 650 |
sig_pd <- pd[pd$sig,]
|
| 651 |
if (nrow(sig_pd)>0)
|
| 652 |
p <- p %>% add_trace(
|
|
@@ -655,7 +598,6 @@ make_plotly_manhattan <- function(scan_all, lod_threshold=2.0, title="QTL Manhat
|
|
| 655 |
text=~paste0("<b>",Marker,"</b><br>Chr: ",Chromosome,"<br>LOD: ",round(LOD,2),"<br>PVE_marker: ",round(PVE_Marker_Percent,1),"%"),
|
| 656 |
hoverinfo="text")
|
| 657 |
|
| 658 |
-
# Threshold line
|
| 659 |
p <- p %>%
|
| 660 |
add_segments(x=min(pd$cum_pos,na.rm=TRUE), xend=max(pd$cum_pos,na.rm=TRUE),
|
| 661 |
y=lod_threshold, yend=lod_threshold,
|
|
@@ -750,9 +692,6 @@ ui <- fluidPage(
|
|
| 750 |
.model-badge{display:inline-block;background:#EFF6FF;border:1px solid #BFDBFE;
|
| 751 |
border-radius:12px;padding:2px 10px;font-size:11px;font-family:var(--mono);
|
| 752 |
color:var(--accent);margin-right:6px;}
|
| 753 |
-
.chr-legend{display:flex;gap:14px;flex-wrap:wrap;padding:6px 0;font-size:11px;align-items:center;}
|
| 754 |
-
.leg-dot{width:10px;height:10px;border-radius:2px;display:inline-block;margin-right:4px;}
|
| 755 |
-
/* Floating chat */
|
| 756 |
#chat-panel{position:fixed;bottom:16px;right:16px;z-index:9999;width:420px;display:flex;flex-direction:column;}
|
| 757 |
#chat-toggle{align-self:flex-end;width:52px;height:52px;border-radius:50%;
|
| 758 |
background:linear-gradient(135deg,var(--accent),#7C3AED);border:none;cursor:pointer;
|
|
@@ -791,7 +730,6 @@ ui <- fluidPage(
|
|
| 791 |
border-radius:5px;padding:7px 14px;font-family:var(--mono);font-size:12px;font-weight:600;cursor:pointer;}
|
| 792 |
#clear_chat{background:transparent;color:var(--muted);border:1px solid var(--border);
|
| 793 |
border-radius:5px;padding:7px 10px;font-family:var(--mono);font-size:12px;cursor:pointer;}
|
| 794 |
-
/* DT tables */
|
| 795 |
table.dataTable{background:#FFF!important;color:var(--txt)!important;}
|
| 796 |
table.dataTable thead th{background:#F1F5F9!important;font-family:var(--mono);font-size:11px;}
|
| 797 |
table.dataTable tbody tr:hover{background:#EFF6FF!important;}
|
|
@@ -803,7 +741,7 @@ ui <- fluidPage(
|
|
| 803 |
title = tags$span(tags$i(class="fas fa-dna",style="color:#1D4ED8;margin-right:6px;"), "QTL-Mapper v6"),
|
| 804 |
id = "nav",
|
| 805 |
|
| 806 |
-
# ββ
|
| 807 |
tabPanel("Data Upload", icon=icon("upload"),
|
| 808 |
fluidRow(column(12,
|
| 809 |
div(class="info-box",
|
|
@@ -843,7 +781,7 @@ ui <- fluidPage(
|
|
| 843 |
numericInput("window_size","Exclusion Window (Β±markers)",value=10,min=1,max=30,step=1)
|
| 844 |
),
|
| 845 |
numericInput("lod_drop","LOD Drop for Interval",value=1.5,min=0.5,max=3.0,step=0.5),
|
| 846 |
-
actionButton("run_btn","
|
| 847 |
style="margin-top:8px;width:100%;")
|
| 848 |
)
|
| 849 |
)
|
|
@@ -879,7 +817,7 @@ ui <- fluidPage(
|
|
| 879 |
))
|
| 880 |
),
|
| 881 |
|
| 882 |
-
# ββ
|
| 883 |
tabPanel("Results", icon=icon("chart-line"),
|
| 884 |
fluidRow(column(12,
|
| 885 |
div(style="display:flex;gap:10px;flex-wrap:wrap;margin-bottom:12px;",
|
|
@@ -897,10 +835,8 @@ ui <- fluidPage(
|
|
| 897 |
),
|
| 898 |
column(5,
|
| 899 |
div(class="card",
|
| 900 |
-
div(class="card-hd","Chromosome Idiogram β QTL Positions
|
| 901 |
-
div(class="card-bd",
|
| 902 |
-
plotOutput("idiogram_plot",height="480px")
|
| 903 |
-
)
|
| 904 |
)
|
| 905 |
)
|
| 906 |
),
|
|
@@ -926,7 +862,7 @@ ui <- fluidPage(
|
|
| 926 |
),
|
| 927 |
fluidRow(column(12,
|
| 928 |
div(class="card",
|
| 929 |
-
div(class="card-hd","QTL Effects Table β Significant Markers"),
|
| 930 |
div(class="card-bd",DTOutput("qtl_table"))
|
| 931 |
)
|
| 932 |
)),
|
|
@@ -938,7 +874,7 @@ ui <- fluidPage(
|
|
| 938 |
))
|
| 939 |
),
|
| 940 |
|
| 941 |
-
# ββ
|
| 942 |
tabPanel("Compare Models", icon=icon("balance-scale"),
|
| 943 |
fluidRow(column(12,
|
| 944 |
div(class="card",
|
|
@@ -948,7 +884,7 @@ ui <- fluidPage(
|
|
| 948 |
checkboxGroupInput("compare_methods","Methods to Compare:",
|
| 949 |
choices = setNames(names(MAPPING_MODELS), sapply(MAPPING_MODELS,`[[`,"label")),
|
| 950 |
selected = c("SIM","CIM"), inline=TRUE),
|
| 951 |
-
actionButton("run_compare","
|
| 952 |
tags$br(),tags$br(),
|
| 953 |
uiOutput("compare_status_ui")
|
| 954 |
)
|
|
@@ -976,7 +912,7 @@ ui <- fluidPage(
|
|
| 976 |
))
|
| 977 |
),
|
| 978 |
|
| 979 |
-
# ββ
|
| 980 |
tabPanel("Domestication", icon=icon("leaf"),
|
| 981 |
fluidRow(
|
| 982 |
column(4,
|
|
@@ -985,7 +921,7 @@ ui <- fluidPage(
|
|
| 985 |
div(class="card-bd",
|
| 986 |
numericInput("fst_thr","Fst Threshold",value=0.1,min=0.05,max=0.5,step=0.01),
|
| 987 |
numericInput("tajima_thr","Tajima's D Threshold",value=-1,min=-5,max=0,step=0.1),
|
| 988 |
-
actionButton("run_dom","
|
| 989 |
)
|
| 990 |
)
|
| 991 |
),
|
|
@@ -1011,19 +947,23 @@ ui <- fluidPage(
|
|
| 1011 |
))
|
| 1012 |
),
|
| 1013 |
|
| 1014 |
-
# ββ
|
| 1015 |
tabPanel("About", icon=icon("info-circle"),
|
| 1016 |
fluidRow(column(8,offset=2,
|
| 1017 |
div(class="card",
|
| 1018 |
div(class="card-bd",
|
| 1019 |
tags$h4(style="color:var(--accent);font-family:var(--mono);","QTL-Mapper v6 β Changes & Methods"),
|
| 1020 |
div(class="warn-box",
|
| 1021 |
-
tags$b("v5
|
| 1022 |
"1. MULTI-CHROMOSOME: robust marker_info join; debug log per chr; all chroms now scan", tags$br(),
|
| 1023 |
"2. MULTIPLE MODELS: SIM, CIM, MQM, LASSO, Ridge β select/compare freely", tags$br(),
|
| 1024 |
"3. IDIOGRAM PLOT: replicates reference image (chromosome bars + colored symbols per trait)", tags$br(),
|
| 1025 |
"4. MANHATTAN: proper cumulative offsets for all chromosomes, not just Chr1", tags$br(),
|
| 1026 |
-
"5. PVE: semi-partial
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1027 |
),
|
| 1028 |
tags$h5(style="margin-top:16px;font-family:var(--mono);","Mapping Methods"),
|
| 1029 |
tags$ul(lapply(MAPPING_MODELS, function(m)
|
|
@@ -1034,7 +974,7 @@ ui <- fluidPage(
|
|
| 1034 |
tags$li("Zeng (1993) PNAS 90:10972 β CIM"),
|
| 1035 |
tags$li("Zeng (1994) Genetics 136:1457 β CIM"),
|
| 1036 |
tags$li("Lander & Botstein (1989) Genetics 121:185 β LOD intervals"),
|
| 1037 |
-
tags$li("Lynch & Walsh (1998) β Semi-partial
|
| 1038 |
tags$li("Tibshirani (1996) JRSS-B 58:267 β LASSO"),
|
| 1039 |
tags$li("Contact: ashmithamganesan@gmail.com, P.sinha@cgiar.org")
|
| 1040 |
)
|
|
@@ -1044,7 +984,7 @@ ui <- fluidPage(
|
|
| 1044 |
)
|
| 1045 |
),
|
| 1046 |
|
| 1047 |
-
# ββ
|
| 1048 |
tags$div(id="chat-panel",
|
| 1049 |
tags$div(id="chat-win",
|
| 1050 |
tags$div(id="chat-hd",
|
|
@@ -1088,25 +1028,27 @@ server <- function(input, output, session) {
|
|
| 1088 |
geno = NULL, pheno = NULL,
|
| 1089 |
test_geno = NULL, pop_data = NULL,
|
| 1090 |
marker_info = NULL, all_markers = NULL,
|
| 1091 |
-
scan_all = NULL,
|
| 1092 |
perf = NULL, tr_pred = NULL, val_pred = NULL,
|
| 1093 |
model_fit = NULL, model_cols = NULL,
|
| 1094 |
pred_test = NULL,
|
| 1095 |
sel_metrics = NULL,
|
| 1096 |
-
compare_res = list(),
|
| 1097 |
chat_msgs = list(),
|
| 1098 |
-
is_typing = FALSE
|
| 1099 |
-
lod_thr = 2.0
|
| 1100 |
)
|
| 1101 |
|
| 1102 |
-
# ββ
|
|
|
|
|
|
|
|
|
|
| 1103 |
output$method_desc_ui <- renderUI({
|
| 1104 |
m <- input$mapping_method
|
| 1105 |
if (is.null(m) || !m %in% names(MAPPING_MODELS)) return(NULL)
|
| 1106 |
div(class="info-box", MAPPING_MODELS[[m]]$desc)
|
| 1107 |
})
|
| 1108 |
|
| 1109 |
-
# ββ Dataset info ββββββββββββββββββββββββββββββββββββββββββ
|
| 1110 |
output$dataset_info_ui <- renderUI({
|
| 1111 |
if (is.null(rv$geno)) return(tags$p("No data loaded yet."))
|
| 1112 |
n_chr <- length(unique(rv$marker_info$Chromosome))
|
|
@@ -1120,7 +1062,7 @@ server <- function(input, output, session) {
|
|
| 1120 |
)
|
| 1121 |
})
|
| 1122 |
|
| 1123 |
-
# ββ Data loading ββββββββββββββββββββββββββββββββββββββββββ
|
| 1124 |
observeEvent(input$geno_file, {
|
| 1125 |
req(input$geno_file)
|
| 1126 |
tryCatch({
|
|
@@ -1128,9 +1070,12 @@ server <- function(input, output, session) {
|
|
| 1128 |
rv$geno <- res$geno
|
| 1129 |
rv$marker_info <- res$marker_info
|
| 1130 |
rv$all_markers <- res$marker_info
|
| 1131 |
-
msg <- paste0("
|
|
|
|
|
|
|
| 1132 |
add_msg("assistant", msg)
|
| 1133 |
-
showNotification(paste(res$n_markers,"markers,",res$n_samples,"samples,",
|
|
|
|
| 1134 |
}, error=function(e) showNotification(paste("Geno error:",e$message), type="error"))
|
| 1135 |
})
|
| 1136 |
|
|
@@ -1164,33 +1109,35 @@ server <- function(input, output, session) {
|
|
| 1164 |
}, error=function(e) showNotification(paste("Test geno error:",e$message), type="error"))
|
| 1165 |
})
|
| 1166 |
|
| 1167 |
-
# ββ
|
| 1168 |
-
output$prev_geno
|
| 1169 |
-
output$prev_pheno
|
| 1170 |
output$prev_test_geno <- renderDT({ req(rv$test_geno); datatable(head(rv$test_geno,10), options=list(scrollX=TRUE,pageLength=5)) })
|
| 1171 |
output$prev_pred <- renderDT({ req(rv$pred_test); datatable(rv$pred_test, options=list(scrollX=TRUE,pageLength=8)) })
|
| 1172 |
output$prev_pop <- renderDT({ req(rv$pop_data); datatable(head(rv$pop_data,10), options=list(scrollX=TRUE,pageLength=5)) })
|
| 1173 |
|
| 1174 |
-
# ββ MAIN ANALYSIS βββββββββββββββββββββββββββββββββββββββββ
|
| 1175 |
observeEvent(input$run_btn, {
|
| 1176 |
req(rv$geno, rv$pheno, input$pheno_col)
|
| 1177 |
|
| 1178 |
-
showNotification(paste("Starting",input$mapping_method,"scan..."), type="message")
|
| 1179 |
-
rv$lod_thr <- input$lod_threshold
|
| 1180 |
|
| 1181 |
tryCatch({
|
| 1182 |
-
cs
|
| 1183 |
-
if (length(cs)==0) {
|
|
|
|
|
|
|
|
|
|
| 1184 |
|
| 1185 |
X <- rv$geno[cs, , drop=FALSE]
|
| 1186 |
y <- as.numeric(rv$pheno[cs, input$pheno_col])
|
| 1187 |
|
| 1188 |
set.seed(42)
|
| 1189 |
-
tr_idx
|
| 1190 |
-
X_tr
|
| 1191 |
-
y_tr
|
| 1192 |
|
| 1193 |
-
withProgress(message=paste("Running",input$mapping_method,"genome scan..."), value=0.1, {
|
| 1194 |
scan_res <- qtl_scan(
|
| 1195 |
genotype_matrix = X_tr,
|
| 1196 |
phenotype_vector = y_tr,
|
|
@@ -1203,18 +1150,6 @@ server <- function(input, output, session) {
|
|
| 1203 |
|
| 1204 |
rv$scan_all <- scan_res
|
| 1205 |
|
| 1206 |
-
if (!"Message" %in% colnames(scan_res)) {
|
| 1207 |
-
sig <- scan_res[scan_res$LOD >= input$lod_threshold & !is.na(scan_res$LOD),]
|
| 1208 |
-
if (nrow(sig)>0) {
|
| 1209 |
-
sig <- add_lod_support_interval(sig, scan_res, input$lod_drop)
|
| 1210 |
-
rv$sig_qtl <- sig[order(-sig$LOD),]
|
| 1211 |
-
} else {
|
| 1212 |
-
rv$sig_qtl <- data.frame(Message=paste("No QTLs above LOD",input$lod_threshold))
|
| 1213 |
-
}
|
| 1214 |
-
} else {
|
| 1215 |
-
rv$sig_qtl <- scan_res
|
| 1216 |
-
}
|
| 1217 |
-
|
| 1218 |
# RF prediction model
|
| 1219 |
nzv_idx <- caret::nearZeroVar(X_tr)
|
| 1220 |
X_tr_rf <- if(length(nzv_idx)>0) X_tr[,-nzv_idx,drop=FALSE] else X_tr
|
|
@@ -1235,7 +1170,7 @@ server <- function(input, output, session) {
|
|
| 1235 |
tr_r2 <- 1 - sum((y_tr-ytr_pred)^2)/sum((y_tr-mean(y_tr))^2)
|
| 1236 |
v_r2 <- 1 - sum((y_v-yv_pred)^2)/sum((y_v-mean(y_v))^2)
|
| 1237 |
rv$perf <- data.frame(
|
| 1238 |
-
Metric=c("
|
| 1239 |
Value=c(tr_r2, cor(y_tr,ytr_pred), v_r2, cor(y_v,yv_pred)))
|
| 1240 |
rv$tr_pred <- data.frame(Observed=y_tr, Predicted=ytr_pred)
|
| 1241 |
rv$val_pred <- data.frame(Observed=y_v, Predicted=yv_pred)
|
|
@@ -1243,25 +1178,27 @@ server <- function(input, output, session) {
|
|
| 1243 |
incProgress(0.3)
|
| 1244 |
})
|
| 1245 |
|
| 1246 |
-
n_sig <- if (!is.null(rv$
|
|
|
|
| 1247 |
n_chr_res <- if (!is.null(rv$scan_all) && !"Message" %in% colnames(rv$scan_all))
|
| 1248 |
length(unique(rv$scan_all$Chromosome)) else 0
|
|
|
|
| 1249 |
add_msg("assistant", paste0(
|
| 1250 |
-
|
| 1251 |
-
"β’
|
| 1252 |
-
"β’ Chromosomes in results:
|
| 1253 |
-
"β’ Validation
|
| 1254 |
))
|
| 1255 |
-
showNotification(paste(input$mapping_method,"done:",n_sig,"QTLs on",n_chr_res,"chromosomes"), type="message")
|
| 1256 |
-
updateTabsetPanel(session,"nav",selected="Results")
|
| 1257 |
|
| 1258 |
}, error=function(e) {
|
| 1259 |
-
showNotification(paste("Analysis error:",e$message), type="error")
|
| 1260 |
cat("ANALYSIS ERROR:", e$message, "\n")
|
| 1261 |
})
|
| 1262 |
})
|
| 1263 |
|
| 1264 |
-
# ββ COMPARE MODELS ββββββββββββββββββββββββββββββββββββββββ
|
| 1265 |
output$compare_status_ui <- renderUI({
|
| 1266 |
if (length(rv$compare_res)==0) return(NULL)
|
| 1267 |
tags$div(class="info-box",
|
|
@@ -1270,7 +1207,7 @@ server <- function(input, output, session) {
|
|
| 1270 |
lapply(names(rv$compare_res), function(m) {
|
| 1271 |
r <- rv$compare_res[[m]]
|
| 1272 |
if (is.null(r)||"Message"%in%colnames(r)) return(tags$span(m,": 0 QTLs "))
|
| 1273 |
-
n <- sum(r$LOD>=
|
| 1274 |
nc <- length(unique(r$Chromosome[!is.na(r$LOD)]))
|
| 1275 |
tags$span(class="model-badge", paste0(m,": ",n," QTLs / ",nc," chr "))
|
| 1276 |
})
|
|
@@ -1280,33 +1217,41 @@ server <- function(input, output, session) {
|
|
| 1280 |
observeEvent(input$run_compare, {
|
| 1281 |
req(rv$geno, rv$pheno, input$compare_methods, input$pheno_col)
|
| 1282 |
methods_sel <- input$compare_methods
|
| 1283 |
-
if (length(methods_sel)==0) {
|
|
|
|
|
|
|
|
|
|
| 1284 |
|
| 1285 |
cs <- intersect(rownames(rv$geno), rownames(rv$pheno))
|
| 1286 |
-
X <- rv$geno[cs,,drop=FALSE]
|
| 1287 |
-
|
| 1288 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1289 |
|
| 1290 |
compare_list <- list()
|
| 1291 |
withProgress(message="Comparing models...", value=0, {
|
| 1292 |
for (mth in methods_sel) {
|
| 1293 |
-
incProgress(1/length(methods_sel), detail=paste("Running",mth))
|
| 1294 |
res <- tryCatch(
|
| 1295 |
qtl_scan(X_tr, y_tr, rv$marker_info, method=mth,
|
| 1296 |
n_cofactors=input$n_cofactors, window_size=input$window_size),
|
| 1297 |
-
error=function(e) { cat("Compare error",mth,":",e$message,"\n"); NULL }
|
| 1298 |
)
|
| 1299 |
if (!is.null(res)) compare_list[[mth]] <- res
|
| 1300 |
}
|
| 1301 |
})
|
| 1302 |
rv$compare_res <- compare_list
|
| 1303 |
-
showNotification(paste("Compared",length(compare_list),"models"), type="message")
|
| 1304 |
})
|
| 1305 |
|
| 1306 |
output$compare_idiogram <- renderPlot({
|
| 1307 |
req(length(rv$compare_res)>0, rv$all_markers)
|
| 1308 |
par(bg="white")
|
| 1309 |
-
make_chromosome_idiogram(rv$compare_res, rv$all_markers,
|
| 1310 |
}, bg="white")
|
| 1311 |
|
| 1312 |
output$compare_bar <- renderPlotly({
|
|
@@ -1315,13 +1260,14 @@ server <- function(input, output, session) {
|
|
| 1315 |
for (mth in names(rv$compare_res)) {
|
| 1316 |
r <- rv$compare_res[[mth]]
|
| 1317 |
if (is.null(r)||"Message"%in%colnames(r)) next
|
| 1318 |
-
sig <- r[r$LOD>=
|
| 1319 |
if (nrow(sig)==0) next
|
| 1320 |
for (ch in unique(sig$Chromosome))
|
| 1321 |
rows <- c(rows, list(data.frame(Method=mth, Chromosome=as.character(ch),
|
| 1322 |
Count=sum(sig$Chromosome==ch), stringsAsFactors=FALSE)))
|
| 1323 |
}
|
| 1324 |
-
if (length(rows)==0)
|
|
|
|
| 1325 |
df <- do.call(rbind, rows)
|
| 1326 |
df$Chromosome <- factor(df$Chromosome, levels=sort(unique(df$Chromosome)))
|
| 1327 |
plot_ly(df, x=~Chromosome, y=~Count, color=~Method, type="bar") %>%
|
|
@@ -1336,14 +1282,13 @@ server <- function(input, output, session) {
|
|
| 1336 |
for (mth in names(rv$compare_res)) {
|
| 1337 |
r <- rv$compare_res[[mth]]
|
| 1338 |
if (is.null(r)||"Message"%in%colnames(r)) next
|
| 1339 |
-
sig <- r[r$LOD>=
|
| 1340 |
if (nrow(sig)==0) next
|
| 1341 |
sig$Method2 <- mth
|
| 1342 |
rows <- c(rows, list(sig[,c("Marker","Chromosome","Position","LOD","PVE_Marker_Percent","Method2")]))
|
| 1343 |
}
|
| 1344 |
if (length(rows)==0) return(datatable(data.frame(Status="No QTLs")))
|
| 1345 |
df <- do.call(rbind, rows)
|
| 1346 |
-
# Add overlap count
|
| 1347 |
overlap <- table(df$Marker)
|
| 1348 |
df$Detected_By_N_Models <- as.integer(overlap[df$Marker])
|
| 1349 |
datatable(df[order(-df$Detected_By_N_Models,-df$LOD),],
|
|
@@ -1351,24 +1296,26 @@ server <- function(input, output, session) {
|
|
| 1351 |
formatRound(c("LOD","PVE_Marker_Percent","Position"),3)
|
| 1352 |
})
|
| 1353 |
|
| 1354 |
-
# ββ PLOTS βββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1355 |
output$manhattan_plot <- renderPlotly({
|
| 1356 |
req(rv$scan_all)
|
| 1357 |
-
make_plotly_manhattan(rv$scan_all,
|
| 1358 |
-
paste(input$mapping_method,"Manhattan Plot"))
|
| 1359 |
})
|
| 1360 |
|
| 1361 |
output$idiogram_plot <- renderPlot({
|
| 1362 |
req(rv$scan_all, rv$all_markers)
|
| 1363 |
res_list <- list()
|
| 1364 |
-
mth
|
| 1365 |
-
if (!is.null(rv$scan_all) && !"Message"%in%colnames(rv$scan_all))
|
| 1366 |
res_list[[mth]] <- rv$scan_all
|
| 1367 |
if (length(res_list)==0) {
|
| 1368 |
-
plot(0,0,type="n",axes=FALSE,xlab="",ylab="")
|
|
|
|
|
|
|
| 1369 |
}
|
| 1370 |
par(bg="white")
|
| 1371 |
-
make_chromosome_idiogram(res_list, rv$all_markers,
|
| 1372 |
}, bg="white")
|
| 1373 |
|
| 1374 |
output$perf_plot <- renderPlotly({
|
|
@@ -1400,33 +1347,51 @@ server <- function(input, output, session) {
|
|
| 1400 |
xaxis=list(title="Observed"),yaxis=list(title="Predicted"))
|
| 1401 |
})
|
| 1402 |
|
| 1403 |
-
# ββ TABLES ββββββββββββββββββββββββββββββββββββββββββββββββ
|
|
|
|
|
|
|
| 1404 |
output$qtl_table <- renderDT({
|
| 1405 |
-
req(rv$
|
| 1406 |
-
if ("Message" %in% colnames(rv$
|
| 1407 |
-
return(datatable(data.frame(Status=rv$
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1408 |
disp <- intersect(c("Marker","Chromosome","Position","LOD","P_Value",
|
| 1409 |
"PVE_Marker_Percent","PVE_CIM_Percent","Additive_Effect","SE_Additive",
|
| 1410 |
"CI_Lower","CI_Upper","Dominance_Effect","Dominance_Ratio","Dominance_Class",
|
| 1411 |
"N_Cofactors","N_Samples","Method","Interval_Start","Interval_End",
|
| 1412 |
-
"Interval_Size_cM","Low_Flank","High_Flank"), colnames(
|
| 1413 |
-
|
| 1414 |
-
|
| 1415 |
-
|
| 1416 |
-
|
|
|
|
|
|
|
|
|
|
| 1417 |
})
|
| 1418 |
|
| 1419 |
output$full_scan_table <- renderDT({
|
| 1420 |
req(rv$scan_all)
|
| 1421 |
if ("Message" %in% colnames(rv$scan_all))
|
| 1422 |
-
return(datatable(data.frame(Status=rv$scan_all$Message[1]),
|
| 1423 |
-
|
|
|
|
|
|
|
| 1424 |
rownames=FALSE) %>%
|
| 1425 |
formatRound(c("LOD","PVE_Marker_Percent","Additive_Effect"),3) %>%
|
| 1426 |
-
formatSignif("P_Value",digits=3)
|
| 1427 |
})
|
| 1428 |
|
| 1429 |
-
# ββ PREDICT TEST ββββββββββββββββββββββββββββββββββββββββββ
|
| 1430 |
observeEvent(input$pred_btn, {
|
| 1431 |
if (is.null(rv$model_fit)) { showNotification("Run analysis first", type="error"); return() }
|
| 1432 |
if (is.null(rv$test_geno)) { showNotification("Upload test genotype first", type="error"); return() }
|
|
@@ -1452,10 +1417,10 @@ server <- function(input, output, session) {
|
|
| 1452 |
rv$pred_test <- data.frame(Sample_ID=rownames(test_raw), Predicted_Phenotype=round(preds,4))
|
| 1453 |
incProgress(0.3)
|
| 1454 |
})
|
| 1455 |
-
showNotification(paste("Predicted",nrow(rv$pred_test),"test samples"), type="message")
|
| 1456 |
})
|
| 1457 |
|
| 1458 |
-
# ββ DOMESTICATION βββββββββββββββββββββββββββββββββββββββββ
|
| 1459 |
calc_sel <- function(gmat, pop, minfo) {
|
| 1460 |
out <- list()
|
| 1461 |
for (m in colnames(gmat)) {
|
|
@@ -1469,9 +1434,11 @@ server <- function(input, output, session) {
|
|
| 1469 |
pid <- 2*fd*(1-fd); piw <- 2*fw*(1-fw)
|
| 1470 |
tdd <- tryCatch((pid-1/length(gd))/sqrt(var(gd)/length(gd)),error=function(e)NA)
|
| 1471 |
mi <- minfo[minfo$Marker==m,]
|
| 1472 |
-
out[[m]] <- data.frame(Marker=m,
|
| 1473 |
-
|
| 1474 |
-
|
|
|
|
|
|
|
| 1475 |
}
|
| 1476 |
if (length(out)==0) return(NULL)
|
| 1477 |
do.call(rbind, out)
|
|
@@ -1481,7 +1448,8 @@ server <- function(input, output, session) {
|
|
| 1481 |
req(rv$geno, rv$pop_data, rv$marker_info)
|
| 1482 |
tryCatch({
|
| 1483 |
cs <- intersect(rownames(rv$geno), rv$pop_data$id)
|
| 1484 |
-
X <- rv$geno[cs,,drop=FALSE]
|
|
|
|
| 1485 |
sel <- calc_sel(X, ps, rv$marker_info)
|
| 1486 |
if (is.null(sel)) { showNotification("No selection metrics computed", type="error"); return() }
|
| 1487 |
sel$Significant <- sel$Fst > input$fst_thr | sel$Tajima_D_Dom < input$tajima_thr
|
|
@@ -1491,7 +1459,7 @@ server <- function(input, output, session) {
|
|
| 1491 |
})
|
| 1492 |
|
| 1493 |
create_man_plotly <- function(data, y_col, title, threshold, y_label=y_col) {
|
| 1494 |
-
blank <- plot_ly()%>%layout(title=title, plot_bgcolor="#FFF", paper_bgcolor="#FFF")
|
| 1495 |
if (is.null(data)||nrow(data)==0||"Message"%in%colnames(data)) return(blank)
|
| 1496 |
pd <- data[!is.na(data[[y_col]])&!is.na(data$Chromosome),]
|
| 1497 |
if (nrow(pd)==0) return(blank)
|
|
@@ -1510,18 +1478,20 @@ server <- function(input, output, session) {
|
|
| 1510 |
p <- plot_ly()
|
| 1511 |
for (ch in chroms)
|
| 1512 |
p <- p %>% add_trace(data=pd[pd$Chromosome==ch,], x=~cum_pos,
|
| 1513 |
-
y=as.formula(paste0("~",y_col)), type="scatter", mode="markers",
|
|
|
|
| 1514 |
marker=list(size=5,color=pal[ch],opacity=.75), showlegend=FALSE,
|
| 1515 |
text=~paste0("Marker: ",Marker,"<br>Chr: ",Chromosome,"<br>",y_label,": ",round(get(y_col),3)),
|
| 1516 |
hoverinfo="text")
|
| 1517 |
if (!is.null(threshold))
|
| 1518 |
p <- p %>% add_segments(x=min(pd$cum_pos,na.rm=TRUE),xend=max(pd$cum_pos,na.rm=TRUE),
|
| 1519 |
-
y=threshold,yend=threshold,
|
|
|
|
| 1520 |
p %>% layout(title=title,
|
| 1521 |
-
xaxis=list(title="Chromosome",tickvals=as.list(chr_mids[chroms]),
|
| 1522 |
ticktext=as.list(paste0("Chr",chroms)), tickangle=45, gridcolor="#F1F5F9"),
|
| 1523 |
-
yaxis=list(title=y_label,gridcolor="#F1F5F9"),
|
| 1524 |
-
plot_bgcolor="#FFF",paper_bgcolor="#FFF")
|
| 1525 |
}
|
| 1526 |
|
| 1527 |
output$fst_plot <- renderPlotly({ req(rv$sel_metrics); create_man_plotly(rv$sel_metrics,"Fst","Fst",input$fst_thr,"Fst") })
|
|
@@ -1533,40 +1503,45 @@ server <- function(input, output, session) {
|
|
| 1533 |
formatRound(c("Fst","Pi_Dom","Pi_Wild","Tajima_D_Dom"),3)
|
| 1534 |
})
|
| 1535 |
|
| 1536 |
-
# ββ DOWNLOADS βββββββββββββββββββββββββββββββββββββββββββββ
|
| 1537 |
output$dl_manhattan <- downloadHandler(
|
| 1538 |
filename=function() paste0("manhattan_v6_",Sys.Date(),".png"),
|
| 1539 |
content=function(file) {
|
| 1540 |
req(rv$scan_all)
|
| 1541 |
if ("Message"%in%colnames(rv$scan_all)) return()
|
| 1542 |
-
pd
|
| 1543 |
pd$Chromosome <- as.character(pd$Chromosome)
|
| 1544 |
chroms <- sort(unique(pd$Chromosome),method="radix")
|
| 1545 |
offsets <- numeric(length(chroms)); names(offsets) <- chroms
|
| 1546 |
for (i in seq_along(chroms)) {
|
| 1547 |
if(i==1){offsets[chroms[1]]<-0;next}
|
| 1548 |
-
offsets[chroms[i]] <- offsets[chroms[i-1]] +
|
|
|
|
| 1549 |
}
|
| 1550 |
pd$cum_pos <- pd$Position + offsets[pd$Chromosome]
|
| 1551 |
-
pd$sig <- pd$LOD >=
|
| 1552 |
chr_colors <- rep(c("#2563EB","#64748B"),ceiling(length(chroms)/2))[seq_along(chroms)]
|
| 1553 |
names(chr_colors) <- chroms
|
| 1554 |
chr_mids <- tapply(pd$cum_pos, pd$Chromosome, median, na.rm=TRUE)
|
| 1555 |
p <- ggplot(pd,aes(x=cum_pos,y=LOD)) +
|
| 1556 |
geom_point(aes(color=Chromosome),size=1.2,alpha=.7,show.legend=FALSE) +
|
| 1557 |
geom_point(data=pd[pd$sig,],color="#DC2626",size=3,shape=18) +
|
| 1558 |
-
geom_hline(yintercept=
|
| 1559 |
scale_color_manual(values=chr_colors) +
|
| 1560 |
scale_x_continuous(breaks=chr_mids[chroms],labels=paste0("Chr",chroms)) +
|
| 1561 |
labs(title=paste(input$mapping_method,"Manhattan Plot"),
|
| 1562 |
-
subtitle=paste0("LOD
|
| 1563 |
x="Chromosome",y="LOD Score") +
|
| 1564 |
theme_bw(base_size=12) +
|
| 1565 |
-
theme(panel.background=element_rect(fill="white"),
|
| 1566 |
-
|
| 1567 |
-
|
|
|
|
|
|
|
|
|
|
| 1568 |
if (sum(pd$sig,na.rm=TRUE)>0 && sum(pd$sig,na.rm=TRUE)<=30)
|
| 1569 |
-
p <- p + ggrepel::geom_label_repel(data=pd[pd$sig,],aes(label=Marker),
|
|
|
|
| 1570 |
ggsave(file,plot=p,width=14,height=6,dpi=200,bg="white")
|
| 1571 |
}
|
| 1572 |
)
|
|
@@ -1579,7 +1554,6 @@ server <- function(input, output, session) {
|
|
| 1579 |
mth <- isolate(input$mapping_method)
|
| 1580 |
if (!is.null(rv$scan_all) && !"Message"%in%colnames(rv$scan_all))
|
| 1581 |
res_list[[mth]] <- rv$scan_all
|
| 1582 |
-
# Also add compare results if available
|
| 1583 |
for (m in names(rv$compare_res)) {
|
| 1584 |
r <- rv$compare_res[[m]]
|
| 1585 |
if (!is.null(r) && !"Message"%in%colnames(r)) res_list[[m]] <- r
|
|
@@ -1587,7 +1561,7 @@ server <- function(input, output, session) {
|
|
| 1587 |
if (length(res_list)==0) return()
|
| 1588 |
png(file, width=1800, height=900, res=150, bg="white")
|
| 1589 |
par(bg="white")
|
| 1590 |
-
make_chromosome_idiogram(res_list, rv$all_markers,
|
| 1591 |
dev.off()
|
| 1592 |
}
|
| 1593 |
)
|
|
@@ -1596,18 +1570,26 @@ server <- function(input, output, session) {
|
|
| 1596 |
filename=function() paste0("qtl_results_v6_",Sys.Date(),".xlsx"),
|
| 1597 |
content=function(file) {
|
| 1598 |
sheets <- list()
|
| 1599 |
-
|
| 1600 |
-
if (!is.null(rv$scan_all) && !"Message"%in%colnames(rv$scan_all))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1601 |
if (!is.null(rv$perf)) sheets[["Performance"]] <- rv$perf
|
| 1602 |
for (m in names(rv$compare_res)) {
|
| 1603 |
r <- rv$compare_res[[m]]
|
| 1604 |
if (!is.null(r) && !"Message"%in%colnames(r))
|
| 1605 |
-
sheets[[paste0("Model_",m)]] <- r[r$LOD>=
|
| 1606 |
}
|
| 1607 |
sheets[["Methods"]] <- data.frame(
|
| 1608 |
Method=names(MAPPING_MODELS),
|
| 1609 |
Description=sapply(MAPPING_MODELS,`[[`,"desc"))
|
| 1610 |
-
if (length(sheets)==0)
|
|
|
|
| 1611 |
writexl::write_xlsx(sheets, file)
|
| 1612 |
}
|
| 1613 |
)
|
|
@@ -1625,11 +1607,12 @@ server <- function(input, output, session) {
|
|
| 1625 |
content=function(file) {
|
| 1626 |
if (!is.null(rv$sel_metrics) && !"Message"%in%colnames(rv$sel_metrics))
|
| 1627 |
writexl::write_xlsx(list(Selection=rv$sel_metrics), file)
|
| 1628 |
-
else
|
|
|
|
| 1629 |
}
|
| 1630 |
)
|
| 1631 |
|
| 1632 |
-
# ββ CHAT ββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1633 |
add_msg <- function(role, content) {
|
| 1634 |
rv$chat_msgs <- c(rv$chat_msgs,
|
| 1635 |
list(list(role=role, content=content, time=format(Sys.time(),"%H:%M"))))
|
|
@@ -1637,33 +1620,39 @@ server <- function(input, output, session) {
|
|
| 1637 |
}
|
| 1638 |
|
| 1639 |
rule_response <- function(q) {
|
| 1640 |
-
ql
|
| 1641 |
has_scan <- !is.null(rv$scan_all) && !"Message"%in%colnames(rv$scan_all)
|
| 1642 |
-
has_qtl <- !is.null(rv$sig_qtl) && !"Message"%in%colnames(rv$sig_qtl)
|
| 1643 |
|
| 1644 |
-
if (grepl("top qtl|best qtl|significant",ql) &&
|
| 1645 |
-
|
| 1646 |
-
|
|
|
|
|
|
|
|
|
|
| 1647 |
for (i in 1:nrow(top5)) {
|
| 1648 |
r <- top5[i,]
|
| 1649 |
-
out <- paste0(out,i,".
|
| 1650 |
-
"
|
|
|
|
|
|
|
|
|
|
| 1651 |
}
|
| 1652 |
return(out)
|
| 1653 |
}
|
| 1654 |
if (grepl("chromosom|chr debug|other chrom|missing chr",ql)) {
|
| 1655 |
if (has_scan) {
|
| 1656 |
-
chr_tbl <- table(rv$scan_all$Chromosome[rv$scan_all$LOD>=
|
| 1657 |
-
return(paste0("
|
|
|
|
| 1658 |
"\n\nTotal chromosomes scanned: ", length(unique(rv$scan_all$Chromosome))))
|
| 1659 |
}
|
| 1660 |
return("Run analysis first to see chromosome results.")
|
| 1661 |
}
|
| 1662 |
if (grepl("sim|cim|differ|method|model",ql))
|
| 1663 |
-
return("
|
| 1664 |
if (grepl("pve|semi.partial|variance",ql))
|
| 1665 |
-
return("
|
| 1666 |
-
paste0("
|
| 1667 |
}
|
| 1668 |
|
| 1669 |
process_chat <- function(user_text) {
|
|
@@ -1673,8 +1662,10 @@ server <- function(input, output, session) {
|
|
| 1673 |
if (token_exists) {
|
| 1674 |
ctx <- ""
|
| 1675 |
if (!is.null(rv$scan_all) && !"Message"%in%colnames(rv$scan_all)) {
|
| 1676 |
-
sig <- rv$scan_all[rv$scan_all$LOD>=
|
| 1677 |
-
ctx <- paste0("Analysis done: ",nrow(sig)," QTLs on ",
|
|
|
|
|
|
|
| 1678 |
}
|
| 1679 |
res <- query_ai(paste0(ctx, "User: ", user_text))
|
| 1680 |
if (res$success) { rv$is_typing <- FALSE; add_msg("assistant", res$text); return() }
|
|
@@ -1694,13 +1685,13 @@ server <- function(input, output, session) {
|
|
| 1694 |
observe({
|
| 1695 |
if (length(rv$chat_msgs)==0)
|
| 1696 |
add_msg("assistant", paste0(
|
| 1697 |
-
"
|
| 1698 |
-
"
|
| 1699 |
-
"
|
| 1700 |
-
"
|
| 1701 |
-
"
|
| 1702 |
-
"
|
| 1703 |
-
"Upload data
|
| 1704 |
"Contact: ashmithamganesan@gmail.com, P.sinha@cgiar.org"
|
| 1705 |
))
|
| 1706 |
})
|
|
@@ -1714,7 +1705,7 @@ server <- function(input, output, session) {
|
|
| 1714 |
})
|
| 1715 |
if (rv$is_typing)
|
| 1716 |
elems <- c(elems, list(div(class="cmsg assistant",
|
| 1717 |
-
div(class="typing",
|
| 1718 |
do.call(tagList, elems)
|
| 1719 |
})
|
| 1720 |
}
|
|
|
|
| 1 |
# ============================================================
|
| 2 |
# QTL-Mapper v6 β Multi-Model QTL Mapping
|
| 3 |
+
# FIXED VERSION: 4 bugs patched vs original v6
|
| 4 |
#
|
| 5 |
+
# FIX 1+3: lod_thr is now a reactive() β slider changes
|
| 6 |
+
# instantly update plots/tables without re-running scan
|
| 7 |
+
# FIX 2: run_compare uses input$val_prop instead of hardcoded 0.8
|
| 8 |
+
# FIX 4: qtl_table filters rv$scan_all live against lod_thr()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
# ============================================================
|
| 10 |
|
| 11 |
options(repos = c(CRAN = "https://cloud.r-project.org"))
|
|
|
|
| 47 |
# ============================================================
|
| 48 |
MAPPING_MODELS <- list(
|
| 49 |
"SIM" = list(label = "Simple Interval Mapping (SIM)", desc = "Single-marker regression; LOD = -log10(p); no cofactors"),
|
| 50 |
+
"CIM" = list(label = "Composite Interval Mapping (CIM)", desc = "CIM with RF-selected cofactors; semi-partial R2 PVE"),
|
| 51 |
"MQM" = list(label = "Multiple QTL Model (MQM / stepwise)", desc = "Forward stepwise selection across all markers"),
|
| 52 |
"LASSO" = list(label = "LASSO QTL (penalized)", desc = "L1 penalized regression; lambda by cross-validation"),
|
| 53 |
"RIDGE" = list(label = "Ridge Regression QTL", desc = "L2 penalized regression; shrinks all marker effects")
|
| 54 |
)
|
| 55 |
|
| 56 |
# ============================================================
|
| 57 |
+
# CLEAN COLUMN NAMES
|
| 58 |
# ============================================================
|
| 59 |
cn <- function(x) trimws(gsub('[\r\n\"]', '', as.character(x)))
|
| 60 |
|
| 61 |
# ============================================================
|
| 62 |
+
# GENOTYPE LOADER
|
| 63 |
# ============================================================
|
| 64 |
load_genotype_file <- function(filepath) {
|
| 65 |
lines <- readLines(filepath, warn = FALSE)
|
| 66 |
lines <- gsub("\r", "", lines)
|
| 67 |
lines <- lines[nchar(trimws(lines)) > 0]
|
| 68 |
+
if (length(lines) < 4) stop("Need >= 4 rows: header + chr + pos + >= 1 sample")
|
| 69 |
|
| 70 |
+
header <- cn(strsplit(lines[1], ",")[[1]])
|
| 71 |
+
chr_row <- cn(strsplit(lines[2], ",")[[1]])
|
| 72 |
+
pos_row <- cn(strsplit(lines[3], ",")[[1]])
|
| 73 |
+
data_lines <- lines[-(1:3)]
|
| 74 |
|
| 75 |
gd <- read.csv(text = paste(data_lines, collapse = "\n"),
|
| 76 |
header = FALSE, stringsAsFactors = FALSE, quote = '"',
|
| 77 |
fill = TRUE)
|
| 78 |
|
|
|
|
| 79 |
if (ncol(gd) < length(header)) {
|
| 80 |
for (k in (ncol(gd)+1):length(header))
|
| 81 |
gd[[paste0("V",k)]] <- NA
|
|
|
|
| 86 |
rownames(gd) <- cn(as.character(gd[, 1]))
|
| 87 |
gd <- gd[, -1, drop = FALSE]
|
| 88 |
|
|
|
|
| 89 |
for (col in colnames(gd))
|
| 90 |
gd[[col]] <- suppressWarnings(as.numeric(as.character(gd[[col]])))
|
| 91 |
|
|
|
|
| 97 |
)
|
| 98 |
marker_info <- marker_info[!is.na(marker_info$Position) & marker_info$Chromosome != "", ]
|
| 99 |
|
|
|
|
| 100 |
valid_cols <- colnames(gd)[colnames(gd) %in% marker_info$Marker]
|
| 101 |
gd <- gd[, valid_cols, drop = FALSE]
|
| 102 |
|
|
|
|
| 110 |
}
|
| 111 |
|
| 112 |
# ============================================================
|
| 113 |
+
# CORE QTL SCAN
|
| 114 |
# ============================================================
|
| 115 |
qtl_scan <- function(genotype_matrix, phenotype_vector, marker_info,
|
| 116 |
method = "CIM", n_cofactors = 10, window_size = 10) {
|
|
|
|
| 125 |
cat("Chromosomes in marker_info:",
|
| 126 |
paste(sort(unique(marker_info$Chromosome)), collapse=", "), "\n")
|
| 127 |
|
| 128 |
+
valid_rows <- !is.na(phenotype_vector)
|
| 129 |
+
X_valid <- genotype_matrix[valid_rows, , drop = FALSE]
|
| 130 |
+
y_valid <- phenotype_vector[valid_rows]
|
| 131 |
|
|
|
|
| 132 |
nzv <- apply(X_valid, 2, function(x) length(unique(na.omit(x))) < 2)
|
| 133 |
X_valid <- X_valid[, !nzv, drop = FALSE]
|
| 134 |
cat("Markers after NZV removal:", ncol(X_valid), "\n")
|
|
|
|
| 137 |
if (method == "RIDGE") return(qtl_scan_lasso(X_valid, y_valid, marker_info, alpha = 0))
|
| 138 |
if (method == "MQM") return(qtl_scan_mqm(X_valid, y_valid, marker_info))
|
| 139 |
|
|
|
|
| 140 |
cofactors <- character(0)
|
| 141 |
if (method == "CIM" && n_cofactors > 0) {
|
| 142 |
max_cof <- max(3, floor(sqrt(n_samples)))
|
|
|
|
| 156 |
cat("CIM cofactors selected:", length(cofactors), "\n")
|
| 157 |
}
|
| 158 |
|
|
|
|
| 159 |
results_list <- list()
|
| 160 |
chr_counts <- table(marker_info$Chromosome[marker_info$Marker %in% colnames(X_valid)])
|
| 161 |
cat("Markers per chr:\n"); print(chr_counts)
|
|
|
|
| 169 |
pheno_v <- y_valid[valid_idx]
|
| 170 |
if (length(unique(geno_v)) < 2 || length(pheno_v) < 8) next
|
| 171 |
|
|
|
|
| 172 |
m_info <- marker_info[marker_info$Marker == m, ]
|
| 173 |
if (nrow(m_info) == 0) next
|
| 174 |
m_chr <- as.character(m_info$Chromosome[1])
|
| 175 |
m_pos <- m_info$Position[1]
|
| 176 |
if (is.na(m_pos)) next
|
| 177 |
|
|
|
|
| 178 |
active_cof <- character(0)
|
| 179 |
if (method == "CIM" && length(cofactors) > 0) {
|
| 180 |
chr_mk <- marker_info[marker_info$Chromosome == m_chr, ]
|
|
|
|
| 192 |
active_cof <- head(active_cof, n_cofactors)
|
| 193 |
}
|
| 194 |
|
|
|
|
| 195 |
tryCatch({
|
| 196 |
df <- data.frame(y = pheno_v, focal = geno_v)
|
| 197 |
if (length(active_cof) > 0) {
|
|
|
|
| 220 |
SS_marker <- RSS_reduced - RSS_full
|
| 221 |
pve_cim <- if (RSS_reduced > 0) max(0, SS_marker / RSS_reduced * 100) else NA
|
| 222 |
|
|
|
|
| 223 |
a_code <- df$focal - 1
|
| 224 |
d_code <- as.numeric(df$focal == 1)
|
| 225 |
has_het <- length(unique(d_code)) > 1
|
|
|
|
| 280 |
if (is.null(cv)) return(data.frame(Message="LASSO/Ridge failed"))
|
| 281 |
|
| 282 |
best_lam <- cv$lambda.1se
|
| 283 |
+
coefs <- coef(cv, s=best_lam)[-1]
|
| 284 |
coef_df <- data.frame(Marker=rownames(coef(cv,s=best_lam))[-1], Effect=as.numeric(coefs))
|
| 285 |
coef_df <- coef_df[abs(coef_df$Effect) > 0, ]
|
| 286 |
if (nrow(coef_df) == 0) return(data.frame(Message="No non-zero effects"))
|
| 287 |
|
|
|
|
| 288 |
coef_df <- merge(coef_df, marker_info, by="Marker", all.x=TRUE)
|
| 289 |
coef_df <- coef_df[!is.na(coef_df$Position), ]
|
| 290 |
max_eff <- max(abs(coef_df$Effect))
|
| 291 |
coef_df$LOD <- abs(coef_df$Effect) / max_eff * 10
|
| 292 |
|
|
|
|
| 293 |
r2_vec <- sapply(coef_df$Marker, function(m) {
|
| 294 |
g <- X_v[, m]; v <- !is.na(g)
|
| 295 |
if (sum(v)<5) return(NA)
|
| 296 |
summary(lm(y_v[v] ~ g[v]))$r.squared * 100
|
| 297 |
})
|
| 298 |
coef_df$PVE_Marker_Percent <- r2_vec
|
| 299 |
+
coef_df$PVE_CIM_Percent <- r2_vec
|
| 300 |
coef_df$Additive_Effect <- coef_df$Effect
|
| 301 |
coef_df$P_Value <- 10^(-coef_df$LOD)
|
| 302 |
coef_df$SE_Additive <- NA
|
|
|
|
| 322 |
valid <- !is.na(y)
|
| 323 |
X_v <- X[valid, , drop=FALSE]; y_v <- y[valid]
|
| 324 |
|
|
|
|
| 325 |
p_vals <- sapply(colnames(X_v), function(m) {
|
| 326 |
g <- X_v[,m]; v2 <- !is.na(g)
|
| 327 |
if (length(unique(g[v2])) < 2 || sum(v2) < 8) return(1)
|
| 328 |
tryCatch(coef(summary(lm(y_v[v2] ~ g[v2])))[2,4], error=function(e) 1)
|
| 329 |
})
|
| 330 |
|
|
|
|
| 331 |
selected <- character(0)
|
| 332 |
remaining <- names(sort(p_vals))
|
| 333 |
threshold <- 0.01
|
|
|
|
| 346 |
}
|
| 347 |
if (length(selected)==0) selected <- names(sort(p_vals))[1:min(5,length(p_vals))]
|
| 348 |
|
|
|
|
| 349 |
results_list <- list()
|
| 350 |
for (m in colnames(X_v)) {
|
| 351 |
g <- X_v[,m]; v2 <- !is.na(g) & !is.na(y_v)
|
|
|
|
| 401 |
sig_df$Interval_Start <- sig_df$Interval_End <- sig_df$Interval_Size_cM <- NA_real_
|
| 402 |
|
| 403 |
for (i in 1:nrow(sig_df)) {
|
| 404 |
+
m <- sig_df$Marker[i]; ch <- sig_df$Chromosome[i]; pk <- sig_df$LOD[i]
|
| 405 |
+
cd <- all_df[as.character(all_df$Chromosome)==as.character(ch) & !is.na(all_df$LOD) & !is.na(all_df$Position),]
|
| 406 |
+
cd <- cd[order(cd$Position),]
|
| 407 |
if (nrow(cd)==0) next
|
| 408 |
+
inc <- cd[cd$LOD >= (pk - lod_drop),]
|
| 409 |
+
fp <- cd$Position[cd$Marker==m]
|
| 410 |
if (nrow(inc)>0 && length(fp)>0) {
|
| 411 |
s <- min(inc$Position, fp); e <- max(inc$Position, fp)
|
| 412 |
sig_df$Interval_Start[i] <- s
|
|
|
|
| 430 |
}
|
| 431 |
|
| 432 |
# ============================================================
|
| 433 |
+
# CHROMOSOME IDIOGRAM PLOT
|
|
|
|
| 434 |
# ============================================================
|
| 435 |
make_chromosome_idiogram <- function(qtl_list, all_markers_df,
|
| 436 |
lod_threshold = 2.0,
|
| 437 |
trait_colors = NULL) {
|
|
|
|
| 438 |
if (is.null(all_markers_df) || nrow(all_markers_df)==0) return(NULL)
|
| 439 |
|
|
|
|
| 440 |
default_colors <- c("#C0392B","#2166AC","#1A7A4A","#E67E22","#8E44AD","#17A589","#F39C12","#2980B9")
|
| 441 |
trait_names <- names(qtl_list)
|
| 442 |
if (is.null(trait_colors))
|
| 443 |
trait_colors <- setNames(default_colors[seq_along(trait_names)], trait_names)
|
| 444 |
|
| 445 |
+
shapes <- c(16, 17, 18, 15, 3, 4, 8, 9)
|
|
|
|
| 446 |
|
|
|
|
| 447 |
chroms <- sort(unique(as.character(all_markers_df$Chromosome)))
|
| 448 |
n_chr <- length(chroms)
|
| 449 |
+
bar_height <- 0.35
|
| 450 |
+
x_gap <- 1.2
|
| 451 |
|
|
|
|
| 452 |
par(mar=c(4,2,3,1), bg="white")
|
| 453 |
plot(0, 0, type="n",
|
| 454 |
xlim = c(0, n_chr * x_gap + 0.5),
|
|
|
|
| 457 |
xlab="", ylab="cM", main="",
|
| 458 |
frame.plot=FALSE)
|
| 459 |
|
|
|
|
| 460 |
max_pos <- max(all_markers_df$Position, na.rm=TRUE)
|
| 461 |
y_ticks <- pretty(c(0, max_pos), n=6)
|
| 462 |
axis(2, at=y_ticks, labels=y_ticks, cex.axis=0.75, col="grey60", col.axis="grey30", las=1)
|
| 463 |
mtext("cM", side=2, line=2.5, cex=0.8, col="grey40")
|
| 464 |
|
| 465 |
for (ci in seq_along(chroms)) {
|
| 466 |
+
chr <- chroms[ci]
|
| 467 |
+
x_cen <- (ci-1) * x_gap + 0.7
|
| 468 |
|
|
|
|
| 469 |
chr_mk <- all_markers_df[as.character(all_markers_df$Chromosome)==as.character(chr),]
|
| 470 |
if (nrow(chr_mk)==0) next
|
| 471 |
chr_len <- max(chr_mk$Position, na.rm=TRUE)
|
| 472 |
chr_min <- min(chr_mk$Position, na.rm=TRUE)
|
| 473 |
|
|
|
|
| 474 |
rect(x_cen - bar_height*0.6, chr_min,
|
| 475 |
x_cen + bar_height*0.6, chr_len,
|
| 476 |
col = "grey88", border = "grey60", lwd=1.2)
|
| 477 |
|
|
|
|
| 478 |
cap_h <- chr_len * 0.02
|
| 479 |
rect(x_cen - bar_height*0.6, chr_min - cap_h,
|
| 480 |
x_cen + bar_height*0.6, chr_min,
|
|
|
|
| 483 |
x_cen + bar_height*0.6, chr_len + cap_h,
|
| 484 |
col="grey75", border="grey60", lwd=0.8)
|
| 485 |
|
|
|
|
| 486 |
cen_pos <- chr_min + (chr_len - chr_min) * 0.4
|
| 487 |
rect(x_cen - bar_height*0.6, cen_pos - chr_len*0.04,
|
| 488 |
x_cen + bar_height*0.6, cen_pos + chr_len*0.04,
|
| 489 |
col="grey50", border="grey40", lwd=0.5)
|
| 490 |
|
|
|
|
| 491 |
for (mk_pos in chr_mk$Position) {
|
| 492 |
segments(x_cen - bar_height*0.55, mk_pos,
|
| 493 |
x_cen + bar_height*0.55, mk_pos,
|
| 494 |
col="grey70", lwd=0.4)
|
| 495 |
}
|
| 496 |
|
|
|
|
| 497 |
for (ti in seq_along(trait_names)) {
|
| 498 |
+
tr <- trait_names[ti]
|
| 499 |
+
qdf <- qtl_list[[tr]]
|
| 500 |
if (is.null(qdf) || "Message" %in% colnames(qdf)) next
|
| 501 |
+
sig <- qdf[as.character(qdf$Chromosome)==as.character(chr) &
|
| 502 |
+
!is.na(qdf$LOD) & qdf$LOD >= lod_threshold, ]
|
| 503 |
if (nrow(sig)==0) next
|
| 504 |
|
| 505 |
col_ti <- trait_colors[[tr]]
|
| 506 |
pch_ti <- shapes[((ti-1) %% length(shapes)) + 1]
|
| 507 |
cex_fun <- function(lod) pmax(0.7, pmin(2.2, 0.5 + lod/4))
|
| 508 |
|
|
|
|
| 509 |
x_off <- if (ti %% 2 == 1) x_cen + bar_height * 0.75 else x_cen - bar_height * 0.75
|
| 510 |
|
| 511 |
for (ri in 1:nrow(sig)) {
|
| 512 |
pos <- sig$Position[ri]
|
|
|
|
| 513 |
if (ti %% 2 == 1)
|
| 514 |
segments(x_cen + bar_height*0.6, pos, x_off, pos, col=col_ti, lwd=0.8, lty=2)
|
| 515 |
else
|
| 516 |
segments(x_cen - bar_height*0.6, pos, x_off, pos, col=col_ti, lwd=0.8, lty=2)
|
|
|
|
| 517 |
points(x_off, pos, pch=pch_ti, col=col_ti, bg=col_ti,
|
| 518 |
cex=cex_fun(sig$LOD[ri]))
|
|
|
|
| 519 |
if (sig$LOD[ri] >= lod_threshold * 1.5) {
|
| 520 |
text(x_off + ifelse(ti%%2==1, 0.15, -0.15), pos,
|
| 521 |
round(sig$LOD[ri], 1), cex=0.55, col=col_ti, font=2)
|
|
|
|
| 523 |
}
|
| 524 |
}
|
| 525 |
|
|
|
|
| 526 |
text(x_cen, chr_len + cap_h + chr_len*0.04, paste0("Chr", chr),
|
| 527 |
cex=0.72, font=2, col="grey20")
|
| 528 |
}
|
| 529 |
|
|
|
|
| 530 |
if (length(trait_names) > 0) {
|
| 531 |
legend_x <- 0.1
|
| 532 |
legend_y <- max_pos * 0.98
|
|
|
|
| 546 |
title.col = "grey30")
|
| 547 |
}
|
| 548 |
|
| 549 |
+
title(main = paste0("QTL Chromosome Map β LOD >= ", lod_threshold,
|
| 550 |
" | Method: ", paste(unique(unlist(lapply(qtl_list, function(q)
|
| 551 |
if (!is.null(q) && !"Message" %in% colnames(q) && "Method" %in% colnames(q))
|
| 552 |
unique(q$Method) else NULL))), collapse="/")),
|
|
|
|
| 554 |
}
|
| 555 |
|
| 556 |
# ============================================================
|
| 557 |
+
# PLOTLY MANHATTAN
|
| 558 |
# ============================================================
|
| 559 |
make_plotly_manhattan <- function(scan_all, lod_threshold=2.0, title="QTL Manhattan Plot") {
|
| 560 |
blank <- plot_ly() %>% layout(title=title, plot_bgcolor="#FFFFFF", paper_bgcolor="#FFFFFF")
|
|
|
|
| 565 |
pd$Chromosome <- as.character(pd$Chromosome)
|
| 566 |
chroms <- sort(unique(pd$Chromosome), method="radix")
|
| 567 |
|
|
|
|
| 568 |
offsets <- numeric(length(chroms)); names(offsets) <- chroms
|
| 569 |
for (i in seq_along(chroms)) {
|
| 570 |
if (i==1) { offsets[chroms[1]] <- 0; next }
|
|
|
|
| 590 |
text=~paste0("Marker: ",Marker,"<br>Chr: ",Chromosome,"<br>Pos: ",round(Position,1)," cM<br>LOD: ",round(LOD,2),"<br>PVE: ",round(PVE_Marker_Percent,1),"%"),
|
| 591 |
hoverinfo="text", showlegend=FALSE)
|
| 592 |
}
|
|
|
|
| 593 |
sig_pd <- pd[pd$sig,]
|
| 594 |
if (nrow(sig_pd)>0)
|
| 595 |
p <- p %>% add_trace(
|
|
|
|
| 598 |
text=~paste0("<b>",Marker,"</b><br>Chr: ",Chromosome,"<br>LOD: ",round(LOD,2),"<br>PVE_marker: ",round(PVE_Marker_Percent,1),"%"),
|
| 599 |
hoverinfo="text")
|
| 600 |
|
|
|
|
| 601 |
p <- p %>%
|
| 602 |
add_segments(x=min(pd$cum_pos,na.rm=TRUE), xend=max(pd$cum_pos,na.rm=TRUE),
|
| 603 |
y=lod_threshold, yend=lod_threshold,
|
|
|
|
| 692 |
.model-badge{display:inline-block;background:#EFF6FF;border:1px solid #BFDBFE;
|
| 693 |
border-radius:12px;padding:2px 10px;font-size:11px;font-family:var(--mono);
|
| 694 |
color:var(--accent);margin-right:6px;}
|
|
|
|
|
|
|
|
|
|
| 695 |
#chat-panel{position:fixed;bottom:16px;right:16px;z-index:9999;width:420px;display:flex;flex-direction:column;}
|
| 696 |
#chat-toggle{align-self:flex-end;width:52px;height:52px;border-radius:50%;
|
| 697 |
background:linear-gradient(135deg,var(--accent),#7C3AED);border:none;cursor:pointer;
|
|
|
|
| 730 |
border-radius:5px;padding:7px 14px;font-family:var(--mono);font-size:12px;font-weight:600;cursor:pointer;}
|
| 731 |
#clear_chat{background:transparent;color:var(--muted);border:1px solid var(--border);
|
| 732 |
border-radius:5px;padding:7px 10px;font-family:var(--mono);font-size:12px;cursor:pointer;}
|
|
|
|
| 733 |
table.dataTable{background:#FFF!important;color:var(--txt)!important;}
|
| 734 |
table.dataTable thead th{background:#F1F5F9!important;font-family:var(--mono);font-size:11px;}
|
| 735 |
table.dataTable tbody tr:hover{background:#EFF6FF!important;}
|
|
|
|
| 741 |
title = tags$span(tags$i(class="fas fa-dna",style="color:#1D4ED8;margin-right:6px;"), "QTL-Mapper v6"),
|
| 742 |
id = "nav",
|
| 743 |
|
| 744 |
+
# ββ DATA UPLOAD βββββββββββββββββββββββββββββββββββοΏ½οΏ½ββββββββ
|
| 745 |
tabPanel("Data Upload", icon=icon("upload"),
|
| 746 |
fluidRow(column(12,
|
| 747 |
div(class="info-box",
|
|
|
|
| 781 |
numericInput("window_size","Exclusion Window (Β±markers)",value=10,min=1,max=30,step=1)
|
| 782 |
),
|
| 783 |
numericInput("lod_drop","LOD Drop for Interval",value=1.5,min=0.5,max=3.0,step=0.5),
|
| 784 |
+
actionButton("run_btn","Run QTL Analysis",class="btn btn-primary btn-block",
|
| 785 |
style="margin-top:8px;width:100%;")
|
| 786 |
)
|
| 787 |
)
|
|
|
|
| 817 |
))
|
| 818 |
),
|
| 819 |
|
| 820 |
+
# ββ RESULTS ββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 821 |
tabPanel("Results", icon=icon("chart-line"),
|
| 822 |
fluidRow(column(12,
|
| 823 |
div(style="display:flex;gap:10px;flex-wrap:wrap;margin-bottom:12px;",
|
|
|
|
| 835 |
),
|
| 836 |
column(5,
|
| 837 |
div(class="card",
|
| 838 |
+
div(class="card-hd","Chromosome Idiogram β QTL Positions"),
|
| 839 |
+
div(class="card-bd",plotOutput("idiogram_plot",height="480px"))
|
|
|
|
|
|
|
| 840 |
)
|
| 841 |
)
|
| 842 |
),
|
|
|
|
| 862 |
),
|
| 863 |
fluidRow(column(12,
|
| 864 |
div(class="card",
|
| 865 |
+
div(class="card-hd","QTL Effects Table β Significant Markers (live LOD filter)"),
|
| 866 |
div(class="card-bd",DTOutput("qtl_table"))
|
| 867 |
)
|
| 868 |
)),
|
|
|
|
| 874 |
))
|
| 875 |
),
|
| 876 |
|
| 877 |
+
# ββ COMPARE MODELS βββββββββββββββββββββββββββββββββββββββββ
|
| 878 |
tabPanel("Compare Models", icon=icon("balance-scale"),
|
| 879 |
fluidRow(column(12,
|
| 880 |
div(class="card",
|
|
|
|
| 884 |
checkboxGroupInput("compare_methods","Methods to Compare:",
|
| 885 |
choices = setNames(names(MAPPING_MODELS), sapply(MAPPING_MODELS,`[[`,"label")),
|
| 886 |
selected = c("SIM","CIM"), inline=TRUE),
|
| 887 |
+
actionButton("run_compare","Run All Selected Models",class="btn btn-primary"),
|
| 888 |
tags$br(),tags$br(),
|
| 889 |
uiOutput("compare_status_ui")
|
| 890 |
)
|
|
|
|
| 912 |
))
|
| 913 |
),
|
| 914 |
|
| 915 |
+
# ββ DOMESTICATION ββββββββββββββββββββββββββββββββββββββββββ
|
| 916 |
tabPanel("Domestication", icon=icon("leaf"),
|
| 917 |
fluidRow(
|
| 918 |
column(4,
|
|
|
|
| 921 |
div(class="card-bd",
|
| 922 |
numericInput("fst_thr","Fst Threshold",value=0.1,min=0.05,max=0.5,step=0.01),
|
| 923 |
numericInput("tajima_thr","Tajima's D Threshold",value=-1,min=-5,max=0,step=0.1),
|
| 924 |
+
actionButton("run_dom","Run Domestication",class="btn btn-primary btn-block")
|
| 925 |
)
|
| 926 |
)
|
| 927 |
),
|
|
|
|
| 947 |
))
|
| 948 |
),
|
| 949 |
|
| 950 |
+
# ββ ABOUT ββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 951 |
tabPanel("About", icon=icon("info-circle"),
|
| 952 |
fluidRow(column(8,offset=2,
|
| 953 |
div(class="card",
|
| 954 |
div(class="card-bd",
|
| 955 |
tags$h4(style="color:var(--accent);font-family:var(--mono);","QTL-Mapper v6 β Changes & Methods"),
|
| 956 |
div(class="warn-box",
|
| 957 |
+
tags$b("v5->v6 Key Fixes:"), tags$br(),
|
| 958 |
"1. MULTI-CHROMOSOME: robust marker_info join; debug log per chr; all chroms now scan", tags$br(),
|
| 959 |
"2. MULTIPLE MODELS: SIM, CIM, MQM, LASSO, Ridge β select/compare freely", tags$br(),
|
| 960 |
"3. IDIOGRAM PLOT: replicates reference image (chromosome bars + colored symbols per trait)", tags$br(),
|
| 961 |
"4. MANHATTAN: proper cumulative offsets for all chromosomes, not just Chr1", tags$br(),
|
| 962 |
+
"5. PVE: semi-partial R2 (denominator = RSS after cofactors, not raw SS_total)", tags$br(),
|
| 963 |
+
tags$b("Bug fixes in this build:"), tags$br(),
|
| 964 |
+
"FIX 1+3: lod_thr is now reactive() β slider updates all plots/tables instantly", tags$br(),
|
| 965 |
+
"FIX 2: Compare tab uses input$val_prop instead of hardcoded 0.8", tags$br(),
|
| 966 |
+
"FIX 4: QTL table live-filters rv$scan_all on every slider change"
|
| 967 |
),
|
| 968 |
tags$h5(style="margin-top:16px;font-family:var(--mono);","Mapping Methods"),
|
| 969 |
tags$ul(lapply(MAPPING_MODELS, function(m)
|
|
|
|
| 974 |
tags$li("Zeng (1993) PNAS 90:10972 β CIM"),
|
| 975 |
tags$li("Zeng (1994) Genetics 136:1457 β CIM"),
|
| 976 |
tags$li("Lander & Botstein (1989) Genetics 121:185 β LOD intervals"),
|
| 977 |
+
tags$li("Lynch & Walsh (1998) β Semi-partial R2"),
|
| 978 |
tags$li("Tibshirani (1996) JRSS-B 58:267 β LASSO"),
|
| 979 |
tags$li("Contact: ashmithamganesan@gmail.com, P.sinha@cgiar.org")
|
| 980 |
)
|
|
|
|
| 984 |
)
|
| 985 |
),
|
| 986 |
|
| 987 |
+
# ββ FLOATING CHAT βββββββββββββββββββββββββββββββββββββββββ
|
| 988 |
tags$div(id="chat-panel",
|
| 989 |
tags$div(id="chat-win",
|
| 990 |
tags$div(id="chat-hd",
|
|
|
|
| 1028 |
geno = NULL, pheno = NULL,
|
| 1029 |
test_geno = NULL, pop_data = NULL,
|
| 1030 |
marker_info = NULL, all_markers = NULL,
|
| 1031 |
+
scan_all = NULL,
|
| 1032 |
perf = NULL, tr_pred = NULL, val_pred = NULL,
|
| 1033 |
model_fit = NULL, model_cols = NULL,
|
| 1034 |
pred_test = NULL,
|
| 1035 |
sel_metrics = NULL,
|
| 1036 |
+
compare_res = list(),
|
| 1037 |
chat_msgs = list(),
|
| 1038 |
+
is_typing = FALSE
|
|
|
|
| 1039 |
)
|
| 1040 |
|
| 1041 |
+
# ββ FIX 1+3: lod_thr as reactive β tracks slider in real time ββ
|
| 1042 |
+
lod_thr <- reactive({ input$lod_threshold })
|
| 1043 |
+
|
| 1044 |
+
# ββ Method description ββββββββββββββββββββββββββββββββββββββ
|
| 1045 |
output$method_desc_ui <- renderUI({
|
| 1046 |
m <- input$mapping_method
|
| 1047 |
if (is.null(m) || !m %in% names(MAPPING_MODELS)) return(NULL)
|
| 1048 |
div(class="info-box", MAPPING_MODELS[[m]]$desc)
|
| 1049 |
})
|
| 1050 |
|
| 1051 |
+
# ββ Dataset info ββββββββββββββββββββββββββββββββββββββββββββ
|
| 1052 |
output$dataset_info_ui <- renderUI({
|
| 1053 |
if (is.null(rv$geno)) return(tags$p("No data loaded yet."))
|
| 1054 |
n_chr <- length(unique(rv$marker_info$Chromosome))
|
|
|
|
| 1062 |
)
|
| 1063 |
})
|
| 1064 |
|
| 1065 |
+
# ββ Data loading ββββββββββββββββββββββββββββββββββββββββββββ
|
| 1066 |
observeEvent(input$geno_file, {
|
| 1067 |
req(input$geno_file)
|
| 1068 |
tryCatch({
|
|
|
|
| 1070 |
rv$geno <- res$geno
|
| 1071 |
rv$marker_info <- res$marker_info
|
| 1072 |
rv$all_markers <- res$marker_info
|
| 1073 |
+
msg <- paste0("Genotype loaded: ", res$n_markers, " markers, ", res$n_samples,
|
| 1074 |
+
" samples, ", length(res$chromosomes), " chromosomes: ",
|
| 1075 |
+
paste(res$chromosomes, collapse=", "))
|
| 1076 |
add_msg("assistant", msg)
|
| 1077 |
+
showNotification(paste(res$n_markers,"markers,",res$n_samples,"samples,",
|
| 1078 |
+
length(res$chromosomes),"chromosomes"), type="message")
|
| 1079 |
}, error=function(e) showNotification(paste("Geno error:",e$message), type="error"))
|
| 1080 |
})
|
| 1081 |
|
|
|
|
| 1109 |
}, error=function(e) showNotification(paste("Test geno error:",e$message), type="error"))
|
| 1110 |
})
|
| 1111 |
|
| 1112 |
+
# ββ Previews ββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1113 |
+
output$prev_geno <- renderDT({ req(input$geno_file); datatable(head(read.csv(input$geno_file$datapath),10), options=list(scrollX=TRUE,pageLength=5)) })
|
| 1114 |
+
output$prev_pheno <- renderDT({ req(input$pheno_file); datatable(head(read.csv(input$pheno_file$datapath),10), options=list(scrollX=TRUE,pageLength=5)) })
|
| 1115 |
output$prev_test_geno <- renderDT({ req(rv$test_geno); datatable(head(rv$test_geno,10), options=list(scrollX=TRUE,pageLength=5)) })
|
| 1116 |
output$prev_pred <- renderDT({ req(rv$pred_test); datatable(rv$pred_test, options=list(scrollX=TRUE,pageLength=8)) })
|
| 1117 |
output$prev_pop <- renderDT({ req(rv$pop_data); datatable(head(rv$pop_data,10), options=list(scrollX=TRUE,pageLength=5)) })
|
| 1118 |
|
| 1119 |
+
# ββ MAIN ANALYSIS βββββββββββββββββββββββββββββββββββββββββββ
|
| 1120 |
observeEvent(input$run_btn, {
|
| 1121 |
req(rv$geno, rv$pheno, input$pheno_col)
|
| 1122 |
|
| 1123 |
+
showNotification(paste("Starting", input$mapping_method, "scan..."), type="message")
|
|
|
|
| 1124 |
|
| 1125 |
tryCatch({
|
| 1126 |
+
cs <- intersect(rownames(rv$geno), rownames(rv$pheno))
|
| 1127 |
+
if (length(cs)==0) {
|
| 1128 |
+
showNotification("No common samples between genotype and phenotype!", type="error")
|
| 1129 |
+
return()
|
| 1130 |
+
}
|
| 1131 |
|
| 1132 |
X <- rv$geno[cs, , drop=FALSE]
|
| 1133 |
y <- as.numeric(rv$pheno[cs, input$pheno_col])
|
| 1134 |
|
| 1135 |
set.seed(42)
|
| 1136 |
+
tr_idx <- caret::createDataPartition(y, p = 1 - input$val_prop, list=FALSE)
|
| 1137 |
+
X_tr <- X[tr_idx,,drop=FALSE]; X_v <- X[-tr_idx,,drop=FALSE]
|
| 1138 |
+
y_tr <- y[tr_idx]; y_v <- y[-tr_idx]
|
| 1139 |
|
| 1140 |
+
withProgress(message=paste("Running", input$mapping_method, "genome scan..."), value=0.1, {
|
| 1141 |
scan_res <- qtl_scan(
|
| 1142 |
genotype_matrix = X_tr,
|
| 1143 |
phenotype_vector = y_tr,
|
|
|
|
| 1150 |
|
| 1151 |
rv$scan_all <- scan_res
|
| 1152 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1153 |
# RF prediction model
|
| 1154 |
nzv_idx <- caret::nearZeroVar(X_tr)
|
| 1155 |
X_tr_rf <- if(length(nzv_idx)>0) X_tr[,-nzv_idx,drop=FALSE] else X_tr
|
|
|
|
| 1170 |
tr_r2 <- 1 - sum((y_tr-ytr_pred)^2)/sum((y_tr-mean(y_tr))^2)
|
| 1171 |
v_r2 <- 1 - sum((y_v-yv_pred)^2)/sum((y_v-mean(y_v))^2)
|
| 1172 |
rv$perf <- data.frame(
|
| 1173 |
+
Metric=c("R2 Train","R Train","R2 Validation","R Validation"),
|
| 1174 |
Value=c(tr_r2, cor(y_tr,ytr_pred), v_r2, cor(y_v,yv_pred)))
|
| 1175 |
rv$tr_pred <- data.frame(Observed=y_tr, Predicted=ytr_pred)
|
| 1176 |
rv$val_pred <- data.frame(Observed=y_v, Predicted=yv_pred)
|
|
|
|
| 1178 |
incProgress(0.3)
|
| 1179 |
})
|
| 1180 |
|
| 1181 |
+
n_sig <- if (!is.null(rv$scan_all) && !"Message" %in% colnames(rv$scan_all))
|
| 1182 |
+
sum(rv$scan_all$LOD >= lod_thr() & !is.na(rv$scan_all$LOD), na.rm=TRUE) else 0
|
| 1183 |
n_chr_res <- if (!is.null(rv$scan_all) && !"Message" %in% colnames(rv$scan_all))
|
| 1184 |
length(unique(rv$scan_all$Chromosome)) else 0
|
| 1185 |
+
|
| 1186 |
add_msg("assistant", paste0(
|
| 1187 |
+
input$mapping_method, " scan complete!\n\n",
|
| 1188 |
+
"β’ ", n_sig, " QTLs above LOD ", lod_thr(), "\n",
|
| 1189 |
+
"β’ Chromosomes in results: ", n_chr_res, "\n",
|
| 1190 |
+
"β’ Validation R2: ", round(rv$perf$Value[3], 3)
|
| 1191 |
))
|
| 1192 |
+
showNotification(paste(input$mapping_method, "done:", n_sig, "QTLs on", n_chr_res, "chromosomes"), type="message")
|
| 1193 |
+
updateTabsetPanel(session, "nav", selected="Results")
|
| 1194 |
|
| 1195 |
}, error=function(e) {
|
| 1196 |
+
showNotification(paste("Analysis error:", e$message), type="error")
|
| 1197 |
cat("ANALYSIS ERROR:", e$message, "\n")
|
| 1198 |
})
|
| 1199 |
})
|
| 1200 |
|
| 1201 |
+
# ββ COMPARE MODELS ββββββββββββββββββββββββββββββββββββββββββ
|
| 1202 |
output$compare_status_ui <- renderUI({
|
| 1203 |
if (length(rv$compare_res)==0) return(NULL)
|
| 1204 |
tags$div(class="info-box",
|
|
|
|
| 1207 |
lapply(names(rv$compare_res), function(m) {
|
| 1208 |
r <- rv$compare_res[[m]]
|
| 1209 |
if (is.null(r)||"Message"%in%colnames(r)) return(tags$span(m,": 0 QTLs "))
|
| 1210 |
+
n <- sum(r$LOD >= lod_thr(), na.rm=TRUE)
|
| 1211 |
nc <- length(unique(r$Chromosome[!is.na(r$LOD)]))
|
| 1212 |
tags$span(class="model-badge", paste0(m,": ",n," QTLs / ",nc," chr "))
|
| 1213 |
})
|
|
|
|
| 1217 |
observeEvent(input$run_compare, {
|
| 1218 |
req(rv$geno, rv$pheno, input$compare_methods, input$pheno_col)
|
| 1219 |
methods_sel <- input$compare_methods
|
| 1220 |
+
if (length(methods_sel)==0) {
|
| 1221 |
+
showNotification("Select at least one method", type="warning")
|
| 1222 |
+
return()
|
| 1223 |
+
}
|
| 1224 |
|
| 1225 |
cs <- intersect(rownames(rv$geno), rownames(rv$pheno))
|
| 1226 |
+
X <- rv$geno[cs,,drop=FALSE]
|
| 1227 |
+
y <- as.numeric(rv$pheno[cs, input$pheno_col])
|
| 1228 |
+
|
| 1229 |
+
# FIX 2: use input$val_prop instead of hardcoded 0.8
|
| 1230 |
+
set.seed(42)
|
| 1231 |
+
tr_idx <- caret::createDataPartition(y, p = 1 - input$val_prop, list=FALSE)
|
| 1232 |
+
X_tr <- X[tr_idx,,drop=FALSE]
|
| 1233 |
+
y_tr <- y[tr_idx]
|
| 1234 |
|
| 1235 |
compare_list <- list()
|
| 1236 |
withProgress(message="Comparing models...", value=0, {
|
| 1237 |
for (mth in methods_sel) {
|
| 1238 |
+
incProgress(1/length(methods_sel), detail=paste("Running", mth))
|
| 1239 |
res <- tryCatch(
|
| 1240 |
qtl_scan(X_tr, y_tr, rv$marker_info, method=mth,
|
| 1241 |
n_cofactors=input$n_cofactors, window_size=input$window_size),
|
| 1242 |
+
error=function(e) { cat("Compare error", mth, ":", e$message, "\n"); NULL }
|
| 1243 |
)
|
| 1244 |
if (!is.null(res)) compare_list[[mth]] <- res
|
| 1245 |
}
|
| 1246 |
})
|
| 1247 |
rv$compare_res <- compare_list
|
| 1248 |
+
showNotification(paste("Compared", length(compare_list), "models"), type="message")
|
| 1249 |
})
|
| 1250 |
|
| 1251 |
output$compare_idiogram <- renderPlot({
|
| 1252 |
req(length(rv$compare_res)>0, rv$all_markers)
|
| 1253 |
par(bg="white")
|
| 1254 |
+
make_chromosome_idiogram(rv$compare_res, rv$all_markers, lod_thr())
|
| 1255 |
}, bg="white")
|
| 1256 |
|
| 1257 |
output$compare_bar <- renderPlotly({
|
|
|
|
| 1260 |
for (mth in names(rv$compare_res)) {
|
| 1261 |
r <- rv$compare_res[[mth]]
|
| 1262 |
if (is.null(r)||"Message"%in%colnames(r)) next
|
| 1263 |
+
sig <- r[r$LOD >= lod_thr() & !is.na(r$LOD),]
|
| 1264 |
if (nrow(sig)==0) next
|
| 1265 |
for (ch in unique(sig$Chromosome))
|
| 1266 |
rows <- c(rows, list(data.frame(Method=mth, Chromosome=as.character(ch),
|
| 1267 |
Count=sum(sig$Chromosome==ch), stringsAsFactors=FALSE)))
|
| 1268 |
}
|
| 1269 |
+
if (length(rows)==0)
|
| 1270 |
+
return(plot_ly() %>% layout(title="No significant QTLs found"))
|
| 1271 |
df <- do.call(rbind, rows)
|
| 1272 |
df$Chromosome <- factor(df$Chromosome, levels=sort(unique(df$Chromosome)))
|
| 1273 |
plot_ly(df, x=~Chromosome, y=~Count, color=~Method, type="bar") %>%
|
|
|
|
| 1282 |
for (mth in names(rv$compare_res)) {
|
| 1283 |
r <- rv$compare_res[[mth]]
|
| 1284 |
if (is.null(r)||"Message"%in%colnames(r)) next
|
| 1285 |
+
sig <- r[r$LOD >= lod_thr() & !is.na(r$LOD),]
|
| 1286 |
if (nrow(sig)==0) next
|
| 1287 |
sig$Method2 <- mth
|
| 1288 |
rows <- c(rows, list(sig[,c("Marker","Chromosome","Position","LOD","PVE_Marker_Percent","Method2")]))
|
| 1289 |
}
|
| 1290 |
if (length(rows)==0) return(datatable(data.frame(Status="No QTLs")))
|
| 1291 |
df <- do.call(rbind, rows)
|
|
|
|
| 1292 |
overlap <- table(df$Marker)
|
| 1293 |
df$Detected_By_N_Models <- as.integer(overlap[df$Marker])
|
| 1294 |
datatable(df[order(-df$Detected_By_N_Models,-df$LOD),],
|
|
|
|
| 1296 |
formatRound(c("LOD","PVE_Marker_Percent","Position"),3)
|
| 1297 |
})
|
| 1298 |
|
| 1299 |
+
# ββ PLOTS βββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1300 |
output$manhattan_plot <- renderPlotly({
|
| 1301 |
req(rv$scan_all)
|
| 1302 |
+
make_plotly_manhattan(rv$scan_all, lod_thr(),
|
| 1303 |
+
paste(input$mapping_method, "Manhattan Plot"))
|
| 1304 |
})
|
| 1305 |
|
| 1306 |
output$idiogram_plot <- renderPlot({
|
| 1307 |
req(rv$scan_all, rv$all_markers)
|
| 1308 |
res_list <- list()
|
| 1309 |
+
mth <- input$mapping_method
|
| 1310 |
+
if (!is.null(rv$scan_all) && !"Message" %in% colnames(rv$scan_all))
|
| 1311 |
res_list[[mth]] <- rv$scan_all
|
| 1312 |
if (length(res_list)==0) {
|
| 1313 |
+
plot(0,0,type="n",axes=FALSE,xlab="",ylab="")
|
| 1314 |
+
text(0,0,"Run analysis first",cex=1.2)
|
| 1315 |
+
return()
|
| 1316 |
}
|
| 1317 |
par(bg="white")
|
| 1318 |
+
make_chromosome_idiogram(res_list, rv$all_markers, lod_thr())
|
| 1319 |
}, bg="white")
|
| 1320 |
|
| 1321 |
output$perf_plot <- renderPlotly({
|
|
|
|
| 1347 |
xaxis=list(title="Observed"),yaxis=list(title="Predicted"))
|
| 1348 |
})
|
| 1349 |
|
| 1350 |
+
# ββ TABLES ββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1351 |
+
|
| 1352 |
+
# FIX 4: live-filter rv$scan_all against lod_thr() on every render
|
| 1353 |
output$qtl_table <- renderDT({
|
| 1354 |
+
req(rv$scan_all)
|
| 1355 |
+
if ("Message" %in% colnames(rv$scan_all))
|
| 1356 |
+
return(datatable(data.frame(Status=rv$scan_all$Message[1]),
|
| 1357 |
+
options=list(dom="t")))
|
| 1358 |
+
|
| 1359 |
+
sig <- rv$scan_all[!is.na(rv$scan_all$LOD) & rv$scan_all$LOD >= lod_thr(), , drop=FALSE]
|
| 1360 |
+
|
| 1361 |
+
if (nrow(sig)==0)
|
| 1362 |
+
return(datatable(data.frame(Status=paste("No QTLs above LOD", lod_thr())),
|
| 1363 |
+
options=list(dom="t")))
|
| 1364 |
+
|
| 1365 |
+
sig <- add_lod_support_interval(sig, rv$scan_all, input$lod_drop)
|
| 1366 |
+
sig <- sig[order(-sig$LOD), ]
|
| 1367 |
+
|
| 1368 |
disp <- intersect(c("Marker","Chromosome","Position","LOD","P_Value",
|
| 1369 |
"PVE_Marker_Percent","PVE_CIM_Percent","Additive_Effect","SE_Additive",
|
| 1370 |
"CI_Lower","CI_Upper","Dominance_Effect","Dominance_Ratio","Dominance_Class",
|
| 1371 |
"N_Cofactors","N_Samples","Method","Interval_Start","Interval_End",
|
| 1372 |
+
"Interval_Size_cM","Low_Flank","High_Flank"), colnames(sig))
|
| 1373 |
+
|
| 1374 |
+
datatable(sig[, disp],
|
| 1375 |
+
options=list(scrollX=TRUE, pageLength=10), rownames=FALSE) %>%
|
| 1376 |
+
formatRound(intersect(c("LOD","PVE_Marker_Percent","PVE_CIM_Percent",
|
| 1377 |
+
"Additive_Effect","SE_Additive","CI_Lower","CI_Upper",
|
| 1378 |
+
"Dominance_Ratio","Interval_Size_cM"), disp), 3) %>%
|
| 1379 |
+
formatSignif(intersect("P_Value", disp), digits=3)
|
| 1380 |
})
|
| 1381 |
|
| 1382 |
output$full_scan_table <- renderDT({
|
| 1383 |
req(rv$scan_all)
|
| 1384 |
if ("Message" %in% colnames(rv$scan_all))
|
| 1385 |
+
return(datatable(data.frame(Status=rv$scan_all$Message[1]),
|
| 1386 |
+
options=list(dom="t")))
|
| 1387 |
+
datatable(rv$scan_all,
|
| 1388 |
+
options=list(scrollX=TRUE, pageLength=15, order=list(list(4,"desc"))),
|
| 1389 |
rownames=FALSE) %>%
|
| 1390 |
formatRound(c("LOD","PVE_Marker_Percent","Additive_Effect"),3) %>%
|
| 1391 |
+
formatSignif("P_Value", digits=3)
|
| 1392 |
})
|
| 1393 |
|
| 1394 |
+
# ββ PREDICT TEST ββββββββββββββββββββββββββββββββββββββββββββ
|
| 1395 |
observeEvent(input$pred_btn, {
|
| 1396 |
if (is.null(rv$model_fit)) { showNotification("Run analysis first", type="error"); return() }
|
| 1397 |
if (is.null(rv$test_geno)) { showNotification("Upload test genotype first", type="error"); return() }
|
|
|
|
| 1417 |
rv$pred_test <- data.frame(Sample_ID=rownames(test_raw), Predicted_Phenotype=round(preds,4))
|
| 1418 |
incProgress(0.3)
|
| 1419 |
})
|
| 1420 |
+
showNotification(paste("Predicted", nrow(rv$pred_test), "test samples"), type="message")
|
| 1421 |
})
|
| 1422 |
|
| 1423 |
+
# ββ DOMESTICATION βββββββββββββββββββββββββββββββββββββββββββ
|
| 1424 |
calc_sel <- function(gmat, pop, minfo) {
|
| 1425 |
out <- list()
|
| 1426 |
for (m in colnames(gmat)) {
|
|
|
|
| 1434 |
pid <- 2*fd*(1-fd); piw <- 2*fw*(1-fw)
|
| 1435 |
tdd <- tryCatch((pid-1/length(gd))/sqrt(var(gd)/length(gd)),error=function(e)NA)
|
| 1436 |
mi <- minfo[minfo$Marker==m,]
|
| 1437 |
+
out[[m]] <- data.frame(Marker=m,
|
| 1438 |
+
Chromosome=if(nrow(mi)>0)mi$Chromosome[1] else NA,
|
| 1439 |
+
Position=if(nrow(mi)>0)mi$Position[1] else NA,
|
| 1440 |
+
Fst=fst, Pi_Dom=pid, Pi_Wild=piw, Tajima_D_Dom=tdd,
|
| 1441 |
+
stringsAsFactors=FALSE)
|
| 1442 |
}
|
| 1443 |
if (length(out)==0) return(NULL)
|
| 1444 |
do.call(rbind, out)
|
|
|
|
| 1448 |
req(rv$geno, rv$pop_data, rv$marker_info)
|
| 1449 |
tryCatch({
|
| 1450 |
cs <- intersect(rownames(rv$geno), rv$pop_data$id)
|
| 1451 |
+
X <- rv$geno[cs,,drop=FALSE]
|
| 1452 |
+
ps <- rv$pop_data[rv$pop_data$id %in% cs,]
|
| 1453 |
sel <- calc_sel(X, ps, rv$marker_info)
|
| 1454 |
if (is.null(sel)) { showNotification("No selection metrics computed", type="error"); return() }
|
| 1455 |
sel$Significant <- sel$Fst > input$fst_thr | sel$Tajima_D_Dom < input$tajima_thr
|
|
|
|
| 1459 |
})
|
| 1460 |
|
| 1461 |
create_man_plotly <- function(data, y_col, title, threshold, y_label=y_col) {
|
| 1462 |
+
blank <- plot_ly() %>% layout(title=title, plot_bgcolor="#FFF", paper_bgcolor="#FFF")
|
| 1463 |
if (is.null(data)||nrow(data)==0||"Message"%in%colnames(data)) return(blank)
|
| 1464 |
pd <- data[!is.na(data[[y_col]])&!is.na(data$Chromosome),]
|
| 1465 |
if (nrow(pd)==0) return(blank)
|
|
|
|
| 1478 |
p <- plot_ly()
|
| 1479 |
for (ch in chroms)
|
| 1480 |
p <- p %>% add_trace(data=pd[pd$Chromosome==ch,], x=~cum_pos,
|
| 1481 |
+
y=as.formula(paste0("~",y_col)), type="scatter", mode="markers",
|
| 1482 |
+
name=paste("Chr",ch),
|
| 1483 |
marker=list(size=5,color=pal[ch],opacity=.75), showlegend=FALSE,
|
| 1484 |
text=~paste0("Marker: ",Marker,"<br>Chr: ",Chromosome,"<br>",y_label,": ",round(get(y_col),3)),
|
| 1485 |
hoverinfo="text")
|
| 1486 |
if (!is.null(threshold))
|
| 1487 |
p <- p %>% add_segments(x=min(pd$cum_pos,na.rm=TRUE),xend=max(pd$cum_pos,na.rm=TRUE),
|
| 1488 |
+
y=threshold,yend=threshold,
|
| 1489 |
+
line=list(color="#DC2626",dash="dash",width=1.5), showlegend=FALSE)
|
| 1490 |
p %>% layout(title=title,
|
| 1491 |
+
xaxis=list(title="Chromosome", tickvals=as.list(chr_mids[chroms]),
|
| 1492 |
ticktext=as.list(paste0("Chr",chroms)), tickangle=45, gridcolor="#F1F5F9"),
|
| 1493 |
+
yaxis=list(title=y_label, gridcolor="#F1F5F9"),
|
| 1494 |
+
plot_bgcolor="#FFF", paper_bgcolor="#FFF")
|
| 1495 |
}
|
| 1496 |
|
| 1497 |
output$fst_plot <- renderPlotly({ req(rv$sel_metrics); create_man_plotly(rv$sel_metrics,"Fst","Fst",input$fst_thr,"Fst") })
|
|
|
|
| 1503 |
formatRound(c("Fst","Pi_Dom","Pi_Wild","Tajima_D_Dom"),3)
|
| 1504 |
})
|
| 1505 |
|
| 1506 |
+
# ββ DOWNLOADS βββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1507 |
output$dl_manhattan <- downloadHandler(
|
| 1508 |
filename=function() paste0("manhattan_v6_",Sys.Date(),".png"),
|
| 1509 |
content=function(file) {
|
| 1510 |
req(rv$scan_all)
|
| 1511 |
if ("Message"%in%colnames(rv$scan_all)) return()
|
| 1512 |
+
pd <- rv$scan_all[!is.na(rv$scan_all$LOD)&!is.na(rv$scan_all$Position),]
|
| 1513 |
pd$Chromosome <- as.character(pd$Chromosome)
|
| 1514 |
chroms <- sort(unique(pd$Chromosome),method="radix")
|
| 1515 |
offsets <- numeric(length(chroms)); names(offsets) <- chroms
|
| 1516 |
for (i in seq_along(chroms)) {
|
| 1517 |
if(i==1){offsets[chroms[1]]<-0;next}
|
| 1518 |
+
offsets[chroms[i]] <- offsets[chroms[i-1]] +
|
| 1519 |
+
max(pd$Position[pd$Chromosome==chroms[i-1]],na.rm=TRUE)*1.05
|
| 1520 |
}
|
| 1521 |
pd$cum_pos <- pd$Position + offsets[pd$Chromosome]
|
| 1522 |
+
pd$sig <- pd$LOD >= lod_thr()
|
| 1523 |
chr_colors <- rep(c("#2563EB","#64748B"),ceiling(length(chroms)/2))[seq_along(chroms)]
|
| 1524 |
names(chr_colors) <- chroms
|
| 1525 |
chr_mids <- tapply(pd$cum_pos, pd$Chromosome, median, na.rm=TRUE)
|
| 1526 |
p <- ggplot(pd,aes(x=cum_pos,y=LOD)) +
|
| 1527 |
geom_point(aes(color=Chromosome),size=1.2,alpha=.7,show.legend=FALSE) +
|
| 1528 |
geom_point(data=pd[pd$sig,],color="#DC2626",size=3,shape=18) +
|
| 1529 |
+
geom_hline(yintercept=lod_thr(),linetype="dashed",color="#DC2626",linewidth=.6) +
|
| 1530 |
scale_color_manual(values=chr_colors) +
|
| 1531 |
scale_x_continuous(breaks=chr_mids[chroms],labels=paste0("Chr",chroms)) +
|
| 1532 |
labs(title=paste(input$mapping_method,"Manhattan Plot"),
|
| 1533 |
+
subtitle=paste0("LOD >= ",lod_thr()," | ",sum(pd$sig,na.rm=TRUE)," sig. QTLs"),
|
| 1534 |
x="Chromosome",y="LOD Score") +
|
| 1535 |
theme_bw(base_size=12) +
|
| 1536 |
+
theme(panel.background=element_rect(fill="white"),
|
| 1537 |
+
plot.background=element_rect(fill="white"),
|
| 1538 |
+
panel.grid.minor=element_blank(),
|
| 1539 |
+
panel.grid.major.x=element_blank(),
|
| 1540 |
+
axis.text.x=element_text(angle=45,hjust=1),
|
| 1541 |
+
plot.title=element_text(face="bold"))
|
| 1542 |
if (sum(pd$sig,na.rm=TRUE)>0 && sum(pd$sig,na.rm=TRUE)<=30)
|
| 1543 |
+
p <- p + ggrepel::geom_label_repel(data=pd[pd$sig,],aes(label=Marker),
|
| 1544 |
+
size=2.5,max.overlaps=15,fill="white",color="#DC2626",segment.color="#DC2626")
|
| 1545 |
ggsave(file,plot=p,width=14,height=6,dpi=200,bg="white")
|
| 1546 |
}
|
| 1547 |
)
|
|
|
|
| 1554 |
mth <- isolate(input$mapping_method)
|
| 1555 |
if (!is.null(rv$scan_all) && !"Message"%in%colnames(rv$scan_all))
|
| 1556 |
res_list[[mth]] <- rv$scan_all
|
|
|
|
| 1557 |
for (m in names(rv$compare_res)) {
|
| 1558 |
r <- rv$compare_res[[m]]
|
| 1559 |
if (!is.null(r) && !"Message"%in%colnames(r)) res_list[[m]] <- r
|
|
|
|
| 1561 |
if (length(res_list)==0) return()
|
| 1562 |
png(file, width=1800, height=900, res=150, bg="white")
|
| 1563 |
par(bg="white")
|
| 1564 |
+
make_chromosome_idiogram(res_list, rv$all_markers, lod_thr())
|
| 1565 |
dev.off()
|
| 1566 |
}
|
| 1567 |
)
|
|
|
|
| 1570 |
filename=function() paste0("qtl_results_v6_",Sys.Date(),".xlsx"),
|
| 1571 |
content=function(file) {
|
| 1572 |
sheets <- list()
|
| 1573 |
+
# Use same live filter as the table
|
| 1574 |
+
if (!is.null(rv$scan_all) && !"Message"%in%colnames(rv$scan_all)) {
|
| 1575 |
+
sig <- rv$scan_all[!is.na(rv$scan_all$LOD) & rv$scan_all$LOD >= lod_thr(),]
|
| 1576 |
+
if (nrow(sig)>0) {
|
| 1577 |
+
sig <- add_lod_support_interval(sig, rv$scan_all, isolate(input$lod_drop))
|
| 1578 |
+
sheets[["QTL_Significant"]] <- sig[order(-sig$LOD),]
|
| 1579 |
+
}
|
| 1580 |
+
sheets[["Full_Scan"]] <- rv$scan_all
|
| 1581 |
+
}
|
| 1582 |
if (!is.null(rv$perf)) sheets[["Performance"]] <- rv$perf
|
| 1583 |
for (m in names(rv$compare_res)) {
|
| 1584 |
r <- rv$compare_res[[m]]
|
| 1585 |
if (!is.null(r) && !"Message"%in%colnames(r))
|
| 1586 |
+
sheets[[paste0("Model_",m)]] <- r[r$LOD >= lod_thr() & !is.na(r$LOD),]
|
| 1587 |
}
|
| 1588 |
sheets[["Methods"]] <- data.frame(
|
| 1589 |
Method=names(MAPPING_MODELS),
|
| 1590 |
Description=sapply(MAPPING_MODELS,`[[`,"desc"))
|
| 1591 |
+
if (length(sheets)==0)
|
| 1592 |
+
sheets[["Empty"]] <- data.frame(msg="Run analysis first")
|
| 1593 |
writexl::write_xlsx(sheets, file)
|
| 1594 |
}
|
| 1595 |
)
|
|
|
|
| 1607 |
content=function(file) {
|
| 1608 |
if (!is.null(rv$sel_metrics) && !"Message"%in%colnames(rv$sel_metrics))
|
| 1609 |
writexl::write_xlsx(list(Selection=rv$sel_metrics), file)
|
| 1610 |
+
else
|
| 1611 |
+
writexl::write_xlsx(list(Empty=data.frame(msg="Run domestication first")), file)
|
| 1612 |
}
|
| 1613 |
)
|
| 1614 |
|
| 1615 |
+
# ββ CHAT ββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1616 |
add_msg <- function(role, content) {
|
| 1617 |
rv$chat_msgs <- c(rv$chat_msgs,
|
| 1618 |
list(list(role=role, content=content, time=format(Sys.time(),"%H:%M"))))
|
|
|
|
| 1620 |
}
|
| 1621 |
|
| 1622 |
rule_response <- function(q) {
|
| 1623 |
+
ql <- tolower(q)
|
| 1624 |
has_scan <- !is.null(rv$scan_all) && !"Message"%in%colnames(rv$scan_all)
|
|
|
|
| 1625 |
|
| 1626 |
+
if (grepl("top qtl|best qtl|significant",ql) && has_scan) {
|
| 1627 |
+
sig <- rv$scan_all[!is.na(rv$scan_all$LOD) & rv$scan_all$LOD >= lod_thr(),]
|
| 1628 |
+
sig <- sig[order(-sig$LOD),]
|
| 1629 |
+
top5 <- head(sig, 5)
|
| 1630 |
+
if (nrow(top5)==0) return(paste("No QTLs above LOD", lod_thr()))
|
| 1631 |
+
out <- "Top QTLs:\n\n"
|
| 1632 |
for (i in 1:nrow(top5)) {
|
| 1633 |
r <- top5[i,]
|
| 1634 |
+
out <- paste0(out, i, ". ", r$Marker, " (Chr ", r$Chromosome,
|
| 1635 |
+
" @ ", round(r$Position,1), " cM)\n",
|
| 1636 |
+
" LOD: ", round(r$LOD,2),
|
| 1637 |
+
" | PVE_marker: ", round(r$PVE_Marker_Percent,1),
|
| 1638 |
+
"% | Add: ", round(r$Additive_Effect,3), "\n\n")
|
| 1639 |
}
|
| 1640 |
return(out)
|
| 1641 |
}
|
| 1642 |
if (grepl("chromosom|chr debug|other chrom|missing chr",ql)) {
|
| 1643 |
if (has_scan) {
|
| 1644 |
+
chr_tbl <- table(rv$scan_all$Chromosome[rv$scan_all$LOD >= lod_thr() & !is.na(rv$scan_all$LOD)])
|
| 1645 |
+
return(paste0("QTLs per chromosome:\n\n",
|
| 1646 |
+
paste(paste0("Chr",names(chr_tbl),": ",chr_tbl," QTL(s)"),collapse="\n"),
|
| 1647 |
"\n\nTotal chromosomes scanned: ", length(unique(rv$scan_all$Chromosome))))
|
| 1648 |
}
|
| 1649 |
return("Run analysis first to see chromosome results.")
|
| 1650 |
}
|
| 1651 |
if (grepl("sim|cim|differ|method|model",ql))
|
| 1652 |
+
return("Mapping Models:\n\nSIM: Single-marker regression, no cofactors, simplest, most false positives\nCIM: Cofactor-controlled β reduces noise from linked QTLs\nMQM: Forward stepwise β builds multi-QTL model iteratively\nLASSO: L1 penalty β selects sparse set of causal markers\nRidge: L2 penalty β shrinks all marker effects simultaneously")
|
| 1653 |
if (grepl("pve|semi.partial|variance",ql))
|
| 1654 |
+
return("PVE in v6:\n\nPVE_marker = R2 of lm(Y ~ a_code + d_code) β unconditional\nPVE_CIM = (RSS_reduced - RSS_full) / RSS_reduced x 100 β semi-partial R2 after cofactors")
|
| 1655 |
+
paste0("QTL-Mapper v6 AI\n\nv6 Fixes: multi-chromosome scan | 5 mapping models | chromosome idiogram | reactive LOD threshold\n\nQuick links: Top QTLs | CIM vs SIM | Chr debug | PVE explained")
|
| 1656 |
}
|
| 1657 |
|
| 1658 |
process_chat <- function(user_text) {
|
|
|
|
| 1662 |
if (token_exists) {
|
| 1663 |
ctx <- ""
|
| 1664 |
if (!is.null(rv$scan_all) && !"Message"%in%colnames(rv$scan_all)) {
|
| 1665 |
+
sig <- rv$scan_all[rv$scan_all$LOD >= lod_thr() & !is.na(rv$scan_all$LOD),]
|
| 1666 |
+
ctx <- paste0("Analysis done: ", nrow(sig), " QTLs on ",
|
| 1667 |
+
length(unique(rv$scan_all$Chromosome)),
|
| 1668 |
+
" chromosomes. Method: ", input$mapping_method, ". ")
|
| 1669 |
}
|
| 1670 |
res <- query_ai(paste0(ctx, "User: ", user_text))
|
| 1671 |
if (res$success) { rv$is_typing <- FALSE; add_msg("assistant", res$text); return() }
|
|
|
|
| 1685 |
observe({
|
| 1686 |
if (length(rv$chat_msgs)==0)
|
| 1687 |
add_msg("assistant", paste0(
|
| 1688 |
+
"QTL-Mapper v6 (fixed)\n\n",
|
| 1689 |
+
"New in v6:\n",
|
| 1690 |
+
"- 5 mapping models: SIM, CIM, MQM, LASSO, Ridge\n",
|
| 1691 |
+
"- Multi-chromosome fixed β all chromosomes scan correctly\n",
|
| 1692 |
+
"- LOD slider now reactive β updates all plots/tables instantly\n",
|
| 1693 |
+
"- Compare tab uses the same validation proportion as main analysis\n\n",
|
| 1694 |
+
"Upload data -> choose method -> Run QTL Analysis\n",
|
| 1695 |
"Contact: ashmithamganesan@gmail.com, P.sinha@cgiar.org"
|
| 1696 |
))
|
| 1697 |
})
|
|
|
|
| 1705 |
})
|
| 1706 |
if (rv$is_typing)
|
| 1707 |
elems <- c(elems, list(div(class="cmsg assistant",
|
| 1708 |
+
div(class="typing",div(class="tdot"),div(class="tdot"),div(class="tdot")))))
|
| 1709 |
do.call(tagList, elems)
|
| 1710 |
})
|
| 1711 |
}
|