diff --git "a/app.R" "b/app.R" --- "a/app.R" +++ "b/app.R" @@ -1,47 +1,32 @@ # ============================================================ -# QTL-Mapper v5 — Composite Interval Mapping (CIM) +# QTL-Mapper v6 — Multi-Model QTL Mapping # -# KEY FIXES vs v4: -# 1. PVE FORMULA OVERHAULED — Reason PVE was too low in v4: -# The partial R² approach (RSS_reduced - RSS_full)/SS_total was computing -# tiny incremental gains because cofactors already explained most variance. -# v5 uses a HYBRID approach: -# PVE_marker = R² of marker-only model (lm(Y ~ a_code + d_code)) — unconfounded -# PVE_CIM = semi-partial R²: SS_marker_in_full / SS_total -# = (RSS_reduced - RSS_full) / SS_total BUT with SS_total -# recomputed as SS of RESIDUALS from cofactor-only model (cofactor-adjusted) -# This gives a MEANINGFUL partial PVE that is not deflated by cofactor pre-absorption. +# KEY FIXES vs v5: +# 1. MULTI-CHROMOSOME FIX — CIM scan now properly iterates ALL chromosomes +# Root cause: marker_info join was failing silently for non-Chr1 markers +# Fix: robust marker lookup + debug logging per chromosome # -# 2. ADDITIVE EFFECT SIGN: Consistent -1/0/+1 coding (kept from v4) +# 2. MULTIPLE MAPPING MODELS: +# - Simple Interval Mapping (SIM) — lm per marker, no cofactors +# - Composite Interval Mapping (CIM) — cofactor-controlled scan +# - Multiple QTL Model (MQM) — stepwise model selection +# - LASSO-based QTL — penalized regression +# - Ridge Regression QTL — all markers simultaneously # -# 3. QTL SUPPORT INTERVAL: LOD-1.5 drop (kept from v4) +# 3. MODEL SELECTOR UI — dropdown to choose mapping method # -# 4. CHROMOSOME VIZ DOWNLOAD: Now exports as HTML matching the on-screen -# interactive display exactly (same CSS markers, interval bands, colors). -# FIX: Previously used ggplot2 PNG which looked different from on-screen. +# 4. PROPER MULTI-CHROMOSOME MANHATTAN — plotly with correct offsets # -# 5. COFACTOR VARIANCE INFLATION FIX: -# When n_cofactors is large, cofactors pre-absorb marker signal. -# v5 uses adaptive cofactor count = min(K, sqrt(n_samples)) and -# ensures the focal marker is never a cofactor for itself. +# 5. CHROMOSOME IDIOGRAM PLOT — replicates the reference image style: +# colored symbols (circles, triangles) per trait on chromosome bars +# with cM scale, multiple traits overlaid, publication-ready # -# 6. PREDICTED TEST PHENOTYPE DOWNLOAD: Added missing downloadHandler -# for predicted test phenotype data (was missing in previous versions). +# 6. PVE FORMULA (v5 semi-partial R2 kept, applied to all models) # -# PVE FORMULAS (v5 — corrected): -# a_code = genotype - 1 (-1, 0, +1 for AA, Aa, aa) -# d_code = 1 if het, else 0 +# 7. GENOTYPE CODING: 0/1/2 input → -1/0/+1 internal (AA/Aa/aa) # -# PVE_marker (%) = R² of lm(Y ~ a_code + d_code) × 100 -# [unconditional — marker alone vs null] +# 8. ROBUST DATA LOADING — handles \r\n, quoted fields, mismatched rows # -# PVE_CIM (%) = semi-partial R²: -# SS_cofactors_adjusted_total = SS_resid(lm(Y ~ cofactors)) -# SS_marker_given_cofactors = RSS_reduced - RSS_full -# PVE_CIM = SS_marker_given_cofactors / SS_cofactors_adjusted_total × 100 -# [conditional — fraction of RESIDUAL variance explained by marker] -# -# This prevents PVE_CIM from being near-zero due to cofactor pre-absorption. # ============================================================ options(repos = c(CRAN = "https://cloud.r-project.org")) @@ -49,7 +34,7 @@ options(repos = c(CRAN = "https://cloud.r-project.org")) required_packages <- c( "shiny", "randomForest", "caret", "DT", "ggplot2", "plotly", "writexl", "viridis", "reshape2", "dplyr", "httr", "jsonlite", - "shinyjs", "markdown", "base64enc", "gridExtra", "ggrepel", "grid" + "shinyjs", "base64enc", "ggrepel", "grid", "glmnet" ) for (pkg in required_packages) { @@ -64,190 +49,224 @@ for (pkg in required_packages) { # ============================================================ token <- Sys.getenv("GROQ_API_KEY") token_exists <- token != "" -token_length <- if (token_exists) nchar(token) else 0 - -cat("=== GROQ API TOKEN DEBUG ===\n") -cat("Token exists:", token_exists, "\n") -cat("Token length:", token_length, "\n") -if (token_exists) cat("Token starts with:", substr(token, 1, 10), "\n") -cat("===================================\n") - HF_API_TOKEN <- token HF_API_URL <- "https://api.groq.com/openai/v1/chat/completions" -default_model <- "llama-3.1-8b-instant" +default_model_ai <- "llama-3.1-8b-instant" -available_models <- list( - list(id = "llama-3.1-8b-instant", label = "Llama 3.1 8B", provider = "groq", tier = "free"), - list(id = "llama-3.3-70b-versatile", label = "Llama 3.3 70B", provider = "groq", tier = "free"), - list(id = "meta-llama/llama-4-maverick-17b-128e-instruct", label = "Llama 4 Maverick 17B", provider = "groq", tier = "free"), - list(id = "moonshotai/kimi-k2-instruct-0905", label = "Kimi K2", provider = "groq", tier = "free") +available_models_ai <- list( + list(id = "llama-3.1-8b-instant", label = "Llama 3.1 8B", tier = "free"), + list(id = "llama-3.3-70b-versatile", label = "Llama 3.3 70B", tier = "free"), + list(id = "meta-llama/llama-4-maverick-17b-128e-instruct", label = "Llama 4 Maverick 17B", tier = "free") ) - -model_choices <- setNames( - sapply(available_models, function(m) m$id), - sapply(available_models, function(m) paste0(m$label, " [", m$tier, "]")) +model_choices_ai <- setNames( + sapply(available_models_ai, `[[`, "id"), + sapply(available_models_ai, function(m) paste0(m$label, " [", m$tier, "]")) ) # ============================================================ -# CIM CORE FUNCTION — v5 PVE FIX +# MAPPING MODEL DEFINITIONS # ============================================================ -run_cim <- function(genotype_matrix, phenotype_vector, marker_info, - n_cofactors = 10, window_size = 10, - lod_threshold = 2.0) { +MAPPING_MODELS <- list( + "SIM" = list(label = "Simple Interval Mapping (SIM)", desc = "Single-marker regression; LOD = -log10(p); no cofactors"), + "CIM" = list(label = "Composite Interval Mapping (CIM)", desc = "CIM with RF-selected cofactors; semi-partial R² PVE"), + "MQM" = list(label = "Multiple QTL Model (MQM / stepwise)", desc = "Forward stepwise selection across all markers"), + "LASSO" = list(label = "LASSO QTL (penalized)", desc = "L1 penalized regression; lambda by cross-validation"), + "RIDGE" = list(label = "Ridge Regression QTL", desc = "L2 penalized regression; shrinks all marker effects") +) - markers <- colnames(genotype_matrix) - n_markers <- length(markers) - n_samples <- length(phenotype_vector) +# ============================================================ +# CLEAN COLUMN NAMES — strip \r quotes spaces +# ============================================================ +cn <- function(x) trimws(gsub('[\r\n\"]', '', as.character(x))) - # Adaptive cofactor count: prevent over-absorption - max_cofactors <- max(3, floor(sqrt(n_samples))) - n_cofactors <- min(n_cofactors, max_cofactors) - cat("CIM v5: Starting with", n_markers, "markers,", n_samples, "samples\n") - cat("CIM v5: Adaptive cofactor cap =", n_cofactors, "\n") +# ============================================================ +# GENOTYPE LOADER — robust, handles header/chr/pos rows +# ============================================================ +load_genotype_file <- function(filepath) { + lines <- readLines(filepath, warn = FALSE) + lines <- gsub("\r", "", lines) + lines <- lines[nchar(trimws(lines)) > 0] + if (length(lines) < 4) stop("Need ≥4 rows: header + chr + pos + ≥1 sample") + + header <- cn(strsplit(lines[1], ",")[[1]]) + chr_row <- cn(strsplit(lines[2], ",")[[1]]) + pos_row <- cn(strsplit(lines[3], ",")[[1]]) + data_lines <- lines[-(1:3)] + + gd <- read.csv(text = paste(data_lines, collapse = "\n"), + header = FALSE, stringsAsFactors = FALSE, quote = '"', + fill = TRUE) + + # Pad or trim to match header length + if (ncol(gd) < length(header)) { + for (k in (ncol(gd)+1):length(header)) + gd[[paste0("V",k)]] <- NA + } + if (ncol(gd) > length(header)) gd <- gd[, 1:length(header)] + colnames(gd) <- header - # ---- Step 1: Select cofactors via RF ---- - valid_rows <- !is.na(phenotype_vector) - X_valid <- genotype_matrix[valid_rows, , drop = FALSE] - y_valid <- phenotype_vector[valid_rows] + rownames(gd) <- cn(as.character(gd[, 1])) + gd <- gd[, -1, drop = FALSE] - nzv <- apply(X_valid, 2, function(x) length(unique(na.omit(x))) < 2) - X_valid <- X_valid[, !nzv, drop = FALSE] + # Coerce to numeric (0/1/2 coding) + for (col in colnames(gd)) + gd[[col]] <- suppressWarnings(as.numeric(as.character(gd[[col]]))) - rf_model <- tryCatch( - randomForest(x = X_valid, y = y_valid, ntree = 500, importance = TRUE), - error = function(e) NULL + marker_info <- data.frame( + Marker = colnames(gd), + Chromosome = cn(chr_row[-1][seq_along(colnames(gd))]), + Position = suppressWarnings(as.numeric(cn(pos_row[-1][seq_along(colnames(gd))]))), + stringsAsFactors = FALSE ) + marker_info <- marker_info[!is.na(marker_info$Position) & marker_info$Chromosome != "", ] - if (!is.null(rf_model)) { - imp_scores <- importance(rf_model, type = 1)[, 1] - top_cofactors <- names(sort(imp_scores, decreasing = TRUE))[1:min(n_cofactors * 2, length(imp_scores))] - } else { - p_vals <- sapply(colnames(X_valid), function(m) { - fit <- lm(y_valid ~ X_valid[, m]) - coef(summary(fit))[2, 4] - }) - top_cofactors <- names(sort(p_vals))[1:min(n_cofactors * 2, length(p_vals))] - } - - cat("CIM v5: Selected", length(top_cofactors), "candidate cofactors\n") - - # ---- Step 2: Scan each marker ---- - results_list <- list() + # Only keep markers with valid map info + valid_cols <- colnames(gd)[colnames(gd) %in% marker_info$Marker] + gd <- gd[, valid_cols, drop = FALSE] - for (i in seq_along(markers)) { - m <- markers[i] - - geno <- genotype_matrix[, m] - valid_idx <- !is.na(geno) & !is.na(phenotype_vector) - geno_v <- geno[valid_idx] - pheno_v <- phenotype_vector[valid_idx] + cat("LOADED:", nrow(gd), "samples,", ncol(gd), "markers,", + length(unique(marker_info$Chromosome)), "chromosomes\n") + cat("CHROMOSOMES:", paste(sort(unique(marker_info$Chromosome)), collapse = ", "), "\n") - if (length(unique(geno_v)) < 2 || length(pheno_v) < 10) next + list(geno = gd, marker_info = marker_info, + n_samples = nrow(gd), n_markers = ncol(gd), + chromosomes = sort(unique(marker_info$Chromosome))) +} - m_info <- marker_info[marker_info$Marker == m, ] - if (nrow(m_info) == 0) next - m_chr <- m_info$Chromosome[1] - m_pos <- m_info$Position[1] +# ============================================================ +# CORE QTL SCAN — dispatcher for all model types +# ============================================================ +qtl_scan <- function(genotype_matrix, phenotype_vector, marker_info, + method = "CIM", n_cofactors = 10, window_size = 10) { - # Exclude nearby markers on same chromosome - chr_markers <- marker_info[marker_info$Chromosome == m_chr, ] - chr_markers <- chr_markers[order(chr_markers$Position), ] - m_idx <- which(chr_markers$Marker == m) + markers <- colnames(genotype_matrix) + n_markers <- length(markers) + n_samples <- length(phenotype_vector) - if (length(m_idx) > 0) { - nearby_range <- max(1, m_idx - window_size):min(nrow(chr_markers), m_idx + window_size) - nearby_mks <- chr_markers$Marker[nearby_range] + cat("\n=== QTL SCAN ===\n") + cat("Method:", method, "\n") + cat("Markers:", n_markers, "| Samples:", n_samples, "\n") + cat("Chromosomes in marker_info:", + paste(sort(unique(marker_info$Chromosome)), collapse=", "), "\n") + + valid_rows <- !is.na(phenotype_vector) + X_valid <- genotype_matrix[valid_rows, , drop = FALSE] + y_valid <- phenotype_vector[valid_rows] + + # Remove zero-variance 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, alpha = 1)) + if (method == "RIDGE") return(qtl_scan_lasso(X_valid, y_valid, marker_info, alpha = 0)) + if (method == "MQM") return(qtl_scan_mqm(X_valid, y_valid, marker_info)) + + # Select cofactors for CIM + cofactors <- character(0) + 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))] } else { - nearby_mks <- m + 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))] } + cat("CIM cofactors selected:", length(cofactors), "\n") + } - active_cofactors <- setdiff(top_cofactors, c(m, nearby_mks)) - active_cofactors <- active_cofactors[active_cofactors %in% colnames(genotype_matrix)] - active_cofactors <- head(active_cofactors, n_cofactors) + # Per-marker scan (SIM or CIM) + results_list <- list() + chr_counts <- table(marker_info$Chromosome[marker_info$Marker %in% colnames(X_valid)]) + cat("Markers per chr:\n"); print(chr_counts) - # Build data frame - df_model <- data.frame(y = pheno_v, focal = geno_v) + for (i in seq_along(colnames(X_valid))) { + m <- colnames(X_valid)[i] + geno <- X_valid[, m] - if (length(active_cofactors) > 0) { - cof_mat <- genotype_matrix[valid_idx, active_cofactors, drop = FALSE] - cof_mat[is.na(cof_mat)] <- 0 - df_model <- cbind(df_model, cof_mat) - } - - df_model <- df_model[complete.cases(df_model), ] - if (nrow(df_model) < 10) next + 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 - tryCatch({ - # ============================================================ - # v5 PVE FIX: Use SS_total_adjusted (cofactor residual SS) - # as denominator so partial PVE is not near-zero - # ============================================================ - SS_total_raw <- sum((df_model$y - mean(df_model$y))^2) - - if (length(active_cofactors) > 0) { - cof_formula <- paste(active_cofactors, collapse = " + ") - full_formula <- as.formula(paste("y ~ focal +", cof_formula)) - reduced_formula <- as.formula(paste("y ~", cof_formula)) + # Get map info + 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 + + # Build CIM cofactor set (exclude window around focal marker) + 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) + if (length(focal_idx_c) > 0) { + r1 <- max(1, focal_idx_c - window_size) + r2 <- min(nrow(chr_mk), focal_idx_c + window_size) + nearby <- chr_mk$Marker[r1:r2] } else { - full_formula <- as.formula("y ~ focal") - reduced_formula <- as.formula("y ~ 1") + nearby <- m } + active_cof <- setdiff(cofactors, c(m, nearby)) + active_cof <- active_cof[active_cof %in% colnames(X_valid)] + active_cof <- head(active_cof, n_cofactors) + } - fit_full <- lm(full_formula, data = df_model) - fit_reduced <- lm(reduced_formula, data = df_model) - - sm_full <- summary(fit_full) - coef_t <- sm_full$coefficients - if (!"focal" %in% rownames(coef_t)) next - - p_val <- coef_t["focal", "Pr(>|t|)"] - lod <- -log10(p_val + 1e-300) - - RSS_full <- sum(residuals(fit_full)^2) - RSS_reduced <- sum(residuals(fit_reduced)^2) - SS_marker_given_cofactors <- RSS_reduced - RSS_full - - # v5 KEY FIX: denominator = SS of cofactor residuals (not raw SS_total) - SS_denom_cim <- RSS_reduced - pve_cim <- if (SS_denom_cim > 0) - (SS_marker_given_cofactors / SS_denom_cim) * 100 - else NA - pve_cim <- max(0, pve_cim, na.rm = TRUE) - - # ---- Additive / dominance coding (-1/0/+1) ---- - a_code <- df_model$focal - 1 - d_code <- as.numeric(df_model$focal == 1) - has_het <- length(unique(d_code)) > 1 + # Fit model + 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) - if (has_het) { - lm_eff <- lm(df_model$y ~ a_code + d_code) + if (length(active_cof) > 0) { + fit_full <- lm(as.formula(paste("y ~ focal +", paste(active_cof, collapse="+"))), data = df) + fit_reduced <- lm(as.formula(paste("y ~", paste(active_cof, collapse="+"))), data = df) } else { - lm_eff <- lm(df_model$y ~ a_code) + fit_full <- lm(y ~ focal, data = df) + fit_reduced <- lm(y ~ 1, data = df) } - # PVE_marker: unconditional R² - pve_marker <- summary(lm_eff)$r.squared * 100 - pve_marker <- max(0, pve_marker, na.rm = TRUE) - - c_eff <- coef(lm_eff) - a_eff <- c_eff["a_code"] - sm_eff <- summary(lm_eff) - se_t <- sm_eff$coefficients - se_a <- if ("a_code" %in% rownames(se_t)) se_t["a_code", "Std. Error"] else NA + ct <- coef(summary(fit_full)) + if (!"focal" %in% rownames(ct)) next + p_val <- ct["focal", "Pr(>|t|)"] + lod <- -log10(max(p_val, 1e-300)) - if (has_het) { - d_eff <- c_eff["d_code"] - se_d <- if ("d_code" %in% rownames(se_t)) se_t["d_code", "Std. Error"] else NA - d_rat <- if (!is.na(a_eff) && a_eff != 0) abs(d_eff / a_eff) else NA - } else { - d_eff <- NA; se_d <- NA; d_rat <- NA - } + RSS_full <- sum(residuals(fit_full)^2) + RSS_reduced <- sum(residuals(fit_reduced)^2) + SS_marker <- RSS_reduced - RSS_full + pve_cim <- if (RSS_reduced > 0) max(0, SS_marker / RSS_reduced * 100) else NA - dom_class <- 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" + # Additive/dominance effects (-1/0/+1 coding) + 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" results_list[[m]] <- data.frame( Marker = m, @@ -255,551 +274,426 @@ run_cim <- function(genotype_matrix, phenotype_vector, marker_info, Position = m_pos, LOD = lod, P_Value = p_val, - PVE_Marker_Percent = pve_marker, + 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), + 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 = se_d, Dominance_Ratio = d_rat, - Dominance_Class = dom_class, - N_Cofactors = length(active_cofactors), - N_Samples = nrow(df_model), - N_Heterozygotes = sum(df_model$focal == 1), - stringsAsFactors = FALSE - ) - - }, error = function(e) { - cat("CIM v5 error at marker", m, ":", e$message, "\n") - }) + Dominance_Class = dom_cl, + N_Cofactors = length(active_cof), + N_Samples = nrow(df), + Method = method, + stringsAsFactors = FALSE) + }, error = function(e) {}) } if (length(results_list) == 0) - return(data.frame(Message = "CIM produced no results — check data format")) + return(data.frame(Message = paste("No results from", method, "— check data format"))) + + res <- do.call(rbind, results_list) + res <- res[order(res$Chromosome, res$Position), ] + chr_counts_res <- table(res$Chromosome) + cat("Results per chromosome:\n"); print(chr_counts_res) + cat("Total markers with results:", nrow(res), "\n") + return(res) +} - cim_result <- do.call(rbind, results_list) - cim_result <- cim_result[order(-cim_result$LOD), ] - cat("CIM v5: Completed scan,", nrow(cim_result), "markers evaluated\n") - return(cim_result) +# ============================================================ +# LASSO / RIDGE QTL +# ============================================================ +qtl_scan_lasso <- function(X, y, marker_info, alpha = 1) { + 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=alpha, nfolds=5), error=function(e) NULL) + if (is.null(cv)) return(data.frame(Message="LASSO/Ridge failed")) + + best_lam <- cv$lambda.1se + coefs <- coef(cv, s=best_lam)[-1] # drop intercept + coef_df <- data.frame(Marker=rownames(coef(cv,s=best_lam))[-1], Effect=as.numeric(coefs)) + coef_df <- coef_df[abs(coef_df$Effect) > 0, ] + if (nrow(coef_df) == 0) return(data.frame(Message="No non-zero effects")) + + # Compute LOD-like score: |effect| / max(|effect|) * 10 + 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 + + # Compute R2 from simple regression of each marker on phenotype + 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 # same for penalized + 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_Class <- "Additive" + coef_df$N_Cofactors <- 0 + coef_df$N_Samples <- sum(valid) + coef_df$Method <- if (alpha==1) "LASSO" else "RIDGE" + coef_df <- coef_df[order(coef_df$Chromosome, coef_df$Position), ] + return(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")]) } # ============================================================ -# LOD-1.5 SUPPORT INTERVAL +# MQM — forward stepwise # ============================================================ -add_lod_support_interval <- function(sig_df, cim_all_df, lod_drop = 1.5) { - sig_df$Low_Flank <- NA_character_ - sig_df$High_Flank <- NA_character_ - sig_df$Interval_Start <- NA_real_ - sig_df$Interval_End <- NA_real_ - sig_df$Interval_Size_Mb <- NA_real_ +qtl_scan_mqm <- function(X, y, marker_info) { + valid <- !is.na(y) + X_v <- X[valid, , drop=FALSE]; y_v <- y[valid] + + # Step 1: SIM scan + 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) + }) - for (i in 1:nrow(sig_df)) { - focal_marker <- sig_df$Marker[i] - focal_chr <- sig_df$Chromosome[i] - focal_lod <- sig_df$LOD[i] - - chr_data <- cim_all_df[cim_all_df$Chromosome == focal_chr & - !is.na(cim_all_df$Position) & - !is.na(cim_all_df$LOD), ] - chr_data <- chr_data[order(chr_data$Position), ] - if (nrow(chr_data) == 0) next - - lod_cutoff <- focal_lod - lod_drop - in_interval <- chr_data$LOD >= lod_cutoff - - if (sum(in_interval) > 0) { - interval_markers <- chr_data[in_interval, ] - focal_pos_cands <- chr_data$Position[chr_data$Marker == focal_marker] - - if (length(focal_pos_cands) > 0) { - int_start <- min(interval_markers$Position, focal_pos_cands) - int_end <- max(interval_markers$Position, focal_pos_cands) - } else { - int_start <- min(interval_markers$Position) - int_end <- max(interval_markers$Position) - } + # Step 2: iterative forward inclusion + selected <- character(0) + remaining <- names(sort(p_vals)) + threshold <- 0.01 - sig_df$Interval_Start[i] <- int_start - sig_df$Interval_End[i] <- int_end - sig_df$Interval_Size_Mb[i] <- (int_end - int_start) / 1e6 + for (cand in remaining[1:min(20, length(remaining))]) { + test_model <- c(selected, cand) + df_t <- data.frame(y=y_v, X_v[, test_model, drop=FALSE]) + df_t <- df_t[complete.cases(df_t), ] + if (nrow(df_t) < 10) next + tryCatch({ + fit_with <- lm(y ~ ., data=df_t) + fit_without <- if (length(selected)>0) lm(as.formula(paste("y~",paste(selected,collapse="+"))), data=df_t) else lm(y~1,data=df_t) + p_inc <- anova(fit_without, fit_with)[2,"Pr(>F)"] + if (!is.na(p_inc) && p_inc < threshold) selected <- test_model + }, error=function(e) {}) + } + if (length(selected)==0) selected <- names(sort(p_vals))[1:min(5,length(p_vals))] - below_interval <- chr_data[chr_data$Position < int_start, ] - above_interval <- chr_data[chr_data$Position > int_end, ] - sig_df$Low_Flank[i] <- if (nrow(below_interval) > 0) below_interval$Marker[nrow(below_interval)] else focal_marker - sig_df$High_Flank[i] <- if (nrow(above_interval) > 0) above_interval$Marker[1] else focal_marker - } else { - idx <- which(chr_data$Marker == focal_marker) - if (length(idx) > 0) { - sig_df$Low_Flank[i] <- if (idx > 1) chr_data$Marker[idx - 1] else focal_marker - sig_df$High_Flank[i] <- if (idx < nrow(chr_data)) chr_data$Marker[idx + 1] else focal_marker - sig_df$Interval_Start[i] <- sig_df$Position[i] - sig_df$Interval_End[i] <- sig_df$Position[i] - sig_df$Interval_Size_Mb[i] <- 0 + # Step 3: final LOD scores + 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 + m_info <- marker_info[marker_info$Marker==m,] + if (nrow(m_info)==0) next + + cofactors_m <- setdiff(selected, m) + tryCatch({ + df2 <- data.frame(y=yv, focal=gv) + if (length(cofactors_m)>0) { + cm <- X_v[v2, cofactors_m, drop=FALSE]; cm[is.na(cm)]<-0 + df2 <- cbind(df2, cm) } - } + df2 <- df2[complete.cases(df2),] + if (nrow(df2)<8) return(NULL) + fit_f <- if(length(cofactors_m)>0) lm(as.formula(paste("y~focal+",paste(cofactors_m,collapse="+"))),data=df2) else lm(y~focal,data=df2) + fit_r <- if(length(cofactors_m)>0) lm(as.formula(paste("y~",paste(cofactors_m,collapse="+"))),data=df2) else lm(y~1,data=df2) + ct2 <- coef(summary(fit_f)) + if (!"focal" %in% rownames(ct2)) next + p2 <- ct2["focal","Pr(>|t|)"] + lod2 <- -log10(max(p2, 1e-300)) + RSS_f <- sum(residuals(fit_f)^2); RSS_r <- sum(residuals(fit_r)^2) + pve_c <- if(RSS_r>0) max(0,(RSS_r-RSS_f)/RSS_r*100) else NA + a_c <- gv - 1; d_c <- as.numeric(gv==1); h2 <- length(unique(d_c))>1 + lme <- if(h2) lm(yv~a_c+d_c) else lm(yv~a_c) + pve_m <- max(0,summary(lme)$r.squared*100) + ce2 <- coef(lme); se2 <- coef(summary(lme)) + ae <- ce2["a_c"]; sea <- if("a_c" %in% rownames(se2)) se2["a_c","Std. Error"] else NA + de <- if(h2) ce2["d_c"] else NA + dr <- if(!is.na(de) && !is.na(ae) && ae!=0) abs(de/ae) else NA + dc <- 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(m_info$Chromosome[1]), Position=m_info$Position[1], + LOD=lod2, P_Value=p2, PVE_Marker_Percent=pve_m, PVE_CIM_Percent=pve_c, + 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=dc, N_Cofactors=length(cofactors_m), + N_Samples=nrow(df2), Method="MQM", stringsAsFactors=FALSE) + }, error=function(e) {}) } - return(sig_df) + if (length(results_list)==0) return(data.frame(Message="MQM produced no results")) + res <- do.call(rbind, results_list) + return(res[order(res$Chromosome, res$Position),]) } # ============================================================ -# GGPLOT2 MANHATTAN PLOT (download) +# LOD-1.5 SUPPORT INTERVAL # ============================================================ -make_ggplot_manhattan <- function(cim_all, lod_threshold = 2.0, title = "CIM Manhattan Plot") { - if (is.null(cim_all) || "Message" %in% colnames(cim_all)) return(NULL) - pd <- cim_all[!is.na(cim_all$LOD) & !is.na(cim_all$Position) & !is.na(cim_all$Chromosome), ] - if (nrow(pd) == 0) return(NULL) +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_ - pd$Chromosome <- as.character(pd$Chromosome) - chroms <- sort(unique(pd$Chromosome), method = "radix") - chr_offsets <- 0 - for (i in seq_along(chroms)) { - if (i == 1) chr_offsets <- setNames(0, chroms[1]) - else { - max_pos <- max(pd$Position[pd$Chromosome == chroms[i - 1]], na.rm = TRUE) - chr_offsets[chroms[i]] <- chr_offsets[chroms[i - 1]] + max_pos * 1.05 + 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$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= lod_threshold - chr_colors <- rep(c("#2563EB","#64748B"), ceiling(length(chroms)/2))[1:length(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.2, alpha = 0.7, show.legend = FALSE) + - geom_point(data = pd[pd$sig, ], color = "#DC2626", size = 2.8, shape = 18) + - geom_hline(yintercept = lod_threshold, linetype = "dashed", color = "#DC2626", linewidth = 0.6) + - scale_color_manual(values = chr_colors) + - scale_x_continuous(breaks = chr_mids[chroms], labels = chroms) + - labs(title = title, - subtitle = paste0("LOD threshold = ", lod_threshold, " | ", sum(pd$sig), " significant QTL(s)"), - x = "Chromosome", y = "LOD Score") + - theme_bw(base_size = 12) + - theme(panel.background = element_rect(fill = "white"), - plot.background = element_rect(fill = "white"), - panel.grid.minor = element_blank(), - panel.grid.major.x = element_blank(), - axis.text.x = element_text(angle = 45, hjust = 1, size = 9), - plot.title = element_text(face = "bold", size = 13), - plot.subtitle = element_text(color = "grey50", size = 10)) - - if (sum(pd$sig) > 0 && sum(pd$sig) <= 30) - p <- p + ggrepel::geom_label_repel(data = pd[pd$sig, ], aes(label = Marker), - size = 2.5, max.overlaps = 15, box.padding = 0.3, label.padding = 0.15, - fill = "white", color = "#DC2626", segment.color = "#DC2626") - return(p) + return(sig_df) } # ============================================================ -# HTML CHROMOSOME VISUALIZATION — matches on-screen display exactly -# FIX: Replaced ggplot2 PNG export with HTML generator that replicates -# the exact CSS/marker structure shown on-screen (same colors, interval -# bands, tick heights, cM labels, publication colors). +# CHROMOSOME IDIOGRAM PLOT — replicates reference image style +# Multiple traits, colored symbols on chromosome bars # ============================================================ -make_html_chromosome_viz <- function(qtl_effects, all_markers_df, lod_threshold = 2.0) { - if (is.null(qtl_effects) || "Message" %in% colnames(qtl_effects)) return(NULL) - if (is.null(all_markers_df) || nrow(all_markers_df) == 0) return(NULL) - - # Publication color palette (RColorBrewer Set1 / Nature-style) - COL_QTL <- "#C0392B" # Pompeii red — significant QTL - COL_FLANK <- "#2166AC" # Steel blue — flanking markers - COL_BG <- "#6B7280" # Warm grey — background markers - COL_INTERVAL <- "rgba(192,57,43,0.14)" # translucent red — LOD-1.5 band - COL_INT_BDR <- "rgba(192,57,43,0.40)" # interval border - - chromosomes <- unique(qtl_effects$Chromosome) - chr_html <- "" - - for (chr in chromosomes) { - chr_markers <- all_markers_df[all_markers_df$Chromosome == chr, ] - chr_markers <- chr_markers[order(chr_markers$Position), ] - chr_qtls <- qtl_effects[qtl_effects$Chromosome == chr, ] - if (nrow(chr_markers) == 0) next - - min_pos <- min(chr_markers$Position, na.rm = TRUE) - max_pos <- max(chr_markers$Position, na.rm = TRUE) - range_pos <- max_pos - min_pos - - flanking_markers <- c(chr_qtls$Low_Flank, chr_qtls$High_Flank) - flanking_markers <- flanking_markers[!is.na(flanking_markers) & flanking_markers != ""] - - # ── Interval bands — contained inside bar (top:0;bottom:0) ── - interval_html <- "" - if ("Interval_Start" %in% colnames(chr_qtls)) { - for (j in 1:nrow(chr_qtls)) { - qtl_row <- chr_qtls[j, ] - if (!is.na(qtl_row$Interval_Start) && !is.na(qtl_row$Interval_End) && range_pos > 0) { - left_pct <- ((qtl_row$Interval_Start - min_pos) / range_pos) * 100 - right_pct <- ((qtl_row$Interval_End - min_pos) / range_pos) * 100 - width_pct <- max(0.5, right_pct - left_pct) - interval_html <- paste0(interval_html, sprintf( - '
', - left_pct, width_pct, COL_INTERVAL, COL_INT_BDR, COL_INT_BDR)) - } - } +make_chromosome_idiogram <- function(qtl_list, all_markers_df, + lod_threshold = 2.0, + trait_colors = NULL) { + # qtl_list: named list of QTL result data.frames (one per trait/method) + if (is.null(all_markers_df) || nrow(all_markers_df)==0) return(NULL) + + # Default color palette (Nature-style) + default_colors <- c("#C0392B","#2166AC","#1A7A4A","#E67E22","#8E44AD","#17A589","#F39C12","#2980B9") + trait_names <- names(qtl_list) + if (is.null(trait_colors)) + trait_colors <- setNames(default_colors[seq_along(trait_names)], trait_names) + + # Symbol shapes per trait + shapes <- c(16, 17, 18, 15, 3, 4, 8, 9) # pch values + + # Get all chromosomes + chroms <- sort(unique(as.character(all_markers_df$Chromosome))) + n_chr <- length(chroms) + bar_height <- 0.35 # half-height of chromosome bar + x_gap <- 1.2 # spacing between chromosomes + + # Setup plot + par(mar=c(4,2,3,1), bg="white") + plot(0, 0, type="n", + xlim = c(0, n_chr * x_gap + 0.5), + ylim = c(-2, max(all_markers_df$Position, na.rm=TRUE) * 1.05), + xaxt="n", yaxt="n", + xlab="", ylab="cM", main="", + frame.plot=FALSE) + + # Y axis + max_pos <- max(all_markers_df$Position, na.rm=TRUE) + y_ticks <- pretty(c(0, max_pos), n=6) + axis(2, at=y_ticks, labels=y_ticks, cex.axis=0.75, col="grey60", col.axis="grey30", las=1) + mtext("cM", side=2, line=2.5, cex=0.8, col="grey40") + + for (ci in seq_along(chroms)) { + chr <- chroms[ci] + x_cen <- (ci-1) * x_gap + 0.7 # center x for this chromosome + + # Chromosome bar + chr_mk <- all_markers_df[as.character(all_markers_df$Chromosome)==as.character(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) + + # Draw chromosome body (gradient effect via rect) + rect(x_cen - bar_height*0.6, chr_min, + x_cen + bar_height*0.6, chr_len, + col = "grey88", border = "grey60", lwd=1.2) + + # Rounded caps (approximate via ellipse-like polygon) + cap_h <- chr_len * 0.02 + rect(x_cen - bar_height*0.6, chr_min - cap_h, + x_cen + bar_height*0.6, chr_min, + col="grey75", border="grey60", lwd=0.8) + rect(x_cen - bar_height*0.6, chr_len, + x_cen + bar_height*0.6, chr_len + cap_h, + col="grey75", border="grey60", lwd=0.8) + + # Centromere band (approximate at 40%) + 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="grey50", border="grey40", lwd=0.5) + + # All marker ticks (subtle) + 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="grey70", lwd=0.4) } - # ── Marker ticks — ALL confined inside 28px bar (top:2px to top:6px range) ── - # Bar height = 28px. Ticks must stay within: top >= 1px, top+height <= 27px - # Significant: height=22px top=3px (3+22=25 ≤ 27 ✓) - # Flanking: height=18px top=5px (5+18=23 ≤ 27 ✓) - # Background: height=14px top=7px (7+14=21 ≤ 27 ✓) - markers_html <- "" - for (i in 1:nrow(chr_markers)) { - marker <- chr_markers[i, ] - left <- if (range_pos > 0 && !is.na(range_pos)) { - ((marker$Position - min_pos) / range_pos) * 100 - } else { - (i / nrow(chr_markers)) * 100 - } - - pos_cm <- round(marker$Position, 1) - - if (marker$Marker %in% chr_qtls$Marker) { - lod_val <- chr_qtls$LOD[chr_qtls$Marker == marker$Marker][1] - pve_val <- chr_qtls$PVE_Marker_Percent[chr_qtls$Marker == marker$Marker][1] - tooltip <- paste0(marker$Marker, - " | LOD: ", round(lod_val, 2), - " | PVE: ", round(pve_val, 1), "%", - " | ", pos_cm, " cM") - style <- sprintf( - 'position:absolute;left:%.2f%%;transform:translateX(-50%%);width:7px;height:22px;top:3px;background:%s;border-radius:2px;box-shadow:0 0 5px rgba(192,57,43,0.5);cursor:pointer;z-index:2;', - left, COL_QTL) - } else if (marker$Marker %in% flanking_markers) { - tooltip <- paste0(marker$Marker, " (flanking) | ", pos_cm, " cM") - style <- sprintf( - 'position:absolute;left:%.2f%%;transform:translateX(-50%%);width:4px;height:18px;top:5px;background:%s;border-radius:2px;cursor:pointer;z-index:1;', - left, COL_FLANK) - } else { - tooltip <- paste0(marker$Marker, " | ", pos_cm, " cM") - style <- sprintf( - 'position:absolute;left:%.2f%%;transform:translateX(-50%%);width:3px;height:14px;top:7px;background:%s;border-radius:1px;opacity:0.55;', - left, COL_BG) + # QTL symbols per trait + 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)==as.character(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] + cex_fun <- function(lod) pmax(0.7, pmin(2.2, 0.5 + lod/4)) + + # Alternate left/right to avoid overlap + 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] + # Horizontal connector line + if (ti %% 2 == 1) + segments(x_cen + bar_height*0.6, pos, x_off, pos, col=col_ti, lwd=0.8, lty=2) + else + segments(x_cen - bar_height*0.6, pos, x_off, pos, col=col_ti, lwd=0.8, lty=2) + # Symbol + points(x_off, pos, pch=pch_ti, col=col_ti, bg=col_ti, + cex=cex_fun(sig$LOD[ri])) + # LOD label for large effects + 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) + } } - markers_html <- paste0(markers_html, - sprintf('
', style, tooltip)) } - # Title with interval sizes in cM - int_sizes_str <- "" - if ("Interval_Size_Mb" %in% colnames(chr_qtls)) { - sizes <- chr_qtls$Interval_Size_Mb[!is.na(chr_qtls$Interval_Size_Mb)] - if (length(sizes) > 0) - int_sizes_str <- paste0( - ' (LOD-1.5: ', - paste(round(sizes, 2), collapse = ", "), ' cM)') - } + # Chromosome label at top + text(x_cen, chr_len + cap_h + chr_len*0.04, paste0("Chr", chr), + cex=0.72, font=2, col="grey20") + } - chr_html <- paste0(chr_html, sprintf(' -
-
- Chromosome %s — %d markers, %d QTLs%s -
-
- %s%s -
-
- %.1f cM - %.1f cM -
-
', - chr, nrow(chr_markers), nrow(chr_qtls), int_sizes_str, - interval_html, markers_html, - min_pos, max_pos)) + # Legend + if (length(trait_names) > 0) { + legend_x <- 0.1 + legend_y <- max_pos * 0.98 + legend(legend_x, legend_y, + 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 = "white", + box.col = "grey70", + title = "Traits/Methods", + title.col = "grey30") } - # Full HTML page — publication style - html_content <- sprintf(' - - - - - QTL Chromosome Map — CIM v5 - - - - - - -
- LEGEND: -
-
- Significant QTL -
-
-
- Flanking marker -
-
-
- LOD-1.5 interval -
-
-
- All markers -
- Hover markers for details -
- -
- PVE_CIM = semi-partial R²  |  - PVE_marker = unconditional R²  |  - Interval = markers within 1.5 LOD of peak  |  - Positions in cM -
- - %s - - - -', - lod_threshold, - format(Sys.time(), "%Y-%m-%d %H:%M"), - chr_html) - - return(html_content) + title(main = paste0("QTL Chromosome Map — LOD ≥ ", lod_threshold, + " | Method: ", paste(unique(unlist(lapply(qtl_list, function(q) + if (!is.null(q) && !"Message" %in% colnames(q) && "Method" %in% colnames(q)) + unique(q$Method) else NULL))), collapse="/")), + cex.main=0.9, font.main=1, col.main="grey20") } # ============================================================ -# API / AI FUNCTIONS +# PLOTLY MANHATTAN — multi-chromosome, proper offsets # ============================================================ -test_api_connection <- function(model_id = default_model) { - if (!token_exists) return(list(success = FALSE, error = "No token found")) - tryCatch({ - response <- POST( - url = HF_API_URL, - add_headers(Authorization = paste("Bearer", HF_API_TOKEN), "Content-Type" = "application/json"), - body = toJSON(list(model = model_id, messages = list(list(role = "user", content = "Hi")), max_tokens = 10L), auto_unbox = TRUE), - encode = "json", timeout(15)) - if (status_code(response) == 200) return(list(success = TRUE)) - err <- tryCatch(content(response, "text", encoding = "UTF-8"), error = function(e) paste("Status:", status_code(response))) - list(success = FALSE, error = paste("Status:", status_code(response), "-", substr(err, 1, 200))) - }, error = function(e) list(success = FALSE, error = e$message)) -} +make_plotly_manhattan <- function(scan_all, lod_threshold=2.0, title="QTL Manhattan Plot") { + blank <- plot_ly() %>% layout(title=title, plot_bgcolor="#FFFFFF", paper_bgcolor="#FFFFFF") + 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) -api_test <- test_api_connection(default_model) -use_hf_api <- token_exists && api_test$success -cat("API Test:", if (api_test$success) "SUCCESS" else paste("FAILED -", api_test$error), "\n") - -query_hf_api <- function(prompt, model_id = default_model, max_length = 500, temperature = 0.7) { - if (!token_exists) return(list(success = FALSE, error = "HF_API_TOKEN not set")) - tryCatch({ - response <- POST( - url = HF_API_URL, - add_headers(Authorization = paste("Bearer", HF_API_TOKEN), "Content-Type" = "application/json"), - body = toJSON(list( - model = model_id, - messages = list( - list(role = "system", content = "You are an expert bioinformatics assistant specializing in QTL analysis using Composite Interval Mapping. Be concise and helpful."), - list(role = "user", content = prompt)), - max_tokens = as.integer(max_length), - temperature = temperature), auto_unbox = TRUE), - encode = "json", timeout(60)) - if (status_code(response) == 200) { - result <- content(response, as = "parsed", encoding = "UTF-8") - return(list(success = TRUE, text = result$choices[[1]]$message$content)) - } - err <- tryCatch(content(response, "text", encoding = "UTF-8"), error = function(e) paste("Status:", status_code(response))) - list(success = FALSE, error = paste("API error:", status_code(response), "-", substr(err, 1, 200))) - }, error = function(e) list(success = FALSE, error = e$message)) -} - -build_system_prompt <- function(rv) { - ctx <- c("CURRENT ANALYSIS RESULTS (Composite Interval Mapping v5):") - if (!is.null(rv$cim_all) && !"Message" %in% colnames(rv$cim_all)) { - sig <- rv$cim_all[rv$cim_all$LOD >= rv$lod_threshold, ] - ctx <- c(ctx, - sprintf("\nCIM Results: %d significant QTLs above LOD %.1f", nrow(sig), rv$lod_threshold), - sprintf("Top PVE_CIM (semi-partial R²): %.1f%%", if (nrow(sig) > 0) max(sig$PVE_CIM_Percent) else 0)) - if (nrow(sig) > 0) { - top3 <- head(sig, 3) - ctx <- c(ctx, "\nTop QTLs:") - for (i in 1:nrow(top3)) { - r <- top3[i, ] - ctx <- c(ctx, sprintf(" %d. %s (Chr %s): LOD=%.2f, PVE_marker=%.1f%%, PVE_CIM=%.1f%%, A=%.3f", - i, r$Marker, r$Chromosome, r$LOD, r$PVE_Marker_Percent, r$PVE_CIM_Percent, r$Additive_Effect)) - } - } - } - paste(ctx, collapse = "\n") -} - -enhanced_rule_response <- function(user_message, rv) { - q <- tolower(trimws(user_message)) - has_cim <- !is.null(rv$cim_all) && !"Message" %in% colnames(rv$cim_all) - has_qtl <- has_cim && any(rv$cim_all$LOD >= rv$lod_threshold) - has_perf <- !is.null(rv$performance_metrics) - - if (grepl("pve|variance explained|partial r2|what is pve|cim|semi.partial|low pve", q)) { - if (has_qtl) { - sig <- rv$cim_all[rv$cim_all$LOD >= rv$lod_threshold, ] - top_pve <- sig[which.max(sig$PVE_CIM_Percent), ] - return(paste0( - "📊 **PVE in CIM v5 — Semi-Partial R² (Fixed)**\n\n", - "**Why PVE was low in v4:**\n", - "• v4 used SS_total (raw) as denominator → marker contribution tiny vs full phenotypic variance\n", - "• With many cofactors, nearly all variance absorbed → partial R² ≈ 0\n\n", - "**v5 Fix — Semi-partial R²:**\n", - "• `PVE_marker (%)` = R² of lm(Y ~ a_code + d_code) × 100 [unconditional]\n", - "• `PVE_CIM (%)` = (RSS_reduced - RSS_full) / RSS_reduced × 100\n", - " Denominator = RESIDUAL SS after cofactors (not raw total)\n", - " = fraction of REMAINING variance explained by focal marker\n\n", - "**Adaptive cofactor cap:** min(K, sqrt(n_samples)) to prevent over-absorption\n\n", - "**Top QTL:** ", top_pve$Marker, " (Chr ", top_pve$Chromosome, ")\n", - "• LOD: ", round(top_pve$LOD, 2), "\n", - "• PVE_marker: ", round(top_pve$PVE_Marker_Percent, 1), "%\n", - "• PVE_CIM (semi-partial R²): ", round(top_pve$PVE_CIM_Percent, 1), "%\n", - "• Additive effect (-1/0/+1): ", round(top_pve$Additive_Effect, 3) - )) - } - return("Run CIM analysis first to see PVE values. v5 fixes the low-PVE issue using semi-partial R².") - } + pd$Chromosome <- as.character(pd$Chromosome) + chroms <- sort(unique(pd$Chromosome), method="radix") - if (grepl("interval|region|support|lod drop|flanking|boundary", q)) { - if (has_qtl) { - sig <- rv$cim_all[rv$cim_all$LOD >= rv$lod_threshold, ] - qtl_table <- rv$qtl_effects_train - out <- "🎯 **QTL Support Intervals (LOD-1.5 drop)**\n\nInterval = markers within 1.5 LOD of peak\nRef: Lander & Botstein (1989) Genetics\n\n" - if (!is.null(qtl_table) && !"Message" %in% colnames(qtl_table)) { - for (i in 1:min(5, nrow(qtl_table))) { - r <- qtl_table[i, ] - size_mb <- if (!is.na(r$Interval_Size_Mb)) paste0(round(r$Interval_Size_Mb, 2), " Mb") else "N/A" - out <- paste0(out, r$Marker, " (Chr ", r$Chromosome, ")\n", - " Interval: ", format(r$Interval_Start, big.mark=","), " — ", format(r$Interval_End, big.mark=","), " bp (", size_mb, ")\n", - " Flanking: [", r$Low_Flank, "] ← QTL → [", r$High_Flank, "]\n\n") - } - } - return(out) - } - return("Run analysis first to see support intervals.") + # Build cumulative offsets + offsets <- numeric(length(chroms)); names(offsets) <- chroms + for (i in seq_along(chroms)) { + if (i==1) { offsets[chroms[1]] <- 0; next } + prev_max <- max(pd$Position[pd$Chromosome==chroms[i-1]], na.rm=TRUE) + offsets[chroms[i]] <- offsets[chroms[i-1]] + prev_max * 1.05 } - if (grepl("top qtl|best qtl|highest lod|significant qtl|list qtl|show qtl", q)) { - if (has_qtl) { - sig <- rv$cim_all[rv$cim_all$LOD >= rv$lod_threshold, ] - top5 <- head(sig, 5) - out <- "🎯 **Top QTLs by LOD (CIM v5)**\n\n" - for (i in 1:nrow(top5)) { - r <- top5[i, ] - out <- paste0(out, i, ". **", r$Marker, "** (Chr ", r$Chromosome, ")\n", - " • LOD: **", round(r$LOD, 2), "**\n", - " • PVE_marker: ", round(r$PVE_Marker_Percent, 1), "% | PVE_CIM: ", round(r$PVE_CIM_Percent, 1), "%\n", - " • Additive: ", round(r$Additive_Effect, 3), "\n\n") - } - return(out) - } - return("No significant QTLs detected. Try lowering the LOD threshold.") - } + 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) + chr_colors <- rep(c("#1D4ED8","#64748B"), ceiling(length(chroms)/2))[seq_along(chroms)] + names(chr_colors) <- chroms - if (grepl("model performance|r2|r squared|validation|negative r2", q) && has_perf) { - pm <- rv$performance_metrics - val_r2 <- pm$Value[pm$Metric == "R² (Validation)"] - out <- paste0("📈 **Model Performance**\n\n• Training R²: ", round(pm$Value[pm$Metric == "R² (Train)"], 3), - "\n• Validation R²: **", round(val_r2, 3), "**\n\n") - if (val_r2 < 0) out <- paste0(out, "⚠️ Negative validation R² — overfitting or small sample.\nTry fewer cofactors or larger dataset.") - else if (val_r2 >= 0.5) out <- paste0(out, "🎯 Excellent validation R²!") - return(out) + cat("MANHATTAN: chroms =", paste(chroms, collapse=","), "| sig =", sum(pd$sig, na.rm=TRUE), "\n") + + 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=5, color=chr_colors[ch], opacity=0.75), + text=~paste0("Marker: ",Marker,"
Chr: ",Chromosome,"
Pos: ",round(Position,1)," cM
LOD: ",round(LOD,2),"
PVE: ",round(PVE_Marker_Percent,1),"%"), + hoverinfo="text", showlegend=FALSE) } - - paste0("👋 Vanakam! TerraByte-AI (CIM v5 — PVE fixed)\n\n", - "Key fixes in v5:\n", - "• PVE_CIM now uses semi-partial R² (denominator = residual SS after cofactors)\n", - "• PVE_marker = unconditional R² of marker-only model\n", - "• Adaptive cofactor count = min(K, √n) to prevent over-absorption\n", - "• Chromosome viz is now downloadable as HTML (same as on-screen)\n", - "• Predicted test phenotype download is now available\n\n", - "Ask about: **PVE / low PVE** | **Intervals** | **Top QTLs** | **Performance**\n\n", - "Contact: ashmithamganesan@gmail.com, P.sinha@cgiar.org") + # Significant markers + 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=9, color="#DC2626", symbol="diamond"), + text=~paste0("",Marker,"
Chr: ",Chromosome,"
LOD: ",round(LOD,2),"
PVE_marker: ",round(PVE_Marker_Percent,1),"%"), + hoverinfo="text") + + # Threshold line + p <- 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="#DC2626",dash="dash",width=1.5), + showlegend=FALSE) %>% + layout( + title=list(text=paste0(title," | ",sum(pd$sig,na.rm=TRUE)," sig. QTL(s)"), + font=list(size=14,color="#1E293B")), + xaxis=list(title="Chromosome", tickvals=as.list(chr_mids[chroms]), + ticktext=as.list(paste0("Chr",chroms)), + tickangle=45, gridcolor="#F1F5F9", color="#475569"), + yaxis=list(title="LOD Score", gridcolor="#F1F5F9", color="#475569", + zeroline=FALSE), + plot_bgcolor="#FFFFFF", paper_bgcolor="#FFFFFF", + font=list(color="#475569"), + legend=list(orientation="h",y=-0.15)) + return(p) } -generate_ai_response <- function(user_message, rv, model_id = default_model) { - if (token_exists) { - context <- build_system_prompt(rv) - prompt <- paste("CONTEXT:", context, "\n\nUSER:", user_message, - "\n\nAnswer specifically using the context above. Be concise.") - result <- query_hf_api(prompt, model_id = model_id) - if (result$success) return(result$text) - } - enhanced_rule_response(user_message, rv) +# ============================================================ +# API +# ============================================================ +query_ai <- function(prompt, model_id=default_model_ai) { + if (!token_exists) return(list(success=FALSE, error="No token")) + tryCatch({ + res <- httr::POST(HF_API_URL, + httr::add_headers(Authorization=paste("Bearer",HF_API_TOKEN), "Content-Type"="application/json"), + body=jsonlite::toJSON(list(model=model_id, + messages=list(list(role="system",content="Expert QTL/bioinformatics assistant."), + list(role="user",content=prompt)), + max_tokens=600L, temperature=0.7), auto_unbox=TRUE), + encode="json", httr::timeout(45)) + if (httr::status_code(res)==200) { + r <- httr::content(res,as="parsed",encoding="UTF-8") + return(list(success=TRUE, text=r$choices[[1]]$message$content)) + } + list(success=FALSE, error=paste("HTTP",httr::status_code(res))) + }, error=function(e) list(success=FALSE, error=e$message)) } # ============================================================ @@ -808,406 +702,341 @@ generate_ai_response <- function(user_message, rv, model_id = default_model) { ui <- fluidPage( shinyjs::useShinyjs(), tags$head( - tags$link(rel = "stylesheet", href = "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css"), - tags$link(rel = "stylesheet", href = "https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;600&family=IBM+Plex+Sans:wght@300;400;500;600&display=swap"), + tags$link(rel="stylesheet", + href="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;600&family=IBM+Plex+Sans:wght@300;400;500;600&display=swap"), + tags$link(rel="stylesheet", + href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css"), tags$script(HTML(" - function simulateQTLDiscovery() { - setTimeout(function() { - const markers = document.querySelectorAll('.chromosome-marker'); - let delay = 0; - markers.forEach(function(marker) { - setTimeout(function() { - marker.classList.add('highlighted'); - setTimeout(function() { marker.classList.add('pulse'); }, 300); - }, delay); - delay += 100; - }); - }, 100); - } - function resetAnimation() { - const markers = document.querySelectorAll('.chromosome-marker'); - markers.forEach(function(marker) { - marker.classList.remove('highlighted', 'pulse'); - }); - } - Shiny.addCustomMessageHandler('simulateQTLDiscovery', function(m) { simulateQTLDiscovery(); }); - Shiny.addCustomMessageHandler('resetAnimation', function(m) { resetAnimation(); }); - Shiny.addCustomMessageHandler('scrollChatBottom', function(m) { - setTimeout(function() { - var cb = document.getElementById('chat_messages'); - if (cb) cb.scrollTop = cb.scrollHeight; - }, 100); + $(document).on('keydown','#chat_input',function(e){ + if(e.key==='Enter'&&!e.shiftKey){e.preventDefault();$('#send_chat').click();} }); - $(document).on('keydown', '#chat_input', function(e) { - if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); $('#send_chat').click(); } + Shiny.addCustomMessageHandler('scrollChat',function(m){ + setTimeout(function(){var c=document.getElementById('chat_msgs');if(c)c.scrollTop=c.scrollHeight;},80); }); ")), tags$style(HTML(" - :root { - --bg-primary:#FFFFFF; --bg-secondary:#F8FAFC; --bg-tertiary:#F1F5F9; - --border:#E2E8F0; --text-primary:#1E293B; --text-secondary:#475569; - --text-muted:#94A3B8; --accent:#1D4ED8; --accent-hover:#1E40AF; - --success:#15803D; --warning:#B45309; --danger:#DC2626; - --purple:#7C3AED; --teal:#0F766E; - --font-mono:'IBM Plex Mono',monospace; --font-sans:'IBM Plex Sans',sans-serif; + :root{ + --bg:#F8FAFC;--card:#FFFFFF;--border:#E2E8F0; + --txt:#1E293B;--muted:#64748B;--accent:#1D4ED8; + --green:#15803D;--red:#DC2626;--orange:#C05621; + --mono:'IBM Plex Mono',monospace;--sans:'IBM Plex Sans',sans-serif; } - *{box-sizing:border-box;margin:0;padding:0;} - body{font-family:var(--font-sans);background:var(--bg-primary);color:var(--text-primary);font-size:14px;} - .navbar{background:#FFFFFF!important;border-bottom:2px solid var(--accent)!important;box-shadow:0 1px 4px rgba(0,0,0,.08);} - .navbar-brand{color:var(--accent)!important;font-family:var(--font-mono);font-weight:600;} - .navbar-nav>li>a{color:var(--text-secondary)!important;font-size:13px;} - .navbar-nav>li.active>a,.navbar-nav>li>a:hover{color:var(--accent)!important;background:transparent!important;} - .main-header{background:linear-gradient(135deg,#EFF6FF,#DBEAFE);border:1px solid #BFDBFE;border-left:4px solid var(--accent);padding:20px 24px;border-radius:8px;margin-bottom:20px;} - .main-header h2{font-family:var(--font-mono);font-size:1.2rem;font-weight:600;color:var(--accent);} - .main-header p{color:var(--text-secondary);margin-top:6px;font-size:13px;} - .cim-box{background:#F0FDF4;border:1px solid #86EFAC;border-left:3px solid var(--success);border-radius:6px;padding:12px 16px;margin:10px 0;font-family:var(--font-mono);font-size:12px;color:#166534;} - .cim-box .box-title{font-weight:600;color:var(--success);margin-bottom:6px;} - .fix-box{background:#FEF3C7;border:1px solid #FCD34D;border-left:3px solid var(--warning);border-radius:6px;padding:12px 16px;margin:10px 0;font-family:var(--font-mono);font-size:12px;color:#92400E;} - .card{background:var(--bg-secondary);border:1px solid var(--border);border-radius:8px;margin-bottom:20px;box-shadow:0 1px 3px rgba(0,0,0,.05);} - .card-header{background:var(--bg-tertiary);border-bottom:1px solid var(--border);padding:12px 16px;font-family:var(--font-mono);font-size:11px;color:var(--text-secondary);letter-spacing:.5px;text-transform:uppercase;border-radius:8px 8px 0 0;} - .card-body{padding:16px;} - .form-control,.selectize-input{background:#FFFFFF!important;border:1px solid var(--border)!important;color:var(--text-primary)!important;border-radius:4px;font-size:13px;} - .form-control:focus{border-color:var(--accent)!important;box-shadow:0 0 0 2px rgba(29,78,216,.15)!important;} - label{color:var(--text-secondary);font-size:12px;margin-bottom:4px;} - .btn{border-radius:4px;font-family:var(--font-mono);font-size:12px;font-weight:600;transition:all .15s;border:1px solid;} - .btn-primary{background:var(--accent);border-color:var(--accent);color:#FFFFFF;} - .btn-primary:hover{background:var(--accent-hover);border-color:var(--accent-hover);color:#FFFFFF;} - .btn-info{background:transparent;border-color:var(--teal);color:var(--teal);} - .btn-info:hover{background:var(--teal);color:white;} - .btn-danger{background:transparent;border-color:var(--danger);color:var(--danger);} - .btn-danger:hover{background:var(--danger);color:white;} - .btn-success{background:var(--success);border-color:var(--success);color:white;} - .help-block{color:var(--text-muted);font-size:11px;margin-top:4px;} - .dataTables_wrapper{color:var(--text-secondary)!important;} - table.dataTable{background:#FFFFFF!important;color:var(--text-primary)!important;border-color:var(--border)!important;} - table.dataTable thead th{background:var(--bg-tertiary)!important;color:var(--text-secondary)!important;border-bottom:1px solid var(--border)!important;font-family:var(--font-mono);font-size:11px;letter-spacing:.5px;} + *{box-sizing:border-box;} + body{font-family:var(--sans);background:var(--bg);color:var(--txt);font-size:14px;margin:0;} + .navbar{background:#FFF!important;border-bottom:2px solid var(--accent)!important;} + .navbar-brand{font-family:var(--mono);font-weight:600;color:var(--accent)!important;} + .navbar-nav>li>a{color:var(--muted)!important;font-size:13px;} + .navbar-nav>li.active>a{color:var(--accent)!important;background:transparent!important;} + .card{background:var(--card);border:1px solid var(--border);border-radius:8px;margin-bottom:16px;} + .card-hd{background:#F1F5F9;border-bottom:1px solid var(--border);padding:10px 14px; + font-family:var(--mono);font-size:11px;color:var(--muted);letter-spacing:.5px; + text-transform:uppercase;border-radius:8px 8px 0 0;font-weight:600;} + .card-bd{padding:14px;} + .info-box{background:#EFF6FF;border:1px solid #BFDBFE;border-left:3px solid var(--accent); + border-radius:6px;padding:10px 14px;margin:8px 0;font-size:12px;color:#1E40AF;font-family:var(--mono);} + .warn-box{background:#FEF9C3;border:1px solid #FDE047;border-left:3px solid #CA8A04; + border-radius:6px;padding:10px 14px;margin:8px 0;font-size:12px;color:#713F12;font-family:var(--mono);} + .btn{border-radius:4px;font-family:var(--mono);font-size:12px;font-weight:600;border:1px solid;} + .btn-primary{background:var(--accent);border-color:var(--accent);color:#FFF;} + .btn-primary:hover{background:#1E40AF;color:#FFF;} + .btn-success{background:var(--green);border-color:var(--green);color:#FFF;} + .btn-info{background:transparent;border-color:#0F766E;color:#0F766E;} + .btn-info:hover{background:#0F766E;color:#FFF;} + .btn-warning{background:transparent;border-color:var(--orange);color:var(--orange);} + .btn-warning:hover{background:var(--orange);color:#FFF;} + .form-control,.selectize-input{background:#FFF!important;border:1px solid var(--border)!important; + color:var(--txt)!important;font-size:13px;border-radius:4px;} + label{font-size:12px;color:var(--muted);} + .model-badge{display:inline-block;background:#EFF6FF;border:1px solid #BFDBFE; + border-radius:12px;padding:2px 10px;font-size:11px;font-family:var(--mono); + color:var(--accent);margin-right:6px;} + .chr-legend{display:flex;gap:14px;flex-wrap:wrap;padding:6px 0;font-size:11px;align-items:center;} + .leg-dot{width:10px;height:10px;border-radius:2px;display:inline-block;margin-right:4px;} + /* Floating chat */ + #chat-panel{position:fixed;bottom:16px;right:16px;z-index:9999;width:420px;display:flex;flex-direction:column;} + #chat-toggle{align-self:flex-end;width:52px;height:52px;border-radius:50%; + background:linear-gradient(135deg,var(--accent),#7C3AED);border:none;cursor:pointer; + display:flex;align-items:center;justify-content:center;color:#FFF;font-size:22px; + box-shadow:0 4px 16px rgba(29,78,216,.35);} + #chat-win{display:none;flex-direction:column;background:#FFF;border:1px solid #BFDBFE; + border-radius:12px;margin-bottom:10px;height:560px;overflow:hidden; + box-shadow:0 8px 32px rgba(0,0,0,.12);} + #chat-win.open{display:flex;} + #chat-hd{background:linear-gradient(135deg,#EFF6FF,#DBEAFE);border-bottom:1px solid #BFDBFE; + padding:10px 14px;display:flex;justify-content:space-between;align-items:center;} + #chat-hd h4{margin:0;font-family:var(--mono);font-size:13px;font-weight:600;} + #chat-close{background:none;border:none;color:var(--muted);cursor:pointer;font-size:18px;} + #chat_msgs{flex:1;overflow-y:auto;padding:14px;display:flex;flex-direction:column;gap:10px;background:#F8FAFC;} + .cmsg{max-width:90%;} + .cmsg.user{align-self:flex-end;} + .cmsg.assistant{align-self:flex-start;} + .cbub{padding:10px 14px;border-radius:14px;font-size:13px;line-height:1.55;white-space:pre-wrap;word-break:break-word;} + .cmsg.user .cbub{background:linear-gradient(135deg,var(--accent),#1E40AF);color:#FFF;border-bottom-right-radius:4px;} + .cmsg.assistant .cbub{background:#FFF;border:1px solid var(--border);border-bottom-left-radius:4px;} + .cmeta{font-size:10px;color:var(--muted);margin-top:3px;font-family:var(--mono);} + .typing{display:flex;gap:4px;padding:10px 14px;background:#FFF;border:1px solid var(--border); + border-radius:14px;width:fit-content;} + .tdot{width:7px;height:7px;background:#94A3B8;border-radius:50%;animation:tb 1.4s infinite;} + .tdot:nth-child(2){animation-delay:.2s;}.tdot:nth-child(3){animation-delay:.4s;} + @keyframes tb{0%,60%,100%{transform:translateY(0);}30%{transform:translateY(-7px);}} + .qq{padding:6px 12px;display:flex;flex-wrap:wrap;gap:5px;border-bottom:1px solid var(--border);background:#FFF;} + .qqb{background:#EFF6FF;border:1px solid #BFDBFE;color:var(--accent);border-radius:12px; + padding:3px 10px;font-size:11px;cursor:pointer;} + .qqb:hover{background:var(--accent);color:#FFF;} + #chat-ft{padding:10px 14px;border-top:1px solid var(--border);background:#FFF;} + #chat_input{width:100%;background:#F8FAFC!important;border:1px solid var(--border)!important; + border-radius:6px;font-size:13px;resize:none;padding:8px 10px;margin-bottom:7px;font-family:var(--sans);} + .chat-acts{display:flex;gap:8px;} + #send_chat{flex:1;background:linear-gradient(135deg,var(--accent),#1E40AF);color:#FFF;border:none; + border-radius:5px;padding:7px 14px;font-family:var(--mono);font-size:12px;font-weight:600;cursor:pointer;} + #clear_chat{background:transparent;color:var(--muted);border:1px solid var(--border); + border-radius:5px;padding:7px 10px;font-family:var(--mono);font-size:12px;cursor:pointer;} + /* DT tables */ + table.dataTable{background:#FFF!important;color:var(--txt)!important;} + table.dataTable thead th{background:#F1F5F9!important;font-family:var(--mono);font-size:11px;} table.dataTable tbody tr:hover{background:#EFF6FF!important;} - table.dataTable tbody td{border-bottom:1px solid var(--border)!important;font-size:12px;} - .dataTables_info,.dataTables_length,.dataTables_filter,.dataTables_paginate{color:var(--text-muted)!important;font-size:12px;} - .dataTables_filter input,.dataTables_length select{background:#FFFFFF!important;border:1px solid var(--border)!important;color:var(--text-primary)!important;border-radius:3px;} - .paginate_button{color:var(--text-secondary)!important;} - .paginate_button.current{background:var(--accent)!important;color:white!important;border-color:var(--accent)!important;} - .chromosome-container{margin:14px 0;padding:14px 18px;background:#FFFFFF;border-radius:8px;border:1px solid #D1D5DB;box-shadow:0 1px 4px rgba(0,0,0,.06);} - .chromosome{height:28px;background:linear-gradient(to right,#E5E7EB,#D1D5DB);border-radius:14px;margin:10px 0;position:relative;overflow:hidden;border:1px solid #9CA3AF;} - .chromosome-marker{position:absolute;height:20px;width:4px;background:#6B7280;border-radius:1px;top:4px;transform:translateX(-50%);transition:all .3s ease;} - .chromosome-marker.significant{background:#C0392B!important;height:22px!important;width:7px!important;top:3px!important;box-shadow:0 0 5px rgba(192,57,43,.5);} - .chromosome-marker.flanking{background:#2166AC!important;height:20px!important;width:4px!important;top:4px!important;} - .chromosome-marker.selection{background:#1A7A4A!important;} - .chromosome-marker.interval{background:#E67E22!important;height:18px!important;width:3px!important;top:5px!important;opacity:.8;} - .chromosome-marker.highlighted{background:#8E44AD!important;box-shadow:0 0 8px rgba(142,68,173,.5);} - .chromosome-marker.pulse{animation:pulse 1.5s infinite;} - @keyframes pulse{0%,100%{transform:translateX(-50%) scale(1);}50%{transform:translateX(-50%) scale(1.25);opacity:.75;}} - .chromosome-legend{display:flex;justify-content:space-between;font-size:10px;color:#6B7280;font-family:var(--font-mono);margin-top:3px;letter-spacing:0.3px;} - .chromosome-title{font-family:var(--font-mono);font-size:11px;color:#1F3A6E;margin-bottom:4px;font-weight:600;} - .interval-band{position:absolute;top:0;bottom:0;background:rgba(192,57,43,.13);border-left:1px solid rgba(192,57,43,.35);border-right:1px solid rgba(192,57,43,.35);} - .chr-legend{display:flex;gap:16px;padding:8px 0;font-size:11px;flex-wrap:wrap;} - .legend-item{display:flex;align-items:center;gap:5px;color:var(--text-secondary);} - .legend-dot{width:10px;height:10px;border-radius:2px;} - #chat-panel{position:fixed;bottom:20px;right:20px;z-index:9999;width:440px;display:flex;flex-direction:column;} - #chat-toggle-btn{align-self:flex-end;width:56px;height:56px;border-radius:50%;background:linear-gradient(135deg,var(--accent),var(--purple));border:none;cursor:pointer;display:flex;align-items:center;justify-content:center;box-shadow:0 4px 20px rgba(29,78,216,.3);transition:all .2s;color:white;font-size:24px;} - #chat-toggle-btn:hover{transform:scale(1.05);} - #chat-window{display:none;flex-direction:column;background:#FFFFFF;border:1px solid #BFDBFE;border-radius:12px;overflow:hidden;box-shadow:0 8px 40px rgba(0,0,0,.12);margin-bottom:10px;height:640px;} - #chat-window.open{display:flex;} - #chat-header{background:linear-gradient(135deg,#EFF6FF,#DBEAFE);border-bottom:1px solid #BFDBFE;padding:12px 16px;display:flex;flex-direction:column;gap:8px;} - .chat-header-top{display:flex;align-items:center;justify-content:space-between;} - .chat-title{display:flex;align-items:center;gap:10px;} - .chat-avatar{width:32px;height:32px;background:linear-gradient(135deg,var(--accent),var(--purple));border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:16px;color:white;font-weight:bold;flex-shrink:0;} - #chat-header h4{font-family:var(--font-mono);font-size:13px;font-weight:600;color:var(--text-primary);margin:0;} - #chat-header p{font-size:11px;color:var(--text-muted);margin:0;} - #chat-header p.ai-mode{color:var(--success);} - #chat-close-btn{background:none;border:none;color:var(--text-muted);cursor:pointer;font-size:18px;padding:4px;transition:color .15s;} - #chat-close-btn:hover{color:var(--text-primary);} - .chat-model-selector{display:flex;align-items:center;gap:8px;padding:4px 0;} - .chat-model-selector label{color:var(--text-muted);font-size:10px;font-family:var(--font-mono);white-space:nowrap;margin:0;} - .chat-model-selector select{flex:1;background:#FFFFFF!important;border:1px solid var(--border)!important;color:var(--text-secondary)!important;border-radius:4px;font-size:11px;font-family:var(--font-mono);padding:3px 6px;} - .model-status-dot{width:7px;height:7px;border-radius:50%;flex-shrink:0;} - .model-status-dot.online{background:var(--success);box-shadow:0 0 6px var(--success);} - .model-status-dot.offline{background:var(--warning);box-shadow:0 0 6px var(--warning);} - .test-model-btn{background:transparent;border:1px solid var(--border);color:var(--text-muted);border-radius:3px;padding:2px 7px;font-size:10px;font-family:var(--font-mono);cursor:pointer;transition:all .15s;white-space:nowrap;} - .test-model-btn:hover{border-color:var(--accent);color:var(--accent);} - #chat_messages{flex:1;overflow-y:auto;padding:16px;display:flex;flex-direction:column;gap:12px;background:#F8FAFC;} - .chat-msg{max-width:92%;animation:fadeIn .3s ease;} - @keyframes fadeIn{from{opacity:0;transform:translateY(10px);}to{opacity:1;transform:translateY(0);}} - .chat-msg.user{align-self:flex-end;} - .chat-msg.assistant{align-self:flex-start;} - .chat-bubble{padding:12px 16px;border-radius:16px;font-size:13px;line-height:1.6;word-wrap:break-word;white-space:pre-wrap;} - .chat-msg.user .chat-bubble{background:linear-gradient(135deg,var(--accent),#1E40AF);color:white;border-bottom-right-radius:4px;} - .chat-msg.assistant .chat-bubble{background:#FFFFFF;color:var(--text-primary);border:1px solid var(--border);border-bottom-left-radius:4px;} - .chat-bubble strong{color:var(--accent);} - .chat-meta{font-size:10px;color:var(--text-muted);margin-top:4px;font-family:var(--font-mono);padding:0 4px;display:flex;align-items:center;gap:6px;} - .chat-meta .model-tag{color:var(--purple);font-size:9px;} - .typing-indicator{display:flex;gap:4px;padding:12px 16px;background:#FFFFFF;border:1px solid var(--border);border-radius:16px;border-bottom-left-radius:4px;width:fit-content;} - .typing-dot{width:8px;height:8px;background:#94A3B8;border-radius:50%;animation:typingBounce 1.4s infinite;} - .typing-dot:nth-child(2){animation-delay:.2s;} - .typing-dot:nth-child(3){animation-delay:.4s;} - @keyframes typingBounce{0%,60%,100%{transform:translateY(0);}30%{transform:translateY(-8px);}} - .quick-questions{padding:8px 16px;display:flex;flex-wrap:wrap;gap:6px;border-bottom:1px solid var(--border);background:#FFFFFF;} - .quick-q-btn{background:#EFF6FF;border:1px solid #BFDBFE;color:var(--accent);border-radius:16px;padding:4px 12px;font-size:11px;cursor:pointer;transition:all .15s;} - .quick-q-btn:hover{background:var(--accent);color:white;} - #chat-footer{padding:12px 16px;border-top:1px solid var(--border);background:#FFFFFF;} - #chat_input{width:100%;background:#F8FAFC!important;border:1px solid var(--border)!important;border-radius:8px;color:var(--text-primary)!important;font-size:13px;resize:none;padding:10px 12px;font-family:var(--font-sans);margin-bottom:8px;} - #chat_input:focus{border-color:var(--accent)!important;outline:none;} - .chat-actions{display:flex;gap:8px;} - #send_chat{flex:1;background:linear-gradient(135deg,var(--accent),#1E40AF);color:white;border:none;border-radius:6px;padding:8px 16px;font-family:var(--font-mono);font-size:12px;font-weight:600;cursor:pointer;transition:all .15s;display:flex;align-items:center;justify-content:center;gap:6px;} - #send_chat:hover:not(:disabled){transform:translateY(-1px);box-shadow:0 4px 12px rgba(29,78,216,.3);} - #send_chat:disabled{opacity:.5;cursor:not-allowed;} - #clear_chat{background:transparent;color:var(--text-muted);border:1px solid var(--border);border-radius:6px;padding:8px 12px;font-family:var(--font-mono);font-size:12px;cursor:pointer;transition:all .15s;} - #clear_chat:hover{border-color:var(--danger);color:var(--danger);} - .download-bar{background:#EFF6FF;border:1px solid #BFDBFE;border-radius:6px;padding:10px 14px;margin-bottom:12px;display:flex;gap:10px;align-items:center;flex-wrap:wrap;} - .download-bar span{font-size:12px;color:var(--text-secondary);font-family:var(--font-mono);} + table.dataTable tbody td{font-size:12px;} ")) ), navbarPage( - title = tags$span(tags$i(class = "fas fa-dna", style = "margin-right:8px;color:#1D4ED8;"), "QTL-Mapper CIM v5"), - id = "nav", - - # ---- DATA UPLOAD ---- - tabPanel("Data Upload", icon = icon("upload"), - div(class = "main-header", - h2(tags$i(class = "fas fa-upload", style = "margin-right:8px;"), "Data Upload — CIM v5"), - p("Semi-partial R² PVE | -1/0/+1 coding | LOD-1.5 intervals | downloadable chromosome viz (HTML) | predicted test phenotype download") - ), + title = tags$span(tags$i(class="fas fa-dna",style="color:#1D4ED8;margin-right:6px;"), "QTL-Mapper v6"), + id = "nav", + + # ─── DATA UPLOAD ─────────────────────────────────────────── + tabPanel("Data Upload", icon=icon("upload"), fluidRow(column(12, - div(class = "cim-box", - div(class = "box-title", tags$i(class = "fas fa-check-circle", style = "margin-right:6px;"), "CIM v5 — PVE Formula Fix + New Downloads"), - tags$pre(style = "background:transparent;border:none;margin:0;color:#166534;font-size:11px;", - "WHY PVE WAS LOW IN v4:\n", - " Partial R² = (RSS_reduced - RSS_full) / SS_total_raw\n", - " When cofactors explain 90% of variance: SS_total = 1000, SS_marker_given_cofactors = 20\n", - " PVE_CIM = 20/1000 = 2% ← tiny despite real effect!\n\n", - "v5 FIX — Semi-partial R² (denominator = residual SS after cofactors):\n", - " SS_denom = RSS_reduced = residual SS after cofactors alone\n", - " PVE_CIM = (RSS_reduced - RSS_full) / RSS_reduced × 100\n", - " Same example: 20/100 = 20% ← fraction of REMAINING variance explained\n\n", - "NEW IN THIS BUILD:\n", - " 1. Chromosome viz downloads as HTML — pixel-identical to on-screen display\n", - " 2. Predicted test phenotype download button added to Test Data card") + div(class="info-box", + tags$b("QTL-Mapper v6 — Multi-Model, Multi-Chromosome"), + tags$br(), + "Format: Row1=header (id,marker1,...), Row2=chromosomes, Row3=positions (cM), rows4+=samples. Genotypes coded 0/1/2." ) )), fluidRow( column(4, - div(class = "card", - div(class = "card-header", tags$i(class = "fas fa-table", style = "margin-right:6px;"), "Training Data"), - div(class = "card-body", - fileInput("genotype_file", "Training Genotype CSV", accept = ".csv", buttonLabel = "Browse"), - helpText("Row1=header(id,markers), Row2=chromosomes, Row3=positions, rest=samples. Coded 0/1/2."), - fileInput("phenotype_file", "Training Phenotype CSV", accept = ".csv", buttonLabel = "Browse"), - helpText("id column + numeric trait columns."), - selectInput("phenotype_column", "Select Phenotype Column", choices = NULL) + div(class="card", + div(class="card-hd",tags$i(class="fas fa-table",style="margin-right:5px;"),"Training Data"), + div(class="card-bd", + fileInput("geno_file","Training Genotype CSV",accept=".csv"), + fileInput("pheno_file","Training Phenotype CSV",accept=".csv"), + selectInput("pheno_col","Select Trait/Phenotype",choices=NULL), + tags$hr(), + 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-header", tags$i(class = "fas fa-sliders-h", style = "margin-right:6px;color:#7C3AED;"), "CIM Parameters"), - div(class = "card-body", - sliderInput("test_size", "Validation Proportion", min = 0.1, max = 0.5, value = 0.2, step = 0.05), - numericInput("lod_threshold","LOD Threshold", value = 2.0, min = 0.5, max = 10.0, step = 0.1), - numericInput("n_cofactors", "CIM Cofactors (K)", value = 10, min = 1, max = 30, step = 1), - helpText("Actual cofactors used = min(K, √n_samples) — adaptive to prevent over-absorption"), - 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), - helpText("LOD-1.5 is the standard QTL confidence interval width"), - actionButton("run_analysis", "Run CIM Analysis", class = "btn-primary btn-block", icon = icon("play")) + div(class="card", + div(class="card-hd",tags$i(class="fas fa-sliders-h",style="margin-right:5px;color:#7C3AED;"),"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), + 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("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:8px;width:100%;") ) ) ), column(4, - div(class = "card", - div(class = "card-header", tags$i(class = "fas fa-vial", style = "margin-right:6px;color:#15803D;"), "Test Data (Optional)"), - div(class = "card-body", - fileInput("test_genotype_file", "Test Genotype CSV", accept = ".csv", buttonLabel = "Browse"), - helpText("Same format as training genotype."), - tags$br(), - fileInput("pop_file", "Population Metadata CSV", accept = ".csv", buttonLabel = "Browse"), - helpText("Columns: id, population (e.g. Domesticated/Wild)."), - actionButton("predict_test_phenotype", "Predict Test Phenotypes", class = "btn-info btn-block", icon = icon("magic")), - tags$br(), - # ── FIX: Added predicted test phenotype download button ── - downloadButton("download_predicted_test", "Download Predicted Phenotypes (.xlsx)", - class = "btn btn-success btn-block", - style = "width:100%;margin-top:8px;") + div(class="card", + div(class="card-hd",tags$i(class="fas fa-info-circle",style="margin-right:5px;"),"Dataset Info"), + div(class="card-bd", uiOutput("dataset_info_ui")) + ), + div(class="card", + div(class="card-hd","Predict Test Phenotypes"), + div(class="card-bd", + actionButton("pred_btn","Predict Test",class="btn btn-info btn-block"), + tags$br(),tags$br(), + downloadButton("dl_pred","Download Predicted (.xlsx)",class="btn btn-success btn-block", + style="width:100%;") ) ) ) ), fluidRow(column(12, - div(class = "card", - div(class = "card-header", "Data Preview"), - div(class = "card-body", + div(class="card", + div(class="card-hd","Data Preview"), + div(class="card-bd", tabsetPanel( - tabPanel("Training Genotype", DTOutput("geno_preview")), - tabPanel("Training Phenotype", DTOutput("pheno_preview")), - tabPanel("Test Genotype", DTOutput("test_geno_preview")), - tabPanel("Predicted Test Phenotype", DTOutput("predicted_test_pheno_preview")) + tabPanel("Training Genotype", DTOutput("prev_geno")), + tabPanel("Training Phenotype", DTOutput("prev_pheno")), + tabPanel("Test Genotype", DTOutput("prev_test_geno")), + tabPanel("Predicted Phenotype", DTOutput("prev_pred")) ) ) ) )) ), - # ---- RESULTS ---- - tabPanel("Results", icon = icon("chart-line"), - div(class = "main-header", - h2(tags$i(class = "fas fa-chart-line", style = "margin-right:8px;"), "CIM Results v5"), - p("Semi-partial R² PVE (fixed) | LOD-1.5 intervals | -1/0/+1 additive coding | downloadable plots") - ), + # ─── RESULTS ─────────────────────────────────────────────── + tabPanel("Results", icon=icon("chart-line"), fluidRow(column(12, - div(class = "download-bar", - tags$span(tags$i(class = "fas fa-download"), " Download:"), - downloadButton("download_manhattan_plot", "Manhattan Plot (.png)", class = "btn btn-primary"), - # ── FIX: Changed label from .png to .html — now exports HTML matching on-screen ── - downloadButton("download_chromosome_plot", "Chromosome Map (.html)", class = "btn btn-info"), - downloadButton("download_train_results", "CIM Results (.xlsx)", class = "btn btn-success") + div(style="display:flex;gap:10px;flex-wrap:wrap;margin-bottom:12px;", + downloadButton("dl_manhattan","Manhattan (.png)",class="btn btn-primary"), + downloadButton("dl_idiogram","Chromosome Map (.png)",class="btn btn-info"), + downloadButton("dl_results","QTL Results (.xlsx)",class="btn btn-success") ) )), fluidRow( - column(6, div(class = "card", div(class = "card-header", "CIM Manhattan Plot (LOD Scores)"), div(class = "card-body", plotlyOutput("lod_plot_2d", height = "500px")))), - column(6, div(class = "card", - div(class = "card-header", "Chromosome Visualization — LOD-1.5 Intervals (download .html = same as this)"), - div(class = "card-body", - div(class = "chr-legend", - div(class = "legend-item", div(class = "legend-dot", style = "background:#C0392B;"), "Significant QTL"), - div(class = "legend-item", div(class = "legend-dot", style = "background:#2166AC;"), "Flanking marker"), - div(class = "legend-item", div(class = "legend-dot", style = "background:rgba(192,57,43,0.18);border:1px solid rgba(192,57,43,0.4);"), "LOD-1.5 interval"), - div(class = "legend-item", div(class = "legend-dot", style = "background:#6B7280;"), "All markers") - ), - uiOutput("chromosome_viz"), - div(style = "margin:12px 0;display:flex;gap:8px;", - actionButton("simulate_btn", "Simulate Discovery", class = "btn-info"), - actionButton("reset_btn", "Reset", class = "btn-danger") + column(7, + div(class="card", + div(class="card-hd","Manhattan Plot — LOD Scores Across All Chromosomes"), + div(class="card-bd",plotlyOutput("manhattan_plot",height="480px")) + ) + ), + column(5, + div(class="card", + div(class="card-hd","Chromosome Idiogram — QTL Positions (reference-style)"), + div(class="card-bd", + plotOutput("idiogram_plot",height="480px") ) ) - )) + ) ), fluidRow( - column(4, div(class = "card", div(class = "card-header", "Model Performance"), div(class = "card-body", plotlyOutput("performance_plot")))), - column(4, div(class = "card", div(class = "card-header", "Train: Predicted vs Observed"), div(class = "card-body", plotlyOutput("regression_plot_train", height = "300px")))), - column(4, div(class = "card", div(class = "card-header", "Validation: Predicted vs Observed"), div(class = "card-body", plotlyOutput("regression_plot_test", height = "300px")))) + column(4, + div(class="card", + div(class="card-hd","Model Performance"), + div(class="card-bd",plotlyOutput("perf_plot",height="280px")) + ) + ), + column(4, + div(class="card", + div(class="card-hd","Train: 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")) + ) + ) ), fluidRow(column(12, - div(class = "card", - div(class = "card-header", "CIM QTL Table — Semi-Partial R² PVE | LOD-1.5 Intervals | -1/0/+1 Additive"), - div(class = "card-body", - div(style = "background:#FEF9C3;border:1px solid #FDE047;border-radius:4px;padding:8px 12px;margin-bottom:8px;font-size:11px;font-family:'IBM Plex Mono';color:#713F12;", - "PVE_CIM = (RSS_cofactors_only - RSS_with_marker) / RSS_cofactors_only × 100 [% of cofactor-residual variance]", - tags$br(), - "PVE_Marker = R² of lm(Y ~ a_code + d_code) × 100 [% of total variance, unconditional]" - ), - DTOutput("qtl_effects_table_train") - ) + div(class="card", + div(class="card-hd","QTL Effects Table — Significant Markers"), + div(class="card-bd",DTOutput("qtl_table")) ) )), fluidRow(column(12, - div(class = "card", - div(class = "card-header", "Epistasis Analysis"), - div(class = "card-body", - DTOutput("epistasis_table"), - plotlyOutput("epistasis_heatmap", height = "400px") - ) + div(class="card", + div(class="card-hd","Full Genome Scan Results"), + div(class="card-bd",DTOutput("full_scan_table")) ) )) ), - # ---- DOMESTICATION ---- - tabPanel("Domestication", icon = icon("leaf"), - div(class = "main-header", - h2(tags$i(class = "fas fa-leaf", style = "margin-right:8px;"), "Domestication Analysis"), - p("Fst, Tajima's D, nucleotide diversity — needs population metadata") + # ─── COMPARE MODELS ──────────────────────────────────────── + tabPanel("Compare Models", icon=icon("balance-scale"), + fluidRow(column(12, + div(class="card", + div(class="card-hd","Run Multiple Models & Compare"), + div(class="card-bd", + div(class="warn-box","Select models to compare. Each will run a full genome scan and results overlaid on the idiogram."), + checkboxGroupInput("compare_methods","Methods to Compare:", + choices = setNames(names(MAPPING_MODELS), sapply(MAPPING_MODELS,`[[`,"label")), + selected = c("SIM","CIM"), 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 Idiogram"), + div(class="card-bd",plotOutput("compare_idiogram",height="500px")) + ) + ), + column(6, + div(class="card", + div(class="card-hd","QTL Count by Method & Chromosome"), + div(class="card-bd",plotlyOutput("compare_bar",height="500px")) + ) + ) ), + fluidRow(column(12, + div(class="card", + div(class="card-hd","QTL Overlap Across Models"), + div(class="card-bd",DTOutput("compare_table")) + ) + )) + ), + + # ─── DOMESTICATION ────────────────────────────────────────── + tabPanel("Domestication", icon=icon("leaf"), fluidRow( column(4, - div(class = "card", - div(class = "card-header", "Parameters"), - div(class = "card-body", - numericInput("fst_threshold", "Fst Threshold", value = 0.1, min = 0.05, max = 0.5, step = 0.01), - numericInput("tajima_threshold", "Tajima's D Threshold", value = -1, min = -5, max = 0, step = 0.1), - actionButton("run_domestication", "Run Domestication Analysis", class = "btn-primary btn-block", icon = icon("play")) + div(class="card", + div(class="card-hd","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",class="btn btn-primary btn-block") ) ) ), column(8, - div(class = "card", - div(class = "card-header", "Population Data Preview"), - div(class = "card-body", DTOutput("pop_preview")) + div(class="card", + div(class="card-hd","Population Data Preview"), + div(class="card-bd",DTOutput("prev_pop")) ) ) ), fluidRow( - column(6, div(class = "card", div(class = "card-header", "Fst Manhattan Plot"), div(class = "card-body", plotlyOutput("fst_plot", height = "400px")))), - column(6, div(class = "card", div(class = "card-header", "Tajima's D Manhattan Plot"), div(class = "card-body", plotlyOutput("tajima_plot", height = "400px")))) + column(6,div(class="card",div(class="card-hd","Fst Manhattan"), div(class="card-bd",plotlyOutput("fst_plot",height="380px")))), + column(6,div(class="card",div(class="card-hd","Tajima's D Manhattan"),div(class="card-bd",plotlyOutput("tajima_plot",height="380px")))) ), fluidRow(column(12, - div(class = "card", - div(class = "card-header", "Selection Signatures"), - div(class = "card-body", - DTOutput("selection_table"), tags$br(), - downloadButton("download_selection", "Download Selection Results (.xlsx)") + div(class="card", + div(class="card-hd","Selection Signatures"), + div(class="card-bd", + DTOutput("sel_table"),tags$br(), + downloadButton("dl_sel","Download (.xlsx)",class="btn btn-success") ) ) )) ), - # ---- INTERPRETATION ---- - tabPanel("Interpretation", icon = icon("lightbulb"), - div(class = "main-header", - h2(tags$i(class = "fas fa-lightbulb", style = "margin-right:8px;"), "Results Interpretation"), - p("Semi-partial R² PVE | LOD-1.5 interval sizes | dominance classification") - ), - fluidRow(column(12, div(class = "card", div(class = "card-header", "Analysis Summary"), div(class = "card-body", uiOutput("analysis_summary"))))), - fluidRow( - column(6, div(class = "card", div(class = "card-header", "QTL Significance"), div(class = "card-body", uiOutput("qtl_interpretation")))), - column(6, div(class = "card", div(class = "card-header", "Effect Sizes (Add + Dom)"), div(class = "card-body", uiOutput("effect_interpretation")))) - ), - fluidRow(column(12, div(class = "card", div(class = "card-header", "Epistasis"), div(class = "card-body", uiOutput("epistasis_interpretation"))))), - fluidRow(column(12, div(class = "card", div(class = "card-header", "Recommendations"),div(class = "card-body", uiOutput("recommendations"))))) - ), - - # ---- ABOUT ---- - tabPanel("About", icon = icon("info-circle"), - div(class = "main-header", - h2(tags$i(class = "fas fa-info-circle", style = "margin-right:8px;"), "About QTL-Mapper CIM v5") - ), - fluidRow(column(8, offset = 2, - div(class = "card", - div(class = "card-body", - h4(style = "color:#1D4ED8;font-family:'IBM Plex Mono';margin-bottom:12px;", "Changes in v5 (PVE Fix + New Downloads)"), - div(class = "fix-box", - tags$pre(style = "background:transparent;border:none;margin:0;color:#92400E;font-size:11px;", - "v4 BUG: PVE very low / near-zero\n\n", - "ROOT CAUSE:\n", - " When cofactors explain most variance, SS_total_raw >> (RSS_reduced - RSS_full)\n", - " Example: n=200, 10 cofactors explaining 80% variance:\n", - " SS_total_raw = 1000, RSS_reduced = 200, RSS_full = 160\n", - " v4 PVE_CIM = (200-160)/1000 = 4% ← deflated!\n", - " v5 PVE_CIM = (200-160)/200 = 20% ← correct semi-partial R²\n\n", - "v5 FIX 1 — Semi-partial R²:\n", - " PVE_CIM = (RSS_reduced - RSS_full) / RSS_reduced × 100\n", - " Denominator = variance REMAINING after cofactors, not raw total\n\n", - "v5 FIX 2 — Adaptive cofactor cap:\n", - " n_cofactors_used = min(n_cofactors_user, floor(sqrt(n_samples)))\n", - " Prevents too many cofactors absorbing all marker signal\n\n", - "v5 FIX 3 — Chromosome viz download (HTML, not PNG):\n", - " Now exports the same HTML/CSS layout as the on-screen display\n", - " Same red QTL ticks, blue flanking markers, pink LOD-1.5 interval bands\n", - " Hover markers for LOD + PVE tooltip. Opens in any browser.\n\n", - "v5 FIX 4 — Predicted test phenotype download:\n", - " Download button added to Test Data card\n", - " Exports id + Predicted_Phenotype to .xlsx\n\n", - "KEPT FROM v4:\n", - " Additive coding: -1/0/+1 | LOD-1.5 support intervals\n", - " PVE_marker = unconditional R² (marker alone vs null)") + # ─── ABOUT ───────────────────────────────────────────────── + tabPanel("About", icon=icon("info-circle"), + fluidRow(column(8,offset=2, + div(class="card", + div(class="card-bd", + tags$h4(style="color:var(--accent);font-family:var(--mono);","QTL-Mapper v6 — Changes & Methods"), + div(class="warn-box", + tags$b("v5→v6 Key Fixes:"), tags$br(), + "1. MULTI-CHROMOSOME: robust marker_info join; debug log per chr; all chroms now scan", tags$br(), + "2. MULTIPLE MODELS: SIM, CIM, MQM, LASSO, Ridge — select/compare freely", tags$br(), + "3. IDIOGRAM PLOT: replicates reference image (chromosome bars + colored symbols per trait)", tags$br(), + "4. MANHATTAN: proper cumulative offsets for all chromosomes, not just Chr1", tags$br(), + "5. PVE: semi-partial R² (denominator = RSS after cofactors, not raw SS_total)" ), - h4(style = "color:#1D4ED8;font-family:'IBM Plex Mono';margin:16px 0 8px;", "Thresholds"), - tags$ul(style = "color:#475569;line-height:2;", - tags$li("LOD > 2: Suggestive | LOD > 3: Significant | LOD > 5: Highly significant"), - tags$li("PVE_CIM > 20%: Major (of residual) | 10-20%: Moderate | <10%: Minor"), - tags$li("PVE_marker > 15%: Major QTL | 5-15%: Moderate | <5%: Minor"), - tags$li("|d/a| > 1: Overdominance | ~1: Dominance | 0.2-0.5: Partial | <0.2: Additive"), - tags$li("LOD-1.5 interval: Lander & Botstein (1989) Genetics 121:185"), - tags$li("Semi-partial R²: Lynch & Walsh (1998) Genetics & Analysis of Quantitative Traits"), - tags$li("CIM: Zeng (1993) PNAS 90:10972; Zeng (1994) Genetics 136:1457") + tags$h5(style="margin-top:16px;font-family:var(--mono);","Mapping Methods"), + tags$ul(lapply(MAPPING_MODELS, function(m) + tags$li(tags$b(m$label),"—",m$desc) + )), + tags$h5(style="margin-top:16px;font-family:var(--mono);","References"), + tags$ul( + tags$li("Zeng (1993) PNAS 90:10972 — CIM"), + tags$li("Zeng (1994) Genetics 136:1457 — CIM"), + tags$li("Lander & Botstein (1989) Genetics 121:185 — LOD intervals"), + tags$li("Lynch & Walsh (1998) — Semi-partial R²"), + tags$li("Tibshirani (1996) JRSS-B 58:267 — LASSO"), + tags$li("Contact: ashmithamganesan@gmail.com, P.sinha@cgiar.org") ) ) ) @@ -1215,51 +1044,38 @@ ui <- fluidPage( ) ), - # ============================================================ - # FLOATING CHAT - # ============================================================ - tags$div(id = "chat-panel", - tags$div(id = "chat-window", - tags$div(id = "chat-header", - tags$div(class = "chat-header-top", - tags$div(class = "chat-title", - tags$div(class = "chat-avatar", "AI"), - tags$div( - tags$h4("QTL-CIM AI Assistant v5"), - tags$p(id = "model_status_text", - if (token_exists) "AI mode ready" else "Rule-based mode", - class = if (token_exists) "ai-mode" else "") - ) - ), - tags$button(id = "chat-close-btn", - onclick = "document.getElementById('chat-window').classList.remove('open');", - tags$i(class = "fas fa-times")) + # ─── FLOATING CHAT ─────────────────────────────────────────── + tags$div(id="chat-panel", + tags$div(id="chat-win", + tags$div(id="chat-hd", + tags$div( + tags$h4(tags$i(class="fas fa-robot",style="margin-right:6px;"), "QTL-AI v6 Assistant"), + tags$small(style="color:var(--muted);font-family:var(--mono);", + if(token_exists) "AI mode" else "Rule-based mode") ), - tags$div(class = "chat-model-selector", - tags$label(tags$i(class = "fas fa-robot"), " Model:"), - tags$div(id = "model_status_dot", class = paste0("model-status-dot ", if (token_exists) "online" else "offline")), - selectInput("selected_model", label = NULL, choices = model_choices, selected = default_model, width = "100%"), - actionButton("test_model_btn", "Test", class = "test-model-btn") - ) + tags$button(id="chat-close", + onclick="document.getElementById('chat-win').classList.remove('open');", + tags$i(class="fas fa-times")) ), - tags$div(class = "quick-questions", - tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q','Why is PVE low? How is it fixed in v5?',{priority:'event'});", "Low PVE fix"), - tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q','Show top QTLs',{priority:'event'});", "Top QTLs"), - tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q','Explain LOD support interval',{priority:'event'});", "Intervals"), - tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q','Why is my R2 negative?',{priority:'event'});", "Negative R²") + tags$div(class="qq", + tags$button(class="qqb",onclick="Shiny.setInputValue('qq','How does CIM differ from SIM?',{priority:'event'});","CIM vs SIM"), + tags$button(class="qqb",onclick="Shiny.setInputValue('qq','Why no results on other chromosomes?',{priority:'event'});","Chr debug"), + tags$button(class="qqb",onclick="Shiny.setInputValue('qq','Show top QTLs',{priority:'event'});","Top QTLs"), + tags$button(class="qqb",onclick="Shiny.setInputValue('qq','Explain PVE semi-partial R2',{priority:'event'});","PVE explained") ), - tags$div(id = "chat_messages", uiOutput("chat_display")), - tags$div(id = "chat-footer", - tags$textarea(id = "chat_input", placeholder = "Ask about CIM v5... (Enter to send)", rows = "2"), - tags$div(class = "chat-actions", - actionButton("send_chat", "Send", icon = icon("paper-plane"), class = "btn-primary"), - actionButton("clear_chat", "Clear", icon = icon("trash-alt"), class = "btn-danger") + tags$div(id="chat_msgs", uiOutput("chat_ui")), + tags$div(id="chat-ft", + tags$textarea(id="chat_input",rows="2", + placeholder="Ask about QTL mapping... (Enter to send)"), + tags$div(class="chat-acts", + actionButton("send_chat","Send",icon=icon("paper-plane"),class="btn btn-primary"), + actionButton("clear_chat","Clear",class="btn btn-warning") ) ) ), - tags$button(id = "chat-toggle-btn", - onclick = "document.getElementById('chat-window').classList.toggle('open');", - tags$i(class = "fas fa-robot")) + tags$button(id="chat-toggle", + onclick="document.getElementById('chat-win').classList.toggle('open');", + tags$i(class="fas fa-robot")) ) ) @@ -1268,939 +1084,639 @@ ui <- fluidPage( # ============================================================ server <- function(input, output, session) { - values <- reactiveValues( - genotype_data = NULL, - phenotype_data = NULL, - test_genotype_data = NULL, - predicted_test_phenotype_data = NULL, - all_markers = NULL, - chromosome_info = NULL, - position_info = NULL, - cim_all = NULL, - qtl_effects_train = NULL, - performance_metrics = NULL, - train_predictions = NULL, - test_predictions = NULL, - epistasis_all = NULL, - epistasis_sig = NULL, - pop_data = NULL, - selection_metrics = NULL, - model_fit = NULL, - model_train_cols = NULL, # exact columns used to train RF (after NZV removal) - chat_messages = list(), - is_typing = FALSE, - lod_threshold = 2, - lod_drop = 1.5, - current_model = default_model + rv <- reactiveValues( + geno = NULL, pheno = NULL, + test_geno = NULL, pop_data = NULL, + marker_info = NULL, all_markers = NULL, + scan_all = NULL, sig_qtl = NULL, + perf = NULL, tr_pred = NULL, val_pred = NULL, + model_fit = NULL, model_cols = NULL, + pred_test = NULL, + sel_metrics = NULL, + compare_res = list(), # named list: method → scan_all + chat_msgs = list(), + is_typing = FALSE, + lod_thr = 2.0 ) - # ---- Model selector ---- - observe({ req(input$selected_model); values$current_model <- input$selected_model }) - - observeEvent(input$test_model_btn, { - req(input$selected_model) - add_message("assistant", paste0("Testing model: **", input$selected_model, "**...")) - result <- test_api_connection(input$selected_model) - if (result$success) { - add_message("assistant", paste0("✅ **", input$selected_model, "** is working!")) - shinyjs::runjs("document.getElementById('model_status_dot').className='model-status-dot online';") - } else { - add_message("assistant", paste0("❌ Failed: ", result$error)) - shinyjs::runjs("document.getElementById('model_status_dot').className='model-status-dot offline';") - } + # ── 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", MAPPING_MODELS[[m]]$desc) }) - # ---- Chat helpers ---- - add_message <- function(role, content, model_used = NULL) { - values$chat_messages <- c(values$chat_messages, - list(list(role = role, content = content, - time = format(Sys.time(), "%H:%M"), model = model_used))) - if (length(values$chat_messages) > 100) - values$chat_messages <- tail(values$chat_messages, 100) - session$sendCustomMessage("scrollChatBottom", list()) - } - - process_message <- function(user_text) { - if (nchar(trimws(user_text)) == 0) return() - add_message("user", user_text) - values$is_typing <- TRUE - model_id <- isolate(values$current_model) - response <- generate_ai_response(user_text, values, model_id = model_id) - values$is_typing <- FALSE - add_message("assistant", response, model_used = if (token_exists) gsub(".*/", "", model_id) else NULL) - } - - observeEvent(input$send_chat, { user_text <- trimws(input$chat_input); if (nchar(user_text) == 0) return(); updateTextAreaInput(session, "chat_input", value = ""); process_message(user_text) }) - observeEvent(input$quick_q, { req(input$quick_q); process_message(input$quick_q) }) - observeEvent(input$clear_chat, { values$chat_messages <- list(); add_message("assistant", "Chat cleared. How can I help?") }) - - observe({ - if (length(values$chat_messages) == 0) { - add_message("assistant", paste0( - "👋 Vanakam! TerraByte-AI (CIM v5 — PVE fixed)\n\n", - "**v5 Key Fixes:**\n", - "• PVE_CIM now uses RSS_cofactors as denominator (semi-partial R²)\n", - "• Adaptive cofactor cap = min(K, √n_samples)\n", - "• Chromosome viz downloads as HTML — same as on-screen ✅\n", - "• Predicted test phenotype download now available ✅\n\n", - "Click 'Low PVE fix' above for a detailed explanation.\n", - "Contact: ashmithamganesan@gmail.com, P.sinha@cgiar.org" - )) - } - }) - - output$chat_display <- renderUI({ - msgs <- values$chat_messages - if (length(msgs) == 0) return(NULL) - elems <- lapply(msgs, function(msg) { - content_html <- HTML(gsub("\n", "
", htmltools::htmlEscape(msg$content))) - div(class = paste("chat-msg", msg$role), - div(class = "chat-bubble", content_html), - div(class = "chat-meta", - span(msg$time), - if (!is.null(msg$model) && msg$role == "assistant") - span(class = "model-tag", paste0("[", msg$model, "]")) - ) - ) - }) - if (values$is_typing) { - elems <- c(elems, list(div(class = "chat-msg assistant", - div(class = "typing-indicator", - div(class = "typing-dot"), div(class = "typing-dot"), div(class = "typing-dot"))))) - } - do.call(tagList, elems) + # ── Dataset info ────────────────────────────────────────── + output$dataset_info_ui <- renderUI({ + if (is.null(rv$geno)) return(tags$p("No data loaded yet.")) + n_chr <- length(unique(rv$marker_info$Chromosome)) + tagList( + tags$p(tags$b("Samples:"), nrow(rv$geno)), + tags$p(tags$b("Markers:"), ncol(rv$geno)), + tags$p(tags$b("Chromosomes:"), n_chr), + tags$p(tags$b("Chr list:"), paste(sort(unique(rv$marker_info$Chromosome)), collapse=", ")), + if (!is.null(rv$pheno)) + tags$p(tags$b("Traits:"), ncol(rv$pheno)) + ) }) - # ============================================================ - # DATA LOADING - # ============================================================ - # Shared name-cleaner: strip \r, quotes, leading/trailing spaces - cn <- function(x) trimws(gsub('[\r\n\"]', '', as.character(x))) - - observeEvent(input$genotype_file, { - req(input$genotype_file) + # ── Data loading ────────────────────────────────────────── + observeEvent(input$geno_file, { + req(input$geno_file) tryCatch({ - all_data <- readLines(input$genotype_file$datapath) - all_data <- gsub("\r", "", all_data) - all_data <- all_data[nchar(trimws(all_data)) > 0] - if (length(all_data) < 4) { showNotification("Need ≥4 rows", type = "error"); return() } - header <- cn(strsplit(all_data[1], ",")[[1]]) - chromosome_row <- cn(strsplit(all_data[2], ",")[[1]]) - position_row <- cn(strsplit(all_data[3], ",")[[1]]) - genotype_data <- read.csv(text = paste(all_data[-(1:3)], collapse = "\n"), - header = FALSE, stringsAsFactors = FALSE, quote = '"') - if (ncol(genotype_data) != length(header)) { - showNotification(paste0("Header has ", length(header), " cols but data has ", ncol(genotype_data)), type = "error"); return() - } - colnames(genotype_data) <- header - rownames(genotype_data) <- cn(as.character(genotype_data[, 1])) - genotype_data <- genotype_data[, -1, drop = FALSE] - for (col in colnames(genotype_data)) - genotype_data[[col]] <- suppressWarnings(as.numeric(as.character(genotype_data[[col]]))) - values$genotype_data <- genotype_data - values$chromosome_info <- chromosome_row[-1] - values$position_info <- suppressWarnings(as.numeric(position_row[-1])) - values$all_markers <- data.frame( - Marker = colnames(genotype_data), - Chromosome = chromosome_row[-1], - Position = suppressWarnings(as.numeric(position_row[-1])), - stringsAsFactors = FALSE) - cat("TRAIN GENO LOADED:", nrow(genotype_data), "samples,", ncol(genotype_data), "markers\n") - cat("TRAIN first 3 cols:", paste(colnames(genotype_data)[1:3], collapse="|"), "\n") - showNotification(paste("Loaded", ncol(genotype_data), "markers,", nrow(genotype_data), "samples"), type = "message") - add_message("assistant", paste0("✅ Genotype: **", ncol(genotype_data), " markers**, **", nrow(genotype_data), " samples**")) - }, error = function(e) showNotification(paste("Geno error:", e$message), type = "error")) + res <- load_genotype_file(input$geno_file$datapath) + rv$geno <- res$geno + rv$marker_info <- res$marker_info + rv$all_markers <- res$marker_info + msg <- paste0("✅ Genotype loaded: **",res$n_markers," markers**, **",res$n_samples," samples**, **",length(res$chromosomes)," chromosomes**: ",paste(res$chromosomes,collapse=", ")) + add_msg("assistant", msg) + showNotification(paste(res$n_markers,"markers,",res$n_samples,"samples,",length(res$chromosomes),"chromosomes"), type="message") + }, error=function(e) showNotification(paste("Geno error:",e$message), type="error")) }) - observeEvent(input$phenotype_file, { - req(input$phenotype_file) + observeEvent(input$pheno_file, { + req(input$pheno_file) tryCatch({ - pd <- read.csv(input$phenotype_file$datapath) - rownames(pd) <- pd[, 1]; pd <- pd[, -1] + pd <- read.csv(input$pheno_file$datapath) + rownames(pd) <- pd[,1]; pd <- pd[,-1,drop=FALSE] for (col in colnames(pd)) pd[[col]] <- as.numeric(as.character(pd[[col]])) - values$phenotype_data <- pd - updateSelectInput(session, "phenotype_column", choices = colnames(pd), selected = colnames(pd)[1]) - showNotification(paste("Loaded", ncol(pd), "traits"), type = "message") - add_message("assistant", paste0("✅ Phenotype: **", ncol(pd), " traits**, **", nrow(pd), " samples**")) - }, error = function(e) showNotification(paste("Pheno error:", e$message), type = "error")) + rv$pheno <- pd + updateSelectInput(session,"pheno_col",choices=colnames(pd),selected=colnames(pd)[1]) + showNotification(paste(ncol(pd),"traits loaded"), type="message") + }, error=function(e) showNotification(paste("Pheno error:",e$message), type="error")) }) observeEvent(input$pop_file, { req(input$pop_file) tryCatch({ pd <- read.csv(input$pop_file$datapath) - if (!all(c("id", "population") %in% colnames(pd))) { showNotification("Need 'id' and 'population' columns", type = "error"); return() } - values$pop_data <- pd - showNotification(paste("Population data:", nrow(pd), "samples"), type = "message") - }, error = function(e) showNotification(paste("Pop error:", e$message), type = "error")) + rv$pop_data <- pd + showNotification(paste("Pop data:",nrow(pd),"samples"), type="message") + }, error=function(e) showNotification(paste("Pop error:",e$message), type="error")) }) - observeEvent(input$test_genotype_file, { - req(input$test_genotype_file) + observeEvent(input$test_geno_file, { + req(input$test_geno_file) tryCatch({ - all_data <- readLines(input$test_genotype_file$datapath) - all_data <- gsub("\r", "", all_data) - all_data <- all_data[nchar(trimws(all_data)) > 0] - if (length(all_data) < 4) { - showNotification("Test genotype needs ≥4 rows (header + chr + pos + ≥1 sample)", type = "error"); return() - } - # Use SAME cn() cleaner as training loader - header <- cn(strsplit(all_data[1], ",")[[1]]) - gd <- read.csv(text = paste(all_data[-(1:3)], collapse = "\n"), - header = FALSE, stringsAsFactors = FALSE, quote = '"') - if (ncol(gd) != length(header)) { - showNotification(paste0("Header has ", length(header), " cols but data has ", ncol(gd)), type = "error"); return() - } - colnames(gd) <- header - rownames(gd) <- cn(as.character(gd[, 1])) - gd <- gd[, -1, drop = FALSE] - for (col in colnames(gd)) - gd[[col]] <- suppressWarnings(as.numeric(as.character(gd[[col]]))) - values$test_genotype_data <- gd - cat("TEST GENO LOADED:", nrow(gd), "samples,", ncol(gd), "markers\n") - cat("TEST first 3 cols:", paste(colnames(gd)[1:3], collapse="|"), "\n") - showNotification(paste0("✅ Test genotype: ", nrow(gd), " samples, ", ncol(gd), " markers"), type = "message") - }, error = function(e) { - showNotification(paste("Test geno error:", e$message), type = "error", duration = 10) - cat("TEST GENO ERROR:", e$message, "\n") - }) + 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")) }) - output$geno_preview <- renderDT({ req(input$genotype_file); datatable(head(read.csv(input$genotype_file$datapath), 10), options = list(scrollX = TRUE, pageLength = 5)) }) - output$pheno_preview <- renderDT({ req(input$phenotype_file); datatable(head(read.csv(input$phenotype_file$datapath), 10), options = list(scrollX = TRUE, pageLength = 5)) }) - output$test_geno_preview <- renderDT({ req(input$test_genotype_file); datatable(head(read.csv(input$test_genotype_file$datapath), 10), options = list(scrollX = TRUE, pageLength = 5)) }) - output$pop_preview <- renderDT({ req(input$pop_file); datatable(head(read.csv(input$pop_file$datapath), 10), options = list(scrollX = TRUE, pageLength = 5)) }) - output$predicted_test_pheno_preview <- renderDT({ - req(values$predicted_test_phenotype_data) - datatable(values$predicted_test_phenotype_data, options = list(scrollX = TRUE, pageLength = 5)) - }) + # ── PREVIEWS ────────────────────────────────────────────── + output$prev_geno <- renderDT({ req(input$geno_file); datatable(head(read.csv(input$geno_file$datapath),10), options=list(scrollX=TRUE,pageLength=5)) }) + output$prev_pheno <- renderDT({ req(input$pheno_file); datatable(head(read.csv(input$pheno_file$datapath),10), options=list(scrollX=TRUE,pageLength=5)) }) + output$prev_test_geno <- renderDT({ req(rv$test_geno); datatable(head(rv$test_geno,10), options=list(scrollX=TRUE,pageLength=5)) }) + output$prev_pred <- renderDT({ req(rv$pred_test); datatable(rv$pred_test, options=list(scrollX=TRUE,pageLength=8)) }) + output$prev_pop <- renderDT({ req(rv$pop_data); datatable(head(rv$pop_data,10), options=list(scrollX=TRUE,pageLength=5)) }) + + # ── MAIN ANALYSIS ───────────────────────────────────────── + observeEvent(input$run_btn, { + req(rv$geno, rv$pheno, input$pheno_col) - # ============================================================ - # MAIN CIM ANALYSIS - # ============================================================ - observeEvent(input$run_analysis, { - req(values$genotype_data, values$phenotype_data, input$phenotype_column) - showNotification("Starting CIM v5 analysis...", type = "message") - values$lod_threshold <- input$lod_threshold - values$lod_drop <- input$lod_drop + showNotification(paste("Starting",input$mapping_method,"scan..."), type="message") + rv$lod_thr <- input$lod_threshold tryCatch({ - common_samples <- intersect(rownames(values$genotype_data), rownames(values$phenotype_data)) - if (length(common_samples) == 0) { showNotification("No common samples", type = "error"); return() } - - X <- values$genotype_data[common_samples, , drop = FALSE] - y <- as.numeric(values$phenotype_data[common_samples, input$phenotype_column]) - - set.seed(123) - train_index <- createDataPartition(y, p = 1 - input$test_size, list = FALSE) - X_train <- X[train_index, , drop = FALSE]; X_val <- X[-train_index, , drop = FALSE] - y_train <- y[train_index]; y_val <- y[-train_index] - - withProgress(message = "Running CIM v5 genome scan...", value = 0.1, { - cim_results <- run_cim( - genotype_matrix = X_train, - phenotype_vector = y_train, - marker_info = values$all_markers, + cs <- intersect(rownames(rv$geno), rownames(rv$pheno)) + if (length(cs)==0) { showNotification("No common samples between genotype and phenotype!", 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] + + withProgress(message=paste("Running",input$mapping_method,"genome scan..."), value=0.1, { + scan_res <- qtl_scan( + genotype_matrix = X_tr, + phenotype_vector = y_tr, + marker_info = rv$marker_info, + method = input$mapping_method, n_cofactors = input$n_cofactors, - window_size = input$window_size, - lod_threshold = input$lod_threshold + window_size = input$window_size ) - incProgress(0.7) - }) - - values$cim_all <- cim_results + incProgress(0.6) - if (!"Message" %in% colnames(cim_results)) { - sig_qtls <- cim_results[cim_results$LOD >= input$lod_threshold, ] - if (nrow(sig_qtls) > 0) { - sig_qtls <- add_lod_support_interval(sig_qtls, cim_results, input$lod_drop) - values$qtl_effects_train <- sig_qtls[order(-sig_qtls$LOD), ] - } else { - values$qtl_effects_train <- data.frame(Message = paste("No QTLs above LOD", input$lod_threshold)) - } - } else { - values$qtl_effects_train <- cim_results - } + rv$scan_all <- scan_res - # RF model for prediction - nzv <- nearZeroVar(X_train) - X_tr_rf <- if (length(nzv) > 0) X_train[, -nzv, drop = FALSE] else X_train - X_v_rf <- X_val[, colnames(X_tr_rf), drop = FALSE] - - model <- tryCatch( - train(x = X_tr_rf, y = y_train, method = "rf", - trControl = trainControl(method = "cv", number = 5), - importance = TRUE, tuneLength = 3), - error = function(e) { - train(x = X_tr_rf, y = y_train, method = "lm", - trControl = trainControl(method = "cv", number = 5)) - }) - values$model_fit <- model - values$model_train_cols <- colnames(X_tr_rf) # store exact training columns for test prediction - - y_train_pred <- predict(model, X_tr_rf) - y_val_pred <- predict(model, X_v_rf) - train_r2 <- 1 - sum((y_train - y_train_pred)^2) / sum((y_train - mean(y_train))^2) - val_r2 <- 1 - sum((y_val - y_val_pred)^2) / sum((y_val - mean(y_val))^2) - - values$performance_metrics <- data.frame( - Metric = c("R² (Train)", "R (Train)", "R² (Validation)", "R (Validation)"), - Value = c(train_r2, cor(y_train, y_train_pred), val_r2, cor(y_val, y_val_pred)), - stringsAsFactors = FALSE) - - values$train_predictions <- data.frame(Observed = y_train, Predicted = y_train_pred) - values$test_predictions <- data.frame(Observed = y_val, Predicted = y_val_pred) - - # Epistasis - if (!is.null(values$qtl_effects_train) && !"Message" %in% colnames(values$qtl_effects_train)) { - sig_markers <- values$qtl_effects_train$Marker - all_markers_v <- colnames(X_train) - epi_list <- list() - withProgress(message = "Calculating epistasis...", value = 0, { - for (m1 in sig_markers) { - for (m2 in all_markers_v) { - if (m1 == m2) next - tryCatch({ - d <- data.frame(y = y_train, m1 = X_train[, m1], m2 = X_train[, m2]) - d <- na.omit(d); if (nrow(d) < 10) next - fit <- lm(y ~ m1 * m2, data = d) - ct <- summary(fit)$coefficients - if ("m1:m2" %in% rownames(ct)) { - epi_list[[length(epi_list) + 1]] <- data.frame( - QTL1 = m1, QTL2 = m2, - Interaction_p = ct["m1:m2", "Pr(>|t|)"], - Effect_Size = coef(fit)["m1:m2"], stringsAsFactors = FALSE) - } - }, error = function(e) {}) - } + if (!"Message" %in% colnames(scan_res)) { + sig <- scan_res[scan_res$LOD >= input$lod_threshold & !is.na(scan_res$LOD),] + if (nrow(sig)>0) { + sig <- add_lod_support_interval(sig, scan_res, input$lod_drop) + rv$sig_qtl <- sig[order(-sig$LOD),] + } else { + rv$sig_qtl <- data.frame(Message=paste("No QTLs above LOD",input$lod_threshold)) } - }) - if (length(epi_list) > 0) { - ea <- do.call(rbind, epi_list) - values$epistasis_all <- ea - values$epistasis_sig <- ea[ea$Interaction_p < 0.05, ] } else { - values$epistasis_all <- data.frame(Message = "No epistatic interactions found") - values$epistasis_sig <- data.frame(Message = "No epistatic interactions found") + rv$sig_qtl <- scan_res } - } - n_qtl <- if (!is.null(values$qtl_effects_train) && !"Message" %in% colnames(values$qtl_effects_train)) nrow(values$qtl_effects_train) else 0 - max_pve <- if (n_qtl > 0) round(max(values$qtl_effects_train$PVE_CIM_Percent, na.rm = TRUE), 1) else 0 - max_pve_m <- if (n_qtl > 0) round(max(values$qtl_effects_train$PVE_Marker_Percent, na.rm = TRUE), 1) else 0 - - showNotification("CIM v5 analysis completed!", type = "message") - add_message("assistant", paste0( - "✅ **CIM v5 analysis complete!**\n\n", - "• **", n_qtl, " QTLs** above LOD ", input$lod_threshold, "\n", - "• Top PVE_marker: **", max_pve_m, "%** | Top PVE_CIM: **", max_pve, "%**\n", - "• Validation R²: **", round(val_r2, 3), "**\n", - "• PVE formula: semi-partial R² ✅\n", - "• Cofactor cap: min(", input$n_cofactors, ", √", length(y_train), ") = ", min(input$n_cofactors, floor(sqrt(length(y_train)))), " ✅\n\n", - "Download: Chromosome Map (.html) = same as on-screen view ✅" + # 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] + 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)) + ) + rv$model_fit <- fit + + ytr_pred <- predict(fit, X_tr_rf) + yv_pred <- predict(fit, X_v_rf) + tr_r2 <- 1 - sum((y_tr-ytr_pred)^2)/sum((y_tr-mean(y_tr))^2) + v_r2 <- 1 - sum((y_v-yv_pred)^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_pred), v_r2, cor(y_v,yv_pred))) + rv$tr_pred <- data.frame(Observed=y_tr, Predicted=ytr_pred) + rv$val_pred <- data.frame(Observed=y_v, Predicted=yv_pred) + + incProgress(0.3) + }) + + n_sig <- if (!is.null(rv$sig_qtl) && !"Message" %in% colnames(rv$sig_qtl)) nrow(rv$sig_qtl) else 0 + n_chr_res <- if (!is.null(rv$scan_all) && !"Message" %in% colnames(rv$scan_all)) + length(unique(rv$scan_all$Chromosome)) else 0 + add_msg("assistant", paste0( + "✅ **",input$mapping_method," scan complete!**\n\n", + "• **",n_sig," QTLs** above LOD ",input$lod_threshold,"\n", + "• Chromosomes in results: **",n_chr_res,"**\n", + "• Validation R²: **",round(rv$perf$Value[3],3),"**" )) - updateTabsetPanel(session, "nav", selected = "Results") + showNotification(paste(input$mapping_method,"done:",n_sig,"QTLs on",n_chr_res,"chromosomes"), type="message") + updateTabsetPanel(session,"nav",selected="Results") - }, error = function(e) { - showNotification(paste("CIM v5 Error:", e$message), type = "error") - cat("CIM v5 ERROR:", e$message, "\n") + }, error=function(e) { + showNotification(paste("Analysis error:",e$message), type="error") + cat("ANALYSIS ERROR:", e$message, "\n") }) }) - # ============================================================ - # PREDICT TEST PHENOTYPES - # ============================================================ - observeEvent(input$predict_test_phenotype, { + # ── 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=", "), + 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(m,": 0 QTLs ")) + n <- sum(r$LOD>=rv$lod_thr, na.rm=TRUE) + nc <- length(unique(r$Chromosome[!is.na(r$LOD)])) + tags$span(class="model-badge", paste0(m,": ",n," QTLs / ",nc," chr ")) + }) + ) + }) - # ── Guard: need model + test data ─────────────────────────── - if (is.null(values$model_fit)) { - showNotification("❌ Run CIM Analysis first to train the model.", type = "error", duration = 8) - return() - } - if (is.null(values$test_genotype_data)) { - showNotification("❌ Upload a Test Genotype CSV first.", type = "error", duration = 8) - return() + observeEvent(input$run_compare, { + req(rv$geno, rv$pheno, input$compare_methods, input$pheno_col) + methods_sel <- input$compare_methods + if (length(methods_sel)==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=0.8,list=FALSE) + X_tr <- X[tr_idx,,drop=FALSE]; y_tr <- y[tr_idx] + + compare_list <- list() + withProgress(message="Comparing models...", value=0, { + for (mth in methods_sel) { + incProgress(1/length(methods_sel), 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 } + ) + if (!is.null(res)) compare_list[[mth]] <- res + } + }) + rv$compare_res <- compare_list + showNotification(paste("Compared",length(compare_list),"models"), type="message") + }) + + output$compare_idiogram <- renderPlot({ + req(length(rv$compare_res)>0, rv$all_markers) + par(bg="white") + make_chromosome_idiogram(rv$compare_res, rv$all_markers, rv$lod_thr) + }, bg="white") + + output$compare_bar <- renderPlotly({ + 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>=rv$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))) } + 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") %>% + layout(barmode="group", title="QTL Count by Method & Chromosome", + xaxis=list(title="Chromosome"), yaxis=list(title="# Significant QTLs"), + plot_bgcolor="#FFF", paper_bgcolor="#FFF") + }) - withProgress(message = "Predicting test phenotypes...", value = 0, { + output$compare_table <- renderDT({ + 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>=rv$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")])) + } + if (length(rows)==0) return(datatable(data.frame(Status="No QTLs"))) + df <- do.call(rbind, rows) + # Add overlap count + overlap <- table(df$Marker) + df$Detected_By_N_Models <- as.integer(overlap[df$Marker]) + datatable(df[order(-df$Detected_By_N_Models,-df$LOD),], + options=list(scrollX=TRUE,pageLength=15), rownames=FALSE) %>% + formatRound(c("LOD","PVE_Marker_Percent","Position"),3) + }) - # ── Step 1: Setup ──────────────────────────────────────── - incProgress(0.05, detail = "Loading model and test data...") - Sys.sleep(0.05) + # ── PLOTS ───────────────────────────────────────────────── + output$manhattan_plot <- renderPlotly({ + req(rv$scan_all) + make_plotly_manhattan(rv$scan_all, rv$lod_thr, + paste(input$mapping_method,"Manhattan Plot")) + }) - model <- values$model_fit - test_raw <- values$test_genotype_data # data.frame: rows=samples, cols=markers + output$idiogram_plot <- renderPlot({ + req(rv$scan_all, rv$all_markers) + res_list <- list() + mth <- input$mapping_method + if (!is.null(rv$scan_all) && !"Message"%in%colnames(rv$scan_all)) + res_list[[mth]] <- 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="white") + make_chromosome_idiogram(res_list, rv$all_markers, rv$lod_thr) + }, bg="white") + + output$perf_plot <- renderPlotly({ + req(rv$perf) + plot_ly(rv$perf, x=~Metric, y=~Value, type="bar", + marker=list(color=c("#1D4ED8","#3B82F6","#15803D","#22C55E")), + text=~round(Value,3), textposition="outside") %>% + layout(title="Model Performance", yaxis=list(range=c(0,1.15),title="Value"), + plot_bgcolor="#FFF", paper_bgcolor="#FFF") + }) - # Get the exact predictor column names the model was trained on - train_cols <- values$model_train_cols - if (is.null(train_cols)) { - # Fallback: extract from caret model object - train_cols <- tryCatch(model$finalModel$xNames, error = function(e) NULL) - if (is.null(train_cols)) - train_cols <- tryCatch(colnames(model$trainingData)[-ncol(model$trainingData)], error = function(e) NULL) - if (is.null(train_cols)) - train_cols <- colnames(values$genotype_data) - } + output$reg_train <- renderPlotly({ + req(rv$tr_pred) + plot_ly(rv$tr_pred,x=~Observed,y=~Predicted,type="scatter",mode="markers", + marker=list(size=5,color="#1D4ED8",opacity=.75)) %>% + add_trace(x=range(rv$tr_pred$Observed),y=range(rv$tr_pred$Observed), + type="scatter",mode="lines",line=list(color="#DC2626",dash="dash"),showlegend=FALSE) %>% + layout(title="Training",plot_bgcolor="#FFF",paper_bgcolor="#FFF", + xaxis=list(title="Observed"),yaxis=list(title="Predicted")) + }) - cat("PREDICT: train_cols =", length(train_cols), - "| test cols =", ncol(test_raw), "\n") - cat("PREDICT: train[1:3] =", paste(train_cols[1:3], collapse="|"), "\n") - cat("PREDICT: test[1:3] =", paste(colnames(test_raw)[1:3], collapse="|"), "\n") - - # ── Step 2: Marker overlap ─────────────────────────────── - incProgress(0.10, detail = "Matching markers...") - Sys.sleep(0.05) - - common_m <- intersect(train_cols, colnames(test_raw)) - missing_m <- setdiff(train_cols, colnames(test_raw)) - - cat("PREDICT: common =", length(common_m), "| missing =", length(missing_m), "\n") - - if (length(common_m) == 0) { - showNotification( - paste0("No markers matched! Train has ", length(train_cols), - " markers, test has ", ncol(test_raw), ". Check marker names match exactly."), - type = "error", duration = 15) - add_message("assistant", paste0( - "❌ **Prediction failed — zero marker overlap**\n\n", - "Train markers (first 5): ", paste(head(train_cols, 5), collapse=", "), "\n", - "Test markers (first 5): ", paste(head(colnames(test_raw), 5), collapse=", "), "\n\n", - "Both CSVs must have identical marker column names.")) - return() - } + output$reg_val <- renderPlotly({ + req(rv$val_pred) + plot_ly(rv$val_pred,x=~Observed,y=~Predicted,type="scatter",mode="markers", + marker=list(size=5,color="#15803D",opacity=.75)) %>% + add_trace(x=range(rv$val_pred$Observed),y=range(rv$val_pred$Observed), + type="scatter",mode="lines",line=list(color="#DC2626",dash="dash"),showlegend=FALSE) %>% + layout(title="Validation",plot_bgcolor="#FFF",paper_bgcolor="#FFF", + xaxis=list(title="Observed"),yaxis=list(title="Predicted")) + }) - if (length(missing_m) > 0) - showNotification(paste0(length(missing_m), " markers missing from test — imputing with 0"), - type = "warning", duration = 5) + # ── TABLES ──────────────────────────────────────────────── + output$qtl_table <- renderDT({ + req(rv$sig_qtl) + if ("Message" %in% colnames(rv$sig_qtl)) + return(datatable(data.frame(Status=rv$sig_qtl$Message[1]), options=list(dom="t"))) + 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(rv$sig_qtl)) + datatable(rv$sig_qtl[,disp], options=list(scrollX=TRUE,pageLength=10), rownames=FALSE) %>% + 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) + }) - # ── Step 3: Build aligned data.frame ──────────────────── - incProgress(0.25, detail = paste0("Aligning ", nrow(test_raw), " samples × ", length(train_cols), " markers...")) - Sys.sleep(0.05) + 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"))), + rownames=FALSE) %>% + formatRound(c("LOD","PVE_Marker_Percent","Additive_Effect"),3) %>% + formatSignif("P_Value",digits=3) + }) - # Build complete data.frame with ALL training columns in training order - n_test <- nrow(test_raw) - ids <- rownames(test_raw) + # ── 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() } - # Pre-allocate with zeros - X_pred <- as.data.frame( - matrix(0, nrow = n_test, ncol = length(train_cols), - dimnames = list(ids, train_cols)) - ) + withProgress(message="Predicting...", value=0.2, { + train_cols <- rv$model_cols + test_raw <- rv$test_geno + common_m <- intersect(train_cols, colnames(test_raw)) + cat("PREDICT: common markers:", length(common_m), "of", length(train_cols), "\n") - # Fill in the columns we have + 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) { - vals <- suppressWarnings(as.numeric(as.character(test_raw[[col]]))) - vals[is.na(vals)] <- 0 - X_pred[[col]] <- vals + v <- suppressWarnings(as.numeric(as.character(test_raw[[col]]))); v[is.na(v)] <- 0 + X_pred[[col]] <- v } + incProgress(0.5) - cat("PREDICT: X_pred dims =", nrow(X_pred), "x", ncol(X_pred), "\n") - cat("PREDICT: col order match =", identical(colnames(X_pred), train_cols), "\n") - cat("PREDICT: any NA =", any(is.na(X_pred)), "\n") - - # ── Step 4: Predict ────────────────────────────────────── - incProgress(0.40, detail = paste0("Running model on ", n_test, " samples...")) - Sys.sleep(0.05) - - preds <- tryCatch({ - # Try caret predict first (works if column names exactly match) - as.numeric(predict(model, newdata = X_pred)) - }, error = function(e1) { - cat("PREDICT caret failed:", e1$message, "\n") - tryCatch({ - # Fallback 1: use randomForest finalModel directly - as.numeric(predict(model$finalModel, newdata = X_pred)) - }, error = function(e2) { - cat("PREDICT finalModel failed:", e2$message, "\n") - tryCatch({ - # Fallback 2: use randomForest finalModel with matrix - as.numeric(predict(model$finalModel, newdata = as.matrix(X_pred))) - }, error = function(e3) { - stop(paste("All predict methods failed.\n", - "caret:", e1$message, "\n", - "finalModel df:", e2$message, "\n", - "finalModel mat:", e3$message)) - }) - }) - }) - - # ── Step 5: Save results ───────────────────────────────── - incProgress(0.15, detail = "Saving results...") - Sys.sleep(0.05) - - result_df <- data.frame( - Sample_ID = ids, - Predicted_Phenotype = round(preds, 4), - stringsAsFactors = FALSE + preds <- tryCatch( + as.numeric(predict(rv$model_fit, newdata=X_pred)), + error=function(e) as.numeric(predict(rv$model_fit$finalModel, newdata=X_pred)) ) - - values$predicted_test_phenotype_data <- result_df - - cat("PREDICT: SUCCESS —", nrow(result_df), "predictions\n") - cat("PREDICT: range", round(min(preds),3), "to", round(max(preds),3), "\n") - - incProgress(0.05, detail = "Done!") - Sys.sleep(0.05) - - }) # end withProgress - - # ── Success notification ───────────────────────────────── - res <- values$predicted_test_phenotype_data - n <- nrow(res) - rng <- paste0(round(min(res$Predicted_Phenotype),3), " – ", round(max(res$Predicted_Phenotype),3)) - - showNotification(paste0("✅ Predicted ", n, " test samples (", rng, ")"), - type = "message", duration = 6) - - add_message("assistant", paste0( - "✅ **Test phenotypes predicted!**\n\n", - "• **", n, "** samples predicted\n", - "• Predicted range: **", rng, "**\n", - "• Markers matched: **", length(intersect(values$model_train_cols, colnames(values$test_genotype_data))), - "** / ", length(values$model_train_cols), "\n", - "• Preview: *Data Upload → Predicted Test Phenotype* tab\n", - "• Save: click **Download Predicted Phenotypes (.xlsx)**" - )) + 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") }) - - # ============================================================ - # DOMESTICATION - # ============================================================ - calculate_selection_metrics <- function(geno_mat, pop_data, marker_info) { - metrics_list <- list() - for (marker in colnames(geno_mat)) { - geno <- geno_mat[, marker] - pop <- pop_data$population[match(rownames(geno_mat), pop_data$id)] - valid_idx <- !is.na(geno) & !is.na(pop) - geno <- geno[valid_idx]; pop <- pop[valid_idx] - if (length(unique(pop)) < 2) next - gd <- geno[pop == "Domesticated"]; gw <- geno[pop == "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 - pi_d <- 2 * fd * (1 - fd); pi_w <- 2 * fw * (1 - fw) - td_d <- tryCatch((pi_d - 1/length(gd)) / sqrt(var(gd)/length(gd)), error = function(e) NA) - td_w <- tryCatch((pi_w - 1/length(gw)) / sqrt(var(gw)/length(gw)), error = function(e) NA) - mr <- marker_info[marker_info$Marker == marker, ] - metrics_list[[marker]] <- data.frame( - Marker = marker, - Chromosome = ifelse(nrow(mr) > 0, mr$Chromosome[1], NA), - Position = ifelse(nrow(mr) > 0, mr$Position[1], NA), - Fst = fst, Pi_Dom = pi_d, Pi_Wild = pi_w, - Tajima_D_Dom = td_d, Tajima_D_Wild = td_w, - stringsAsFactors = FALSE) + # ── 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) } - if (length(metrics_list) == 0) return(NULL) - do.call(rbind, metrics_list) + if (length(out)==0) return(NULL) + do.call(rbind, out) } - observeEvent(input$run_domestication, { - req(values$genotype_data, values$pop_data, values$all_markers) + observeEvent(input$run_dom, { + req(rv$geno, rv$pop_data, rv$marker_info) tryCatch({ - cs <- intersect(rownames(values$genotype_data), values$pop_data$id) - if (length(cs) == 0) { showNotification("No common samples", type = "error"); return() } - X <- values$genotype_data[cs, , drop = FALSE] - ps <- values$pop_data[values$pop_data$id %in% cs, ] - sel <- calculate_selection_metrics(X, ps, values$all_markers) - if (is.null(sel)) { showNotification("No selection metrics", type = "error"); return() } - sel$Significant <- sel$Fst > input$fst_threshold | sel$Tajima_D_Dom < input$tajima_threshold - values$selection_metrics <- sel - showNotification(paste("Domestication done:", sum(sel$Significant, na.rm = TRUE), "signatures"), type = "message") - }, error = function(e) showNotification(paste("Dom error:", e$message), type = "error")) + 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$tajima_thr + rv$sel_metrics <- sel + showNotification(paste(sum(sel$Significant,na.rm=TRUE),"selection signatures"), type="message") + }, error=function(e) showNotification(paste("Dom error:",e$message), type="error")) }) - # ============================================================ - # MANHATTAN HELPER (plotly) - # ============================================================ - create_manhattan <- function(data, y_col, title, threshold, y_label = y_col) { - blank <- plot_ly() %>% layout(title = title, plot_bgcolor = "#FFFFFF", paper_bgcolor = "#FFFFFF", font = list(color = "#475569")) - 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) - chroms <- sort(unique(as.character(pd$Chromosome)), method = "radix") - chrom_pos <- data.frame() + create_man_plotly <- function(data, y_col, title, threshold, y_label=y_col) { + blank <- plot_ly()%>%layout(title=title, plot_bgcolor="#FFF", paper_bgcolor="#FFF") + 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 for (i in seq_along(chroms)) { - cd <- pd[pd$Chromosome == chroms[i], ] - if (nrow(cd) > 0) { cd$PosScaled <- cd$Position / max(cd$Position, na.rm = TRUE) + (i - 1); chrom_pos <- rbind(chrom_pos, cd) } + if(i==1){offsets[chroms[1]]<-0;next} + pm <- max(pd$Position[pd$Chromosome==chroms[i-1]],na.rm=TRUE) + offsets[chroms[i]] <- offsets[chroms[i-1]] + pm*1.05 } - pal <- rep(c("#1D4ED8","#64748B"), ceiling(length(chroms)/2)) - p <- plot_ly() %>% - add_trace(data = chrom_pos, x = ~PosScaled, y = as.formula(paste0("~", y_col)), - type = "scatter", mode = "markers", color = ~factor(Chromosome), colors = pal[1:length(chroms)], - marker = list(size = 6, opacity = 0.7), - text = ~paste("Marker:", Marker, "
Chr:", Chromosome, "
", y_label, ":", round(get(y_col), 3)), - hoverinfo = "text", showlegend = FALSE) - if (!is.null(threshold) && !is.na(threshold)) - p <- p %>% add_segments(x = min(chrom_pos$PosScaled, na.rm = TRUE), xend = max(chrom_pos$PosScaled, na.rm = TRUE), - y = threshold, yend = threshold, line = list(color = "#DC2626", dash = "dash", width = 1.5)) - p %>% layout(title = list(text = title, font = list(color = "#1E293B")), - xaxis = list(title = "Chromosome", color = "#475569", - ticktext = chroms, tickvals = tapply(chrom_pos$PosScaled, chrom_pos$Chromosome, median, na.rm = TRUE), - tickangle = 45, gridcolor = "#F1F5F9"), - yaxis = list(title = y_label, color = "#475569", gridcolor = "#F1F5F9"), - plot_bgcolor = "#FFFFFF", paper_bgcolor = "#FFFFFF", font = list(color = "#475569")) + pd$cum_pos <- pd$Position + offsets[pd$Chromosome] + chr_mids <- tapply(pd$cum_pos, pd$Chromosome, median, na.rm=TRUE) + pal <- rep(c("#1D4ED8","#64748B"),ceiling(length(chroms)/2))[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=5,color=pal[ch],opacity=.75), showlegend=FALSE, + text=~paste0("Marker: ",Marker,"
Chr: ",Chromosome,"
",y_label,": ",round(get(y_col),3)), + 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="#DC2626",dash="dash",width=1.5), showlegend=FALSE) + p %>% layout(title=title, + xaxis=list(title="Chromosome",tickvals=as.list(chr_mids[chroms]), + ticktext=as.list(paste0("Chr",chroms)), tickangle=45, gridcolor="#F1F5F9"), + yaxis=list(title=y_label,gridcolor="#F1F5F9"), + plot_bgcolor="#FFF",paper_bgcolor="#FFF") } - # ============================================================ - # PLOTS - # ============================================================ - output$lod_plot_2d <- renderPlotly({ req(values$cim_all); create_manhattan(values$cim_all, "LOD", "CIM Manhattan Plot", input$lod_threshold, "LOD Score") }) - output$fst_plot <- renderPlotly({ req(values$selection_metrics); create_manhattan(values$selection_metrics, "Fst", "Fst Plot", input$fst_threshold, "Fst") }) - - output$tajima_plot <- renderPlotly({ - req(values$selection_metrics) - if ("Message" %in% colnames(values$selection_metrics)) - return(plot_ly() %>% layout(title = "No data", plot_bgcolor = "#FFFFFF", paper_bgcolor = "#FFFFFF")) - d <- values$selection_metrics - chroms <- sort(unique(as.character(d$Chromosome)), method = "radix") - cp <- data.frame() - for (i in seq_along(chroms)) { - cd <- d[d$Chromosome == chroms[i], ] - if (nrow(cd) > 0) { cd$PosScaled <- cd$Position / max(cd$Position, na.rm = TRUE) + (i - 1); cp <- rbind(cp, cd) } - } - plot_ly() %>% - add_trace(data = cp, x = ~PosScaled, y = ~Tajima_D_Dom, type = "scatter", mode = "markers", - name = "Domesticated", marker = list(size = 5, color = "#1D4ED8", opacity = .7)) %>% - add_trace(data = cp, x = ~PosScaled, y = ~Tajima_D_Wild, type = "scatter", mode = "markers", - name = "Wild", marker = list(size = 5, color = "#F97316", opacity = .7)) %>% - add_segments(x = min(cp$PosScaled, na.rm = TRUE), xend = max(cp$PosScaled, na.rm = TRUE), - y = input$tajima_threshold, yend = input$tajima_threshold, - line = list(color = "#DC2626", dash = "dash", width = 1.5)) %>% - layout(title = "Tajima's D", - xaxis = list(title = "Chromosome", ticktext = chroms, - tickvals = tapply(cp$PosScaled, cp$Chromosome, median, na.rm = TRUE), tickangle = 45, gridcolor = "#F1F5F9"), - yaxis = list(title = "Tajima's D", gridcolor = "#F1F5F9"), - plot_bgcolor = "#FFFFFF", paper_bgcolor = "#FFFFFF", font = list(color = "#475569")) - }) - - output$performance_plot <- renderPlotly({ - req(values$performance_metrics) - plot_ly(data = values$performance_metrics, x = ~Metric, y = ~Value, type = "bar", - marker = list(color = c("#1D4ED8","#3B82F6","#15803D","#22C55E")), - text = ~round(Value, 3), textposition = "outside") %>% - layout(title = "Model Performance", - yaxis = list(title = "Value", range = c(0, 1.1), gridcolor = "#F1F5F9"), - xaxis = list(gridcolor = "#F1F5F9"), - plot_bgcolor = "#FFFFFF", paper_bgcolor = "#FFFFFF", font = list(color = "#475569")) + output$fst_plot <- renderPlotly({ req(rv$sel_metrics); create_man_plotly(rv$sel_metrics,"Fst","Fst",input$fst_thr,"Fst") }) + output$tajima_plot <- renderPlotly({ req(rv$sel_metrics); create_man_plotly(rv$sel_metrics,"Tajima_D_Dom","Tajima's D",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), rownames=FALSE) %>% + formatRound(c("Fst","Pi_Dom","Pi_Wild","Tajima_D_Dom"),3) }) - output$regression_plot_train <- renderPlotly({ - req(values$train_predictions) - plot_ly(data = values$train_predictions, x = ~Observed, y = ~Predicted, - type = "scatter", mode = "markers", marker = list(size = 6, color = "#1D4ED8", opacity = .7)) %>% - add_trace(x = range(values$train_predictions$Observed), y = range(values$train_predictions$Observed), - type = "scatter", mode = "lines", line = list(color = "#DC2626", dash = "dash")) %>% - layout(title = "Training Set", - xaxis = list(title = "Observed", gridcolor = "#F1F5F9"), - yaxis = list(title = "Predicted", gridcolor = "#F1F5F9"), - plot_bgcolor = "#FFFFFF", paper_bgcolor = "#FFFFFF", font = list(color = "#475569")) - }) - - output$regression_plot_test <- renderPlotly({ - req(values$test_predictions) - plot_ly(data = values$test_predictions, x = ~Observed, y = ~Predicted, - type = "scatter", mode = "markers", marker = list(size = 6, color = "#15803D", opacity = .7)) %>% - add_trace(x = range(values$test_predictions$Observed), y = range(values$test_predictions$Observed), - type = "scatter", mode = "lines", line = list(color = "#DC2626", dash = "dash")) %>% - layout(title = "Validation Set", - xaxis = list(title = "Observed", gridcolor = "#F1F5F9"), - yaxis = list(title = "Predicted", gridcolor = "#F1F5F9"), - plot_bgcolor = "#FFFFFF", paper_bgcolor = "#FFFFFF", font = list(color = "#475569")) - }) - - # ============================================================ - # TABLES - # ============================================================ - output$qtl_effects_table_train <- renderDT({ - req(values$qtl_effects_train) - if ("Message" %in% colnames(values$qtl_effects_train)) - return(datatable(data.frame(Status = values$qtl_effects_train$Message[1]), options = list(dom = "t"))) - display_cols <- intersect( - c("Marker","Chromosome","Position","LOD","P_Value", - "PVE_Marker_Percent","PVE_CIM_Percent", - "Additive_Effect","SE_Additive","CI_Lower","CI_Upper", - "Dominance_Effect","SE_Dominance","Dominance_Ratio","Dominance_Class", - "N_Cofactors","N_Samples","N_Heterozygotes", - "Interval_Start","Interval_End","Interval_Size_Mb", - "Low_Flank","High_Flank"), - colnames(values$qtl_effects_train)) - datatable(values$qtl_effects_train[, display_cols], - options = list(pageLength = 10, scrollX = TRUE), rownames = FALSE, - caption = tags$caption(style = "caption-side:top;font-size:11px;color:#475569;", - "PVE_CIM = semi-partial R² (% of cofactor-residual variance) | PVE_Marker = unconditional R² | Interval = LOD-1.5")) %>% - formatRound(intersect(c("LOD","PVE_Marker_Percent","PVE_CIM_Percent", - "Additive_Effect","SE_Additive","CI_Lower","CI_Upper", - "Dominance_Effect","SE_Dominance","Dominance_Ratio","Interval_Size_Mb"), display_cols), 3) %>% - formatSignif(intersect("P_Value", display_cols), digits = 3) - }) - - output$epistasis_table <- renderDT({ - req(values$epistasis_sig) - if ("Message" %in% colnames(values$epistasis_sig)) - return(datatable(data.frame(Status = values$epistasis_sig$Message[1]), options = list(dom = "t"))) - datatable(values$epistasis_sig[order(values$epistasis_sig$Interaction_p), ], - options = list(pageLength = 10, scrollX = TRUE), rownames = FALSE) %>% - formatSignif(c("Interaction_p","Effect_Size"), digits = 4) - }) - - output$selection_table <- renderDT({ - req(values$selection_metrics) - if ("Message" %in% colnames(values$selection_metrics)) - return(datatable(data.frame(Status = values$selection_metrics$Message[1]), options = list(dom = "t"))) - df <- values$selection_metrics - if (!is.null(values$qtl_effects_train) && !"Message" %in% colnames(values$qtl_effects_train)) - df$QTL_Overlap <- df$Marker %in% values$qtl_effects_train$Marker - dc <- intersect(c("Marker","Chromosome","Fst","Pi_Dom","Pi_Wild","Tajima_D_Dom","Significant","QTL_Overlap"), colnames(df)) - datatable(df[order(-df$Fst), dc], options = list(pageLength = 10, scrollX = TRUE), rownames = FALSE) %>% - formatRound(c("Fst","Pi_Dom","Pi_Wild","Tajima_D_Dom"), 3) - }) - - # ============================================================ - # CHROMOSOME VISUALIZATION (interactive, on-screen) - # ============================================================ - output$chromosome_viz <- renderUI({ - req(values$qtl_effects_train, values$all_markers, values$cim_all) - if ("Message" %in% colnames(values$qtl_effects_train)) - return(div(class = "alert alert-info", values$qtl_effects_train$Message[1])) - - chromosomes <- unique(values$qtl_effects_train$Chromosome) - tagList(lapply(chromosomes, function(chr) { - chr_markers <- values$all_markers[values$all_markers$Chromosome == chr, ] - chr_markers <- chr_markers[order(chr_markers$Position), ] - chr_qtls <- values$qtl_effects_train[values$qtl_effects_train$Chromosome == chr, ] - sel_markers <- NULL - if (!is.null(values$selection_metrics) && !"Message" %in% colnames(values$selection_metrics)) - sel_markers <- values$selection_metrics[values$selection_metrics$Chromosome == chr & isTRUE(values$selection_metrics$Significant), ] - - min_pos <- min(chr_markers$Position, na.rm = TRUE) - max_pos <- max(chr_markers$Position, na.rm = TRUE) - range_pos <- max_pos - min_pos - flanking_markers <- c(chr_qtls$Low_Flank, chr_qtls$High_Flank) - flanking_markers <- flanking_markers[!is.na(flanking_markers) & flanking_markers != ""] - - div(class = "chromosome-container", - div(class = "chromosome-title", - paste("Chromosome", chr, "—", nrow(chr_markers), "markers,", nrow(chr_qtls), "QTLs"), - if (nrow(chr_qtls) > 0 && "Interval_Size_Mb" %in% colnames(chr_qtls)) { - sizes <- chr_qtls$Interval_Size_Mb[!is.na(chr_qtls$Interval_Size_Mb)] - if (length(sizes) > 0) tags$span(style = "color:#C0392B;margin-left:8px;font-weight:normal;", - paste0("(LOD-1.5: ", paste(round(sizes, 2), collapse=", "), " cM)")) - } - ), - div(class = "chromosome", style = "position:relative;", - lapply(1:nrow(chr_qtls), function(j) { - qtl_row <- chr_qtls[j, ] - if (!is.na(qtl_row$Interval_Start) && range_pos > 0) { - left_pct <- ((qtl_row$Interval_Start - min_pos) / range_pos) * 100 - right_pct <- ((qtl_row$Interval_End - min_pos) / range_pos) * 100 - div(class = "interval-band", style = paste0("left:", round(left_pct, 2), "%;width:", round(max(0.5, right_pct - left_pct), 2), "%;")) - } - }), - lapply(1:nrow(chr_markers), function(i) { - marker <- chr_markers[i, ] - left <- if (range_pos > 0 && !is.na(range_pos)) ((marker$Position - min_pos) / range_pos) * 100 else (i / nrow(chr_markers)) * 100 - mclass <- "chromosome-marker" - if (marker$Marker %in% chr_qtls$Marker) { - mclass <- paste(mclass, "significant") - } else if (!is.null(sel_markers) && nrow(sel_markers) > 0 && marker$Marker %in% sel_markers$Marker) { - mclass <- paste(mclass, "selection") - } else if (marker$Marker %in% flanking_markers) { - mclass <- paste(mclass, "flanking") - } - div(class = mclass, style = paste0("left:", round(left, 2), "%;"), - title = paste0(marker$Marker, " pos:", round(marker$Position, 1), " cM")) - }) - ), - div(class = "chromosome-legend", - span(paste(round(min_pos, 1), "cM")), - span(paste(round(max_pos, 1), "cM")) - ) - ) - })) - }) - - observeEvent(input$simulate_btn, session$sendCustomMessage("simulateQTLDiscovery", list())) - observeEvent(input$reset_btn, session$sendCustomMessage("resetAnimation", list())) - - # ============================================================ - # DOWNLOADS - # ============================================================ - - # Manhattan plot — ggplot2 PNG (unchanged) - output$download_manhattan_plot <- downloadHandler( - filename = function() paste0("manhattan_cim_v5_", Sys.Date(), ".png"), - content = function(file) { - req(values$cim_all) - p <- make_ggplot_manhattan(values$cim_all, values$lod_threshold, "CIM Manhattan Plot — LOD Scores (v5)") - if (is.null(p)) p <- ggplot() + labs(title = "No data") + theme_bw() - ggsave(file, plot = p, width = 14, height = 6, dpi = 200, bg = "white") + # ── DOWNLOADS ───────────────────────────────────────────── + output$dl_manhattan <- downloadHandler( + filename=function() paste0("manhattan_v6_",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),] + pd$Chromosome <- as.character(pd$Chromosome) + 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 + } + pd$cum_pos <- pd$Position + offsets[pd$Chromosome] + pd$sig <- pd$LOD >= rv$lod_thr + chr_colors <- rep(c("#2563EB","#64748B"),ceiling(length(chroms)/2))[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.2,alpha=.7,show.legend=FALSE) + + geom_point(data=pd[pd$sig,],color="#DC2626",size=3,shape=18) + + geom_hline(yintercept=rv$lod_thr,linetype="dashed",color="#DC2626",linewidth=.6) + + 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 ≥ ",rv$lod_thr," | ",sum(pd$sig,na.rm=TRUE)," sig. QTLs"), + x="Chromosome",y="LOD Score") + + theme_bw(base_size=12) + + theme(panel.background=element_rect(fill="white"),plot.background=element_rect(fill="white"), + panel.grid.minor=element_blank(),panel.grid.major.x=element_blank(), + axis.text.x=element_text(angle=45,hjust=1),plot.title=element_text(face="bold")) + 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="#DC2626",segment.color="#DC2626") + ggsave(file,plot=p,width=14,height=6,dpi=200,bg="white") } ) - # ── FIX: Chromosome map now downloads as HTML identical to on-screen display ── - output$download_chromosome_plot <- downloadHandler( - filename = function() paste0("chromosome_map_v5_", Sys.Date(), ".html"), - content = function(file) { - req(values$qtl_effects_train, values$all_markers) - if ("Message" %in% colnames(values$qtl_effects_train)) { - writeLines(paste0( - '', - '

