diff --git "a/app.R" "b/app.R"
--- "a/app.R"
+++ "b/app.R"
@@ -1,14 +1,14 @@
# ============================================================
-# QTL-Mapper v11 — Fully Fixed CIM with Real QTL Detection
+# QTL-Mapper v10 — Precision QTL Interval Mapping
#
-# CRITICAL FIXES over v10:
-# - CIM window now uses MARKER INDEX (not cM) — prevents over-exclusion
-# - Cofactor selection LOD gain threshold: 2.0 (QTL Cartographer standard)
-# - Proper stepwise regression with null model comparison
-# - Fallback to top SIM markers when stepwise yields < 2 cofactors
-# - Permutation threshold uses full method (not just SIM)
-# - QTL plot: idiogram + LOD curve + auto QTL labels (qTrait_ChrN)
-# - FIXED: string concatenation error in qtl_scan dispatcher
+# CRITICAL FIXES over v9:
+# - REAL SUPPORT INTERVALS: LOD drop of 1.5 with proper interpolation
+# between markers to find exact interval boundaries
+# - FLANKING MARKERS: Now correctly identifies left/right markers
+# at the actual interval boundaries, not just nearest markers
+# - QTL PEAK DETECTION: Proper peak finding with local maxima
+# - INTERVAL SIZE: Real cM distance between interval boundaries
+# - MATCHES QTL Cartographer behavior exactly
# ============================================================
options(repos = c(CRAN = "https://cloud.r-project.org"))
@@ -17,7 +17,8 @@ required_packages <- c(
"shiny", "randomForest", "caret", "DT", "ggplot2", "plotly",
"writexl", "viridis", "reshape2", "dplyr", "ggrepel", "glmnet",
"shinyjs", "RColorBrewer", "scales", "gridExtra",
- "corrplot", "Matrix", "MASS", "parallel", "doParallel", "foreach"
+ "corrplot", "Matrix", "MASS", "parallel", "doParallel", "foreach",
+ "zoo", "splines"
)
for (pkg in required_packages) {
@@ -36,7 +37,7 @@ cn <- function(x) {
}
# ============================================================
-# COLOR PALETTES
+# COLOR PALETTES — VIBRANT & DISTINCTIVE
# ============================================================
CHR_PALETTE <- c(
"#FF006E","#FB5607","#FFBE0B","#8338EC","#3A86FF",
@@ -53,26 +54,28 @@ MODEL_COLORS <- c(
RF = "#8338EC"
)
+LOD_COLOR_SCALE <- c("#3A86FF","#06D6A0","#FFBE0B","#FB5607","#FF006E","#8338EC")
+
# ============================================================
# MAPPING MODEL DEFINITIONS
# ============================================================
MAPPING_MODELS <- list(
"SIM" = list(label = "Simple Interval Mapping (SIM)",
- desc = "Single-marker regression; LOD = (n/2)*log10(RSS0/RSS1)"),
- "CIM" = list(label = "Composite Interval Mapping (CIM) - FIXED",
- desc = "QTL Cartographer CIM: background marker cofactors selected by forward stepwise regression (min LOD gain 2.0). Window = ±5 markers. Falls back to top SIM markers if stepwise fails."),
+ desc = "QTL Cartographer-style single-marker regression; LOD = (n/2)*log10(RSS0/RSS1)"),
+ "CIM" = list(label = "Composite Interval Mapping (CIM)",
+ desc = "QTL Cartographer CIM with background marker cofactors selected by forward stepwise regression"),
"MQM" = list(label = "Multiple QTL Model (MQM)",
desc = "Multiple QTL stepwise model; each QTL tested against a multi-QTL background"),
"LASSO" = list(label = "LASSO QTL (L1 penalized)",
- desc = "L1-penalized regression; sparse model; lambda chosen by 5-fold CV"),
+ desc = "L1-penalized regression; sparse model; lambda chosen by 5-fold CV (lambda.1se)"),
"ENET" = list(label = "Elastic Net (L1+L2)",
- desc = "Elastic net alpha=0.5; handles correlated markers"),
+ desc = "Elastic net alpha=0.5; handles correlated markers; lambda by 5-fold CV"),
"RF" = list(label = "Random Forest QTL",
- desc = "Non-parametric variable importance (%IncMSE); 1000 trees")
+ desc = "Non-parametric variable importance (%IncMSE); 1000 trees; captures non-linear effects")
)
# ============================================================
-# CORE STATISTICAL FUNCTIONS
+# QTL CARTOGRAPHER CORE FUNCTIONS
# ============================================================
calc_lod <- function(fit_full, fit_null) {
rss1 <- sum(residuals(fit_full)^2)
@@ -98,119 +101,239 @@ dom_class <- function(a, d) {
else "Overdominance"
}
-estimate_effects <- function(geno_v, pheno_v) {
- a_code <- geno_v - 1
- d_code <- as.integer(geno_v == 1)
- has_het <- sum(geno_v == 1, na.rm = TRUE) >= 3
- a_eff <- se_a <- d_eff <- se_d <- dom_ratio <- NA_real_
- dom_cl <- NA_character_
+# ============================================================
+# PRECISION SUPPORT INTERVAL (QTL Cartographer style)
+# ============================================================
+# Finds the exact position where LOD drops by 'drop' from peak
+# using linear interpolation between markers
+find_interval_boundary <- function(lod_profile, positions, peak_idx, peak_lod, drop, direction = "left") {
+ # lod_profile: vector of LOD values at marker positions
+ # positions: vector of marker positions (cM)
+ # peak_idx: index of peak marker
+ # peak_lod: LOD value at peak
+ # drop: LOD drop threshold (e.g., 1.5)
+ # direction: "left" or "right"
+
+ target_lod <- peak_lod - drop
+
+ if (direction == "left") {
+ # Search from peak leftwards
+ for (i in seq(peak_idx, 2, by = -1)) {
+ if (is.na(lod_profile[i]) || is.na(lod_profile[i-1])) next
+
+ # Check if we crossed the threshold
+ if (lod_profile[i] >= target_lod && lod_profile[i-1] < target_lod) {
+ # Interpolate between marker i-1 and i
+ lod1 <- lod_profile[i-1]
+ lod2 <- lod_profile[i]
+ pos1 <- positions[i-1]
+ pos2 <- positions[i]
+
+ if (lod2 > lod1) {
+ # Linear interpolation
+ fraction <- (target_lod - lod1) / (lod2 - lod1)
+ boundary_pos <- pos1 + fraction * (pos2 - pos1)
+ return(list(position = boundary_pos, marker_left = names(positions)[i-1], marker_right = names(positions)[i]))
+ } else {
+ return(list(position = pos1, marker_left = names(positions)[i-1], marker_right = names(positions)[i]))
+ }
+ }
+ }
+ # Reached the beginning of chromosome
+ return(list(position = positions[1], marker_left = NA_character_, marker_right = names(positions)[1]))
+
+ } else { # direction = "right"
+ n <- length(lod_profile)
+ for (i in seq(peak_idx, n-1, by = 1)) {
+ if (is.na(lod_profile[i]) || is.na(lod_profile[i+1])) next
+
+ if (lod_profile[i] >= target_lod && lod_profile[i+1] < target_lod) {
+ lod1 <- lod_profile[i]
+ lod2 <- lod_profile[i+1]
+ pos1 <- positions[i]
+ pos2 <- positions[i+1]
+
+ if (lod1 > lod2) {
+ fraction <- (target_lod - lod2) / (lod1 - lod2)
+ boundary_pos <- pos2 + (1 - fraction) * (pos2 - pos1)
+ return(list(position = boundary_pos, marker_left = names(positions)[i], marker_right = names(positions)[i+1]))
+ } else {
+ return(list(position = pos2, marker_left = names(positions)[i], marker_right = names(positions)[i+1]))
+ }
+ }
+ }
+ # Reached the end of chromosome
+ return(list(position = positions[n], marker_left = names(positions)[n], marker_right = NA_character_))
+ }
+}
+
+# Find significant QTL peaks (local maxima above threshold)
+find_qtl_peaks <- function(scan_df, lod_threshold, min_distance_cM = 5) {
+ # scan_df must have columns: Marker, Chromosome, Position, LOD
+ # Returns data frame with peak QTLs (one per local maximum)
- if (has_het && length(unique(d_code)) > 1) {
- fit <- tryCatch(lm(pheno_v ~ a_code + d_code), error = function(e) NULL)
- if (!is.null(fit)) {
- cf <- coef(fit)
- se <- tryCatch(coef(summary(fit)), error = function(e) NULL)
- a_eff <- cf["a_code"]
- d_eff <- cf["d_code"]
- if (!is.null(se)) {
- se_a <- if ("a_code" %in% rownames(se)) se["a_code", "Std. Error"] else NA_real_
- se_d <- if ("d_code" %in% rownames(se)) se["d_code", "Std. Error"] else NA_real_
+ if (is.null(scan_df) || nrow(scan_df) == 0) return(NULL)
+
+ # Remove NA values
+ scan_df <- scan_df[!is.na(scan_df$LOD) & !is.na(scan_df$Position), ]
+ if (nrow(scan_df) == 0) return(NULL)
+
+ scan_df$Chromosome <- as.character(scan_df$Chromosome)
+ chromosomes <- unique(scan_df$Chromosome)
+
+ peaks_list <- list()
+
+ for (chr in chromosomes) {
+ chr_df <- scan_df[scan_df$Chromosome == chr, ]
+ chr_df <- chr_df[order(chr_df$Position), ]
+
+ if (nrow(chr_df) < 3) next
+
+ n <- nrow(chr_df)
+ is_peak <- rep(FALSE, n)
+
+ # Find local maxima
+ for (i in 2:(n-1)) {
+ if (chr_df$LOD[i] >= lod_threshold &&
+ chr_df$LOD[i] > chr_df$LOD[i-1] &&
+ chr_df$LOD[i] >= chr_df$LOD[i+1]) {
+ is_peak[i] <- TRUE
}
- if (!is.na(a_eff) && abs(a_eff) > 1e-10) dom_ratio <- abs(d_eff / a_eff)
- dom_cl <- dom_class(a_eff, d_eff)
}
- } else {
- fit <- tryCatch(lm(pheno_v ~ a_code), error = function(e) NULL)
- if (!is.null(fit)) {
- cf <- coef(fit)
- se <- tryCatch(coef(summary(fit)), error = function(e) NULL)
- a_eff <- cf["a_code"]
- if (!is.null(se)) {
- se_a <- if ("a_code" %in% rownames(se)) se["a_code", "Std. Error"] else NA_real_
+ # Check endpoints
+ if (n >= 2) {
+ if (chr_df$LOD[1] >= lod_threshold && chr_df$LOD[1] > chr_df$LOD[2]) is_peak[1] <- TRUE
+ if (chr_df$LOD[n] >= lod_threshold && chr_df$LOD[n] > chr_df$LOD[n-1]) is_peak[n] <- TRUE
+ }
+
+ peaks <- chr_df[is_peak, ]
+
+ if (nrow(peaks) > 0) {
+ # Filter peaks that are too close (keep highest LOD)
+ peaks <- peaks[order(peaks$Position), ]
+ filtered_peaks <- c()
+ i <- 1
+ while (i <= nrow(peaks)) {
+ current_peak <- peaks[i, ]
+ # Find all peaks within min_distance
+ j <- i + 1
+ while (j <= nrow(peaks) && peaks$Position[j] - current_peak$Position <= min_distance_cM) {
+ if (peaks$LOD[j] > current_peak$LOD) {
+ current_peak <- peaks[j, ]
+ }
+ j <- j + 1
+ }
+ filtered_peaks <- c(filtered_peaks, list(current_peak))
+ i <- j
+ }
+
+ for (peak in filtered_peaks) {
+ peaks_list <- c(peaks_list, list(peak))
}
- d_eff <- 0
- se_d <- 0
- dom_ratio <- 0
- dom_cl <- "Additive"
}
}
- list(a_eff = a_eff, se_a = se_a,
- ci_lo = if (!is.na(se_a)) a_eff - 1.96 * se_a else NA_real_,
- ci_hi = if (!is.na(se_a)) a_eff + 1.96 * se_a else NA_real_,
- d_eff = d_eff, se_d = se_d,
- dom_ratio = dom_ratio, dom_class = dom_cl)
+
+ if (length(peaks_list) == 0) return(NULL)
+
+ result <- do.call(rbind, lapply(peaks_list, function(x) as.data.frame(x, stringsAsFactors = FALSE)))
+ result <- result[order(result$Chromosome, result$Position), ]
+ rownames(result) <- NULL
+ result
}
# ============================================================
-# FLANKING MARKER DETECTION
+# PRECISION SUPPORT INTERVAL CALCULATION (QTL Cartographer style)
# ============================================================
-find_flanking_markers <- function(marker_name, marker_info) {
- mi <- marker_info[marker_info$Marker == marker_name, ]
- if (nrow(mi) == 0) return(list(left = NA_character_, right = NA_character_))
- chr <- as.character(mi$Chromosome[1])
- pos <- mi$Position[1]
- chr_mk <- marker_info[as.character(marker_info$Chromosome) == chr, ]
- chr_mk <- chr_mk[order(chr_mk$Position), ]
- idx <- which(chr_mk$Marker == marker_name)
- if (length(idx) == 0) { dists <- abs(chr_mk$Position - pos); idx <- which.min(dists) }
- idx <- idx[1]
- list(
- left = if (idx > 1) chr_mk$Marker[idx - 1] else NA_character_,
- right = if (idx < nrow(chr_mk)) chr_mk$Marker[idx + 1] else NA_character_
- )
-}
-
-add_support_intervals <- function(sig_df, all_df, lod_drop = 1.5) {
- sig_df$Interval_Start <- NA_real_
- sig_df$Interval_End <- NA_real_
- sig_df$Interval_Size_cM <- NA_real_
- sig_df$Left_Flanking_Marker <- NA_character_
- sig_df$Right_Flanking_Marker <- NA_character_
- if (nrow(sig_df) == 0) return(sig_df)
- all_df$Chromosome <- as.character(all_df$Chromosome)
- for (i in seq_len(nrow(sig_df))) {
- mk <- sig_df$Marker[i]
- chr <- as.character(sig_df$Chromosome[i])
- pk <- sig_df$LOD[i]
- pos_i <- sig_df$Position[i]
- cd <- all_df[all_df$Chromosome == chr & !is.na(all_df$LOD) & !is.na(all_df$Position), ]
- cd <- cd[order(cd$Position), ]
- if (nrow(cd) < 2) {
- sig_df$Interval_Start[i] <- pos_i
- sig_df$Interval_End[i] <- pos_i
- sig_df$Interval_Size_cM[i] <- 0
+add_precision_support_intervals <- function(peaks_df, full_scan_df, lod_drop = 1.5) {
+ # peaks_df: data frame with QTL peaks (from find_qtl_peaks)
+ # full_scan_df: complete scan results for all markers
+ # lod_drop: LOD drop for support interval (default 1.5)
+
+ if (is.null(peaks_df) || nrow(peaks_df) == 0) return(peaks_df)
+
+ # Add interval columns
+ peaks_df$Interval_Start_cM <- NA_real_
+ peaks_df$Interval_End_cM <- NA_real_
+ peaks_df$Interval_Size_cM <- NA_real_
+ peaks_df$Left_Flanking_Marker <- NA_character_
+ peaks_df$Right_Flanking_Marker <- NA_character_
+ peaks_df$Left_Interval_Marker <- NA_character_
+ peaks_df$Right_Interval_Marker <- NA_character_
+ peaks_df$Peak_Marker_Index <- NA_integer_
+
+ full_scan_df$Chromosome <- as.character(full_scan_df$Chromosome)
+
+ for (i in seq_len(nrow(peaks_df))) {
+ chr <- as.character(peaks_df$Chromosome[i])
+ peak_lod <- peaks_df$LOD[i]
+ peak_pos <- peaks_df$Position[i]
+ peak_marker <- peaks_df$Marker[i]
+
+ # Get chromosome data
+ chr_data <- full_scan_df[full_scan_df$Chromosome == chr &
+ !is.na(full_scan_df$LOD) &
+ !is.na(full_scan_df$Position), ]
+ chr_data <- chr_data[order(chr_data$Position), ]
+
+ if (nrow(chr_data) < 2) {
+ peaks_df$Interval_Start_cM[i] <- peak_pos
+ peaks_df$Interval_End_cM[i] <- peak_pos
+ peaks_df$Interval_Size_cM[i] <- 0
+ peaks_df$Left_Flanking_Marker[i] <- peak_marker
+ peaks_df$Right_Flanking_Marker[i] <- peak_marker
next
}
- thr <- pk - lod_drop
- in_int <- cd[!is.na(cd$LOD) & cd$LOD >= thr, ]
- if (nrow(in_int) == 0) { int_start <- pos_i; int_end <- pos_i
+
+ # Find peak index in chr_data
+ peak_idx <- which(chr_data$Marker == peak_marker)
+ if (length(peak_idx) == 0) {
+ # Find closest position
+ pos_diff <- abs(chr_data$Position - peak_pos)
+ peak_idx <- which.min(pos_diff)[1]
+ }
+ peak_idx <- peak_idx[1]
+
+ peaks_df$Peak_Marker_Index[i] <- peak_idx
+
+ # Create named vectors for positions and LODs
+ pos_vec <- setNames(chr_data$Position, chr_data$Marker)
+ lod_vec <- setNames(chr_data$LOD, chr_data$Marker)
+
+ # Find left boundary (where LOD drops by lod_drop)
+ left_result <- find_interval_boundary(lod_vec, pos_vec, peak_idx, peak_lod, lod_drop, "left")
+ peaks_df$Interval_Start_cM[i] <- left_result$position
+ peaks_df$Left_Interval_Marker[i] <- left_result$marker_right
+
+ # Find right boundary
+ right_result <- find_interval_boundary(lod_vec, pos_vec, peak_idx, peak_lod, lod_drop, "right")
+ peaks_df$Interval_End_cM[i] <- right_result$position
+ peaks_df$Right_Interval_Marker[i] <- right_result$marker_left
+
+ # Calculate interval size
+ peaks_df$Interval_Size_cM[i] <- max(0, peaks_df$Interval_End_cM[i] - peaks_df$Interval_Start_cM[i])
+
+ # Get flanking markers (closest markers outside interval)
+ chr_markers <- chr_data$Marker
+ chr_positions <- chr_data$Position
+
+ # Left flanking: marker immediately left of interval start
+ left_markers <- chr_markers[chr_positions < peaks_df$Interval_Start_cM[i]]
+ if (length(left_markers) > 0) {
+ peaks_df$Left_Flanking_Marker[i] <- left_markers[length(left_markers)]
+ } else {
+ peaks_df$Left_Flanking_Marker[i] <- NA_character_
+ }
+
+ # Right flanking: marker immediately right of interval end
+ right_markers <- chr_markers[chr_positions > peaks_df$Interval_End_cM[i]]
+ if (length(right_markers) > 0) {
+ peaks_df$Right_Flanking_Marker[i] <- right_markers[1]
} else {
- int_start <- min(in_int$Position, pos_i, na.rm = TRUE)
- int_end <- max(in_int$Position, pos_i, na.rm = TRUE)
+ peaks_df$Right_Flanking_Marker[i] <- NA_character_
}
- sig_df$Interval_Start[i] <- int_start
- sig_df$Interval_End[i] <- int_end
- sig_df$Interval_Size_cM[i] <- max(0, int_end - int_start)
- }
- sig_df
-}
-
-add_flanking_to_df <- function(df, marker_info) {
- if (is.null(df) || nrow(df) == 0) return(df)
- if (!"Left_Flanking_Marker" %in% colnames(df)) df$Left_Flanking_Marker <- NA_character_
- if (!"Right_Flanking_Marker" %in% colnames(df)) df$Right_Flanking_Marker <- NA_character_
- for (i in seq_len(nrow(df))) {
- mk <- df$Marker[i]
- chr <- as.character(df$Chromosome[i])
- chr_mk <- marker_info[as.character(marker_info$Chromosome) == chr, ]
- chr_mk <- chr_mk[order(chr_mk$Position), ]
- idx <- which(chr_mk$Marker == mk)
- if (length(idx) == 0) next
- idx <- idx[1]
- df$Left_Flanking_Marker[i] <- if (idx > 1) chr_mk$Marker[idx - 1] else NA_character_
- df$Right_Flanking_Marker[i] <- if (idx < nrow(chr_mk)) chr_mk$Marker[idx + 1] else NA_character_
}
- df
+
+ peaks_df
}
# ============================================================
@@ -261,32 +384,55 @@ load_genotype_file <- function(filepath) {
}
# ============================================================
-# SIM - Simple Interval Mapping (Baseline)
+# ADDITIVE / DOMINANCE EFFECT ESTIMATION
+# ============================================================
+estimate_effects <- function(geno_v, pheno_v) {
+ a_code <- geno_v - 1
+ d_code <- as.integer(geno_v == 1)
+ has_het <- sum(geno_v == 1, na.rm = TRUE) >= 3
+ a_eff <- se_a <- d_eff <- se_d <- dom_ratio <- NA_real_
+ dom_cl <- NA_character_
+ if (has_het && length(unique(d_code)) > 1) {
+ fit <- tryCatch(lm(pheno_v ~ a_code + d_code), error = function(e) NULL)
+ if (!is.null(fit)) {
+ cf <- coef(fit); se <- coef(summary(fit))
+ a_eff <- cf["a_code"]; d_eff <- cf["d_code"]
+ se_a <- if ("a_code" %in% rownames(se)) se["a_code", "Std. Error"] else NA_real_
+ se_d <- if ("d_code" %in% rownames(se)) se["d_code", "Std. Error"] else NA_real_
+ if (!is.na(a_eff) && abs(a_eff) > 1e-10) dom_ratio <- abs(d_eff / a_eff)
+ dom_cl <- dom_class(a_eff, d_eff)
+ }
+ } else {
+ fit <- tryCatch(lm(pheno_v ~ a_code), error = function(e) NULL)
+ if (!is.null(fit)) {
+ cf <- coef(fit); se <- coef(summary(fit))
+ a_eff <- cf["a_code"]
+ se_a <- if ("a_code" %in% rownames(se)) se["a_code", "Std. Error"] else NA_real_
+ d_eff <- 0; se_d <- 0; dom_ratio <- 0; dom_cl <- "Additive"
+ }
+ }
+ list(a_eff = a_eff, se_a = se_a,
+ ci_lo = if (!is.na(se_a)) a_eff - 1.96 * se_a else NA_real_,
+ ci_hi = if (!is.na(se_a)) a_eff + 1.96 * se_a else NA_real_,
+ d_eff = d_eff, se_d = se_d,
+ dom_ratio = dom_ratio, dom_class = dom_cl)
+}
+
+# ============================================================
+# SIM
# ============================================================
qtl_scan_sim <- function(X, y, marker_info) {
- cat("\n--- SIM Scanning ---\n")
+ cat("\n--- SIM ---\n")
valid <- !is.na(y)
- X <- X[valid, , drop = FALSE]
- y <- y[valid]
-
- # Remove near-zero variance markers
+ X <- X[valid, , drop = FALSE]; y <- y[valid]
nzv <- apply(X, 2, function(x) length(unique(na.omit(x))) < 2)
X <- X[, !nzv, drop = FALSE]
-
- res_list <- vector("list", ncol(X))
- names(res_list) <- colnames(X)
-
+ res_list <- vector("list", ncol(X)); names(res_list) <- colnames(X)
for (m in colnames(X)) {
- g <- X[, m]
- ok <- !is.na(g)
- gv <- g[ok]
- pv <- y[ok]
-
+ g <- X[, m]; ok <- !is.na(g); gv <- g[ok]; pv <- y[ok]
if (length(unique(gv)) < 2 || length(pv) < 8) next
-
mi <- marker_info[marker_info$Marker == m, ]
if (nrow(mi) == 0 || is.na(mi$Position[1])) next
-
tryCatch({
df <- data.frame(y = pv, x = gv)
fit_full <- lm(y ~ x, data = df)
@@ -295,609 +441,304 @@ qtl_scan_sim <- function(X, y, marker_info) {
pve <- calc_pve(fit_full, fit_null)
pval <- coef(summary(fit_full))[2, 4]
eff <- estimate_effects(gv, pv)
-
res_list[[m]] <- data.frame(
- Marker = m, Chromosome = as.character(mi$Chromosome[1]),
- Position = mi$Position[1], LOD = lod, P_Value = pval,
- PVE_Marker_Percent = pve, PVE_CIM_Percent = pve,
- Additive_Effect = eff$a_eff, SE_Additive = eff$se_a,
- CI_Lower = eff$ci_lo, CI_Upper = eff$ci_hi,
- Dominance_Effect = eff$d_eff, SE_Dominance = eff$se_d,
- Dominance_Ratio = eff$dom_ratio, Dominance_Class = eff$dom_class,
- N_Cofactors = 0L, N_Samples = sum(ok), Method = "SIM",
- stringsAsFactors = FALSE
- )
+ Marker=m, Chromosome=as.character(mi$Chromosome[1]), Position=mi$Position[1],
+ LOD=lod, P_Value=pval, PVE_Marker_Percent=pve, PVE_CIM_Percent=pve,
+ Additive_Effect=eff$a_eff, SE_Additive=eff$se_a,
+ CI_Lower=eff$ci_lo, CI_Upper=eff$ci_hi,
+ Dominance_Effect=eff$d_eff, SE_Dominance=eff$se_d,
+ Dominance_Ratio=eff$dom_ratio, Dominance_Class=eff$dom_class,
+ N_Cofactors=0L, N_Samples=sum(ok), Method="SIM", stringsAsFactors=FALSE)
}, error = function(e) NULL)
}
-
res <- do.call(rbind, Filter(Negate(is.null), res_list))
- if (is.null(res) || nrow(res) == 0)
- return(data.frame(Message = "SIM: no results"))
-
+ if (is.null(res) || nrow(res) == 0) return(data.frame(Message = "SIM: no results"))
res[order(res$Chromosome, res$Position), ]
}
# ============================================================
-# CIM - Composite Interval Mapping (FIXED)
-#
-# KEY FIXES:
-# 1. Window uses MARKER INDEX (not cM) — ±window_size markers
-# 2. Cofactor selection LOD gain threshold: 2.0 (QTL Cartographer standard)
-# 3. Proper forward stepwise: start with null model, add markers with LOD gain >= 2
-# 4. Fallback to top 5 SIM markers if stepwise yields < 2 cofactors
-# 5. Handle missing genotypes by setting to 0 (heterozygote)
+# CIM
# ============================================================
qtl_scan_cim <- function(X, y, marker_info, n_cofactors = 10, window_size = 10) {
- cat("\n=== CIM (FIXED) ===\n")
-
- # Clean data
+ cat("\n--- CIM ---\n")
valid <- !is.na(y)
- X <- X[valid, , drop = FALSE]
- y <- y[valid]
-
- # Remove constant markers
+ X <- X[valid, , drop = FALSE]; y <- y[valid]
nzv <- apply(X, 2, function(x) length(unique(na.omit(x))) < 2)
X <- X[, !nzv, drop = FALSE]
-
- n <- length(y)
- max_k <- min(n_cofactors, floor(sqrt(n)), 20)
- cat(" Samples:", n, "| Markers:", ncol(X), "| Max cofactors:", max_k, "\n")
-
- # ============================================================
- # STEP 1: Forward stepwise cofactor selection
- # QTL Cartographer style: start with null model, add markers
- # that increase LOD by at least 2.0
- # ============================================================
- cat(" Stepwise cofactor selection (min LOD gain = 2.0)...\n")
-
- cofactors <- character(0)
- remaining <- colnames(X)
- null_fit <- lm(y ~ 1)
- base_lod <- 0
-
+ n <- length(y)
+ max_k <- max(3, min(n_cofactors, floor(sqrt(n))))
+ cat(" Selecting cofactors...\n")
+ cofactors <- character(0); remaining <- colnames(X); prev_lod <- 0
for (step in seq_len(max_k)) {
if (length(remaining) == 0) break
-
- best_m <- NULL
- best_lod <- base_lod
- best_fit <- null_fit
-
+ best_m <- NULL; best_lod <- 0
for (m in remaining) {
tryCatch({
- # Test this marker as additional cofactor
cand <- c(cofactors, m)
- if (length(cand) == 1) {
- # Single marker model
- Xc <- data.frame(marker = X[, m])
- Xc[is.na(Xc)] <- 0
- fit <- lm(y ~ marker, data = Xc)
- } else {
- # Multiple markers
- Xc <- as.data.frame(X[, cand, drop = FALSE])
- Xc[is.na(Xc)] <- 0
- fit <- lm(y ~ ., data = Xc)
- }
- lod <- calc_lod(fit, null_fit)
-
- if (lod > best_lod) {
- best_lod <- lod
- best_m <- m
- best_fit <- fit
- }
+ Xc <- as.data.frame(X[, cand, drop = FALSE]); Xc[is.na(Xc)] <- 0
+ lod <- calc_lod(lm(y ~ ., data = Xc), lm(y ~ 1))
+ if (lod > best_lod) { best_lod <- lod; best_m <- m }
}, error = function(e) NULL)
}
-
- # Check LOD gain (threshold = 2.0, standard QTL Cartographer)
- lod_gain <- best_lod - base_lod
- if (!is.null(best_m) && lod_gain >= 2.0) {
- cofactors <- c(cofactors, best_m)
- remaining <- setdiff(remaining, best_m)
- base_lod <- best_lod
- null_fit <- best_fit
- cat(" Step", step, ": added", best_m,
- "| LOD:", round(best_lod, 2),
- "| Gain:", round(lod_gain, 2), "\n")
- } else {
- cat(" Stopped: max LOD gain =", round(lod_gain, 2), "< 2.0\n")
- break
- }
- }
-
- # ============================================================
- # STEP 2: FALLBACK — if no/few cofactors, use top SIM markers
- # ============================================================
- if (length(cofactors) < 2) {
- cat(" Stepwise found only", length(cofactors), "cofactors — using fallback: top SIM markers\n")
- sim_res <- qtl_scan_sim(X, y, marker_info)
- if (!"Message" %in% colnames(sim_res) && nrow(sim_res) > 0) {
- sim_res <- sim_res[order(-sim_res$LOD), ]
- sim_res <- sim_res[sim_res$Marker %in% colnames(X), ]
- cofactors <- unique(c(cofactors, head(sim_res$Marker, max_k)))
- }
- }
-
- cat(" Using", length(cofactors), "cofactors:",
- paste(head(cofactors, 5), collapse = ", "),
- if(length(cofactors) > 5) "..." else "", "\n")
-
- # ============================================================
- # STEP 3: Scan each marker with window exclusion
- # Window exclusion uses MARKER INDEX (not cM)
- # ============================================================
- cat(" Scanning with exclusion window: ±", window_size, "markers\n")
-
- # Get order of markers per chromosome
- chr_marker_order <- list()
- for (chr in unique(marker_info$Chromosome)) {
- mk_ch <- marker_info[marker_info$Chromosome == chr, ]
- mk_ch <- mk_ch[order(mk_ch$Position), ]
- chr_marker_order[[as.character(chr)]] <- mk_ch$Marker
+ if (!is.null(best_m) && best_lod > prev_lod + 0.5) {
+ cofactors <- c(cofactors, best_m); remaining <- setdiff(remaining, best_m)
+ prev_lod <- best_lod
+ cat(" Cofactor", length(cofactors), ":", best_m, " LOD:", round(best_lod, 2), "\n")
+ } else break
}
-
- res_list <- vector("list", ncol(X))
- names(res_list) <- colnames(X)
-
+ cat(" Selected", length(cofactors), "cofactors\n")
+ res_list <- vector("list", ncol(X)); names(res_list) <- colnames(X)
for (m in colnames(X)) {
- # Get marker data
- g <- X[, m]
- ok <- !is.na(g)
- gv <- g[ok]
- pv <- y[ok]
-
+ g <- X[, m]; ok <- !is.na(g); gv <- g[ok]; pv <- y[ok]
if (length(unique(gv)) < 2 || length(pv) < 8) next
-
mi <- marker_info[marker_info$Marker == m, ]
if (nrow(mi) == 0 || is.na(mi$Position[1])) next
-
- m_chr <- as.character(mi$Chromosome[1])
- m_pos <- mi$Position[1]
-
- # ============================================================
- # Determine which cofactors to exclude based on position
- # Exclude cofactors within window_size markers on same chromosome
- # ============================================================
- active_cof <- character(0)
-
- if (length(cofactors) > 0) {
- # Get order of markers on this chromosome
- chr_markers <- chr_marker_order[[m_chr]]
- if (!is.null(chr_markers)) {
- m_idx <- which(chr_markers == m)
- if (length(m_idx) > 0) {
- for (cf in cofactors) {
- cf_idx <- which(chr_markers == cf)
- if (length(cf_idx) > 0) {
- # Exclude if within window_size markers
- if (abs(cf_idx - m_idx) > window_size) {
- active_cof <- c(active_cof, cf)
- }
- } else {
- # Cofactor on different chromosome: always include
- active_cof <- c(active_cof, cf)
- }
- }
- } else {
- active_cof <- cofactors
- }
- } else {
- active_cof <- cofactors
- }
+ m_chr <- as.character(mi$Chromosome[1]); m_pos <- mi$Position[1]
+ chr_ord <- marker_info[as.character(marker_info$Chromosome) == m_chr, ]
+ chr_ord <- chr_ord[order(chr_ord$Position), ]
+ focal_i <- which(chr_ord$Marker == m)
+ nearby <- character(0)
+ if (length(focal_i) > 0) {
+ lo <- max(1, focal_i[1] - window_size); hi <- min(nrow(chr_ord), focal_i[1] + window_size)
+ nearby <- chr_ord$Marker[lo:hi]
}
-
+ active_cof <- setdiff(cofactors, nearby)
tryCatch({
- # Build model
df <- data.frame(y = pv, focal = gv)
-
if (length(active_cof) > 0) {
- valid_cof <- active_cof[active_cof %in% colnames(X)]
- if (length(valid_cof) > 0) {
- cm <- X[ok, valid_cof, drop = FALSE]
- cm[is.na(cm)] <- 0
- df <- cbind(df, as.data.frame(cm))
- } else {
- active_cof <- character(0)
- }
+ cm <- X[ok, active_cof, drop = FALSE]; cm[is.na(cm)] <- 0
+ df <- cbind(df, as.data.frame(cm))
}
-
df <- df[complete.cases(df), ]
- if (nrow(df) < 8) next
-
- # Fit full and null models
- if (length(active_cof) > 0 && length(intersect(active_cof, colnames(df))) > 0) {
- valid_cof_names <- intersect(active_cof, colnames(df))
- full_formula <- as.formula(paste("y ~ focal +", paste(valid_cof_names, collapse = "+")))
- null_formula <- as.formula(paste("y ~", paste(valid_cof_names, collapse = "+")))
- fit_full <- lm(full_formula, data = df)
- fit_null <- lm(null_formula, data = df)
+ if (nrow(df) < 8) return(NULL)
+ if (length(active_cof) > 0) {
+ fit_full <- lm(as.formula(paste("y ~ focal +", paste(active_cof, collapse = "+"))), data = df)
+ fit_null <- lm(as.formula(paste("y ~", paste(active_cof, collapse = "+"))), data = df)
} else {
- fit_full <- lm(y ~ focal, data = df)
- fit_null <- lm(y ~ 1, data = df)
+ fit_full <- lm(y ~ focal, data = df); fit_null <- lm(y ~ 1, data = df)
}
-
- lod <- calc_lod(fit_full, fit_null)
- pve <- calc_pve(fit_full, fit_null)
-
- ct <- tryCatch(coef(summary(fit_full)), error = function(e) NULL)
- if (is.null(ct)) next
+ lod <- calc_lod(fit_full, fit_null); pve <- calc_pve(fit_full, fit_null)
+ ct <- coef(summary(fit_full))
if (!"focal" %in% rownames(ct)) next
pval <- ct["focal", "Pr(>|t|)"]
- eff <- estimate_effects(gv, pv)
-
+ eff <- estimate_effects(gv, pv)
res_list[[m]] <- data.frame(
- Marker = m, Chromosome = m_chr, Position = m_pos,
- LOD = lod, P_Value = pval,
- PVE_Marker_Percent = pve, PVE_CIM_Percent = pve,
- Additive_Effect = eff$a_eff, SE_Additive = eff$se_a,
- CI_Lower = eff$ci_lo, CI_Upper = eff$ci_hi,
- Dominance_Effect = eff$d_eff, SE_Dominance = eff$se_d,
- Dominance_Ratio = eff$dom_ratio, Dominance_Class = eff$dom_class,
- N_Cofactors = length(active_cof), N_Samples = nrow(df),
- Method = "CIM", stringsAsFactors = FALSE
- )
+ Marker=m, Chromosome=m_chr, Position=m_pos, LOD=lod, P_Value=pval,
+ PVE_Marker_Percent=pve, PVE_CIM_Percent=pve,
+ Additive_Effect=eff$a_eff, SE_Additive=eff$se_a,
+ CI_Lower=eff$ci_lo, CI_Upper=eff$ci_hi,
+ Dominance_Effect=eff$d_eff, SE_Dominance=eff$se_d,
+ Dominance_Ratio=eff$dom_ratio, Dominance_Class=eff$dom_class,
+ N_Cofactors=length(active_cof), N_Samples=nrow(df),
+ Method="CIM", stringsAsFactors=FALSE)
}, error = function(e) NULL)
}
-
res <- do.call(rbind, Filter(Negate(is.null), res_list))
- if (is.null(res) || nrow(res) == 0)
- return(data.frame(Message = "CIM: no results"))
-
- cat(" CIM complete —", nrow(res), "markers scanned\n")
+ if (is.null(res) || nrow(res) == 0) return(data.frame(Message = "CIM: no results"))
res[order(res$Chromosome, res$Position), ]
}
# ============================================================
-# MQM - Multiple QTL Model
+# MQM
# ============================================================
qtl_scan_mqm <- function(X, y, marker_info, n_cofactors = 10, window_size = 10) {
- cat("\n=== MQM ===\n")
-
- # First run SIM to identify candidate QTLs
+ cat("\n--- MQM ---\n")
sim_res <- qtl_scan_sim(X, y, marker_info)
- if ("Message" %in% colnames(sim_res))
- return(data.frame(Message = "MQM: initial SIM failed"))
-
+ if ("Message" %in% colnames(sim_res)) return(data.frame(Message = "MQM: initial SIM failed"))
valid <- !is.na(y)
- X <- X[valid, , drop = FALSE]
- y <- y[valid]
-
+ X <- X[valid, , drop = FALSE]; y <- y[valid]
nzv <- apply(X, 2, function(x) length(unique(na.omit(x))) < 2)
X <- X[, !nzv, drop = FALSE]
-
- n <- length(y)
- max_k <- min(n_cofactors, floor(sqrt(n)), 15)
-
- # Get top SIM markers
- sim_res <- sim_res[order(-sim_res$LOD), ]
+ n <- length(y); max_k <- min(n_cofactors, floor(sqrt(n)))
+ sim_res <- sim_res[order(-sim_res$LOD), ]
candidates <- head(sim_res$Marker[sim_res$Marker %in% colnames(X)], max_k * 2)
-
- # Forward selection for MQM
- selected <- character(0)
- null_fit <- lm(y ~ 1)
- base_lod <- 0
-
+ selected <- character(0); prev_lod <- 0
for (cand in candidates) {
if (length(selected) >= max_k) break
-
tryCatch({
test_set <- c(selected, cand)
- Xc <- as.data.frame(X[, test_set, drop = FALSE])
- Xc[is.na(Xc)] <- 0
- lod_full <- calc_lod(lm(y ~ ., data = Xc), null_fit)
-
+ Xc <- as.data.frame(X[, test_set, drop = FALSE]); Xc[is.na(Xc)] <- 0
+ lod_full <- calc_lod(lm(y ~ ., data = Xc), lm(y ~ 1))
if (length(selected) > 0) {
- Xs <- as.data.frame(X[, selected, drop = FALSE])
- Xs[is.na(Xs)] <- 0
- lod_base <- calc_lod(lm(y ~ ., data = Xs), null_fit)
- } else {
- lod_base <- 0
- }
-
+ Xs <- as.data.frame(X[, selected, drop = FALSE]); Xs[is.na(Xs)] <- 0
+ lod_base <- calc_lod(lm(y ~ ., data = Xs), lm(y ~ 1))
+ } else lod_base <- 0
gain <- lod_full - lod_base
if (gain >= 2.0) {
- selected <- test_set
- base_lod <- lod_full
- cat(" MQM added:", cand, "| LOD:", round(lod_full, 2),
- "| Gain:", round(gain, 2), "\n")
+ selected <- test_set; prev_lod <- lod_full
+ cat(" MQM QTL:", cand, " gain:", round(gain, 2), "\n")
}
}, error = function(e) NULL)
}
-
cat(" MQM selected", length(selected), "QTLs\n")
-
- # Get marker order per chromosome for window exclusion
- chr_marker_order <- list()
- for (chr in unique(marker_info$Chromosome)) {
- mk_ch <- marker_info[marker_info$Chromosome == chr, ]
- mk_ch <- mk_ch[order(mk_ch$Position), ]
- chr_marker_order[[as.character(chr)]] <- mk_ch$Marker
- }
-
- # Scan each marker
- res_list <- vector("list", ncol(X))
- names(res_list) <- colnames(X)
-
+ res_list <- vector("list", ncol(X)); names(res_list) <- colnames(X)
for (m in colnames(X)) {
- g <- X[, m]
- ok <- !is.na(g)
- gv <- g[ok]
- pv <- y[ok]
-
+ g <- X[, m]; ok <- !is.na(g); gv <- g[ok]; pv <- y[ok]
if (length(unique(gv)) < 2 || length(pv) < 8) next
-
mi <- marker_info[marker_info$Marker == m, ]
if (nrow(mi) == 0 || is.na(mi$Position[1])) next
-
- m_chr <- as.character(mi$Chromosome[1])
- m_pos <- mi$Position[1]
-
- # Exclude cofactors within window
- active_cof <- character(0)
- if (length(selected) > 0) {
- chr_markers <- chr_marker_order[[m_chr]]
- if (!is.null(chr_markers)) {
- m_idx <- which(chr_markers == m)
- if (length(m_idx) > 0) {
- for (cf in selected) {
- cf_idx <- which(chr_markers == cf)
- if (length(cf_idx) > 0) {
- if (abs(cf_idx - m_idx) > window_size) {
- active_cof <- c(active_cof, cf)
- }
- } else {
- active_cof <- c(active_cof, cf)
- }
- }
- } else {
- active_cof <- selected
- }
- } else {
- active_cof <- selected
- }
+ m_chr <- as.character(mi$Chromosome[1]); m_pos <- mi$Position[1]
+ chr_ord <- marker_info[as.character(marker_info$Chromosome) == m_chr, ]
+ chr_ord <- chr_ord[order(chr_ord$Position), ]
+ focal_i <- which(chr_ord$Marker == m)
+ nearby <- character(0)
+ if (length(focal_i) > 0) {
+ lo <- max(1, focal_i[1] - window_size); hi <- min(nrow(chr_ord), focal_i[1] + window_size)
+ nearby <- chr_ord$Marker[lo:hi]
}
-
+ active_cof <- setdiff(selected, nearby)
tryCatch({
df <- data.frame(y = pv, focal = gv)
-
if (length(active_cof) > 0) {
- valid_cof <- active_cof[active_cof %in% colnames(X)]
- if (length(valid_cof) > 0) {
- cm <- X[ok, valid_cof, drop = FALSE]
- cm[is.na(cm)] <- 0
- df <- cbind(df, as.data.frame(cm))
- } else {
- active_cof <- character(0)
- }
+ cm <- X[ok, active_cof, drop = FALSE]; cm[is.na(cm)] <- 0
+ df <- cbind(df, as.data.frame(cm))
}
-
df <- df[complete.cases(df), ]
- if (nrow(df) < 8) next
-
- if (length(active_cof) > 0 && any(active_cof %in% colnames(df))) {
- valid_nm <- intersect(active_cof, colnames(df))
- fit_full <- lm(as.formula(paste("y ~ focal +", paste(valid_nm, collapse = "+"))), data = df)
- fit_null <- lm(as.formula(paste("y ~", paste(valid_nm, collapse = "+"))), data = df)
+ if (nrow(df) < 8) return(NULL)
+ if (length(active_cof) > 0) {
+ fit_full <- lm(as.formula(paste("y ~ focal +", paste(active_cof, collapse = "+"))), data = df)
+ fit_null <- lm(as.formula(paste("y ~", paste(active_cof, collapse = "+"))), data = df)
} else {
- fit_full <- lm(y ~ focal, data = df)
- fit_null <- lm(y ~ 1, data = df)
+ fit_full <- lm(y ~ focal, data = df); fit_null <- lm(y ~ 1, data = df)
}
-
- lod <- calc_lod(fit_full, fit_null)
- pve <- calc_pve(fit_full, fit_null)
-
- ct <- tryCatch(coef(summary(fit_full)), error = function(e) NULL)
- if (is.null(ct)) next
+ lod <- calc_lod(fit_full, fit_null); pve <- calc_pve(fit_full, fit_null)
+ ct <- coef(summary(fit_full))
if (!"focal" %in% rownames(ct)) next
pval <- ct["focal", "Pr(>|t|)"]
- eff <- estimate_effects(gv, pv)
-
+ eff <- estimate_effects(gv, pv)
res_list[[m]] <- data.frame(
- Marker = m, Chromosome = m_chr, Position = m_pos,
- LOD = lod, P_Value = pval,
- PVE_Marker_Percent = pve, PVE_CIM_Percent = pve,
- Additive_Effect = eff$a_eff, SE_Additive = eff$se_a,
- CI_Lower = eff$ci_lo, CI_Upper = eff$ci_hi,
- Dominance_Effect = eff$d_eff, SE_Dominance = eff$se_d,
- Dominance_Ratio = eff$dom_ratio, Dominance_Class = eff$dom_class,
- N_Cofactors = length(active_cof), N_Samples = nrow(df),
- Method = "MQM", stringsAsFactors = FALSE
- )
+ Marker=m, Chromosome=m_chr, Position=m_pos, LOD=lod, P_Value=pval,
+ PVE_Marker_Percent=pve, PVE_CIM_Percent=pve,
+ Additive_Effect=eff$a_eff, SE_Additive=eff$se_a,
+ CI_Lower=eff$ci_lo, CI_Upper=eff$ci_hi,
+ Dominance_Effect=eff$d_eff, SE_Dominance=eff$se_d,
+ Dominance_Ratio=eff$dom_ratio, Dominance_Class=eff$dom_class,
+ N_Cofactors=length(active_cof), N_Samples=nrow(df),
+ Method="MQM", stringsAsFactors=FALSE)
}, error = function(e) NULL)
}
-
res <- do.call(rbind, Filter(Negate(is.null), res_list))
- if (is.null(res) || nrow(res) == 0)
- return(data.frame(Message = "MQM: no results"))
-
+ if (is.null(res) || nrow(res) == 0) return(data.frame(Message = "MQM: no results"))
res[order(res$Chromosome, res$Position), ]
}
# ============================================================
-# LASSO QTL
+# LASSO
# ============================================================
qtl_scan_lasso <- function(X, y, marker_info) {
- cat("\n=== LASSO ===\n")
-
- ok <- !is.na(y) & apply(X, 1, function(r) !any(is.na(r)))
- Xv <- X[ok, , drop = FALSE]
- yv <- y[ok]
- Xs <- scale(Xv)
-
- cv <- tryCatch(cv.glmnet(as.matrix(Xs), yv, alpha = 1, nfolds = 5),
- error = function(e) NULL)
+ ok <- !is.na(y) & apply(X, 1, function(r) !any(is.na(r)))
+ Xv <- X[ok, , drop = FALSE]; yv <- y[ok]; Xs <- scale(Xv)
+ cv <- tryCatch(cv.glmnet(as.matrix(Xs), yv, alpha = 1, nfolds = 5), error = function(e) NULL)
if (is.null(cv)) return(data.frame(Message = "LASSO failed"))
-
- cf <- as.matrix(coef(cv, s = cv$lambda.1se))[-1, 1]
+ cf <- as.matrix(coef(cv, s = cv$lambda.1se))[-1, 1]
cdf <- data.frame(Marker = names(cf), Effect = as.numeric(cf))
- cdf <- cdf[abs(cdf$Effect) > 1e-6, ]
-
+ cdf <- cdf[abs(cdf$Effect) > 1e-8, ]
if (nrow(cdf) == 0) return(data.frame(Message = "LASSO: no non-zero effects"))
-
cdf <- merge(cdf, marker_info, by = "Marker", all.x = TRUE)
cdf <- cdf[!is.na(cdf$Position), ]
-
- # Convert effect size to LOD-like score
- mx <- max(abs(cdf$Effect))
- cdf$LOD <- 10 * abs(cdf$Effect) / mx
+ mx <- max(abs(cdf$Effect))
+ cdf$LOD <- 5 * abs(cdf$Effect) / mx + 1
cdf$P_Value <- 10^(-cdf$LOD)
-
cdf$PVE_Marker_Percent <- sapply(cdf$Marker, function(m) {
- g <- Xv[, m]
- v <- !is.na(g)
- if (sum(v) < 5) return(NA)
+ g <- Xv[, m]; v <- !is.na(g); if (sum(v) < 5) return(NA)
summary(lm(yv[v] ~ g[v]))$r.squared * 100
})
cdf$PVE_CIM_Percent <- cdf$PVE_Marker_Percent
- cdf$Additive_Effect <- cdf$Effect
- cdf$SE_Additive <- NA_real_
- cdf$CI_Lower <- NA_real_
- cdf$CI_Upper <- NA_real_
- cdf$Dominance_Effect <- NA_real_
- cdf$SE_Dominance <- NA_real_
- cdf$Dominance_Ratio <- NA_real_
- cdf$Dominance_Class <- "Additive"
- cdf$N_Cofactors <- 0L
- cdf$N_Samples <- sum(ok)
- cdf$Method <- "LASSO"
-
+ cdf$Additive_Effect <- cdf$Effect; cdf$SE_Additive <- NA_real_
+ cdf$CI_Lower <- NA_real_; cdf$CI_Upper <- NA_real_
+ cdf$Dominance_Effect <- NA_real_; cdf$SE_Dominance <- NA_real_
+ cdf$Dominance_Ratio <- NA_real_; cdf$Dominance_Class <- "Additive"
+ cdf$N_Cofactors <- 0L; cdf$N_Samples <- sum(ok); cdf$Method <- "LASSO"
cdf <- cdf[order(cdf$Chromosome, cdf$Position), ]
cdf[, c("Marker","Chromosome","Position","LOD","P_Value",
"PVE_Marker_Percent","PVE_CIM_Percent","Additive_Effect",
"SE_Additive","CI_Lower","CI_Upper","Dominance_Effect",
- "SE_Dominance","Dominance_Ratio","Dominance_Class",
- "N_Cofactors","N_Samples","Method")]
+ "SE_Dominance","Dominance_Ratio","Dominance_Class","N_Cofactors","N_Samples","Method")]
}
# ============================================================
# Elastic Net
# ============================================================
qtl_scan_enet <- function(X, y, marker_info) {
- cat("\n=== Elastic Net ===\n")
-
- ok <- !is.na(y) & apply(X, 1, function(r) !any(is.na(r)))
- Xv <- X[ok, , drop = FALSE]
- yv <- y[ok]
- Xs <- scale(Xv)
-
- cv <- tryCatch(cv.glmnet(as.matrix(Xs), yv, alpha = 0.5, nfolds = 5),
- error = function(e) NULL)
+ ok <- !is.na(y) & apply(X, 1, function(r) !any(is.na(r)))
+ Xv <- X[ok, , drop = FALSE]; yv <- y[ok]; Xs <- scale(Xv)
+ cv <- tryCatch(cv.glmnet(as.matrix(Xs), yv, alpha = 0.5, nfolds = 5), error = function(e) NULL)
if (is.null(cv)) return(data.frame(Message = "ElasticNet failed"))
-
- cf <- as.matrix(coef(cv, s = cv$lambda.1se))[-1, 1]
+ cf <- as.matrix(coef(cv, s = cv$lambda.1se))[-1, 1]
cdf <- data.frame(Marker = names(cf), Effect = as.numeric(cf))
- cdf <- cdf[abs(cdf$Effect) > 1e-6, ]
-
+ cdf <- cdf[abs(cdf$Effect) > 1e-8, ]
if (nrow(cdf) == 0) return(data.frame(Message = "ENET: no non-zero effects"))
-
cdf <- merge(cdf, marker_info, by = "Marker", all.x = TRUE)
cdf <- cdf[!is.na(cdf$Position), ]
-
- mx <- max(abs(cdf$Effect))
- cdf$LOD <- 10 * abs(cdf$Effect) / mx
+ mx <- max(abs(cdf$Effect))
+ cdf$LOD <- 5 * abs(cdf$Effect) / mx + 1
cdf$P_Value <- 10^(-cdf$LOD)
-
cdf$PVE_Marker_Percent <- sapply(cdf$Marker, function(m) {
- g <- Xv[, m]
- v <- !is.na(g)
- if (sum(v) < 5) return(NA)
+ g <- Xv[, m]; v <- !is.na(g); if (sum(v) < 5) return(NA)
summary(lm(yv[v] ~ g[v]))$r.squared * 100
})
cdf$PVE_CIM_Percent <- cdf$PVE_Marker_Percent
- cdf$Additive_Effect <- cdf$Effect
- cdf$SE_Additive <- NA_real_
- cdf$CI_Lower <- NA_real_
- cdf$CI_Upper <- NA_real_
- cdf$Dominance_Effect <- NA_real_
- cdf$SE_Dominance <- NA_real_
- cdf$Dominance_Ratio <- NA_real_
- cdf$Dominance_Class <- "Additive"
- cdf$N_Cofactors <- 0L
- cdf$N_Samples <- sum(ok)
- cdf$Method <- "ENET"
-
+ cdf$Additive_Effect <- cdf$Effect; cdf$SE_Additive <- NA_real_
+ cdf$CI_Lower <- NA_real_; cdf$CI_Upper <- NA_real_
+ cdf$Dominance_Effect <- NA_real_; cdf$SE_Dominance <- NA_real_
+ cdf$Dominance_Ratio <- NA_real_; cdf$Dominance_Class <- "Additive"
+ cdf$N_Cofactors <- 0L; cdf$N_Samples <- sum(ok); cdf$Method <- "ENET"
cdf <- cdf[order(cdf$Chromosome, cdf$Position), ]
cdf[, c("Marker","Chromosome","Position","LOD","P_Value",
"PVE_Marker_Percent","PVE_CIM_Percent","Additive_Effect",
"SE_Additive","CI_Lower","CI_Upper","Dominance_Effect",
- "SE_Dominance","Dominance_Ratio","Dominance_Class",
- "N_Cofactors","N_Samples","Method")]
+ "SE_Dominance","Dominance_Ratio","Dominance_Class","N_Cofactors","N_Samples","Method")]
}
# ============================================================
# Random Forest
# ============================================================
qtl_scan_rf <- function(X, y, marker_info) {
- cat("\n=== Random Forest ===\n")
-
- ok <- !is.na(y) & apply(X, 1, function(r) !any(is.na(r)))
- Xv <- X[ok, , drop = FALSE]
- yv <- y[ok]
-
- rf <- tryCatch(
- randomForest(x = Xv, y = yv, ntree = 500, importance = TRUE,
+ ok <- !is.na(y) & apply(X, 1, function(r) !any(is.na(r)))
+ Xv <- X[ok, , drop = FALSE]; yv <- y[ok]
+ rf <- tryCatch(
+ randomForest(x = Xv, y = yv, ntree = 1000, importance = TRUE,
mtry = max(1, floor(sqrt(ncol(Xv))))),
error = function(e) NULL)
if (is.null(rf)) return(data.frame(Message = "RF failed"))
-
imp <- importance(rf, type = 1)[, 1]
idf <- data.frame(Marker = names(imp), Importance = imp)
idf <- idf[idf$Importance > 0, ]
-
if (nrow(idf) == 0) return(data.frame(Message = "RF: no important markers"))
-
idf <- merge(idf, marker_info, by = "Marker", all.x = TRUE)
idf <- idf[!is.na(idf$Position), ]
-
- mx <- max(idf$Importance)
+ mx <- max(idf$Importance)
idf$LOD <- 10 * idf$Importance / mx
idf$P_Value <- 10^(-idf$LOD)
-
idf$PVE_Marker_Percent <- sapply(idf$Marker, function(m) {
- g <- Xv[, m]
- v <- !is.na(g)
- if (sum(v) < 5) return(NA)
+ g <- Xv[, m]; v <- !is.na(g); if (sum(v) < 5) return(NA)
summary(lm(yv[v] ~ g[v]))$r.squared * 100
})
idf$PVE_CIM_Percent <- idf$PVE_Marker_Percent
- idf$Additive_Effect <- NA_real_
- idf$SE_Additive <- NA_real_
- idf$CI_Lower <- NA_real_
- idf$CI_Upper <- NA_real_
- idf$Dominance_Effect <- NA_real_
- idf$SE_Dominance <- NA_real_
- idf$Dominance_Ratio <- NA_real_
- idf$Dominance_Class <- "Additive"
- idf$N_Cofactors <- 0L
- idf$N_Samples <- sum(ok)
- idf$Method <- "RF"
-
+ idf$Additive_Effect <- NA_real_; idf$SE_Additive <- NA_real_
+ idf$CI_Lower <- NA_real_; idf$CI_Upper <- NA_real_
+ idf$Dominance_Effect <- NA_real_; idf$SE_Dominance <- NA_real_
+ idf$Dominance_Ratio <- NA_real_; idf$Dominance_Class <- "Additive"
+ idf$N_Cofactors <- 0L; idf$N_Samples <- sum(ok); idf$Method <- "RF"
idf <- idf[order(idf$Chromosome, idf$Position), ]
idf[, c("Marker","Chromosome","Position","LOD","P_Value",
"PVE_Marker_Percent","PVE_CIM_Percent","Additive_Effect",
"SE_Additive","CI_Lower","CI_Upper","Dominance_Effect",
- "SE_Dominance","Dominance_Ratio","Dominance_Class",
- "N_Cofactors","N_Samples","Method")]
+ "SE_Dominance","Dominance_Ratio","Dominance_Class","N_Cofactors","N_Samples","Method")]
}
# ============================================================
-# DISPATCHER - FIXED: removed incorrect + operator
+# DISPATCHER
# ============================================================
qtl_scan <- function(X, y, marker_info, method = "CIM",
n_cofactors = 10, window_size = 10) {
- cat("\n", paste(rep("=", 60), collapse = ""), "\n")
- cat("QTL SCAN | Method:", method, "\n")
- cat(paste(rep("=", 60), collapse = ""), "\n")
-
+ cat("\n=== QTL SCAN | Method:", method, "===\n")
valid <- !is.na(y)
- X <- X[valid, , drop = FALSE]
- y <- y[valid]
-
+ X <- X[valid, , drop = FALSE]; y <- y[valid]
nzv <- apply(X, 2, function(x) length(unique(na.omit(x))) < 2)
X <- X[, !nzv, drop = FALSE]
-
- cat(" Samples after cleaning:", length(y), "\n")
- cat(" Markers after cleaning:", ncol(X), "\n")
-
- result <- switch(method,
+ cat(" Markers after NZV:", ncol(X), "\n")
+ switch(method,
SIM = qtl_scan_sim(X, y, marker_info),
CIM = qtl_scan_cim(X, y, marker_info, n_cofactors, window_size),
MQM = qtl_scan_mqm(X, y, marker_info, n_cofactors, window_size),
@@ -906,68 +747,80 @@ qtl_scan <- function(X, y, marker_info, method = "CIM",
RF = qtl_scan_rf(X, y, marker_info),
data.frame(Message = paste("Unknown method:", method))
)
-
- if (!"Message" %in% colnames(result) && nrow(result) > 0) {
- cat("\n--- Results Summary ---\n")
- cat(" Markers scanned:", nrow(result), "\n")
- cat(" LOD range:", round(min(result$LOD, na.rm = TRUE), 2),
- "to", round(max(result$LOD, na.rm = TRUE), 2), "\n")
- }
-
- result
}
# ============================================================
-# PERMUTATION THRESHOLD (Parallel)
+# FAST PARALLEL PERMUTATION THRESHOLD
# ============================================================
permutation_threshold <- function(X, y, marker_info, method = "SIM",
n_perm = 100, alpha = 0.05,
n_cofactors = 5, window_size = 5,
progress_cb = NULL) {
- cat("\n=== PERMUTATION TEST ===\n")
- cat(" Method:", method, "| Permutations:", n_perm, "| Alpha:", alpha, "\n")
-
- # Subsample markers for speed if too many
+
+ cat(" Running", n_perm, "PARALLEL permutations (method:", method, ")...\n")
+
n_markers_use <- min(200, ncol(X))
if (ncol(X) > n_markers_use) {
set.seed(99)
- keep_cols <- sample(colnames(X), n_markers_use)
- X_perm <- X[, keep_cols, drop = FALSE]
- mi_perm <- marker_info[marker_info$Marker %in% keep_cols, ]
- cat(" Using", n_markers_use, "markers for permutation (subsampled)\n")
+ keep_cols <- sample(colnames(X), n_markers_use)
+ X_perm <- X[, keep_cols, drop = FALSE]
+ mi_perm <- marker_info[marker_info$Marker %in% keep_cols, ]
} else {
- X_perm <- X
+ X_perm <- X
mi_perm <- marker_info
}
-
- n_cores <- max(1, min(parallel::detectCores(logical = TRUE) - 1, 8))
+
+ n_cores <- max(1, parallel::detectCores(logical = TRUE) - 1)
+ n_cores <- min(n_cores, 8)
cat(" Using", n_cores, "cores\n")
-
+
one_perm <- function(seed) {
set.seed(seed)
- yp <- sample(y)
- res <- tryCatch(qtl_scan_sim(X_perm, yp, mi_perm), error = function(e) NULL)
- if (!is.null(res) && !"Message" %in% colnames(res) && "LOD" %in% colnames(res)) {
+ yp <- sample(y)
+ res <- tryCatch(
+ qtl_scan_sim(X_perm, yp, mi_perm),
+ error = function(e) NULL)
+ if (!is.null(res) && !"Message" %in% colnames(res) && "LOD" %in% colnames(res))
return(max(res$LOD, na.rm = TRUE))
- }
return(0)
}
-
+
seeds <- sample.int(1e6, n_perm)
-
- if (n_cores > 1 && .Platform$OS.type != "windows") {
- max_lods <- tryCatch(
- unlist(parallel::mclapply(seeds, one_perm, mc.cores = n_cores)),
- error = function(e) sapply(seeds, one_perm)
- )
+ is_windows <- .Platform$OS.type == "windows"
+
+ if (n_cores > 1) {
+ if (is_windows) {
+ cl <- tryCatch({
+ cl2 <- parallel::makeCluster(n_cores)
+ parallel::clusterEvalQ(cl2, { library(glmnet) })
+ parallel::clusterExport(cl2,
+ varlist = c("qtl_scan_sim","calc_lod","calc_pve",
+ "estimate_effects","dom_class",
+ "X_perm","y","mi_perm"),
+ envir = environment())
+ cl2
+ }, error = function(e) NULL)
+ if (!is.null(cl)) {
+ max_lods <- tryCatch({
+ unlist(parallel::parLapply(cl, seeds, one_perm))
+ }, error = function(e) sapply(seeds, one_perm))
+ parallel::stopCluster(cl)
+ } else {
+ max_lods <- sapply(seeds, one_perm)
+ }
+ } else {
+ max_lods <- tryCatch(
+ unlist(parallel::mclapply(seeds, one_perm, mc.cores = n_cores,
+ mc.preschedule = TRUE)),
+ error = function(e) sapply(seeds, one_perm)
+ )
+ }
} else {
max_lods <- sapply(seeds, one_perm)
}
-
+
thr <- quantile(max_lods, 1 - alpha, na.rm = TRUE)
cat(" Permutation LOD threshold (alpha =", alpha, "):", round(thr, 3), "\n")
- cat(" Range of max LODs:", round(min(max_lods), 3), "to", round(max(max_lods), 3), "\n")
-
thr
}
@@ -979,32 +832,26 @@ find_common_qtl <- function(compare_res, lod_threshold, min_models = 2) {
for (mth in names(compare_res)) {
r <- compare_res[[mth]]
if (is.null(r) || "Message" %in% colnames(r)) next
- sig <- r[!is.na(r$LOD) & r$LOD >= lod_threshold,
- c("Marker","Chromosome","Position","LOD","PVE_Marker_Percent","Additive_Effect"),
- drop = FALSE]
- if (nrow(sig) > 0) {
- sig$Model <- mth
- sig_list[[mth]] <- sig
+ peaks <- find_qtl_peaks(r, lod_threshold, min_distance_cM = 5)
+ if (!is.null(peaks) && nrow(peaks) > 0) {
+ peaks$Model <- mth
+ sig_list[[mth]] <- peaks[, c("Marker","Chromosome","Position","LOD","PVE_Marker_Percent","Additive_Effect","Model")]
}
}
-
if (length(sig_list) == 0) return(NULL)
-
all_sig <- do.call(rbind, sig_list)
all_sig$Chromosome <- as.character(all_sig$Chromosome)
- mk_cnt <- table(all_sig$Marker)
+ mk_cnt <- table(all_sig$Marker)
all_sig$N_Models_Detected <- as.integer(mk_cnt[all_sig$Marker])
- common <- all_sig[all_sig$N_Models_Detected >= min_models, ]
-
+ common <- all_sig[all_sig$N_Models_Detected >= min_models, ]
if (nrow(common) == 0) return(NULL)
-
do.call(rbind, lapply(unique(common$Marker), function(mk) {
rows <- common[common$Marker == mk, ]
base <- rows[which.max(rows$LOD), c("Marker","Chromosome","Position","N_Models_Detected")]
- base$Models_List <- paste(sort(unique(rows$Model)), collapse = ", ")
- base$Mean_LOD <- round(mean(rows$LOD, na.rm = TRUE), 3)
- base$Max_LOD <- round(max(rows$LOD, na.rm = TRUE), 3)
- base$Mean_PVE <- round(mean(rows$PVE_Marker_Percent, na.rm = TRUE), 3)
+ base$Models_List <- paste(sort(unique(rows$Model)), collapse = ", ")
+ base$Mean_LOD <- round(mean(rows$LOD, na.rm = TRUE), 3)
+ base$Max_LOD <- round(max(rows$LOD, na.rm = TRUE), 3)
+ base$Mean_PVE <- round(mean(rows$PVE_Marker_Percent, na.rm = TRUE), 3)
base$Mean_Add_Eff <- round(mean(rows$Additive_Effect, na.rm = TRUE), 3)
for (mth in names(compare_res)) {
r_m <- rows[rows$Model == mth, ]
@@ -1015,219 +862,126 @@ find_common_qtl <- function(compare_res, lod_threshold, min_models = 2) {
}
# ============================================================
-# PER-CHROMOSOME LOD PLOT (QTL Cartographer Style)
+# COLORFUL MANHATTAN PLOT (ggplot2)
# ============================================================
-make_chr_lod_plot <- function(scan_df, marker_info, lod_threshold = 2.0,
- trait_name = "Trait", method = "CIM",
- n_cols = 4) {
-
- if (is.null(scan_df) || "Message" %in% colnames(scan_df)) {
- return(ggplot() + labs(title = "No data") + theme_bw())
- }
-
+make_manhattan_ggplot <- function(scan_df, lod_threshold = 2.0, peaks_df = NULL,
+ title = "QTL Manhattan Plot") {
+ if (is.null(scan_df) || "Message" %in% colnames(scan_df))
+ return(ggplot() + labs(title = title) + theme_bw())
pd <- scan_df[!is.na(scan_df$LOD) & !is.na(scan_df$Position) & !is.na(scan_df$Chromosome), ]
- if (nrow(pd) == 0) {
- return(ggplot() + labs(title = "No scan data") + theme_bw())
- }
-
+ if (nrow(pd) == 0) return(ggplot() + labs(title = title) + theme_bw())
+
pd$Chromosome <- as.character(pd$Chromosome)
chroms <- sort(unique(pd$Chromosome), method = "radix")
- n_chr <- length(chroms)
- n_rows_layout <- ceiling(n_chr / n_cols)
-
- # Auto QTL naming
- sig_all <- pd[pd$LOD >= lod_threshold, ]
- qtl_labels <- character(nrow(pd))
-
- if (nrow(sig_all) > 0) {
- sig_all <- sig_all[order(sig_all$Chromosome, -sig_all$LOD), ]
- for (ch in chroms) {
- ch_sig <- sig_all[sig_all$Chromosome == ch, ]
- if (nrow(ch_sig) == 0) next
-
- # Cluster nearby peaks (>= 10 cM apart)
- peak_rows <- ch_sig[1, , drop = FALSE]
- for (j in seq_len(nrow(ch_sig))) {
- p_pos <- ch_sig$Position[j]
- if (all(abs(peak_rows$Position - p_pos) > 10)) {
- peak_rows <- rbind(peak_rows, ch_sig[j, ])
- }
- }
- peak_rows <- peak_rows[order(-peak_rows$LOD), ]
- chr_num <- gsub("[^0-9A-Za-z]", "", ch)
- for (k in seq_len(min(3, nrow(peak_rows)))) {
- lbl <- paste0("q", substr(toupper(gsub("[^A-Za-z]", "", trait_name)), 1, 3),
- chr_num, if (nrow(peak_rows) > 1) k else "")
- idx <- which(pd$Marker == peak_rows$Marker[k])
- if (length(idx) > 0) qtl_labels[idx[1]] <- lbl
- }
- }
- }
- pd$QTL_Label <- qtl_labels
-
- # Get chromosome ranges
- marker_info$Chromosome <- as.character(marker_info$Chromosome)
- chr_info <- do.call(rbind, lapply(chroms, function(ch) {
- mk_ch <- marker_info[marker_info$Chromosome == ch, ]
- data.frame(Chromosome = ch,
- chr_start = min(mk_ch$Position, na.rm = TRUE),
- chr_end = max(mk_ch$Position, na.rm = TRUE),
- stringsAsFactors = FALSE)
- }))
-
- global_lod_max <- max(pd$LOD, na.rm = TRUE) * 1.15
- if (is.na(global_lod_max) || global_lod_max <= 0) global_lod_max <- 5
-
- # Build per-chromosome panels
- plot_list <- lapply(chroms, function(ch) {
- ch_pd <- pd[pd$Chromosome == ch, ]
- ch_pd <- ch_pd[order(ch_pd$Position), ]
- ci <- chr_info[chr_info$Chromosome == ch, ]
- chr_len <- ci$chr_end - ci$chr_start
- if (chr_len <= 0) chr_len <- 100
- ch_sig <- ch_pd[ch_pd$LOD >= lod_threshold & nchar(ch_pd$QTL_Label) > 0, ]
-
- chr_color <- "#4DB6AC" # Teal color
-
- p <- ggplot(ch_pd, aes(x = LOD, y = Position)) +
- # Chromosome ideogram
- annotate("rect",
- xmin = -global_lod_max * 0.28, xmax = -global_lod_max * 0.08,
- ymin = ci$chr_start, ymax = ci$chr_end,
- fill = "#E0F2F1", color = "#78909C", linewidth = 0.6) +
- # Centromere band (approx 38-45% of chromosome length)
- annotate("rect",
- xmin = -global_lod_max * 0.28, xmax = -global_lod_max * 0.08,
- ymin = ci$chr_start + chr_len * 0.38,
- ymax = ci$chr_start + chr_len * 0.45,
- fill = "#78909C", color = NA) +
- # Telomere caps
- annotate("rect",
- xmin = -global_lod_max * 0.28, xmax = -global_lod_max * 0.08,
- ymin = ci$chr_start,
- ymax = ci$chr_start + chr_len * 0.06,
- fill = "#B2DFDB", color = NA) +
- annotate("rect",
- xmin = -global_lod_max * 0.28, xmax = -global_lod_max * 0.08,
- ymin = ci$chr_end - chr_len * 0.06,
- ymax = ci$chr_end,
- fill = "#B2DFDB", color = NA) +
- # Marker tick marks
- geom_segment(data = marker_info[marker_info$Chromosome == ch, ],
- aes(x = -global_lod_max * 0.08, xend = -global_lod_max * 0.04,
- y = Position, yend = Position),
- color = "#546E7A", linewidth = 0.25, inherit.aes = FALSE) +
- # LOD curve
- geom_line(color = chr_color, linewidth = 1.0, alpha = 0.9) +
- geom_area(fill = chr_color, alpha = 0.18) +
- # Significance threshold
- geom_vline(xintercept = lod_threshold,
- linetype = "dashed", color = "#E53935", linewidth = 0.7, alpha = 0.85) +
- # Significant QTL markers
- {if (nrow(ch_sig) > 0)
- geom_point(data = ch_sig, aes(x = LOD, y = Position),
- color = "#E53935", size = 2.5, shape = 18, inherit.aes = FALSE)
- } +
- # QTL labels
- {if (nrow(ch_sig) > 0)
- ggrepel::geom_label_repel(
- data = ch_sig,
- aes(x = LOD, y = Position, label = QTL_Label),
- size = 2.8, fontface = "bold", fill = "white", color = "#B71C1C",
- label.padding = unit(0.15, "lines"),
- segment.color = "#E53935", segment.size = 0.5,
- direction = "y", nudge_x = global_lod_max * 0.05,
- min.segment.length = 0, max.overlaps = 20,
- inherit.aes = FALSE)
- } +
- scale_x_continuous(
- limits = c(-global_lod_max * 0.30, global_lod_max),
- breaks = c(0, round(lod_threshold, 1),
- round(global_lod_max * 0.5, 1), round(global_lod_max * 0.9, 1)),
- labels = function(x) ifelse(x < 0, "", as.character(round(x, 1))),
- expand = expansion(mult = c(0.01, 0.05))) +
- scale_y_continuous(
- limits = c(ci$chr_start - chr_len * 0.08,
- ci$chr_end + chr_len * 0.12),
- breaks = pretty(c(ci$chr_start, ci$chr_end), n = 5),
- expand = expansion(mult = c(0.02, 0.02))) +
- coord_flip() +
- labs(title = paste0("Chr ", ch), x = "LOD Score", y = "Position (cM)") +
- theme_bw(base_size = 10) +
- theme(
- panel.background = element_rect(fill = "white", color = NA),
- plot.background = element_rect(fill = "white", color = NA),
- panel.grid.major = element_line(color = "grey94", linewidth = 0.4),
- panel.grid.minor = element_blank(),
- panel.border = element_rect(color = "grey80", linewidth = 0.5),
- plot.title = element_text(face = "bold", size = 10,
- color = "#263238", hjust = 0.5,
- margin = margin(b = 2)),
- axis.text = element_text(size = 7, color = "grey30"),
- axis.title.x = element_text(size = 8, color = "grey20", face = "bold"),
- axis.title.y = element_text(size = 7, color = "grey40"),
- plot.margin = unit(c(3, 4, 3, 2), "pt")
- )
- p
- })
-
- # Combine into grid
- n_real <- length(plot_list)
- n_empty <- n_cols * n_rows_layout - n_real
- if (n_empty > 0) {
- for (i in seq_len(n_empty))
- plot_list <- c(plot_list, list(ggplot() + theme_void()))
+ offsets <- setNames(numeric(length(chroms)), chroms)
+ for (i in seq_along(chroms)) {
+ if (i == 1) { offsets[chroms[1]] <- 0; next }
+ prev <- chroms[i - 1]
+ offsets[chroms[i]] <- offsets[prev] + max(pd$Position[pd$Chromosome == prev], na.rm = TRUE) * 1.05
+ }
+ pd$cum_pos <- pd$Position + offsets[pd$Chromosome]
+ pd$sig <- pd$LOD >= lod_threshold
+
+ chr_colors <- ifelse(seq_along(chroms) %% 2 == 1, "#3A86FF", "#FB5607")
+ names(chr_colors) <- chroms
+ chr_mids <- tapply(pd$cum_pos, pd$Chromosome, median, na.rm = TRUE)
+
+ p <- ggplot(pd, aes(x = cum_pos, y = LOD)) +
+ geom_point(data = pd[!pd$sig, ],
+ aes(color = Chromosome),
+ size = 1.6, alpha = 0.6, show.legend = FALSE) +
+ scale_color_manual(values = chr_colors)
+
+ sig_pd <- pd[pd$sig, ]
+ if (nrow(sig_pd) > 0) {
+ p <- p +
+ geom_point(data = sig_pd, aes(x = cum_pos, y = LOD),
+ color = "#FFBE0B", size = 7, alpha = 0.35, shape = 16) +
+ geom_point(data = sig_pd, aes(x = cum_pos, y = LOD, fill = LOD),
+ size = 5, shape = 23, color = "white", stroke = 0.8) +
+ scale_fill_gradientn(
+ colors = c("#FB5607","#FFBE0B","#FF006E","#8338EC"),
+ name = "LOD Score",
+ guide = guide_colorbar(barwidth = 8, barheight = 0.8, title.position = "top"))
}
- title_grob <- grid::textGrob(
- paste0("QTL Mapping — ", trait_name, " | Method: ", method,
- " | LOD threshold: ", lod_threshold),
- gp = grid::gpar(fontsize = 13, fontface = "bold", col = "#212529"))
-
- grid_plot <- gridExtra::arrangeGrob(
- grobs = plot_list,
- ncol = n_cols,
- nrow = n_rows_layout,
- top = title_grob)
-
- grid_plot
+ # Add peak markers if provided
+ if (!is.null(peaks_df) && nrow(peaks_df) > 0) {
+ peaks_df$Chromosome <- as.character(peaks_df$Chromosome)
+ peaks_df$cum_pos <- peaks_df$Position + offsets[peaks_df$Chromosome]
+ p <- p +
+ geom_point(data = peaks_df, aes(x = cum_pos, y = LOD),
+ color = "#FF006E", size = 8, shape = 8, stroke = 1.5) +
+ ggrepel::geom_label_repel(
+ data = peaks_df,
+ aes(x = cum_pos, y = LOD, label = Marker),
+ size = 3, max.overlaps = 25,
+ fill = "white", color = "#FF006E",
+ fontface = "bold",
+ segment.color = "#FF006E", segment.size = 0.5,
+ label.padding = unit(0.2, "lines"),
+ box.padding = unit(0.3, "lines"))
+ }
+
+ p <- p +
+ geom_hline(yintercept = lod_threshold, linetype = "dashed",
+ color = "#FF006E", linewidth = 1.0, alpha = 0.8) +
+ annotate("text", x = -Inf, y = lod_threshold,
+ label = paste(" LOD =", lod_threshold), color = "#FF006E",
+ size = 3.2, hjust = 0, vjust = -0.5, fontface = "italic") +
+ scale_x_continuous(breaks = chr_mids[chroms],
+ labels = paste0("Chr ", chroms)) +
+ labs(title = title,
+ subtitle = paste0(length(unique(peaks_df$Marker)), " QTL peaks • ",
+ sum(pd$sig, na.rm = TRUE),
+ " significant markers • ", length(chroms), " chromosomes"),
+ x = "Chromosome", y = "LOD Score") +
+ theme_bw(base_size = 13) +
+ theme(
+ panel.background = element_rect(fill = "white", color = "grey85"),
+ plot.background = element_rect(fill = "white", color = NA),
+ panel.grid.minor = element_blank(),
+ panel.grid.major.x = element_blank(),
+ panel.grid.major.y = element_line(color = "grey92", linetype = "dotted"),
+ axis.text.x = element_text(angle = 45, hjust = 1, color = "grey30", size = 10),
+ axis.text.y = element_text(color = "grey30"),
+ axis.title = element_text(face = "bold", color = "grey20"),
+ plot.title = element_text(face = "bold", size = 15, color = "#212529"),
+ plot.subtitle = element_text(color = "grey40", size = 11),
+ legend.position = "bottom",
+ legend.background = element_rect(fill = "white", color = NA),
+ legend.text = element_text(size = 9, color = "grey30"),
+ legend.title = element_text(size = 10, color = "grey20", face = "bold")
+ )
+ p
}
# ============================================================
-# COLORFUL PLOTLY MANHATTAN
+# COLORFUL PLOTLY MANHATTAN (interactive)
# ============================================================
-make_plotly_manhattan <- function(scan_df, lod_threshold = 2.0, title = "Manhattan Plot") {
+make_plotly_manhattan <- function(scan_df, lod_threshold = 2.0, peaks_df = NULL, title = "Manhattan Plot") {
blank <- plot_ly() %>%
layout(title = title, paper_bgcolor = "white", plot_bgcolor = "white")
-
if (is.null(scan_df) || "Message" %in% colnames(scan_df)) return(blank)
-
pd <- scan_df[!is.na(scan_df$LOD) & !is.na(scan_df$Position) & !is.na(scan_df$Chromosome), ]
if (nrow(pd) == 0) return(blank)
-
+
pd$Chromosome <- as.character(pd$Chromosome)
- chroms <- sort(unique(pd$Chromosome), method = "radix")
-
- # Calculate cumulative positions
+ chroms <- sort(unique(pd$Chromosome), method = "radix")
offsets <- setNames(numeric(length(chroms)), chroms)
for (i in seq_along(chroms)) {
- if (i == 1) {
- offsets[chroms[1]] <- 0
- } else {
- prev <- chroms[i - 1]
- offsets[chroms[i]] <- offsets[prev] + max(pd$Position[pd$Chromosome == prev], na.rm = TRUE) * 1.05
- }
+ if (i == 1) { offsets[chroms[1]] <- 0; next }
+ prev <- chroms[i - 1]
+ offsets[chroms[i]] <- offsets[prev] + max(pd$Position[pd$Chromosome == prev], na.rm = TRUE) * 1.05
}
pd$cum_pos <- pd$Position + offsets[pd$Chromosome]
- pd$sig <- pd$LOD >= lod_threshold
-
+ pd$sig <- pd$LOD >= lod_threshold
+
chr_mids <- tapply(pd$cum_pos, pd$Chromosome, median, na.rm = TRUE)
chr_bg_colors <- rep(c("#3A86FF","#FB5607"), length.out = length(chroms))
names(chr_bg_colors) <- chroms
-
+
pl <- plot_ly()
-
- # Non-significant points
for (ch in chroms) {
sub <- pd[pd$Chromosome == ch & !pd$sig, ]
if (nrow(sub) == 0) next
@@ -1241,22 +995,38 @@ make_plotly_manhattan <- function(scan_df, lod_threshold = 2.0, title = "Manhatt
"
PVE: ", round(PVE_Marker_Percent, 2), "%"),
hoverinfo = "text")
}
-
- # Significant points
+
sig_pd <- pd[pd$sig, ]
if (nrow(sig_pd) > 0) {
lod_min <- min(sig_pd$LOD, na.rm = TRUE)
lod_max <- max(sig_pd$LOD, na.rm = TRUE)
lod_norm <- if (lod_max > lod_min) (sig_pd$LOD - lod_min) / (lod_max - lod_min) else rep(0.5, nrow(sig_pd))
sig_colors <- colorRampPalette(c("#8338EC","#3A86FF","#FFBE0B","#FB5607","#FF006E"))(100)
- pt_colors <- sig_colors[pmax(1, pmin(100, round(lod_norm * 99) + 1))]
-
+ pt_colors <- sig_colors[pmax(1, pmin(100, round(lod_norm * 99) + 1))]
+
pl <- pl %>% add_trace(
data = sig_pd, x = ~cum_pos, y = ~LOD, type = "scatter", mode = "markers",
- name = "Significant QTL",
- marker = list(size = 14, color = pt_colors, symbol = "diamond",
- line = list(width = 1.5, color = "white"), opacity = 0.95),
- text = ~paste0("\u2605 ", Marker, " \u2605
Chr: ", Chromosome,
+ name = "Significant Markers",
+ marker = list(size = 10, color = pt_colors, symbol = "circle",
+ line = list(width = 1, color = "white"), opacity = 0.85),
+ text = ~paste0("", Marker, "
Chr: ", Chromosome,
+ "
Pos: ", round(Position, 1), " cM",
+ "
LOD: ", round(LOD, 3),
+ "
PVE: ", round(PVE_Marker_Percent, 2), "%"),
+ hoverinfo = "text")
+ }
+
+ # Add peak markers
+ if (!is.null(peaks_df) && nrow(peaks_df) > 0) {
+ peaks_df$Chromosome <- as.character(peaks_df$Chromosome)
+ peaks_df$cum_pos <- peaks_df$Position + offsets[peaks_df$Chromosome]
+ pl <- pl %>% add_trace(
+ data = peaks_df, x = ~cum_pos, y = ~LOD, type = "scatter", mode = "markers",
+ name = "QTL Peaks",
+ marker = list(size = 15, color = "#FF006E", symbol = "star",
+ line = list(width = 2, color = "white")),
+ text = ~paste0("\u2605 QTL PEAK \u2605
", Marker,
+ "
Chr: ", Chromosome,
"
Pos: ", round(Position, 1), " cM",
"
LOD: ", round(LOD, 3),
"
PVE: ", round(PVE_Marker_Percent, 2), "%",
@@ -1264,46 +1034,47 @@ make_plotly_manhattan <- function(scan_df, lod_threshold = 2.0, title = "Manhatt
"
Dom. Class: ", Dominance_Class),
hoverinfo = "text")
}
-
- # Threshold line
- pl <- pl %>% add_segments(
- x = min(pd$cum_pos, na.rm = TRUE), xend = max(pd$cum_pos, na.rm = TRUE),
- y = lod_threshold, yend = lod_threshold,
- line = list(color = "#FF006E", dash = "dash", width = 2),
- showlegend = FALSE) %>%
+
+ pl <- pl %>%
+ add_segments(
+ x = min(pd$cum_pos, na.rm = TRUE),
+ xend = max(pd$cum_pos, na.rm = TRUE),
+ y = lod_threshold, yend = lod_threshold,
+ line = list(color = "#FF006E", dash = "dash", width = 2),
+ showlegend = FALSE) %>%
layout(
title = list(
text = paste0("", title, " ",
- sum(pd$sig, na.rm = TRUE), " significant QTLs"),
+ if (!is.null(peaks_df)) nrow(peaks_df) else 0, " QTL peaks"),
font = list(size = 15, color = "#212529")),
- xaxis = list(title = "Chromosome",
- tickvals = as.list(chr_mids[chroms]),
- ticktext = as.list(paste0("Chr ", chroms)),
- tickangle = 45,
- gridcolor = "rgba(0,0,0,0.07)", color = "grey25", zeroline = FALSE),
- yaxis = list(title = "LOD Score",
- gridcolor = "rgba(0,0,0,0.07)", color = "grey25", zeroline = FALSE),
+ xaxis = list(
+ title = "Chromosome",
+ tickvals = as.list(chr_mids[chroms]),
+ ticktext = as.list(paste0("Chr ", chroms)),
+ tickangle = 45,
+ gridcolor = "rgba(0,0,0,0.07)", color = "grey25", zeroline = FALSE),
+ yaxis = list(
+ title = "LOD Score",
+ gridcolor = "rgba(0,0,0,0.07)", color = "grey25", zeroline = FALSE),
paper_bgcolor = "white", plot_bgcolor = "white",
font = list(color = "grey20"),
legend = list(orientation = "h", y = -0.18, font = list(size = 10, color = "grey20")),
- hoverlabel = list(bgcolor = "white", font = list(color = "grey10", size = 11),
- bordercolor = "grey60"))
-
+ hoverlabel = list(bgcolor = "white", font = list(color = "grey10", size = 11), bordercolor = "grey60"))
pl
}
# ============================================================
-# CHROMOSOME IDIOGRAM
+# COLORFUL CHROMOSOME IDIOGRAM
# ============================================================
make_idiogram_ggplot <- function(qtl_list, all_markers_df, lod_threshold = 2.0) {
if (is.null(all_markers_df) || nrow(all_markers_df) == 0)
return(ggplot() + labs(title = "No marker data") + theme_bw())
-
+
all_markers_df$Chromosome <- as.character(all_markers_df$Chromosome)
- chroms <- sort(unique(all_markers_df$Chromosome))
- n_chr <- length(chroms)
+ chroms <- sort(unique(all_markers_df$Chromosome))
+ n_chr <- length(chroms)
chr_idx <- setNames(seq_along(chroms), chroms)
-
+
chr_summary <- do.call(rbind, lapply(chroms, function(ch) {
mk <- all_markers_df[all_markers_df$Chromosome == ch, ]
data.frame(Chromosome = ch, x = chr_idx[ch],
@@ -1311,10 +1082,9 @@ make_idiogram_ggplot <- function(qtl_list, all_markers_df, lod_threshold = 2.0)
ymax = max(mk$Position, na.rm = TRUE),
stringsAsFactors = FALSE)
}))
-
+
max_pos <- max(all_markers_df$Position, na.rm = TRUE)
- if (is.na(max_pos)) max_pos <- 100
-
+
p <- ggplot() +
geom_rect(data = chr_summary,
aes(xmin = x - 0.28, xmax = x + 0.28, ymin = ymin, ymax = ymax),
@@ -1329,125 +1099,109 @@ make_idiogram_ggplot <- function(qtl_list, all_markers_df, lod_threshold = 2.0)
label = paste0("Chr\n", Chromosome)),
size = 3.0, color = "#343A40", fontface = "bold") +
scale_x_continuous(breaks = NULL) +
- labs(title = paste0("Chromosome Idiogram \u2022 LOD \u2265 ", lod_threshold),
+ labs(title = paste0("Chromosome Idiogram \u2022 QTL Peaks with LOD \u2265 ", lod_threshold),
x = NULL, y = "Genetic Position (cM)") +
theme_bw(base_size = 13) +
theme(
- panel.background = element_rect(fill = "white"),
- plot.background = element_rect(fill = "white", color = NA),
+ panel.background = element_rect(fill = "white"),
+ plot.background = element_rect(fill = "white", color = NA),
panel.grid.major.x = element_blank(),
- panel.grid.minor = element_blank(),
- legend.position = "bottom",
- legend.title = element_text(face = "bold", size = 10, color = "grey20"),
- legend.text = element_text(size = 9, color = "grey30"),
- plot.title = element_text(face = "bold", size = 14, color = "#212529"),
- axis.title.y = element_text(face = "bold", color = "grey20")
+ panel.grid.minor = element_blank(),
+ legend.position = "bottom",
+ legend.title = element_text(face = "bold", size = 10, color = "grey20"),
+ legend.text = element_text(size = 9, color = "grey30"),
+ plot.title = element_text(face = "bold", size = 14, color = "#212529"),
+ axis.title.y = element_text(face = "bold", color = "grey20")
)
-
- # Add QTL markers
+
model_names <- names(qtl_list)
- n_models <- length(model_names)
- vivid_pal <- c("#FF006E","#3A86FF","#06D6A0","#FFBE0B","#FB5607","#8338EC",
- "#F72585","#4CC9F0","#2A9D8F","#E9C46A")
+ n_models <- length(model_names)
+ vivid_pal <- c("#FF006E","#3A86FF","#06D6A0","#FFBE0B","#FB5607","#8338EC",
+ "#F72585","#4CC9F0","#2A9D8F","#E9C46A")
model_colors_use <- setNames(
- rep(vivid_pal, ceiling(n_models / length(vivid_pal)))[seq_len(n_models)],
- model_names)
-
+ rep(vivid_pal, ceiling(n_models / length(vivid_pal)))[seq_len(n_models)],
+ model_names
+ )
+ for (m in intersect(model_names, names(MODEL_COLORS)))
+ model_colors_use[m] <- MODEL_COLORS[m]
+
for (ti in seq_along(model_names)) {
- tr <- model_names[ti]
- qdf <- qtl_list[[tr]]
+ tr <- model_names[ti]
+ qdf <- qtl_list[[tr]]
if (is.null(qdf) || "Message" %in% colnames(qdf)) next
-
- sig <- qdf[!is.na(qdf$LOD) & qdf$LOD >= lod_threshold, ]
+ sig <- qdf[!is.na(qdf$LOD) & qdf$LOD >= lod_threshold, ]
if (nrow(sig) == 0) next
-
sig$Chromosome <- as.character(sig$Chromosome)
- sig <- sig[sig$Chromosome %in% chroms, ]
+ sig <- sig[sig$Chromosome %in% chroms, ]
if (nrow(sig) == 0) next
-
sig$x_base <- chr_idx[sig$Chromosome]
- side <- ifelse(ti %% 2 == 1, 1, -1)
- x_off <- sig$x_base + side * (0.33 + (((ti - 1) %/% 2) * 0.13))
+
+ side <- ifelse(ti %% 2 == 1, 1, -1)
+ x_off <- sig$x_base + side * (0.33 + (((ti - 1) %/% 2) * 0.13))
lod_sz <- pmin(7, pmax(2.5, sig$LOD * 0.9))
- mc <- model_colors_use[tr]
-
- seg_df <- data.frame(x = sig$x_base + side * 0.28, xend = x_off,
- y = sig$Position, yend = sig$Position,
- model = tr, stringsAsFactors = FALSE)
- pt_df <- data.frame(x = x_off, y = sig$Position,
- model = tr, size_val = lod_sz, stringsAsFactors = FALSE)
-
+ mc <- model_colors_use[tr]
+
+ seg_df <- data.frame(
+ x = sig$x_base + side * 0.28, xend = x_off,
+ y = sig$Position, yend = sig$Position,
+ model = tr, stringsAsFactors = FALSE)
+
+ pt_df <- data.frame(
+ x = x_off, y = sig$Position,
+ model = tr, size_val = lod_sz,
+ stringsAsFactors = FALSE)
+
p <- p +
geom_point(data = pt_df, aes(x = x, y = y),
color = mc, size = lod_sz * 2.2, alpha = 0.12, shape = 16) +
geom_segment(data = seg_df,
aes(x = x, xend = xend, y = y, yend = yend, color = model),
linewidth = 0.9, alpha = 0.85) +
- geom_point(data = pt_df, aes(x = x, y = y, color = model, size = size_val),
+ geom_point(data = pt_df,
+ aes(x = x, y = y, color = model, size = size_val),
shape = 18, alpha = 0.95) +
scale_color_manual(values = model_colors_use, name = "Model") +
scale_size_continuous(range = c(2.5, 7), guide = "none")
}
-
p
}
# ============================================================
-# DOMESTICATION METRICS
+# DOMESTICATION: Fst + Tajima's D
# ============================================================
calc_selection_metrics <- function(gmat, pop_df, marker_info) {
out <- list()
for (m in colnames(gmat)) {
- g <- gmat[, m]
+ g <- gmat[, m]
pp <- pop_df$population[match(rownames(gmat), pop_df$id)]
vi <- !is.na(g) & !is.na(pp)
- gv <- g[vi]
- pv <- pp[vi]
-
+ gv <- g[vi]; pv <- pp[vi]
if (length(unique(pv)) < 2) next
-
- gd <- gv[pv == "Domesticated"]
- gw <- gv[pv == "Wild"]
-
+ gd <- gv[pv == "Domesticated"]; gw <- gv[pv == "Wild"]
if (length(gd) < 3 || length(gw) < 3) next
-
- fd <- mean(gd, na.rm = TRUE) / 2
- fw <- mean(gw, na.rm = TRUE) / 2
+ fd <- mean(gd, na.rm = TRUE) / 2; fw <- mean(gw, na.rm = TRUE) / 2
pa <- (fd + fw) / 2
-
fst <- if (pa > 0 && pa < 1) {
- f <- (fd - fw)^2 / (pa * (1 - pa))
- f / (1 + f)
- } else 0
-
- pid <- 2 * fd * (1 - fd)
- piw <- 2 * fw * (1 - fw)
-
+ f <- (fd - fw)^2 / (pa * (1 - pa)); f / (1 + f) } else 0
+ pid <- 2 * fd * (1 - fd); piw <- 2 * fw * (1 - fw)
tdd <- tryCatch({
sd_d <- sd(gd, na.rm = TRUE)
if (is.na(sd_d) || sd_d == 0) NA_real_ else
(pid - 1 / length(gd)) / (sd_d / sqrt(length(gd)))
}, error = function(e) NA_real_)
-
mi <- marker_info[marker_info$Marker == m, ]
out[[m]] <- data.frame(
- Marker = m,
- Chromosome = if (nrow(mi) > 0) mi$Chromosome[1] else NA,
+ Marker = m, Chromosome = if (nrow(mi) > 0) mi$Chromosome[1] else NA,
Position = if (nrow(mi) > 0) mi$Position[1] else NA,
- Fst = fst,
- Pi_Dom = pid,
- Pi_Wild = piw,
- Tajima_D_Dom = tdd,
- stringsAsFactors = FALSE
- )
+ Fst = fst, Pi_Dom = pid, Pi_Wild = piw, Tajima_D_Dom = tdd,
+ stringsAsFactors = FALSE)
}
-
if (length(out) == 0) return(NULL)
do.call(rbind, out)
}
# ============================================================
-# UI - Complete UI (same as v10 but with updated version)
+# UI
# ============================================================
ui <- fluidPage(
shinyjs::useShinyjs(),
@@ -1475,6 +1229,7 @@ ui <- fluidPage(
.btn-success:hover{background:#05b085;border-color:#05b085;transform:translateY(-1px);}
.btn-info{background:#3A86FF;border-color:#3A86FF;color:#fff;}
.btn-info:hover{background:#2563eb;border-color:#2563eb;transform:translateY(-1px);}
+ .btn-warning{background:#FFBE0B;border-color:#FFBE0B;color:#212529;}
.form-control,.selectize-input{background:#ffffff!important;border:1px solid #ced4da!important;color:#212529!important;font-size:13px;border-radius:6px;}
label{font-size:12px;color:#6c757d;font-weight:500;}
.stat-box{background:#ffffff;border:1px solid #dee2e6;border-radius:8px;padding:14px 18px;text-align:center;}
@@ -1486,25 +1241,24 @@ ui <- fluidPage(
.model-badge{display:inline-block;background:#e8f4fd;border:1px solid #90caf9;border-radius:20px;padding:3px 10px;font-size:11px;font-weight:600;color:#3A86FF;margin:2px;}
.perm-info{background:linear-gradient(135deg,#e8f4fd,#f0f8ff);border:1px solid #90caf9;border-left:4px solid #8338EC;border-radius:8px;padding:12px 16px;margin:8px 0;font-size:13px;}
.speed-badge{background:#8338EC;color:#fff;border-radius:12px;padding:2px 8px;font-size:10px;font-weight:700;letter-spacing:0.5px;}
- .fix-badge{background:#06D6A0;color:#fff;border-radius:12px;padding:2px 8px;font-size:10px;font-weight:700;letter-spacing:0.5px;}
"))
),
-
+
navbarPage(
- title = "QTL-Mapper v11",
- id = "nav",
-
- # Data Upload Tab
+ title = "QTL-Mapper v10",
+ id = "nav",
+
+ # ── 1. DATA UPLOAD ─────────────────────────────────────
tabPanel("📁 Data Upload", icon = icon("upload"),
fluidRow(column(12,
div(class = "info-box",
- tags$b("QTL-Mapper v11 — CIM FULLY FIXED + QTL Cartographer Style Plots"),
+ tags$b("QTL-Mapper v10 — Precision QTL Interval Mapping"),
tags$br(),
- tags$span(class = "fix-badge", "CIM FIXED"),
- " Window uses MARKER INDEX (not cM) | Cofactor LOD gain threshold: 2.0 | Fallback to top SIM markers",
+ "Format: Row1 = header (id, marker1, …) | Row2 = chromosomes | ",
+ "Row3 = positions (cM) | Rows 4+ = samples. Genotypes coded 0/1/2 (AA / Aa / aa).",
tags$br(),
- tags$span(class = "fix-badge", "QTL PLOT"),
- " Per-chromosome idiogram + LOD curve with auto QTL labels (qTrait_ChrN)"
+ tags$span(style = "color:#3A86FF;font-weight:600;",
+ "v10: REAL QTL support intervals with LOD drop • Local peak detection • Precise flanking markers")
)
)),
fluidRow(
@@ -1527,17 +1281,17 @@ ui <- fluidPage(
div(class = "card-hd", "Mapping Parameters"),
div(class = "card-bd",
selectInput("mapping_method", "Mapping Method",
- choices = setNames(names(MAPPING_MODELS), sapply(MAPPING_MODELS, `[[`, "label")),
+ choices = setNames(names(MAPPING_MODELS), sapply(MAPPING_MODELS, `[[`, "label")),
selected = "CIM"),
uiOutput("method_desc_ui"),
sliderInput("lod_threshold", "LOD Threshold", min = 0.5, max = 10, value = 2.0, step = 0.1),
sliderInput("val_prop", "Validation Proportion", min = 0.1, max = 0.4, value = 0.2, step = 0.05),
conditionalPanel("input.mapping_method == 'CIM' || input.mapping_method == 'MQM'",
numericInput("n_cofactors", "Max Cofactors (K)", value = 10, min = 1, max = 30),
- numericInput("window_size", "Exclusion Window (±markers)", value = 5, min = 1, max = 20)
+ numericInput("window_size", "Exclusion Window (±markers)", value = 10, min = 1, max = 30)
),
- numericInput("lod_drop", "LOD Drop for Support Interval", value = 1.5, min = 0.5, max = 3.0, step = 0.5),
- numericInput("chr_lod_ncols", "Chr-LOD Plot Columns", value = 4, min = 2, max = 6),
+ numericInput("lod_drop", "LOD Drop for Support Interval", value = 1.5, min = 0.5, max = 3.0, step = 0.1),
+ numericInput("min_peak_distance", "Minimum Distance Between QTL Peaks (cM)", value = 5, min = 0, max = 20, step = 1),
actionButton("run_btn", "▶ Run QTL Analysis",
class = "btn btn-primary btn-block",
style = "margin-top:10px;width:100%;"),
@@ -1546,8 +1300,9 @@ ui <- fluidPage(
conditionalPanel("input.run_permutation",
div(class = "perm-info",
tags$span(class = "speed-badge", "FAST"),
- tags$b(" Parallel Permutations"), tags$br(),
- tags$small("Uses SIM on subsampled markers. ~10× faster."),
+ tags$b(" Parallel Permutations"),
+ tags$br(),
+ tags$small("Auto-detects CPU cores. Uses SIM on 200 marker subsample for speed."),
tags$br(), tags$br(),
numericInput("n_perm", "Number of Permutations", value = 100, min = 50, max = 1000, step = 50),
numericInput("perm_alpha", "Alpha (significance)", value = 0.05, min = 0.01, max = 0.20, step = 0.01)
@@ -1587,15 +1342,14 @@ ui <- fluidPage(
)
))
),
-
- # Results Tab
+
+ # ── 2. RESULTS ─────────────────────────────────────────
tabPanel("📊 Results", icon = icon("chart-line"),
fluidRow(column(12,
div(style = "display:flex;gap:10px;flex-wrap:wrap;margin-bottom:14px;",
- downloadButton("dl_manhattan", "Manhattan Plot (PNG)", class = "btn btn-info"),
- downloadButton("dl_idiogram", "Chromosome Map (PNG)", class = "btn btn-info"),
- downloadButton("dl_chr_lod_plot", "Chr-by-Chr LOD Plot (PNG)", class = "btn btn-info"),
- downloadButton("dl_results", "Full Results (.xlsx)", class = "btn btn-success")
+ downloadButton("dl_manhattan", "Manhattan Plot (PNG)", class = "btn btn-info"),
+ downloadButton("dl_idiogram", "Chromosome Map (PNG)", class = "btn btn-info"),
+ downloadButton("dl_results", "Full Results (.xlsx)", class = "btn btn-success")
)
)),
fluidRow(
@@ -1612,16 +1366,6 @@ ui <- fluidPage(
)
)
),
- fluidRow(column(12,
- div(class = "card",
- div(class = "card-hd", "Per-Chromosome LOD Score Plot (QTL Cartographer Style)"),
- div(class = "card-bd",
- div(class = "info-box", style = "font-size:12px;margin-bottom:8px;",
- "Each panel: left = chromosome ideogram | right = LOD curve | red dashed = significance threshold | diamonds = significant QTLs"),
- uiOutput("chr_lod_plot_ui")
- )
- )
- )),
fluidRow(
column(4,
div(class = "card",
@@ -1644,8 +1388,8 @@ ui <- fluidPage(
),
fluidRow(column(12,
div(class = "card",
- div(class = "card-hd", "Significant QTLs — Above LOD Threshold (with Flanking Markers & Support Intervals)"),
- div(class = "card-bd", DTOutput("qtl_table"))
+ div(class = "card-hd", "Significant QTL Peaks — Above LOD Threshold"),
+ div(class = "card-bd", DTOutput("qtl_peaks_table"))
)
)),
fluidRow(column(12,
@@ -1655,16 +1399,17 @@ ui <- fluidPage(
)
))
),
-
- # Compare Models Tab
+
+ # ── 3. COMPARE MODELS ──────────────────────────────────
tabPanel("⚖️ Compare Models", icon = icon("balance-scale"),
fluidRow(column(12,
div(class = "card",
div(class = "card-hd", "Multi-Model Comparison"),
div(class = "card-bd",
- div(class = "info-box", "Select methods, click Run. Each runs a full genome scan independently."),
+ div(class = "info-box",
+ "Select methods, click Run. Each runs a full genome scan independently."),
checkboxGroupInput("compare_methods", "Methods to Compare:",
- choices = setNames(names(MAPPING_MODELS), sapply(MAPPING_MODELS, `[[`, "label")),
+ choices = setNames(names(MAPPING_MODELS), sapply(MAPPING_MODELS, `[[`, "label")),
selected = c("SIM", "CIM", "LASSO"), inline = TRUE),
actionButton("run_compare", "Run Selected Models", class = "btn btn-primary"),
tags$br(), tags$br(),
@@ -1688,13 +1433,13 @@ ui <- fluidPage(
),
fluidRow(column(12,
div(class = "card",
- div(class = "card-hd", "All Significant QTLs — All Models"),
+ div(class = "card-hd", "All Significant QTL Peaks — All Models"),
div(class = "card-bd", DTOutput("compare_table"))
)
))
),
-
- # Common QTL Tab
+
+ # ── 4. COMMON QTL ──────────────────────────────────────
tabPanel("🎯 Common QTL", icon = icon("bullseye"),
fluidRow(column(12,
div(class = "card",
@@ -1733,8 +1478,8 @@ ui <- fluidPage(
)
))
),
-
- # Domestication Tab
+
+ # ── 5. DOMESTICATION ───────────────────────────────────
tabPanel("🌾 Domestication", icon = icon("leaf"),
fluidRow(
column(4,
@@ -1778,26 +1523,33 @@ ui <- fluidPage(
)
))
),
-
- # About Tab
+
+ # ── 6. ABOUT ───────────────────────────────────────────
tabPanel("ℹ️ About", icon = icon("info-circle"),
fluidRow(column(10, offset = 1,
div(class = "card",
div(class = "card-bd",
- tags$h4(style = "color:#FF006E;", "QTL-Mapper v11 — Fully Fixed CIM + QTL Cartographer Plots"),
+ tags$h4(style = "color:#FF006E;", "QTL-Mapper v10 — Precision QTL Interval Mapping"),
div(class = "info-box",
- tags$b("v11 Critical Fixes:"), tags$br(),
- tags$span(class = "fix-badge", "CIM FIX #1"),
- " Window exclusion uses MARKER INDEX (not cM) — prevents over-exclusion on dense maps", tags$br(),
- tags$span(class = "fix-badge", "CIM FIX #2"),
- " Cofactor LOD gain threshold: 2.0 (QTL Cartographer standard)", tags$br(),
- tags$span(class = "fix-badge", "CIM FIX #3"),
- " Fallback to top SIM markers if stepwise yields < 2 cofactors", tags$br(),
- tags$span(class = "fix-badge", "QTL PLOT"),
- " Per-chromosome idiogram + LOD curve with auto QTL labels",
- tags$br(),
- tags$span(class = "fix-badge", "BUG FIX"),
- " Fixed string concatenation error in qtl_scan dispatcher"
+ tags$b("v10 Key Improvements:"), tags$br(),
+ "• REAL QTL support intervals: LOD drop of 1.5 with interpolation between markers", tags$br(),
+ "• Proper local peak detection: identifies true QTL peaks, not just markers", tags$br(),
+ "• Precise flanking markers: identifies markers at interval boundaries", tags$br(),
+ "• Interval size in cM: actual genetic distance between support interval boundaries", tags$br(),
+ "• Matches QTL Cartographer behavior exactly", tags$br(),
+ "• All v9 features retained: parallel permutations, colorful plots, multi-model comparison"
+ ),
+ div(class = "info-box", style = "margin-top:12px;",
+ tags$b("All Features:"), tags$br(),
+ "• 6 Mapping Models: SIM, CIM, MQM (QTL Cartographer-compatible), LASSO, Elastic Net, Random Forest", tags$br(),
+ "• LOD = (n/2)·log10(RSS0/RSS1) — matches QTL Cartographer definition", tags$br(),
+ "• Additive + Dominance effects with SE and CI", tags$br(),
+ "• Dominance class: Additive / Partial / Dominance / Overdominance", tags$br(),
+ "• LOD-drop support intervals with interpolation between markers", tags$br(),
+ "• Left & Right Flanking Markers at interval boundaries", tags$br(),
+ "• Multi-model comparison + Common QTL detection", tags$br(),
+ "• Domestication: Fst and Tajima's D", tags$br(),
+ "• Excel export with all columns"
),
tags$h5(style = "margin-top:18px;font-weight:600;color:#3A86FF;", "References"),
tags$ul(
@@ -1810,7 +1562,7 @@ ui <- fluidPage(
tags$hr(),
tags$p(style = "text-align:center;color:#6c757d;font-size:12px;",
"Contact: ashmithamganesan@gmail.com | P.sinha@cgiar.org",
- tags$br(), "QTL-Mapper v11 © 2024")
+ tags$br(), "QTL-Mapper v10 © 2024")
)
)
))
@@ -1822,30 +1574,32 @@ ui <- fluidPage(
# SERVER
# ============================================================
server <- function(input, output, session) {
-
+
rv <- reactiveValues(
- geno = NULL, pheno = NULL,
- test_geno = NULL, pop_data = NULL,
+ geno = NULL, pheno = NULL,
+ test_geno = NULL, pop_data = NULL,
marker_info = NULL,
- scan_all = NULL,
- perf = NULL, tr_pred = NULL, val_pred = NULL,
- model_fit = NULL, model_cols = NULL,
- pred_test = NULL,
+ scan_all = NULL,
+ qtl_peaks = NULL,
+ perf = NULL, tr_pred = NULL, val_pred = NULL,
+ model_fit = NULL, model_cols = NULL,
+ pred_test = NULL,
sel_metrics = NULL,
compare_res = list(),
+ compare_peaks = list(),
perm_threshold = NULL
)
-
+
lod_thr <- reactive({ input$lod_threshold })
-
- # Method description
+
+ # ---- Method description ----
output$method_desc_ui <- renderUI({
m <- input$mapping_method
if (is.null(m) || !m %in% names(MAPPING_MODELS)) return(NULL)
div(class = "info-box", style = "font-size:12px;", MAPPING_MODELS[[m]]$desc)
})
-
- # Dataset summary
+
+ # ---- Dataset summary ----
output$dataset_info_ui <- renderUI({
if (is.null(rv$geno))
return(div(class = "warn-box", "Upload genotype and phenotype files to begin."))
@@ -1870,35 +1624,34 @@ server <- function(input, output, session) {
if (!is.null(rv$perm_threshold))
div(class = "perm-info", style = "margin-top:8px;",
tags$span(class = "speed-badge", "FAST"),
- tags$b(" Permutation LOD threshold: "), round(rv$perm_threshold, 3))
+ tags$b(" Permutation LOD threshold: "),
+ round(rv$perm_threshold, 3))
)
})
-
- # File loaders
+
+ # ---- File loaders ----
observeEvent(input$geno_file, {
req(input$geno_file)
tryCatch({
res <- load_genotype_file(input$geno_file$datapath)
- rv$geno <- res$geno
- rv$marker_info <- res$marker_info
+ rv$geno <- res$geno; rv$marker_info <- res$marker_info
showNotification(paste("Loaded", res$n_markers, "markers,", res$n_samples, "samples"),
type = "message", duration = 4)
}, error = function(e) showNotification(paste("Genotype error:", e$message), type = "error"))
})
-
+
observeEvent(input$pheno_file, {
req(input$pheno_file)
tryCatch({
pd <- read.csv(input$pheno_file$datapath)
- rownames(pd) <- pd[, 1]
- pd <- pd[, -1, drop = FALSE]
+ rownames(pd) <- pd[, 1]; pd <- pd[, -1, drop = FALSE]
for (col in colnames(pd)) pd[[col]] <- as.numeric(as.character(pd[[col]]))
rv$pheno <- pd
updateSelectInput(session, "pheno_col", choices = colnames(pd), selected = colnames(pd)[1])
showNotification(paste("Loaded", ncol(pd), "traits"), type = "message", duration = 3)
}, error = function(e) showNotification(paste("Phenotype error:", e$message), type = "error"))
})
-
+
observeEvent(input$pop_file, {
req(input$pop_file)
tryCatch({
@@ -1906,7 +1659,7 @@ server <- function(input, output, session) {
showNotification(paste("Population data:", nrow(rv$pop_data), "samples"), type = "message")
}, error = function(e) showNotification(paste("Pop error:", e$message), type = "error"))
})
-
+
observeEvent(input$test_geno_file, {
req(input$test_geno_file)
tryCatch({
@@ -1915,211 +1668,177 @@ server <- function(input, output, session) {
showNotification(paste("Test genotype:", nrow(res$geno), "samples"), type = "message")
}, error = function(e) showNotification(paste("Test geno error:", e$message), type = "error"))
})
-
- # Previews
- output$prev_geno <- renderDT({ req(rv$geno); datatable(head(rv$geno, 10), options = list(scrollX = TRUE, pageLength = 5, dom = "t")) })
- output$prev_pheno <- renderDT({ req(rv$pheno); datatable(head(rv$pheno, 10), options = list(scrollX = TRUE, pageLength = 5, dom = "t")) })
- output$prev_marker_info <- renderDT({ req(rv$marker_info); datatable(rv$marker_info, options = list(scrollX = TRUE, pageLength = 10)) })
- output$prev_test_geno <- renderDT({ req(rv$test_geno); datatable(head(rv$test_geno, 10), options = list(scrollX = TRUE, pageLength = 5, dom = "t")) })
- output$prev_pred <- renderDT({ req(rv$pred_test); datatable(rv$pred_test, options = list(scrollX = TRUE, pageLength = 10)) })
- output$prev_pop <- renderDT({ req(rv$pop_data); datatable(head(rv$pop_data, 20), options = list(scrollX = TRUE, pageLength = 10)) })
-
- # MAIN ANALYSIS
+
+ # ---- Previews ----
+ output$prev_geno <- renderDT({ req(rv$geno); datatable(head(rv$geno, 10), options = list(scrollX = TRUE, pageLength = 5, dom = "t")) })
+ output$prev_pheno <- renderDT({ req(rv$pheno); datatable(head(rv$pheno, 10), options = list(scrollX = TRUE, pageLength = 5, dom = "t")) })
+ output$prev_marker_info <- renderDT({ req(rv$marker_info); datatable(rv$marker_info, options = list(scrollX = TRUE, pageLength = 10)) })
+ output$prev_test_geno <- renderDT({ req(rv$test_geno); datatable(head(rv$test_geno, 10), options = list(scrollX = TRUE, pageLength = 5, dom = "t")) })
+ output$prev_pred <- renderDT({ req(rv$pred_test); datatable(rv$pred_test, options = list(scrollX = TRUE, pageLength = 10)) })
+ output$prev_pop <- renderDT({ req(rv$pop_data); datatable(head(rv$pop_data, 20), options = list(scrollX = TRUE, pageLength = 10)) })
+
+ # ---- MAIN ANALYSIS ----
observeEvent(input$run_btn, {
req(rv$geno, rv$pheno, input$pheno_col)
showNotification(paste("Starting", input$mapping_method, "analysis..."), type = "message")
-
tryCatch({
cs <- intersect(rownames(rv$geno), rownames(rv$pheno))
- if (length(cs) == 0) {
- showNotification("No common samples!", type = "error")
- return()
- }
-
+ if (length(cs) == 0) { showNotification("No common samples!", type = "error"); return() }
X <- rv$geno[cs, , drop = FALSE]
y <- as.numeric(rv$pheno[cs, input$pheno_col])
-
set.seed(42)
tr_idx <- caret::createDataPartition(y, p = 1 - input$val_prop, list = FALSE)
- X_tr <- X[tr_idx, , drop = FALSE]
- y_tr <- y[tr_idx]
- X_v <- X[-tr_idx, , drop = FALSE]
- y_v <- y[-tr_idx]
-
+ X_tr <- X[tr_idx, , drop = FALSE]; y_tr <- y[tr_idx]
+ X_v <- X[-tr_idx, , drop = FALSE]; y_v <- y[-tr_idx]
+
withProgress(message = paste("Running", input$mapping_method, "..."), value = 0.1, {
- # Permutation threshold if requested
+
if (isTRUE(input$run_permutation)) {
- incProgress(0, detail = "Running parallel permutations...")
+ incProgress(0, detail = "Running parallel permutations (fast)...")
+ n_cores_avail <- max(1, parallel::detectCores(logical = TRUE) - 1)
+ showNotification(
+ paste0("Permutation test: ", input$n_perm, " perms on ",
+ min(n_cores_avail, 8), " cores (marker subsample 200)"),
+ type = "message", duration = 4)
rv$perm_threshold <- permutation_threshold(
X_tr, y_tr, rv$marker_info,
- method = input$mapping_method,
- n_perm = input$n_perm,
- alpha = input$perm_alpha,
+ method = input$mapping_method,
+ n_perm = input$n_perm,
+ alpha = input$perm_alpha,
n_cofactors = input$n_cofactors,
- window_size = input$window_size
- )
- updateSliderInput(session, "lod_threshold", value = round(rv$perm_threshold, 2))
+ window_size = input$window_size)
+ cat("Permutation LOD threshold:", rv$perm_threshold, "\n")
+ updateSliderInput(session, "lod_threshold",
+ value = round(rv$perm_threshold, 2))
}
incProgress(0.15)
-
- # Run QTL scan
+
rv$scan_all <- qtl_scan(X_tr, y_tr, rv$marker_info,
- method = input$mapping_method,
+ method = input$mapping_method,
n_cofactors = input$n_cofactors,
window_size = input$window_size)
- incProgress(0.5)
+ incProgress(0.35)
- # Build prediction model (Random Forest)
- nzv_i <- caret::nearZeroVar(X_tr)
+ # Find QTL peaks
+ rv$qtl_peaks <- find_qtl_peaks(rv$scan_all, lod_thr(), input$min_peak_distance)
+ if (!is.null(rv$qtl_peaks) && nrow(rv$qtl_peaks) > 0) {
+ # Add precision support intervals
+ rv$qtl_peaks <- add_precision_support_intervals(rv$qtl_peaks, rv$scan_all, input$lod_drop)
+ cat("Found", nrow(rv$qtl_peaks), "QTL peaks\n")
+ } else {
+ cat("No QTL peaks found above threshold\n")
+ }
+ incProgress(0.15)
+
+ # Prediction model
+ nzv_i <- caret::nearZeroVar(X_tr)
Xtr_rf <- if (length(nzv_i) > 0) X_tr[, -nzv_i, drop = FALSE] else X_tr
- Xv_rf <- X_v[, colnames(Xtr_rf), drop = FALSE]
+ Xv_rf <- X_v[, colnames(Xtr_rf), drop = FALSE]
rv$model_cols <- colnames(Xtr_rf)
-
+
fit <- tryCatch(
caret::train(x = Xtr_rf, y = y_tr, method = "rf",
- trControl = caret::trainControl(method = "cv", number = 5),
- tuneLength = 3),
+ trControl = caret::trainControl(method = "cv", number = 5), tuneLength = 3),
error = function(e)
caret::train(x = Xtr_rf, y = y_tr, method = "lm",
- trControl = caret::trainControl(method = "cv", number = 5))
- )
+ trControl = caret::trainControl(method = "cv", number = 5)))
rv$model_fit <- fit
-
- ytr_p <- predict(fit, Xtr_rf)
- yv_p <- predict(fit, Xv_rf)
- tr_r2 <- max(0, 1 - sum((y_tr - ytr_p)^2) / sum((y_tr - mean(y_tr))^2))
- v_r2 <- max(0, 1 - sum((y_v - yv_p)^2) / sum((y_v - mean(y_v))^2))
-
- rv$perf <- data.frame(
+
+ ytr_p <- predict(fit, Xtr_rf); yv_p <- predict(fit, Xv_rf)
+ tr_r2 <- max(0, 1 - sum((y_tr - ytr_p)^2) / sum((y_tr - mean(y_tr))^2))
+ v_r2 <- max(0, 1 - sum((y_v - yv_p)^2) / sum((y_v - mean(y_v))^2))
+
+ rv$perf <- data.frame(
Metric = c("R² Train", "R Train", "R² Validation", "R Validation"),
- Value = c(tr_r2, cor(y_tr, ytr_p), v_r2, cor(y_v, yv_p))
- )
- rv$tr_pred <- data.frame(Observed = y_tr, Predicted = ytr_p)
- rv$val_pred <- data.frame(Observed = y_v, Predicted = yv_p)
+ Value = c(tr_r2, cor(y_tr, ytr_p), v_r2, cor(y_v, yv_p)))
+ rv$tr_pred <- data.frame(Observed = y_tr, Predicted = ytr_p)
+ rv$val_pred <- data.frame(Observed = y_v, Predicted = yv_p)
incProgress(0.35)
})
-
- n_sig <- if (!is.null(rv$scan_all) && !"Message" %in% colnames(rv$scan_all))
- sum(rv$scan_all$LOD >= lod_thr() & !is.na(rv$scan_all$LOD), na.rm = TRUE) else 0
-
- showNotification(paste(input$mapping_method, "done —", n_sig, "significant QTLs"),
+
+ n_sig <- if (!is.null(rv$qtl_peaks) && nrow(rv$qtl_peaks) > 0) nrow(rv$qtl_peaks) else 0
+ showNotification(paste(input$mapping_method, "done —", n_sig, "QTL peaks detected"),
type = "message")
updateTabsetPanel(session, "nav", selected = "📊 Results")
-
}, error = function(e) {
showNotification(paste("Analysis error:", e$message), type = "error")
cat("ERROR:", e$message, "\n")
})
})
-
- # Per-chromosome LOD plot
- chr_lod_plot_reactive <- reactive({
- req(rv$scan_all, rv$marker_info)
- if ("Message" %in% colnames(rv$scan_all)) return(NULL)
- make_chr_lod_plot(
- scan_df = rv$scan_all,
- marker_info = rv$marker_info,
- lod_threshold = lod_thr(),
- trait_name = isolate(input$pheno_col),
- method = isolate(input$mapping_method),
- n_cols = input$chr_lod_ncols
- )
- })
-
- output$chr_lod_plot_ui <- renderUI({
- req(rv$scan_all, rv$marker_info)
- if ("Message" %in% colnames(rv$scan_all))
- return(div(class = "warn-box", "Run analysis first"))
- n_chr <- length(unique(as.character(rv$marker_info$Chromosome)))
- n_cols <- max(2, min(input$chr_lod_ncols, 6))
- n_rows <- ceiling(n_chr / n_cols)
- ht <- max(300, n_rows * 200)
- plotOutput("chr_lod_plot_output", height = paste0(ht, "px"))
- })
-
- output$chr_lod_plot_output <- renderPlot({
- p <- chr_lod_plot_reactive()
- req(!is.null(p))
- grid::grid.draw(p)
- }, bg = "white")
-
- # COMPARE MODELS
+
+ # ---- COMPARE MODELS ----
output$compare_status_ui <- renderUI({
if (length(rv$compare_res) == 0) return(NULL)
div(class = "good-box",
- tags$b("Completed: "), paste(names(rv$compare_res), collapse = ", "), tags$br(),
+ tags$b("Completed: "), paste(names(rv$compare_res), collapse = ", "),
+ tags$br(),
lapply(names(rv$compare_res), function(m) {
r <- rv$compare_res[[m]]
- n <- if (!is.null(r) && !"Message" %in% colnames(r))
- sum(!is.na(r$LOD) & r$LOD >= lod_thr(), na.rm = TRUE) else 0
+ n <- if (!is.null(r) && !"Message" %in% colnames(r)) {
+ peaks <- find_qtl_peaks(r, lod_thr(), input$min_peak_distance)
+ if (!is.null(peaks)) nrow(peaks) else 0
+ } else 0
tags$span(class = "model-badge", paste0(m, ": ", n, " QTLs"))
}))
})
-
+
observeEvent(input$run_compare, {
req(rv$geno, rv$pheno, input$compare_methods, input$pheno_col)
if (length(input$compare_methods) == 0) {
- showNotification("Select at least one method", type = "warning")
- return()
- }
-
- cs <- intersect(rownames(rv$geno), rownames(rv$pheno))
- X <- rv$geno[cs, , drop = FALSE]
- y <- as.numeric(rv$pheno[cs, input$pheno_col])
-
+ showNotification("Select at least one method", type = "warning"); return() }
+ cs <- intersect(rownames(rv$geno), rownames(rv$pheno))
+ X <- rv$geno[cs, , drop = FALSE]
+ y <- as.numeric(rv$pheno[cs, input$pheno_col])
set.seed(42)
tr_i <- caret::createDataPartition(y, p = 1 - input$val_prop, list = FALSE)
- X_tr <- X[tr_i, , drop = FALSE]
- y_tr <- y[tr_i]
-
+ X_tr <- X[tr_i, , drop = FALSE]; y_tr <- y[tr_i]
clist <- list()
+ peaks_list <- list()
withProgress(message = "Comparing models...", value = 0, {
for (mth in input$compare_methods) {
incProgress(1 / length(input$compare_methods), detail = paste("Running", mth))
res <- tryCatch(
qtl_scan(X_tr, y_tr, rv$marker_info, method = mth,
n_cofactors = input$n_cofactors, window_size = input$window_size),
- error = function(e) {
- cat("Compare error", mth, ":", e$message, "\n")
- NULL
+ error = function(e) { cat("Compare error", mth, ":", e$message, "\n"); NULL })
+ if (!is.null(res) && !"Message" %in% colnames(res)) {
+ clist[[mth]] <- res
+ peaks <- find_qtl_peaks(res, lod_thr(), input$min_peak_distance)
+ if (!is.null(peaks) && nrow(peaks) > 0) {
+ peaks <- add_precision_support_intervals(peaks, res, input$lod_drop)
+ peaks_list[[mth]] <- peaks
}
- )
- if (!is.null(res)) clist[[mth]] <- res
+ }
}
})
rv$compare_res <- clist
+ rv$compare_peaks <- peaks_list
showNotification(paste("Compared", length(clist), "models"), type = "message")
})
-
+
output$compare_idiogram <- renderPlot({
- req(length(rv$compare_res) > 0, rv$marker_info)
- valid_res <- Filter(function(r) !is.null(r) && !"Message" %in% colnames(r), rv$compare_res)
- req(length(valid_res) > 0)
- make_idiogram_ggplot(valid_res, rv$marker_info, lod_thr())
+ req(length(rv$compare_peaks) > 0, rv$marker_info)
+ make_idiogram_ggplot(rv$compare_peaks, rv$marker_info, lod_thr())
}, bg = "white")
-
+
output$compare_bar <- renderPlotly({
- req(length(rv$compare_res) > 0)
+ req(length(rv$compare_peaks) > 0)
rows <- list()
- for (mth in names(rv$compare_res)) {
- r <- rv$compare_res[[mth]]
- if (is.null(r) || "Message" %in% colnames(r)) next
- sig <- r[!is.na(r$LOD) & r$LOD >= lod_thr(), ]
- if (nrow(sig) == 0) next
- for (ch in unique(sig$Chromosome))
+ for (mth in names(rv$compare_peaks)) {
+ peaks <- rv$compare_peaks[[mth]]
+ if (is.null(peaks) || nrow(peaks) == 0) next
+ for (ch in unique(peaks$Chromosome))
rows <- c(rows, list(data.frame(Method = mth, Chromosome = as.character(ch),
- Count = sum(sig$Chromosome == ch))))
+ Count = sum(peaks$Chromosome == ch))))
}
if (length(rows) == 0)
return(plot_ly() %>% layout(title = "No significant QTLs",
paper_bgcolor = "white", plot_bgcolor = "white"))
-
df <- do.call(rbind, rows)
df$Chromosome <- factor(df$Chromosome, levels = sort(unique(df$Chromosome)))
- n_m <- length(unique(df$Method))
+ n_m <- length(unique(df$Method))
vivid <- c("#FF006E","#3A86FF","#06D6A0","#FFBE0B","#FB5607","#8338EC")
mcols <- vivid[seq_len(n_m)]
-
plot_ly(df, x = ~Chromosome, y = ~Count, color = ~Method, type = "bar",
colors = mcols) %>%
layout(barmode = "group",
@@ -2132,55 +1851,52 @@ server <- function(input, output, session) {
paper_bgcolor = "white", plot_bgcolor = "white",
legend = list(font = list(color = "grey20")))
})
-
+
output$compare_table <- renderDT({
- req(length(rv$compare_res) > 0)
+ req(length(rv$compare_peaks) > 0)
rows <- list()
- for (mth in names(rv$compare_res)) {
- r <- rv$compare_res[[mth]]
- if (is.null(r) || "Message" %in% colnames(r)) next
- sig <- r[!is.na(r$LOD) & r$LOD >= lod_thr(), ]
- if (nrow(sig) == 0) next
- sig <- add_support_intervals(sig, r, input$lod_drop)
- sig$Model_Used <- mth
- keep_cols <- intersect(c("Marker","Chromosome","Position","LOD",
- "PVE_Marker_Percent","Additive_Effect",
- "Left_Flanking_Marker","Right_Flanking_Marker","Model_Used"),
- colnames(sig))
- rows <- c(rows, list(sig[, keep_cols, drop = FALSE]))
+ for (mth in names(rv$compare_peaks)) {
+ peaks <- rv$compare_peaks[[mth]]
+ if (is.null(peaks) || nrow(peaks) == 0) next
+ peaks$Model_Used <- mth
+ rows <- c(rows, list(peaks[, c("Marker","Chromosome","Position","LOD",
+ "PVE_Marker_Percent","Additive_Effect",
+ "Interval_Start_cM","Interval_End_cM",
+ "Interval_Size_cM","Left_Flanking_Marker",
+ "Right_Flanking_Marker","Model_Used")]))
}
if (length(rows) == 0) return(datatable(data.frame(Status = "No QTLs found")))
df <- do.call(rbind, rows)
- df$N_Models <- as.integer(table(df$Marker)[df$Marker])
- datatable(df[order(-df$N_Models, -df$LOD), ],
+ datatable(df[order(-df$LOD), ],
options = list(scrollX = TRUE, pageLength = 15, dom = "Blfrtip"),
rownames = FALSE, class = "cell-border stripe hover") %>%
- formatRound(c("LOD","PVE_Marker_Percent","Position","Additive_Effect"), 3)
+ formatRound(c("LOD","PVE_Marker_Percent","Position","Additive_Effect",
+ "Interval_Start_cM","Interval_End_cM","Interval_Size_cM"), 2)
})
-
- # COMMON QTL
+
+ # ---- COMMON QTL ----
common_qtl_data <- reactive({
- req(length(rv$compare_res) > 0)
- find_common_qtl(rv$compare_res, lod_thr(), min_models = input$min_models)
+ req(length(rv$compare_peaks) > 0)
+ find_common_qtl(rv$compare_peaks, lod_thr(), min_models = input$min_models)
})
-
+
output$common_qtl_summary_ui <- renderUI({
cq <- common_qtl_data()
if (is.null(cq) || nrow(cq) == 0)
return(div(class = "warn-box", "No common QTLs. Run Compare Models first."))
n_all <- nrow(cq)
- n_max <- sum(cq$N_Models_Detected == length(rv$compare_res), na.rm = TRUE)
+ n_max <- sum(cq$N_Models_Detected == length(rv$compare_peaks), na.rm = TRUE)
div(class = "good-box",
- tags$b(n_all), " common QTLs | ", tags$b(n_max), " in ALL models", tags$br(),
+ tags$b(n_all), " common QTLs | ", tags$b(n_max), " in ALL models",
+ tags$br(),
tags$small("Chromosomes: ", paste(sort(unique(cq$Chromosome)), collapse = ", ")))
})
-
+
output$common_qtl_table <- renderDT({
cq <- common_qtl_data()
if (is.null(cq) || nrow(cq) == 0)
return(datatable(data.frame(Status = "Run Compare Models tab first"),
options = list(dom = "t")))
- cq <- add_flanking_to_df(cq, rv$marker_info)
num_cols <- intersect(
c("Position","Mean_LOD","Max_LOD","Mean_PVE","Mean_Add_Eff",
paste0("LOD_", names(rv$compare_res))),
@@ -2189,15 +1905,15 @@ server <- function(input, output, session) {
rownames = FALSE, class = "cell-border stripe hover") %>%
formatRound(num_cols, 3) %>%
formatStyle("N_Models_Detected",
- background = styleColorBar(range(cq$N_Models_Detected, na.rm = TRUE), "#06D6A0"),
- backgroundSize = "100% 80%", backgroundRepeat = "no-repeat",
- backgroundPosition = "center") %>%
+ background = styleColorBar(range(cq$N_Models_Detected, na.rm = TRUE), "#06D6A0"),
+ backgroundSize = "100% 80%", backgroundRepeat = "no-repeat",
+ backgroundPosition = "center") %>%
formatStyle("Max_LOD",
- background = styleColorBar(range(cq$Max_LOD, na.rm = TRUE), "#FF006E"),
- backgroundSize = "100% 80%", backgroundRepeat = "no-repeat",
- backgroundPosition = "center")
+ background = styleColorBar(range(cq$Max_LOD, na.rm = TRUE), "#FF006E"),
+ backgroundSize = "100% 80%", backgroundRepeat = "no-repeat",
+ backgroundPosition = "center")
})
-
+
output$common_idiogram <- renderPlot({
cq <- common_qtl_data()
req(!is.null(cq), nrow(cq) > 0, rv$marker_info)
@@ -2205,15 +1921,15 @@ server <- function(input, output, session) {
qtl_list_cq <- setNames(lapply(n_levels, function(nl) {
sub <- cq[cq$N_Models_Detected == nl,
c("Marker","Chromosome","Position","Max_LOD","Mean_PVE","Mean_Add_Eff")]
- colnames(sub)[colnames(sub) == "Max_LOD"] <- "LOD"
- colnames(sub)[colnames(sub) == "Mean_PVE"] <- "PVE_Marker_Percent"
+ colnames(sub)[colnames(sub) == "Max_LOD"] <- "LOD"
+ colnames(sub)[colnames(sub) == "Mean_PVE"] <- "PVE_Marker_Percent"
colnames(sub)[colnames(sub) == "Mean_Add_Eff"] <- "Additive_Effect"
sub$Method <- paste0(nl, " models")
sub
}), paste0(n_levels, " model(s)"))
make_idiogram_ggplot(qtl_list_cq, rv$marker_info, lod_thr())
}, bg = "white")
-
+
output$common_bar <- renderPlotly({
cq <- common_qtl_data()
if (is.null(cq) || nrow(cq) == 0)
@@ -2222,7 +1938,7 @@ server <- function(input, output, session) {
df <- cq %>%
dplyr::group_by(Chromosome, N_Models_Detected) %>%
dplyr::summarise(Count = dplyr::n(), .groups = "drop")
- df$Label <- paste0(df$N_Models_Detected, " model(s)")
+ df$Label <- paste0(df$N_Models_Detected, " model(s)")
df$Chromosome <- factor(df$Chromosome, levels = sort(unique(as.character(df$Chromosome))))
plot_ly(df, x = ~Chromosome, y = ~Count, color = ~Label, type = "bar",
colors = c("#FF006E","#FB5607","#FFBE0B","#06D6A0","#3A86FF","#8338EC")) %>%
@@ -2236,22 +1952,25 @@ server <- function(input, output, session) {
paper_bgcolor = "white", plot_bgcolor = "white",
legend = list(orientation = "h", y = -0.18, font = list(color = "grey20")))
})
-
- # MAIN PLOTS
+
+ # ---- MAIN PLOTS ----
output$manhattan_plot <- renderPlotly({
req(rv$scan_all)
- make_plotly_manhattan(rv$scan_all, lod_thr(),
+ make_plotly_manhattan(rv$scan_all, lod_thr(), rv$qtl_peaks,
paste(input$mapping_method, "Manhattan Plot"))
})
-
+
output$idiogram_plot <- renderPlot({
- req(rv$scan_all, rv$marker_info)
- valid <- if (!is.null(rv$scan_all) && !"Message" %in% colnames(rv$scan_all))
- list(setNames(list(rv$scan_all), input$mapping_method)) else list()
- if (length(valid) == 0) ggplot() + labs(title = "Run analysis first") + theme_bw()
- else make_idiogram_ggplot(valid[[1]], rv$marker_info, lod_thr())
+ req(rv$marker_info)
+ valid_peaks <- if (!is.null(rv$qtl_peaks) && nrow(rv$qtl_peaks) > 0)
+ list(setNames(list(rv$qtl_peaks), input$mapping_method)) else list()
+ if (length(valid_peaks) == 0) {
+ ggplot() + labs(title = "Run analysis first") + theme_bw()
+ } else {
+ make_idiogram_ggplot(valid_peaks, rv$marker_info, lod_thr())
+ }
}, bg = "white")
-
+
output$perf_plot <- renderPlotly({
req(rv$perf)
clrs <- c("#FF006E","#06D6A0","#FF006E","#06D6A0")
@@ -2265,7 +1984,7 @@ server <- function(input, output, session) {
xaxis = list(title = "", tickangle = 15, color = "grey20"),
paper_bgcolor = "white", plot_bgcolor = "white")
})
-
+
output$reg_train <- renderPlotly({
req(rv$tr_pred)
rng <- range(c(rv$tr_pred$Observed, rv$tr_pred$Predicted), na.rm = TRUE)
@@ -2276,11 +1995,11 @@ server <- function(input, output, session) {
line = list(color = "#3A86FF", dash = "dash", width = 2),
showlegend = FALSE) %>%
layout(title = list(text = "Training Set", font = list(size = 13, color = "grey10")),
- xaxis = list(title = "Observed", gridcolor = "rgba(0,0,0,0.08)", color = "grey20"),
+ xaxis = list(title = "Observed", gridcolor = "rgba(0,0,0,0.08)", color = "grey20"),
yaxis = list(title = "Predicted", gridcolor = "rgba(0,0,0,0.08)", color = "grey20"),
paper_bgcolor = "white", plot_bgcolor = "white")
})
-
+
output$reg_val <- renderPlotly({
req(rv$val_pred)
rng <- range(c(rv$val_pred$Observed, rv$val_pred$Predicted), na.rm = TRUE)
@@ -2291,73 +2010,60 @@ server <- function(input, output, session) {
line = list(color = "#FF006E", dash = "dash", width = 2),
showlegend = FALSE) %>%
layout(title = list(text = "Validation Set", font = list(size = 13, color = "grey10")),
- xaxis = list(title = "Observed", gridcolor = "rgba(0,0,0,0.08)", color = "grey20"),
+ xaxis = list(title = "Observed", gridcolor = "rgba(0,0,0,0.08)", color = "grey20"),
yaxis = list(title = "Predicted", gridcolor = "rgba(0,0,0,0.08)", color = "grey20"),
paper_bgcolor = "white", plot_bgcolor = "white")
})
-
- # QTL TABLES
- output$qtl_table <- renderDT({
- req(rv$scan_all)
- if ("Message" %in% colnames(rv$scan_all))
- return(datatable(data.frame(Status = rv$scan_all$Message[1]), options = list(dom = "t")))
- sig <- rv$scan_all[!is.na(rv$scan_all$LOD) & rv$scan_all$LOD >= lod_thr(), , drop = FALSE]
- if (nrow(sig) == 0)
- return(datatable(data.frame(Status = paste("No QTLs above LOD", lod_thr())),
+
+ # ---- QTL TABLES ----
+ output$qtl_peaks_table <- renderDT({
+ req(rv$qtl_peaks)
+ if (is.null(rv$qtl_peaks) || nrow(rv$qtl_peaks) == 0)
+ return(datatable(data.frame(Status = paste("No QTL peaks above LOD", lod_thr())),
options = list(dom = "t")))
- sig <- add_support_intervals(sig, rv$scan_all, input$lod_drop)
- sig <- sig[order(-sig$LOD), ]
- show_cols <- intersect(
- c("Marker","Chromosome","Position","LOD","P_Value",
- "PVE_Marker_Percent","PVE_CIM_Percent",
- "Additive_Effect","SE_Additive","CI_Lower","CI_Upper",
- "Dominance_Effect","SE_Dominance","Dominance_Ratio","Dominance_Class",
- "N_Cofactors","N_Samples","Method",
- "Interval_Start","Interval_End","Interval_Size_cM",
- "Left_Flanking_Marker","Right_Flanking_Marker"),
- colnames(sig))
- datatable(sig[, show_cols],
+
+ show_cols <- c("Marker","Chromosome","Position","LOD","P_Value",
+ "PVE_Marker_Percent","Additive_Effect","SE_Additive",
+ "CI_Lower","CI_Upper","Dominance_Class",
+ "Interval_Start_cM","Interval_End_cM","Interval_Size_cM",
+ "Left_Flanking_Marker","Right_Flanking_Marker",
+ "Left_Interval_Marker","Right_Interval_Marker","N_Samples")
+ show_cols <- intersect(show_cols, colnames(rv$qtl_peaks))
+
+ datatable(rv$qtl_peaks[, show_cols],
options = list(scrollX = TRUE, pageLength = 10, dom = "Blfrtip"),
rownames = FALSE, class = "cell-border stripe hover") %>%
- formatRound(intersect(c("LOD","PVE_Marker_Percent","PVE_CIM_Percent",
- "Additive_Effect","SE_Additive","CI_Lower","CI_Upper",
- "Dominance_Ratio","Interval_Start","Interval_End",
- "Interval_Size_cM"), show_cols), 3) %>%
+ formatRound(intersect(c("LOD","PVE_Marker_Percent","Position","Additive_Effect",
+ "SE_Additive","CI_Lower","CI_Upper",
+ "Interval_Start_cM","Interval_End_cM","Interval_Size_cM"),
+ show_cols), 2) %>%
formatSignif(intersect("P_Value", show_cols), digits = 3)
})
-
+
output$full_scan_table <- renderDT({
req(rv$scan_all)
if ("Message" %in% colnames(rv$scan_all))
return(datatable(data.frame(Status = rv$scan_all$Message[1]), options = list(dom = "t")))
- fs <- add_flanking_to_df(rv$scan_all, rv$marker_info)
- datatable(fs,
+ datatable(rv$scan_all,
options = list(scrollX = TRUE, pageLength = 15, dom = "Blfrtip",
order = list(list(4, "desc"))),
rownames = FALSE, class = "cell-border stripe hover") %>%
- formatRound(intersect(c("LOD","PVE_Marker_Percent","Additive_Effect"), colnames(fs)), 3) %>%
- formatSignif(intersect("P_Value", colnames(fs)), digits = 3)
+ formatRound(intersect(c("LOD","PVE_Marker_Percent","Additive_Effect"),
+ colnames(rv$scan_all)), 3) %>%
+ formatSignif(intersect("P_Value", colnames(rv$scan_all)), digits = 3)
})
-
- # PREDICT TEST
+
+ # ---- PREDICT TEST ----
observeEvent(input$pred_btn, {
- if (is.null(rv$model_fit)) {
- showNotification("Run analysis first", type = "error")
- return()
- }
- if (is.null(rv$test_geno)) {
- showNotification("Upload test genotype first", type = "error")
- return()
- }
-
+ if (is.null(rv$model_fit)) { showNotification("Run analysis first", type = "error"); return() }
+ if (is.null(rv$test_geno)) { showNotification("Upload test genotype first", type = "error"); return() }
withProgress(message = "Predicting test samples...", value = 0.3, {
train_cols <- rv$model_cols
Xpred <- as.data.frame(matrix(0, nrow = nrow(rv$test_geno), ncol = length(train_cols),
dimnames = list(rownames(rv$test_geno), train_cols)))
for (col in intersect(train_cols, colnames(rv$test_geno))) {
v <- suppressWarnings(as.numeric(as.character(rv$test_geno[[col]])))
- v[is.na(v)] <- 0
- Xpred[[col]] <- v
+ v[is.na(v)] <- 0; Xpred[[col]] <- v
}
incProgress(0.5)
preds <- tryCatch(as.numeric(predict(rv$model_fit, newdata = Xpred)),
@@ -2367,19 +2073,16 @@ server <- function(input, output, session) {
})
showNotification(paste("Predicted", nrow(rv$pred_test), "samples"), type = "message")
})
-
- # DOMESTICATION
+
+ # ---- DOMESTICATION ----
observeEvent(input$run_dom, {
req(rv$geno, rv$pop_data, rv$marker_info)
tryCatch({
- cs <- intersect(rownames(rv$geno), rv$pop_data$id)
- X <- rv$geno[cs, , drop = FALSE]
- ps <- rv$pop_data[rv$pop_data$id %in% cs, ]
+ cs <- intersect(rownames(rv$geno), rv$pop_data$id)
+ X <- rv$geno[cs, , drop = FALSE]
+ ps <- rv$pop_data[rv$pop_data$id %in% cs, ]
sel <- calc_selection_metrics(X, ps, rv$marker_info)
- if (is.null(sel)) {
- showNotification("No selection metrics computed", type = "error")
- return()
- }
+ if (is.null(sel)) { showNotification("No selection metrics computed", type = "error"); return() }
sel$Significant <- (!is.na(sel$Fst) & sel$Fst > input$fst_thr) |
(!is.na(sel$Tajima_D_Dom) & sel$Tajima_D_Dom < input$tajima_thr)
rv$sel_metrics <- sel
@@ -2387,40 +2090,35 @@ server <- function(input, output, session) {
type = "message")
}, error = function(e) showNotification(paste("Domestication error:", e$message), type = "error"))
})
-
+
make_dom_plotly <- function(data, y_col, title, threshold, y_lab = y_col) {
- blank <- plot_ly() %>% layout(title = title, paper_bgcolor = "white", plot_bgcolor = "white")
+ blank <- plot_ly() %>%
+ layout(title = title, paper_bgcolor = "white", plot_bgcolor = "white")
if (is.null(data) || nrow(data) == 0) return(blank)
-
pd <- data[!is.na(data[[y_col]]) & !is.na(data$Chromosome), ]
if (nrow(pd) == 0) return(blank)
-
pd$Chromosome <- as.character(pd$Chromosome)
- chroms <- sort(unique(pd$Chromosome), method = "radix")
-
+ chroms <- sort(unique(pd$Chromosome), method = "radix")
offsets <- setNames(numeric(length(chroms)), chroms)
for (i in seq_along(chroms)) {
- if (i == 1) {
- offsets[chroms[1]] <- 0
- } else {
- offsets[chroms[i]] <- offsets[chroms[i-1]] +
- max(pd$Position[pd$Chromosome == chroms[i-1]], na.rm = TRUE) * 1.05
- }
+ if (i == 1) { offsets[chroms[1]] <- 0; next }
+ offsets[chroms[i]] <- offsets[chroms[i - 1]] +
+ max(pd$Position[pd$Chromosome == chroms[i - 1]], na.rm = TRUE) * 1.05
}
pd$cum_pos <- pd$Position + offsets[pd$Chromosome]
- chr_mids <- tapply(pd$cum_pos, pd$Chromosome, median, na.rm = TRUE)
- chr_clrs <- rep(c("#3A86FF","#FB5607"), length.out = length(chroms))
+ chr_mids <- tapply(pd$cum_pos, pd$Chromosome, median, na.rm = TRUE)
+ chr_clrs <- rep(c("#3A86FF","#FB5607"), length.out = length(chroms))
names(chr_clrs) <- chroms
-
pl <- plot_ly()
for (ch in chroms) {
sub <- pd[pd$Chromosome == ch, ]
- pl <- pl %>% add_trace(
+ pl <- pl %>% add_trace(
data = sub, x = ~cum_pos, y = as.formula(paste0("~", y_col)),
type = "scatter", mode = "markers", name = paste("Chr", ch), showlegend = FALSE,
marker = list(size = 6, color = chr_clrs[ch], opacity = 0.75),
text = ~paste0("", Marker, "
Chr: ", Chromosome,
- "
Pos: ", round(Position, 1), "
", y_lab, ": ", round(get(y_col), 4)),
+ "
Pos: ", round(Position, 1),
+ "
", y_lab, ": ", round(get(y_col), 4)),
hoverinfo = "text")
}
if (!is.null(threshold))
@@ -2428,7 +2126,6 @@ server <- function(input, output, session) {
x = min(pd$cum_pos, na.rm = TRUE), xend = max(pd$cum_pos, na.rm = TRUE),
y = threshold, yend = threshold,
line = list(color = "#FF006E", dash = "dash", width = 1.8), showlegend = FALSE)
-
pl %>% layout(
title = list(text = title, font = list(size = 14, color = "grey10")),
xaxis = list(title = "Chromosome", tickvals = as.list(chr_mids[chroms]),
@@ -2437,10 +2134,10 @@ server <- function(input, output, session) {
yaxis = list(title = y_lab, gridcolor = "rgba(0,0,0,0.08)", color = "grey20", zeroline = FALSE),
paper_bgcolor = "white", plot_bgcolor = "white")
}
-
- output$fst_plot <- renderPlotly({ req(rv$sel_metrics); make_dom_plotly(rv$sel_metrics, "Fst", "Fst Manhattan Plot", input$fst_thr, "Fst") })
+
+ output$fst_plot <- renderPlotly({ req(rv$sel_metrics); make_dom_plotly(rv$sel_metrics, "Fst", "Fst Manhattan Plot", input$fst_thr, "Fst") })
output$tajima_plot <- renderPlotly({ req(rv$sel_metrics); make_dom_plotly(rv$sel_metrics, "Tajima_D_Dom", "Tajima's D Manhattan Plot", input$tajima_thr, "Tajima D") })
-
+
output$sel_table <- renderDT({
req(rv$sel_metrics)
datatable(rv$sel_metrics[order(-rv$sel_metrics$Fst), ],
@@ -2448,174 +2145,91 @@ server <- function(input, output, session) {
rownames = FALSE, class = "cell-border stripe hover") %>%
formatRound(c("Fst","Pi_Dom","Pi_Wild","Tajima_D_Dom"), 4)
})
-
- # DOWNLOADS
+
+ # ---- DOWNLOADS ----
output$dl_manhattan <- downloadHandler(
filename = function() paste0("manhattan_", Sys.Date(), ".png"),
- content = function(file) {
+ content = function(file) {
req(rv$scan_all)
- pd <- rv$scan_all[!is.na(rv$scan_all$LOD) & !is.na(rv$scan_all$Position), ]
- pd$Chromosome <- as.character(pd$Chromosome)
- chroms <- sort(unique(pd$Chromosome), method = "radix")
- offsets <- setNames(numeric(length(chroms)), chroms)
- for (i in seq_along(chroms)) {
- if (i == 1) {
- offsets[chroms[1]] <- 0
- } else {
- prev <- chroms[i - 1]
- offsets[chroms[i]] <- offsets[prev] + max(pd$Position[pd$Chromosome == prev], na.rm = TRUE) * 1.05
- }
- }
- pd$cum_pos <- pd$Position + offsets[pd$Chromosome]
- pd$sig <- pd$LOD >= lod_thr()
- chr_mids <- tapply(pd$cum_pos, pd$Chromosome, median, na.rm = TRUE)
- chr_colors <- setNames(rep(c("#3A86FF","#FB5607"), length.out = length(chroms)), chroms)
-
- p <- ggplot(pd[!pd$sig, ], aes(x = cum_pos, y = LOD)) +
- geom_point(aes(color = Chromosome), size = 1.6, alpha = 0.6, show.legend = FALSE) +
- scale_color_manual(values = chr_colors) +
- {if (sum(pd$sig) > 0) list(
- geom_point(data = pd[pd$sig,], aes(x = cum_pos, y = LOD),
- color = "#FFBE0B", size = 7, alpha = 0.35, shape = 16),
- geom_point(data = pd[pd$sig,], aes(x = cum_pos, y = LOD, fill = LOD),
- size = 5, shape = 23, color = "white", stroke = 0.8),
- scale_fill_gradientn(colors = c("#FB5607","#FFBE0B","#FF006E","#8338EC"),
- name = "LOD Score")
- )} +
- geom_hline(yintercept = lod_thr(), linetype = "dashed",
- color = "#FF006E", linewidth = 1.0) +
- scale_x_continuous(breaks = chr_mids[chroms],
- labels = paste0("Chr ", chroms)) +
- labs(title = paste(input$mapping_method, "Manhattan Plot"),
- x = "Chromosome", y = "LOD Score") +
- theme_bw(base_size = 13) +
- theme(axis.text.x = element_text(angle = 45, hjust = 1),
- panel.grid.minor = element_blank(),
- panel.grid.major.x = element_blank(),
- plot.background = element_rect(fill = "white", color = NA))
+ p <- make_manhattan_ggplot(rv$scan_all, lod_thr(), rv$qtl_peaks,
+ paste(input$mapping_method, "Manhattan Plot"))
ggsave(file, plot = p, width = 14, height = 6, dpi = 200, bg = "white")
}
)
-
+
output$dl_idiogram <- downloadHandler(
filename = function() paste0("idiogram_", Sys.Date(), ".png"),
- content = function(file) {
+ content = function(file) {
req(rv$marker_info)
- res_list <- Filter(function(r) !is.null(r) && !"Message" %in% colnames(r),
- c(if (!is.null(rv$scan_all) && !"Message" %in% colnames(rv$scan_all))
- setNames(list(rv$scan_all), isolate(input$mapping_method)) else list(),
- rv$compare_res))
+ res_list <- list()
+ if (!is.null(rv$qtl_peaks) && nrow(rv$qtl_peaks) > 0) {
+ res_list[[input$mapping_method]] <- rv$qtl_peaks
+ }
+ for (m in names(rv$compare_peaks)) {
+ if (!is.null(rv$compare_peaks[[m]]) && nrow(rv$compare_peaks[[m]]) > 0) {
+ res_list[[m]] <- rv$compare_peaks[[m]]
+ }
+ }
if (length(res_list) == 0) return()
p <- make_idiogram_ggplot(res_list, rv$marker_info, lod_thr())
ggsave(file, plot = p, width = 12, height = 8, dpi = 200, bg = "white")
}
)
-
- output$dl_chr_lod_plot <- downloadHandler(
- filename = function() paste0("chr_lod_plot_", Sys.Date(), ".png"),
- content = function(file) {
- req(rv$scan_all, rv$marker_info)
- if ("Message" %in% colnames(rv$scan_all)) return()
- p <- make_chr_lod_plot(
- scan_df = rv$scan_all,
- marker_info = rv$marker_info,
- lod_threshold = lod_thr(),
- trait_name = isolate(input$pheno_col),
- method = isolate(input$mapping_method),
- n_cols = isolate(input$chr_lod_ncols)
- )
- n_chr <- length(unique(as.character(rv$marker_info$Chromosome)))
- n_cols <- max(2, min(isolate(input$chr_lod_ncols), 6))
- n_rows <- ceiling(n_chr / n_cols)
- png(file, width = n_cols * 3.5 * 100, height = n_rows * 3 * 100, res = 100)
- grid::grid.draw(p)
- dev.off()
- }
- )
-
+
output$dl_results <- downloadHandler(
- filename = function() paste0("qtl_results_v11_", Sys.Date(), ".xlsx"),
- content = function(file) {
+ filename = function() paste0("qtl_results_", Sys.Date(), ".xlsx"),
+ content = function(file) {
sheets <- list()
-
+ if (!is.null(rv$qtl_peaks) && nrow(rv$qtl_peaks) > 0) {
+ sheets[["QTL_Peaks"]] <- rv$qtl_peaks
+ }
if (!is.null(rv$scan_all) && !"Message" %in% colnames(rv$scan_all)) {
- sig <- rv$scan_all[!is.na(rv$scan_all$LOD) & rv$scan_all$LOD >= lod_thr(), ]
- if (nrow(sig) > 0) {
- sig <- add_support_intervals(sig, rv$scan_all, isolate(input$lod_drop))
- if (!"Left_Flanking_Marker" %in% colnames(sig) ||
- all(is.na(sig$Left_Flanking_Marker)))
- sig <- add_flanking_to_df(sig, rv$marker_info)
- sheets[["QTL_Significant"]] <- sig[order(-sig$LOD), ]
- }
- full_fl <- add_flanking_to_df(rv$scan_all, rv$marker_info)
- sheets[["Full_Scan"]] <- full_fl
+ sheets[["Full_Scan"]] <- rv$scan_all
}
-
if (!is.null(rv$perf)) sheets[["Performance"]] <- rv$perf
-
- for (m in names(rv$compare_res)) {
- r <- rv$compare_res[[m]]
- if (!is.null(r) && !"Message" %in% colnames(r)) {
- sig_m <- r[!is.na(r$LOD) & r$LOD >= lod_thr(), ]
- if (nrow(sig_m) > 0) {
- sig_m <- add_support_intervals(sig_m, r, isolate(input$lod_drop))
- if (!"Left_Flanking_Marker" %in% colnames(sig_m) ||
- all(is.na(sig_m$Left_Flanking_Marker)))
- sig_m <- add_flanking_to_df(sig_m, rv$marker_info)
- sheets[[paste0("Model_", m)]] <- sig_m
- }
- full_m <- add_flanking_to_df(r, rv$marker_info)
- sheets[[paste0("FullScan_", m)]] <- full_m
+ for (m in names(rv$compare_peaks)) {
+ if (!is.null(rv$compare_peaks[[m]]) && nrow(rv$compare_peaks[[m]]) > 0) {
+ sheets[[paste0("Peaks_", m)]] <- rv$compare_peaks[[m]]
}
}
-
- cq <- tryCatch(find_common_qtl(rv$compare_res, lod_thr(), isolate(input$min_models)),
+ cq <- tryCatch(find_common_qtl(rv$compare_peaks, lod_thr(), isolate(input$min_models)),
error = function(e) NULL)
- if (!is.null(cq) && nrow(cq) > 0) {
- cq <- add_flanking_to_df(cq, rv$marker_info)
- sheets[["Common_QTL"]] <- cq
- }
-
+ if (!is.null(cq) && nrow(cq) > 0) sheets[["Common_QTL"]] <- cq
sheets[["Methods"]] <- data.frame(
- Method = names(MAPPING_MODELS),
- Label = sapply(MAPPING_MODELS, `[[`, "label"),
- Description = sapply(MAPPING_MODELS, `[[`, "desc")
- )
-
+ Method = names(MAPPING_MODELS),
+ Label = sapply(MAPPING_MODELS, `[[`, "label"),
+ Description = sapply(MAPPING_MODELS, `[[`, "desc"))
if (!is.null(rv$sel_metrics) && nrow(rv$sel_metrics) > 0)
sheets[["Selection_Signatures"]] <- rv$sel_metrics
-
if (length(sheets) == 0) sheets[["Empty"]] <- data.frame(msg = "Run analysis first")
writexl::write_xlsx(sheets, file)
}
)
-
+
output$dl_pred <- downloadHandler(
filename = function() paste0("predictions_", Sys.Date(), ".xlsx"),
- content = function(file) {
+ content = function(file) {
req(rv$pred_test)
writexl::write_xlsx(list(Predictions = rv$pred_test), file)
}
)
-
+
output$dl_common_qtl <- downloadHandler(
filename = function() paste0("common_qtl_", Sys.Date(), ".xlsx"),
- content = function(file) {
- cq <- tryCatch(find_common_qtl(rv$compare_res, lod_thr(), isolate(input$min_models)),
+ content = function(file) {
+ cq <- tryCatch(find_common_qtl(rv$compare_peaks, lod_thr(), isolate(input$min_models)),
error = function(e) NULL)
- if (!is.null(cq) && nrow(cq) > 0) {
- cq <- add_flanking_to_df(cq, rv$marker_info)
+ if (!is.null(cq) && nrow(cq) > 0)
writexl::write_xlsx(list(Common_QTL = cq), file)
- } else {
+ else
writexl::write_xlsx(
list(Empty = data.frame(msg = "No common QTLs or run Compare Models first")), file)
- }
}
)
-
+
output$dl_sel <- downloadHandler(
filename = function() paste0("selection_", Sys.Date(), ".xlsx"),
- content = function(file) {
+ content = function(file) {
if (!is.null(rv$sel_metrics))
writexl::write_xlsx(list(Selection = rv$sel_metrics), file)
else