diff --git "a/app.R" "b/app.R" --- "a/app.R" +++ "b/app.R" @@ -1,22 +1,35 @@ # ============================================================ -# QTL-Mapper v3 — Composite Interval Mapping (CIM) + Fixed Flanking +# QTL-Mapper v4 — Composite Interval Mapping (CIM) # -# KEY FIXES: -# 1. REPLACED Random Forest QTL mapping with Composite Interval Mapping (CIM) -# - CIM fits lm(pheno ~ marker + cofactors) at each marker position -# - Cofactors = top markers from initial RF screen (controls background) -# - LOD = -log10(p-value of marker term) -# - PVE computed from FULL model including cofactors → MUCH higher PVE +# KEY FIXES vs v3: +# 1. ADDITIVE CODING FIXED: genotype 0/1/2 → -1/0/+1 (standard QTL coding) +# - Ensures additive effect = half the allele substitution effect +# - Ref: Falconer & Mackay (1996) Eq. 7.1 # -# 2. FIXED flanking markers -# - Flanking search now uses the FULL marker list (not post-NZV subset) -# - Correctly finds adjacent markers on same chromosome by sorted position +# 2. PVE FORMULA FIXED: +# OLD (wrong): PVE_CIM = R²_full (includes cofactor variance — inflated) +# NEW (correct): PVE_CIM = partial R² of focal marker after cofactors +# = (SS_full - SS_reduced) / SS_total +# where SS_reduced = RSS of model WITHOUT focal marker (cofactors only) +# This gives the INCREMENTAL variance explained by the marker alone. # -# 3. PVE FORMULA (unchanged, still correct): -# Full model: lm(phenotype ~ a + d) [additive + dominance] -# PVE (%) = R²_full × 100 -# Additive_Effect = beta_a, Dominance_Effect = beta_d -# Reference: Falconer & Mackay (1996); Lynch & Walsh (1998) +# 3. QTL SUPPORT INTERVAL FIXED: +# OLD (wrong): flanking = adjacent markers (arbitrary — can span entire chromosome) +# NEW (correct): LOD-1.5 support interval (standard in QTL mapping) +# = all markers within 1.5 LOD units of peak LOD +# Ref: Lander & Botstein (1989); Dupuis & Siegmund (1999) +# +# 4. ADDED: Static ggplot2 downloads for Manhattan plot + Chromosome viz +# +# 5. WHITE BACKGROUND throughout UI and plots +# +# PVE FORMULAS (Falconer & Mackay 1996; Lynch & Walsh 1998): +# Additive coding: a = genotype - 1 (-1, 0, +1 for AA, Aa, aa) +# Dominance coding: d = 1 if heterozygote, else 0 +# Additive effect (a): regression coefficient of a_code +# Dominance effect (d): regression coefficient of d_code +# PVE_marker (%) = partial R² × 100 +# PVE_CIM (%) = (SS_model_with_marker - SS_model_without_marker) / SS_total × 100 # ============================================================ options(repos = c(CRAN = "https://cloud.r-project.org")) @@ -24,7 +37,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" + "shinyjs", "markdown", "base64enc", "gridExtra", "ggrepel" ) for (pkg in required_packages) { @@ -64,20 +77,18 @@ model_choices <- setNames( ) # ============================================================ -# CIM CORE FUNCTION +# CIM CORE FUNCTION — v4 CORRECTED # ============================================================ -# -# Composite Interval Mapping (Zeng 1993, 1994): -# For each marker m: -# 1. Select cofactors = top K markers from RF (excluding nearby markers on same chr) -# 2. Fit: Y ~ marker_m + cofactors (additive model) -# 3. LOD = -log10( p-value of marker_m term ) -# 4. PVE = R²_full × 100 (full model including cofactors) -# -# This gives HIGHER PVE because: -# - Cofactors absorb background genetic variance -# - Each marker's contribution is estimated after controlling for rest -# - Much more powerful than single-marker regression +# Key formula corrections: +# 1. Additive coding: a_code = genotype - 1 (maps 0→-1, 1→0, 2→+1) +# 2. Partial R² for PVE: +# fit_full = lm(Y ~ focal + cofactors) +# fit_reduced = lm(Y ~ cofactors) [no focal] +# PVE_CIM = (RSS_reduced - RSS_full) / SS_total × 100 +# 3. PVE_marker = partial R² from lm(Y ~ a_code + d_code) alone +# fit_add = lm(Y ~ a_code + d_code) +# fit_null = lm(Y ~ 1) +# PVE_marker = (RSS_null - RSS_add) / SS_total × 100 # ============================================================ run_cim <- function(genotype_matrix, phenotype_vector, marker_info, @@ -88,7 +99,7 @@ run_cim <- function(genotype_matrix, phenotype_vector, marker_info, n_markers <- length(markers) n_samples <- length(phenotype_vector) - cat("CIM: Starting with", n_markers, "markers,", n_samples, "samples\n") + cat("CIM v4: Starting with", n_markers, "markers,", n_samples, "samples\n") # ---- Step 1: Select cofactors via RF ---- valid_rows <- !is.na(phenotype_vector) @@ -105,18 +116,18 @@ run_cim <- function(genotype_matrix, phenotype_vector, marker_info, ) if (!is.null(rf_model)) { - imp_scores <- importance(rf_model, type = 1)[, 1] + 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 { # Fallback: single-marker regression ranking - p_vals <- sapply(colnames(X_valid), function(m) { + 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: Selected", length(top_cofactors), "candidate cofactors\n") + cat("CIM v4: Selected", length(top_cofactors), "candidate cofactors\n") # ---- Step 2: Scan each marker with CIM ---- results_list <- list() @@ -153,13 +164,11 @@ run_cim <- function(genotype_matrix, phenotype_vector, marker_info, active_cofactors <- active_cofactors[active_cofactors %in% colnames(genotype_matrix)] active_cofactors <- head(active_cofactors, n_cofactors) - # ---- Build data frame for model ---- - df_model <- data.frame(y = pheno_v, focal = geno_v[valid_idx]) + # ---- Build data frame ---- + df_model <- data.frame(y = pheno_v, focal = geno_v) - # Add cofactors if (length(active_cofactors) > 0) { cof_mat <- genotype_matrix[valid_idx, active_cofactors, drop = FALSE] - # Handle NAs in cofactors cof_mat[is.na(cof_mat)] <- 0 df_model <- cbind(df_model, cof_mat) } @@ -167,58 +176,78 @@ run_cim <- function(genotype_matrix, phenotype_vector, marker_info, df_model <- df_model[complete.cases(df_model), ] if (nrow(df_model) < 5) next - # ---- Fit CIM model ---- + # ---- Fit CIM models ---- tryCatch({ + SS_total <- 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)) + cof_formula <- paste(active_cofactors, collapse = " + ") + full_formula <- as.formula(paste("y ~ focal +", cof_formula)) + reduced_formula <- as.formula(paste("y ~ ", cof_formula)) } else { - full_formula <- as.formula("y ~ focal") + full_formula <- as.formula("y ~ focal") + reduced_formula <- as.formula("y ~ 1") } - fit <- lm(full_formula, data = df_model) - sm <- summary(fit) - coef_t <- sm$coefficients + 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) # avoid log(0) - r2_full <- sm$r.squared + p_val <- coef_t["focal", "Pr(>|t|)"] + lod <- -log10(p_val + 1e-300) + + # CORRECTED PVE: partial R² of focal marker + RSS_full <- sum(residuals(fit_full)^2) + RSS_reduced <- sum(residuals(fit_reduced)^2) + + # Partial R² = incremental variance explained by focal marker + pve_cim <- if (SS_total > 0) ((RSS_reduced - RSS_full) / SS_total) * 100 else NA + pve_cim <- max(0, pve_cim, na.rm = TRUE) # clamp to 0 minimum - # ---- Additive + Dominance effects (on this marker) ---- - a_code <- df_model$focal - d_code <- as.numeric(a_code == 1) + # ---- FIX: Additive coding -1/0/+1 (standard QTL convention) ---- + # genotype 0 (AA) → -1, genotype 1 (Aa) → 0, genotype 2 (aa) → +1 + a_code <- df_model$focal - 1 # KEY FIX: proper additive coding + d_code <- as.numeric(df_model$focal == 1) # dominance: 1 if het has_het <- length(unique(d_code)) > 1 if (has_het) { - lm_eff <- lm(y ~ a_code + d_code, data = df_model) - sm_eff <- summary(lm_eff) - pve_ad <- sm_eff$r.squared * 100 # PVE from add+dom ALONE (marker only) - c_eff <- coef(lm_eff) - a_eff <- c_eff["a_code"] + lm_eff <- lm(df_model$y ~ a_code + d_code) + } else { + lm_eff <- lm(df_model$y ~ a_code) + } + sm_eff <- summary(lm_eff) + + # PVE_marker = partial R² of marker alone (vs null) + fit_null <- lm(df_model$y ~ 1) + RSS_marker <- sum(residuals(lm_eff)^2) + RSS_null_m <- sum(residuals(fit_null)^2) + pve_marker <- if (SS_total > 0) ((RSS_null_m - RSS_marker) / SS_total) * 100 else NA + pve_marker <- max(0, pve_marker, na.rm = TRUE) + + c_eff <- coef(lm_eff) + a_eff <- c_eff["a_code"] + + if (has_het) { d_eff <- c_eff["d_code"] se_t <- sm_eff$coefficients se_a <- se_t["a_code", "Std. Error"] se_d <- se_t["d_code", "Std. Error"] d_rat <- if (!is.na(a_eff) && a_eff != 0) abs(d_eff / a_eff) else NA } else { - lm_eff <- lm(y ~ a_code, data = df_model) - sm_eff <- summary(lm_eff) - pve_ad <- sm_eff$r.squared * 100 - c_eff <- coef(lm_eff) - a_eff <- c_eff["a_code"] - d_eff <- NA; se_a <- NA; se_d <- NA; d_rat <- NA + d_eff <- NA; se_d <- NA; d_rat <- NA + se_t <- sm_eff$coefficients + se_a <- se_t["a_code", "Std. Error"] } - # PVE from full CIM model (marker + cofactors) — this is the HIGH PVE - pve_cim <- r2_full * 100 - - 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" + 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" results_list[[m]] <- data.frame( Marker = m, @@ -226,8 +255,8 @@ run_cim <- function(genotype_matrix, phenotype_vector, marker_info, Position = m_pos, LOD = lod, P_Value = p_val, - PVE_Marker_Percent = pve_ad, # PVE of marker alone (add+dom) - PVE_CIM_Percent = pve_cim, # PVE of full CIM model (marker + cofactors) + PVE_Marker_Percent = pve_marker, + 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), @@ -243,7 +272,7 @@ run_cim <- function(genotype_matrix, phenotype_vector, marker_info, ) }, error = function(e) { - cat("CIM error at marker", m, ":", e$message, "\n") + cat("CIM v4 error at marker", m, ":", e$message, "\n") }) } @@ -253,42 +282,76 @@ run_cim <- function(genotype_matrix, phenotype_vector, marker_info, cim_result <- do.call(rbind, results_list) cim_result <- cim_result[order(-cim_result$LOD), ] - cat("CIM: Completed scan,", nrow(cim_result), "markers evaluated\n") + cat("CIM v4: Completed scan,", nrow(cim_result), "markers evaluated\n") return(cim_result) } # ============================================================ -# FLANKING MARKER FUNCTION — FIXED -# Uses the FULL all_markers table (not post-NZV subset) +# LOD-1.5 SUPPORT INTERVAL FUNCTION (replaces flanking markers) +# Standard QTL support interval: all markers within 1.5 LOD units of peak +# Ref: Lander & Botstein (1989) Genetics; Dupuis & Siegmund (1999) # ============================================================ -add_flanking_markers <- function(sig_df, all_markers_df) { - sig_df$Low_Flank <- NA_character_ - sig_df$High_Flank <- NA_character_ +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_ 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] focal_pos <- sig_df$Position[i] - # Get ALL markers on same chromosome, sorted by position - chr_markers <- all_markers_df[all_markers_df$Chromosome == focal_chr, ] - chr_markers <- chr_markers[order(chr_markers$Position), ] + # Get all CIM results on same chromosome, sorted by position + 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_markers) == 0) next + if (nrow(chr_data) == 0) next + + # LOD-1.5 support interval: markers within 1.5 LOD of peak + lod_cutoff <- focal_lod - lod_drop + in_interval <- chr_data$LOD >= lod_cutoff - # Find position of focal marker in sorted list - idx <- which(chr_markers$Marker == focal_marker) + if (sum(in_interval) > 0) { + interval_markers <- chr_data[in_interval, ] - if (length(idx) > 0) { - sig_df$Low_Flank[i] <- if (idx > 1) chr_markers$Marker[idx - 1] else focal_marker - sig_df$High_Flank[i] <- if (idx < nrow(chr_markers)) chr_markers$Marker[idx + 1] else focal_marker + # Ensure focal marker region is included + focal_pos_candidates <- chr_data$Position[chr_data$Marker == focal_marker] + if (length(focal_pos_candidates) > 0) { + int_start <- min(interval_markers$Position, focal_pos_candidates) + int_end <- max(interval_markers$Position, focal_pos_candidates) + } else { + int_start <- min(interval_markers$Position) + int_end <- max(interval_markers$Position) + } + + 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 + + # Flanking markers = markers immediately outside the interval + 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 { - # Marker not found by name — find by closest position - dists <- abs(chr_markers$Position - focal_pos) - idx <- which.min(dists) - sig_df$Low_Flank[i] <- if (idx > 1) chr_markers$Marker[idx - 1] else focal_marker - sig_df$High_Flank[i] <- if (idx < nrow(chr_markers)) chr_markers$Marker[idx + 1] else focal_marker + # Fallback: use adjacent markers on chromosome + 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 + } } } @@ -296,7 +359,171 @@ add_flanking_markers <- function(sig_df, all_markers_df) { } # ============================================================ -# API / AI FUNCTIONS (unchanged) +# GGPLOT2 MANHATTAN PLOT (for download) +# ============================================================ + +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) + + # Assign cumulative positions for plotting + pd$Chromosome <- as.character(pd$Chromosome) + chroms <- sort(unique(pd$Chromosome), method = "radix") + chr_offsets <- c(0) + for (i in 1:(length(chroms) - 1)) { + max_pos <- max(pd$Position[pd$Chromosome == chroms[i]], na.rm = TRUE) + chr_offsets <- c(chr_offsets, chr_offsets[i] + max_pos + max_pos * 0.05) + } + names(chr_offsets) <- chroms + + pd$cum_pos <- pd$Position + chr_offsets[pd$Chromosome] + pd$sig <- pd$LOD >= lod_threshold + pd$chr_idx <- match(pd$Chromosome, chroms) + + # Chr midpoints for x-axis labels + chr_mids <- tapply(pd$cum_pos, pd$Chromosome, median, na.rm = TRUE) + + # Color alternating chromosomes + chr_colors <- rep(c("#2563EB", "#64748B"), ceiling(length(chroms) / 2))[1:length(chroms)] + names(chr_colors) <- chroms + pd$color <- chr_colors[pd$Chromosome] + + 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, ], aes(x = cum_pos, y = LOD), + color = "#DC2626", size = 2.5, 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) + ) + + # Annotate significant QTLs + 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) +} + +# ============================================================ +# GGPLOT2 CHROMOSOME VISUALIZATION (for download) +# ============================================================ + +make_ggplot_chromosome_viz <- function(qtl_effects, all_markers_df, cim_all = NULL, + 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) + + chromosomes <- unique(qtl_effects$Chromosome) + plot_list <- list() + + 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 + + # Build marker data frame + chr_markers$type <- "Background" + chr_markers$type[chr_markers$Marker %in% chr_qtls$Marker] <- "QTL" + + # Add flanking markers + flank_mks <- c(chr_qtls$Low_Flank, chr_qtls$High_Flank) + flank_mks <- flank_mks[!is.na(flank_mks) & flank_mks != ""] + is_qtl <- chr_markers$Marker %in% chr_qtls$Marker + is_flank <- chr_markers$Marker %in% flank_mks & !is_qtl + chr_markers$type[is_flank] <- "Flanking" + + # Plot + p <- ggplot() + + # Chromosome bar + annotate("rect", xmin = min_pos, xmax = max_pos, ymin = 0.3, ymax = 0.7, + fill = "#E2E8F0", color = "#94A3B8", linewidth = 0.5) + + # Background markers + geom_segment(data = chr_markers[chr_markers$type == "Background", ], + aes(x = Position, xend = Position, y = 0.2, yend = 0.8), + color = "#CBD5E1", linewidth = 0.3, alpha = 0.5) + + # Flanking markers + geom_segment(data = chr_markers[chr_markers$type == "Flanking", ], + aes(x = Position, xend = Position, y = 0.1, yend = 0.9), + color = "#2563EB", linewidth = 0.8) + + # QTL intervals (shaded) + { + if (nrow(chr_qtls) > 0 && "Interval_Start" %in% colnames(chr_qtls)) { + qtl_int <- chr_qtls[!is.na(chr_qtls$Interval_Start), ] + if (nrow(qtl_int) > 0) + annotate("rect", xmin = qtl_int$Interval_Start, xmax = qtl_int$Interval_End, + ymin = 0.1, ymax = 0.9, fill = "#FEE2E2", alpha = 0.5, color = NA) + else list() + } else list() + } + + # QTL markers + geom_segment(data = chr_markers[chr_markers$type == "QTL", ], + aes(x = Position, xend = Position, y = 0.0, yend = 1.0), + color = "#DC2626", linewidth = 2) + + # QTL labels + { + if (nrow(chr_qtls) > 0) + ggrepel::geom_label_repel( + data = chr_qtls, + aes(x = Position, y = 1.05, label = paste0(Marker, "\nLOD=", round(LOD, 1))), + size = 2.5, fill = "white", color = "#DC2626", + box.padding = 0.2, max.overlaps = 10) + else list() + } + + scale_x_continuous(labels = function(x) paste0(round(x / 1e6, 1), " Mb")) + + ylim(-0.2, 1.4) + + labs(title = paste("Chromosome", chr), + x = "Position", y = NULL) + + theme_bw(base_size = 10) + + theme( + panel.background = element_rect(fill = "white"), + plot.background = element_rect(fill = "white"), + axis.text.y = element_blank(), + axis.ticks.y = element_blank(), + panel.grid = element_blank(), + panel.border = element_blank(), + axis.line.x = element_line(color = "grey70"), + plot.title = element_text(face = "bold", size = 10, color = "#1E3A5F") + ) + + plot_list[[chr]] <- p + } + + if (length(plot_list) == 0) return(NULL) + + # Combine all chromosomes + n_cols <- min(2, length(plot_list)) + gridExtra::grid.arrange(grobs = plot_list, ncol = n_cols, + top = grid::textGrob("QTL Chromosome Map", gp = grid::gpar(fontsize = 14, fontface = "bold"))) +} + +# ============================================================ +# API / AI FUNCTIONS # ============================================================ test_api_connection <- function(model_id = default_model) { @@ -341,29 +568,22 @@ query_hf_api <- function(prompt, model_id = default_model, max_length = 500, tem } build_system_prompt <- function(rv) { - ctx <- c("CURRENT ANALYSIS RESULTS (Composite Interval Mapping):") - + ctx <- c("CURRENT ANALYSIS RESULTS (Composite Interval Mapping v4):") 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("Total PVE (CIM model, marker+cofactors): %.1f%%", if (nrow(sig) > 0) max(sig$PVE_CIM_Percent) else 0)) + sprintf("Top PVE_CIM (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, D=%s", - i, r$Marker, r$Chromosome, r$LOD, r$PVE_Marker_Percent, r$PVE_CIM_Percent, r$Additive_Effect, - ifelse(is.na(r$Dominance_Effect), "NA", as.character(round(r$Dominance_Effect, 3))))) + 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)) } } } - if (!is.null(rv$performance_metrics)) { - pm <- rv$performance_metrics - ctx <- c(ctx, sprintf("\nModel R² (Train): %.3f, R² (Validation): %.3f", - pm$Value[pm$Metric == "R² (Train)"], pm$Value[pm$Metric == "R² (Validation)"])) - } paste(ctx, collapse = "\n") } @@ -374,77 +594,88 @@ enhanced_rule_response <- function(user_message, rv) { has_qtl <- has_cim && any(rv$cim_all$LOD >= rv$lod_threshold) has_perf <- !is.null(rv$performance_metrics) - if (grepl("pve|variance explained|how much variance|percent variance|what is pve|cim", q)) { + if (grepl("pve|variance explained|partial r2|what is pve|cim", 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 Composite Interval Mapping**\n\n", - "**Two PVE values are reported:**\n", - "• `PVE_Marker_%` = R² from lm(y ~ a + d) — marker alone\n", - "• `PVE_CIM_%` = R² from full CIM model (marker + cofactors) — HIGHER\n\n", + "📊 **PVE in CIM v4 — Corrected Formulas**\n\n", + "**Two PVE values (both are partial R²):**\n", + "• `PVE_Marker_%` = (RSS_null - RSS_add_dom) / SS_total × 100\n", + " [marker alone, add+dom model vs. null]\n", + "• `PVE_CIM_%` = (RSS_reduced - RSS_full) / SS_total × 100\n", + " [incremental contribution of marker AFTER controlling for cofactors]\n\n", + "**Additive coding (FIXED in v4):** genotype -1/0/+1 (not 0/1/2)\n\n", "**Top QTL:** ", top_pve$Marker, " (Chr ", top_pve$Chromosome, ")\n", "• LOD: ", round(top_pve$LOD, 2), "\n", - "• PVE (marker alone): ", round(top_pve$PVE_Marker_Percent, 1), "%\n", - "• PVE (CIM full model): ", round(top_pve$PVE_CIM_Percent, 1), "%\n", - "• Additive: ", round(top_pve$Additive_Effect, 3), "\n", - "• Dominance: ", ifelse(is.na(top_pve$Dominance_Effect), "NA", round(top_pve$Dominance_Effect, 3)), "\n\n", - "CIM PVE is higher because cofactors absorb background genetic variance,\n", - "letting each QTL's true contribution be measured more accurately." + "• PVE_marker: ", round(top_pve$PVE_Marker_Percent, 1), "%\n", + "• PVE_CIM (partial R²): ", round(top_pve$PVE_CIM_Percent, 1), "%\n", + "• Additive effect: ", round(top_pve$Additive_Effect, 3) )) } return("Run CIM analysis first to see PVE values.") } + 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\n" + out <- paste0(out, "Standard method: interval = all markers within 1.5 LOD of peak\n", + "Ref: 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.") + } + 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 (Composite Interval Mapping)**\n\n" + out <- "🎯 **Top QTLs by LOD (CIM v4)**\n\n" for (i in 1:nrow(top5)) { r <- top5[i, ] - dom <- ifelse(is.na(r$Dominance_Effect), "NA", as.character(round(r$Dominance_Effect, 3))) 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", - " • Flanking: ", r$Low_Flank, " ↔ ", r$High_Flank, "\n\n") + " • Additive: ", round(r$Additive_Effect, 3), "\n\n") } return(out) } return("No significant QTLs detected. Try lowering the LOD threshold.") } - if (grepl("flank|interval|region|boundary", q)) { - if (has_qtl) { - sig <- rv$cim_all[rv$cim_all$LOD >= rv$lod_threshold, ] - out <- "🧬 **QTL Flanking Markers (Fixed)**\n\n" - for (i in 1:min(5, nrow(sig))) { - r <- sig[i, ] - out <- paste0(out, r$Marker, ": [", r$Low_Flank, "] ← QTL → [", r$High_Flank, "]\n") - } - return(out) - } - return("Run analysis first to see flanking markers.") - } - 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² — likely overfitting or small sample.\n", - "Try increasing sample size or reducing cofactors (lower n_cofactors).") + out <- paste0(out, "⚠️ Negative validation R² — overfitting or small sample.\n", + "Try increasing sample size or reducing cofactors.") } else if (val_r2 >= 0.5) { out <- paste0(out, "🎯 Excellent validation R²!") } return(out) } - paste0("👋 Vanakam! TerraByte-AI here (CIM mode).\n\n", - "Ask me about:\n• **PVE / CIM** — how variance is explained\n", - "• **Top QTLs** — flanking markers included\n• **Model performance**\n", - "• **What is CIM?** — Composite Interval Mapping explained\n\n", + paste0("👋 Vanakam! TerraByte-AI (CIM v4 — corrected formulas)\n\n", + "Fixes in v4:\n", + "• Additive coding: -1/0/+1 (standard QTL convention)\n", + "• PVE_CIM: partial R² (incremental, not inflated)\n", + "• QTL interval: LOD-1.5 support interval (not adjacent markers)\n\n", + "Ask me about:\n• **PVE / CIM** — what changed\n", + "• **Intervals / flanking** — LOD-1.5 support\n", + "• **Top QTLs** | **Model performance**\n\n", "Contact: ashmithamganesan@gmail.com, P.sinha@cgiar.org") } @@ -460,7 +691,7 @@ generate_ai_response <- function(user_message, rv, model_id = default_model) { } # ============================================================ -# UI +# UI — WHITE BACKGROUND # ============================================================ ui <- fluidPage( @@ -501,68 +732,106 @@ ui <- fluidPage( }); ")), tags$style(HTML(" + /* ===================== WHITE THEME ===================== */ :root { - --bg-primary:#0d1117;--bg-secondary:#161b22;--bg-tertiary:#21262d; - --border:#30363d;--text-primary:#e6edf3;--text-secondary:#8b949e; - --text-muted:#6e7681;--accent:#58a6ff;--accent-hover:#79c0ff; - --success:#3fb950;--warning:#d29922;--danger:#f85149; - --purple:#bc8cff;--teal:#39d353; - --font-mono:'IBM Plex Mono',monospace;--font-sans:'IBM Plex Sans',sans-serif; + --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; } *{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:var(--bg-secondary)!important;border-bottom:1px solid var(--border);} - .navbar-brand{color:var(--text-primary)!important;font-family:var(--font-mono);font-weight:600;} + + /* Navbar */ + .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,#1c2b3a,#0d1117);border:1px solid var(--border);border-left:3px solid var(--accent);padding:20px 24px;border-radius:6px;margin-bottom:20px;} - .main-header h2{font-family:var(--font-mono);font-size:1.3rem;font-weight:600;color:var(--accent);} + + /* Header */ + .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:#0d1a0d;border:1px solid var(--success);border-left:3px solid var(--success);border-radius:6px;padding:12px 16px;margin:10px 0;font-family:var(--font-mono);font-size:12px;color:#7ee787;} + + /* CIM info box */ + .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;} - .card{background:var(--bg-secondary);border:1px solid var(--border);border-radius:6px;margin-bottom:20px;} - .card-header{background:var(--bg-tertiary);border-bottom:1px solid var(--border);padding:12px 16px;font-family:var(--font-mono);font-size:12px;color:var(--text-secondary);letter-spacing:.5px;text-transform:uppercase;} + + /* Fix box */ + .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;} + + /* Cards */ + .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:var(--bg-tertiary)!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(88,166,255,.2)!important;} + + /* Forms */ + .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;} + + /* Buttons */ .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:#0d1117;} - .btn-primary:hover{background:var(--accent-hover);border-color:var(--accent-hover);color:#0d1117;} + .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:#0d1117;} + .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;} + + /* Tables */ .dataTables_wrapper{color:var(--text-secondary)!important;} - table.dataTable{background:var(--bg-secondary)!important;color:var(--text-primary)!important;border-color:var(--border)!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;} - table.dataTable tbody tr:hover{background:var(--bg-tertiary)!important;} + 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:var(--bg-tertiary)!important;border:1px solid var(--border)!important;color:var(--text-primary)!important;border-radius:3px;} + .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:#0d1117!important;border-color:var(--accent)!important;} - .chromosome-container{margin:12px 0;padding:12px 16px;background:var(--bg-tertiary);border-radius:4px;border:1px solid var(--border);} - .chromosome{height:24px;background:linear-gradient(to right,var(--bg-primary),var(--border));border-radius:12px;margin:8px 0;position:relative;overflow:hidden;border:1px solid var(--border);} - .chromosome-marker{position:absolute;height:34px;width:6px;background:var(--text-muted);border-radius:3px;top:-5px;transform:translateX(-50%);transition:all .3s ease;} - .chromosome-marker.significant{background:var(--danger)!important;height:40px!important;width:8px!important;top:-8px!important;} + .paginate_button.current{background:var(--accent)!important;color:white!important;border-color:var(--accent)!important;} + + /* Chromosome viz */ + .chromosome-container{margin:12px 0;padding:12px 16px;background:#FFFFFF;border-radius:6px;border:1px solid var(--border);box-shadow:0 1px 2px rgba(0,0,0,.04);} + .chromosome{height:24px;background:linear-gradient(to right,#F1F5F9,#E2E8F0);border-radius:12px;margin:8px 0;position:relative;overflow:hidden;border:1px solid #CBD5E1;} + .chromosome-marker{position:absolute;height:34px;width:6px;background:#94A3B8;border-radius:3px;top:-5px;transform:translateX(-50%);transition:all .3s ease;} + .chromosome-marker.significant{background:var(--danger)!important;height:42px!important;width:9px!important;top:-9px!important;box-shadow:0 0 6px rgba(220,38,38,.4);} .chromosome-marker.flanking{background:var(--accent)!important;height:30px!important;width:5px!important;top:-3px!important;} .chromosome-marker.selection{background:var(--success)!important;} - .chromosome-marker.highlighted{background:var(--warning)!important;box-shadow:0 0 10px rgba(210,153,34,.6);} + .chromosome-marker.interval{background:#FBBF24!important;height:26px!important;width:4px!important;top:-1px!important;opacity:.7;} + .chromosome-marker.highlighted{background:var(--warning)!important;box-shadow:0 0 10px rgba(180,83,9,.5);} .chromosome-marker.pulse{animation:pulse 1.5s infinite;} @keyframes pulse{0%,100%{transform:translateX(-50%) scale(1);}50%{transform:translateX(-50%) scale(1.3);opacity:.7;}} .chromosome-legend{display:flex;justify-content:space-between;font-size:10px;color:var(--text-muted);font-family:var(--font-mono);margin-top:2px;} .chromosome-title{font-family:var(--font-mono);font-size:11px;color:var(--accent);margin-bottom:4px;} + .interval-band{position:absolute;top:0;bottom:0;background:rgba(220,38,38,.12);border:1px solid rgba(220,38,38,.2);} + .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 */ #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(88,166,255,.4);transition:all .2s;color:#0d1117;font-size:24px;} + #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:var(--bg-secondary);border:1px solid var(--accent);border-radius:12px;overflow:hidden;box-shadow:0 8px 40px rgba(0,0,0,.5);margin-bottom:10px;height:640px;} + #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,var(--bg-tertiary),#1c2b3a);border-bottom:1px solid var(--border);padding:12px 16px;display:flex;flex-direction:column;gap:8px;} + #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:#0d1117;font-weight:bold;flex-shrink:0;} + .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);} @@ -570,66 +839,72 @@ ui <- fluidPage( #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:var(--bg-primary)!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;} + .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:var(--bg-primary);} + #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),#3a7bd5);color:#0d1117;border-bottom-right-radius:4px;} - .chat-msg.assistant .chat-bubble{background:var(--bg-tertiary);color:var(--text-primary);border:1px solid var(--border);border-bottom-left-radius:4px;} + .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:var(--bg-tertiary);border:1px solid var(--border);border-radius:16px;border-bottom-left-radius:4px;width:fit-content;} - .typing-dot{width:8px;height:8px;background:var(--text-muted);border-radius:50%;animation:typingBounce 1.4s infinite;} + .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:var(--bg-secondary);} - .quick-q-btn{background:var(--bg-tertiary);border:1px solid var(--border);color:var(--text-secondary);border-radius:16px;padding:4px 12px;font-size:11px;cursor:pointer;transition:all .15s;} - .quick-q-btn:hover{border-color:var(--accent);color:var(--accent);background:rgba(88,166,255,.1);} - #chat-footer{padding:12px 16px;border-top:1px solid var(--border);background:var(--bg-tertiary);} - #chat_input{width:100%;background:var(--bg-secondary)!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;} + .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),#3a7bd5);color:#0d1117;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(88,166,255,.4);} + #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 buttons area */ + .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);} ")) ), navbarPage( - title = tags$span(tags$i(class = "fas fa-dna", style = "margin-right:8px;color:#58a6ff;"), "QTL-Mapper CIM"), + title = tags$span(tags$i(class = "fas fa-dna", style = "margin-right:8px;color:#1D4ED8;"), "QTL-Mapper CIM v4"), 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 Mode"), - p("Composite Interval Mapping: higher power, correct flanking markers, better PVE estimation") + h2(tags$i(class = "fas fa-upload", style = "margin-right:8px;"), "Data Upload — CIM v4"), + p("Corrected formulas: -1/0/+1 additive coding | partial R² PVE | LOD-1.5 support intervals") ), fluidRow( column(12, div(class = "cim-box", - div(class = "box-title", tags$i(class = "fas fa-chart-line", style = "margin-right:6px;"), "CIM Method + PVE Formula"), - tags$pre(style = "background:transparent;border:none;margin:0;color:#7ee787;font-size:11px;", - "Composite Interval Mapping (Zeng 1993, 1994):\n", - " For each marker m:\n", - " 1. Cofactors = top K markers from RF (excluding nearby markers ±window on same chr)\n", - " 2. Fit: lm(Y ~ marker_m + cofactors) → LOD = -log10(p_marker)\n", - " 3. PVE_CIM (%) = R²_full × 100 [marker + cofactors — higher than single-marker PVE]\n", - " 4. PVE_marker (%) = R² from lm(Y ~ a + d) [marker alone, add+dom model]\n\n", - "Flanking fix: uses FULL marker table (not post-NZV subset)\n", - "Ref: Zeng (1993) PNAS; Falconer & Mackay (1996); Lynch & Walsh (1998)") + div(class = "box-title", tags$i(class = "fas fa-check-circle", style = "margin-right:6px;"), "CIM v4 — What Was Fixed"), + tags$pre(style = "background:transparent;border:none;margin:0;color:#166534;font-size:11px;", + "FIX 1 — Additive coding: genotype 0/1/2 → coded as -1/0/+1 (standard QTL convention)\n", + " Effect = half allele substitution effect [Falconer & Mackay 1996, Eq. 7.1]\n\n", + "FIX 2 — PVE formula (partial R², NOT full model R²):\n", + " PVE_marker (%) = (RSS_null - RSS_add_dom) / SS_total × 100\n", + " PVE_CIM (%) = (RSS_without_focal - RSS_with_focal) / SS_total × 100\n", + " Both are INCREMENTAL contributions — not inflated by cofactor variance\n\n", + "FIX 3 — QTL support interval (LOD-1.5 drop, NOT adjacent markers):\n", + " Interval = all markers within 1.5 LOD units of the peak\n", + " Ref: Lander & Botstein (1989) Genetics 121:185-199\n", + " Flanking markers = adjacent markers OUTSIDE the LOD-1.5 interval") ) ) ), @@ -648,21 +923,21 @@ ui <- fluidPage( ), column(4, div(class = "card", - div(class = "card-header", tags$i(class = "fas fa-sliders-h", style = "margin-right:6px;color:#bc8cff;"), "CIM Parameters"), + 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("More cofactors = better background control, slower. Try 5-15."), numericInput("window_size", "Exclusion Window (±markers)", value = 10, min = 1, max = 30, step = 1), - helpText("Nearby markers excluded from cofactors to avoid collinearity."), + numericInput("lod_drop", "LOD Drop for Support Interval", value = 1.5, min = 0.5, max = 3.0, step = 0.5), + helpText("Standard: 1.5 LOD drop defines the QTL confidence interval"), actionButton("run_analysis", "Run CIM Analysis", class = "btn-primary btn-block", icon = icon("play")) ) ) ), column(4, div(class = "card", - div(class = "card-header", tags$i(class = "fas fa-vial", style = "margin-right:6px;color:#3fb950;"), "Test Data (Optional)"), + 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."), @@ -694,14 +969,31 @@ ui <- fluidPage( # ---- 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"), - p("LOD genome scan, flanking markers, additive + dominance PVE, model performance") + h2(tags$i(class = "fas fa-chart-line", style = "margin-right:8px;"), "CIM Results v4"), + p("LOD scan | LOD-1.5 support intervals | corrected partial R² PVE | -1/0/+1 additive coding") ), + # Download bar 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(12, + div(class = "download-bar", + tags$span(tags$i(class = "fas fa-download"), " Download plots:"), + downloadButton("download_manhattan_plot", "Manhattan Plot (.png)", class = "btn btn-primary"), + downloadButton("download_chromosome_plot", "Chromosome Map (.png)", class = "btn btn-info"), + downloadButton("download_train_results", "CIM 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"), + div(class = "card-header", "Chromosome Visualization — LOD-1.5 Intervals"), div(class = "card-body", + div(class = "chr-legend", + div(class = "legend-item", div(class = "legend-dot", style = "background:#DC2626;"), "Significant QTL"), + div(class = "legend-item", div(class = "legend-dot", style = "background:#1D4ED8;"), "Flanking marker"), + div(class = "legend-item", div(class = "legend-dot", style = "background:#FCA5A5;border:1px solid #DC2626;"), "LOD-1.5 interval"), + div(class = "legend-item", div(class = "legend-dot", style = "background:#CBD5E1;"), "All markers") + ), uiOutput("chromosome_viz"), div(style = "margin:12px 0;display:flex;gap:8px;", actionButton("simulate_btn", "Simulate Discovery", class = "btn-info"), @@ -717,11 +1009,9 @@ ui <- fluidPage( ), fluidRow( column(12, div(class = "card", - div(class = "card-header", "CIM QTL Effects — All markers scanned (Additive + Dominance PVE)"), + div(class = "card-header", "CIM QTL Table — LOD-1.5 Support Intervals | Partial R² PVE | -1/0/+1 Additive"), div(class = "card-body", - DTOutput("qtl_effects_table_train"), - tags$br(), - downloadButton("download_train_results", "Download CIM Results (.xlsx)") + DTOutput("qtl_effects_table_train") ) )) ), @@ -761,8 +1051,8 @@ ui <- fluidPage( ) ), 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-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")))) ), fluidRow( column(12, @@ -771,7 +1061,7 @@ ui <- fluidPage( div(class = "card-body", DTOutput("selection_table"), tags$br(), - downloadButton("download_selection", "Download Selection Results") + downloadButton("download_selection", "Download Selection Results (.xlsx)") ) ) ) @@ -782,49 +1072,52 @@ ui <- fluidPage( tabPanel("Interpretation", icon = icon("lightbulb"), div(class = "main-header", h2(tags$i(class = "fas fa-lightbulb", style = "margin-right:8px;"), "Results Interpretation"), - p("CIM QTL interpretation: PVE_marker vs PVE_CIM, flanking regions, dominance class") + p("LOD-1.5 interval sizes | partial R² PVE | dominance classification") ), - fluidRow(column(12, div(class = "card", div(class = "card-header", "Analysis Summary"), div(class = "card-body", uiOutput("analysis_summary"))))), + 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")))) + 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"))))) + 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 v3") + h2(tags$i(class = "fas fa-info-circle", style = "margin-right:8px;"), "About QTL-Mapper CIM v4") ), fluidRow( column(8, offset = 2, div(class = "card", div(class = "card-body", - h4(style = "color:#58a6ff;font-family:'IBM Plex Mono';margin-bottom:12px;", "What Changed in v3"), - div(class = "cim-box", - tags$pre(style = "background:transparent;border:none;margin:0;color:#7ee787;font-size:11px;", - "FIX 1 — PVE now reports two values:\n", - " PVE_Marker_% = R² from lm(y ~ a + d) [marker alone]\n", - " PVE_CIM_% = R² from lm(y ~ marker + cofactors) [full CIM model]\n", - " → PVE_CIM is always ≥ PVE_Marker; often much higher\n\n", - "FIX 2 — Flanking markers fixed:\n", - " OLD: used colnames(X_train) after NZV removal → flanking lookup FAILED\n", - " NEW: uses all_markers table (full set before NZV removal)\n", - " Position-based fallback if marker not found by name\n\n", - "METHOD — Composite Interval Mapping (Zeng 1993, PNAS):\n", - " For each marker: fit lm(Y ~ focal_marker + K_cofactors)\n", - " Cofactors selected by RF importance, excluding nearby markers\n", - " LOD = -log10(p-value of focal marker term)\n", - " This controls background genetic variance → higher power & PVE") + h4(style = "color:#1D4ED8;font-family:'IBM Plex Mono';margin-bottom:12px;", "Changes in v4 (Formula Corrections)"), + div(class = "fix-box", + tags$pre(style = "background:transparent;border:none;margin:0;color:#92400E;font-size:11px;", + "v3 BUG → v4 FIX\n\n", + "1. ADDITIVE CODING\n", + " v3 (wrong): a_code = df_model$focal (uses raw 0/1/2)\n", + " v4 (fixed): a_code = df_model$focal - 1 (maps to -1/0/+1)\n", + " Why: -1/0/+1 is the standard QTL additive model; effect = half allele sub\n\n", + "2. PVE_CIM\n", + " v3 (wrong): PVE_CIM = R²_full × 100 (INFLATED — includes cofactor variance)\n", + " v4 (fixed): PVE_CIM = (RSS_without_focal - RSS_with_focal) / SS_total × 100\n", + " This is the true incremental contribution of the marker after cofactors\n\n", + "3. QTL SUPPORT INTERVAL\n", + " v3 (wrong): flanking = ±1 adjacent marker (can span whole chromosome)\n", + " v4 (fixed): LOD-1.5 support interval = markers within 1.5 LOD of peak\n", + " Reports: Interval_Start, Interval_End, Interval_Size_Mb\n", + " Flanking = markers immediately OUTSIDE the interval boundary") ), - h4(style = "color:#58a6ff;font-family:'IBM Plex Mono';margin:16px 0 8px;", "Thresholds"), - tags$ul(style = "color:#8b949e;line-height:2;", - tags$li("LOD > 2: Suggestive QTL | LOD > 3: Significant | LOD > 5: Highly significant"), + h4(style = "color:#1D4ED8;font-family:'IBM Plex Mono';margin:16px 0 8px;", "Thresholds & References"), + 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 QTL | 10-20%: Moderate | <10%: Minor"), - tags$li("|d/a| > 1: Overdominance | ~1: Complete dominance | <0.5: Additive"), - tags$li("Fst > 0.2: Strong differentiation | Tajima's D < -2: Selective sweep") + tags$li("|d/a| > 1: Overdominance | ~1: Complete dom | 0.2-0.5: Partial dom | <0.2: Additive"), + tags$li("LOD-1.5 interval: Lander & Botstein (1989) Genetics 121:185"), + tags$li("Additive model: Falconer & Mackay (1996) Quant. Genetics 4th ed."), + tags$li("CIM method: Zeng (1993) PNAS 90:10972; Zeng (1994) Genetics 136:1457") ) ) ) @@ -843,7 +1136,7 @@ ui <- fluidPage( tags$div(class = "chat-title", tags$div(class = "chat-avatar", "AI"), tags$div( - tags$h4("QTL-CIM AI Assistant"), + tags$h4("QTL-CIM AI Assistant v4"), tags$p(id = "model_status_text", if (token_exists) "AI mode ready" else "Rule-based mode", class = if (token_exists) "ai-mode" else "") @@ -861,14 +1154,14 @@ ui <- fluidPage( ) ), tags$div(class = "quick-questions", - tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q','What is PVE in CIM?',{priority:'event'});", "PVE / CIM"), - 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','Show flanking markers',{priority:'event'});", "Flanking"), - tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q','Why is my R2 negative?',{priority:'event'});","Negative R²") + tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q','What is PVE in CIM v4?',{priority:'event'});", "PVE / Partial R²"), + 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(id = "chat_messages", uiOutput("chat_display")), tags$div(id = "chat-footer", - tags$textarea(id = "chat_input", placeholder = "Ask about CIM results... (Enter to send)", rows = "2"), + tags$textarea(id = "chat_input", placeholder = "Ask about CIM v4 results... (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") @@ -895,8 +1188,8 @@ server <- function(input, output, session) { all_markers = NULL, chromosome_info = NULL, position_info = NULL, - cim_all = NULL, # Full CIM scan results - qtl_effects_train = NULL, # Significant QTLs with flanking + cim_all = NULL, + qtl_effects_train = NULL, performance_metrics = NULL, train_predictions = NULL, test_predictions = NULL, @@ -908,6 +1201,7 @@ server <- function(input, output, session) { chat_messages = list(), is_typing = FALSE, lod_threshold = 2, + lod_drop = 1.5, current_model = default_model ) @@ -919,7 +1213,7 @@ server <- function(input, output, session) { observeEvent(input$test_model_btn, { req(input$selected_model) - add_message("assistant", paste0("⏳ Testing model: **", 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!")) @@ -957,7 +1251,7 @@ server <- function(input, output, session) { process_message(user_text) }) - observeEvent(input$quick_q, { req(input$quick_q); process_message(input$quick_q) }) + 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?") @@ -966,11 +1260,11 @@ server <- function(input, output, session) { observe({ if (length(values$chat_messages) == 0) { add_message("assistant", paste0( - "👋 Vanakam! TerraByte-AI (CIM v3)\n\n", - "**What's new:**\n", - "• CIM (Composite Interval Mapping) — higher PVE, better power\n", - "• Flanking markers fixed — uses full marker table\n", - "• Two PVE values: PVE_marker (add+dom alone) & PVE_CIM (full model)\n\n", + "👋 Vanakam! TerraByte-AI (CIM v4 — corrected)\n\n", + "**v4 Formula Fixes:**\n", + "• Additive coding: -1/0/+1 (was 0/1/2 — incorrect)\n", + "• PVE_CIM: partial R² (was full model R² — inflated)\n", + "• QTL interval: LOD-1.5 drop (was adjacent markers — too wide/narrow)\n\n", "Upload data and run CIM analysis to get started!\n", "Contact: ashmithamganesan@gmail.com, P.sinha@cgiar.org" )) @@ -1068,10 +1362,10 @@ server <- function(input, output, session) { }, 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$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$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)) }) # ============================================================ @@ -1080,8 +1374,9 @@ server <- function(input, output, session) { observeEvent(input$run_analysis, { req(values$genotype_data, values$phenotype_data, input$phenotype_column) - showNotification("Starting CIM analysis...", type = "message") + showNotification("Starting CIM v4 analysis...", type = "message") values$lod_threshold <- input$lod_threshold + values$lod_drop <- input$lod_drop tryCatch({ common_samples <- intersect(rownames(values$genotype_data), rownames(values$phenotype_data)) @@ -1096,11 +1391,11 @@ server <- function(input, output, session) { y_train <- y[train_index]; y_val <- y[-train_index] # ---- Run CIM scan ---- - withProgress(message = "Running CIM genome scan...", value = 0.1, { + withProgress(message = "Running CIM v4 genome scan...", value = 0.1, { cim_results <- run_cim( genotype_matrix = X_train, phenotype_vector = y_train, - marker_info = values$all_markers, # FULL marker table — key fix + marker_info = values$all_markers, n_cofactors = input$n_cofactors, window_size = input$window_size, lod_threshold = input$lod_threshold @@ -1110,13 +1405,17 @@ server <- function(input, output, session) { values$cim_all <- cim_results - # ---- Extract significant QTLs and add FIXED flanking ---- + # ---- Extract significant QTLs and add LOD-1.5 support intervals ---- if (!"Message" %in% colnames(cim_results)) { sig_qtls <- cim_results[cim_results$LOD >= input$lod_threshold, ] if (nrow(sig_qtls) > 0) { - # Add flanking using FULL all_markers table - sig_qtls <- add_flanking_markers(sig_qtls, values$all_markers) + # LOD-1.5 support interval (fixes large regions) + sig_qtls <- add_lod_support_interval( + sig_df = sig_qtls, + cim_all_df = cim_results, + lod_drop = 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)) @@ -1125,7 +1424,7 @@ server <- function(input, output, session) { values$qtl_effects_train <- cim_results } - # ---- RF model for prediction (separate from CIM mapping) ---- + # ---- 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] @@ -1155,7 +1454,7 @@ server <- function(input, output, session) { # ---- Epistasis ---- if (!is.null(values$qtl_effects_train) && !"Message" %in% colnames(values$qtl_effects_train)) { - sig_markers <- values$qtl_effects_train$Marker + sig_markers <- values$qtl_effects_train$Marker all_markers_v <- colnames(X_train) epi_list <- list() @@ -1192,22 +1491,24 @@ server <- function(input, output, session) { } 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_cim <- if (n_qtl > 0) round(max(values$qtl_effects_train$PVE_CIM_Percent), 1) else 0 + max_pve_cim <- if (n_qtl > 0) round(max(values$qtl_effects_train$PVE_CIM_Percent, na.rm = TRUE), 1) else 0 - showNotification("CIM analysis completed!", type = "message") + showNotification("CIM v4 analysis completed!", type = "message") add_message("assistant", paste0( - "✅ **CIM analysis complete!**\n\n", + "✅ **CIM v4 analysis complete!**\n\n", "• Found **", n_qtl, " QTLs** above LOD ", input$lod_threshold, "\n", - "• Top QTL PVE_CIM: **", max_pve_cim, "%** (full CIM model)\n", + "• Top QTL PVE_CIM (partial R²): **", max_pve_cim, "%**\n", "• Validation R²: **", round(val_r2, 3), "**\n", - "• Flanking markers: ✅ fixed (uses full marker table)\n\n", - "Ask me about PVE, flanking markers, or top QTLs!" + "• Intervals: LOD-1.5 support ✅\n", + "• Additive coding: -1/0/+1 ✅\n", + "• PVE: partial R² ✅\n\n", + "Ask me about PVE, intervals, or top QTLs!" )) updateTabsetPanel(session, "nav", selected = "Results") }, error = function(e) { - showNotification(paste("CIM Error:", e$message), type = "error") - cat("CIM ERROR:", e$message, "\n") + showNotification(paste("CIM v4 Error:", e$message), type = "error") + cat("CIM v4 ERROR:", e$message, "\n") }) }) @@ -1277,16 +1578,16 @@ server <- function(input, output, session) { }) # ============================================================ - # MANHATTAN HELPER + # MANHATTAN HELPER (plotly — interactive) # ============================================================ create_manhattan <- function(data, y_col, title, threshold, y_label = y_col) { if (is.null(data) || nrow(data) == 0 || "Message" %in% colnames(data)) return(plot_ly() %>% layout(title = "No data — run analysis first", - plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e"))) + plot_bgcolor = "#FFFFFF", paper_bgcolor = "#FFFFFF", font = list(color = "#475569"))) pd <- data[!is.na(data[[y_col]]) & !is.na(data$Chromosome), ] if (nrow(pd) == 0) return(plot_ly() %>% layout(title = "No valid data", - plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e"))) + plot_bgcolor = "#FFFFFF", paper_bgcolor = "#FFFFFF", font = list(color = "#475569"))) chroms <- unique(pd$Chromosome) chrom_pos <- data.frame() for (i in seq_along(chroms)) { @@ -1297,10 +1598,12 @@ server <- function(input, output, session) { chrom_pos <- rbind(chrom_pos, cd) } } + 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 = viridis(length(chroms)), marker = list(size = 6, opacity = 0.7), + colors = pal[1:length(chroms)], + marker = list(size = 6, opacity = 0.7), text = ~paste("Marker:", Marker, "
Chr:", Chromosome, "
Pos:", Position, "
", y_label, ":", round(get(y_col), 3)), hoverinfo = "text", showlegend = FALSE) @@ -1308,14 +1611,15 @@ server <- function(input, output, session) { 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 = "red", dash = "dash", width = 1)) - p %>% layout(title = title, - xaxis = list(title = "Chromosome", + 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), - yaxis = list(title = y_label), - plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e")) + tickangle = 45, gridcolor = "#F1F5F9"), + yaxis = list(title = y_label, color = "#475569", gridcolor = "#F1F5F9"), + plot_bgcolor = "#FFFFFF", paper_bgcolor = "#FFFFFF", + font = list(color = "#475569")) } # ============================================================ @@ -1332,7 +1636,7 @@ server <- function(input, output, session) { output$tajima_plot <- renderPlotly({ req(values$selection_metrics) if ("Message" %in% colnames(values$selection_metrics)) - return(plot_ly() %>% layout(title = "No data", plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e"))) + return(plot_ly() %>% layout(title = "No data", plot_bgcolor = "#FFFFFF", paper_bgcolor = "#FFFFFF")) d <- values$selection_metrics chroms <- unique(d$Chromosome) cp <- data.frame() @@ -1341,55 +1645,61 @@ server <- function(input, output, session) { 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 = "#58a6ff", 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 = "red", dash = "dash", width = 1)) %>% - layout(title = "Tajima's D", xaxis = list(title = "Chromosome", ticktext = chroms, tickvals = tapply(cp$PosScaled, cp$Chromosome, median, na.rm = TRUE), tickangle = 45), yaxis = list(title = "Tajima's D"), - plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e")) + 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("#58a6ff","#58a6ff","#3fb950","#3fb950")), + marker = list(color = c("#1D4ED8","#3B82F6","#15803D","#22C55E")), text = ~round(Value, 3), textposition = "outside") %>% - layout(title = "Model Performance (RF for Prediction)", yaxis = list(title = "Value", range = c(0, 1.1)), - plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e")) + 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$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 = "#58a6ff", opacity = .7)) %>% + 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 = "#f85149", dash = "dash")) %>% - layout(title = "Training Set", xaxis = list(title = "Observed"), yaxis = list(title = "Predicted"), - plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e")) + 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 = "#3fb950", opacity = .7)) %>% + 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 = "#f85149", dash = "dash")) %>% - layout(title = "Validation Set", xaxis = list(title = "Observed"), yaxis = list(title = "Predicted"), - plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e")) + 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")) }) output$epistasis_heatmap <- renderPlotly({ req(values$epistasis_all) if ("Message" %in% colnames(values$epistasis_all)) return(plot_ly() %>% layout(title = values$epistasis_all$Message[1], - plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e"))) + plot_bgcolor = "#FFFFFF", paper_bgcolor = "#FFFFFF", font = list(color = "#475569"))) qtls <- unique(values$epistasis_all$QTL1) mks <- unique(values$epistasis_all$QTL2) pm <- matrix(NA, nrow = length(qtls), ncol = length(mks), dimnames = list(qtls, mks)) for (i in 1:nrow(values$epistasis_all)) pm[values$epistasis_all$QTL1[i], values$epistasis_all$QTL2[i]] <- -log10(values$epistasis_all$Interaction_p[i]) - plot_ly(x = colnames(pm), y = rownames(pm), z = pm, type = "heatmap", colorscale = "Viridis") %>% - layout(title = "Epistatic Interactions (-log10 p)", xaxis = list(title = "Marker", tickangle = 45), yaxis = list(title = "QTL"), - plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e")) + plot_ly(x = colnames(pm), y = rownames(pm), z = pm, type = "heatmap", colorscale = "Blues") %>% + layout(title = "Epistatic Interactions (-log10 p)", xaxis = list(title = "Marker", tickangle = 45), + yaxis = list(title = "QTL"), plot_bgcolor = "#FFFFFF", paper_bgcolor = "#FFFFFF", font = list(color = "#475569")) }) # ============================================================ @@ -1407,15 +1717,17 @@ server <- function(input, output, session) { "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 = "PVE_Marker = R²(lm(y~a+d))×100 | PVE_CIM = R²(lm(y~marker+cofactors))×100") %>% + caption = tags$caption(style = "caption-side:top;font-size:11px;color:#475569;", + "PVE_Marker = partial R²(null vs add+dom) | PVE_CIM = partial R²(no focal vs with focal) | Interval = LOD-1.5 support")) %>% formatRound(intersect(c("LOD","PVE_Marker_Percent","PVE_CIM_Percent", "Additive_Effect","SE_Additive","CI_Lower","CI_Upper", - "Dominance_Effect","SE_Dominance","Dominance_Ratio"), display_cols), 3) %>% + "Dominance_Effect","SE_Dominance","Dominance_Ratio","Interval_Size_Mb"), display_cols), 3) %>% formatSignif(intersect(c("P_Value"), display_cols), digits = 3) }) @@ -1441,17 +1753,16 @@ server <- function(input, output, session) { }) # ============================================================ - # CHROMOSOME VISUALIZATION (uses FULL all_markers — flanking fixed) + # CHROMOSOME VISUALIZATION — LOD-1.5 INTERVALS # ============================================================ output$chromosome_viz <- renderUI({ - req(values$qtl_effects_train, values$all_markers) + 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) { - # Use FULL all_markers (not post-NZV subset) 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, ] @@ -1466,11 +1777,30 @@ server <- function(input, output, session) { 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 <- 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")), - div(class = "chromosome", + 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:#B45309;margin-left:8px;", + paste0("(LOD-1.5 intervals: ", paste(round(sizes, 2), collapse = ", "), " Mb)")) + } + ), + div(class = "chromosome", style = "position:relative;", + # LOD-1.5 interval shading + 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 + width_pct <- right_pct - left_pct + div(class = "interval-band", + style = paste0("left:", round(left_pct, 2), "%;width:", round(width_pct, 2), "%;")) + } + }), + # Markers lapply(1:nrow(chr_markers), function(i) { marker <- chr_markers[i, ] left <- if (range_pos > 0 && !is.na(range_pos)) @@ -1500,6 +1830,85 @@ server <- function(input, output, session) { observeEvent(input$simulate_btn, session$sendCustomMessage("simulateQTLDiscovery", list())) observeEvent(input$reset_btn, session$sendCustomMessage("resetAnimation", list())) + # ============================================================ + # DOWNLOADS — Manhattan + Chromosome plots (ggplot2 → PNG) + # ============================================================ + + output$download_manhattan_plot <- downloadHandler( + filename = function() paste0("manhattan_cim_", Sys.Date(), ".png"), + content = function(file) { + req(values$cim_all) + p <- make_ggplot_manhattan(values$cim_all, values$lod_threshold, + title = "CIM Manhattan Plot (LOD Scores)") + if (is.null(p)) { + # fallback blank + p <- ggplot() + labs(title = "No data") + theme_bw() + } + ggsave(file, plot = p, width = 14, height = 6, dpi = 200, bg = "white") + } + ) + + output$download_chromosome_plot <- downloadHandler( + filename = function() paste0("chromosome_map_", Sys.Date(), ".png"), + content = function(file) { + req(values$qtl_effects_train, values$all_markers) + grob <- make_ggplot_chromosome_viz( + qtl_effects = values$qtl_effects_train, + all_markers_df = values$all_markers, + cim_all = values$cim_all, + lod_threshold = values$lod_threshold + ) + if (is.null(grob)) { + # fallback + p <- ggplot() + labs(title = "No QTL data") + theme_bw() + ggsave(file, plot = p, width = 10, height = 6, dpi = 200, bg = "white") + } else { + png(file, width = 2800, height = 400 * ceiling(length(unique(values$qtl_effects_train$Chromosome)) / 2) + 200, + res = 200, bg = "white") + grid::grid.draw(grob) + dev.off() + } + } + ) + + output$download_train_results <- downloadHandler( + filename = function() paste0("cim_results_v4_", 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_Documentation"]] <- data.frame( + Item = c("Version","Method","Additive_Coding","PVE_Marker","PVE_CIM", + "QTL_Interval","Flanking_Markers","Cofactor_Selection","Reference"), + Description = c( + "CIM v4 — corrected formulas", + "Composite Interval Mapping (Zeng 1993, 1994)", + "a_code = genotype - 1 → maps 0/1/2 to -1/0/+1 (standard QTL convention)", + "Partial R²: (RSS_null - RSS_add_dom) / SS_total × 100", + "Partial R²: (RSS_without_focal - RSS_with_focal) / SS_total × 100 [incremental]", + "LOD-1.5 support interval: all markers within 1.5 LOD units of peak LOD", + "Markers immediately outside the LOD-1.5 interval on each side", + "Top K markers by RF importance, excluding ±window markers on same chromosome", + "Zeng (1993) PNAS 90:10972; Lander & Botstein (1989) Genetics 121:185; Falconer & Mackay (1996)"), + stringsAsFactors = FALSE) + write_xlsx(sheets, file) + } + ) + + 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) + } + ) + # ============================================================ # INTERPRETATION # ============================================================ @@ -1509,13 +1918,20 @@ server <- function(input, output, session) { 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), 1) else NA + max_pve <- if (has_qtl) round(max(values$qtl_effects_train$PVE_CIM_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 Analysis Summary"), - tags$p(paste(n_qtl, "QTLs detected above LOD", input$lod_threshold, "| Validation R²:", val_r2)), - if (!is.na(max_pve)) tags$p(paste("Max PVE_CIM:", max_pve, "% (marker + cofactors)")), - tags$p(style = "color:#3fb950;font-size:12px;", - tags$i(class = "fas fa-check-circle"), " CIM: flanking markers use full marker table ✓") + tags$h5("CIM v4 Analysis Summary"), + tags$p(paste(n_qtl, "QTLs detected above LOD", values$lod_threshold, "| Validation R²:", val_r2)), + if (!is.na(max_pve)) tags$p(paste("Max PVE_CIM (partial R²):", max_pve, "%")), + if (!is.na(avg_int)) tags$p(paste("Mean LOD-1.5 interval size:", avg_int, "Mb")), + tags$p(style = "color:#15803D;font-size:12px;", + tags$i(class = "fas fa-check-circle"), + " v4 fixes: -1/0/+1 coding ✓ | partial R² PVE ✓ | LOD-1.5 intervals ✓") ) }) @@ -1523,9 +1939,12 @@ server <- function(input, output, session) { 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. Try lower LOD threshold."))) 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"), + 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:", round(top$PVE_Marker_Percent, 1), "% | PVE_CIM:", round(top$PVE_CIM_Percent, 1), "%")) ) @@ -1535,11 +1954,13 @@ server <- function(input, output, session) { 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_CIM_Percent), ] - dom <- if (!is.na(top$Dominance_Effect)) paste0("Dominance = ", round(top$Dominance_Effect, 3), " (", top$Dominance_Class, ")") else "No heterozygotes (additive model)" + 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_CIM QTL"), - tags$p(paste(top$Marker, "—", round(top$PVE_CIM_Percent, 1), "% PVE (CIM model)")), - tags$p(paste("Additive effect =", round(top$Additive_Effect, 3))), + tags$p(paste(top$Marker, "—", round(top$PVE_CIM_Percent, 1), "% PVE (partial R²)")), + tags$p(paste("Additive effect (a, -1/0/+1 coding) =", round(top$Additive_Effect, 3))), tags$p(dom) ) }) @@ -1549,66 +1970,30 @@ server <- function(input, output, session) { return(div(tags$h5("Epistasis"), tags$p("No significant interactions."))) 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), ")"))) + tags$p(paste(nrow(values$epistasis_sig), "interactions. Strongest:", top$QTL1, "×", top$QTL2, + "(p =", format.pval(top$Interaction_p), ")"))) }) 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) - r <- c("Validate top CIM QTLs in independent populations", - "Use Low_Flank / High_Flank for fine-mapping intervals", - "Annotate QTL regions for candidate genes") + 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 — NOT adjacent-marker flanking", + "Annotate LOD-1.5 intervals for candidate genes", + "PVE_CIM is partial R² (incremental) — sum of top QTLs gives total explained variance" + ) if (n_ovdom > 0) r <- c(r, paste(n_ovdom, "overdominant QTL(s) — consider heterosis breeding")) - r <- c(r, "PVE_CIM includes cofactor variance — use PVE_Marker for single-QTL estimates") + if (large_int > 0) r <- c(r, paste(large_int, "QTL(s) with interval >10 Mb — increase marker density")) r } else { c("Upload genotype + phenotype CSV files", "Click 'Run CIM Analysis'", "Try LOD threshold = 2 to start") } - div(tags$h5("Recommendations"), tags$ul(lapply(recs, tags$li), style = "color:#8b949e;")) + div(tags$h5("Recommendations"), tags$ul(lapply(recs, tags$li), style = "color:#475569;")) }) - - # ============================================================ - # DOWNLOADS - # ============================================================ - - output$download_train_results <- downloadHandler( - filename = function() paste0("cim_results_", 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_Documentation"]] <- data.frame( - Item = c("Method","Cofactor selection","LOD formula","PVE_Marker","PVE_CIM", - "Additive_Effect","Dominance_Effect","Flanking fix","Reference"), - Description = c( - "Composite Interval Mapping (CIM)", - "Top K markers by RF importance, excluding ±window on same chromosome", - "-log10(p-value of focal marker in lm(Y ~ marker + cofactors))", - "R² from lm(Y ~ additive_code + dominance_code) × 100 — marker alone", - "R² from full CIM model (marker + cofactors) × 100 — includes background", - "beta_a from lm(Y ~ a + d) — allele substitution effect", - "beta_d from lm(Y ~ a + d) — heterozygote deviation from midparent", - "Uses full all_markers table (not post-NZV subset)", - "Zeng (1993) PNAS; Falconer & Mackay (1996); Lynch & Walsh (1998)"), - stringsAsFactors = FALSE) - write_xlsx(sheets, file) - } - ) - - 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) - } - ) } shinyApp(ui = ui, server = server) \ No newline at end of file