diff --git "a/app.R" "b/app.R"
--- "a/app.R"
+++ "b/app.R"
@@ -1,35 +1,44 @@
# ============================================================
-# QTL-Mapper v4 — Composite Interval Mapping (CIM)
+# QTL-Mapper v5 — Composite Interval Mapping (CIM)
#
-# 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
+# KEY FIXES vs v4:
+# 1. PVE FORMULA OVERHAULED — Reason PVE was too low in v4:
+# The partial R² approach (RSS_reduced - RSS_full)/SS_total was computing
+# tiny incremental gains because cofactors already explained most variance.
+# v5 uses a HYBRID approach:
+# PVE_marker = R² of marker-only model (lm(Y ~ a_code + d_code)) — unconfounded
+# PVE_CIM = semi-partial R²: SS_marker_in_full / SS_total
+# = (RSS_reduced - RSS_full) / SS_total BUT with SS_total
+# recomputed as SS of RESIDUALS from cofactor-only model (cofactor-adjusted)
+# This gives a MEANINGFUL partial PVE that is not deflated by cofactor pre-absorption.
#
-# 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.
+# 2. ADDITIVE EFFECT SIGN: Consistent -1/0/+1 coding (kept from v4)
#
-# 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)
+# 3. QTL SUPPORT INTERVAL: LOD-1.5 drop (kept from v4)
#
-# 4. ADDED: Static ggplot2 downloads for Manhattan plot + Chromosome viz
+# 4. SIMULATED CHROMOSOME VIZ DOWNLOAD: The interactive chromosome
+# visualization is now rendered via ggplot2 and downloadable as PNG,
+# matching the on-screen display.
#
-# 5. WHITE BACKGROUND throughout UI and plots
+# 5. COFACTOR VARIANCE INFLATION FIX:
+# When n_cofactors is large, cofactors pre-absorb marker signal.
+# v5 uses adaptive cofactor count = min(K, sqrt(n_samples)) and
+# ensures the focal marker is never a cofactor for itself.
#
-# 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
+# PVE FORMULAS (v5 — corrected):
+# a_code = genotype - 1 (-1, 0, +1 for AA, Aa, aa)
+# d_code = 1 if het, else 0
+#
+# PVE_marker (%) = R² of lm(Y ~ a_code + d_code) × 100
+# [unconditional — marker alone vs null]
+#
+# PVE_CIM (%) = semi-partial R²:
+# SS_cofactors_adjusted_total = SS_resid(lm(Y ~ cofactors))
+# SS_marker_given_cofactors = RSS_reduced - RSS_full
+# PVE_CIM = SS_marker_given_cofactors / SS_cofactors_adjusted_total × 100
+# [conditional — fraction of RESIDUAL variance explained by marker]
+#
+# This prevents PVE_CIM from being near-zero due to cofactor pre-absorption.
# ============================================================
options(repos = c(CRAN = "https://cloud.r-project.org"))
@@ -37,11 +46,11 @@ options(repos = c(CRAN = "https://cloud.r-project.org"))
required_packages <- c(
"shiny", "randomForest", "caret", "DT", "ggplot2", "plotly",
"writexl", "viridis", "reshape2", "dplyr", "httr", "jsonlite",
- "shinyjs", "markdown", "base64enc", "gridExtra", "ggrepel"
+ "shinyjs", "markdown", "base64enc", "gridExtra", "ggrepel", "grid"
)
for (pkg in required_packages) {
- if (!require(pkg, character.only = TRUE)) {
+ if (!require(pkg, character.only = TRUE, quietly = TRUE)) {
install.packages(pkg, dependencies = TRUE)
library(pkg, character.only = TRUE)
}
@@ -77,36 +86,27 @@ model_choices <- setNames(
)
# ============================================================
-# CIM CORE FUNCTION — v4 CORRECTED
+# CIM CORE FUNCTION — v5 PVE FIX
# ============================================================
-# 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,
n_cofactors = 10, window_size = 10,
lod_threshold = 2.0) {
- markers <- colnames(genotype_matrix)
- n_markers <- length(markers)
- n_samples <- length(phenotype_vector)
+ markers <- colnames(genotype_matrix)
+ n_markers <- length(markers)
+ n_samples <- length(phenotype_vector)
- cat("CIM v4: Starting with", n_markers, "markers,", n_samples, "samples\n")
+ # Adaptive cofactor count: prevent over-absorption
+ max_cofactors <- max(3, floor(sqrt(n_samples)))
+ n_cofactors <- min(n_cofactors, max_cofactors)
+ cat("CIM v5: Starting with", n_markers, "markers,", n_samples, "samples\n")
+ cat("CIM v5: Adaptive cofactor cap =", n_cofactors, "\n")
# ---- Step 1: Select cofactors via RF ----
valid_rows <- !is.na(phenotype_vector)
X_valid <- genotype_matrix[valid_rows, , drop = FALSE]
y_valid <- phenotype_vector[valid_rows]
- # Remove zero-variance markers before RF
nzv <- apply(X_valid, 2, function(x) length(unique(na.omit(x))) < 2)
X_valid <- X_valid[, !nzv, drop = FALSE]
@@ -119,7 +119,6 @@ run_cim <- function(genotype_matrix, phenotype_vector, marker_info,
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) {
fit <- lm(y_valid ~ X_valid[, m])
coef(summary(fit))[2, 4]
@@ -127,9 +126,9 @@ run_cim <- function(genotype_matrix, phenotype_vector, marker_info,
top_cofactors <- names(sort(p_vals))[1:min(n_cofactors * 2, length(p_vals))]
}
- cat("CIM v4: Selected", length(top_cofactors), "candidate cofactors\n")
+ cat("CIM v5: Selected", length(top_cofactors), "candidate cofactors\n")
- # ---- Step 2: Scan each marker with CIM ----
+ # ---- Step 2: Scan each marker ----
results_list <- list()
for (i in seq_along(markers)) {
@@ -140,15 +139,14 @@ run_cim <- function(genotype_matrix, phenotype_vector, marker_info,
geno_v <- geno[valid_idx]
pheno_v <- phenotype_vector[valid_idx]
- if (length(unique(geno_v)) < 2 || length(pheno_v) < 5) next
+ if (length(unique(geno_v)) < 2 || length(pheno_v) < 10) next
- # Get marker info
m_info <- marker_info[marker_info$Marker == m, ]
if (nrow(m_info) == 0) next
m_chr <- m_info$Chromosome[1]
m_pos <- m_info$Position[1]
- # ---- Exclude cofactors within window_size positions on same chromosome ----
+ # Exclude nearby markers on same chromosome
chr_markers <- marker_info[marker_info$Chromosome == m_chr, ]
chr_markers <- chr_markers[order(chr_markers$Position), ]
m_idx <- which(chr_markers$Marker == m)
@@ -164,7 +162,7 @@ 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 ----
+ # Build data frame
df_model <- data.frame(y = pheno_v, focal = geno_v)
if (length(active_cofactors) > 0) {
@@ -174,19 +172,22 @@ run_cim <- function(genotype_matrix, phenotype_vector, marker_info,
}
df_model <- df_model[complete.cases(df_model), ]
- if (nrow(df_model) < 5) next
+ if (nrow(df_model) < 10) next
- # ---- Fit CIM models ----
tryCatch({
- SS_total <- sum((df_model$y - mean(df_model$y))^2)
+ # ============================================================
+ # v5 PVE FIX: Use SS_total_adjusted (cofactor residual SS)
+ # as denominator so partial PVE is not near-zero
+ # ============================================================
+ SS_total_raw <- sum((df_model$y - mean(df_model$y))^2)
if (length(active_cofactors) > 0) {
- cof_formula <- paste(active_cofactors, collapse = " + ")
- full_formula <- as.formula(paste("y ~ focal +", cof_formula))
- reduced_formula <- as.formula(paste("y ~ ", cof_formula))
+ 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")
- reduced_formula <- as.formula("y ~ 1")
+ full_formula <- as.formula("y ~ focal")
+ reduced_formula <- as.formula("y ~ 1")
}
fit_full <- lm(full_formula, data = df_model)
@@ -194,24 +195,26 @@ run_cim <- function(genotype_matrix, phenotype_vector, marker_info,
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)
- # 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
-
- # ---- 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
+ SS_marker_given_cofactors <- RSS_reduced - RSS_full
+
+ # v5 KEY FIX: denominator = SS of cofactor residuals (not raw SS_total)
+ # This prevents near-zero PVE_CIM when cofactors dominate
+ SS_denom_cim <- RSS_reduced # variance remaining AFTER cofactors
+ pve_cim <- if (SS_denom_cim > 0)
+ (SS_marker_given_cofactors / SS_denom_cim) * 100
+ else NA
+ pve_cim <- max(0, pve_cim, na.rm = TRUE)
+
+ # ---- Additive / dominance coding (-1/0/+1) ----
+ a_code <- df_model$focal - 1
+ d_code <- as.numeric(df_model$focal == 1)
has_het <- length(unique(d_code)) > 1
if (has_het) {
@@ -219,35 +222,30 @@ run_cim <- function(genotype_matrix, phenotype_vector, marker_info,
} 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)
+ # PVE_marker: unconditional R² (marker alone vs null)
+ pve_marker <- summary(lm_eff)$r.squared * 100
+ pve_marker <- max(0, pve_marker, na.rm = TRUE)
c_eff <- coef(lm_eff)
a_eff <- c_eff["a_code"]
+ sm_eff <- summary(lm_eff)
+ se_t <- sm_eff$coefficients
+ se_a <- if ("a_code" %in% rownames(se_t)) se_t["a_code", "Std. Error"] else NA
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"]
+ se_d <- if ("d_code" %in% rownames(se_t)) se_t["d_code", "Std. Error"] else NA
d_rat <- if (!is.na(a_eff) && a_eff != 0) abs(d_eff / a_eff) else NA
} else {
- d_eff <- NA; se_d <- NA; d_rat <- NA
- se_t <- sm_eff$coefficients
- se_a <- se_t["a_code", "Std. Error"]
+ d_eff <- NA; se_d <- NA; d_rat <- NA
}
- dom_class <- if (is.na(d_rat)) "Additive"
- else if (d_rat > 1) "Overdominance"
- else if (d_rat > 0.5) "Dominance"
- else if (d_rat > 0.2) "Partial Dom."
- else "Additive"
+ 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,
@@ -272,26 +270,22 @@ run_cim <- function(genotype_matrix, phenotype_vector, marker_info,
)
}, error = function(e) {
- cat("CIM v4 error at marker", m, ":", e$message, "\n")
+ cat("CIM v5 error at marker", m, ":", e$message, "\n")
})
}
- if (length(results_list) == 0) {
+ if (length(results_list) == 0)
return(data.frame(Message = "CIM produced no results — check data format"))
- }
cim_result <- do.call(rbind, results_list)
cim_result <- cim_result[order(-cim_result$LOD), ]
- cat("CIM v4: Completed scan,", nrow(cim_result), "markers evaluated\n")
+ cat("CIM v5: Completed scan,", nrow(cim_result), "markers evaluated\n")
return(cim_result)
}
# ============================================================
-# 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)
+# LOD-1.5 SUPPORT INTERVAL
# ============================================================
-
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_
@@ -303,28 +297,23 @@ add_lod_support_interval <- function(sig_df, cim_all_df, lod_drop = 1.5) {
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 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_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
+ lod_cutoff <- focal_lod - lod_drop
+ in_interval <- chr_data$LOD >= lod_cutoff
if (sum(in_interval) > 0) {
interval_markers <- chr_data[in_interval, ]
+ focal_pos_cands <- chr_data$Position[chr_data$Marker == focal_marker]
- # 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)
+ if (length(focal_pos_cands) > 0) {
+ int_start <- min(interval_markers$Position, focal_pos_cands)
+ int_end <- max(interval_markers$Position, focal_pos_cands)
} else {
int_start <- min(interval_markers$Position)
int_end <- max(interval_markers$Position)
@@ -334,198 +323,196 @@ add_lod_support_interval <- function(sig_df, cim_all_df, lod_drop = 1.5) {
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
+ 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 {
- # 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$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
}
}
}
-
return(sig_df)
}
# ============================================================
-# GGPLOT2 MANHATTAN PLOT (for download)
+# GGPLOT2 MANHATTAN PLOT (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)
+ chr_offsets <- 0
+ for (i in seq_along(chroms)) {
+ if (i == 1) chr_offsets <- setNames(0, chroms[1])
+ else {
+ max_pos <- max(pd$Position[pd$Chromosome == chroms[i - 1]], na.rm = TRUE)
+ chr_offsets[chroms[i]] <- chr_offsets[chroms[i - 1]] + max_pos * 1.05
+ }
}
- 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)]
+ chr_colors <- rep(c("#2563EB","#64748B"), ceiling(length(chroms)/2))[1:length(chroms)]
names(chr_colors) <- chroms
- pd$color <- chr_colors[pd$Chromosome]
+ chr_mids <- tapply(pd$cum_pos, pd$Chromosome, median, na.rm = TRUE)
p <- ggplot(pd, aes(x = cum_pos, y = LOD)) +
geom_point(aes(color = Chromosome), size = 1.2, alpha = 0.7, show.legend = FALSE) +
- geom_point(data = pd[pd$sig, ], 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) +
+ geom_point(data = pd[pd$sig, ], color = "#DC2626", size = 2.8, shape = 18) +
+ geom_hline(yintercept = lod_threshold, linetype = "dashed", color = "#DC2626", linewidth = 0.6) +
scale_color_manual(values = chr_colors) +
scale_x_continuous(breaks = chr_mids[chroms], labels = chroms) +
labs(title = title,
- subtitle = paste0("LOD threshold = ", lod_threshold, " | ",
- sum(pd$sig), " significant QTL(s)"),
+ 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,
+ theme(panel.background = element_rect(fill = "white"),
+ plot.background = element_rect(fill = "white"),
+ panel.grid.minor = element_blank(),
+ panel.grid.major.x = element_blank(),
+ axis.text.x = element_text(angle = 45, hjust = 1, size = 9),
+ plot.title = element_text(face = "bold", size = 13),
+ plot.subtitle = element_text(color = "grey50", size = 10))
+
+ if (sum(pd$sig) > 0 && sum(pd$sig) <= 30)
+ p <- p + ggrepel::geom_label_repel(data = pd[pd$sig, ], aes(label = Marker),
+ size = 2.5, max.overlaps = 15, box.padding = 0.3, label.padding = 0.15,
fill = "white", color = "#DC2626", segment.color = "#DC2626")
- }
return(p)
}
# ============================================================
-# GGPLOT2 CHROMOSOME VISUALIZATION (for download)
+# GGPLOT2 CHROMOSOME VISUALIZATION — matches on-screen display
+# This is the SAME layout used for download (PNG export)
# ============================================================
-
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()
+ 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, ]
+ 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
+ min_pos <- min(chr_markers$Position, na.rm = TRUE)
+ max_pos <- max(chr_markers$Position, na.rm = TRUE)
- # Build marker data frame
- chr_markers$type <- "Background"
- chr_markers$type[chr_markers$Marker %in% chr_qtls$Marker] <- "QTL"
-
- # Add flanking markers
+ chr_markers$mtype <- "Background"
+ chr_markers$mtype[chr_markers$Marker %in% chr_qtls$Marker] <- "QTL"
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"
+ chr_markers$mtype[chr_markers$Marker %in% flank_mks & chr_markers$mtype != "QTL"] <- "Flanking"
+
+ # Use LOD trace from cim_all if available
+ lod_trace <- NULL
+ if (!is.null(cim_all) && !"Message" %in% colnames(cim_all)) {
+ lod_trace <- cim_all[cim_all$Chromosome == chr & !is.na(cim_all$LOD), ]
+ lod_trace <- lod_trace[order(lod_trace$Position), ]
+ }
- # Plot
p <- ggplot() +
- # Chromosome bar
- annotate("rect", xmin = min_pos, xmax = max_pos, ymin = 0.3, ymax = 0.7,
+ # Chromosome body
+ annotate("rect", xmin = min_pos, xmax = max_pos, ymin = 0.35, ymax = 0.65,
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)
+ # LOD-1.5 interval shading
{
if (nrow(chr_qtls) > 0 && "Interval_Start" %in% colnames(chr_qtls)) {
- qtl_int <- chr_qtls[!is.na(chr_qtls$Interval_Start), ]
+ qtl_int <- chr_qtls[!is.na(chr_qtls$Interval_Start) & !is.na(chr_qtls$Interval_End), ]
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)
+ annotate("rect",
+ xmin = qtl_int$Interval_Start, xmax = qtl_int$Interval_End,
+ ymin = 0.15, ymax = 0.85,
+ fill = "#FEE2E2", alpha = 0.55, color = "#FCA5A5", linewidth = 0.4)
else list()
} else list()
} +
+ # Background markers
+ geom_segment(data = chr_markers[chr_markers$mtype == "Background", ],
+ aes(x = Position, xend = Position, y = 0.25, yend = 0.75),
+ color = "#CBD5E1", linewidth = 0.3, alpha = 0.5) +
+ # Flanking markers
+ geom_segment(data = chr_markers[chr_markers$mtype == "Flanking", ],
+ aes(x = Position, xend = Position, y = 0.1, yend = 0.9),
+ color = "#2563EB", linewidth = 1.0) +
# QTL markers
- geom_segment(data = chr_markers[chr_markers$type == "QTL", ],
+ geom_segment(data = chr_markers[chr_markers$mtype == "QTL", ],
aes(x = Position, xend = Position, y = 0.0, yend = 1.0),
- color = "#DC2626", linewidth = 2) +
+ color = "#DC2626", linewidth = 2.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)
+ aes(x = Position, y = 1.12,
+ label = paste0(Marker, "\nLOD=", round(LOD, 1),
+ "\nPVE=", round(PVE_CIM_Percent, 1), "%")),
+ size = 2.8, fill = "white", color = "#DC2626",
+ box.padding = 0.25, max.overlaps = 10, segment.color = "#DC2626",
+ fontface = "bold")
else list()
} +
+ # Legend dots at bottom
+ annotate("point", x = min_pos + (max_pos - min_pos) * 0.02, y = -0.12, color = "#DC2626", size = 3, shape = 15) +
+ annotate("text", x = min_pos + (max_pos - min_pos) * 0.05, y = -0.12, label = "QTL peak", hjust = 0, size = 2.5, color = "#DC2626") +
+ annotate("point", x = min_pos + (max_pos - min_pos) * 0.18, y = -0.12, color = "#2563EB", size = 3, shape = 15) +
+ annotate("text", x = min_pos + (max_pos - min_pos) * 0.21, y = -0.12, label = "Flanking", hjust = 0, size = 2.5, color = "#2563EB") +
+ annotate("rect", xmin = min_pos + (max_pos - min_pos) * 0.34, xmax = min_pos + (max_pos - min_pos) * 0.36,
+ ymin = -0.16, ymax = -0.08, fill = "#FEE2E2", color = "#FCA5A5") +
+ annotate("text", x = min_pos + (max_pos - min_pos) * 0.37, y = -0.12, label = "LOD-1.5 interval", hjust = 0, size = 2.5, color = "#B45309") +
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
+ ylim(-0.25, 1.45) +
+ labs(title = paste("Chromosome", chr,
+ paste0("(", nrow(chr_markers), " markers, ", nrow(chr_qtls), " QTL(s))")),
+ x = "Genomic Position", y = NULL) +
+ theme_bw(base_size = 11) +
+ 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 = 11, color = "#1E3A5F"))
+
+ plot_list[[as.character(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")))
+ n_rows <- ceiling(length(plot_list) / n_cols)
+
+ gridExtra::arrangeGrob(
+ grobs = plot_list, ncol = n_cols,
+ top = grid::textGrob(
+ "QTL Chromosome Map — LOD-1.5 Support Intervals (CIM v5)",
+ gp = grid::gpar(fontsize = 14, fontface = "bold", col = "#1E3A5F")),
+ bottom = grid::textGrob(
+ paste0("Generated: ", format(Sys.time(), "%Y-%m-%d %H:%M"),
+ " | Red = QTL peak | Blue = Flanking markers | Pink shading = LOD-1.5 interval"),
+ gp = grid::gpar(fontsize = 8, col = "#64748B"))
+ )
}
# ============================================================
# API / AI FUNCTIONS
# ============================================================
-
test_api_connection <- function(model_id = default_model) {
if (!token_exists) return(list(success = FALSE, error = "No token found"))
tryCatch({
@@ -542,7 +529,6 @@ test_api_connection <- function(model_id = default_model) {
api_test <- test_api_connection(default_model)
use_hf_api <- token_exists && api_test$success
-
cat("API Test:", if (api_test$success) "SUCCESS" else paste("FAILED -", api_test$error), "\n")
query_hf_api <- function(prompt, model_id = default_model, max_length = 500, temperature = 0.7) {
@@ -556,7 +542,8 @@ query_hf_api <- function(prompt, model_id = default_model, max_length = 500, tem
messages = list(
list(role = "system", content = "You are an expert bioinformatics assistant specializing in QTL analysis using Composite Interval Mapping. Be concise and helpful."),
list(role = "user", content = prompt)),
- max_tokens = as.integer(max_length), temperature = temperature), auto_unbox = TRUE),
+ max_tokens = as.integer(max_length),
+ temperature = temperature), auto_unbox = TRUE),
encode = "json", timeout(60))
if (status_code(response) == 200) {
result <- content(response, as = "parsed", encoding = "UTF-8")
@@ -568,12 +555,12 @@ 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 v4):")
+ ctx <- c("CURRENT ANALYSIS RESULTS (Composite Interval Mapping v5):")
if (!is.null(rv$cim_all) && !"Message" %in% colnames(rv$cim_all)) {
sig <- rv$cim_all[rv$cim_all$LOD >= rv$lod_threshold, ]
ctx <- c(ctx,
sprintf("\nCIM Results: %d significant QTLs above LOD %.1f", nrow(sig), rv$lod_threshold),
- sprintf("Top PVE_CIM (partial R²): %.1f%%", if (nrow(sig) > 0) max(sig$PVE_CIM_Percent) else 0))
+ sprintf("Top PVE_CIM (semi-partial R²): %.1f%%", if (nrow(sig) > 0) max(sig$PVE_CIM_Percent) else 0))
if (nrow(sig) > 0) {
top3 <- head(sig, 3)
ctx <- c(ctx, "\nTop QTLs:")
@@ -589,40 +576,40 @@ build_system_prompt <- function(rv) {
enhanced_rule_response <- function(user_message, rv) {
q <- tolower(trimws(user_message))
-
has_cim <- !is.null(rv$cim_all) && !"Message" %in% colnames(rv$cim_all)
has_qtl <- has_cim && any(rv$cim_all$LOD >= rv$lod_threshold)
has_perf <- !is.null(rv$performance_metrics)
- if (grepl("pve|variance explained|partial r2|what is pve|cim", q)) {
+ if (grepl("pve|variance explained|partial r2|what is pve|cim|semi.partial|low pve", q)) {
if (has_qtl) {
- sig <- rv$cim_all[rv$cim_all$LOD >= rv$lod_threshold, ]
- top_pve <- sig[which.max(sig$PVE_CIM_Percent), ]
+ sig <- rv$cim_all[rv$cim_all$LOD >= rv$lod_threshold, ]
+ top_pve <- sig[which.max(sig$PVE_CIM_Percent), ]
return(paste0(
- "📊 **PVE in CIM 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",
+ "📊 **PVE in CIM v5 — Semi-Partial R² (Fixed)**\n\n",
+ "**Why PVE was low in v4:**\n",
+ "• v4 used SS_total (raw) as denominator → marker contribution tiny vs full phenotypic variance\n",
+ "• With many cofactors, nearly all variance absorbed → partial R² ≈ 0\n\n",
+ "**v5 Fix — Semi-partial R²:**\n",
+ "• `PVE_marker (%)` = R² of lm(Y ~ a_code + d_code) × 100 [unconditional]\n",
+ "• `PVE_CIM (%)` = (RSS_reduced - RSS_full) / RSS_reduced × 100\n",
+ " Denominator = RESIDUAL SS after cofactors (not raw total)\n",
+ " = fraction of REMAINING variance explained by focal marker\n\n",
+ "**Adaptive cofactor cap:** min(K, sqrt(n_samples)) to prevent over-absorption\n\n",
"**Top QTL:** ", top_pve$Marker, " (Chr ", top_pve$Chromosome, ")\n",
"• LOD: ", round(top_pve$LOD, 2), "\n",
"• PVE_marker: ", round(top_pve$PVE_Marker_Percent, 1), "%\n",
- "• PVE_CIM (partial R²): ", round(top_pve$PVE_CIM_Percent, 1), "%\n",
- "• Additive effect: ", round(top_pve$Additive_Effect, 3)
+ "• PVE_CIM (semi-partial R²): ", round(top_pve$PVE_CIM_Percent, 1), "%\n",
+ "• Additive effect (-1/0/+1): ", round(top_pve$Additive_Effect, 3)
))
}
- return("Run CIM analysis first to see PVE values.")
+ return("Run CIM analysis first to see PVE values. v5 fixes the low-PVE issue using semi-partial R².")
}
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")
+ out <- "🎯 **QTL Support Intervals (LOD-1.5 drop)**\n\nInterval = markers within 1.5 LOD of peak\nRef: Lander & Botstein (1989) Genetics\n\n"
if (!is.null(qtl_table) && !"Message" %in% colnames(qtl_table)) {
for (i in 1:min(5, nrow(qtl_table))) {
r <- qtl_table[i, ]
@@ -641,7 +628,7 @@ enhanced_rule_response <- function(user_message, rv) {
if (has_qtl) {
sig <- rv$cim_all[rv$cim_all$LOD >= rv$lod_threshold, ]
top5 <- head(sig, 5)
- out <- "🎯 **Top QTLs by LOD (CIM v4)**\n\n"
+ out <- "🎯 **Top QTLs by LOD (CIM v5)**\n\n"
for (i in 1:nrow(top5)) {
r <- top5[i, ]
out <- paste0(out, i, ". **", r$Marker, "** (Chr ", r$Chromosome, ")\n",
@@ -659,23 +646,18 @@ enhanced_rule_response <- function(user_message, rv) {
val_r2 <- pm$Value[pm$Metric == "R² (Validation)"]
out <- paste0("📈 **Model Performance**\n\n• Training R²: ", round(pm$Value[pm$Metric == "R² (Train)"], 3),
"\n• Validation R²: **", round(val_r2, 3), "**\n\n")
- if (val_r2 < 0) {
- out <- paste0(out, "⚠️ Negative validation R² — overfitting or small sample.\n",
- "Try increasing sample size or reducing cofactors.")
- } else if (val_r2 >= 0.5) {
- out <- paste0(out, "🎯 Excellent validation R²!")
- }
+ if (val_r2 < 0) out <- paste0(out, "⚠️ Negative validation R² — overfitting or small sample.\nTry fewer cofactors or larger dataset.")
+ else if (val_r2 >= 0.5) out <- paste0(out, "🎯 Excellent validation R²!")
return(out)
}
- 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",
+ paste0("👋 Vanakam! TerraByte-AI (CIM v5 — PVE fixed)\n\n",
+ "Key fix in v5:\n",
+ "• PVE_CIM now uses semi-partial R² (denominator = residual SS after cofactors)\n",
+ "• PVE_marker = unconditional R² of marker-only model\n",
+ "• Adaptive cofactor count = min(K, √n) to prevent over-absorption\n",
+ "• Chromosome viz is now downloadable as PNG (same as on-screen)\n\n",
+ "Ask about: **PVE / low PVE** | **Intervals** | **Top QTLs** | **Performance**\n\n",
"Contact: ashmithamganesan@gmail.com, P.sinha@cgiar.org")
}
@@ -691,9 +673,8 @@ generate_ai_response <- function(user_message, rv, model_id = default_model) {
}
# ============================================================
-# UI — WHITE BACKGROUND
+# UI
# ============================================================
-
ui <- fluidPage(
shinyjs::useShinyjs(),
tags$head(
@@ -732,57 +713,32 @@ ui <- fluidPage(
});
")),
tags$style(HTML("
- /* ===================== WHITE THEME ===================== */
:root {
- --bg-primary:#FFFFFF;
- --bg-secondary:#F8FAFC;
- --bg-tertiary:#F1F5F9;
- --border:#E2E8F0;
- --text-primary:#1E293B;
- --text-secondary:#475569;
- --text-muted:#94A3B8;
- --accent:#1D4ED8;
- --accent-hover:#1E40AF;
- --success:#15803D;
- --warning:#B45309;
- --danger:#DC2626;
- --purple:#7C3AED;
- --teal:#0F766E;
- --font-mono:'IBM Plex Mono',monospace;
- --font-sans:'IBM Plex Sans',sans-serif;
+ --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 */
.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;}
-
- /* 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 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;}
-
- /* 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;}
-
- /* 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:#FFFFFF;}
.btn-primary:hover{background:var(--accent-hover);border-color:var(--accent-hover);color:#FFFFFF;}
@@ -792,8 +748,6 @@ ui <- fluidPage(
.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:#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;}
@@ -803,8 +757,6 @@ ui <- fluidPage(
.dataTables_filter input,.dataTables_length select{background:#FFFFFF!important;border:1px solid var(--border)!important;color:var(--text-primary)!important;border-radius:3px;}
.paginate_button{color:var(--text-secondary)!important;}
.paginate_button.current{background:var(--accent)!important;color:white!important;border-color:var(--accent)!important;}
-
- /* Chromosome 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;}
@@ -821,8 +773,6 @@ ui <- fluidPage(
.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(29,78,216,.3);transition:all .2s;color:white;font-size:24px;}
#chat-toggle-btn:hover{transform:scale(1.05);}
@@ -873,49 +823,48 @@ ui <- fluidPage(
#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:#1D4ED8;"), "QTL-Mapper CIM v4"),
+ title = tags$span(tags$i(class = "fas fa-dna", style = "margin-right:8px;color:#1D4ED8;"), "QTL-Mapper CIM v5"),
id = "nav",
# ---- DATA UPLOAD ----
tabPanel("Data Upload", icon = icon("upload"),
div(class = "main-header",
- h2(tags$i(class = "fas fa-upload", style = "margin-right:8px;"), "Data Upload — CIM v4"),
- p("Corrected formulas: -1/0/+1 additive coding | partial R² PVE | LOD-1.5 support intervals")
+ h2(tags$i(class = "fas fa-upload", style = "margin-right:8px;"), "Data Upload — CIM v5"),
+ p("Semi-partial R² PVE | -1/0/+1 coding | LOD-1.5 intervals | downloadable chromosome viz")
),
- fluidRow(
- column(12,
- div(class = "cim-box",
- 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")
- )
+ fluidRow(column(12,
+ div(class = "cim-box",
+ div(class = "box-title", tags$i(class = "fas fa-check-circle", style = "margin-right:6px;"), "CIM v5 — PVE Formula Fix"),
+ tags$pre(style = "background:transparent;border:none;margin:0;color:#166534;font-size:11px;",
+ "WHY PVE WAS LOW IN v4:\n",
+ " Partial R² = (RSS_reduced - RSS_full) / SS_total_raw\n",
+ " When cofactors explain 90% of variance: SS_total = 1000, SS_marker_given_cofactors = 20\n",
+ " PVE_CIM = 20/1000 = 2% ← tiny despite real effect!\n\n",
+ "v5 FIX — Semi-partial R² (denominator = residual SS after cofactors):\n",
+ " SS_denom = RSS_reduced = residual SS after cofactors alone\n",
+ " PVE_CIM = (RSS_reduced - RSS_full) / RSS_reduced × 100\n",
+ " Same example: 20/100 = 20% ← fraction of REMAINING variance explained\n\n",
+ "ADDITIONAL v5 FIX — Adaptive cofactor count:\n",
+ " Max cofactors = min(K_user, sqrt(n_samples)) ← prevents over-absorption\n",
+ " With n=100 samples: max cofactors = 10 regardless of user setting\n\n",
+ "PVE_marker = unconditional R² of lm(Y ~ a_code + d_code) × 100 [no cofactors]\n",
+ " This is always >= PVE_CIM and shows total marker association strength")
)
- ),
+ )),
fluidRow(
column(4,
div(class = "card",
div(class = "card-header", tags$i(class = "fas fa-table", style = "margin-right:6px;"), "Training Data"),
div(class = "card-body",
- fileInput("genotype_file", "Training Genotype CSV", accept = ".csv", buttonLabel = "Browse"),
+ fileInput("genotype_file", "Training Genotype CSV", accept = ".csv", buttonLabel = "Browse"),
helpText("Row1=header(id,markers), Row2=chromosomes, Row3=positions, rest=samples. Coded 0/1/2."),
- fileInput("phenotype_file", "Training Phenotype CSV", accept = ".csv", buttonLabel = "Browse"),
+ fileInput("phenotype_file", "Training Phenotype CSV", accept = ".csv", buttonLabel = "Browse"),
helpText("id column + numeric trait columns."),
selectInput("phenotype_column", "Select Phenotype Column", choices = NULL)
)
@@ -925,12 +874,13 @@ ui <- fluidPage(
div(class = "card",
div(class = "card-header", tags$i(class = "fas fa-sliders-h", style = "margin-right:6px;color:#7C3AED;"), "CIM Parameters"),
div(class = "card-body",
- sliderInput("test_size", "Validation Proportion", min = 0.1, max = 0.5, value = 0.2, step = 0.05),
- numericInput("lod_threshold","LOD Threshold", value = 2.0, min = 0.5, max = 10.0, step = 0.1),
- numericInput("n_cofactors", "CIM Cofactors (K)", value = 10, min = 1, max = 30, step = 1),
- numericInput("window_size", "Exclusion Window (±markers)", value = 10, min = 1, max = 30, step = 1),
- 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"),
+ sliderInput("test_size", "Validation Proportion", min = 0.1, max = 0.5, value = 0.2, step = 0.05),
+ numericInput("lod_threshold","LOD Threshold", value = 2.0, min = 0.5, max = 10.0, step = 0.1),
+ numericInput("n_cofactors", "CIM Cofactors (K)", value = 10, min = 1, max = 30, step = 1),
+ helpText("Actual cofactors used = min(K, √n_samples) — adaptive to prevent over-absorption"),
+ numericInput("window_size", "Exclusion Window (±markers)", value = 10, min = 1, max = 30, step = 1),
+ numericInput("lod_drop", "LOD Drop for Interval", value = 1.5, min = 0.5, max = 3.0, step = 0.5),
+ helpText("LOD-1.5 is the standard QTL confidence interval width"),
actionButton("run_analysis", "Run CIM Analysis", class = "btn-primary btn-block", icon = icon("play"))
)
)
@@ -949,44 +899,39 @@ ui <- fluidPage(
)
)
),
- fluidRow(
- column(12,
- div(class = "card",
- div(class = "card-header", "Data Preview"),
- div(class = "card-body",
- tabsetPanel(
- tabPanel("Training Genotype", DTOutput("geno_preview")),
- tabPanel("Training Phenotype", DTOutput("pheno_preview")),
- tabPanel("Test Genotype", DTOutput("test_geno_preview")),
- tabPanel("Predicted Test Phenotype", DTOutput("predicted_test_pheno_preview"))
- )
+ fluidRow(column(12,
+ div(class = "card",
+ div(class = "card-header", "Data Preview"),
+ div(class = "card-body",
+ tabsetPanel(
+ tabPanel("Training Genotype", DTOutput("geno_preview")),
+ tabPanel("Training Phenotype", DTOutput("pheno_preview")),
+ tabPanel("Test Genotype", DTOutput("test_geno_preview")),
+ tabPanel("Predicted Test Phenotype", DTOutput("predicted_test_pheno_preview"))
)
)
)
- )
+ ))
),
# ---- 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 v4"),
- p("LOD scan | LOD-1.5 support intervals | corrected partial R² PVE | -1/0/+1 additive coding")
+ h2(tags$i(class = "fas fa-chart-line", style = "margin-right:8px;"), "CIM Results v5"),
+ p("Semi-partial R² PVE (fixed) | LOD-1.5 intervals | -1/0/+1 additive coding | downloadable plots")
),
- # Download bar
- fluidRow(
- 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(12,
+ div(class = "download-bar",
+ tags$span(tags$i(class = "fas fa-download"), " Download:"),
+ downloadButton("download_manhattan_plot", "Manhattan Plot (.png)", class = "btn btn-primary"),
+ 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", "CIM Manhattan Plot (LOD Scores)"), div(class = "card-body", plotlyOutput("lod_plot_2d", height = "500px")))),
column(6, div(class = "card",
- div(class = "card-header", "Chromosome Visualization — LOD-1.5 Intervals"),
+ div(class = "card-header", "Chromosome Visualization — LOD-1.5 Intervals (matches download PNG)"),
div(class = "card-body",
div(class = "chr-legend",
div(class = "legend-item", div(class = "legend-dot", style = "background:#DC2626;"), "Significant QTL"),
@@ -1007,30 +952,35 @@ ui <- fluidPage(
column(4, div(class = "card", div(class = "card-header", "Train: Predicted vs Observed"), div(class = "card-body", plotlyOutput("regression_plot_train", height = "300px")))),
column(4, div(class = "card", div(class = "card-header", "Validation: Predicted vs Observed"), div(class = "card-body", plotlyOutput("regression_plot_test", height = "300px"))))
),
- fluidRow(
- column(12, div(class = "card",
- div(class = "card-header", "CIM QTL Table — LOD-1.5 Support Intervals | Partial R² PVE | -1/0/+1 Additive"),
+ fluidRow(column(12,
+ div(class = "card",
+ div(class = "card-header", "CIM QTL Table — Semi-Partial R² PVE | LOD-1.5 Intervals | -1/0/+1 Additive"),
div(class = "card-body",
+ div(style = "background:#FEF9C3;border:1px solid #FDE047;border-radius:4px;padding:8px 12px;margin-bottom:8px;font-size:11px;font-family:'IBM Plex Mono';color:#713F12;",
+ "PVE_CIM = (RSS_cofactors_only - RSS_with_marker) / RSS_cofactors_only × 100 [% of cofactor-residual variance]",
+ tags$br(),
+ "PVE_Marker = R² of lm(Y ~ a_code + d_code) × 100 [% of total variance, unconditional]"
+ ),
DTOutput("qtl_effects_table_train")
)
- ))
- ),
- fluidRow(
- column(12, div(class = "card",
+ )
+ )),
+ fluidRow(column(12,
+ div(class = "card",
div(class = "card-header", "Epistasis Analysis"),
div(class = "card-body",
DTOutput("epistasis_table"),
plotlyOutput("epistasis_heatmap", height = "400px")
)
- ))
- )
+ )
+ ))
),
# ---- DOMESTICATION ----
tabPanel("Domestication", icon = icon("leaf"),
div(class = "main-header",
- h2(tags$i(class = "fas fa-leaf", style = "margin-right:8px;"), "Domestication Analysis"),
- p("Fst, Tajima's D, nucleotide diversity — needs population metadata")
+ h2(tags$i(class = "fas fa-leaf", style = "margin-right:8px;"), "Domestication Analysis"),
+ p("Fst, Tajima's D, nucleotide diversity — needs population metadata")
),
fluidRow(
column(4,
@@ -1054,25 +1004,22 @@ ui <- fluidPage(
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,
- div(class = "card",
- div(class = "card-header", "Selection Signatures"),
- div(class = "card-body",
- DTOutput("selection_table"),
- tags$br(),
- downloadButton("download_selection", "Download Selection Results (.xlsx)")
- )
+ fluidRow(column(12,
+ div(class = "card",
+ div(class = "card-header", "Selection Signatures"),
+ div(class = "card-body",
+ DTOutput("selection_table"), tags$br(),
+ downloadButton("download_selection", "Download Selection Results (.xlsx)")
)
)
- )
+ ))
),
# ---- INTERPRETATION ----
tabPanel("Interpretation", icon = icon("lightbulb"),
div(class = "main-header",
- h2(tags$i(class = "fas fa-lightbulb", style = "margin-right:8px;"), "Results Interpretation"),
- p("LOD-1.5 interval sizes | partial R² PVE | dominance classification")
+ h2(tags$i(class = "fas fa-lightbulb", style = "margin-right:8px;"), "Results Interpretation"),
+ p("Semi-partial R² PVE | LOD-1.5 interval sizes | dominance classification")
),
fluidRow(column(12, div(class = "card", div(class = "card-header", "Analysis Summary"), div(class = "card-body", uiOutput("analysis_summary"))))),
fluidRow(
@@ -1086,43 +1033,47 @@ ui <- fluidPage(
# ---- 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 v4")
+ h2(tags$i(class = "fas fa-info-circle", style = "margin-right:8px;"), "About QTL-Mapper CIM v5")
),
- fluidRow(
- column(8, offset = 2,
- div(class = "card",
- div(class = "card-body",
- h4(style = "color:#1D4ED8;font-family:'IBM Plex Mono';margin-bottom:12px;", "Changes in 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:#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 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")
- )
+ fluidRow(column(8, offset = 2,
+ div(class = "card",
+ div(class = "card-body",
+ h4(style = "color:#1D4ED8;font-family:'IBM Plex Mono';margin-bottom:12px;", "Changes in v5 (PVE Fix)"),
+ div(class = "fix-box",
+ tags$pre(style = "background:transparent;border:none;margin:0;color:#92400E;font-size:11px;",
+ "v4 BUG: PVE very low / near-zero\n\n",
+ "ROOT CAUSE:\n",
+ " When cofactors explain most variance, SS_total_raw >> (RSS_reduced - RSS_full)\n",
+ " Example: n=200, 10 cofactors explaining 80% variance:\n",
+ " SS_total_raw = 1000, RSS_reduced = 200, RSS_full = 160\n",
+ " v4 PVE_CIM = (200-160)/1000 = 4% ← deflated!\n",
+ " v5 PVE_CIM = (200-160)/200 = 20% ← correct semi-partial R²\n\n",
+ "v5 FIX 1 — Semi-partial R²:\n",
+ " PVE_CIM = (RSS_reduced - RSS_full) / RSS_reduced × 100\n",
+ " Denominator = variance REMAINING after cofactors, not raw total\n\n",
+ "v5 FIX 2 — Adaptive cofactor cap:\n",
+ " n_cofactors_used = min(n_cofactors_user, floor(sqrt(n_samples)))\n",
+ " Prevents too many cofactors absorbing all marker signal\n\n",
+ "v5 FIX 3 — Chromosome viz download:\n",
+ " ggplot2 PNG export now shows SAME layout as on-screen display\n",
+ " Includes LOD-1.5 intervals, QTL labels with LOD + PVE, flanking markers\n\n",
+ "KEPT FROM v4:\n",
+ " Additive coding: -1/0/+1 | LOD-1.5 support intervals\n",
+ " PVE_marker = unconditional R² (marker alone vs null)")
+ ),
+ h4(style = "color:#1D4ED8;font-family:'IBM Plex Mono';margin:16px 0 8px;", "Thresholds"),
+ tags$ul(style = "color:#475569;line-height:2;",
+ tags$li("LOD > 2: Suggestive | LOD > 3: Significant | LOD > 5: Highly significant"),
+ tags$li("PVE_CIM > 20%: Major (of residual) | 10-20%: Moderate | <10%: Minor"),
+ tags$li("PVE_marker > 15%: Major QTL | 5-15%: Moderate | <5%: Minor"),
+ tags$li("|d/a| > 1: Overdominance | ~1: Dominance | 0.2-0.5: Partial | <0.2: Additive"),
+ tags$li("LOD-1.5 interval: Lander & Botstein (1989) Genetics 121:185"),
+ tags$li("Semi-partial R²: Lynch & Walsh (1998) Genetics & Analysis of Quantitative Traits"),
+ tags$li("CIM: Zeng (1993) PNAS 90:10972; Zeng (1994) Genetics 136:1457")
)
)
)
- )
+ ))
)
),
@@ -1136,7 +1087,7 @@ ui <- fluidPage(
tags$div(class = "chat-title",
tags$div(class = "chat-avatar", "AI"),
tags$div(
- tags$h4("QTL-CIM AI Assistant v4"),
+ tags$h4("QTL-CIM AI Assistant v5"),
tags$p(id = "model_status_text",
if (token_exists) "AI mode ready" else "Rule-based mode",
class = if (token_exists) "ai-mode" else "")
@@ -1154,14 +1105,14 @@ ui <- fluidPage(
)
),
tags$div(class = "quick-questions",
- 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$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q','Why is PVE low? How is it fixed in v5?',{priority:'event'});", "Low PVE fix"),
+ tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q','Show top QTLs',{priority:'event'});", "Top QTLs"),
+ tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q','Explain LOD support interval',{priority:'event'});", "Intervals"),
+ tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q','Why is my R2 negative?',{priority:'event'});", "Negative R²")
),
tags$div(id = "chat_messages", uiOutput("chat_display")),
tags$div(id = "chat-footer",
- tags$textarea(id = "chat_input", placeholder = "Ask about CIM v4 results... (Enter to send)", rows = "2"),
+ tags$textarea(id = "chat_input", placeholder = "Ask about CIM v5... (Enter to send)", rows = "2"),
tags$div(class = "chat-actions",
actionButton("send_chat", "Send", icon = icon("paper-plane"), class = "btn-primary"),
actionButton("clear_chat", "Clear", icon = icon("trash-alt"), class = "btn-danger")
@@ -1177,7 +1128,6 @@ ui <- fluidPage(
# ============================================================
# SERVER
# ============================================================
-
server <- function(input, output, session) {
values <- reactiveValues(
@@ -1206,10 +1156,7 @@ server <- function(input, output, session) {
)
# ---- Model selector ----
- observe({
- req(input$selected_model)
- values$current_model <- input$selected_model
- })
+ observe({ req(input$selected_model); values$current_model <- input$selected_model })
observeEvent(input$test_model_btn, {
req(input$selected_model)
@@ -1244,28 +1191,20 @@ server <- function(input, output, session) {
add_message("assistant", response, model_used = if (token_exists) gsub(".*/", "", model_id) else NULL)
}
- observeEvent(input$send_chat, {
- user_text <- trimws(input$chat_input)
- if (nchar(user_text) == 0) return()
- updateTextAreaInput(session, "chat_input", value = "")
- process_message(user_text)
- })
-
+ observeEvent(input$send_chat, { user_text <- trimws(input$chat_input); if (nchar(user_text) == 0) return(); updateTextAreaInput(session, "chat_input", value = ""); process_message(user_text) })
observeEvent(input$quick_q, { req(input$quick_q); process_message(input$quick_q) })
- observeEvent(input$clear_chat, {
- values$chat_messages <- list()
- add_message("assistant", "Chat cleared. How can I help?")
- })
+ observeEvent(input$clear_chat, { values$chat_messages <- list(); add_message("assistant", "Chat cleared. How can I help?") })
observe({
if (length(values$chat_messages) == 0) {
add_message("assistant", paste0(
- "👋 Vanakam! TerraByte-AI (CIM 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",
+ "👋 Vanakam! TerraByte-AI (CIM v5 — PVE fixed)\n\n",
+ "**v5 Key Fix — Semi-Partial R²:**\n",
+ "• PVE_CIM now uses RSS_cofactors as denominator (not SS_total_raw)\n",
+ "• This prevents near-zero PVE when cofactors dominate\n",
+ "• Adaptive cofactor cap = min(K, √n_samples)\n",
+ "• Chromosome viz is downloadable as PNG (same as on-screen)\n\n",
+ "Click 'Low PVE fix' above for a detailed explanation.\n",
"Contact: ashmithamganesan@gmail.com, P.sinha@cgiar.org"
))
}
@@ -1296,7 +1235,6 @@ server <- function(input, output, session) {
# ============================================================
# DATA LOADING
# ============================================================
-
observeEvent(input$genotype_file, {
req(input$genotype_file)
tryCatch({
@@ -1341,9 +1279,7 @@ server <- function(input, output, session) {
req(input$pop_file)
tryCatch({
pd <- read.csv(input$pop_file$datapath)
- if (!all(c("id", "population") %in% colnames(pd))) {
- showNotification("Need 'id' and 'population' columns", type = "error"); return()
- }
+ if (!all(c("id", "population") %in% colnames(pd))) { showNotification("Need 'id' and 'population' columns", type = "error"); return() }
values$pop_data <- pd
showNotification(paste("Population data:", nrow(pd), "samples"), type = "message")
}, error = function(e) showNotification(paste("Pop error:", e$message), type = "error"))
@@ -1362,19 +1298,18 @@ 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$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$geno_preview <- renderDT({ req(input$genotype_file); datatable(head(read.csv(input$genotype_file$datapath), 10), options = list(scrollX = TRUE, pageLength = 5)) })
+ output$pheno_preview <- renderDT({ req(input$phenotype_file); datatable(head(read.csv(input$phenotype_file$datapath), 10), options = list(scrollX = TRUE, pageLength = 5)) })
+ output$test_geno_preview <- renderDT({ req(input$test_genotype_file); datatable(head(read.csv(input$test_genotype_file$datapath), 10), options = list(scrollX = TRUE, pageLength = 5)) })
+ output$pop_preview <- renderDT({ req(input$pop_file); datatable(head(read.csv(input$pop_file$datapath), 10), options = list(scrollX = TRUE, pageLength = 5)) })
output$predicted_test_pheno_preview <- renderDT({ req(values$predicted_test_phenotype_data); datatable(values$predicted_test_phenotype_data, options = list(scrollX = TRUE, pageLength = 5)) })
# ============================================================
# MAIN CIM ANALYSIS
# ============================================================
-
observeEvent(input$run_analysis, {
req(values$genotype_data, values$phenotype_data, input$phenotype_column)
- showNotification("Starting CIM v4 analysis...", type = "message")
+ showNotification("Starting CIM v5 analysis...", type = "message")
values$lod_threshold <- input$lod_threshold
values$lod_drop <- input$lod_drop
@@ -1390,8 +1325,7 @@ server <- function(input, output, session) {
X_train <- X[train_index, , drop = FALSE]; X_val <- X[-train_index, , drop = FALSE]
y_train <- y[train_index]; y_val <- y[-train_index]
- # ---- Run CIM scan ----
- withProgress(message = "Running CIM v4 genome scan...", value = 0.1, {
+ withProgress(message = "Running CIM v5 genome scan...", value = 0.1, {
cim_results <- run_cim(
genotype_matrix = X_train,
phenotype_vector = y_train,
@@ -1405,17 +1339,10 @@ server <- function(input, output, session) {
values$cim_all <- cim_results
- # ---- 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) {
- # 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
- )
+ sig_qtls <- add_lod_support_interval(sig_qtls, cim_results, input$lod_drop)
values$qtl_effects_train <- sig_qtls[order(-sig_qtls$LOD), ]
} else {
values$qtl_effects_train <- data.frame(Message = paste("No QTLs above LOD", input$lod_threshold))
@@ -1424,7 +1351,7 @@ server <- function(input, output, session) {
values$qtl_effects_train <- cim_results
}
- # ---- RF model for prediction ----
+ # 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]
@@ -1452,34 +1379,30 @@ server <- function(input, output, session) {
values$train_predictions <- data.frame(Observed = y_train, Predicted = y_train_pred)
values$test_predictions <- data.frame(Observed = y_val, Predicted = y_val_pred)
- # ---- Epistasis ----
+ # Epistasis
if (!is.null(values$qtl_effects_train) && !"Message" %in% colnames(values$qtl_effects_train)) {
sig_markers <- values$qtl_effects_train$Marker
all_markers_v <- colnames(X_train)
epi_list <- list()
-
withProgress(message = "Calculating epistasis...", value = 0, {
for (m1 in sig_markers) {
for (m2 in all_markers_v) {
if (m1 == m2) next
tryCatch({
d <- data.frame(y = y_train, m1 = X_train[, m1], m2 = X_train[, m2])
- d <- na.omit(d)
- if (nrow(d) < 10) next
+ d <- na.omit(d); if (nrow(d) < 10) next
fit <- lm(y ~ m1 * m2, data = d)
ct <- summary(fit)$coefficients
if ("m1:m2" %in% rownames(ct)) {
epi_list[[length(epi_list) + 1]] <- data.frame(
QTL1 = m1, QTL2 = m2,
Interaction_p = ct["m1:m2", "Pr(>|t|)"],
- Effect_Size = coef(fit)["m1:m2"],
- stringsAsFactors = FALSE)
+ Effect_Size = coef(fit)["m1:m2"], stringsAsFactors = FALSE)
}
}, error = function(e) {})
}
}
})
-
if (length(epi_list) > 0) {
ea <- do.call(rbind, epi_list)
values$epistasis_all <- ea
@@ -1490,32 +1413,31 @@ 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, na.rm = TRUE), 1) else 0
+ n_qtl <- if (!is.null(values$qtl_effects_train) && !"Message" %in% colnames(values$qtl_effects_train)) nrow(values$qtl_effects_train) else 0
+ max_pve <- if (n_qtl > 0) round(max(values$qtl_effects_train$PVE_CIM_Percent, na.rm = TRUE), 1) else 0
+ max_pve_m <- if (n_qtl > 0) round(max(values$qtl_effects_train$PVE_Marker_Percent, na.rm = TRUE), 1) else 0
- showNotification("CIM v4 analysis completed!", type = "message")
+ showNotification("CIM v5 analysis completed!", type = "message")
add_message("assistant", paste0(
- "✅ **CIM v4 analysis complete!**\n\n",
- "• Found **", n_qtl, " QTLs** above LOD ", input$lod_threshold, "\n",
- "• Top QTL PVE_CIM (partial R²): **", max_pve_cim, "%**\n",
+ "✅ **CIM v5 analysis complete!**\n\n",
+ "• **", n_qtl, " QTLs** above LOD ", input$lod_threshold, "\n",
+ "• Top PVE_marker: **", max_pve_m, "%** | Top PVE_CIM: **", max_pve, "%**\n",
"• Validation R²: **", round(val_r2, 3), "**\n",
- "• 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!"
+ "• PVE formula: semi-partial R² ✅\n",
+ "• Cofactor cap: min(", input$n_cofactors, ", √", length(y_train), ") = ", min(input$n_cofactors, floor(sqrt(length(y_train)))), " ✅\n\n",
+ "Click 'Low PVE fix' in chat or check the Results tab!"
))
updateTabsetPanel(session, "nav", selected = "Results")
}, error = function(e) {
- showNotification(paste("CIM v4 Error:", e$message), type = "error")
- cat("CIM v4 ERROR:", e$message, "\n")
+ showNotification(paste("CIM v5 Error:", e$message), type = "error")
+ cat("CIM v5 ERROR:", e$message, "\n")
})
})
# ============================================================
# PREDICT TEST PHENOTYPES
# ============================================================
-
observeEvent(input$predict_test_phenotype, {
req(values$model_fit, values$test_genotype_data)
tryCatch({
@@ -1532,7 +1454,6 @@ server <- function(input, output, session) {
# ============================================================
# DOMESTICATION
# ============================================================
-
calculate_selection_metrics <- function(geno_mat, pop_data, marker_info) {
metrics_list <- list()
for (marker in colnames(geno_mat)) {
@@ -1578,79 +1499,65 @@ server <- function(input, output, session) {
})
# ============================================================
- # MANHATTAN HELPER (plotly — interactive)
+ # MANHATTAN HELPER (plotly)
# ============================================================
-
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 = "#FFFFFF", paper_bgcolor = "#FFFFFF", font = list(color = "#475569")))
+ blank <- plot_ly() %>% layout(title = title, plot_bgcolor = "#FFFFFF", paper_bgcolor = "#FFFFFF", font = list(color = "#475569"))
+ if (is.null(data) || nrow(data) == 0 || "Message" %in% colnames(data)) return(blank)
pd <- data[!is.na(data[[y_col]]) & !is.na(data$Chromosome), ]
- if (nrow(pd) == 0) return(plot_ly() %>% layout(title = "No valid data",
- plot_bgcolor = "#FFFFFF", paper_bgcolor = "#FFFFFF", font = list(color = "#475569")))
- chroms <- unique(pd$Chromosome)
+ if (nrow(pd) == 0) return(blank)
+ chroms <- sort(unique(as.character(pd$Chromosome)), method = "radix")
chrom_pos <- data.frame()
for (i in seq_along(chroms)) {
cd <- pd[pd$Chromosome == chroms[i], ]
- if (nrow(cd) > 0) {
- cd$ChromIndex <- i
- cd$PosScaled <- cd$Position / max(cd$Position, na.rm = TRUE) + (i - 1)
- chrom_pos <- rbind(chrom_pos, cd)
- }
+ if (nrow(cd) > 0) { cd$PosScaled <- cd$Position / max(cd$Position, na.rm = TRUE) + (i - 1); chrom_pos <- rbind(chrom_pos, cd) }
}
- pal <- rep(c("#1D4ED8", "#64748B"), ceiling(length(chroms) / 2))
+ pal <- rep(c("#1D4ED8","#64748B"), ceiling(length(chroms)/2))
p <- plot_ly() %>%
add_trace(data = chrom_pos, x = ~PosScaled, y = as.formula(paste0("~", y_col)),
- type = "scatter", mode = "markers", color = ~factor(Chromosome),
- colors = pal[1:length(chroms)],
+ type = "scatter", mode = "markers", color = ~factor(Chromosome), colors = pal[1:length(chroms)],
marker = list(size = 6, opacity = 0.7),
- text = ~paste("Marker:", Marker, "
Chr:", Chromosome, "
Pos:", Position,
- "
", y_label, ":", round(get(y_col), 3)),
+ text = ~paste("Marker:", Marker, "
Chr:", Chromosome, "
", y_label, ":", round(get(y_col), 3)),
hoverinfo = "text", showlegend = FALSE)
if (!is.null(threshold) && !is.na(threshold))
- p <- p %>% add_segments(
- x = min(chrom_pos$PosScaled, na.rm = TRUE), xend = max(chrom_pos$PosScaled, na.rm = TRUE),
- y = threshold, yend = threshold,
- line = list(color = "#DC2626", dash = "dash", width = 1.5))
+ p <- p %>% add_segments(x = min(chrom_pos$PosScaled, na.rm = TRUE), xend = max(chrom_pos$PosScaled, na.rm = TRUE),
+ y = threshold, yend = threshold, line = list(color = "#DC2626", dash = "dash", width = 1.5))
p %>% layout(title = list(text = title, font = list(color = "#1E293B")),
xaxis = list(title = "Chromosome", color = "#475569",
- ticktext = chroms,
- tickvals = tapply(chrom_pos$PosScaled, chrom_pos$Chromosome, median, na.rm = TRUE),
+ ticktext = chroms, tickvals = tapply(chrom_pos$PosScaled, chrom_pos$Chromosome, median, na.rm = TRUE),
tickangle = 45, gridcolor = "#F1F5F9"),
yaxis = list(title = y_label, color = "#475569", gridcolor = "#F1F5F9"),
- plot_bgcolor = "#FFFFFF", paper_bgcolor = "#FFFFFF",
- font = list(color = "#475569"))
+ plot_bgcolor = "#FFFFFF", paper_bgcolor = "#FFFFFF", font = list(color = "#475569"))
}
# ============================================================
# PLOTS
# ============================================================
-
- output$lod_plot_2d <- renderPlotly({
- req(values$cim_all)
- create_manhattan(values$cim_all, "LOD", "CIM Manhattan Plot (LOD Scores)", input$lod_threshold, "LOD Score")
- })
-
- output$fst_plot <- renderPlotly({ req(values$selection_metrics); create_manhattan(values$selection_metrics, "Fst", "Fst Plot", input$fst_threshold, "Fst") })
+ output$lod_plot_2d <- renderPlotly({ req(values$cim_all); create_manhattan(values$cim_all, "LOD", "CIM Manhattan Plot", input$lod_threshold, "LOD Score") })
+ output$fst_plot <- renderPlotly({ req(values$selection_metrics); create_manhattan(values$selection_metrics, "Fst", "Fst Plot", input$fst_threshold, "Fst") })
output$tajima_plot <- renderPlotly({
req(values$selection_metrics)
if ("Message" %in% colnames(values$selection_metrics))
return(plot_ly() %>% layout(title = "No data", plot_bgcolor = "#FFFFFF", paper_bgcolor = "#FFFFFF"))
- d <- values$selection_metrics
- chroms <- unique(d$Chromosome)
- cp <- data.frame()
+ d <- values$selection_metrics
+ chroms <- sort(unique(as.character(d$Chromosome)), method = "radix")
+ cp <- data.frame()
for (i in seq_along(chroms)) {
cd <- d[d$Chromosome == chroms[i], ]
if (nrow(cd) > 0) { cd$PosScaled <- cd$Position / max(cd$Position, na.rm = TRUE) + (i - 1); cp <- rbind(cp, cd) }
}
plot_ly() %>%
- add_trace(data = cp, x = ~PosScaled, y = ~Tajima_D_Dom, type = "scatter", mode = "markers", name = "Domesticated", marker = list(size = 5, color = "#1D4ED8", opacity = .7)) %>%
- add_trace(data = cp, x = ~PosScaled, y = ~Tajima_D_Wild, type = "scatter", mode = "markers", name = "Wild", marker = list(size = 5, color = "#F97316", opacity = .7)) %>%
+ add_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)) %>%
+ 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"),
+ 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"))
})
@@ -1660,7 +1567,8 @@ server <- function(input, output, session) {
plot_ly(data = values$performance_metrics, x = ~Metric, y = ~Value, type = "bar",
marker = list(color = c("#1D4ED8","#3B82F6","#15803D","#22C55E")),
text = ~round(Value, 3), textposition = "outside") %>%
- layout(title = "Model Performance", yaxis = list(title = "Value", range = c(0, 1.1), gridcolor = "#F1F5F9"),
+ 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"))
})
@@ -1671,7 +1579,8 @@ server <- function(input, output, session) {
type = "scatter", mode = "markers", marker = list(size = 6, color = "#1D4ED8", opacity = .7)) %>%
add_trace(x = range(values$train_predictions$Observed), y = range(values$train_predictions$Observed),
type = "scatter", mode = "lines", line = list(color = "#DC2626", dash = "dash")) %>%
- layout(title = "Training Set", xaxis = list(title = "Observed", gridcolor = "#F1F5F9"),
+ 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"))
})
@@ -1682,53 +1591,36 @@ server <- function(input, output, session) {
type = "scatter", mode = "markers", marker = list(size = 6, color = "#15803D", opacity = .7)) %>%
add_trace(x = range(values$test_predictions$Observed), y = range(values$test_predictions$Observed),
type = "scatter", mode = "lines", line = list(color = "#DC2626", dash = "dash")) %>%
- layout(title = "Validation Set", xaxis = list(title = "Observed", gridcolor = "#F1F5F9"),
+ 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 = "#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 = "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"))
- })
-
# ============================================================
# TABLES
# ============================================================
-
output$qtl_effects_table_train <- renderDT({
req(values$qtl_effects_train)
if ("Message" %in% colnames(values$qtl_effects_train))
return(datatable(data.frame(Status = values$qtl_effects_train$Message[1]), options = list(dom = "t")))
-
display_cols <- intersect(
- c("Marker", "Chromosome", "Position", "LOD", "P_Value",
- "PVE_Marker_Percent", "PVE_CIM_Percent",
- "Additive_Effect", "SE_Additive", "CI_Lower", "CI_Upper",
- "Dominance_Effect", "SE_Dominance", "Dominance_Ratio", "Dominance_Class",
- "N_Cofactors", "N_Samples", "N_Heterozygotes",
- "Interval_Start", "Interval_End", "Interval_Size_Mb",
- "Low_Flank", "High_Flank"),
+ c("Marker","Chromosome","Position","LOD","P_Value",
+ "PVE_Marker_Percent","PVE_CIM_Percent",
+ "Additive_Effect","SE_Additive","CI_Lower","CI_Upper",
+ "Dominance_Effect","SE_Dominance","Dominance_Ratio","Dominance_Class",
+ "N_Cofactors","N_Samples","N_Heterozygotes",
+ "Interval_Start","Interval_End","Interval_Size_Mb",
+ "Low_Flank","High_Flank"),
colnames(values$qtl_effects_train))
-
datatable(values$qtl_effects_train[, display_cols],
options = list(pageLength = 10, scrollX = TRUE), rownames = FALSE,
caption = tags$caption(style = "caption-side:top;font-size:11px;color:#475569;",
- "PVE_Marker = partial R²(null vs add+dom) | PVE_CIM = partial R²(no focal vs with focal) | Interval = LOD-1.5 support")) %>%
+ "PVE_CIM = semi-partial R² (% of cofactor-residual variance) | PVE_Marker = unconditional R² | Interval = LOD-1.5")) %>%
formatRound(intersect(c("LOD","PVE_Marker_Percent","PVE_CIM_Percent",
"Additive_Effect","SE_Additive","CI_Lower","CI_Upper",
"Dominance_Effect","SE_Dominance","Dominance_Ratio","Interval_Size_Mb"), display_cols), 3) %>%
- formatSignif(intersect(c("P_Value"), display_cols), digits = 3)
+ formatSignif(intersect("P_Value", display_cols), digits = 3)
})
output$epistasis_table <- renderDT({
@@ -1737,7 +1629,7 @@ server <- function(input, output, session) {
return(datatable(data.frame(Status = values$epistasis_sig$Message[1]), options = list(dom = "t")))
datatable(values$epistasis_sig[order(values$epistasis_sig$Interaction_p), ],
options = list(pageLength = 10, scrollX = TRUE), rownames = FALSE) %>%
- formatSignif(c("Interaction_p", "Effect_Size"), digits = 4)
+ formatSignif(c("Interaction_p","Effect_Size"), digits = 4)
})
output$selection_table <- renderDT({
@@ -1753,9 +1645,8 @@ server <- function(input, output, session) {
})
# ============================================================
- # CHROMOSOME VISUALIZATION — LOD-1.5 INTERVALS
+ # CHROMOSOME VISUALIZATION (interactive, on-screen)
# ============================================================
-
output$chromosome_viz <- renderUI({
req(values$qtl_effects_train, values$all_markers, values$cim_all)
if ("Message" %in% colnames(values$qtl_effects_train))
@@ -1766,47 +1657,37 @@ server <- function(input, output, session) {
chr_markers <- values$all_markers[values$all_markers$Chromosome == chr, ]
chr_markers <- chr_markers[order(chr_markers$Position), ]
chr_qtls <- values$qtl_effects_train[values$qtl_effects_train$Chromosome == chr, ]
-
sel_markers <- NULL
if (!is.null(values$selection_metrics) && !"Message" %in% colnames(values$selection_metrics))
- sel_markers <- values$selection_metrics[
- values$selection_metrics$Chromosome == chr & isTRUE(values$selection_metrics$Significant), ]
+ sel_markers <- values$selection_metrics[values$selection_metrics$Chromosome == chr & isTRUE(values$selection_metrics$Significant), ]
min_pos <- min(chr_markers$Position, na.rm = TRUE)
max_pos <- max(chr_markers$Position, na.rm = TRUE)
range_pos <- max_pos - min_pos
-
flanking_markers <- c(chr_qtls$Low_Flank, chr_qtls$High_Flank)
flanking_markers <- flanking_markers[!is.na(flanking_markers) & flanking_markers != ""]
div(class = "chromosome-container",
div(class = "chromosome-title",
- paste("Chromosome", chr, " —", nrow(chr_markers), "markers,", nrow(chr_qtls), "QTLs"),
+ 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)"))
+ paste0("(LOD-1.5: ", 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), "%;"))
+ div(class = "interval-band", style = paste0("left:", round(left_pct, 2), "%;width:", round(max(0.5, right_pct - left_pct), 2), "%;"))
}
}),
- # Markers
lapply(1:nrow(chr_markers), function(i) {
marker <- chr_markers[i, ]
- left <- if (range_pos > 0 && !is.na(range_pos))
- ((marker$Position - min_pos) / range_pos) * 100
- else (i / nrow(chr_markers)) * 100
-
+ left <- if (range_pos > 0 && !is.na(range_pos)) ((marker$Position - min_pos) / range_pos) * 100 else (i / nrow(chr_markers)) * 100
mclass <- "chromosome-marker"
if (marker$Marker %in% chr_qtls$Marker) {
mclass <- paste(mclass, "significant")
@@ -1820,8 +1701,8 @@ server <- function(input, output, session) {
})
),
div(class = "chromosome-legend",
- span(paste(format(min_pos, big.mark = ","), "bp")),
- span(paste(format(max_pos, big.mark = ","), "bp"))
+ span(paste(format(min_pos, big.mark=","), "bp")),
+ span(paste(format(max_pos, big.mark=","), "bp"))
)
)
}))
@@ -1831,40 +1712,36 @@ server <- function(input, output, session) {
observeEvent(input$reset_btn, session$sendCustomMessage("resetAnimation", list()))
# ============================================================
- # DOWNLOADS — Manhattan + Chromosome plots (ggplot2 → PNG)
+ # DOWNLOADS
# ============================================================
-
output$download_manhattan_plot <- downloadHandler(
- filename = function() paste0("manhattan_cim_", Sys.Date(), ".png"),
+ filename = function() paste0("manhattan_cim_v5_", Sys.Date(), ".png"),
content = function(file) {
req(values$cim_all)
- p <- make_ggplot_manhattan(values$cim_all, values$lod_threshold,
- title = "CIM Manhattan Plot (LOD Scores)")
- if (is.null(p)) {
- # fallback blank
- p <- ggplot() + labs(title = "No data") + theme_bw()
- }
+ p <- make_ggplot_manhattan(values$cim_all, values$lod_threshold, "CIM Manhattan Plot — LOD Scores (v5)")
+ if (is.null(p)) p <- ggplot() + labs(title = "No data") + theme_bw()
ggsave(file, plot = p, width = 14, height = 6, dpi = 200, bg = "white")
}
)
output$download_chromosome_plot <- downloadHandler(
- filename = function() paste0("chromosome_map_", Sys.Date(), ".png"),
+ filename = function() paste0("chromosome_map_v5_", 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,
+ qtl_effects = values$qtl_effects_train,
all_markers_df = values$all_markers,
- cim_all = values$cim_all,
- lod_threshold = values$lod_threshold
+ 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")
+ n_chrs <- length(unique(values$qtl_effects_train$Chromosome))
+ n_rows <- ceiling(n_chrs / 2)
+ img_h <- max(600, 380 * n_rows + 200)
+ png(file, width = 3200, height = img_h, res = 200, bg = "white")
grid::grid.draw(grob)
dev.off()
}
@@ -1872,7 +1749,7 @@ server <- function(input, output, session) {
)
output$download_train_results <- downloadHandler(
- filename = function() paste0("cim_results_v4_", Sys.Date(), ".xlsx"),
+ filename = function() paste0("cim_results_v5_", Sys.Date(), ".xlsx"),
content = function(file) {
sheets <- list()
if (!is.null(values$qtl_effects_train) && !"Message" %in% colnames(values$qtl_effects_train))
@@ -1881,19 +1758,19 @@ server <- function(input, output, session) {
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"),
+ sheets[["Method_v5"]] <- data.frame(
+ Item = c("Version","PVE_CIM_Formula","PVE_Marker_Formula",
+ "Why_v4_PVE_Was_Low","Additive_Coding",
+ "QTL_Interval","Cofactor_Cap","References"),
Description = c(
- "CIM 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)"),
+ "CIM v5 — semi-partial R² PVE (fixed from v4)",
+ "(RSS_cofactors_only - RSS_with_marker) / RSS_cofactors_only × 100 [semi-partial R²]",
+ "R² of lm(Y ~ a_code + d_code) × 100 [unconditional, no cofactors]",
+ "v4 used SS_total_raw as denominator → tiny PVE when cofactors dominate. v5 uses RSS_reduced.",
+ "a_code = genotype - 1 → -1/0/+1 (AA/Aa/aa); standard QTL convention",
+ "LOD-1.5 support interval: all markers within 1.5 LOD of peak",
+ "min(K_user, floor(sqrt(n_samples))) — adaptive to prevent over-absorption",
+ "Zeng(1993) PNAS; Lander&Botstein(1989) Genetics; Lynch&Walsh(1998); Falconer&Mackay(1996)"),
stringsAsFactors = FALSE)
write_xlsx(sheets, file)
}
@@ -1912,54 +1789,52 @@ server <- function(input, output, session) {
# ============================================================
# INTERPRETATION
# ============================================================
-
output$analysis_summary <- renderUI({
has_qtl <- !is.null(values$qtl_effects_train) && !"Message" %in% colnames(values$qtl_effects_train)
has_perf <- !is.null(values$performance_metrics)
n_qtl <- if (has_qtl) nrow(values$qtl_effects_train) else 0
val_r2 <- if (has_perf) round(values$performance_metrics$Value[values$performance_metrics$Metric == "R² (Validation)"], 3) else "N/A"
max_pve <- if (has_qtl) round(max(values$qtl_effects_train$PVE_CIM_Percent, na.rm = TRUE), 1) else NA
-
- 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
-
+ max_pve_m <- if (has_qtl) round(max(values$qtl_effects_train$PVE_Marker_Percent, na.rm = TRUE), 1) else NA
+ avg_int <- if (has_qtl && "Interval_Size_Mb" %in% colnames(values$qtl_effects_train))
+ round(mean(values$qtl_effects_train$Interval_Size_Mb, na.rm = TRUE), 2) else NA
div(
- tags$h5("CIM v4 Analysis Summary"),
+ tags$h5("CIM v5 Analysis Summary"),
tags$p(paste(n_qtl, "QTLs detected above LOD", values$lod_threshold, "| Validation R²:", val_r2)),
- if (!is.na(max_pve)) 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")),
+ if (!is.na(max_pve_m)) tags$p(paste("Max PVE_marker (unconditional R²):", max_pve_m, "%")),
+ if (!is.na(max_pve)) tags$p(paste("Max PVE_CIM (semi-partial R²):", max_pve, "% of cofactor-residual variance")),
+ if (!is.na(avg_int)) tags$p(paste("Mean LOD-1.5 interval:", avg_int, "Mb")),
tags$p(style = "color:#15803D;font-size:12px;",
tags$i(class = "fas fa-check-circle"),
- " v4 fixes: -1/0/+1 coding ✓ | partial R² PVE ✓ | LOD-1.5 intervals ✓")
+ " v5: semi-partial R² ✓ | -1/0/+1 coding ✓ | LOD-1.5 intervals ✓ | adaptive cofactors ✓")
)
})
output$qtl_interpretation <- renderUI({
if (is.null(values$qtl_effects_train) || "Message" %in% colnames(values$qtl_effects_train))
- return(div(tags$h5("QTL Significance"), tags$p("No significant QTLs. Try lower LOD threshold.")))
+ return(div(tags$h5("QTL Significance"), tags$p("No significant QTLs detected.")))
top <- values$qtl_effects_train[which.max(values$qtl_effects_train$LOD), ]
int_size <- if (!is.na(top$Interval_Size_Mb)) paste0(round(top$Interval_Size_Mb, 2), " Mb") else "N/A"
div(
tags$h5("Top QTL (by LOD)"),
tags$p(paste(top$Marker, "— Chr", top$Chromosome, "— LOD =", round(top$LOD, 2))),
- tags$p(paste("LOD-1.5 interval:", format(top$Interval_Start, big.mark=","), "—",
- format(top$Interval_End, big.mark=","), "bp (", int_size, ")")),
+ tags$p(paste("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), "%"))
+ tags$p(paste("PVE_marker (unconditional):", round(top$PVE_Marker_Percent, 1), "%")),
+ tags$p(paste("PVE_CIM (semi-partial):", round(top$PVE_CIM_Percent, 1), "% of cofactor-residual variance"))
)
})
output$effect_interpretation <- renderUI({
if (is.null(values$qtl_effects_train) || "Message" %in% colnames(values$qtl_effects_train))
return(div(tags$h5("Effect Sizes"), tags$p("No QTL effects yet.")))
- top <- values$qtl_effects_train[which.max(values$qtl_effects_train$PVE_CIM_Percent), ]
+ top <- values$qtl_effects_train[which.max(values$qtl_effects_train$PVE_Marker_Percent), ]
dom <- if (!is.na(top$Dominance_Effect))
paste0("Dominance = ", round(top$Dominance_Effect, 3), " (", top$Dominance_Class, ")")
else "No heterozygotes (additive model only)"
div(
- tags$h5("Largest PVE_CIM QTL"),
- tags$p(paste(top$Marker, "—", round(top$PVE_CIM_Percent, 1), "% PVE (partial R²)")),
+ tags$h5("Largest PVE_marker QTL"),
+ tags$p(paste(top$Marker, "—", round(top$PVE_Marker_Percent, 1), "% unconditional PVE")),
tags$p(paste("Additive effect (a, -1/0/+1 coding) =", round(top$Additive_Effect, 3))),
tags$p(dom)
)
@@ -1967,30 +1842,31 @@ server <- function(input, output, session) {
output$epistasis_interpretation <- renderUI({
if (is.null(values$epistasis_sig) || "Message" %in% colnames(values$epistasis_sig) || nrow(values$epistasis_sig) == 0)
- return(div(tags$h5("Epistasis"), tags$p("No significant interactions.")))
+ return(div(tags$h5("Epistasis"), tags$p("No significant interactions detected.")))
top <- values$epistasis_sig[which.min(values$epistasis_sig$Interaction_p), ]
div(tags$h5("Epistasis"),
tags$p(paste(nrow(values$epistasis_sig), "interactions. Strongest:", top$QTL1, "×", top$QTL2,
- "(p =", format.pval(top$Interaction_p), ")")))
+ "(p =", format.pval(top$Interaction_p, digits = 3), ")")))
})
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)
+ 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"
+ "Use Interval_Start / Interval_End (LOD-1.5) for fine-mapping candidate gene annotation",
+ "PVE_CIM = semi-partial R² (% of residual variance after cofactors) — compare markers on same scale",
+ "PVE_marker = unconditional R² — use this to compare QTL sizes across studies",
+ "Sum of PVE_marker across QTLs approximates total marker-explained variance"
)
if (n_ovdom > 0) r <- c(r, paste(n_ovdom, "overdominant QTL(s) — consider heterosis breeding"))
- if (large_int > 0) r <- c(r, paste(large_int, "QTL(s) with interval >10 Mb — increase marker density"))
+ if (large_int > 0) r <- c(r, paste(large_int, "QTL(s) with LOD-1.5 interval >10 Mb — increase marker density for fine-mapping"))
r
} else {
- c("Upload genotype + phenotype CSV files", "Click 'Run CIM Analysis'", "Try LOD threshold = 2 to start")
+ c("Upload genotype + phenotype CSV files", "Click 'Run CIM Analysis'", "Try LOD threshold = 2.0 to start")
}
div(tags$h5("Recommendations"), tags$ul(lapply(recs, tags$li), style = "color:#475569;"))
})