diff --git "a/app.R" "b/app.R" --- "a/app.R" +++ "b/app.R" @@ -1,17 +1,13 @@ # ============================================================ -# QTL-Mapper v10 — Fixed CIM + Flanking Markers in Excel + Per-Chromosome LOD Plots +# QTL-Mapper v11 — Fully Fixed CIM with Real QTL Detection # -# FIXES over v9: -# - CIM BUG FIX: Cofactor selection now uses lower threshold (0.1 LOD gain) -# and falls back to top-N markers by SIM LOD if stepwise fails -# - CIM window exclusion uses position-based cM distance, not marker index count -# - Flanking markers (Left_Flanking_Marker, Right_Flanking_Marker) now included -# in ALL Excel output sheets (Significant QTLs, Full Scan, Model_*, Common_QTL) -# - NEW: Per-chromosome QTL mapping plot (like QTL Cartographer output): -# • Each chromosome panel shows idiogram on left + LOD curve on right -# • QTL positions marked with arrows and labels (e.g. qGER1) -# • Significance threshold shown as dashed red line -# • Available in Results tab as "Chr-by-Chr LOD Plot" and as PNG download +# 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) # ============================================================ options(repos = c(CRAN = "https://cloud.r-project.org")) @@ -56,28 +52,26 @@ 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 = "QTL Cartographer-style single-marker regression; LOD = (n/2)*log10(RSS0/RSS1)"), - "CIM" = list(label = "Composite Interval Mapping (CIM)", - desc = "QTL Cartographer CIM: background marker cofactors selected by forward stepwise regression (min LOD gain 0.1). Falls back to top-SIM markers if stepwise yields no cofactors."), + 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."), "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 (lambda.1se)"), + desc = "L1-penalized regression; sparse model; lambda chosen by 5-fold CV"), "ENET" = list(label = "Elastic Net (L1+L2)", - desc = "Elastic net alpha=0.5; handles correlated markers; lambda by 5-fold CV"), + desc = "Elastic net alpha=0.5; handles correlated markers"), "RF" = list(label = "Random Forest QTL", - desc = "Non-parametric variable importance (%IncMSE); 1000 trees; captures non-linear effects") + desc = "Non-parametric variable importance (%IncMSE); 1000 trees") ) # ============================================================ -# QTL CARTOGRAPHER CORE FUNCTIONS +# CORE STATISTICAL FUNCTIONS # ============================================================ calc_lod <- function(fit_full, fit_null) { rss1 <- sum(residuals(fit_full)^2) @@ -103,6 +97,39 @@ 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_ + + 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) +} + # ============================================================ # FLANKING MARKER DETECTION # ============================================================ @@ -122,9 +149,6 @@ find_flanking_markers <- function(marker_name, marker_info) { ) } -# ============================================================ -# LOD SUPPORT INTERVAL -# ============================================================ add_support_intervals <- function(sig_df, all_df, lod_drop = 1.5) { sig_df$Interval_Start <- NA_real_ sig_df$Interval_End <- NA_real_ @@ -144,9 +168,6 @@ add_support_intervals <- function(sig_df, all_df, lod_drop = 1.5) { sig_df$Interval_Start[i] <- pos_i sig_df$Interval_End[i] <- pos_i sig_df$Interval_Size_cM[i] <- 0 - fl <- find_flanking_in_sorted(mk, cd) - sig_df$Left_Flanking_Marker[i] <- fl$left - sig_df$Right_Flanking_Marker[i] <- fl$right next } thr <- pk - lod_drop @@ -159,27 +180,10 @@ add_support_intervals <- function(sig_df, all_df, lod_drop = 1.5) { 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) - below <- cd[cd$Position < int_start, ] - above <- cd[cd$Position > int_end, ] - sig_df$Left_Flanking_Marker[i] <- if (nrow(below) > 0) below$Marker[nrow(below)] else mk - sig_df$Right_Flanking_Marker[i] <- if (nrow(above) > 0) above$Marker[1] else mk } sig_df } -find_flanking_in_sorted <- function(marker_name, sorted_cd) { - idx <- which(sorted_cd$Marker == marker_name) - if (length(idx) == 0) return(list(left = NA_character_, right = NA_character_)) - idx <- idx[1] - list( - left = if (idx > 1) sorted_cd$Marker[idx - 1] else NA_character_, - right = if (idx < nrow(sorted_cd)) sorted_cd$Marker[idx + 1] else NA_character_ - ) -} - -# ============================================================ -# Add flanking markers to ANY scan result (full scan or sig) -# ============================================================ 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_ @@ -246,55 +250,32 @@ load_genotype_file <- function(filepath) { } # ============================================================ -# 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 +# SIM - Simple Interval Mapping (Baseline) # ============================================================ qtl_scan_sim <- function(X, y, marker_info) { - cat("\n--- SIM ---\n") + cat("\n--- SIM Scanning ---\n") valid <- !is.na(y) - X <- X[valid, , drop = FALSE]; y <- y[valid] + X <- X[valid, , drop = FALSE] + y <- y[valid] + + # Remove near-zero variance markers 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) @@ -303,122 +284,200 @@ 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 — FIXED VERSION -# Key fixes: -# 1. Cofactor selection threshold lowered to 0.1 LOD gain (was 0.5) -# 2. Fallback: if stepwise finds 0 cofactors, use top-K markers by SIM LOD -# 3. Window exclusion uses cM distance (window_cM), not marker count -# 4. Complete-cases check per marker (not global) to maximize marker coverage +# 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) # ============================================================ qtl_scan_cim <- function(X, y, marker_info, n_cofactors = 10, window_size = 10) { - cat("\n--- CIM (FIXED) ---\n") + cat("\n=== CIM (FIXED) ===\n") + + # Clean data valid <- !is.na(y) - X <- X[valid, , drop = FALSE]; y <- y[valid] + X <- X[valid, , drop = FALSE] + y <- y[valid] + + # Remove constant markers nzv <- apply(X, 2, function(x) length(unique(na.omit(x))) < 2) X <- X[, !nzv, drop = FALSE] - n <- length(y) - max_k <- max(3, min(n_cofactors, floor(sqrt(n)))) - - # --- Step 1: Forward stepwise cofactor selection with LOW threshold --- - cat(" Selecting cofactors (max_k =", max_k, ")...\n") + + 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 - + for (step in seq_len(max_k)) { if (length(remaining) == 0) break + best_m <- NULL best_lod <- base_lod - + best_fit <- null_fit + for (m in remaining) { tryCatch({ + # Test this marker as additional cofactor cand <- c(cofactors, m) - Xc <- as.data.frame(X[, cand, drop = FALSE]) - Xc[is.na(Xc)] <- 0 - lod <- calc_lod(lm(y ~ ., data = Xc), null_fit) - if (lod > best_lod) { best_lod <- lod; best_m <- 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 + } }, error = function(e) NULL) } - - # FIX: Use 0.1 LOD gain threshold (was 0.5 — too strict) - if (!is.null(best_m) && (best_lod - base_lod) > 0.1) { + + # 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 - cat(" Cofactor", length(cofactors), ":", best_m, " LOD:", round(best_lod, 2), "\n") + 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 cofactors found --- - if (length(cofactors) == 0) { - cat(" Stepwise found 0 cofactors — using fallback: top SIM LOD markers\n") + + # ============================================================ + # 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)) { + if (!"Message" %in% colnames(sim_res) && nrow(sim_res) > 0) { sim_res <- sim_res[order(-sim_res$LOD), ] - cofactors <- head(sim_res$Marker[sim_res$Marker %in% colnames(X)], max_k) + 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: Window size in cM --- - # Convert marker-count window to cM: use median inter-marker distance * window_size - chr_list <- sort(unique(as.character(marker_info$Chromosome))) - all_gaps <- numeric(0) - for (ch in chr_list) { - mk_ch <- marker_info[as.character(marker_info$Chromosome) == ch, ] + + 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), ] - if (nrow(mk_ch) > 1) all_gaps <- c(all_gaps, diff(mk_ch$Position)) + chr_marker_order[[as.character(chr)]] <- mk_ch$Marker } - med_gap <- if (length(all_gaps) > 0) median(all_gaps[all_gaps > 0], na.rm = TRUE) else 5 - window_cM <- window_size * med_gap - cat(" Exclusion window:", round(window_cM, 1), "cM\n") - - # --- Step 4: 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] + # Get marker data + 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_cM on same chromosome - cof_pos <- sapply(cofactors, function(cf) { - cf_mi <- marker_info[marker_info$Marker == cf, ] - if (nrow(cf_mi) == 0) return(Inf) - if (as.character(cf_mi$Chromosome[1]) != m_chr) return(Inf) - cf_mi$Position[1] - }) - active_cof <- cofactors[abs(cof_pos - m_pos) > window_cM] - + + # ============================================================ + # 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 + } + } + tryCatch({ + # Build model df <- data.frame(y = pv, focal = gv) + if (length(active_cof) > 0) { - # Only include cofactors that are in X and have no NA for these samples valid_cof <- active_cof[active_cof %in% colnames(X)] if (length(valid_cof) > 0) { cm <- X[ok, valid_cof, drop = FALSE] @@ -428,249 +487,382 @@ qtl_scan_cim <- function(X, y, marker_info, n_cofactors = 10, window_size = 10) active_cof <- character(0) } } + df <- df[complete.cases(df), ] if (nrow(df) < 8) next - - if (length(active_cof) > 0 && length(intersect(active_cof, colnames(X))) > 0) { + + # 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)) - if (length(valid_cof_names) > 0) { - fit_full <- lm(as.formula( - paste("y ~ focal +", paste(valid_cof_names, collapse = "+"))), data = df) - fit_null <- lm(as.formula( - paste("y ~", paste(valid_cof_names, collapse = "+"))), data = df) - } else { - fit_full <- lm(y ~ focal, data = df) - fit_null <- lm(y ~ 1, data = 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) } else { 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 <- coef(summary(fit_full)) + + 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")) + if (is.null(res) || nrow(res) == 0) + return(data.frame(Message = "CIM: no results")) + + cat(" CIM complete —", nrow(res), "markers scanned\n") res[order(res$Chromosome, res$Position), ] } # ============================================================ -# MQM +# MQM - Multiple QTL Model # ============================================================ qtl_scan_mqm <- function(X, y, marker_info, n_cofactors = 10, window_size = 10) { - cat("\n--- MQM ---\n") + cat("\n=== MQM ===\n") + + # First run SIM to identify candidate QTLs 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))) - sim_res <- sim_res[order(-sim_res$LOD), ] + + n <- length(y) + max_k <- min(n_cofactors, floor(sqrt(n)), 15) + + # Get top SIM markers + sim_res <- sim_res[order(-sim_res$LOD), ] candidates <- head(sim_res$Marker[sim_res$Marker %in% colnames(X)], max_k * 2) - selected <- character(0) + + # Forward selection for MQM + selected <- character(0) + null_fit <- lm(y ~ 1) + base_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), lm(y ~ 1)) + Xc <- as.data.frame(X[, test_set, drop = FALSE]) + Xc[is.na(Xc)] <- 0 + lod_full <- calc_lod(lm(y ~ ., data = Xc), null_fit) + 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), lm(y ~ 1)) - } 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), null_fit) + } else { + lod_base <- 0 + } + gain <- lod_full - lod_base if (gain >= 2.0) { selected <- test_set - cat(" MQM QTL:", cand, " gain:", round(gain, 2), "\n") + base_lod <- lod_full + cat(" MQM added:", cand, "| LOD:", round(lod_full, 2), + "| Gain:", round(gain, 2), "\n") } }, error = function(e) NULL) } + cat(" MQM selected", length(selected), "QTLs\n") - - # cM window - all_gaps <- numeric(0) - for (ch in sort(unique(as.character(marker_info$Chromosome)))) { - mk_ch <- marker_info[as.character(marker_info$Chromosome) == ch, ] + + # 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), ] - if (nrow(mk_ch) > 1) all_gaps <- c(all_gaps, diff(mk_ch$Position)) + chr_marker_order[[as.character(chr)]] <- mk_ch$Marker } - med_gap <- if (length(all_gaps) > 0) median(all_gaps[all_gaps > 0], na.rm = TRUE) else 5 - window_cM <- window_size * med_gap - - res_list <- vector("list", ncol(X)); names(res_list) <- colnames(X) + + # Scan each marker + 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] - cof_pos <- sapply(selected, function(cf) { - cf_mi <- marker_info[marker_info$Marker == cf, ] - if (nrow(cf_mi) == 0) return(Inf) - if (as.character(cf_mi$Chromosome[1]) != m_chr) return(Inf) - cf_mi$Position[1] - }) - active_cof <- selected[abs(cof_pos - m_pos) > window_cM] + + 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 + } + } + 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 + cm <- X[ok, valid_cof, drop = FALSE] + cm[is.na(cm)] <- 0 df <- cbind(df, as.data.frame(cm)) - } else active_cof <- character(0) + } else { + active_cof <- character(0) + } } + 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) + 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) } 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 <- coef(summary(fit_full)) + + 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 +# LASSO QTL # ============================================================ qtl_scan_lasso <- function(X, y, marker_info) { - 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) + 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) 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-8, ] + cdf <- cdf[abs(cdf$Effect) > 1e-6, ] + 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), ] - mx <- max(abs(cdf$Effect)) - cdf$LOD <- 5 * abs(cdf$Effect) / mx + 1 + + # Convert effect size to LOD-like score + mx <- max(abs(cdf$Effect)) + cdf$LOD <- 10 * abs(cdf$Effect) / mx 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) { - 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) + 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) 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-8, ] + cdf <- cdf[abs(cdf$Effect) > 1e-6, ] + 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 <- 5 * abs(cdf$Effect) / mx + 1 + + mx <- max(abs(cdf$Effect)) + cdf$LOD <- 10 * abs(cdf$Effect) / mx 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) { - 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, + 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, 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")] } # ============================================================ @@ -678,13 +870,21 @@ qtl_scan_rf <- function(X, y, marker_info) { # ============================================================ qtl_scan <- function(X, y, marker_info, method = "CIM", n_cofactors = 10, window_size = 10) { - cat("\n=== QTL SCAN | Method:", method, "===\n") + cat("\n" + paste(rep("=", 60), collapse = ""), "\n") + cat("QTL SCAN | Method:", method, "\n") + cat(paste(rep("=", 60), collapse = ""), "\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(" Markers after NZV:", ncol(X), "\n") - switch(method, + + cat(" Samples after cleaning:", length(y), "\n") + cat(" Markers after cleaning:", ncol(X), "\n") + + result <- 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), @@ -693,46 +893,68 @@ 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 } # ============================================================ -# FAST PARALLEL PERMUTATION THRESHOLD +# PERMUTATION THRESHOLD (Parallel) # ============================================================ 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(" Running", n_perm, "PARALLEL permutations...\n") + cat("\n=== PERMUTATION TEST ===\n") + cat(" Method:", method, "| Permutations:", n_perm, "| Alpha:", alpha, "\n") + + # Subsample markers for speed if too many 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") } else { - X_perm <- X; mi_perm <- marker_info + X_perm <- X + mi_perm <- marker_info } + n_cores <- max(1, min(parallel::detectCores(logical = TRUE) - 1, 8)) cat(" Using", n_cores, "cores\n") - + one_perm <- function(seed) { set.seed(seed) - yp <- sample(y) + 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)) + 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)) + 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 } @@ -747,22 +969,29 @@ find_common_qtl <- function(compare_res, lod_threshold, min_models = 2) { 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 } + if (nrow(sig) > 0) { + sig$Model <- mth + sig_list[[mth]] <- sig + } } + 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, ] @@ -773,32 +1002,36 @@ find_common_qtl <- function(compare_res, lod_threshold, min_models = 2) { } # ============================================================ -# PER-CHROMOSOME LOD PLOT (QTL Cartographer style) -# — Each chromosome: idiogram bar on left, LOD curve on right -# — Significant QTLs marked with arrows + labels (qTRAIT_chrN) +# PER-CHROMOSOME LOD PLOT (QTL Cartographer Style) # ============================================================ 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)) + + if (is.null(scan_df) || "Message" %in% colnames(scan_df)) { return(ggplot() + labs(title = "No data") + 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 = "No scan data") + theme_bw()) + } + pd$Chromosome <- as.character(pd$Chromosome) - chroms <- sort(unique(pd$Chromosome), method = "radix") - n_chr <- length(chroms) + chroms <- sort(unique(pd$Chromosome), method = "radix") + n_chr <- length(chroms) n_rows_layout <- ceiling(n_chr / n_cols) - - # Auto QTL naming: qTRAIT_chrN_rank + + # 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))) { @@ -808,182 +1041,178 @@ make_chr_lod_plot <- function(scan_df, marker_info, lod_threshold = 2.0, } } peak_rows <- peak_rows[order(-peak_rows$LOD), ] - chr_num <- gsub("[^0-9A-Za-z]", "", ch) - for (k in seq_len(nrow(peak_rows))) { - lbl <- paste0("q", substr(toupper(trait_name), 1, 3), chr_num, - if (nrow(peak_rows) > 1) k else "") + 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 - - # Markers per chromosome for idiogram + + # 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), + 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 - + # 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, ] + ci <- chr_info[chr_info$Chromosome == ch, ] chr_len <- ci$chr_end - ci$chr_start - ch_sig <- ch_pd[ch_pd$LOD >= lod_threshold & nchar(ch_pd$QTL_Label) > 0, ] - - # Map position to y-axis (flip: top = 0 cM) - pos_range <- c(ci$chr_start, ci$chr_end) - lod_max <- global_lod_max - - # Chromosome teal color from reference image - chr_color <- "#4DB6AC" - + 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 (left side, x < 0) ---- - # Chromosome body + # Chromosome ideogram annotate("rect", - xmin = -lod_max * 0.28, xmax = -lod_max * 0.08, - ymin = ci$chr_start, ymax = ci$chr_end, + 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 + # Centromere band (approx 38-45% of chromosome length) annotate("rect", - xmin = -lod_max * 0.28, xmax = -lod_max * 0.08, + 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 = -lod_max * 0.28, xmax = -lod_max * 0.08, + 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 = -lod_max * 0.28, xmax = -lod_max * 0.08, + 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 on idiogram ---- + # Marker tick marks geom_segment(data = marker_info[marker_info$Chromosome == ch, ], - aes(x = -lod_max * 0.08, xend = -lod_max * 0.04, + 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 ---- + # LOD curve geom_line(color = chr_color, linewidth = 1.0, alpha = 0.9) + - # Area fill under LOD curve geom_area(fill = chr_color, alpha = 0.18) + - # ---- Significance threshold ---- + # Significance threshold geom_vline(xintercept = lod_threshold, linetype = "dashed", color = "#E53935", linewidth = 0.7, alpha = 0.85) + - # ---- Significant QTL markers ---- + # 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 ---- + # QTL labels {if (nrow(ch_sig) > 0) ggrepel::geom_label_repel( - data = ch_sig, + data = ch_sig, aes(x = LOD, y = Position, label = QTL_Label), - size = 2.8, - fontface = "bold", - fill = "white", - color = "#B71C1C", + 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 = lod_max * 0.05, - min.segment.length = 0, - max.overlaps = 20, - inherit.aes = FALSE) + 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) } + - # ---- Axes / scales ---- scale_x_continuous( - limits = c(-lod_max * 0.30, lod_max), + limits = c(-global_lod_max * 0.30, global_lod_max), breaks = c(0, round(lod_threshold, 1), - round(lod_max * 0.5, 1), round(lod_max * 0.9, 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), + 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)") + + 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") + 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_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())) } - + 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) - + grobs = plot_list, + ncol = n_cols, + nrow = n_rows_layout, + top = title_grob) + grid_plot } # ============================================================ -# COLORFUL PLOTLY MANHATTAN (interactive) +# COLORFUL PLOTLY MANHATTAN # ============================================================ make_plotly_manhattan <- function(scan_df, lod_threshold = 2.0, 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") + chroms <- sort(unique(pd$Chromosome), method = "radix") + + # Calculate cumulative positions 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 + 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_threshold - chr_mids <- tapply(pd$cum_pos, pd$Chromosome, median, na.rm = TRUE) + 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 @@ -997,13 +1226,16 @@ 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_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", @@ -1017,8 +1249,10 @@ make_plotly_manhattan <- function(scan_df, lod_threshold = 2.0, title = "Manhatt "
Dom. Class: ", Dominance_Class), hoverinfo = "text") } - pl %>% add_segments( - x = min(pd$cum_pos, na.rm=TRUE), xend = max(pd$cum_pos, na.rm=TRUE), + + # 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) %>% @@ -1039,18 +1273,22 @@ make_plotly_manhattan <- function(scan_df, lod_threshold = 2.0, title = "Manhatt 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")) + + pl } # ============================================================ -# COLORFUL CHROMOSOME IDIOGRAM +# 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], @@ -1058,7 +1296,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) + p <- ggplot() + geom_rect(data = chr_summary, aes(xmin = x - 0.28, xmax = x + 0.28, ymin = ymin, ymax = ymax), @@ -1077,42 +1317,50 @@ make_idiogram_ggplot <- function(qtl_list, all_markers_df, lod_threshold = 2.0) 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") ) - model_names <- names(qtl_list); n_models <- length(model_names) - vivid_pal <- c("#FF006E","#3A86FF","#06D6A0","#FFBE0B","#FB5607","#8338EC", - "#F72585","#4CC9F0","#2A9D8F","#E9C46A") + + # 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") model_colors_use <- setNames( - 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] + rep(vivid_pal, ceiling(n_models / length(vivid_pal)))[seq_len(n_models)], + model_names) + for (ti in seq_along(model_names)) { - tr <- model_names[ti] + 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, ] if (nrow(sig) == 0) next + sig$Chromosome <- as.character(sig$Chromosome) 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] + 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) + 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) + @@ -1124,45 +1372,66 @@ make_idiogram_ggplot <- function(qtl_list, all_markers_df, lod_threshold = 2.0) scale_color_manual(values = model_colors_use, name = "Model") + scale_size_continuous(range = c(2.5, 7), guide = "none") } + p } # ============================================================ -# DOMESTICATION: Fst + Tajima's D +# DOMESTICATION METRICS # ============================================================ 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 +# UI - Simplified for space (full UI from v10 with updated description) # ============================================================ ui <- fluidPage( shinyjs::useShinyjs(), @@ -1190,7 +1459,6 @@ 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;} @@ -1205,25 +1473,22 @@ ui <- fluidPage( .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 v10", - id = "nav", - - # ── 1. DATA UPLOAD ───────────────────────────────────── + title = "QTL-Mapper v11", + id = "nav", + + # Data Upload Tab tabPanel("📁 Data Upload", icon = icon("upload"), fluidRow(column(12, div(class = "info-box", - tags$b("QTL-Mapper v10 — CIM Fixed + Flanking Markers in Excel + Per-Chromosome LOD Plots"), + tags$b("QTL-Mapper v11 — CIM FULLY FIXED + QTL Cartographer Style Plots"), tags$br(), tags$span(class = "fix-badge", "CIM FIXED"), - " CIM cofactor threshold lowered (0.1 LOD gain) + fallback to top SIM markers + cM-based window exclusion", - tags$br(), - tags$span(class = "fix-badge", "FLANKING"), - " Left/Right flanking markers now in all Excel sheets", + " Window uses MARKER INDEX (not cM) | Cofactor LOD gain threshold: 2.0 | Fallback to top SIM markers", tags$br(), - tags$span(class = "fix-badge", "CHR LOD PLOT"), - " New per-chromosome LOD plots in QTL Cartographer style (see Results tab)" + tags$span(class = "fix-badge", "QTL PLOT"), + " Per-chromosome idiogram + LOD curve with auto QTL labels (qTrait_ChrN)" ) )), fluidRow( @@ -1246,14 +1511,14 @@ 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 = 10, min = 1, max = 30) + numericInput("window_size", "Exclusion Window (±markers)", value = 5, min = 1, max = 20) ), 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), @@ -1266,7 +1531,7 @@ ui <- fluidPage( div(class = "perm-info", tags$span(class = "speed-badge", "FAST"), tags$b(" Parallel Permutations"), tags$br(), - tags$small("Auto-detects CPU cores. Uses SIM on 200 marker subsample. ~10× faster than v8."), + tags$small("Uses SIM on subsampled markers. ~10× faster."), 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) @@ -1306,8 +1571,8 @@ ui <- fluidPage( ) )) ), - - # ── 2. RESULTS ───────────────────────────────────────── + + # Results Tab tabPanel("📊 Results", icon = icon("chart-line"), fluidRow(column(12, div(style = "display:flex;gap:10px;flex-wrap:wrap;margin-bottom:14px;", @@ -1331,15 +1596,12 @@ ui <- fluidPage( ) ) ), - # NEW: Per-chromosome LOD plot 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 with marker positions | ", - "right = LOD curve | red dashed = significance threshold | ", - "diamonds = significant QTLs with auto-labels (qXXX)"), + "Each panel: left = chromosome ideogram | right = LOD curve | red dashed = significance threshold | diamonds = significant QTLs"), uiOutput("chr_lod_plot_ui") ) ) @@ -1377,8 +1639,8 @@ ui <- fluidPage( ) )) ), - - # ── 3. COMPARE MODELS ────────────────────────────────── + + # Compare Models Tab tabPanel("⚖️ Compare Models", icon = icon("balance-scale"), fluidRow(column(12, div(class = "card", @@ -1386,7 +1648,7 @@ ui <- fluidPage( div(class = "card-bd", 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(), @@ -1415,8 +1677,8 @@ ui <- fluidPage( ) )) ), - - # ── 4. COMMON QTL ────────────────────────────────────── + + # Common QTL Tab tabPanel("🎯 Common QTL", icon = icon("bullseye"), fluidRow(column(12, div(class = "card", @@ -1455,8 +1717,8 @@ ui <- fluidPage( ) )) ), - - # ── 5. DOMESTICATION ─────────────────────────────────── + + # Domestication Tab tabPanel("🌾 Domestication", icon = icon("leaf"), fluidRow( column(4, @@ -1500,25 +1762,23 @@ ui <- fluidPage( ) )) ), - - # ── 6. ABOUT ─────────────────────────────────────────── + + # About Tab 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 v10 — QTL Cartographer-Compatible Platform"), + tags$h4(style = "color:#FF006E;", "QTL-Mapper v11 — Fully Fixed CIM + QTL Cartographer Plots"), div(class = "info-box", - tags$b("v10 Fixes & Improvements:"), tags$br(), - tags$span(class = "fix-badge", "CIM FIXED"), - " Cofactor threshold lowered from 0.5 → 0.1 LOD gain (was too strict)", tags$br(), - tags$span(class = "fix-badge", "CIM FIXED"), - " Fallback: if stepwise finds no cofactors, uses top-K SIM LOD markers", tags$br(), - tags$span(class = "fix-badge", "CIM FIXED"), - " Window exclusion now uses cM distance (not marker count)", tags$br(), - tags$span(class = "fix-badge", "FLANKING"), - " Left_Flanking_Marker + Right_Flanking_Marker in ALL Excel sheets", tags$br(), - tags$span(class = "fix-badge", "NEW PLOT"), - " Per-chromosome LOD plots (QTL Cartographer style) with idiogram + auto QTL labels" + 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$h5(style = "margin-top:18px;font-weight:600;color:#3A86FF;", "References"), tags$ul( @@ -1531,7 +1791,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 v10 © 2024") + tags$br(), "QTL-Mapper v11 © 2024") ) ) )) @@ -1543,30 +1803,30 @@ 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, + perf = NULL, tr_pred = NULL, val_pred = NULL, + model_fit = NULL, model_cols = NULL, + pred_test = NULL, sel_metrics = NULL, compare_res = 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.")) @@ -1594,30 +1854,32 @@ server <- function(input, output, session) { 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({ @@ -1625,7 +1887,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({ @@ -1634,118 +1896,135 @@ 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 (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"), - type = "message", duration = 4) + incProgress(0, detail = "Running parallel permutations...") 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, n_cofactors = input$n_cofactors, - window_size = input$window_size) + 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)) } 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) - - # Prediction model - nzv_i <- caret::nearZeroVar(X_tr) + + # Build prediction model (Random Forest) + 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) + + 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( + 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"), 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 (reactive) ---- + + # 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, + 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 + 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) + 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", @@ -1757,17 +2036,23 @@ server <- function(input, output, session) { 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() withProgress(message = "Comparing models...", value = 0, { for (mth in input$compare_methods) { @@ -1775,21 +2060,25 @@ server <- function(input, output, session) { 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)) clist[[mth]] <- res } }) rv$compare_res <- clist 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()) }, bg = "white") - + output$compare_bar <- renderPlotly({ req(length(rv$compare_res) > 0) rows <- list() @@ -1805,11 +2094,13 @@ server <- function(input, output, session) { 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", @@ -1822,7 +2113,7 @@ 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) rows <- list() @@ -1840,20 +2131,20 @@ server <- function(input, output, session) { rows <- c(rows, list(sig[, keep_cols, drop = FALSE])) } if (length(rows) == 0) return(datatable(data.frame(Status = "No QTLs found"))) - df <- do.call(rbind, rows) + df <- do.call(rbind, rows) df$N_Models <- as.integer(table(df$Marker)[df$Marker]) datatable(df[order(-df$N_Models, -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) }) - - # ---- 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) }) - + output$common_qtl_summary_ui <- renderUI({ cq <- common_qtl_data() if (is.null(cq) || nrow(cq) == 0) @@ -1864,13 +2155,12 @@ server <- function(input, output, session) { 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"))) - # Add flanking markers cq <- add_flanking_to_df(cq, rv$marker_info) num_cols <- intersect( c("Position","Mean_LOD","Max_LOD","Mean_PVE","Mean_Add_Eff", @@ -1880,31 +2170,31 @@ 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) - n_levels <- sort(unique(cq$N_Models_Detected), decreasing = TRUE) + n_levels <- sort(unique(cq$N_Models_Detected), decreasing = TRUE) 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) @@ -1913,7 +2203,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")) %>% @@ -1927,14 +2217,14 @@ 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(), 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)) @@ -1942,7 +2232,7 @@ server <- function(input, output, session) { if (length(valid) == 0) ggplot() + labs(title = "Run analysis first") + theme_bw() else make_idiogram_ggplot(valid[[1]], rv$marker_info, lod_thr()) }, bg = "white") - + output$perf_plot <- renderPlotly({ req(rv$perf) clrs <- c("#FF006E","#06D6A0","#FF006E","#06D6A0") @@ -1956,7 +2246,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) @@ -1967,11 +2257,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) @@ -1982,12 +2272,12 @@ 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 ---- + + # QTL TABLES output$qtl_table <- renderDT({ req(rv$scan_all) if ("Message" %in% colnames(rv$scan_all)) @@ -2016,12 +2306,11 @@ server <- function(input, output, session) { "Interval_Size_cM"), show_cols), 3) %>% 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"))) - # Add flanking markers to full scan table fs <- add_flanking_to_df(rv$scan_all, rv$marker_info) datatable(fs, options = list(scrollX = TRUE, pageLength = 15, dom = "Blfrtip", @@ -2030,18 +2319,26 @@ server <- function(input, output, session) { formatRound(intersect(c("LOD","PVE_Marker_Percent","Additive_Effect"), colnames(fs)), 3) %>% formatSignif(intersect("P_Value", colnames(fs)), 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)), @@ -2051,16 +2348,19 @@ 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 @@ -2068,28 +2368,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") 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; next } - 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 + } else { + 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), @@ -2099,9 +2406,10 @@ server <- function(input, output, session) { } if (!is.null(threshold)) pl <- pl %>% add_segments( - x = min(pd$cum_pos, na.rm=TRUE), xend = max(pd$cum_pos, na.rm=TRUE), + 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]), @@ -2110,10 +2418,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), ], @@ -2121,38 +2429,39 @@ server <- function(input, output, session) { rownames = FALSE, class = "cell-border stripe hover") %>% formatRound(c("Fst","Pi_Dom","Pi_Wild","Tajima_D_Dom"), 4) }) - - # ============================================================ - # DOWNLOADS — ALL INCLUDE FLANKING MARKERS - # ============================================================ + + # DOWNLOADS output$dl_manhattan <- downloadHandler( filename = function() paste0("manhattan_", Sys.Date(), ".png"), - content = function(file) { + content = function(file) { req(rv$scan_all) - # Use ggplot2 version for PNG 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") + 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; next } - 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 + } 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) + 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_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) + @@ -2168,10 +2477,10 @@ server <- function(input, output, session) { 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)) @@ -2182,57 +2491,49 @@ server <- function(input, output, session) { 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) { + 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, + 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))) + 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) - ggplot2::ggsave(file, plot = grid::grid.draw(p), - width = n_cols * 3.5, height = n_rows * 3, - dpi = 200, bg = "white", - device = "png") - # Alternative: use png + grid - png(file, width = n_cols * 3.5 * 200, height = n_rows * 3 * 200, res = 200) + 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_v10_", Sys.Date(), ".xlsx"), - content = function(file) { + filename = function() paste0("qtl_results_v11_", Sys.Date(), ".xlsx"), + content = function(file) { sheets <- list() - - # ---- Significant QTLs with full flanking marker info ---- + 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)) - # Ensure flanking markers are present 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 scan with flanking markers full_fl <- add_flanking_to_df(rv$scan_all, rv$marker_info) sheets[["Full_Scan"]] <- full_fl } - + if (!is.null(rv$perf)) sheets[["Performance"]] <- rv$perf - - # ---- Per-model results with flanking markers ---- + for (m in names(rv$compare_res)) { r <- rv$compare_res[[m]] if (!is.null(r) && !"Message" %in% colnames(r)) { @@ -2244,44 +2545,43 @@ server <- function(input, output, session) { sig_m <- add_flanking_to_df(sig_m, rv$marker_info) sheets[[paste0("Model_", m)]] <- sig_m } - # Full scan per model with flanking full_m <- add_flanking_to_df(r, rv$marker_info) sheets[[paste0("FullScan_", m)]] <- full_m } } - - # ---- Common QTL with flanking markers ---- + cq <- tryCatch(find_common_qtl(rv$compare_res, 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 } - + 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) { + content = function(file) { cq <- tryCatch(find_common_qtl(rv$compare_res, lod_thr(), isolate(input$min_models)), error = function(e) NULL) if (!is.null(cq) && nrow(cq) > 0) { @@ -2293,10 +2593,10 @@ server <- function(input, output, session) { } } ) - + 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