No QTL data available. Run CIM analysis first.

', - ''), file) - return() - } - html_content <- make_html_chromosome_viz( - qtl_effects = values$qtl_effects_train, - all_markers_df = values$all_markers, - lod_threshold = values$lod_threshold - ) - if (is.null(html_content)) { - writeLines('

Error generating chromosome visualization.

', file) - } else { - writeLines(html_content, file) + output$dl_idiogram <- downloadHandler( + filename=function() paste0("chromosome_idiogram_v6_",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 + # Also add compare results if available + 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 (length(res_list)==0) return() + png(file, width=1800, height=900, res=150, bg="white") + par(bg="white") + make_chromosome_idiogram(res_list, rv$all_markers, rv$lod_thr) + dev.off() } ) - # CIM results XLSX (unchanged) - output$download_train_results <- downloadHandler( - filename = function() paste0("cim_results_v5_", Sys.Date(), ".xlsx"), - content = function(file) { + output$dl_results <- downloadHandler( + filename=function() paste0("qtl_results_v6_",Sys.Date(),".xlsx"), + content=function(file) { sheets <- list() - if (!is.null(values$qtl_effects_train) && !"Message" %in% colnames(values$qtl_effects_train)) - sheets[["CIM_QTL_Results"]] <- values$qtl_effects_train - if (!is.null(values$cim_all) && !"Message" %in% colnames(values$cim_all)) - sheets[["CIM_Full_Scan"]] <- values$cim_all - if (!is.null(values$performance_metrics)) - sheets[["Performance"]] <- values$performance_metrics - sheets[["Method_v5"]] <- data.frame( - Item = c("Version","PVE_CIM_Formula","PVE_Marker_Formula", - "Why_v4_PVE_Was_Low","Additive_Coding", - "QTL_Interval","Cofactor_Cap","References"), - Description = c( - "CIM v5 — semi-partial R² PVE (fixed from v4)", - "(RSS_cofactors_only - RSS_with_marker) / RSS_cofactors_only × 100 [semi-partial R²]", - "R² of lm(Y ~ a_code + d_code) × 100 [unconditional, no cofactors]", - "v4 used SS_total_raw as denominator → tiny PVE when cofactors dominate. v5 uses RSS_reduced.", - "a_code = genotype - 1 → -1/0/+1 (AA/Aa/aa); standard QTL convention", - "LOD-1.5 support interval: all markers within 1.5 LOD of peak", - "min(K_user, floor(sqrt(n_samples))) — adaptive to prevent over-absorption", - "Zeng(1993) PNAS; Lander&Botstein(1989) Genetics; Lynch&Walsh(1998); Falconer&Mackay(1996)"), - stringsAsFactors = FALSE) - write_xlsx(sheets, file) + if (!is.null(rv$sig_qtl) && !"Message"%in%colnames(rv$sig_qtl)) sheets[["QTL_Significant"]] <- rv$sig_qtl + if (!is.null(rv$scan_all) && !"Message"%in%colnames(rv$scan_all)) 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>=rv$lod_thr & !is.na(r$LOD),] + } + 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") + writexl::write_xlsx(sheets, file) } ) - # ── FIX: Added predicted test phenotype download handler ── - output$download_predicted_test <- downloadHandler( - filename = function() paste0("predicted_test_phenotype_", Sys.Date(), ".xlsx"), - content = function(file) { - req(values$predicted_test_phenotype_data) - write_xlsx( - list(Predicted_Phenotypes = values$predicted_test_phenotype_data), - file - ) + output$dl_pred <- downloadHandler( + filename=function() paste0("predicted_phenotypes_",Sys.Date(),".xlsx"), + content=function(file) { + req(rv$pred_test) + writexl::write_xlsx(list(Predictions=rv$pred_test), file) } ) - # Selection results XLSX (unchanged) - output$download_selection <- downloadHandler( - filename = function() paste0("selection_", Sys.Date(), ".xlsx"), - content = function(file) { - if (!is.null(values$selection_metrics) && !"Message" %in% colnames(values$selection_metrics)) - write_xlsx(list(Selection = values$selection_metrics), file) - else - write_xlsx(list(Message = data.frame(msg = "No results yet")), 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) + else writexl::write_xlsx(list(Empty=data.frame(msg="Run domestication first")), file) } ) - # ============================================================ - # INTERPRETATION - # ============================================================ - output$analysis_summary <- renderUI({ - has_qtl <- !is.null(values$qtl_effects_train) && !"Message" %in% colnames(values$qtl_effects_train) - has_perf <- !is.null(values$performance_metrics) - n_qtl <- if (has_qtl) nrow(values$qtl_effects_train) else 0 - val_r2 <- if (has_perf) round(values$performance_metrics$Value[values$performance_metrics$Metric == "R² (Validation)"], 3) else "N/A" - max_pve <- if (has_qtl) round(max(values$qtl_effects_train$PVE_CIM_Percent, na.rm = TRUE), 1) else NA - max_pve_m <- if (has_qtl) round(max(values$qtl_effects_train$PVE_Marker_Percent, na.rm = TRUE), 1) else NA - avg_int <- if (has_qtl && "Interval_Size_Mb" %in% colnames(values$qtl_effects_train)) - round(mean(values$qtl_effects_train$Interval_Size_Mb, na.rm = TRUE), 2) else NA - div( - tags$h5("CIM v5 Analysis Summary"), - tags$p(paste(n_qtl, "QTLs detected above LOD", values$lod_threshold, "| Validation R²:", val_r2)), - if (!is.na(max_pve_m)) tags$p(paste("Max PVE_marker (unconditional R²):", max_pve_m, "%")), - if (!is.na(max_pve)) tags$p(paste("Max PVE_CIM (semi-partial R²):", max_pve, "% of cofactor-residual variance")), - if (!is.na(avg_int)) tags$p(paste("Mean LOD-1.5 interval:", avg_int, "Mb")), - tags$p(style = "color:#15803D;font-size:12px;", - tags$i(class = "fas fa-check-circle"), - " v5: semi-partial R² ✓ | -1/0/+1 coding ✓ | LOD-1.5 intervals ✓ | adaptive cofactors ✓ | HTML chr download ✓ | predicted phenotype download ✓") - ) - }) + # ── CHAT ────────────────────────────────────────────────── + add_msg <- function(role, content) { + rv$chat_msgs <- c(rv$chat_msgs, + list(list(role=role, content=content, time=format(Sys.time(),"%H:%M")))) + session$sendCustomMessage("scrollChat", list()) + } - output$qtl_interpretation <- renderUI({ - if (is.null(values$qtl_effects_train) || "Message" %in% colnames(values$qtl_effects_train)) - return(div(tags$h5("QTL Significance"), tags$p("No significant QTLs detected."))) - top <- values$qtl_effects_train[which.max(values$qtl_effects_train$LOD), ] - int_size <- if (!is.na(top$Interval_Size_Mb)) paste0(round(top$Interval_Size_Mb, 2), " Mb") else "N/A" - div( - tags$h5("Top QTL (by LOD)"), - tags$p(paste(top$Marker, "— Chr", top$Chromosome, "— LOD =", round(top$LOD, 2))), - tags$p(paste("LOD-1.5 interval:", format(top$Interval_Start, big.mark=","), "—", format(top$Interval_End, big.mark=","), "bp (", int_size, ")")), - tags$p(paste("Flanking:", top$Low_Flank, "↔", top$High_Flank)), - tags$p(paste("PVE_marker (unconditional):", round(top$PVE_Marker_Percent, 1), "%")), - tags$p(paste("PVE_CIM (semi-partial):", round(top$PVE_CIM_Percent, 1), "% of cofactor-residual variance")) - ) - }) + rule_response <- function(q) { + ql <- tolower(q) + has_scan <- !is.null(rv$scan_all) && !"Message"%in%colnames(rv$scan_all) + has_qtl <- !is.null(rv$sig_qtl) && !"Message"%in%colnames(rv$sig_qtl) - output$effect_interpretation <- renderUI({ - if (is.null(values$qtl_effects_train) || "Message" %in% colnames(values$qtl_effects_train)) - return(div(tags$h5("Effect Sizes"), tags$p("No QTL effects yet."))) - top <- values$qtl_effects_train[which.max(values$qtl_effects_train$PVE_Marker_Percent), ] - dom <- if (!is.na(top$Dominance_Effect)) - paste0("Dominance = ", round(top$Dominance_Effect, 3), " (", top$Dominance_Class, ")") - else "No heterozygotes (additive model only)" - div( - tags$h5("Largest PVE_marker QTL"), - tags$p(paste(top$Marker, "—", round(top$PVE_Marker_Percent, 1), "% unconditional PVE")), - tags$p(paste("Additive effect (a, -1/0/+1 coding) =", round(top$Additive_Effect, 3))), - tags$p(dom) - ) + if (grepl("top qtl|best qtl|significant",ql) && has_qtl) { + top5 <- head(rv$sig_qtl, 5) + out <- "🎯 **Top QTLs:**\n\n" + for (i in 1:nrow(top5)) { + r <- top5[i,] + out <- paste0(out,i,". **",r$Marker,"** (Chr ",r$Chromosome," @ ",round(r$Position,1)," cM)\n", + " LOD: ",round(r$LOD,2)," | PVE_marker: ",round(r$PVE_Marker_Percent,1),"% | Add: ",round(r$Additive_Effect,3),"\n\n") + } + return(out) + } + if (grepl("chromosom|chr debug|other chrom|missing chr",ql)) { + if (has_scan) { + chr_tbl <- table(rv$scan_all$Chromosome[rv$scan_all$LOD>=rv$lod_thr & !is.na(rv$scan_all$LOD)]) + return(paste0("📊 **QTLs per chromosome:**\n\n",paste(paste0("Chr",names(chr_tbl),": ",chr_tbl," QTL(s)"),collapse="\n"), + "\n\nTotal chromosomes scanned: ", length(unique(rv$scan_all$Chromosome)))) + } + return("Run analysis first to see chromosome results.") + } + if (grepl("sim|cim|differ|method|model",ql)) + return("📐 **Mapping Models:**\n\n**SIM**: Single-marker regression, no cofactors, simplest, most false positives\n**CIM**: Cofactor-controlled — reduces noise from linked QTLs\n**MQM**: Forward stepwise — builds multi-QTL model iteratively\n**LASSO**: L1 penalty — selects sparse set of causal markers\n**Ridge**: L2 penalty — shrinks all marker effects simultaneously\n\nFor most cross populations: CIM is standard. For GWAS-style: LASSO.") + if (grepl("pve|semi.partial|variance",ql)) + return("📊 **PVE in v6:**\n\n**PVE_marker** = R² of lm(Y ~ a_code + d_code) — unconditional, compare across studies\n**PVE_CIM** = (RSS_reduced − RSS_full) / RSS_reduced × 100 — semi-partial R² (fraction of residual variance after cofactors)\n\nNote: PVE_CIM > PVE_marker is possible if cofactors increase residual variance unusually.") + paste0("👋 **QTL-Mapper v6 AI**\n\nv6 Fixes: multi-chromosome scan ✓ | 5 mapping models ✓ | chromosome idiogram ✓ | proper Manhattan ✓\n\nQuick links: **Top QTLs** | **CIM vs SIM** | **Chr debug** | **PVE explained**") + } + + process_chat <- function(user_text) { + if (nchar(trimws(user_text))==0) return() + add_msg("user", user_text) + rv$is_typing <- TRUE + if (token_exists) { + ctx <- "" + if (!is.null(rv$scan_all) && !"Message"%in%colnames(rv$scan_all)) { + sig <- rv$scan_all[rv$scan_all$LOD>=rv$lod_thr & !is.na(rv$scan_all$LOD),] + ctx <- paste0("Analysis done: ",nrow(sig)," QTLs on ",length(unique(rv$scan_all$Chromosome))," chromosomes. Method: ",input$mapping_method,". ") + } + res <- query_ai(paste0(ctx, "User: ", user_text)) + if (res$success) { rv$is_typing <- FALSE; add_msg("assistant", res$text); return() } + } + resp <- rule_response(user_text) + rv$is_typing <- FALSE + add_msg("assistant", resp) + } + + observeEvent(input$send_chat, { + txt <- trimws(input$chat_input); if(nchar(txt)==0) return() + updateTextAreaInput(session,"chat_input",value=""); process_chat(txt) }) + observeEvent(input$qq, { req(input$qq); process_chat(input$qq) }) + observeEvent(input$clear_chat, { rv$chat_msgs <- list(); add_msg("assistant","Chat cleared.") }) - output$epistasis_interpretation <- renderUI({ - if (is.null(values$epistasis_sig) || "Message" %in% colnames(values$epistasis_sig) || nrow(values$epistasis_sig) == 0) - return(div(tags$h5("Epistasis"), tags$p("No significant interactions detected."))) - top <- values$epistasis_sig[which.min(values$epistasis_sig$Interaction_p), ] - div(tags$h5("Epistasis"), - tags$p(paste(nrow(values$epistasis_sig), "interactions. Strongest:", top$QTL1, "×", top$QTL2, - "(p =", format.pval(top$Interaction_p, digits = 3), ")"))) + observe({ + if (length(rv$chat_msgs)==0) + add_msg("assistant", paste0( + "👋 **QTL-Mapper v6**\n\n", + "**New in v6:**\n", + "• 5 mapping models: SIM, CIM, MQM, LASSO, Ridge\n", + "• Multi-chromosome fixed — all chromosomes now scan correctly\n", + "• Chromosome idiogram matching reference style\n", + "• Compare Models tab — overlay multiple methods\n\n", + "Upload data → choose method → Run QTL Analysis\n", + "Contact: ashmithamganesan@gmail.com, P.sinha@cgiar.org" + )) }) - output$recommendations <- renderUI({ - has_qtl <- !is.null(values$qtl_effects_train) && !"Message" %in% colnames(values$qtl_effects_train) - recs <- if (has_qtl) { - n_ovdom <- sum(values$qtl_effects_train$Dominance_Class == "Overdominance", na.rm = TRUE) - large_int <- if ("Interval_Size_Mb" %in% colnames(values$qtl_effects_train)) - sum(values$qtl_effects_train$Interval_Size_Mb > 10, na.rm = TRUE) else 0 - r <- c( - "Validate top CIM QTLs in independent populations", - "Use Interval_Start / Interval_End (LOD-1.5) for fine-mapping candidate gene annotation", - "PVE_CIM = semi-partial R² (% of residual variance after cofactors) — compare markers on same scale", - "PVE_marker = unconditional R² — use this to compare QTL sizes across studies", - "Sum of PVE_marker across QTLs approximates total marker-explained variance", - "Chromosome Map (.html) download = same view as on-screen; open in any browser for sharing" - ) - if (n_ovdom > 0) r <- c(r, paste(n_ovdom, "overdominant QTL(s) — consider heterosis breeding")) - if (large_int > 0) r <- c(r, paste(large_int, "QTL(s) with LOD-1.5 interval >10 Mb — increase marker density for fine-mapping")) - r - } else { - c("Upload genotype + phenotype CSV files", "Click 'Run CIM Analysis'", "Try LOD threshold = 2.0 to start") - } - div(tags$h5("Recommendations"), tags$ul(lapply(recs, tags$li), style = "color:#475569;")) + output$chat_ui <- renderUI({ + msgs <- rv$chat_msgs + elems <- lapply(msgs, function(msg) { + div(class=paste("cmsg",msg$role), + div(class="cbub", HTML(gsub("\n","
",htmltools::htmlEscape(msg$content)))), + div(class="cmeta", msg$time)) + }) + if (rv$is_typing) + elems <- c(elems, list(div(class="cmsg assistant", + div(class="typing", div(class="tdot"),div(class="tdot"),div(class="tdot"))))) + do.call(tagList, elems) }) } -shinyApp(ui = ui, server = server) \ No newline at end of file +shinyApp(ui=ui, server=server) \ No newline at end of file