diff --git "a/app.R" "b/app.R" --- "a/app.R" +++ "b/app.R" @@ -1,9 +1,10 @@ # ============================================================ -# QTL-Mapper v6 — Multi-Model QTL Mapping (Complete Enhanced) +# QTL-Mapper v7 — QTL Cartographer Compatible Multi-Model QTL Mapping # # FEATURES: +# - QTL Cartographer compatible SIM, CIM, MQM algorithms # - 6 mapping models: SIM, CIM, MQM, LASSO, ElasticNet, RandomForest -# - Pastel/soft color theme for all plots +# - VIBRANT/COLORFUL theme for all plots (not pastel) # - Interactive Manhattan plots with hover info # - Chromosome idiogram with QTL positions # - Common QTL tab for markers significant across models @@ -16,7 +17,7 @@ required_packages <- c( "shiny", "randomForest", "caret", "DT", "ggplot2", "plotly", "writexl", "viridis", "reshape2", "dplyr", "ggrepel", "glmnet", "shinyjs", "RColorBrewer", "scales", "gridExtra", "pheatmap", - "corrplot", "ggpubr", "GGally" + "corrplot", "ggpubr", "GGally", "qtl", "Matrix", "MASS" ) for (pkg in required_packages) { @@ -27,40 +28,96 @@ for (pkg in required_packages) { } # ============================================================ -# PASTEL COLOR PALETTES +# VIBRANT COLOR PALETTES # ============================================================ -PASTEL_COLORS <- c( - "#A8E6CF", "#DCEDC1", "#FFD3B6", "#FFAAA5", "#FF8B94", - "#B5EAD7", "#C7CEEA", "#E2F0CB", "#FFDAC1", "#E2F0CB", - "#B5EAD7", "#FFB7B2", "#C7CEEA", "#FFDAC1", "#E6C8A0" +VIBRANT_COLORS <- c( + "#FF1493", "#00CED1", "#FF4500", "#32CD32", "#FFD700", "#8A2BE2", + "#DC143C", "#00BFFF", "#FF6347", "#7FFF00", "#FF69B4", "#1E90FF", + "#FF8C00", "#00FA9A", "#9370DB", "#F08080", "#3CB371", "#FF6B6B", + "#4ECDC4", "#45B7D1", "#96CEB4", "#FFEAA7", "#DDA0DD", "#F0E68C" ) CHROMOSOME_PALETTE <- c( - "#8DA0CB", "#66C2A5", "#FC8D62", "#E78AC3", "#A6D854", - "#FFD92F", "#E5C494", "#B3B3B3", "#7FBF7B", "#AF8DC3" + "#FF6B6B", "#4ECDC4", "#45B7D1", "#96CEB4", "#FFEAA7", + "#DDA0DD", "#F0E68C", "#FFB347", "#87CEEB", "#DDA0DD" ) -QTL_COLORS <- c("#E15759", "#4E79A7", "#59A14F", "#F28E2B", "#B07AA2", "#9C755F") +QTL_COLORS <- c("#FF1493", "#00CED1", "#FF4500", "#32CD32", "#FFD700", "#8A2BE2") # ============================================================ # MAPPING MODEL DEFINITIONS (6 models) # ============================================================ MAPPING_MODELS <- list( - "SIM" = list(label = "Simple Interval Mapping (SIM)", desc = "Single-marker regression; LOD = -log10(p); baseline model"), - "CIM" = list(label = "Composite Interval Mapping (CIM)", desc = "CIM with RF-selected cofactors; controls background genetic variation"), - "MQM" = list(label = "Multiple QTL Model (MQM)", desc = "Forward stepwise selection across all markers; multi-QTL detection"), + "SIM" = list(label = "Simple Interval Mapping (SIM)", desc = "QTL Cartographer style interval mapping; LOD = -log10(p); baseline model"), + "CIM" = list(label = "Composite Interval Mapping (CIM)", desc = "QTL Cartographer CIM with marker cofactors; controls background genetic variation"), + "MQM" = list(label = "Multiple QTL Model (MQM)", desc = "QTL Cartographer MQM; forward stepwise selection with cofactors"), "LASSO" = list(label = "LASSO QTL (L1 penalized)", desc = "L1 penalized regression; sparse solution; lambda by CV"), "ENET" = list(label = "Elastic Net (L1+L2)", desc = "Elastic net penalty; handles correlated markers; alpha=0.5"), "RF" = list(label = "Random Forest QTL", desc = "Non-parametric; captures non-linear effects; variable importance") ) # ============================================================ -# HELPERS +# QTL CARTOGRAPHER STYLE HELPER FUNCTIONS # ============================================================ -cn <- function(x) trimws(gsub('[\r\n\"]', '', as.character(x))) + +# Calculate LOD score using likelihood ratio (QTL Cartographer style) +calculate_lod_qtlcart <- function(full_model, reduced_model, df_focal = 1) { + # QTL Cartographer LOD = log10(LR) = log10(L_full/L_reduced) + # For linear models: LOD = (n/2) * log10(RSS_reduced/RSS_full) + RSS_full <- sum(residuals(full_model)^2) + RSS_red <- sum(residuals(reduced_model)^2) + n <- length(residuals(full_model)) + + if (RSS_red > 0 && RSS_full > 0) { + lod <- (n/2) * log10(RSS_red / RSS_full) + return(max(0, lod)) + } + return(0) +} + +# Calculate PVE (Percent Variance Explained) - QTL Cartographer style +calculate_pve_qtlcart <- function(full_model, reduced_model) { + RSS_full <- sum(residuals(full_model)^2) + RSS_red <- sum(residuals(reduced_model)^2) + + if (RSS_red > 0) { + pve <- (RSS_red - RSS_full) / RSS_red * 100 + return(max(0, min(100, pve))) + } + return(0) +} + +# Calculate dominance ratio (d/a) - QTL Cartographer style +calculate_dominance_ratio <- function(a_eff, d_eff) { + if (is.na(a_eff) || is.na(d_eff) || abs(a_eff) < 1e-10) return(NA) + ratio <- abs(d_eff / a_eff) + + if (ratio <= 0.2) return("Additive") + if (ratio <= 0.5) return("Partial Dominance") + if (ratio <= 1.0) return("Dominance") + return("Overdominance") +} + +# Calculate support interval (LOD drop 1.5 or 2.0) +calculate_support_interval <- function(chrom_data, peak_pos, peak_lod, lod_drop = 1.5) { + chrom_data <- chrom_data[order(chrom_data$Position), ] + + # Find markers within LOD drop + within_interval <- chrom_data$LOD >= (peak_lod - lod_drop) + + if (sum(within_interval, na.rm = TRUE) < 2) { + return(list(start = peak_pos, end = peak_pos, size = 0)) + } + + interval_data <- chrom_data[within_interval, ] + start_pos <- min(interval_data$Position, na.rm = TRUE) + end_pos <- max(interval_data$Position, na.rm = TRUE) + + list(start = start_pos, end = end_pos, size = end_pos - start_pos) +} # ============================================================ -# GENOTYPE LOADER +# GENOTYPE LOADER (Enhanced) # ============================================================ load_genotype_file <- function(filepath) { lines <- readLines(filepath, warn = FALSE) @@ -83,8 +140,15 @@ load_genotype_file <- function(filepath) { colnames(gd) <- header rownames(gd) <- cn(as.character(gd[, 1])) gd <- gd[, -1, drop = FALSE] - for (col in colnames(gd)) + + # Convert to numeric and code as 0/1/2 for QTL Cartographer compatibility + for (col in colnames(gd)) { gd[[col]] <- suppressWarnings(as.numeric(as.character(gd[[col]]))) + # Ensure values are 0/1/2 (AA=0, Aa=1, aa=2) + if (!all(gd[[col]] %in% c(0,1,2,NA))) { + gd[[col]] <- as.numeric(as.factor(gd[[col]])) - 1 + } + } marker_info <- data.frame( Marker = colnames(gd), @@ -105,220 +169,625 @@ load_genotype_file <- function(filepath) { } # ============================================================ -# QTL SCAN — dispatcher with all 6 models +# QTL SCAN — QTL CARTOGRAPHER COMPATIBLE MODELS # ============================================================ -qtl_scan <- function(genotype_matrix, phenotype_vector, marker_info, - method = "CIM", n_cofactors = 10, window_size = 10) { - - cat("\n=== QTL SCAN ===\nMethod:", method, "\n") - valid_rows <- !is.na(phenotype_vector) - X_valid <- genotype_matrix[valid_rows, , drop = FALSE] - y_valid <- phenotype_vector[valid_rows] - nzv <- apply(X_valid, 2, function(x) length(unique(na.omit(x))) < 2) +# ============================================================ +# SIM: Simple Interval Mapping (QTL Cartographer style) +# ============================================================ +qtl_scan_sim_qtlcart <- function(X, y, marker_info, window_size = 20) { + cat("\n=== QTL Cartographer SIM Analysis ===\n") + + valid_rows <- !is.na(y) + X_valid <- X[valid_rows, , drop = FALSE] + y_valid <- y[valid_rows] + + # Remove monomorphic markers + nzv <- apply(X_valid, 2, function(x) length(unique(na.omit(x))) < 2) X_valid <- X_valid[, !nzv, drop = FALSE] - cat("Markers after NZV removal:", ncol(X_valid), "\n") - - if (method == "LASSO") return(qtl_scan_lasso(X_valid, y_valid, marker_info)) - if (method == "ENET") return(qtl_scan_enet(X_valid, y_valid, marker_info)) - if (method == "RF") return(qtl_scan_rf(X_valid, y_valid, marker_info)) - if (method == "MQM") return(qtl_scan_mqm(X_valid, y_valid, marker_info)) + + results_list <- list() + + for (m in colnames(X_valid)) { + geno <- X_valid[, m] + valid_idx <- !is.na(geno) & !is.na(y_valid) + geno_v <- geno[valid_idx] + pheno_v <- y_valid[valid_idx] + + if (length(unique(geno_v)) < 2 || length(pheno_v) < 8) next + + m_info <- marker_info[marker_info$Marker == m, ] + if (nrow(m_info) == 0) next + m_chr <- as.character(m_info$Chromosome[1]) + m_pos <- m_info$Position[1] + if (is.na(m_pos)) next + + tryCatch({ + # QTL Cartographer SIM: Single marker regression with interval mapping + df <- data.frame(y = pheno_v, marker = geno_v) + df <- df[complete.cases(df), ] + + if (nrow(df) < 8) return(NULL) + + # Fit full model (with marker) + fit_full <- lm(y ~ marker, data = df) + # Fit reduced model (intercept only) + fit_red <- lm(y ~ 1, data = df) + + # Calculate LOD using likelihood ratio (QTL Cartographer style) + lod <- calculate_lod_qtlcart(fit_full, fit_red) + + # Calculate PVE + pve <- calculate_pve_qtlcart(fit_full, fit_red) + + # Calculate additive and dominance effects + # Genotype coding: AA=0, Aa=1, aa=2 + a_code <- geno_v - 1 # Additive component (-1, 0, 1) + d_code <- as.numeric(geno_v == 1) # Dominance component (0 or 1) + + has_het <- sum(geno_v == 1, na.rm = TRUE) > 0 + + if (has_het && length(unique(d_code)) > 1) { + lm_eff <- lm(pheno_v ~ a_code + d_code) + ce <- coef(lm_eff) + se <- coef(summary(lm_eff)) + + a_eff <- ce["a_code"] + se_a <- if ("a_code" %in% rownames(se)) se["a_code", "Std. Error"] else NA + d_eff <- ce["d_code"] + se_d <- if ("d_code" %in% rownames(se)) se["d_code", "Std. Error"] else NA + + # Calculate dominance ratio (d/a) + dom_ratio <- if (!is.na(a_eff) && abs(a_eff) > 1e-10) abs(d_eff / a_eff) else NA + dom_class <- calculate_dominance_ratio(a_eff, d_eff) + } else { + # No heterozygotes - purely additive + lm_eff <- lm(pheno_v ~ a_code) + ce <- coef(lm_eff) + se <- coef(summary(lm_eff)) + + a_eff <- ce["a_code"] + se_a <- if ("a_code" %in% rownames(se)) se["a_code", "Std. Error"] else NA + d_eff <- NA + dom_ratio <- NA + dom_class <- "Additive" + } + + # P-value from F-test + p_val <- summary(fit_full)$coefficients[2, 4] + + results_list[[m]] <- data.frame( + Marker = m, Chromosome = m_chr, Position = m_pos, + LOD = lod, P_Value = p_val, + PVE_Marker_Percent = pve, PVE_CIM_Percent = pve, + Additive_Effect = a_eff, SE_Additive = se_a, + CI_Lower = ifelse(is.na(se_a), NA, a_eff - 1.96 * se_a), + CI_Upper = ifelse(is.na(se_a), NA, a_eff + 1.96 * se_a), + Dominance_Effect = d_eff, SE_Dominance = if(exists("se_d")) se_d else NA, + Dominance_Ratio = dom_ratio, Dominance_Class = dom_class, + N_Cofactors = 0, N_Samples = nrow(df), + Method = "SIM", stringsAsFactors = FALSE + ) + }, error = function(e) { + cat("Error processing marker", m, ":", e$message, "\n") + }) + } + + if (length(results_list) == 0) { + return(data.frame(Message = "SIM produced no results — check data format")) + } + + res <- do.call(rbind, results_list) + res <- res[order(res$Chromosome, res$Position), ] + res +} - # SIM / CIM per-marker scan - cofactors <- character(0) +# ============================================================ +# CIM: Composite Interval Mapping (QTL Cartographer style) +# ============================================================ +qtl_scan_cim_qtlcart <- function(X, y, marker_info, n_cofactors = 10, window_size = 10) { + cat("\n=== QTL Cartographer CIM Analysis ===\n") + + valid_rows <- !is.na(y) + X_valid <- X[valid_rows, , drop = FALSE] + y_valid <- y[valid_rows] + + # Remove monomorphic markers + nzv <- apply(X_valid, 2, function(x) length(unique(na.omit(x))) < 2) + X_valid <- X_valid[, !nzv, drop = FALSE] + n_samples <- length(y_valid) - if (method == "CIM" && n_cofactors > 0) { - max_cof <- max(3, floor(sqrt(n_samples))) - n_cof <- min(n_cofactors, max_cof) - rf_res <- tryCatch( - randomForest(x = X_valid, y = y_valid, ntree = 300, importance = TRUE), - error = function(e) NULL) - if (!is.null(rf_res)) { - imp <- importance(rf_res, type = 1)[, 1] - cofactors <- names(sort(imp, decreasing = TRUE))[1:min(n_cof*2, length(imp))] + max_cof <- max(3, min(n_cofactors, floor(sqrt(n_samples)))) + + # Select cofactors using stepwise regression (QTL Cartographer style) + cat("Selecting cofactors for CIM...\n") + + # Build initial model with all markers + all_markers <- colnames(X_valid) + cofactors <- character(0) + + # Forward stepwise selection for cofactors + remaining_markers <- all_markers + best_lod <- 0 + + for (step in 1:max_cof) { + if (length(remaining_markers) == 0) break + + best_marker <- NULL + best_step_lod <- 0 + + for (m in remaining_markers) { + tryCatch({ + # Test each marker as potential cofactor + if (length(cofactors) == 0) { + fit <- lm(y_valid ~ X_valid[, m]) + } else { + cof_data <- as.data.frame(X_valid[, cofactors, drop = FALSE]) + cof_data[is.na(cof_data)] <- 0 + fit <- lm(y_valid ~ X_valid[, m] + ., data = cof_data) + } + + lod <- calculate_lod_qtlcart(fit, lm(y_valid ~ 1)) + + if (lod > best_step_lod) { + best_step_lod <- lod + best_marker <- m + } + }, error = function(e) {}) + } + + if (!is.null(best_marker) && best_step_lod > best_lod * 1.1) { + cofactors <- c(cofactors, best_marker) + remaining_markers <- setdiff(remaining_markers, best_marker) + best_lod <- best_step_lod + cat("Selected cofactor:", best_marker, "LOD:", round(best_step_lod, 3), "\n") } else { - pv <- sapply(colnames(X_valid), function(m) - tryCatch(coef(summary(lm(y_valid ~ X_valid[,m])))[2,4], error=function(e) 1)) - cofactors <- names(sort(pv))[1:min(n_cof*2, length(pv))] + break } } - + + cat("Selected", length(cofactors), "cofactors for CIM\n") + + # Now scan each marker with cofactors as background results_list <- list() + for (m in colnames(X_valid)) { - geno <- X_valid[, m] + geno <- X_valid[, m] valid_idx <- !is.na(geno) & !is.na(y_valid) - geno_v <- geno[valid_idx]; pheno_v <- y_valid[valid_idx] + geno_v <- geno[valid_idx] + pheno_v <- y_valid[valid_idx] + if (length(unique(geno_v)) < 2 || length(pheno_v) < 8) next - + m_info <- marker_info[marker_info$Marker == m, ] if (nrow(m_info) == 0) next m_chr <- as.character(m_info$Chromosome[1]) m_pos <- m_info$Position[1] if (is.na(m_pos)) next - - active_cof <- character(0) - if (method == "CIM" && length(cofactors) > 0) { - chr_mk <- marker_info[marker_info$Chromosome == m_chr, ] - chr_mk <- chr_mk[order(chr_mk$Position), ] - focal_idx_c <- which(chr_mk$Marker == m) - nearby <- if (length(focal_idx_c) > 0) - chr_mk$Marker[max(1,focal_idx_c-window_size):min(nrow(chr_mk),focal_idx_c+window_size)] - else m - active_cof <- head(setdiff(cofactors, c(m, nearby))[ - setdiff(cofactors, c(m, nearby)) %in% colnames(X_valid)], n_cofactors) + + # Exclude markers on same chromosome within window (QTL Cartographer style) + active_cof <- cofactors + if (length(cofactors) > 0) { + chr_mk <- marker_info[marker_info$Chromosome == m_chr, ] + chr_mk <- chr_mk[order(chr_mk$Position), ] + focal_idx <- which(chr_mk$Marker == m) + + if (length(focal_idx) > 0) { + nearby <- chr_mk$Marker[ + max(1, focal_idx - window_size):min(nrow(chr_mk), focal_idx + window_size) + ] + active_cof <- setdiff(cofactors, nearby) + } } - + tryCatch({ df <- data.frame(y = pheno_v, focal = geno_v) + if (length(active_cof) > 0) { - cm <- X_valid[valid_idx, active_cof, drop = FALSE]; cm[is.na(cm)] <- 0 + cm <- X_valid[valid_idx, active_cof, drop = FALSE] + cm[is.na(cm)] <- 0 df <- cbind(df, cm) } + df <- df[complete.cases(df), ] if (nrow(df) < 8) return(NULL) - - fit_full <- if (length(active_cof) > 0) - lm(as.formula(paste("y ~ focal +", paste(active_cof, collapse="+"))), data=df) - else lm(y ~ focal, data=df) - fit_reduced <- if (length(active_cof) > 0) - lm(as.formula(paste("y ~", paste(active_cof, collapse="+"))), data=df) - else lm(y ~ 1, data=df) - - ct <- coef(summary(fit_full)) + + # Full model (with focal marker + cofactors) + if (length(active_cof) > 0) { + fit_full <- lm(as.formula(paste("y ~ focal +", paste(active_cof, collapse = "+"))), data = df) + fit_red <- lm(as.formula(paste("y ~", paste(active_cof, collapse = "+"))), data = df) + } else { + fit_full <- lm(y ~ focal, data = df) + fit_red <- lm(y ~ 1, data = df) + } + + # Calculate LOD using likelihood ratio + lod <- calculate_lod_qtlcart(fit_full, fit_red) + + # Calculate PVE + pve <- calculate_pve_qtlcart(fit_full, fit_red) + + # Get p-value + ct <- coef(summary(fit_full)) if (!"focal" %in% rownames(ct)) next p_val <- ct["focal", "Pr(>|t|)"] - lod <- -log10(max(p_val, 1e-300)) - - RSS_f <- sum(residuals(fit_full)^2); RSS_r <- sum(residuals(fit_reduced)^2) - pve_cim <- if (RSS_r > 0) max(0, (RSS_r-RSS_f)/RSS_r*100) else NA - - a_code <- df$focal - 1; d_code <- as.numeric(df$focal == 1) - has_het <- length(unique(d_code)) > 1 - lm_eff <- if (has_het) lm(df$y ~ a_code + d_code) else lm(df$y ~ a_code) - pve_m <- max(0, summary(lm_eff)$r.squared * 100) - ce <- coef(lm_eff); se_t <- coef(summary(lm_eff)) - a_eff <- ce["a_code"] - se_a <- if ("a_code" %in% rownames(se_t)) se_t["a_code","Std. Error"] else NA - d_eff <- if (has_het) ce["d_code"] else NA - d_rat <- if (!is.na(d_eff) && !is.na(a_eff) && a_eff != 0) abs(d_eff/a_eff) else NA - dom_cl <- if (is.na(d_rat)) "Additive" - else if (d_rat > 1) "Overdominance" - else if (d_rat > 0.5) "Dominance" - else if (d_rat > 0.2) "Partial Dom." else "Additive" - + + # Calculate additive and dominance effects + a_code <- geno_v - 1 + d_code <- as.numeric(geno_v == 1) + has_het <- sum(geno_v == 1, na.rm = TRUE) > 0 + + if (has_het && length(unique(d_code)) > 1) { + lm_eff <- lm(pheno_v ~ a_code + d_code) + ce <- coef(lm_eff) + se <- coef(summary(lm_eff)) + + a_eff <- ce["a_code"] + se_a <- if ("a_code" %in% rownames(se)) se["a_code", "Std. Error"] else NA + d_eff <- ce["d_code"] + + dom_ratio <- if (!is.na(a_eff) && abs(a_eff) > 1e-10) abs(d_eff / a_eff) else NA + dom_class <- calculate_dominance_ratio(a_eff, d_eff) + } else { + lm_eff <- lm(pheno_v ~ a_code) + ce <- coef(lm_eff) + se <- coef(summary(lm_eff)) + + a_eff <- ce["a_code"] + se_a <- if ("a_code" %in% rownames(se)) se["a_code", "Std. Error"] else NA + d_eff <- NA + dom_ratio <- NA + dom_class <- "Additive" + } + results_list[[m]] <- data.frame( - Marker=m, Chromosome=m_chr, Position=m_pos, - LOD=lod, P_Value=p_val, - PVE_Marker_Percent=pve_m, PVE_CIM_Percent=pve_cim, - Additive_Effect=a_eff, SE_Additive=se_a, - CI_Lower=ifelse(is.na(se_a),NA,a_eff-1.96*se_a), - CI_Upper=ifelse(is.na(se_a),NA,a_eff+1.96*se_a), - Dominance_Effect=d_eff, Dominance_Ratio=d_rat, Dominance_Class=dom_cl, - N_Cofactors=length(active_cof), N_Samples=nrow(df), - Method=method, stringsAsFactors=FALSE) - }, error=function(e) {}) + Marker = m, Chromosome = m_chr, Position = m_pos, + LOD = lod, P_Value = p_val, + PVE_Marker_Percent = pve, PVE_CIM_Percent = pve, + Additive_Effect = a_eff, SE_Additive = se_a, + CI_Lower = ifelse(is.na(se_a), NA, a_eff - 1.96 * se_a), + CI_Upper = ifelse(is.na(se_a), NA, a_eff + 1.96 * se_a), + Dominance_Effect = d_eff, SE_Dominance = NA, + Dominance_Ratio = dom_ratio, Dominance_Class = dom_class, + N_Cofactors = length(active_cof), N_Samples = nrow(df), + Method = "CIM", stringsAsFactors = FALSE + ) + }, error = function(e) {}) + } + + if (length(results_list) == 0) { + return(data.frame(Message = "CIM produced no results — check data format")) } + + res <- do.call(rbind, results_list) + res <- res[order(res$Chromosome, res$Position), ] + res +} - if (length(results_list)==0) - return(data.frame(Message=paste("No results from", method, "— check data format"))) +# ============================================================ +# MQM: Multiple QTL Model (QTL Cartographer style) +# ============================================================ +qtl_scan_mqm_qtlcart <- function(X, y, marker_info, n_cofactors = 10, window_size = 10) { + cat("\n=== QTL Cartographer MQM Analysis ===\n") + + valid_rows <- !is.na(y) + X_valid <- X[valid_rows, , drop = FALSE] + y_valid <- y[valid_rows] + + # Remove monomorphic markers + nzv <- apply(X_valid, 2, function(x) length(unique(na.omit(x))) < 2) + X_valid <- X_valid[, !nzv, drop = FALSE] + + n_samples <- length(y_valid) + max_cof <- min(n_cofactors, floor(sqrt(n_samples))) + + # MQM: Forward stepwise selection of QTLs + cat("MQM: Forward stepwise QTL selection...\n") + + selected_qtls <- character(0) + selected_positions <- numeric(0) + selected_lods <- numeric(0) + + # Initial scan to identify potential QTLs + initial_scan <- qtl_scan_sim_qtlcart(X_valid, y_valid, marker_info) + + if (is.null(initial_scan) || "Message" %in% colnames(initial_scan)) { + return(data.frame(Message = "MQM: Initial scan failed")) + } + + # Sort by LOD and select top candidates + initial_scan <- initial_scan[order(-initial_scan$LOD), ] + candidates <- head(initial_scan$Marker, max_cof * 2) + + # Forward selection + remaining <- candidates + best_lod <- 0 + + for (step in 1:max_cof) { + if (length(remaining) == 0) break + + best_candidate <- NULL + best_step_lod <- 0 + best_fit <- NULL + + for (m in remaining) { + tryCatch({ + # Build model with current selected QTLs + candidate + if (length(selected_qtls) == 0) { + fit <- lm(y_valid ~ X_valid[, m]) + } else { + selected_data <- as.data.frame(X_valid[, selected_qtls, drop = FALSE]) + selected_data[is.na(selected_data)] <- 0 + fit <- lm(y_valid ~ X_valid[, m] + ., data = selected_data) + } + + # Compare to model without candidate + if (length(selected_qtls) == 0) { + fit_red <- lm(y_valid ~ 1) + } else { + selected_data <- as.data.frame(X_valid[, selected_qtls, drop = FALSE]) + selected_data[is.na(selected_data)] <- 0 + fit_red <- lm(y_valid ~ ., data = selected_data) + } + + lod <- calculate_lod_qtlcart(fit, fit_red) + + if (lod > best_step_lod) { + best_step_lod <- lod + best_candidate <- m + best_fit <- fit + } + }, error = function(e) {}) + } + + # Use LOD threshold of 2.0 for inclusion (QTL Cartographer standard) + if (!is.null(best_candidate) && best_step_lod > 2.0 && best_step_lod > best_lod * 0.9) { + selected_qtls <- c(selected_qtls, best_candidate) + remaining <- setdiff(remaining, best_candidate) + best_lod <- best_step_lod + + # Get position info + m_info <- marker_info[marker_info$Marker == best_candidate, ] + selected_positions <- c(selected_positions, m_info$Position[1]) + selected_lods <- c(selected_lods, best_step_lod) + + cat("Selected QTL:", best_candidate, "LOD:", round(best_step_lod, 3), + "Pos:", m_info$Position[1], "\n") + } else { + break + } + } + + cat("Selected", length(selected_qtls), "QTLs in MQM model\n") + + # Now scan each marker with selected QTLs as cofactors + results_list <- list() + + for (m in colnames(X_valid)) { + geno <- X_valid[, m] + valid_idx <- !is.na(geno) & !is.na(y_valid) + geno_v <- geno[valid_idx] + pheno_v <- y_valid[valid_idx] + + if (length(unique(geno_v)) < 2 || length(pheno_v) < 8) next + + m_info <- marker_info[marker_info$Marker == m, ] + if (nrow(m_info) == 0) next + m_chr <- as.character(m_info$Chromosome[1]) + m_pos <- m_info$Position[1] + if (is.na(m_pos)) next + + # Exclude markers on same chromosome within window + active_cof <- selected_qtls + if (length(selected_qtls) > 0) { + chr_mk <- marker_info[marker_info$Chromosome == m_chr, ] + chr_mk <- chr_mk[order(chr_mk$Position), ] + focal_idx <- which(chr_mk$Marker == m) + + if (length(focal_idx) > 0) { + nearby <- chr_mk$Marker[ + max(1, focal_idx - window_size):min(nrow(chr_mk), focal_idx + window_size) + ] + active_cof <- setdiff(selected_qtls, nearby) + } + } + + tryCatch({ + df <- data.frame(y = pheno_v, focal = geno_v) + + if (length(active_cof) > 0) { + cm <- X_valid[valid_idx, active_cof, drop = FALSE] + cm[is.na(cm)] <- 0 + df <- cbind(df, cm) + } + + df <- df[complete.cases(df), ] + if (nrow(df) < 8) return(NULL) + + # Full model + if (length(active_cof) > 0) { + fit_full <- lm(as.formula(paste("y ~ focal +", paste(active_cof, collapse = "+"))), data = df) + fit_red <- lm(as.formula(paste("y ~", paste(active_cof, collapse = "+"))), data = df) + } else { + fit_full <- lm(y ~ focal, data = df) + fit_red <- lm(y ~ 1, data = df) + } + + lod <- calculate_lod_qtlcart(fit_full, fit_red) + pve <- calculate_pve_qtlcart(fit_full, fit_red) + + ct <- coef(summary(fit_full)) + if (!"focal" %in% rownames(ct)) next + p_val <- ct["focal", "Pr(>|t|)"] + + # Calculate effects + a_code <- geno_v - 1 + d_code <- as.numeric(geno_v == 1) + has_het <- sum(geno_v == 1, na.rm = TRUE) > 0 + + if (has_het && length(unique(d_code)) > 1) { + lm_eff <- lm(pheno_v ~ a_code + d_code) + ce <- coef(lm_eff) + se <- coef(summary(lm_eff)) + + a_eff <- ce["a_code"] + se_a <- if ("a_code" %in% rownames(se)) se["a_code", "Std. Error"] else NA + d_eff <- ce["d_code"] + + dom_ratio <- if (!is.na(a_eff) && abs(a_eff) > 1e-10) abs(d_eff / a_eff) else NA + dom_class <- calculate_dominance_ratio(a_eff, d_eff) + } else { + lm_eff <- lm(pheno_v ~ a_code) + ce <- coef(lm_eff) + se <- coef(summary(lm_eff)) + + a_eff <- ce["a_code"] + se_a <- if ("a_code" %in% rownames(se)) se["a_code", "Std. Error"] else NA + d_eff <- NA + dom_ratio <- NA + dom_class <- "Additive" + } + + results_list[[m]] <- data.frame( + Marker = m, Chromosome = m_chr, Position = m_pos, + LOD = lod, P_Value = p_val, + PVE_Marker_Percent = pve, PVE_CIM_Percent = pve, + Additive_Effect = a_eff, SE_Additive = se_a, + CI_Lower = ifelse(is.na(se_a), NA, a_eff - 1.96 * se_a), + CI_Upper = ifelse(is.na(se_a), NA, a_eff + 1.96 * se_a), + Dominance_Effect = d_eff, SE_Dominance = NA, + Dominance_Ratio = dom_ratio, Dominance_Class = dom_class, + N_Cofactors = length(active_cof), N_Samples = nrow(df), + Method = "MQM", stringsAsFactors = FALSE + ) + }, error = function(e) {}) + } + + if (length(results_list) == 0) { + return(data.frame(Message = "MQM produced no results — check data format")) + } + res <- do.call(rbind, results_list) - res[order(res$Chromosome, res$Position), ] + res <- res[order(res$Chromosome, res$Position), ] + res } # ============================================================ -# LASSO QTL +# LASSO QTL (Enhanced) # ============================================================ qtl_scan_lasso <- function(X, y, marker_info) { valid <- !is.na(y) & apply(X, 1, function(r) !any(is.na(r))) X_v <- X[valid,,drop=FALSE]; y_v <- y[valid] - cv <- tryCatch(cv.glmnet(as.matrix(X_v), y_v, alpha=1, nfolds=5), error=function(e) NULL) + + # Standardize X for LASSO + X_scaled <- scale(X_v) + + cv <- tryCatch(cv.glmnet(as.matrix(X_scaled), y_v, alpha=1, nfolds=5), error=function(e) NULL) if (is.null(cv)) return(data.frame(Message="LASSO failed")) - - coefs <- coef(cv, s=cv$lambda.1se)[-1] + + # Use lambda.1se for sparser solution + coefs <- as.matrix(coef(cv, s=cv$lambda.1se))[-1, 1] coef_df <- data.frame(Marker=rownames(coef(cv,s=cv$lambda.1se))[-1], Effect=as.numeric(coefs)) - coef_df <- coef_df[abs(coef_df$Effect) > 0, ] + coef_df <- coef_df[abs(coef_df$Effect) > 1e-6, ] if (nrow(coef_df)==0) return(data.frame(Message="No non-zero effects")) - + coef_df <- merge(coef_df, marker_info, by="Marker", all.x=TRUE) coef_df <- coef_df[!is.na(coef_df$Position), ] + + # Calculate LOD from effect size (scaled) max_eff <- max(abs(coef_df$Effect)) - coef_df$LOD <- abs(coef_df$Effect) / max_eff * 10 - + coef_df$LOD <- 5 * abs(coef_df$Effect) / max_eff + 1 + + # Calculate PVE for each marker r2_vec <- sapply(coef_df$Marker, function(m) { g <- X_v[,m]; v <- !is.na(g) if (sum(v)<5) return(NA) summary(lm(y_v[v] ~ g[v]))$r.squared * 100 }) + coef_df$PVE_Marker_Percent <- r2_vec coef_df$PVE_CIM_Percent <- r2_vec coef_df$Additive_Effect <- coef_df$Effect coef_df$P_Value <- 10^(-coef_df$LOD) coef_df$SE_Additive <- NA; coef_df$CI_Lower <- NA; coef_df$CI_Upper <- NA - coef_df$Dominance_Effect <- NA; coef_df$Dominance_Ratio <- NA + coef_df$Dominance_Effect <- NA; coef_df$SE_Dominance <- NA + coef_df$Dominance_Ratio <- NA coef_df$Dominance_Class <- "Additive" coef_df$N_Cofactors <- 0 coef_df$N_Samples <- sum(valid) coef_df$Method <- "LASSO" + coef_df <- coef_df[order(coef_df$Chromosome, coef_df$Position), ] coef_df[, c("Marker","Chromosome","Position","LOD","P_Value", "PVE_Marker_Percent","PVE_CIM_Percent","Additive_Effect", "SE_Additive","CI_Lower","CI_Upper","Dominance_Effect", - "Dominance_Ratio","Dominance_Class","N_Cofactors","N_Samples","Method")] + "SE_Dominance","Dominance_Ratio","Dominance_Class","N_Cofactors","N_Samples","Method")] } # ============================================================ -# Elastic Net QTL +# Elastic Net QTL (Enhanced) # ============================================================ qtl_scan_enet <- function(X, y, marker_info) { valid <- !is.na(y) & apply(X, 1, function(r) !any(is.na(r))) X_v <- X[valid,,drop=FALSE]; y_v <- y[valid] - cv <- tryCatch(cv.glmnet(as.matrix(X_v), y_v, alpha=0.5, nfolds=5), error=function(e) NULL) + + # Standardize X + X_scaled <- scale(X_v) + + cv <- tryCatch(cv.glmnet(as.matrix(X_scaled), y_v, alpha=0.5, nfolds=5), error=function(e) NULL) if (is.null(cv)) return(data.frame(Message="Elastic Net failed")) - - coefs <- coef(cv, s=cv$lambda.1se)[-1] + + coefs <- as.matrix(coef(cv, s=cv$lambda.1se))[-1, 1] coef_df <- data.frame(Marker=rownames(coef(cv,s=cv$lambda.1se))[-1], Effect=as.numeric(coefs)) - coef_df <- coef_df[abs(coef_df$Effect) > 0, ] + coef_df <- coef_df[abs(coef_df$Effect) > 1e-6, ] if (nrow(coef_df)==0) return(data.frame(Message="No non-zero effects")) - + coef_df <- merge(coef_df, marker_info, by="Marker", all.x=TRUE) coef_df <- coef_df[!is.na(coef_df$Position), ] + max_eff <- max(abs(coef_df$Effect)) - coef_df$LOD <- abs(coef_df$Effect) / max_eff * 10 - + coef_df$LOD <- 5 * abs(coef_df$Effect) / max_eff + 1 + r2_vec <- sapply(coef_df$Marker, function(m) { g <- X_v[,m]; v <- !is.na(g) if (sum(v)<5) return(NA) summary(lm(y_v[v] ~ g[v]))$r.squared * 100 }) + coef_df$PVE_Marker_Percent <- r2_vec coef_df$PVE_CIM_Percent <- r2_vec coef_df$Additive_Effect <- coef_df$Effect coef_df$P_Value <- 10^(-coef_df$LOD) coef_df$SE_Additive <- NA; coef_df$CI_Lower <- NA; coef_df$CI_Upper <- NA - coef_df$Dominance_Effect <- NA; coef_df$Dominance_Ratio <- NA + coef_df$Dominance_Effect <- NA; coef_df$SE_Dominance <- NA + coef_df$Dominance_Ratio <- NA coef_df$Dominance_Class <- "Additive" coef_df$N_Cofactors <- 0 coef_df$N_Samples <- sum(valid) coef_df$Method <- "ENET" + coef_df <- coef_df[order(coef_df$Chromosome, coef_df$Position), ] coef_df[, c("Marker","Chromosome","Position","LOD","P_Value", "PVE_Marker_Percent","PVE_CIM_Percent","Additive_Effect", "SE_Additive","CI_Lower","CI_Upper","Dominance_Effect", - "Dominance_Ratio","Dominance_Class","N_Cofactors","N_Samples","Method")] + "SE_Dominance","Dominance_Ratio","Dominance_Class","N_Cofactors","N_Samples","Method")] } # ============================================================ -# Random Forest QTL +# Random Forest QTL (Enhanced) # ============================================================ qtl_scan_rf <- function(X, y, marker_info) { valid <- !is.na(y) & apply(X, 1, function(r) !any(is.na(r))) X_v <- X[valid,,drop=FALSE]; y_v <- y[valid] + # Use more trees for better importance estimates rf_fit <- tryCatch( - randomForest(x = X_v, y = y_v, ntree = 500, importance = TRUE), + randomForest(x = X_v, y = y_v, ntree = 1000, importance = TRUE, + mtry = max(1, floor(sqrt(ncol(X_v))))), error = function(e) NULL) if (is.null(rf_fit)) return(data.frame(Message="Random Forest failed")) + # Use %IncMSE for importance imp <- importance(rf_fit, type = 1)[, 1] imp_df <- data.frame(Marker = names(imp), Importance = imp) imp_df <- imp_df[imp_df$Importance > 0, ] @@ -328,7 +797,8 @@ qtl_scan_rf <- function(X, y, marker_info) { imp_df <- imp_df[!is.na(imp_df$Position), ] max_imp <- max(imp_df$Importance) - imp_df$LOD <- imp_df$Importance / max_imp * 10 + # Scale importance to LOD-like scale (0-10) + imp_df$LOD <- 10 * imp_df$Importance / max_imp r2_vec <- sapply(imp_df$Marker, function(m) { g <- X_v[,m]; v <- !is.na(g) @@ -344,6 +814,7 @@ qtl_scan_rf <- function(X, y, marker_info) { imp_df$CI_Lower <- NA imp_df$CI_Upper <- NA imp_df$Dominance_Effect <- NA + imp_df$SE_Dominance <- NA imp_df$Dominance_Ratio <- NA imp_df$Dominance_Class <- "Additive" imp_df$N_Cofactors <- 0 @@ -354,105 +825,81 @@ qtl_scan_rf <- function(X, y, marker_info) { imp_df[, c("Marker","Chromosome","Position","LOD","P_Value", "PVE_Marker_Percent","PVE_CIM_Percent","Additive_Effect", "SE_Additive","CI_Lower","CI_Upper","Dominance_Effect", - "Dominance_Ratio","Dominance_Class","N_Cofactors","N_Samples","Method")] + "SE_Dominance","Dominance_Ratio","Dominance_Class","N_Cofactors","N_Samples","Method")] } # ============================================================ -# MQM — forward stepwise +# MAIN QTL SCAN DISPATCHER # ============================================================ -qtl_scan_mqm <- function(X, y, marker_info) { - valid <- !is.na(y) - X_v <- X[valid,,drop=FALSE]; y_v <- y[valid] - - p_vals <- sapply(colnames(X_v), function(m) { - g <- X_v[,m]; v2 <- !is.na(g) - if (length(unique(g[v2]))<2 || sum(v2)<8) return(1) - tryCatch(coef(summary(lm(y_v[v2]~g[v2])))[2,4], error=function(e) 1) - }) - - selected <- character(0) - threshold <- 0.01 - for (cand in names(sort(p_vals))[1:min(20,length(p_vals))]) { - test_model <- c(selected, cand) - df_t <- data.frame(y=y_v, X_v[,test_model,drop=FALSE])[complete.cases( - data.frame(y=y_v, X_v[,test_model,drop=FALSE])),] - if (nrow(df_t)<10) next - tryCatch({ - fw <- lm(y~.,data=df_t) - wo <- if(length(selected)>0) lm(as.formula(paste("y~",paste(selected,collapse="+"))),data=df_t) else lm(y~1,data=df_t) - p <- anova(wo,fw)[2,"Pr(>F)"] - if (!is.na(p) && p < threshold) selected <- test_model - }, error=function(e) {}) - } - if (length(selected)==0) selected <- names(sort(p_vals))[1:min(5,length(p_vals))] - - results_list <- list() - for (m in colnames(X_v)) { - g <- X_v[,m]; v2 <- !is.na(g)&!is.na(y_v) - gv <- g[v2]; yv <- y_v[v2] - if (length(unique(gv))<2 || length(yv)<8) next - mi <- marker_info[marker_info$Marker==m,] - if (nrow(mi)==0) next - cof_m <- setdiff(selected, m) - tryCatch({ - df2 <- data.frame(y=yv, focal=gv) - if (length(cof_m)>0) { cm <- X_v[v2,cof_m,drop=FALSE]; cm[is.na(cm)]<-0; df2 <- cbind(df2,cm) } - df2 <- df2[complete.cases(df2),] - if (nrow(df2)<8) return(NULL) - ff <- if(length(cof_m)>0) lm(as.formula(paste("y~focal+",paste(cof_m,collapse="+"))),data=df2) else lm(y~focal,data=df2) - fr <- if(length(cof_m)>0) lm(as.formula(paste("y~",paste(cof_m,collapse="+"))),data=df2) else lm(y~1,data=df2) - ct2 <- coef(summary(ff)) - if (!"focal"%in%rownames(ct2)) next - p2 <- ct2["focal","Pr(>|t|)"]; lod2 <- -log10(max(p2,1e-300)) - RF <- sum(residuals(ff)^2); RR <- sum(residuals(fr)^2) - pvc <- if(RR>0) max(0,(RR-RF)/RR*100) else NA - ac <- gv-1; dc <- as.numeric(gv==1); h2 <- length(unique(dc))>1 - le <- if(h2) lm(yv~ac+dc) else lm(yv~ac) - pvm <- max(0,summary(le)$r.squared*100) - ce2 <- coef(le); se2 <- coef(summary(le)) - ae <- ce2["ac"]; sea <- if("ac"%in%rownames(se2)) se2["ac","Std. Error"] else NA - de <- if(h2) ce2["dc"] else NA - dr <- if(!is.na(de)&&!is.na(ae)&&ae!=0) abs(de/ae) else NA - dc2 <- if(is.na(dr)) "Additive" else if(dr>1) "Overdominance" else if(dr>0.5) "Dominance" else if(dr>0.2) "Partial Dom." else "Additive" - results_list[[m]] <- data.frame( - Marker=m, Chromosome=as.character(mi$Chromosome[1]), Position=mi$Position[1], - LOD=lod2, P_Value=p2, PVE_Marker_Percent=pvm, PVE_CIM_Percent=pvc, - Additive_Effect=ae, SE_Additive=sea, - CI_Lower=ifelse(is.na(sea),NA,ae-1.96*sea), CI_Upper=ifelse(is.na(sea),NA,ae+1.96*sea), - Dominance_Effect=de, Dominance_Ratio=dr, Dominance_Class=dc2, - N_Cofactors=length(cof_m), N_Samples=nrow(df2), Method="MQM", - stringsAsFactors=FALSE) - }, error=function(e) {}) +qtl_scan <- function(genotype_matrix, phenotype_vector, marker_info, + method = "CIM", n_cofactors = 10, window_size = 10) { + + cat("\n=== QTL SCAN ===\nMethod:", method, "\n") + + valid_rows <- !is.na(phenotype_vector) + X_valid <- genotype_matrix[valid_rows, , drop = FALSE] + y_valid <- phenotype_vector[valid_rows] + + nzv <- apply(X_valid, 2, function(x) length(unique(na.omit(x))) < 2) + X_valid <- X_valid[, !nzv, drop = FALSE] + cat("Markers after NZV removal:", ncol(X_valid), "\n") + + # Dispatch to appropriate method + if (method == "SIM") { + return(qtl_scan_sim_qtlcart(X_valid, y_valid, marker_info)) + } else if (method == "CIM") { + return(qtl_scan_cim_qtlcart(X_valid, y_valid, marker_info, n_cofactors, window_size)) + } else if (method == "MQM") { + return(qtl_scan_mqm_qtlcart(X_valid, y_valid, marker_info, n_cofactors, window_size)) + } else if (method == "LASSO") { + return(qtl_scan_lasso(X_valid, y_valid, marker_info)) + } else if (method == "ENET") { + return(qtl_scan_enet(X_valid, y_valid, marker_info)) + } else if (method == "RF") { + return(qtl_scan_rf(X_valid, y_valid, marker_info)) + } else { + return(data.frame(Message = paste("Unknown method:", method))) } - if (length(results_list)==0) return(data.frame(Message="MQM produced no results")) - res <- do.call(rbind, results_list) - res[order(res$Chromosome, res$Position),] } # ============================================================ -# LOD SUPPORT INTERVAL +# LOD SUPPORT INTERVAL (QTL Cartographer style) # ============================================================ add_lod_support_interval <- function(sig_df, all_df, lod_drop=1.5) { sig_df$Low_Flank <- sig_df$High_Flank <- NA_character_ sig_df$Interval_Start <- sig_df$Interval_End <- sig_df$Interval_Size_cM <- NA_real_ + for (i in 1:nrow(sig_df)) { - m <- sig_df$Marker[i]; ch <- sig_df$Chromosome[i]; pk <- sig_df$LOD[i] - cd <- all_df[as.character(all_df$Chromosome)==as.character(ch)&!is.na(all_df$LOD)&!is.na(all_df$Position),] - cd <- cd[order(cd$Position),] - if (nrow(cd)==0) next - inc <- cd[cd$LOD>=(pk-lod_drop),]; fp <- cd$Position[cd$Marker==m] - if (nrow(inc)>0 && length(fp)>0) { - s <- min(inc$Position,fp); e <- max(inc$Position,fp) - sig_df$Interval_Start[i] <- s; sig_df$Interval_End[i] <- e - sig_df$Interval_Size_cM[i] <- e-s - below <- cd[cd$Positione,] - sig_df$Low_Flank[i] <- if(nrow(below)>0) below$Marker[nrow(below)] else m - sig_df$High_Flank[i] <- if(nrow(above)>0) above$Marker[1] else m + m <- sig_df$Marker[i] + ch <- as.character(sig_df$Chromosome[i]) + pk <- sig_df$LOD[i] + + cd <- all_df[as.character(all_df$Chromosome) == ch & !is.na(all_df$LOD) & !is.na(all_df$Position), ] + cd <- cd[order(cd$Position), ] + + if (nrow(cd) == 0) next + + # Find interval where LOD >= peak - lod_drop + interval <- cd[cd$LOD >= (pk - lod_drop), ] + fp <- cd$Position[cd$Marker == m] + + if (nrow(interval) > 0 && length(fp) > 0) { + s <- min(interval$Position, fp) + e <- max(interval$Position, fp) + sig_df$Interval_Start[i] <- s + sig_df$Interval_End[i] <- e + sig_df$Interval_Size_cM[i] <- e - s + + # Find flanking markers + below <- cd[cd$Position < s, ] + above <- cd[cd$Position > e, ] + sig_df$Low_Flank[i] <- if(nrow(below) > 0) below$Marker[nrow(below)] else m + sig_df$High_Flank[i] <- if(nrow(above) > 0) above$Marker[1] else m } else { - idx <- which(cd$Marker==m) - if (length(idx)>0) { - sig_df$Low_Flank[i] <- if(idx>1) cd$Marker[idx-1] else m - sig_df$High_Flank[i] <- if(idx 0) { + sig_df$Low_Flank[i] <- if(idx > 1) cd$Marker[idx-1] else m + sig_df$High_Flank[i] <- if(idx < nrow(cd)) cd$Marker[idx+1] else m sig_df$Interval_Start[i] <- sig_df$Interval_End[i] <- sig_df$Position[i] sig_df$Interval_Size_cM[i] <- 0 } @@ -462,159 +909,218 @@ add_lod_support_interval <- function(sig_df, all_df, lod_drop=1.5) { } # ============================================================ -# BEAUTIFUL CHROMOSOME IDIOGRAM PLOT (Pastel Theme) +# VIBRANT CHROMOSOME IDIOGRAM PLOT # ============================================================ make_chromosome_idiogram <- function(qtl_list, all_markers_df, lod_threshold=2.0, trait_colors=NULL) { - if (is.null(all_markers_df)||nrow(all_markers_df)==0) return(NULL) + if (is.null(all_markers_df) || nrow(all_markers_df) == 0) return(NULL) - # Use pastel colors for traits - default_colors <- PASTEL_COLORS + # Use vibrant colors for traits + default_colors <- VIBRANT_COLORS trait_names <- names(qtl_list) if (is.null(trait_colors)) trait_colors <- setNames(default_colors[seq_along(trait_names)], trait_names) - shapes <- c(16,17,18,15,3,4,8,9) + shapes <- c(16, 17, 15, 18, 8, 4, 3, 12) chroms <- sort(unique(as.character(all_markers_df$Chromosome))) x_gap <- 1.2 bar_height <- 0.35 - # Set up plot with pastel background - par(mar=c(4,3,3,1), bg="#FDFBF7", family="sans") - plot(0,0,type="n", - xlim=c(0,length(chroms)*x_gap+0.5), - ylim=c(-2,max(all_markers_df$Position,na.rm=TRUE)*1.08), - xaxt="n",yaxt="n",xlab="",ylab="",main="",frame.plot=FALSE) + # Set up plot with vibrant background + par(mar = c(4, 3, 3, 1), bg = "#1a1a2e", family = "sans") + plot(0, 0, type = "n", + xlim = c(0, length(chroms) * x_gap + 0.5), + ylim = c(-2, max(all_markers_df$Position, na.rm = TRUE) * 1.08), + xaxt = "n", yaxt = "n", xlab = "", ylab = "", frame.plot = FALSE) - max_pos <- max(all_markers_df$Position,na.rm=TRUE) - axis(2,at=pretty(c(0,max_pos),n=6),labels=pretty(c(0,max_pos),n=6), - cex.axis=0.75,col="#C9B99A",col.axis="#7B6E4A",las=1,line=-0.5) - mtext("Genetic Position (cM)",side=2,line=2,cex=0.8,col="#7B6E4A",font=2) + max_pos <- max(all_markers_df$Position, na.rm = TRUE) + axis(2, at = pretty(c(0, max_pos), n = 6), labels = pretty(c(0, max_pos), n = 6), + cex.axis = 0.75, col = "#888888", col.axis = "#cccccc", las = 1, line = -0.5) + mtext("Genetic Position (cM)", side = 2, line = 2, cex = 0.8, col = "#cccccc", font = 2) for (ci in seq_along(chroms)) { - chr <- chroms[ci]; x_cen <- (ci-1)*x_gap+0.7 - chr_mk <- all_markers_df[as.character(all_markers_df$Chromosome)==chr,] - if (nrow(chr_mk)==0) next - chr_len <- max(chr_mk$Position,na.rm=TRUE) - chr_min <- min(chr_mk$Position,na.rm=TRUE) - cap_h <- chr_len*0.02 - - # Chromosome bar with pastel gradient - rect(x_cen-bar_height*0.6,chr_min,x_cen+bar_height*0.6,chr_len, - col="#E8E0D0",border="#C9B99A",lwd=1.5) - rect(x_cen-bar_height*0.6,chr_min-cap_h,x_cen+bar_height*0.6,chr_min, - col="#D5CCB8",border="#C9B99A",lwd=1) - rect(x_cen-bar_height*0.6,chr_len,x_cen+bar_height*0.6,chr_len+cap_h, - col="#D5CCB8",border="#C9B99A",lwd=1) + chr <- chroms[ci] + x_cen <- (ci - 1) * x_gap + 0.7 + chr_mk <- all_markers_df[as.character(all_markers_df$Chromosome) == chr, ] + if (nrow(chr_mk) == 0) next + chr_len <- max(chr_mk$Position, na.rm = TRUE) + chr_min <- min(chr_mk$Position, na.rm = TRUE) + cap_h <- chr_len * 0.02 + + # Chromosome bar with gradient colors + rect(x_cen - bar_height * 0.6, chr_min, + x_cen + bar_height * 0.6, chr_len, + col = "#2d2d44", border = "#ff6b6b", lwd = 2) + rect(x_cen - bar_height * 0.6, chr_min - cap_h, + x_cen + bar_height * 0.6, chr_min, + col = "#1a1a2e", border = "#ff6b6b", lwd = 1.5) + rect(x_cen - bar_height * 0.6, chr_len, + x_cen + bar_height * 0.6, chr_len + cap_h, + col = "#1a1a2e", border = "#ff6b6b", lwd = 1.5) - # Centromere - cen_pos <- chr_min+(chr_len-chr_min)*0.4 - rect(x_cen-bar_height*0.6,cen_pos-chr_len*0.04, - x_cen+bar_height*0.6,cen_pos+chr_len*0.04, - col="#B8A88A",border="#A89878",lwd=0.8) + # Centromere (vibrant red) + cen_pos <- chr_min + (chr_len - chr_min) * 0.4 + rect(x_cen - bar_height * 0.6, cen_pos - chr_len * 0.04, + x_cen + bar_height * 0.6, cen_pos + chr_len * 0.04, + col = "#ff4444", border = "#ff8888", lwd = 1) # Marker tick marks for (mk_pos in chr_mk$Position) - segments(x_cen-bar_height*0.55,mk_pos,x_cen+bar_height*0.55,mk_pos, - col="#D5CCB8",lwd=0.5) + segments(x_cen - bar_height * 0.55, mk_pos, + x_cen + bar_height * 0.55, mk_pos, + col = "#555555", lwd = 0.5) # Plot QTLs for each method for (ti in seq_along(trait_names)) { - tr <- trait_names[ti]; qdf <- qtl_list[[tr]] - if (is.null(qdf)||"Message"%in%colnames(qdf)) next - sig <- qdf[as.character(qdf$Chromosome)==chr&!is.na(qdf$LOD)&qdf$LOD>=lod_threshold,] - if (nrow(sig)==0) next + tr <- trait_names[ti] + qdf <- qtl_list[[tr]] + if (is.null(qdf) || "Message" %in% colnames(qdf)) next + sig <- qdf[as.character(qdf$Chromosome) == chr & !is.na(qdf$LOD) & qdf$LOD >= lod_threshold, ] + if (nrow(sig) == 0) next + col_ti <- trait_colors[[tr]] - pch_ti <- shapes[((ti-1)%%length(shapes))+1] - x_off <- if(ti%%2==1) x_cen+bar_height*0.75 else x_cen-bar_height*0.75 + pch_ti <- shapes[((ti - 1) %% length(shapes)) + 1] + x_off <- if(ti %% 2 == 1) x_cen + bar_height * 0.75 else x_cen - bar_height * 0.75 + for (ri in 1:nrow(sig)) { pos <- sig$Position[ri] - segments(if(ti%%2==1) x_cen+bar_height*0.6 else x_cen-bar_height*0.6, - pos,x_off,pos,col=adjustcolor(col_ti,alpha.f=0.6),lwd=1.2,lty=2) - points(x_off,pos,pch=pch_ti,col=col_ti,bg=col_ti, - cex=pmax(0.8,pmin(2.2,0.6+sig$LOD[ri]/4))) - if (sig$LOD[ri]>=lod_threshold*1.5) - text(x_off+ifelse(ti%%2==1,0.15,-0.15),pos, - round(sig$LOD[ri],1),cex=0.55,col=col_ti,font=2) + segments(if(ti %% 2 == 1) x_cen + bar_height * 0.6 else x_cen - bar_height * 0.6, + pos, x_off, pos, col = adjustcolor(col_ti, alpha.f = 0.6), lwd = 1.5, lty = 2) + points(x_off, pos, pch = pch_ti, col = col_ti, bg = col_ti, + cex = pmax(0.8, pmin(2.5, 0.6 + sig$LOD[ri] / 3))) + if (sig$LOD[ri] >= lod_threshold * 1.5) + text(x_off + ifelse(ti %% 2 == 1, 0.15, -0.15), pos, + round(sig$LOD[ri], 1), cex = 0.55, col = col_ti, font = 2) } } # Chromosome label - text(x_cen,chr_len+cap_h+chr_len*0.05,paste0("Chr ",chr), - cex=0.75,font=2,col="#5D4E30") + text(x_cen, chr_len + cap_h + chr_len * 0.05, paste0("Chr ", chr), + cex = 0.75, font = 2, col = "#ffaa66") } # Legend - if (length(trait_names)>0) { - legend("topright", inset=c(0.02,0.02), - legend=paste0(trait_names," (",sapply(trait_names,function(tr){ + if (length(trait_names) > 0) { + legend("topright", inset = c(0.02, 0.02), + legend = paste0(trait_names, " (", sapply(trait_names, function(tr) { qdf <- qtl_list[[tr]] - if(is.null(qdf)||"Message"%in%colnames(qdf)) return("0") - sum(!is.na(qdf$LOD)&qdf$LOD>=lod_threshold,na.rm=TRUE) - })," QTL)"), - col=unname(trait_colors[trait_names]),pch=shapes[seq_along(trait_names)], - pt.cex=1.2,cex=0.75,bg="#FDFBF7",box.col="#D5CCB8", - title="Models",title.col="#5D4E30",text.col="#5D4E30") + if(is.null(qdf) || "Message" %in% colnames(qdf)) return("0") + sum(!is.na(qdf$LOD) & qdf$LOD >= lod_threshold, na.rm = TRUE) + }), " QTL)"), + col = unname(trait_colors[trait_names]), pch = shapes[seq_along(trait_names)], + pt.cex = 1.2, cex = 0.75, bg = "#1a1a2e", box.col = "#ff6b6b", + title = "Models", title.col = "#ffaa66", text.col = "#ffffff") } - title(main=paste0("🎯 QTL Chromosome Map — LOD ≥ ",lod_threshold), - cex.main=0.95,font.main=1,col.main="#5D4E30",line=1) + title(main = paste0("🎯 QTL Chromosome Map — LOD ≥ ", lod_threshold), + cex.main = 0.95, font.main = 2, col.main = "#ffaa66", line = 1) } # ============================================================ -# BEAUTIFUL PLOTLY MANHATTAN (Pastel Theme) +# VIBRANT PLOTLY MANHATTAN # ============================================================ make_plotly_manhattan <- function(scan_all, lod_threshold=2.0, title="QTL Manhattan Plot") { - blank <- plot_ly()%>%layout(title=title,plot_bgcolor="#FDFBF7",paper_bgcolor="#FDFBF7") - if (is.null(scan_all)||"Message"%in%colnames(scan_all)) return(blank) - pd <- scan_all[!is.na(scan_all$LOD)&!is.na(scan_all$Position)&!is.na(scan_all$Chromosome),] - if (nrow(pd)==0) return(blank) + blank <- plot_ly() %>% layout( + title = title, + plot_bgcolor = "#1a1a2e", + paper_bgcolor = "#1a1a2e" + ) + + if (is.null(scan_all) || "Message" %in% colnames(scan_all)) return(blank) + + pd <- scan_all[!is.na(scan_all$LOD) & !is.na(scan_all$Position) & !is.na(scan_all$Chromosome), ] + if (nrow(pd) == 0) return(blank) + pd$Chromosome <- as.character(pd$Chromosome) - chroms <- sort(unique(pd$Chromosome),method="radix") - offsets <- numeric(length(chroms)); names(offsets) <- chroms + chroms <- sort(unique(pd$Chromosome), method = "radix") + offsets <- numeric(length(chroms)) + names(offsets) <- 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 + next + } + prev_chr <- chroms[i-1] + offsets[chroms[i]] <- offsets[prev_chr] + max(pd$Position[pd$Chromosome == prev_chr], 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) - - # Pastel colors for chromosomes - chr_colors <- rep(c("#A8E6CF", "#DCEDC1", "#FFD3B6", "#FFAAA5", "#FF8B94", - "#B5EAD7", "#C7CEEA", "#E2F0CB", "#FFDAC1", "#E6C8A0"), - ceiling(length(chroms)/10))[seq_along(chroms)] + + 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) + + # Vibrant colors for chromosomes + chr_colors <- rep(c("#FF6B6B", "#4ECDC4", "#45B7D1", "#96CEB4", "#FFEAA7", + "#DDA0DD", "#F0E68C", "#FFB347", "#87CEEB", "#FF69B4"), + ceiling(length(chroms) / 10))[seq_along(chroms)] names(chr_colors) <- chroms p <- plot_ly() + for (ch in chroms) { - sub <- pd[pd$Chromosome==ch,] - p <- p%>%add_trace(data=sub,x=~cum_pos,y=~LOD,type="scatter",mode="markers", - name=paste("Chr",ch),marker=list(size=6,color=chr_colors[ch],opacity=0.7, - line=list(width=0.5,color="#FFFFFF")), - text=~paste0("",Marker,"
📊 Chr: ",Chromosome,"
📍 Pos: ",round(Position,1), - " cM
📈 LOD: ",round(LOD,2),"
🎯 PVE: ",round(PVE_Marker_Percent,1),"%", - "
⚡ Additive: ",round(Additive_Effect,3)), - hoverinfo="text",showlegend=FALSE) + sub <- pd[pd$Chromosome == ch, ] + p <- p %>% add_trace( + data = sub, x = ~cum_pos, y = ~LOD, + type = "scatter", mode = "markers", + name = paste("Chr", ch), + marker = list(size = 7, color = chr_colors[ch], opacity = 0.8, + line = list(width = 0.5, color = "#ffffff")), + text = ~paste0("", Marker, "
📊 Chr: ", Chromosome, + "
📍 Pos: ", round(Position, 1), " cM", + "
📈 LOD: ", round(LOD, 2), + "
🎯 PVE: ", round(PVE_Marker_Percent, 1), "%", + "
⚡ Additive: ", round(Additive_Effect, 3)), + hoverinfo = "text", + showlegend = FALSE + ) } - sig_pd <- pd[pd$sig,] - if (nrow(sig_pd)>0) - p <- p%>%add_trace(data=sig_pd,x=~cum_pos,y=~LOD,type="scatter",mode="markers", - name="Significant",marker=list(size=11,color="#E15759",symbol="diamond", - line=list(width=1,color="#FFFFFF")), - text=~paste0("🔥 ",Marker," 🔥
📊 Chr: ",Chromosome,"
📍 Pos: ",round(Position,1), - " cM
📈 LOD: ",round(LOD,2),"
🎯 PVE: ",round(PVE_Marker_Percent,1),"%"), - hoverinfo="text") - p%>%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="#E15759",dash="dash",width=1.5),showlegend=FALSE)%>% - layout(title=list(text=paste0("🧬 ",title," | ✨ ",sum(pd$sig,na.rm=TRUE)," significant QTLs"), - font=list(size=15,color="#5D4E30",family="sans")), - xaxis=list(title="Chromosome",tickvals=as.list(chr_mids[chroms]), - ticktext=as.list(paste0("Chr ",chroms)),tickangle=45, - gridcolor="#F0EBE0",color="#8B7A5A",zeroline=FALSE), - yaxis=list(title="LOD Score",gridcolor="#F0EBE0",color="#8B7A5A",zeroline=FALSE), - plot_bgcolor="#FDFBF7",paper_bgcolor="#FDFBF7",font=list(color="#5D4E30",family="sans"), - legend=list(orientation="h",y=-0.12,font=list(size=10)), - hoverlabel=list(bgcolor="#FFFFFF",font=list(color="#5D4E30",size=11))) + + sig_pd <- pd[pd$sig, ] + if (nrow(sig_pd) > 0) { + p <- p %>% add_trace( + data = sig_pd, x = ~cum_pos, y = ~LOD, + type = "scatter", mode = "markers", + name = "Significant", + marker = list(size = 13, color = "#FF1493", symbol = "diamond", + line = list(width = 1.5, color = "#ffffff")), + text = ~paste0("🔥 ", Marker, " 🔥
📊 Chr: ", Chromosome, + "
📍 Pos: ", round(Position, 1), " cM", + "
📈 LOD: ", round(LOD, 2), + "
🎯 PVE: ", round(PVE_Marker_Percent, 1), "%"), + hoverinfo = "text" + ) + } + + p %>% 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 = "#FF1493", dash = "dash", width = 2), + showlegend = FALSE + ) %>% layout( + title = list( + text = paste0("🧬 ", title, " | ✨ ", sum(pd$sig, na.rm = TRUE), " significant QTLs"), + font = list(size = 16, color = "#ffaa66", family = "sans") + ), + xaxis = list( + title = "Chromosome", + tickvals = as.list(chr_mids[chroms]), + ticktext = as.list(paste0("Chr ", chroms)), + tickangle = 45, + gridcolor = "#333344", + color = "#cccccc", + zeroline = FALSE + ), + yaxis = list( + title = "LOD Score", + gridcolor = "#333344", + color = "#cccccc", + zeroline = FALSE + ), + plot_bgcolor = "#1a1a2e", + paper_bgcolor = "#1a1a2e", + font = list(color = "#cccccc", family = "sans"), + legend = list(orientation = "h", y = -0.12, font = list(size = 10, color = "#cccccc")), + hoverlabel = list(bgcolor = "#2d2d44", font = list(color = "#ffffff", size = 11)) + ) } # ============================================================ @@ -624,13 +1130,16 @@ find_common_qtl <- function(compare_res, lod_threshold, min_models=2, window_cM= sig_list <- list() for (mth in names(compare_res)) { r <- compare_res[[mth]] - if (is.null(r)||"Message"%in%colnames(r)) next - sig <- r[!is.na(r$LOD)&r$LOD>=lod_threshold, - c("Marker","Chromosome","Position","LOD","PVE_Marker_Percent","Additive_Effect"), - drop=FALSE] - if (nrow(sig)>0) { sig$Model <- mth; sig_list[[mth]] <- sig } + if (is.null(r) || "Message" %in% colnames(r)) next + sig <- r[!is.na(r$LOD) & r$LOD >= lod_threshold, + c("Marker", "Chromosome", "Position", "LOD", "PVE_Marker_Percent", "Additive_Effect"), + drop = FALSE] + if (nrow(sig) > 0) { + sig$Model <- mth + sig_list[[mth]] <- sig + } } - if (length(sig_list)==0) return(NULL) + if (length(sig_list) == 0) return(NULL) all_sig <- do.call(rbind, sig_list) all_sig$Chromosome <- as.character(all_sig$Chromosome) @@ -639,20 +1148,20 @@ find_common_qtl <- function(compare_res, lod_threshold, min_models=2, window_cM= all_sig$N_Models_Detected <- as.integer(marker_counts[all_sig$Marker]) common <- all_sig[all_sig$N_Models_Detected >= min_models, ] - if (nrow(common)==0) return(NULL) + if (nrow(common) == 0) return(NULL) markers_uniq <- unique(common$Marker) summary_rows <- lapply(markers_uniq, 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$Mean_Add_Eff <- round(mean(rows$Additive_Effect, na.rm=TRUE), 3) + 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$Mean_Add_Eff <- round(mean(rows$Additive_Effect, na.rm = TRUE), 3) for (mth in names(compare_res)) { - r_mth <- rows[rows$Model==mth, ] - base[[paste0("LOD_",mth)]] <- if(nrow(r_mth)>0) round(r_mth$LOD[1],3) else NA + r_mth <- rows[rows$Model == mth, ] + base[[paste0("LOD_", mth)]] <- if(nrow(r_mth) > 0) round(r_mth$LOD[1], 3) else NA } base }) @@ -661,32 +1170,41 @@ find_common_qtl <- function(compare_res, lod_threshold, min_models=2, window_cM= } # ============================================================ -# UI +# UI (Updated with vibrant theme) # ============================================================ ui <- fluidPage( shinyjs::useShinyjs(), tags$head( - tags$link(rel="stylesheet", - href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap"), + tags$link(rel = "stylesheet", + href = "https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap"), tags$style(HTML(" :root{ - --bg:#FDFBF7;--card:#FFFFFF;--border:#EBE5D9; - --txt:#4A3B28;--muted:#8B7A5A;--accent:#7BA07A; - --green:#6B9E6B;--red:#D98A7A;--orange:#D9A87A; - --purple:#9B8BB0;--teal:#7AA89B; + --bg-dark: #0f0f23; + --bg-card: #1a1a2e; + --bg-hover: #2d2d44; + --border: #ff6b6b; + --txt: #ffffff; + --muted: #aaaaaa; + --accent: #ff6b6b; + --green: #4ecdc4; + --red: #ff6b6b; + --orange: #ffb347; + --purple: #dda0dd; + --teal: #45b7d1; + --gold: #ffd700; } *{box-sizing:border-box;} body{ font-family:'Inter',sans-serif; - background:var(--bg); + background:var(--bg-dark); color:var(--txt); font-size:14px; margin:0; } .navbar{ - background:#FFFFFF!important; + background:var(--bg-card)!important; border-bottom:2px solid var(--accent)!important; - box-shadow:0 2px 8px rgba(0,0,0,0.03); + box-shadow:0 2px 8px rgba(0,0,0,0.3); } .navbar-brand{ font-weight:600; @@ -704,15 +1222,15 @@ ui <- fluidPage( border-bottom:2px solid var(--accent); } .card{ - background:var(--card); + background:var(--bg-card); border:1px solid var(--border); border-radius:12px; margin-bottom:20px; - box-shadow:0 2px 6px rgba(0,0,0,0.03); + box-shadow:0 4px 12px rgba(0,0,0,0.2); overflow:hidden; } .card-hd{ - background:#F8F6F2; + background:#2d2d44; border-bottom:1px solid var(--border); padding:12px 16px; font-size:12px; @@ -725,34 +1243,34 @@ ui <- fluidPage( padding:16px; } .info-box{ - background:#F2F6EF; - border:1px solid #D4E2D0; - border-left:3px solid var(--accent); + background:#2d2d44; + border:1px solid var(--teal); + border-left:3px solid var(--teal); border-radius:8px; padding:12px 16px; margin:8px 0; font-size:13px; - color:#5A7A4A; + color:var(--txt); } .warn-box{ - background:#FFF8F0; - border:1px solid #F5E6D0; + background:#2d2d44; + border:1px solid var(--orange); border-left:3px solid var(--orange); border-radius:8px; padding:12px 16px; margin:8px 0; font-size:13px; - color:#A87A4A; + color:var(--txt); } .good-box{ - background:#F0F6F0; - border:1px solid #D4E2D0; + background:#2d2d44; + border:1px solid var(--green); border-left:3px solid var(--green); border-radius:8px; padding:12px 16px; margin:8px 0; font-size:13px; - color:#4A7A4A; + color:var(--txt); } .btn{ border-radius:8px; @@ -764,42 +1282,33 @@ ui <- fluidPage( .btn-primary{ background:var(--accent); border-color:var(--accent); - color:#FFF; + color:#fff; } .btn-primary:hover{ - background:#5A8A5A; - border-color:#5A8A5A; + background:#ff8888; + border-color:#ff8888; transform:translateY(-1px); } .btn-success{ background:var(--green); border-color:var(--green); - color:#FFF; + color:#1a1a2e; } .btn-success:hover{ - background:#5A8A5A; + background:#6dd5cc; transform:translateY(-1px); } .btn-info{ background:var(--teal); border-color:var(--teal); - color:#FFF; + color:#1a1a2e; } .btn-info:hover{ - background:#5A8A7A; + background:#6dc5d1; transform:translateY(-1px); } - .btn-outline{ - background:transparent; - border-color:var(--accent); - color:var(--accent); - } - .btn-outline:hover{ - background:var(--accent); - color:#FFF; - } .form-control,.selectize-input{ - background:#FFF!important; + background:#2d2d44!important; border:1px solid var(--border)!important; color:var(--txt)!important; font-size:13px; @@ -812,19 +1321,19 @@ ui <- fluidPage( } .model-badge{ display:inline-block; - background:#F2F6EF; - border:1px solid #D4E2D0; + background:#2d2d44; + border:1px solid var(--teal); border-radius:20px; padding:4px 12px; font-size:11px; font-weight:600; - color:var(--accent); + color:var(--teal); margin-right:8px; } .common-badge{ display:inline-block; - background:#F0F6F0; - border:1px solid #D4E2D0; + background:#2d2d44; + border:1px solid var(--green); border-radius:20px; padding:4px 12px; font-size:11px; @@ -833,21 +1342,24 @@ ui <- fluidPage( margin-right:8px; } table.dataTable{ - background:#FFF!important; + background:var(--bg-card)!important; border-radius:8px; overflow:hidden; } table.dataTable thead th{ - background:#F8F6F2!important; + background:#2d2d44!important; font-weight:600; font-size:12px; - color:var(--muted); + color:var(--accent); + } + table.dataTable tbody td{ + color:var(--txt); } table.dataTable tbody tr:hover{ - background:#F8F6F2!important; + background:var(--bg-hover)!important; } .stat-value{ - font-size:24px; + font-size:28px; font-weight:700; color:var(--accent); } @@ -857,77 +1369,83 @@ ui <- fluidPage( text-transform:uppercase; letter-spacing:1px; } + .shiny-input-container{ + color:var(--txt); + } ")) ), navbarPage( - title = tags$span(tags$i(class="fas fa-leaf",style="color:#7BA07A;margin-right:8px;"), "QTL-Mapper v6"), + title = tags$span(tags$i(class = "fas fa-dna", style = "color:#ff6b6b;margin-right:8px;"), "QTL-Mapper v7"), id = "nav", + theme = "darkly", # ── DATA UPLOAD ────────────────────────────────────────── - tabPanel("📁 Data Upload", icon=icon("upload"), + tabPanel("📁 Data Upload", icon = icon("upload"), fluidRow(column(12, - div(class="info-box", - tags$i(class="fas fa-info-circle", style="margin-right:8px;"), - tags$b("QTL-Mapper v6 — Multi-Model QTL Analysis"), + div(class = "info-box", + tags$i(class = "fas fa-info-circle", style = "margin-right:8px;"), + tags$b("QTL-Mapper v7 — QTL Cartographer Compatible Multi-Model QTL Analysis"), tags$br(), - "Format: Row1=header (id,marker1,...), Row2=chromosomes, Row3=positions (cM), rows4+=samples. Genotypes coded 0/1/2 (homozygous/heterozygous/other homozygous)." + "Format: Row1=header (id,marker1,...), Row2=chromosomes, Row3=positions (cM), rows4+=samples. Genotypes coded 0/1/2 (homozygous/heterozygous/other homozygous).", + tags$br(), + tags$span(style = "color:#4ecdc4;", "✨ SIM, CIM, MQM now fully compatible with QTL Cartographer algorithms!") ) )), fluidRow( column(4, - div(class="card", - div(class="card-hd",tags$i(class="fas fa-dna",style="margin-right:6px;"),"Training Data"), - div(class="card-bd", - fileInput("geno_file","📊 Genotype CSV",accept=".csv",buttonLabel="Browse",placeholder="No file selected"), - fileInput("pheno_file","📈 Phenotype CSV",accept=".csv",buttonLabel="Browse",placeholder="No file selected"), - selectInput("pheno_col","Select Trait/Phenotype",choices=NULL), - tags$hr(style="margin:12px 0;border-color:#EBE5D9;"), - fileInput("test_geno_file","🧪 Test Genotype CSV (optional)",accept=".csv"), - fileInput("pop_file","👥 Population Metadata CSV (optional)",accept=".csv"), + div(class = "card", + div(class = "card-hd", tags$i(class = "fas fa-dna", style = "margin-right:6px;"), "Training Data"), + div(class = "card-bd", + fileInput("geno_file", "📊 Genotype CSV", accept = ".csv", buttonLabel = "Browse", placeholder = "No file selected"), + fileInput("pheno_file", "📈 Phenotype CSV", accept = ".csv", buttonLabel = "Browse", placeholder = "No file selected"), + selectInput("pheno_col", "Select Trait/Phenotype", choices = NULL), + tags$hr(style = "margin:12px 0;border-color:#2d2d44;"), + fileInput("test_geno_file", "🧪 Test Genotype CSV (optional)", accept = ".csv"), + fileInput("pop_file", "👥 Population Metadata CSV (optional)", accept = ".csv"), helpText("Pop CSV: columns 'id' and 'population'") ) ) ), column(4, - div(class="card", - div(class="card-hd",tags$i(class="fas fa-sliders-h",style="margin-right:6px;"),"Mapping Parameters"), - div(class="card-bd", - selectInput("mapping_method","🎯 Mapping Method", - choices=setNames(names(MAPPING_MODELS), sapply(MAPPING_MODELS,`[[`,"label")), - selected="CIM"), + div(class = "card", + div(class = "card-hd", tags$i(class = "fas fa-sliders-h", style = "margin-right:6px;"), "Mapping Parameters"), + div(class = "card-bd", + selectInput("mapping_method", "🎯 Mapping Method", + 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), + 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,step=1), - numericInput("window_size","🚫 Exclusion Window (±markers)",value=10,min=1,max=30,step=1) + numericInput("n_cofactors", "🔧 Max Cofactors (K)", value = 10, min = 1, max = 30, step = 1), + numericInput("window_size", "🚫 Exclusion Window (±markers)", value = 10, min = 1, max = 30, step = 1) ), - numericInput("lod_drop","📏 LOD Drop for Interval",value=1.5,min=0.5,max=3.0,step=0.5), - actionButton("run_btn","▶ Run QTL Analysis",class="btn btn-primary btn-block", - style="margin-top:12px;width:100%;") + numericInput("lod_drop", "📏 LOD Drop for Interval", value = 1.5, min = 0.5, max = 3.0, step = 0.5), + actionButton("run_btn", "▶ Run QTL Analysis", class = "btn btn-primary btn-block", + style = "margin-top:12px;width:100%;") ) ) ), column(4, - div(class="card", - div(class="card-hd",tags$i(class="fas fa-chart-pie",style="margin-right:6px;"),"Dataset Summary"), - div(class="card-bd", uiOutput("dataset_info_ui")) + div(class = "card", + div(class = "card-hd", tags$i(class = "fas fa-chart-pie", style = "margin-right:6px;"), "Dataset Summary"), + div(class = "card-bd", uiOutput("dataset_info_ui")) ), - div(class="card", - div(class="card-hd",tags$i(class="fas fa-chart-line",style="margin-right:6px;"),"Predict Test Phenotypes"), - div(class="card-bd", - actionButton("pred_btn","🔮 Predict Test Samples",class="btn btn-info btn-block"), + div(class = "card", + div(class = "card-hd", tags$i(class = "fas fa-chart-line", style = "margin-right:6px;"), "Predict Test Phenotypes"), + div(class = "card-bd", + actionButton("pred_btn", "🔮 Predict Test Samples", class = "btn btn-info btn-block"), tags$br(), - downloadButton("dl_pred","💾 Download Predictions (.xlsx)",class="btn btn-success btn-block") + downloadButton("dl_pred", "💾 Download Predictions (.xlsx)", class = "btn btn-success btn-block") ) ) ) ), fluidRow(column(12, - div(class="card", - div(class="card-hd","📋 Data Preview"), - div(class="card-bd", + div(class = "card", + div(class = "card-hd", "📋 Data Preview"), + div(class = "card-bd", tabsetPanel( tabPanel("Training Genotype", DTOutput("prev_geno")), tabPanel("Training Phenotype", DTOutput("prev_pheno")), @@ -940,126 +1458,128 @@ ui <- fluidPage( ), # ── RESULTS ────────────────────────────────────────────── - tabPanel("📊 Results", icon=icon("chart-line"), + tabPanel("📊 Results", icon = icon("chart-line"), fluidRow( column(12, - div(style="display:flex;gap:12px;flex-wrap:wrap;margin-bottom:16px;", - downloadButton("dl_manhattan","📸 Manhattan Plot",class="btn btn-primary"), - downloadButton("dl_idiogram","🗺️ Chromosome Map",class="btn btn-info"), - downloadButton("dl_results","📥 Full Results (.xlsx)",class="btn btn-success") + div(style = "display:flex;gap:12px;flex-wrap:wrap;margin-bottom:16px;", + downloadButton("dl_manhattan", "📸 Manhattan Plot", class = "btn btn-primary"), + downloadButton("dl_idiogram", "🗺️ Chromosome Map", class = "btn btn-info"), + downloadButton("dl_results", "📥 Full Results (.xlsx)", class = "btn btn-success") ) ) ), fluidRow( column(7, - div(class="card", - div(class="card-hd","🧬 Manhattan Plot — LOD Scores Across Genome"), - div(class="card-bd",plotlyOutput("manhattan_plot",height="500px")) + div(class = "card", + div(class = "card-hd", "🧬 Manhattan Plot — LOD Scores Across Genome"), + div(class = "card-bd", plotlyOutput("manhattan_plot", height = "500px")) ) ), column(5, - div(class="card", - div(class="card-hd","🗺️ Chromosome Idiogram — QTL Positions"), - div(class="card-bd",plotOutput("idiogram_plot",height="500px")) + div(class = "card", + div(class = "card-hd", "🗺️ Chromosome Idiogram — QTL Positions"), + div(class = "card-bd", plotOutput("idiogram_plot", height = "500px")) ) ) ), fluidRow( column(4, - div(class="card", - div(class="card-hd","📊 Model Performance Metrics"), - div(class="card-bd",plotlyOutput("perf_plot",height="280px")) + div(class = "card", + div(class = "card-hd", "📊 Model Performance Metrics"), + div(class = "card-bd", plotlyOutput("perf_plot", height = "280px")) ) ), column(4, - div(class="card", - div(class="card-hd","🎯 Training: Predicted vs Observed"), - div(class="card-bd",plotlyOutput("reg_train",height="280px")) + div(class = "card", + div(class = "card-hd", "🎯 Training: Predicted vs Observed"), + div(class = "card-bd", plotlyOutput("reg_train", height = "280px")) ) ), column(4, - div(class="card", - div(class="card-hd","✅ Validation: Predicted vs Observed"), - div(class="card-bd",plotlyOutput("reg_val",height="280px")) + div(class = "card", + div(class = "card-hd", "✅ Validation: Predicted vs Observed"), + div(class = "card-bd", plotlyOutput("reg_val", height = "280px")) ) ) ), fluidRow(column(12, - div(class="card", - div(class="card-hd","🔥 Significant QTLs — Above LOD Threshold"), - div(class="card-bd",DTOutput("qtl_table")) + div(class = "card", + div(class = "card-hd", "🔥 Significant QTLs — Above LOD Threshold"), + div(class = "card-bd", DTOutput("qtl_table")) ) )), fluidRow(column(12, - div(class="card", - div(class="card-hd","📈 Full Genome Scan Results (All Markers)"), - div(class="card-bd",DTOutput("full_scan_table")) + div(class = "card", + div(class = "card-hd", "📈 Full Genome Scan Results (All Markers)"), + div(class = "card-bd", DTOutput("full_scan_table")) ) )) ), # ── COMPARE MODELS ──────────────────────────────────────── - tabPanel("⚖️ Compare Models", icon=icon("balance-scale"), + tabPanel("⚖️ Compare Models", icon = icon("balance-scale"), fluidRow(column(12, - div(class="card", - div(class="card-hd","🔄 Multi-Model Comparison"), - div(class="card-bd", - div(class="warn-box", - tags$i(class="fas fa-info-circle",style="margin-right:6px;"), - "Select models to compare. Each will run a full genome scan. Results will be displayed across tabs." + div(class = "card", + div(class = "card-hd", "🔄 Multi-Model Comparison"), + div(class = "card-bd", + div(class = "warn-box", + tags$i(class = "fas fa-info-circle", style = "margin-right:6px;"), + "Select models to compare. Each will run a full genome scan. Results will be displayed across tabs.", + tags$br(), + tags$span(style = "color:#4ecdc4;", "✨ SIM, CIM, MQM use QTL Cartographer compatible algorithms!") ), - checkboxGroupInput("compare_methods","Methods to Compare:", - choices=setNames(names(MAPPING_MODELS),sapply(MAPPING_MODELS,`[[`,"label")), - selected=c("SIM","CIM","LASSO"),inline=TRUE), - actionButton("run_compare","🚀 Run All Selected Models",class="btn btn-primary"), - tags$br(),tags$br(), + checkboxGroupInput("compare_methods", "Methods to Compare:", + choices = setNames(names(MAPPING_MODELS), sapply(MAPPING_MODELS, `[[`, "label")), + selected = c("SIM", "CIM", "LASSO"), inline = TRUE), + actionButton("run_compare", "🚀 Run All Selected Models", class = "btn btn-primary"), + tags$br(), tags$br(), uiOutput("compare_status_ui") ) ) )), fluidRow( column(6, - div(class="card", - div(class="card-hd","🗺️ Multi-Model Chromosome Map"), - div(class="card-bd",plotOutput("compare_idiogram",height="520px")) + div(class = "card", + div(class = "card-hd", "🗺️ Multi-Model Chromosome Map"), + div(class = "card-bd", plotOutput("compare_idiogram", height = "520px")) ) ), column(6, - div(class="card", - div(class="card-hd","📊 QTL Count by Method & Chromosome"), - div(class="card-bd",plotlyOutput("compare_bar",height="520px")) + div(class = "card", + div(class = "card-hd", "📊 QTL Count by Method & Chromosome"), + div(class = "card-bd", plotlyOutput("compare_bar", height = "520px")) ) ) ), fluidRow(column(12, - div(class="card", - div(class="card-hd","📋 All Significant QTLs — All Models"), - div(class="card-bd",DTOutput("compare_table")) + div(class = "card", + div(class = "card-hd", "📋 All Significant QTLs — All Models"), + div(class = "card-bd", DTOutput("compare_table")) ) )) ), # ── COMMON QTL ─────────────────────────────────────────── - tabPanel("🎯 Common QTL", icon=icon("bullseye"), + tabPanel("🎯 Common QTL", icon = icon("bullseye"), fluidRow(column(12, - div(class="card", - div(class="card-hd", - tags$i(class="fas fa-bullseye",style="margin-right:6px;color:#6B9E6B;"), + div(class = "card", + div(class = "card-hd", + tags$i(class = "fas fa-bullseye", style = "margin-right:6px;color:#4ecdc4;"), "Common QTL — Markers Detected Across Multiple Models"), - div(class="card-bd", + div(class = "card-bd", fluidRow( column(4, - sliderInput("min_models","🎲 Minimum Models Agreeing", - min=2, max=6, value=2, step=1) + sliderInput("min_models", "🎲 Minimum Models Agreeing", + min = 2, max = 6, value = 2, step = 1) ), column(4, - div(style="margin-top:28px;", - downloadButton("dl_common_qtl","💾 Download Common QTL (.xlsx)", - class="btn btn-success btn-block") + div(style = "margin-top:28px;", + downloadButton("dl_common_qtl", "💾 Download Common QTL (.xlsx)", + class = "btn btn-success btn-block") ) ), column(4, - div(style="margin-top:18px;", + div(style = "margin-top:18px;", uiOutput("common_qtl_summary_ui") ) ) @@ -1069,24 +1589,24 @@ ui <- fluidPage( )), fluidRow( column(6, - div(class="card", - div(class="card-hd","🗺️ Common QTL — Chromosome Map"), - div(class="card-bd",plotOutput("common_idiogram",height="500px")) + div(class = "card", + div(class = "card-hd", "🗺️ Common QTL — Chromosome Map"), + div(class = "card-bd", plotOutput("common_idiogram", height = "500px")) ) ), column(6, - div(class="card", - div(class="card-hd","📊 Model Agreement by Chromosome"), - div(class="card-bd",plotlyOutput("common_bar",height="500px")) + div(class = "card", + div(class = "card-hd", "📊 Model Agreement by Chromosome"), + div(class = "card-bd", plotlyOutput("common_bar", height = "500px")) ) ) ), fluidRow(column(12, - div(class="card", - div(class="card-hd","📋 Common QTL Details"), - div(class="card-bd", - div(class="good-box", - tags$i(class="fas fa-star",style="margin-right:6px;"), + div(class = "card", + div(class = "card-hd", "📋 Common QTL Details"), + div(class = "card-bd", + div(class = "good-box", + tags$i(class = "fas fa-star", style = "margin-right:6px;"), "Markers shown here are significant in at least the number of models selected above.", tags$br(), "👉 Run the Compare Models tab first to populate this table." @@ -1099,84 +1619,86 @@ ui <- fluidPage( ), # ── DOMESTICATION ──────────────────────────────────────── - tabPanel("🌾 Domestication", icon=icon("leaf"), + tabPanel("🌾 Domestication", icon = icon("leaf"), fluidRow( column(4, - div(class="card", - div(class="card-hd","⚙️ Selection Parameters"), - div(class="card-bd", - numericInput("fst_thr","📊 Fst Threshold",value=0.1,min=0.05,max=0.5,step=0.01), - numericInput("tajima_thr","📉 Tajima's D Threshold",value=-1,min=-5,max=0,step=0.1), - actionButton("run_dom","🌿 Run Domestication Analysis",class="btn btn-primary btn-block") + div(class = "card", + div(class = "card-hd", "⚙️ Selection Parameters"), + div(class = "card-bd", + numericInput("fst_thr", "📊 Fst Threshold", value = 0.1, min = 0.05, max = 0.5, step = 0.01), + numericInput("tajima_thr", "📉 Tajima's D Threshold", value = -1, min = -5, max = 0, step = 0.1), + actionButton("run_dom", "🌿 Run Domestication Analysis", class = "btn btn-primary btn-block") ) ) ), column(8, - div(class="card", - div(class="card-hd","👥 Population Data"), - div(class="card-bd",DTOutput("prev_pop")) + div(class = "card", + div(class = "card-hd", "👥 Population Data"), + div(class = "card-bd", DTOutput("prev_pop")) ) ) ), fluidRow( column(6, - div(class="card", - div(class="card-hd","🧬 Fst Manhattan Plot"), - div(class="card-bd",plotlyOutput("fst_plot",height="400px")) + div(class = "card", + div(class = "card-hd", "🧬 Fst Manhattan Plot"), + div(class = "card-bd", plotlyOutput("fst_plot", height = "400px")) ) ), column(6, - div(class="card", - div(class="card-hd","📉 Tajima's D Manhattan Plot"), - div(class="card-bd",plotlyOutput("tajima_plot",height="400px")) + div(class = "card", + div(class = "card-hd", "📉 Tajima's D Manhattan Plot"), + div(class = "card-bd", plotlyOutput("tajima_plot", height = "400px")) ) ) ), fluidRow(column(12, - div(class="card", - div(class="card-hd","🔍 Selection Signatures"), - div(class="card-bd", + div(class = "card", + div(class = "card-hd", "🔍 Selection Signatures"), + div(class = "card-bd", DTOutput("sel_table"), tags$br(), - downloadButton("dl_sel","💾 Download Selection Results (.xlsx)",class="btn btn-success") + downloadButton("dl_sel", "💾 Download Selection Results (.xlsx)", class = "btn btn-success") ) ) )) ), # ── ABOUT ──────────────────────────────────────────────── - tabPanel("ℹ️ About", icon=icon("info-circle"), - fluidRow(column(10,offset=1, - div(class="card", - div(class="card-bd", - tags$h4(style="color:#7BA07A;margin-bottom:16px;","🧬 QTL-Mapper v6 — Comprehensive QTL Analysis Platform"), - div(class="info-box", + tabPanel("ℹ️ About", icon = icon("info-circle"), + fluidRow(column(10, offset = 1, + div(class = "card", + div(class = "card-bd", + tags$h4(style = "color:#ff6b6b;margin-bottom:16px;", "🧬 QTL-Mapper v7 — QTL Cartographer Compatible QTL Analysis Platform"), + div(class = "info-box", tags$b("✨ Key Features:"), tags$br(), "• 6 Mapping Models: SIM, CIM, MQM, LASSO, Elastic Net, Random Forest", tags$br(), + "• SIM, CIM, MQM fully compatible with QTL Cartographer algorithms", tags$br(), + "• Likelihood ratio based LOD scores (QTL Cartographer style)", tags$br(), + "• Forward stepwise cofactor selection for CIM and MQM", tags$br(), "• Interactive Manhattan plots with hover information", tags$br(), - "• Chromosome idiogram visualization", tags$br(), + "• Vibrant dark-themed chromosome idiogram visualization", tags$br(), "• Multi-model comparison and common QTL detection", tags$br(), "• Domestication selection signature analysis (Fst, Tajima's D)", tags$br(), "• Test population prediction", tags$br(), - "• Beautiful pastel-themed visualizations" + "• Vibrant dark-themed visualizations" ), - tags$h5(style="margin-top:20px;font-weight:600;","📚 Mapping Methods"), + tags$h5(style = "margin-top:20px;font-weight:600;color:#ffaa66;", "📚 Mapping Methods"), tags$ul(lapply(MAPPING_MODELS, function(m) - tags$li(tags$b(m$label),"—",m$desc,style="margin-bottom:6px;"))), - tags$h5(style="margin-top:20px;font-weight:600;","📖 References"), + tags$li(tags$b(m$label, style = "color:#4ecdc4;"), "—", m$desc, style = "margin-bottom:6px;color:#cccccc;"))), + tags$h5(style = "margin-top:20px;font-weight:600;color:#ffaa66;", "📖 References"), tags$ul( tags$li("Lander & Botstein (1989) Genetics 121:185 — LOD intervals"), tags$li("Zeng (1993) PNAS 90:10972; (1994) Genetics 136:1457 — CIM"), tags$li("Tibshirani (1996) JRSS-B 58:267 — LASSO"), tags$li("Zou & Hastie (2005) JRSS-B 67:301 — Elastic Net"), - tags$li("Breiman (2001) Machine Learning 45:5 — Random Forest"), - tags$li("Wright (2016) Heredity 117:403 — RF in plant breeding") + tags$li("Breiman (2001) Machine Learning 45:5 — Random Forest") ), - tags$hr(), - tags$p(style="text-align:center;color:#8B7A5A;font-size:12px;", + tags$hr(style = "border-color:#2d2d44;"), + tags$p(style = "text-align:center;color:#aaaaaa;font-size:12px;", "📧 Contact: ashmithamganesan@gmail.com | P.sinha@cgiar.org", tags$br(), - "© 2024 QTL-Mapper v6 — All Rights Reserved" + "© 2024 QTL-Mapper v7 — All Rights Reserved" ) ) ) @@ -1186,7 +1708,7 @@ ui <- fluidPage( ) # ============================================================ -# SERVER +# SERVER (Same as before with updated function calls) # ============================================================ server <- function(input, output, session) { @@ -1203,28 +1725,32 @@ server <- function(input, output, session) { ) lod_thr <- reactive({ input$lod_threshold }) + + cn <- function(x) trimws(gsub('[\r\n\"]', '', as.character(x))) # ── 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", tags$i(class="fas fa-flask",style="margin-right:6px;"), MAPPING_MODELS[[m]]$desc) + if (is.null(m) || !m %in% names(MAPPING_MODELS)) return(NULL) + div(class = "info-box", + tags$i(class = "fas fa-flask", style = "margin-right:6px;"), + MAPPING_MODELS[[m]]$desc) }) # ── Dataset info ────────────────────────────────────────── output$dataset_info_ui <- renderUI({ if (is.null(rv$geno)) - return(tags$div(class="warn-box","📂 No data loaded. Please upload genotype and phenotype files.")) + return(tags$div(class = "warn-box", "📂 No data loaded. Please upload genotype and phenotype files.")) tagList( - div(style="display:flex;justify-content:space-between;margin-bottom:8px;", - tags$span(class="stat-value",nrow(rv$geno)), tags$span(class="stat-label","Samples")), - div(style="display:flex;justify-content:space-between;margin-bottom:8px;", - tags$span(class="stat-value",ncol(rv$geno)), tags$span(class="stat-label","Markers")), - div(style="display:flex;justify-content:space-between;margin-bottom:8px;", - tags$span(class="stat-value",length(unique(rv$marker_info$Chromosome))), - tags$span(class="stat-label","Chromosomes")), - if(!is.null(rv$pheno)) div(style="display:flex;justify-content:space-between;", - tags$span(class="stat-value",ncol(rv$pheno)), tags$span(class="stat-label","Traits")) + div(style = "display:flex;justify-content:space-between;margin-bottom:8px;", + tags$span(class = "stat-value", nrow(rv$geno)), tags$span(class = "stat-label", "Samples")), + div(style = "display:flex;justify-content:space-between;margin-bottom:8px;", + tags$span(class = "stat-value", ncol(rv$geno)), tags$span(class = "stat-label", "Markers")), + div(style = "display:flex;justify-content:space-between;margin-bottom:8px;", + tags$span(class = "stat-value", length(unique(rv$marker_info$Chromosome))), + tags$span(class = "stat-label", "Chromosomes")), + if(!is.null(rv$pheno)) div(style = "display:flex;justify-content:space-between;", + tags$span(class = "stat-value", ncol(rv$pheno)), tags$span(class = "stat-label", "Traits")) ) }) @@ -1236,29 +1762,30 @@ server <- function(input, output, session) { rv$geno <- res$geno rv$marker_info <- res$marker_info rv$all_markers <- res$marker_info - showNotification(paste("✅ Loaded",res$n_markers,"markers,",res$n_samples,"samples"), - type="message",duration=3) - }, error=function(e) showNotification(paste("❌ Geno error:",e$message),type="error")) + showNotification(paste("✅ Loaded", res$n_markers, "markers,", res$n_samples, "samples"), + type = "message", duration = 3) + }, error = function(e) showNotification(paste("❌ Geno 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("❌ Pheno error:",e$message),type="error")) + 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("❌ Pheno error:", e$message), type = "error")) }) observeEvent(input$pop_file, { req(input$pop_file) tryCatch({ rv$pop_data <- read.csv(input$pop_file$datapath) - showNotification(paste("✅ Loaded",nrow(rv$pop_data),"samples"),type="message") - }, error=function(e) showNotification(paste("❌ Pop error:",e$message),type="error")) + showNotification(paste("✅ Loaded", nrow(rv$pop_data), "samples"), type = "message") + }, error = function(e) showNotification(paste("❌ Pop error:", e$message), type = "error")) }) observeEvent(input$test_geno_file, { @@ -1266,557 +1793,575 @@ server <- function(input, output, session) { tryCatch({ res <- load_genotype_file(input$test_geno_file$datapath) rv$test_geno <- res$geno - showNotification(paste("✅ Test geno:",nrow(res$geno),"samples"),type="message") - }, error=function(e) showNotification(paste("❌ Test geno error:",e$message),type="error")) + showNotification(paste("✅ Test geno:", nrow(res$geno), "samples"), type = "message") + }, error = function(e) showNotification(paste("❌ Test geno error:", e$message), type = "error")) }) # ── Previews ────────────────────────────────────────────── - output$prev_geno <- renderDT({ req(input$geno_file); datatable(head(read.csv(input$geno_file$datapath),10), options=list(scrollX=TRUE,pageLength=5,dom='t')) }) - output$prev_pheno <- renderDT({ req(input$pheno_file); datatable(head(read.csv(input$pheno_file$datapath),10),options=list(scrollX=TRUE,pageLength=5,dom='t')) }) - 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=8,dom='t')) }) - output$prev_pop <- renderDT({ req(rv$pop_data); datatable(head(rv$pop_data,10),options=list(scrollX=TRUE,pageLength=5,dom='t')) }) + output$prev_geno <- renderDT({ req(input$geno_file); datatable(head(read.csv(input$geno_file$datapath), 10), options = list(scrollX = TRUE, pageLength = 5, dom = 't')) }) + output$prev_pheno <- renderDT({ req(input$pheno_file); datatable(head(read.csv(input$pheno_file$datapath), 10), options = list(scrollX = TRUE, pageLength = 5, dom = 't')) }) + 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 = 8, dom = 't')) }) + output$prev_pop <- renderDT({ req(rv$pop_data); datatable(head(rv$pop_data, 10), options = list(scrollX = TRUE, pageLength = 5, dom = 't')) }) # ── MAIN ANALYSIS ───────────────────────────────────────── observeEvent(input$run_btn, { req(rv$geno, rv$pheno, input$pheno_col) - showNotification(paste("🚀 Starting",input$mapping_method,"scan..."),type="message") + showNotification(paste("🚀 Starting", input$mapping_method, "scan (QTL Cartographer compatible)..."), type = "message") tryCatch({ cs <- intersect(rownames(rv$geno), rownames(rv$pheno)) - 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]) + 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]; X_v <- X[-tr_idx,,drop=FALSE] - y_tr <- y[tr_idx]; y_v <- y[-tr_idx] + tr_idx <- caret::createDataPartition(y, p = 1 - input$val_prop, list = FALSE) + X_tr <- X[tr_idx,, drop = FALSE] + X_v <- X[-tr_idx,, drop = FALSE] + y_tr <- y[tr_idx] + y_v <- y[-tr_idx] - withProgress(message=paste("Running",input$mapping_method,"scan..."),value=0.1,{ + withProgress(message = paste("Running", input$mapping_method, "scan..."), value = 0.1, { rv$scan_all <- qtl_scan(X_tr, y_tr, rv$marker_info, - method=input$mapping_method, - n_cofactors=input$n_cofactors, - window_size=input$window_size) + method = input$mapping_method, + n_cofactors = input$n_cofactors, + window_size = input$window_size) incProgress(0.5) # RF prediction model nzv_idx <- caret::nearZeroVar(X_tr) - X_tr_rf <- if(length(nzv_idx)>0) X_tr[,-nzv_idx,drop=FALSE] else X_tr - X_v_rf <- X_v[,colnames(X_tr_rf),drop=FALSE] + X_tr_rf <- if(length(nzv_idx) > 0) X_tr[, -nzv_idx, drop = FALSE] else X_tr + X_v_rf <- X_v[, colnames(X_tr_rf), drop = FALSE] rv$model_cols <- colnames(X_tr_rf) fit <- tryCatch( - caret::train(x=X_tr_rf,y=y_tr,method="rf", - trControl=caret::trainControl(method="cv",number=5),tuneLength=3), - error=function(e) - caret::train(x=X_tr_rf,y=y_tr,method="lm", - trControl=caret::trainControl(method="cv",number=5))) + caret::train(x = X_tr_rf, y = y_tr, method = "rf", + trControl = caret::trainControl(method = "cv", number = 5), tuneLength = 3), + error = function(e) + caret::train(x = X_tr_rf, y = y_tr, method = "lm", + trControl = caret::trainControl(method = "cv", number = 5))) rv$model_fit <- fit - ytr_p <- predict(fit,X_tr_rf); yv_p <- predict(fit,X_v_rf) - tr_r2 <- 1-sum((y_tr-ytr_p)^2)/sum((y_tr-mean(y_tr))^2) - v_r2 <- 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) + ytr_p <- predict(fit, X_tr_rf) + yv_p <- predict(fit, X_v_rf) + tr_r2 <- 1 - sum((y_tr - ytr_p)^2) / sum((y_tr - mean(y_tr))^2) + v_r2 <- 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) incProgress(0.4) }) - 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,"QTLs detected"),type="message") - updateTabsetPanel(session,"nav",selected="📊 Results") - }, error=function(e) { - showNotification(paste("❌ Analysis error:",e$message),type="error") - cat("ANALYSIS ERROR:",e$message,"\n") + 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, "QTLs detected"), type = "message") + updateTabsetPanel(session, "nav", selected = "📊 Results") + }, error = function(e) { + showNotification(paste("❌ Analysis error:", e$message), type = "error") + cat("ANALYSIS ERROR:", e$message, "\n") }) }) # ── COMPARE MODELS ──────────────────────────────────────── output$compare_status_ui <- renderUI({ - if (length(rv$compare_res)==0) return(NULL) - tags$div(class="info-box", - tags$b("✅ Completed: "), paste(names(rv$compare_res),collapse=", "), + if (length(rv$compare_res) == 0) return(NULL) + tags$div(class = "info-box", + tags$b("✅ Completed: "), paste(names(rv$compare_res), collapse = ", "), tags$br(), lapply(names(rv$compare_res), function(m) { r <- rv$compare_res[[m]] - if(is.null(r)||"Message"%in%colnames(r)) return(tags$span(class="model-badge",paste0(m,": 0 QTLs"))) - n <- sum(r$LOD>=lod_thr(),na.rm=TRUE) - tags$span(class="model-badge",paste0(m,": ",n," QTLs")) + if(is.null(r) || "Message" %in% colnames(r)) return(tags$span(class = "model-badge", paste0(m, ": 0 QTLs"))) + n <- sum(r$LOD >= lod_thr(), na.rm = TRUE) + 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]) + 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]) 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] + tr_idx <- caret::createDataPartition(y, p = 1 - input$val_prop, list = FALSE) + X_tr <- X[tr_idx,, drop = FALSE] + y_tr <- y[tr_idx] compare_list <- list() - withProgress(message="🔄 Comparing models...",value=0,{ + withProgress(message = "🔄 Comparing models...", value = 0, { for (i in seq_along(input$compare_methods)) { mth <- input$compare_methods[i] - incProgress(1/length(input$compare_methods),detail=paste("Running",mth)) + incProgress(1 / length(input$compare_methods), detail = paste("Running", mth)) res <- tryCatch( - qtl_scan(X_tr,y_tr,rv$marker_info,method=mth, - n_cofactors=input$n_cofactors,window_size=input$window_size), - error=function(e) { cat("Compare error",mth,":",e$message,"\n"); NULL }) + 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 }) if (!is.null(res)) compare_list[[mth]] <- res } }) rv$compare_res <- compare_list - showNotification(paste("✅ Compared",length(compare_list),"models"),type="message") + showNotification(paste("✅ Compared", length(compare_list), "models"), type = "message") }) output$compare_idiogram <- renderPlot({ - req(length(rv$compare_res)>0, rv$all_markers) - par(bg="#FDFBF7") + req(length(rv$compare_res) > 0, rv$all_markers) + par(bg = "#1a1a2e") make_chromosome_idiogram(rv$compare_res, rv$all_markers, lod_thr()) - }, bg="#FDFBF7") + }, bg = "#1a1a2e") output$compare_bar <- renderPlotly({ - req(length(rv$compare_res)>0) + req(length(rv$compare_res) > 0) rows <- list() for (mth in names(rv$compare_res)) { r <- rv$compare_res[[mth]] - if(is.null(r)||"Message"%in%colnames(r)) next - sig <- r[r$LOD>=lod_thr()&!is.na(r$LOD),] - if(nrow(sig)==0) next + if(is.null(r) || "Message" %in% colnames(r)) next + sig <- r[r$LOD >= lod_thr() & !is.na(r$LOD), ] + if(nrow(sig) == 0) next for (ch in unique(sig$Chromosome)) - rows <- c(rows,list(data.frame(Method=mth,Chromosome=as.character(ch), - Count=sum(sig$Chromosome==ch),stringsAsFactors=FALSE))) + rows <- c(rows, list(data.frame(Method = mth, Chromosome = as.character(ch), + Count = sum(sig$Chromosome == ch), stringsAsFactors = FALSE))) } - if(length(rows)==0) return(plot_ly()%>%layout(title="No significant QTLs found")) - df <- do.call(rbind,rows) - df$Chromosome <- factor(df$Chromosome,levels=sort(unique(df$Chromosome))) - plot_ly(df,x=~Chromosome,y=~Count,color=~Method,type="bar", - colors=PASTEL_COLORS[1:length(unique(df$Method))])%>% - layout(barmode="group", - title=list(text="📊 QTL Count by Method & Chromosome",font=list(size=14)), - xaxis=list(title="Chromosome",tickangle=45), - yaxis=list(title="# Significant QTLs"), - plot_bgcolor="#FDFBF7",paper_bgcolor="#FDFBF7", - legend=list(title=list(text="Method"))) + if(length(rows) == 0) return(plot_ly() %>% layout(title = "No significant QTLs found")) + df <- do.call(rbind, rows) + df$Chromosome <- factor(df$Chromosome, levels = sort(unique(df$Chromosome))) + plot_ly(df, x = ~Chromosome, y = ~Count, color = ~Method, type = "bar", + colors = VIBRANT_COLORS[1:length(unique(df$Method))]) %>% + layout(barmode = "group", + title = list(text = "📊 QTL Count by Method & Chromosome", font = list(size = 14, color = "#ffaa66")), + xaxis = list(title = "Chromosome", tickangle = 45, gridcolor = "#333344", color = "#cccccc"), + yaxis = list(title = "# Significant QTLs", gridcolor = "#333344", color = "#cccccc"), + plot_bgcolor = "#1a1a2e", paper_bgcolor = "#1a1a2e", + legend = list(title = list(text = "Method"), font = list(color = "#cccccc"))) }) output$compare_table <- renderDT({ - req(length(rv$compare_res)>0) + req(length(rv$compare_res) > 0) rows <- list() for (mth in names(rv$compare_res)) { r <- rv$compare_res[[mth]] - if(is.null(r)||"Message"%in%colnames(r)) next - sig <- r[r$LOD>=lod_thr()&!is.na(r$LOD),] - if(nrow(sig)==0) next + if(is.null(r) || "Message" %in% colnames(r)) next + sig <- r[r$LOD >= lod_thr() & !is.na(r$LOD), ] + if(nrow(sig) == 0) next sig$Method2 <- mth - rows <- c(rows,list(sig[,c("Marker","Chromosome","Position","LOD","PVE_Marker_Percent","Method2")])) + rows <- c(rows, list(sig[, c("Marker", "Chromosome", "Position", "LOD", "PVE_Marker_Percent", "Method2")])) } - if(length(rows)==0) return(datatable(data.frame(Status="No QTLs"))) - df <- do.call(rbind,rows) + if(length(rows) == 0) return(datatable(data.frame(Status = "No QTLs"))) + 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"),3) + 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"), 3) }) # ── COMMON QTL TAB ──────────────────────────────────────── common_qtl_data <- reactive({ - req(length(rv$compare_res)>0) - find_common_qtl(rv$compare_res, lod_thr(), min_models=input$min_models) + req(length(rv$compare_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) - return(div(class="warn-box","⚠️ No common QTLs found. Run Compare Models first.")) + if (is.null(cq) || nrow(cq) == 0) + return(div(class = "warn-box", "⚠️ No common QTLs found. Run Compare Models first.")) n_all <- nrow(cq) - n_max <- sum(cq$N_Models_Detected==length(rv$compare_res), na.rm=TRUE) + n_max <- sum(cq$N_Models_Detected == length(rv$compare_res), na.rm = TRUE) tagList( - div(class="good-box", - tags$span(style="font-size:28px;font-weight:700;color:#6B9E6B;",n_all), - tags$span(" common QTLs detected", style="font-weight:500;"), + div(class = "good-box", + tags$span(style = "font-size:28px;font-weight:700;color:#4ecdc4;", n_all), + tags$span(" common QTLs detected", style = "font-weight:500;"), tags$br(), - tags$span(style="font-size:20px;font-weight:600;color:#7BA07A;",n_max), - tags$span(" detected in ALL models", style="font-weight:500;"), + tags$span(style = "font-size:20px;font-weight:600;color:#ff6b6b;", n_max), + tags$span(" detected in ALL models", style = "font-weight:500;"), tags$br(), - tags$small("📊 Chromosomes: ", paste(sort(unique(cq$Chromosome)),collapse=", ")) + 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, then return here."), - options=list(dom="t"))) - num_cols <- intersect(c("Position","Mean_LOD","Max_LOD","Mean_PVE","Mean_Add_Eff", - paste0("LOD_",names(rv$compare_res))), colnames(cq)) - datatable(cq, options=list(scrollX=TRUE,pageLength=15,dom='Blfrtip'), - rownames=FALSE,class='cell-border stripe hover') %>% + if (is.null(cq) || nrow(cq) == 0) + return(datatable(data.frame(Status = "Run Compare Models tab first, then return here."), + options = list(dom = "t"))) + num_cols <- intersect(c("Position", "Mean_LOD", "Max_LOD", "Mean_PVE", "Mean_Add_Eff", + paste0("LOD_", names(rv$compare_res))), colnames(cq)) + datatable(cq, options = list(scrollX = TRUE, pageLength = 15, dom = 'Blfrtip'), + 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),"#C8E6C8"), - backgroundSize="100% 80%", backgroundRepeat="no-repeat", - backgroundPosition="center") %>% + background = styleColorBar(range(cq$N_Models_Detected, na.rm = TRUE), "#4ecdc4"), + backgroundSize = "100% 80%", backgroundRepeat = "no-repeat", + backgroundPosition = "center") %>% formatStyle("Max_LOD", - background=styleColorBar(range(cq$Max_LOD,na.rm=TRUE),"#D4E2D0"), - backgroundSize="100% 80%", backgroundRepeat="no-repeat", - backgroundPosition="center") + background = styleColorBar(range(cq$Max_LOD, na.rm = TRUE), "#ff6b6b"), + backgroundSize = "100% 80%", backgroundRepeat = "no-repeat", + backgroundPosition = "center") }) output$common_idiogram <- renderPlot({ cq <- common_qtl_data() - req(!is.null(cq), nrow(cq)>0, rv$all_markers) - n_levels <- sort(unique(cq$N_Models_Detected), decreasing=TRUE) - cols <- c("#6B9E6B","#8B9E6B","#AB9E6B","#CB9E6B","#EB9E6B") + req(!is.null(cq), nrow(cq) > 0, rv$all_markers) + n_levels <- sort(unique(cq$N_Models_Detected), decreasing = TRUE) + cols <- c("#ff6b6b", "#ffb347", "#ffd700", "#4ecdc4", "#45b7d1") pal <- setNames(cols[seq_along(n_levels)], as.character(n_levels)) - qtl_list_cq <- lapply(setNames(n_levels, paste0(n_levels," model(s)")), 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)=="Mean_Add_Eff"] <- "Additive_Effect" - sub$Method <- paste0(nl," models") + qtl_list_cq <- lapply(setNames(n_levels, paste0(n_levels, " model(s)")), 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) == "Mean_Add_Eff"] <- "Additive_Effect" + sub$Method <- paste0(nl, " models") sub }) - par(bg="#FDFBF7") + par(bg = "#1a1a2e") make_chromosome_idiogram(qtl_list_cq, rv$all_markers, lod_thr(), - trait_colors=setNames(cols[seq_along(n_levels)], - paste0(n_levels," model(s)"))) - }, bg="#FDFBF7") + trait_colors = setNames(cols[seq_along(n_levels)], + paste0(n_levels, " model(s)"))) + }, bg = "#1a1a2e") output$common_bar <- renderPlotly({ cq <- common_qtl_data() - if (is.null(cq)||nrow(cq)==0) - return(plot_ly()%>%layout(title="No common QTLs",plot_bgcolor="#FDFBF7",paper_bgcolor="#FDFBF7")) + if (is.null(cq) || nrow(cq) == 0) + return(plot_ly() %>% layout(title = "No common QTLs", plot_bgcolor = "#1a1a2e", paper_bgcolor = "#1a1a2e")) 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$Chromosome <- factor(df$Chromosome, levels=sort(unique(as.character(df$Chromosome)))) - - plot_ly(df,x=~Chromosome,y=~Count,color=~Label,type="bar", - colors=c("#6B9E6B","#8B9E6B","#AB9E6B","#CB9E6B","#EB9E6B"))%>% - layout(barmode="stack", - title=list(text="🎯 Common QTL Count by Chromosome",font=list(size=14)), - xaxis=list(title="Chromosome",tickangle=45), - yaxis=list(title="# Common QTLs"), - plot_bgcolor="#FDFBF7",paper_bgcolor="#FDFBF7", - legend=list(title=list(text="Detected by"),orientation="h",y=-0.15)) + dplyr::summarise(Count = dplyr::n(), .groups = "drop") + 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("#ff6b6b", "#ffb347", "#ffd700", "#4ecdc4", "#45b7d1")) %>% + layout(barmode = "stack", + title = list(text = "🎯 Common QTL Count by Chromosome", font = list(size = 14, color = "#ffaa66")), + xaxis = list(title = "Chromosome", tickangle = 45, gridcolor = "#333344", color = "#cccccc"), + yaxis = list(title = "# Common QTLs", gridcolor = "#333344", color = "#cccccc"), + plot_bgcolor = "#1a1a2e", paper_bgcolor = "#1a1a2e", + legend = list(title = list(text = "Detected by"), orientation = "h", y = -0.15, font = list(color = "#cccccc"))) }) # ── MAIN PLOTS ──────────────────────────────────────────── output$manhattan_plot <- renderPlotly({ req(rv$scan_all) - make_plotly_manhattan(rv$scan_all, lod_thr(), paste(input$mapping_method,"Manhattan Plot")) + make_plotly_manhattan(rv$scan_all, lod_thr(), paste(input$mapping_method, "Manhattan Plot")) }) output$idiogram_plot <- renderPlot({ req(rv$scan_all, rv$all_markers) res_list <- list() - if(!is.null(rv$scan_all)&&!"Message"%in%colnames(rv$scan_all)) + if(!is.null(rv$scan_all) && !"Message" %in% colnames(rv$scan_all)) res_list[[input$mapping_method]] <- rv$scan_all - if(length(res_list)==0){ plot(0,0,type="n",axes=FALSE,xlab="",ylab=""); text(0,0,"Run analysis first",cex=1.2); return() } - par(bg="#FDFBF7") + if(length(res_list) == 0){ plot(0,0,type="n",axes=FALSE,xlab="",ylab=""); text(0,0,"Run analysis first",cex=1.2, col="#ffffff"); return() } + par(bg = "#1a1a2e") make_chromosome_idiogram(res_list, rv$all_markers, lod_thr()) - }, bg="#FDFBF7") + }, bg = "#1a1a2e") output$perf_plot <- renderPlotly({ req(rv$perf) - plot_ly(rv$perf,x=~Metric,y=~Value,type="bar", - marker=list(color=c("#7BA07A","#9BB89A","#5A8A5A","#7BA07A")), - text=~round(Value,3),textposition="outside",textfont=list(size=10))%>% - layout(title=list(text="📊 Model Performance",font=list(size=14)), - yaxis=list(range=c(0,1.15),title="Value",gridcolor="#F0EBE0"), - xaxis=list(title="",tickangle=15), - plot_bgcolor="#FDFBF7",paper_bgcolor="#FDFBF7") + plot_ly(rv$perf, x = ~Metric, y = ~Value, type = "bar", + marker = list(color = c("#ff6b6b", "#4ecdc4", "#ff6b6b", "#4ecdc4")), + text = ~round(Value, 3), textposition = "outside", textfont = list(size = 10, color = "#ffffff")) %>% + layout(title = list(text = "📊 Model Performance", font = list(size = 14, color = "#ffaa66")), + yaxis = list(range = c(0, 1.15), title = "Value", gridcolor = "#333344", color = "#cccccc"), + xaxis = list(title = "", tickangle = 15, color = "#cccccc"), + plot_bgcolor = "#1a1a2e", paper_bgcolor = "#1a1a2e") }) output$reg_train <- renderPlotly({ req(rv$tr_pred) - plot_ly(rv$tr_pred,x=~Observed,y=~Predicted,type="scatter",mode="markers", - marker=list(size=8,color="#7BA07A",opacity=.7,line=list(width=0.5,color="#FFFFFF")))%>% - add_trace(x=range(rv$tr_pred$Observed),y=range(rv$tr_pred$Observed), - type="scatter",mode="lines",line=list(color="#D98A7A",dash="dash",width=1.5),showlegend=FALSE)%>% - layout(title=list(text="🎯 Training Set",font=list(size=14)), - xaxis=list(title="Observed",gridcolor="#F0EBE0"), - yaxis=list(title="Predicted",gridcolor="#F0EBE0"), - plot_bgcolor="#FDFBF7",paper_bgcolor="#FDFBF7") + plot_ly(rv$tr_pred, x = ~Observed, y = ~Predicted, type = "scatter", mode = "markers", + marker = list(size = 8, color = "#ff6b6b", opacity = 0.7, line = list(width = 0.5, color = "#ffffff"))) %>% + add_trace(x = range(rv$tr_pred$Observed), y = range(rv$tr_pred$Observed), + type = "scatter", mode = "lines", line = list(color = "#4ecdc4", dash = "dash", width = 2), showlegend = FALSE) %>% + layout(title = list(text = "🎯 Training Set", font = list(size = 14, color = "#ffaa66")), + xaxis = list(title = "Observed", gridcolor = "#333344", color = "#cccccc"), + yaxis = list(title = "Predicted", gridcolor = "#333344", color = "#cccccc"), + plot_bgcolor = "#1a1a2e", paper_bgcolor = "#1a1a2e") }) output$reg_val <- renderPlotly({ req(rv$val_pred) - plot_ly(rv$val_pred,x=~Observed,y=~Predicted,type="scatter",mode="markers", - marker=list(size=8,color="#5A8A5A",opacity=.7,line=list(width=0.5,color="#FFFFFF")))%>% - add_trace(x=range(rv$val_pred$Observed),y=range(rv$val_pred$Observed), - type="scatter",mode="lines",line=list(color="#D98A7A",dash="dash",width=1.5),showlegend=FALSE)%>% - layout(title=list(text="✅ Validation Set",font=list(size=14)), - xaxis=list(title="Observed",gridcolor="#F0EBE0"), - yaxis=list(title="Predicted",gridcolor="#F0EBE0"), - plot_bgcolor="#FDFBF7",paper_bgcolor="#FDFBF7") + plot_ly(rv$val_pred, x = ~Observed, y = ~Predicted, type = "scatter", mode = "markers", + marker = list(size = 8, color = "#4ecdc4", opacity = 0.7, line = list(width = 0.5, color = "#ffffff"))) %>% + add_trace(x = range(rv$val_pred$Observed), y = range(rv$val_pred$Observed), + type = "scatter", mode = "lines", line = list(color = "#ff6b6b", dash = "dash", width = 2), showlegend = FALSE) %>% + layout(title = list(text = "✅ Validation Set", font = list(size = 14, color = "#ffaa66")), + xaxis = list(title = "Observed", gridcolor = "#333344", color = "#cccccc"), + yaxis = list(title = "Predicted", gridcolor = "#333344", color = "#cccccc"), + plot_bgcolor = "#1a1a2e", paper_bgcolor = "#1a1a2e") }) # ── TABLES ──────────────────────────────────────────────── output$qtl_table <- renderDT({ req(rv$scan_all) - if("Message"%in%colnames(rv$scan_all)) - return(datatable(data.frame(Status=rv$scan_all$Message[1]),options=list(dom="t"))) - sig <- rv$scan_all[!is.na(rv$scan_all$LOD)&rv$scan_all$LOD>=lod_thr(),,drop=FALSE] - if(nrow(sig)==0) - return(datatable(data.frame(Status=paste("No QTLs above LOD",lod_thr())),options=list(dom="t"))) + if("Message" %in% colnames(rv$scan_all)) + return(datatable(data.frame(Status = rv$scan_all$Message[1]), options = list(dom = "t"))) + sig <- rv$scan_all[!is.na(rv$scan_all$LOD) & rv$scan_all$LOD >= lod_thr(), , drop = FALSE] + if(nrow(sig) == 0) + return(datatable(data.frame(Status = paste("No QTLs above LOD", lod_thr())), options = list(dom = "t"))) sig <- add_lod_support_interval(sig, rv$scan_all, input$lod_drop) - sig <- sig[order(-sig$LOD),] - disp <- intersect(c("Marker","Chromosome","Position","LOD","P_Value", - "PVE_Marker_Percent","PVE_CIM_Percent","Additive_Effect","SE_Additive", - "CI_Lower","CI_Upper","Dominance_Effect","Dominance_Ratio","Dominance_Class", - "N_Cofactors","N_Samples","Method","Interval_Start","Interval_End", - "Interval_Size_cM","Low_Flank","High_Flank"), colnames(sig)) - datatable(sig[,disp],options=list(scrollX=TRUE,pageLength=10,dom='Blfrtip'), - rownames=FALSE,class='cell-border stripe hover')%>% - formatRound(intersect(c("LOD","PVE_Marker_Percent","PVE_CIM_Percent","Additive_Effect", - "SE_Additive","CI_Lower","CI_Upper","Dominance_Ratio","Interval_Size_cM"),disp),3)%>% - formatSignif(intersect("P_Value",disp),digits=3) + sig <- sig[order(-sig$LOD), ] + disp <- intersect(c("Marker", "Chromosome", "Position", "LOD", "P_Value", + "PVE_Marker_Percent", "PVE_CIM_Percent", "Additive_Effect", "SE_Additive", + "CI_Lower", "CI_Upper", "Dominance_Effect", "SE_Dominance", "Dominance_Ratio", "Dominance_Class", + "N_Cofactors", "N_Samples", "Method", "Interval_Start", "Interval_End", + "Interval_Size_cM", "Low_Flank", "High_Flank"), colnames(sig)) + datatable(sig[, disp], options = list(scrollX = TRUE, pageLength = 10, dom = 'Blfrtip'), + rownames = FALSE, class = 'cell-border stripe hover') %>% + formatRound(intersect(c("LOD", "PVE_Marker_Percent", "PVE_CIM_Percent", "Additive_Effect", + "SE_Additive", "CI_Lower", "CI_Upper", "Dominance_Ratio", "Interval_Size_cM"), disp), 3) %>% + formatSignif(intersect("P_Value", disp), 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"))) - datatable(rv$scan_all,options=list(scrollX=TRUE,pageLength=15,order=list(list(4,"desc")),dom='Blfrtip'), - rownames=FALSE,class='cell-border stripe hover')%>% - formatRound(c("LOD","PVE_Marker_Percent","Additive_Effect"),3)%>% - formatSignif("P_Value",digits=3) + if("Message" %in% colnames(rv$scan_all)) + return(datatable(data.frame(Status = rv$scan_all$Message[1]), options = list(dom = "t"))) + datatable(rv$scan_all, options = list(scrollX = TRUE, pageLength = 15, order = list(list(4, "desc")), dom = 'Blfrtip'), + rownames = FALSE, class = 'cell-border stripe hover') %>% + formatRound(c("LOD", "PVE_Marker_Percent", "Additive_Effect"), 3) %>% + formatSignif("P_Value", digits = 3) }) # ── 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() } - withProgress(message="🔮 Predicting...",value=0.2,{ - train_cols <- rv$model_cols; test_raw <- rv$test_geno + 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...", value = 0.2, { + train_cols <- rv$model_cols + test_raw <- rv$test_geno common_m <- intersect(train_cols, colnames(test_raw)) - X_pred <- as.data.frame(matrix(0,nrow=nrow(test_raw),ncol=length(train_cols), - dimnames=list(rownames(test_raw),train_cols))) + X_pred <- as.data.frame(matrix(0, nrow = nrow(test_raw), ncol = length(train_cols), + dimnames = list(rownames(test_raw), train_cols))) for (col in common_m) { - v <- suppressWarnings(as.numeric(as.character(test_raw[[col]]))); v[is.na(v)]<-0 + v <- suppressWarnings(as.numeric(as.character(test_raw[[col]]))) + v[is.na(v)] <- 0 X_pred[[col]] <- v } incProgress(0.5) - preds <- tryCatch(as.numeric(predict(rv$model_fit,newdata=X_pred)), - error=function(e) as.numeric(predict(rv$model_fit$finalModel,newdata=X_pred))) - rv$pred_test <- data.frame(Sample_ID=rownames(test_raw),Predicted_Phenotype=round(preds,4)) + preds <- tryCatch(as.numeric(predict(rv$model_fit, newdata = X_pred)), + error = function(e) as.numeric(predict(rv$model_fit$finalModel, newdata = X_pred))) + rv$pred_test <- data.frame(Sample_ID = rownames(test_raw), Predicted_Phenotype = round(preds, 4)) incProgress(0.3) }) - showNotification(paste("✅ Predicted",nrow(rv$pred_test),"test samples"),type="message") + showNotification(paste("✅ Predicted", nrow(rv$pred_test), "test samples"), type = "message") }) # ── DOMESTICATION ───────────────────────────────────────── calc_sel <- function(gmat, pop, minfo) { out <- list() for (m in colnames(gmat)) { - g <- gmat[,m]; p <- pop$population[match(rownames(gmat),pop$id)] - vi <- !is.na(g)&!is.na(p); gv <- g[vi]; pv <- p[vi] - if(length(unique(pv))<2) next - 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; 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) - tdd <- tryCatch((pid-1/length(gd))/sqrt(var(gd)/length(gd)),error=function(e)NA) - mi <- minfo[minfo$Marker==m,] - out[[m]] <- data.frame(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) + g <- gmat[, m] + p <- pop$population[match(rownames(gmat), pop$id)] + vi <- !is.na(g) & !is.na(p) + gv <- g[vi] + pv <- p[vi] + if(length(unique(pv)) < 2) next + 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 + 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) + tdd <- tryCatch((pid - 1/length(gd)) / sqrt(var(gd)/length(gd)), error = function(e) NA) + mi <- minfo[minfo$Marker == m, ] + out[[m]] <- data.frame(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) } - if(length(out)==0) return(NULL) - do.call(rbind,out) + if(length(out) == 0) return(NULL) + do.call(rbind, out) } 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,] - sel <- calc_sel(X,ps,rv$marker_info) - if(is.null(sel)){ showNotification("❌ No selection metrics computed",type="error"); return() } - sel$Significant <- sel$Fst>input$fst_thr|sel$Tajima_D_Dom input$fst_thr | sel$Tajima_D_Dom < input$tajima_thr rv$sel_metrics <- sel - showNotification(paste("✅ Found",sum(sel$Significant,na.rm=TRUE),"selection signatures"),type="message") - }, error=function(e) showNotification(paste("❌ Dom error:",e$message),type="error")) + showNotification(paste("✅ Found", sum(sel$Significant, na.rm = TRUE), "selection signatures"), type = "message") + }, error = function(e) showNotification(paste("❌ Dom error:", e$message), type = "error")) }) - create_man_plotly <- function(data, y_col, title, threshold, y_label=y_col) { - blank <- plot_ly()%>%layout(title=title,plot_bgcolor="#FDFBF7",paper_bgcolor="#FDFBF7") - if(is.null(data)||nrow(data)==0||"Message"%in%colnames(data)) return(blank) - pd <- data[!is.na(data[[y_col]])&!is.na(data$Chromosome),] - if(nrow(pd)==0) return(blank) + create_man_plotly <- function(data, y_col, title, threshold, y_label = y_col) { + blank <- plot_ly() %>% layout(title = title, plot_bgcolor = "#1a1a2e", paper_bgcolor = "#1a1a2e") + if(is.null(data) || nrow(data) == 0 || "Message" %in% colnames(data)) 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") - offsets <- numeric(length(chroms)); names(offsets) <- chroms + chroms <- sort(unique(pd$Chromosome), method = "radix") + offsets <- numeric(length(chroms)) + names(offsets) <- 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; next } + offsets[chroms[i]] <- offsets[chroms[i-1]] + max(pd$Position[pd$Chromosome == chroms[i-1]], na.rm = TRUE) * 1.05 } - pd$cum_pos <- pd$Position+offsets[pd$Chromosome] - chr_mids <- tapply(pd$cum_pos,pd$Chromosome,median,na.rm=TRUE) - pal <- rep(c("#A8E6CF","#DCEDC1","#FFD3B6","#FFAAA5"),ceiling(length(chroms)/4))[seq_along(chroms)] + pd$cum_pos <- pd$Position + offsets[pd$Chromosome] + chr_mids <- tapply(pd$cum_pos, pd$Chromosome, median, na.rm = TRUE) + pal <- rep(c("#ff6b6b", "#4ecdc4", "#45b7d1", "#ffb347"), ceiling(length(chroms) / 4))[seq_along(chroms)] names(pal) <- chroms p <- plot_ly() for (ch in chroms) - p <- p%>%add_trace(data=pd[pd$Chromosome==ch,],x=~cum_pos, - y=as.formula(paste0("~",y_col)),type="scatter",mode="markers", - name=paste("Chr",ch),marker=list(size=6,color=pal[ch],opacity=.7,line=list(width=0.5,color="#FFFFFF")), - showlegend=FALSE, - text=~paste0("",Marker,"
📍 Chr: ",Chromosome,"
📏 Pos: ",round(Position,1), - "
📊 ",y_label,": ",round(get(y_col),4)), - hoverinfo="text") + p <- p %>% add_trace(data = pd[pd$Chromosome == ch, ], x = ~cum_pos, + y = as.formula(paste0("~", y_col)), type = "scatter", mode = "markers", + name = paste("Chr", ch), marker = list(size = 6, color = pal[ch], opacity = 0.7, line = list(width = 0.5, color = "#ffffff")), + showlegend = FALSE, + text = ~paste0("", Marker, "
📍 Chr: ", Chromosome, "
📏 Pos: ", round(Position, 1), + "
📊 ", y_label, ": ", round(get(y_col), 4)), + hoverinfo = "text") if(!is.null(threshold)) - p <- p%>%add_segments(x=min(pd$cum_pos,na.rm=TRUE),xend=max(pd$cum_pos,na.rm=TRUE), - y=threshold,yend=threshold,line=list(color="#D98A7A",dash="dash",width=1.5),showlegend=FALSE) - p%>%layout(title=list(text=title,font=list(size=14)), - xaxis=list(title="Chromosome",tickvals=as.list(chr_mids[chroms]), - ticktext=as.list(paste0("Chr ",chroms)),tickangle=45,gridcolor="#F0EBE0"), - yaxis=list(title=y_label,gridcolor="#F0EBE0"), - plot_bgcolor="#FDFBF7",paper_bgcolor="#FDFBF7") + p <- p %>% add_segments(x = min(pd$cum_pos, na.rm = TRUE), xend = max(pd$cum_pos, na.rm = TRUE), + y = threshold, yend = threshold, line = list(color = "#ff6b6b", dash = "dash", width = 2), showlegend = FALSE) + p %>% layout(title = list(text = title, font = list(size = 14, color = "#ffaa66")), + xaxis = list(title = "Chromosome", tickvals = as.list(chr_mids[chroms]), + ticktext = as.list(paste0("Chr ", chroms)), tickangle = 45, gridcolor = "#333344", color = "#cccccc"), + yaxis = list(title = y_label, gridcolor = "#333344", color = "#cccccc"), + plot_bgcolor = "#1a1a2e", paper_bgcolor = "#1a1a2e") } - output$fst_plot <- renderPlotly({ req(rv$sel_metrics); create_man_plotly(rv$sel_metrics,"Fst","🧬 Fst Manhattan Plot",input$fst_thr,"Fst") }) - output$tajima_plot <- renderPlotly({ req(rv$sel_metrics); create_man_plotly(rv$sel_metrics,"Tajima_D_Dom","📉 Tajima's D Manhattan Plot",input$tajima_thr,"Tajima D") }) + output$fst_plot <- renderPlotly({ req(rv$sel_metrics); create_man_plotly(rv$sel_metrics, "Fst", "🧬 Fst Manhattan Plot", input$fst_thr, "Fst") }) + output$tajima_plot <- renderPlotly({ req(rv$sel_metrics); create_man_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),], - options=list(scrollX=TRUE,pageLength=10,dom='Blfrtip'), - rownames=FALSE,class='cell-border stripe hover')%>% - formatRound(c("Fst","Pi_Dom","Pi_Wild","Tajima_D_Dom"),4) + datatable(rv$sel_metrics[order(-rv$sel_metrics$Fst), ], + options = list(scrollX = TRUE, pageLength = 10, dom = 'Blfrtip'), + rownames = FALSE, class = 'cell-border stripe hover') %>% + formatRound(c("Fst", "Pi_Dom", "Pi_Wild", "Tajima_D_Dom"), 4) }) # ── DOWNLOADS ───────────────────────────────────────────── output$dl_manhattan <- downloadHandler( - filename=function() paste0("manhattan_",Sys.Date(),".png"), - content=function(file) { + filename = function() paste0("manhattan_", Sys.Date(), ".png"), + content = function(file) { req(rv$scan_all) - if("Message"%in%colnames(rv$scan_all)) return() - pd <- rv$scan_all[!is.na(rv$scan_all$LOD)&!is.na(rv$scan_all$Position),] + if("Message" %in% colnames(rv$scan_all)) return() + pd <- rv$scan_all[!is.na(rv$scan_all$LOD) & !is.na(rv$scan_all$Position), ] pd$Chromosome <- as.character(pd$Chromosome) - chroms <- sort(unique(pd$Chromosome),method="radix") - offsets <- numeric(length(chroms)); names(offsets) <- chroms + chroms <- sort(unique(pd$Chromosome), method = "radix") + offsets <- numeric(length(chroms)) + names(offsets) <- 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; next } + offsets[chroms[i]] <- offsets[chroms[i-1]] + max(pd$Position[pd$Chromosome == chroms[i-1]], na.rm = TRUE) * 1.05 } - pd$cum_pos <- pd$Position+offsets[pd$Chromosome] - pd$sig <- pd$LOD>=lod_thr() - chr_colors <- rep(c("#A8E6CF","#DCEDC1","#FFD3B6","#FFAAA5"),ceiling(length(chroms)/4))[seq_along(chroms)] + pd$cum_pos <- pd$Position + offsets[pd$Chromosome] + pd$sig <- pd$LOD >= lod_thr() + chr_colors <- rep(c("#ff6b6b", "#4ecdc4", "#45b7d1", "#ffb347"), ceiling(length(chroms) / 4))[seq_along(chroms)] names(chr_colors) <- chroms - chr_mids <- tapply(pd$cum_pos,pd$Chromosome,median,na.rm=TRUE) - p <- ggplot(pd,aes(x=cum_pos,y=LOD))+ - geom_point(aes(color=Chromosome),size=1.5,alpha=.7,show.legend=FALSE)+ - geom_point(data=pd[pd$sig,],color="#E15759",size=4,shape=18)+ - geom_hline(yintercept=lod_thr(),linetype="dashed",color="#E15759",linewidth=.8)+ - scale_color_manual(values=chr_colors)+ - scale_x_continuous(breaks=chr_mids[chroms],labels=paste0("Chr ",chroms))+ - labs(title=paste(input$mapping_method,"Manhattan Plot"), - subtitle=paste0("LOD ≥ ",lod_thr()," | ",sum(pd$sig,na.rm=TRUE)," significant QTLs"), - x="Chromosome",y="LOD Score")+ - theme_minimal(base_size=12)+ - theme(panel.background=element_rect(fill="#FDFBF7",color=NA), - plot.background=element_rect(fill="#FDFBF7",color=NA), - panel.grid.minor=element_blank(), - panel.grid.major.x=element_blank(), - panel.grid.major.y=element_line(color="#F0EBE0"), - axis.text.x=element_text(angle=45,hjust=1,color="#8B7A5A"), - axis.text.y=element_text(color="#8B7A5A"), - axis.title=element_text(color="#5D4E30",face="bold"), - plot.title=element_text(face="bold",color="#5D4E30",size=14), - plot.subtitle=element_text(color="#8B7A5A",size=11)) - if(sum(pd$sig,na.rm=TRUE)>0&&sum(pd$sig,na.rm=TRUE)<=30) - p <- p+ggrepel::geom_label_repel(data=pd[pd$sig,],aes(label=Marker), - size=2.5,max.overlaps=15,fill="white",color="#E15759",segment.color="#E15759") - ggsave(file,plot=p,width=14,height=6,dpi=200,bg="#FDFBF7") + chr_mids <- tapply(pd$cum_pos, pd$Chromosome, median, na.rm = TRUE) + p <- ggplot(pd, aes(x = cum_pos, y = LOD)) + + geom_point(aes(color = Chromosome), size = 1.5, alpha = 0.7, show.legend = FALSE) + + geom_point(data = pd[pd$sig, ], color = "#ff1493", size = 4, shape = 18) + + geom_hline(yintercept = lod_thr(), linetype = "dashed", color = "#ff6b6b", linewidth = 0.8) + + scale_color_manual(values = chr_colors) + + scale_x_continuous(breaks = chr_mids[chroms], labels = paste0("Chr ", chroms)) + + labs(title = paste(input$mapping_method, "Manhattan Plot"), + subtitle = paste0("LOD ≥ ", lod_thr(), " | ", sum(pd$sig, na.rm = TRUE), " significant QTLs"), + x = "Chromosome", y = "LOD Score") + + theme_minimal(base_size = 12) + + theme(panel.background = element_rect(fill = "#1a1a2e", color = NA), + plot.background = element_rect(fill = "#1a1a2e", color = NA), + panel.grid.minor = element_blank(), + panel.grid.major.x = element_blank(), + panel.grid.major.y = element_line(color = "#333344"), + axis.text.x = element_text(angle = 45, hjust = 1, color = "#cccccc"), + axis.text.y = element_text(color = "#cccccc"), + axis.title = element_text(color = "#ffaa66", face = "bold"), + plot.title = element_text(face = "bold", color = "#ffaa66", size = 14), + plot.subtitle = element_text(color = "#aaaaaa", size = 11)) + if(sum(pd$sig, na.rm = TRUE) > 0 && sum(pd$sig, na.rm = TRUE) <= 30) + p <- p + ggrepel::geom_label_repel(data = pd[pd$sig, ], aes(label = Marker), + size = 2.5, max.overlaps = 15, fill = "#2d2d44", color = "#ff1493", segment.color = "#ff1493") + ggsave(file, plot = p, width = 14, height = 6, dpi = 200, bg = "#1a1a2e") } ) output$dl_idiogram <- downloadHandler( - filename=function() paste0("idiogram_",Sys.Date(),".png"), - content=function(file) { + filename = function() paste0("idiogram_", Sys.Date(), ".png"), + content = function(file) { req(rv$scan_all, rv$all_markers) res_list <- list() mth <- isolate(input$mapping_method) - if(!is.null(rv$scan_all)&&!"Message"%in%colnames(rv$scan_all)) res_list[[mth]] <- rv$scan_all + if(!is.null(rv$scan_all) && !"Message" %in% colnames(rv$scan_all)) res_list[[mth]] <- rv$scan_all for (m in names(rv$compare_res)) { r <- rv$compare_res[[m]] - if(!is.null(r)&&!"Message"%in%colnames(r)) res_list[[m]] <- r + if(!is.null(r) && !"Message" %in% colnames(r)) res_list[[m]] <- r } - if(length(res_list)==0) return() - png(file,width=1800,height=900,res=150,bg="#FDFBF7") - par(bg="#FDFBF7") + if(length(res_list) == 0) return() + png(file, width = 1800, height = 900, res = 150, bg = "#1a1a2e") + par(bg = "#1a1a2e") make_chromosome_idiogram(res_list, rv$all_markers, lod_thr()) dev.off() } ) output$dl_results <- downloadHandler( - filename=function() paste0("qtl_results_",Sys.Date(),".xlsx"), - content=function(file) { + filename = function() paste0("qtl_results_", Sys.Date(), ".xlsx"), + content = function(file) { sheets <- list() - 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) { + 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_lod_support_interval(sig, rv$scan_all, isolate(input$lod_drop)) - sheets[["QTL_Significant"]] <- sig[order(-sig$LOD),] + sheets[["QTL_Significant"]] <- sig[order(-sig$LOD), ] } sheets[["Full_Scan"]] <- rv$scan_all } if(!is.null(rv$perf)) sheets[["Performance"]] <- rv$perf for (m in names(rv$compare_res)) { r <- rv$compare_res[[m]] - if(!is.null(r)&&!"Message"%in%colnames(r)) - sheets[[paste0("Model_",m)]] <- r[r$LOD>=lod_thr()&!is.na(r$LOD),] + if(!is.null(r) && !"Message" %in% colnames(r)) + sheets[[paste0("Model_", m)]] <- r[r$LOD >= lod_thr() & !is.na(r$LOD), ] } 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) sheets[["Common_QTL"]] <- cq + error = function(e) NULL) + if(!is.null(cq) && nrow(cq) > 0) sheets[["Common_QTL"]] <- cq sheets[["Methods"]] <- data.frame( - Method=names(MAPPING_MODELS), - Description=sapply(MAPPING_MODELS,`[[`,"desc")) - if(length(sheets)==0) sheets[["Empty"]] <- data.frame(msg="Run analysis first") + Method = names(MAPPING_MODELS), + Description = sapply(MAPPING_MODELS, `[[`, "desc")) + if(length(sheets) == 0) sheets[["Empty"]] <- data.frame(msg = "Run analysis first") writexl::write_xlsx(sheets, file) } ) output$dl_pred <- downloadHandler( - filename=function() paste0("predicted_phenotypes_",Sys.Date(),".xlsx"), - content=function(file) { + filename = function() paste0("predicted_phenotypes_", Sys.Date(), ".xlsx"), + content = function(file) { req(rv$pred_test) - writexl::write_xlsx(list(Predictions=rv$pred_test),file) + 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) { + filename = function() paste0("common_qtl_", Sys.Date(), ".xlsx"), + content = function(file) { cq <- tryCatch(find_common_qtl(rv$compare_res, lod_thr(), isolate(input$min_models)), - error=function(e) NULL) - if(!is.null(cq)&&nrow(cq)>0) - writexl::write_xlsx(list(Common_QTL=cq),file) + error = function(e) NULL) + if(!is.null(cq) && nrow(cq) > 0) + writexl::write_xlsx(list(Common_QTL = cq), file) else - writexl::write_xlsx(list(Empty=data.frame(msg="No common QTLs or run Compare Models first")),file) + writexl::write_xlsx(list(Empty = data.frame(msg = "No common QTLs or run Compare Models first")), file) } ) output$dl_sel <- downloadHandler( - filename=function() paste0("selection_",Sys.Date(),".xlsx"), - content=function(file) { - if(!is.null(rv$sel_metrics)&&!"Message"%in%colnames(rv$sel_metrics)) - writexl::write_xlsx(list(Selection=rv$sel_metrics),file) + filename = function() paste0("selection_", Sys.Date(), ".xlsx"), + content = function(file) { + if(!is.null(rv$sel_metrics) && !"Message" %in% colnames(rv$sel_metrics)) + writexl::write_xlsx(list(Selection = rv$sel_metrics), file) else - writexl::write_xlsx(list(Empty=data.frame(msg="Run domestication first")),file) + writexl::write_xlsx(list(Empty = data.frame(msg = "Run domestication first")), file) } ) } -# #Run the app -shinyApp(ui=ui, server=server) \ No newline at end of file +# Run the app +shinyApp(ui = ui, server = server) \ No newline at end of file