diff --git "a/app.R" "b/app.R"
--- "a/app.R"
+++ "b/app.R"
@@ -1,30 +1,21 @@
# ============================================================
-# QTL-Mapper v3 — Composite Interval Mapping (CIM) + Fixed Flanking
+# QTL-Mapper - With Model Selection & File Upload
+# USING COMPOSITE INTERVAL MAPPING (CIM) for better QTL detection
#
-# KEY FIXES:
-# 1. REPLACED Random Forest QTL mapping with Composite Interval Mapping (CIM)
-# - CIM fits lm(pheno ~ marker + cofactors) at each marker position
-# - Cofactors = top markers from initial RF screen (controls background)
-# - LOD = -log10(p-value of marker term)
-# - PVE computed from FULL model including cofactors → MUCH higher PVE
-#
-# 2. FIXED flanking markers
-# - Flanking search now uses the FULL marker list (not post-NZV subset)
-# - Correctly finds adjacent markers on same chromosome by sorted position
-#
-# 3. PVE FORMULA (unchanged, still correct):
-# Full model: lm(phenotype ~ a + d) [additive + dominance]
-# PVE (%) = R²_full × 100
-# Additive_Effect = beta_a, Dominance_Effect = beta_d
-# Reference: Falconer & Mackay (1996); Lynch & Walsh (1998)
+# KEY IMPROVEMENTS:
+# 1. Replaced Random Forest with Composite Interval Mapping (CIM)
+# 2. CIM controls for background QTLs to increase detection power
+# 3. Better PVE estimation using full additive + dominance model
+# 4. Proper flanking marker identification
+# 5. Multiple regression with cofactors for cleaner QTL signals
# ============================================================
options(repos = c(CRAN = "https://cloud.r-project.org"))
required_packages <- c(
- "shiny", "randomForest", "caret", "DT", "ggplot2", "plotly",
+ "shiny", "qtl", "caret", "DT", "ggplot2", "plotly",
"writexl", "viridis", "reshape2", "dplyr", "httr", "jsonlite",
- "shinyjs", "markdown", "base64enc"
+ "shinyjs", "markdown", "base64enc", "doParallel", "foreach"
)
for (pkg in required_packages) {
@@ -35,27 +26,30 @@ for (pkg in required_packages) {
}
# ============================================================
-# TOKEN / API SETUP
+# TOKEN DEBUG (same as before)
# ============================================================
-token <- Sys.getenv("GROQ_API_KEY")
+token <- Sys.getenv("GROQ_API_KEY")
token_exists <- token != ""
-token_length <- if (token_exists) nchar(token) else 0
+token_length <- if(token_exists) nchar(token) else 0
-cat("=== GROQ API TOKEN DEBUG ===\n")
-cat("Token exists:", token_exists, "\n")
-cat("Token length:", token_length, "\n")
-if (token_exists) cat("Token starts with:", substr(token, 1, 10), "\n")
-cat("===================================\n")
+print("=== GROQ API TOKEN DEBUG ===")
+print(paste("Token exists:", token_exists))
+print(paste("Token length:", token_length))
+if(token_exists) print(paste("Token starts with:", substr(token, 1, 10)))
+print("===================================")
-HF_API_TOKEN <- token
-HF_API_URL <- "https://api.groq.com/openai/v1/chat/completions"
+HF_API_TOKEN <- token
+HF_API_URL <- "https://api.groq.com/openai/v1/chat/completions"
default_model <- "llama-3.1-8b-instant"
+# ============================================================
+# AVAILABLE MODELS CONFIGURATION (same as before)
+# ============================================================
available_models <- list(
- list(id = "llama-3.1-8b-instant", label = "Llama 3.1 8B", provider = "groq", tier = "free"),
- list(id = "llama-3.3-70b-versatile", label = "Llama 3.3 70B", provider = "groq", tier = "free"),
- list(id = "meta-llama/llama-4-maverick-17b-128e-instruct", label = "Llama 4 Maverick 17B", provider = "groq", tier = "free"),
- list(id = "moonshotai/kimi-k2-instruct-0905", label = "Kimi K2", provider = "groq", tier = "free")
+ list(id = "llama-3.1-8b-instant", label = "Llama 3.1 8B", provider = "groq", tier = "free"),
+ list(id = "llama-3.3-70b-versatile", label = "Llama 3.3 70B", provider = "groq", tier = "free"),
+ list(id = "meta-llama/llama-4-maverick-17b-128e-instruct", label = "Llama 4 Maverick 17B", provider = "groq", tier = "free"),
+ list(id = "moonshotai/kimi-k2-instruct-0905", label = "Kimi K2", provider = "groq", tier = "free")
)
model_choices <- setNames(
@@ -64,419 +58,579 @@ model_choices <- setNames(
)
# ============================================================
-# CIM CORE FUNCTION
-# ============================================================
-#
-# Composite Interval Mapping (Zeng 1993, 1994):
-# For each marker m:
-# 1. Select cofactors = top K markers from RF (excluding nearby markers on same chr)
-# 2. Fit: Y ~ marker_m + cofactors (additive model)
-# 3. LOD = -log10( p-value of marker_m term )
-# 4. PVE = R²_full × 100 (full model including cofactors)
-#
-# This gives HIGHER PVE because:
-# - Cofactors absorb background genetic variance
-# - Each marker's contribution is estimated after controlling for rest
-# - Much more powerful than single-marker regression
+# TEST CONNECTION (same as before)
# ============================================================
-
-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)
-
- cat("CIM: Starting with", n_markers, "markers,", n_samples, "samples\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]
-
- rf_model <- tryCatch(
- randomForest(x = X_valid, y = y_valid, ntree = 500, importance = TRUE),
- error = function(e) NULL
- )
-
- if (!is.null(rf_model)) {
- imp_scores <- importance(rf_model, type = 1)[, 1]
- top_cofactors <- names(sort(imp_scores, decreasing = TRUE))[1:min(n_cofactors * 2, length(imp_scores))]
- } else {
- # 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]
- })
- top_cofactors <- names(sort(p_vals))[1:min(n_cofactors * 2, length(p_vals))]
- }
-
- cat("CIM: Selected", length(top_cofactors), "candidate cofactors\n")
-
- # ---- Step 2: Scan each marker with CIM ----
- results_list <- list()
-
- for (i in seq_along(markers)) {
- m <- markers[i]
-
- geno <- genotype_matrix[, m]
- valid_idx <- !is.na(geno) & !is.na(phenotype_vector)
- geno_v <- geno[valid_idx]
- pheno_v <- phenotype_vector[valid_idx]
-
- if (length(unique(geno_v)) < 2 || length(pheno_v) < 5) 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 ----
- chr_markers <- marker_info[marker_info$Chromosome == m_chr, ]
- chr_markers <- chr_markers[order(chr_markers$Position), ]
- m_idx <- which(chr_markers$Marker == m)
-
- if (length(m_idx) > 0) {
- nearby_range <- max(1, m_idx - window_size):min(nrow(chr_markers), m_idx + window_size)
- nearby_mks <- chr_markers$Marker[nearby_range]
- } else {
- nearby_mks <- m
- }
-
- active_cofactors <- setdiff(top_cofactors, c(m, nearby_mks))
- active_cofactors <- active_cofactors[active_cofactors %in% colnames(genotype_matrix)]
- active_cofactors <- head(active_cofactors, n_cofactors)
-
- # ---- Build data frame for model ----
- df_model <- data.frame(y = pheno_v, focal = geno_v[valid_idx])
-
- # Add cofactors
- if (length(active_cofactors) > 0) {
- cof_mat <- genotype_matrix[valid_idx, active_cofactors, drop = FALSE]
- # Handle NAs in cofactors
- cof_mat[is.na(cof_mat)] <- 0
- df_model <- cbind(df_model, cof_mat)
- }
-
- df_model <- df_model[complete.cases(df_model), ]
- if (nrow(df_model) < 5) next
-
- # ---- Fit CIM model ----
- tryCatch({
- if (length(active_cofactors) > 0) {
- cof_formula <- paste(active_cofactors, collapse = " + ")
- full_formula <- as.formula(paste("y ~ focal +", cof_formula))
- } else {
- full_formula <- as.formula("y ~ focal")
- }
-
- fit <- lm(full_formula, data = df_model)
- sm <- summary(fit)
- coef_t <- sm$coefficients
-
- if (!"focal" %in% rownames(coef_t)) next
-
- p_val <- coef_t["focal", "Pr(>|t|)"]
- lod <- -log10(p_val + 1e-300) # avoid log(0)
- r2_full <- sm$r.squared
-
- # ---- Additive + Dominance effects (on this marker) ----
- a_code <- df_model$focal
- d_code <- as.numeric(a_code == 1)
- has_het <- length(unique(d_code)) > 1
-
- if (has_het) {
- lm_eff <- lm(y ~ a_code + d_code, data = df_model)
- sm_eff <- summary(lm_eff)
- pve_ad <- sm_eff$r.squared * 100 # PVE from add+dom ALONE (marker only)
- c_eff <- coef(lm_eff)
- a_eff <- c_eff["a_code"]
- d_eff <- c_eff["d_code"]
- se_t <- sm_eff$coefficients
- se_a <- se_t["a_code", "Std. Error"]
- se_d <- se_t["d_code", "Std. Error"]
- d_rat <- if (!is.na(a_eff) && a_eff != 0) abs(d_eff / a_eff) else NA
- } else {
- lm_eff <- lm(y ~ a_code, data = df_model)
- sm_eff <- summary(lm_eff)
- pve_ad <- sm_eff$r.squared * 100
- c_eff <- coef(lm_eff)
- a_eff <- c_eff["a_code"]
- d_eff <- NA; se_a <- NA; se_d <- NA; d_rat <- NA
- }
-
- # PVE from full CIM model (marker + cofactors) — this is the HIGH PVE
- pve_cim <- r2_full * 100
-
- dom_class <- if (is.na(d_rat)) "Additive"
- else if (d_rat > 1) "Overdominance"
- else if (d_rat > 0.5) "Dominance"
- else if (d_rat > 0.2) "Partial Dom."
- else "Additive"
-
- results_list[[m]] <- data.frame(
- Marker = m,
- Chromosome = m_chr,
- Position = m_pos,
- LOD = lod,
- P_Value = p_val,
- PVE_Marker_Percent = pve_ad, # PVE of marker alone (add+dom)
- PVE_CIM_Percent = pve_cim, # PVE of full CIM model (marker + cofactors)
- Additive_Effect = a_eff,
- SE_Additive = se_a,
- CI_Lower = ifelse(is.na(se_a), NA, a_eff - 1.96 * se_a),
- CI_Upper = ifelse(is.na(se_a), NA, a_eff + 1.96 * se_a),
- Dominance_Effect = d_eff,
- SE_Dominance = se_d,
- Dominance_Ratio = d_rat,
- Dominance_Class = dom_class,
- N_Cofactors = length(active_cofactors),
- N_Samples = nrow(df_model),
- N_Heterozygotes = sum(df_model$focal == 1),
- stringsAsFactors = FALSE
- )
-
- }, error = function(e) {
- cat("CIM error at marker", m, ":", e$message, "\n")
- })
- }
-
- 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: Completed scan,", nrow(cim_result), "markers evaluated\n")
- return(cim_result)
-}
-
-# ============================================================
-# FLANKING MARKER FUNCTION — FIXED
-# Uses the FULL all_markers table (not post-NZV subset)
-# ============================================================
-
-add_flanking_markers <- function(sig_df, all_markers_df) {
- sig_df$Low_Flank <- NA_character_
- sig_df$High_Flank <- NA_character_
-
- for (i in 1:nrow(sig_df)) {
- focal_marker <- sig_df$Marker[i]
- focal_chr <- sig_df$Chromosome[i]
- focal_pos <- sig_df$Position[i]
-
- # Get ALL markers on same chromosome, sorted by position
- chr_markers <- all_markers_df[all_markers_df$Chromosome == focal_chr, ]
- chr_markers <- chr_markers[order(chr_markers$Position), ]
-
- if (nrow(chr_markers) == 0) next
-
- # Find position of focal marker in sorted list
- idx <- which(chr_markers$Marker == focal_marker)
-
- if (length(idx) > 0) {
- sig_df$Low_Flank[i] <- if (idx > 1) chr_markers$Marker[idx - 1] else focal_marker
- sig_df$High_Flank[i] <- if (idx < nrow(chr_markers)) chr_markers$Marker[idx + 1] else focal_marker
- } else {
- # Marker not found by name — find by closest position
- dists <- abs(chr_markers$Position - focal_pos)
- idx <- which.min(dists)
- sig_df$Low_Flank[i] <- if (idx > 1) chr_markers$Marker[idx - 1] else focal_marker
- sig_df$High_Flank[i] <- if (idx < nrow(chr_markers)) chr_markers$Marker[idx + 1] else focal_marker
- }
- }
-
- return(sig_df)
-}
-
-# ============================================================
-# API / AI FUNCTIONS (unchanged)
-# ============================================================
-
test_api_connection <- function(model_id = default_model) {
if (!token_exists) return(list(success = FALSE, error = "No token found"))
+
tryCatch({
response <- POST(
url = HF_API_URL,
- add_headers(Authorization = paste("Bearer", HF_API_TOKEN), "Content-Type" = "application/json"),
- body = toJSON(list(model = model_id, messages = list(list(role = "user", content = "Hi")), max_tokens = 10L), auto_unbox = TRUE),
- encode = "json", timeout(15))
- if (status_code(response) == 200) return(list(success = TRUE))
- err <- tryCatch(content(response, "text", encoding = "UTF-8"), error = function(e) paste("Status:", status_code(response)))
- list(success = FALSE, error = paste("Status:", status_code(response), "-", substr(err, 1, 200)))
+ add_headers(
+ Authorization = paste("Bearer", HF_API_TOKEN),
+ "Content-Type" = "application/json"
+ ),
+ body = toJSON(list(
+ model = model_id,
+ messages = list(list(role = "user", content = "Hi")),
+ max_tokens = 10L
+ ), auto_unbox = TRUE),
+ encode = "json",
+ timeout(15)
+ )
+
+ status <- status_code(response)
+ if (status == 200) return(list(success = TRUE))
+
+ err <- tryCatch(content(response, "text", encoding = "UTF-8"),
+ error = function(e) paste("Status:", status))
+ return(list(success = FALSE,
+ error = paste("Status:", status, "-", substr(err, 1, 200))))
}, error = function(e) list(success = FALSE, error = e$message))
}
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 FUNCTION (same as before)
+# ============================================================
query_hf_api <- function(prompt, model_id = default_model, max_length = 500, temperature = 0.7) {
if (!token_exists) return(list(success = FALSE, error = "HF_API_TOKEN not set"))
+
tryCatch({
response <- POST(
url = HF_API_URL,
- add_headers(Authorization = paste("Bearer", HF_API_TOKEN), "Content-Type" = "application/json"),
+ add_headers(
+ Authorization = paste("Bearer", HF_API_TOKEN),
+ "Content-Type" = "application/json"
+ ),
body = toJSON(list(
model = model_id,
messages = list(
- list(role = "system", content = "You are an expert bioinformatics assistant specializing in QTL analysis using Composite Interval Mapping. Be concise and helpful."),
- list(role = "user", content = prompt)),
- max_tokens = as.integer(max_length), temperature = temperature), auto_unbox = TRUE),
- encode = "json", timeout(60))
- if (status_code(response) == 200) {
+ list(role = "system",
+ content = "You are an expert bioinformatics assistant specializing in QTL analysis. Be concise and helpful."),
+ list(role = "user", content = prompt)
+ ),
+ max_tokens = as.integer(max_length),
+ temperature = temperature
+ ), auto_unbox = TRUE),
+ encode = "json",
+ timeout(60)
+ )
+
+ status <- status_code(response)
+
+ if (status == 200) {
result <- content(response, as = "parsed", encoding = "UTF-8")
- return(list(success = TRUE, text = result$choices[[1]]$message$content))
+ text <- result$choices[[1]]$message$content
+ return(list(success = TRUE, text = text))
}
- err <- tryCatch(content(response, "text", encoding = "UTF-8"), error = function(e) paste("Status:", status_code(response)))
- list(success = FALSE, error = paste("API error:", status_code(response), "-", substr(err, 1, 200)))
+
+ err <- tryCatch(content(response, "text", encoding = "UTF-8"),
+ error = function(e) paste("Status:", status))
+ return(list(success = FALSE,
+ error = paste("API error:", status, "-", substr(err, 1, 200))))
}, error = function(e) list(success = FALSE, error = e$message))
}
+# ============================================================
+# SYSTEM PROMPT CONSTRUCTION (same as before)
+# ============================================================
build_system_prompt <- function(rv) {
- ctx <- c("CURRENT ANALYSIS RESULTS (Composite Interval Mapping):")
-
- if (!is.null(rv$cim_all) && !"Message" %in% colnames(rv$cim_all)) {
- sig <- rv$cim_all[rv$cim_all$LOD >= rv$lod_threshold, ]
- ctx <- c(ctx,
- sprintf("\nCIM Results: %d significant QTLs above LOD %.1f", nrow(sig), rv$lod_threshold),
- sprintf("Total PVE (CIM model, marker+cofactors): %.1f%%", if (nrow(sig) > 0) max(sig$PVE_CIM_Percent) else 0))
- if (nrow(sig) > 0) {
- top3 <- head(sig, 3)
- ctx <- c(ctx, "\nTop QTLs:")
- for (i in 1:nrow(top3)) {
- r <- top3[i, ]
- ctx <- c(ctx, sprintf(" %d. %s (Chr %s): LOD=%.2f, PVE_marker=%.1f%%, PVE_CIM=%.1f%%, A=%.3f, D=%s",
- i, r$Marker, r$Chromosome, r$LOD, r$PVE_Marker_Percent, r$PVE_CIM_Percent, r$Additive_Effect,
- ifelse(is.na(r$Dominance_Effect), "NA", as.character(round(r$Dominance_Effect, 3)))))
- }
+ context_parts <- c("CURRENT ANALYSIS RESULTS:")
+
+ if (!is.null(rv$qtl_effects_train) && !"Message" %in% colnames(rv$qtl_effects_train)) {
+ n_qtl <- nrow(rv$qtl_effects_train)
+ total_pve <- sum(rv$qtl_effects_train$PVE_Percent, na.rm = TRUE)
+
+ context_parts <- c(context_parts,
+ sprintf("\nQTL Results: %d significant QTLs detected above LOD %.1f.", n_qtl, rv$lod_threshold),
+ sprintf("Total variance explained by QTLs: %.1f%% (additive + dominance model).", total_pve))
+
+ top_qtls <- head(rv$qtl_effects_train[order(-rv$qtl_effects_train$LOD), ], 3)
+ context_parts <- c(context_parts, "\nTop QTLs:")
+ for (i in 1:nrow(top_qtls)) {
+ row <- top_qtls[i, ]
+ context_parts <- c(context_parts,
+ sprintf(" %d. %s (Chr %s): LOD=%.2f, PVE=%.1f%%, Additive=%.3f, Dominance=%.3f",
+ i, row$Marker, row$Chromosome, row$LOD, row$PVE_Percent,
+ row$Additive_Effect, ifelse(is.na(row$Dominance_Effect), 0, row$Dominance_Effect)))
}
}
+
if (!is.null(rv$performance_metrics)) {
- pm <- rv$performance_metrics
- ctx <- c(ctx, sprintf("\nModel R² (Train): %.3f, R² (Validation): %.3f",
- pm$Value[pm$Metric == "R² (Train)"], pm$Value[pm$Metric == "R² (Validation)"]))
+ pm <- rv$performance_metrics
+ train_r2 <- pm$Value[pm$Metric == "R² (Train)"]
+ val_r2 <- pm$Value[pm$Metric == "R² (Validation)"]
+ context_parts <- c(context_parts,
+ sprintf("\nModel Performance:"),
+ sprintf(" Training R²: %.3f", train_r2),
+ sprintf(" Validation R²: %.3f", val_r2))
+ }
+
+ if (!is.null(rv$epistasis_sig) && !"Message" %in% colnames(rv$epistasis_sig) && nrow(rv$epistasis_sig) > 0) {
+ n_epi <- nrow(rv$epistasis_sig)
+ top_epi <- rv$epistasis_sig[order(rv$epistasis_sig$Interaction_p), ][1, ]
+ context_parts <- c(context_parts,
+ sprintf("\nEpistasis: %d significant pairwise interactions detected.", n_epi),
+ sprintf(" Strongest: %s x %s (p=%.4f)", top_epi$QTL1, top_epi$QTL2, top_epi$Interaction_p))
}
- paste(ctx, collapse = "\n")
+
+ if (!is.null(rv$selection_metrics) && !"Message" %in% colnames(rv$selection_metrics)) {
+ n_sig <- sum(rv$selection_metrics$Significant, na.rm = TRUE)
+ context_parts <- c(context_parts,
+ sprintf("\nDomestication: %d markers with selection signatures.", n_sig))
+ }
+
+ paste(context_parts, collapse = "\n")
}
+# ============================================================
+# ENHANCED RULE-BASED RESPONSES (same as before)
+# ============================================================
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_qtl <- !is.null(rv$qtl_effects_train) && !"Message" %in% colnames(rv$qtl_effects_train)
has_perf <- !is.null(rv$performance_metrics)
-
- if (grepl("pve|variance explained|how much variance|percent variance|what is pve|cim", q)) {
+ has_epi <- !is.null(rv$epistasis_sig) && !"Message" %in% colnames(rv$epistasis_sig) && nrow(rv$epistasis_sig) > 0
+ has_sel <- !is.null(rv$selection_metrics) && !"Message" %in% colnames(rv$selection_metrics)
+
+ if (grepl("pve|variance explained|how much variance|percent variance|what is pve", q)) {
if (has_qtl) {
- sig <- rv$cim_all[rv$cim_all$LOD >= rv$lod_threshold, ]
- top_pve <- sig[which.max(sig$PVE_CIM_Percent), ]
- return(paste0(
- "📊 **PVE in Composite Interval Mapping**\n\n",
- "**Two PVE values are reported:**\n",
- "• `PVE_Marker_%` = R² from lm(y ~ a + d) — marker alone\n",
- "• `PVE_CIM_%` = R² from full CIM model (marker + cofactors) — HIGHER\n\n",
- "**Top QTL:** ", top_pve$Marker, " (Chr ", top_pve$Chromosome, ")\n",
- "• LOD: ", round(top_pve$LOD, 2), "\n",
- "• PVE (marker alone): ", round(top_pve$PVE_Marker_Percent, 1), "%\n",
- "• PVE (CIM full model): ", round(top_pve$PVE_CIM_Percent, 1), "%\n",
- "• Additive: ", round(top_pve$Additive_Effect, 3), "\n",
- "• Dominance: ", ifelse(is.na(top_pve$Dominance_Effect), "NA", round(top_pve$Dominance_Effect, 3)), "\n\n",
- "CIM PVE is higher because cofactors absorb background genetic variance,\n",
- "letting each QTL's true contribution be measured more accurately."
- ))
+ df <- rv$qtl_effects_train
+ total_pve <- sum(df$PVE_Percent, na.rm = TRUE)
+ top_pve <- df[which.max(df$PVE_Percent), ]
+
+ response <- paste0(
+ "\U0001f4ca **PVE (Phenotypic Variance Explained) Analysis**\n\n",
+ "**PVE Model Used:** Full additive + dominance model\n",
+ " lm(phenotype ~ additive_code + dominance_code)\n\n",
+ "**Your Results:**\n",
+ "\u2022 Total variance explained by all QTLs: **", round(total_pve, 1), "%**\n",
+ "\u2022 Number of QTLs detected: **", nrow(df), "**\n\n",
+ "**Top QTL by PVE:**\n",
+ "\u2022 Marker: **", top_pve$Marker, "**\n",
+ "\u2022 Chromosome: ", top_pve$Chromosome, "\n",
+ "\u2022 PVE: **", round(top_pve$PVE_Percent, 1), "%**\n",
+ "\u2022 LOD: ", round(top_pve$LOD, 2), "\n",
+ "\u2022 Additive effect: ", round(top_pve$Additive_Effect, 3), "\n",
+ "\u2022 Dominance effect: ", ifelse(is.na(top_pve$Dominance_Effect), "NA (no het)", round(top_pve$Dominance_Effect, 3)), "\n\n"
+ )
+
+ if (top_pve$PVE_Percent > 10) {
+ response <- paste0(response, "\U0001f4a1 This is a **major-effect QTL** (>10% PVE).\n\n")
+ } else if (top_pve$PVE_Percent > 5) {
+ response <- paste0(response, "\U0001f4a1 This is a **moderate-effect QTL** (5-10% PVE).\n\n")
+ } else {
+ response <- paste0(response, "\U0001f4a1 This is a **minor-effect QTL** (<5% PVE).\n\n")
+ }
+
+ response <- paste0(response, "**All QTLs by PVE:**\n")
+ df_sorted <- df[order(-df$PVE_Percent), ]
+ for (i in 1:min(5, nrow(df_sorted))) {
+ row <- df_sorted[i, ]
+ response <- paste0(response, sprintf(" %d. %s: %.1f%% (A=%.3f, D=%s)\n",
+ i, row$Marker, row$PVE_Percent, row$Additive_Effect,
+ ifelse(is.na(row$Dominance_Effect), "NA", round(row$Dominance_Effect, 3))))
+ }
+ return(response)
+ } else {
+ return("No QTL results yet. Please run the QTL analysis first to see PVE values.")
}
- return("Run CIM analysis first to see PVE values.")
}
-
+
+ if (grepl("model performance|r2|r squared|how good is my model|validation|negative r2", q)) {
+ if (has_perf) {
+ pm <- rv$performance_metrics
+ train_r2 <- pm$Value[pm$Metric == "R² (Train)"]
+ val_r2 <- pm$Value[pm$Metric == "R² (Validation)"]
+
+ response <- paste0(
+ "\U0001f4c8 **Model Performance Summary**\n\n",
+ "\u2022 Training R²: **", round(train_r2, 3), "**\n",
+ "\u2022 Validation R²: **", round(val_r2, 3), "**\n\n"
+ )
+
+ if (val_r2 < 0) {
+ response <- paste0(response,
+ "\u26a0\ufe0f **Your validation R² is negative** (", round(val_r2, 3), ").\n\n",
+ "**Common causes:**\n",
+ "\u2022 Small sample size relative to number of markers\n",
+ "\u2022 Overfitting\n",
+ "\u2022 Population structure\n\n",
+ "**Recommendations:**\n",
+ "1. Increase sample size\n",
+ "2. Reduce marker number\n",
+ "3. Try simpler models or increase CV folds\n")
+ } else if (val_r2 < 0.2) {
+ response <- paste0(response, "\U0001f4c9 **Low validation R²** (<0.2). Focus on individual QTL interpretation.\n")
+ } else if (val_r2 < 0.5) {
+ response <- paste0(response, "\U0001f4ca **Moderate validation R²** (0.2-0.5).\n")
+ } else {
+ response <- paste0(response, "\U0001f3af **Excellent validation R²** (>0.5)!\n")
+ }
+ return(response)
+ } else {
+ return("Run the QTL analysis first to see model performance metrics.")
+ }
+ }
+
if (grepl("top qtl|best qtl|highest lod|significant qtl|list qtl|show qtl", q)) {
if (has_qtl) {
- sig <- rv$cim_all[rv$cim_all$LOD >= rv$lod_threshold, ]
- top5 <- head(sig, 5)
- out <- "🎯 **Top QTLs by LOD (Composite Interval Mapping)**\n\n"
+ df <- rv$qtl_effects_train[order(-rv$qtl_effects_train$LOD), ]
+ top5 <- head(df, 5)
+
+ response <- "\U0001f3af **Top 5 QTLs by LOD Score**\n\n"
for (i in 1:nrow(top5)) {
- r <- top5[i, ]
- dom <- ifelse(is.na(r$Dominance_Effect), "NA", as.character(round(r$Dominance_Effect, 3)))
- out <- paste0(out, i, ". **", r$Marker, "** (Chr ", r$Chromosome, ")\n",
- " • LOD: **", round(r$LOD, 2), "**\n",
- " • PVE_marker: ", round(r$PVE_Marker_Percent, 1), "% | PVE_CIM: ", round(r$PVE_CIM_Percent, 1), "%\n",
- " • Flanking: ", r$Low_Flank, " ↔ ", r$High_Flank, "\n\n")
+ row <- top5[i, ]
+ dom_str <- ifelse(is.na(row$Dominance_Effect), "NA", as.character(round(row$Dominance_Effect, 3)))
+ response <- paste0(response,
+ i, ". **", row$Marker, "** (Chr ", row$Chromosome, ")\n",
+ " \u2022 LOD: **", round(row$LOD, 2), "**\n",
+ " \u2022 PVE: ", round(row$PVE_Percent, 1), "% (additive + dominance)\n",
+ " \u2022 Additive effect: ", round(row$Additive_Effect, 3), "\n",
+ " \u2022 Dominance effect: ", dom_str, "\n\n")
}
- return(out)
+ return(response)
+ } else {
+ return("No significant QTLs detected. Try lowering the LOD threshold.")
}
- return("No significant QTLs detected. Try lowering the LOD threshold.")
}
-
- if (grepl("flank|interval|region|boundary", q)) {
- if (has_qtl) {
- sig <- rv$cim_all[rv$cim_all$LOD >= rv$lod_threshold, ]
- out <- "🧬 **QTL Flanking Markers (Fixed)**\n\n"
- for (i in 1:min(5, nrow(sig))) {
- r <- sig[i, ]
- out <- paste0(out, r$Marker, ": [", r$Low_Flank, "] ← QTL → [", r$High_Flank, "]\n")
+
+ if (grepl("next steps|what next|recommendations|suggest|advice|what should i do", q)) {
+ if (has_qtl || has_perf || has_epi || has_sel) {
+ response <- "\U0001f52c **Recommended Next Steps**\n\n"
+
+ if (has_qtl) {
+ top_qtl <- rv$qtl_effects_train[which.max(rv$qtl_effects_train$LOD), ]
+ response <- paste0(response,
+ "**1. Validate Top QTLs**\n",
+ " \u2022 Prioritize **", top_qtl$Marker, "** (LOD=", round(top_qtl$LOD, 2), ")\n",
+ " \u2022 Test in independent population\n\n")
+ }
+ if (has_epi) {
+ response <- paste0(response, "**2. Investigate Epistasis**\n",
+ " \u2022 ", nrow(rv$epistasis_sig), " significant interactions\n\n")
+ }
+ if (has_sel) {
+ response <- paste0(response, "**3. Domestication Analysis**\n",
+ " \u2022 ", sum(rv$selection_metrics$Significant, na.rm = TRUE), " selection signatures\n\n")
}
- return(out)
+
+ response <- paste0(response,
+ "**4. Functional Analysis**\n",
+ " \u2022 Annotate QTL regions for candidate genes\n\n",
+ "**5. Breeding Applications**\n",
+ " \u2022 Develop markers for MAS\n")
+ return(response)
+ } else {
+ return("Run the QTL analysis first to get recommendations.")
}
- return("Run analysis first to see flanking markers.")
}
+
+ available <- c()
+ if (has_qtl) available <- c(available, paste(nrow(rv$qtl_effects_train), "QTLs"))
+ if (has_perf) {
+ val_r2 <- rv$performance_metrics$Value[rv$performance_metrics$Metric == "R² (Validation)"]
+ available <- c(available, paste0("R²=", round(val_r2, 3)))
+ }
+ if (has_epi) available <- c(available, paste(nrow(rv$epistasis_sig), "interactions"))
+ if (has_sel) available <- c(available, paste(sum(rv$selection_metrics$Significant), "selection signatures"))
+
+ if (length(available) > 0) {
+ return(paste0(
+ "I can see you have: ", paste(available, collapse = ", "), ".\n\n",
+ "What would you like to know? Try asking about:\n",
+ "\u2022 **What is PVE?**\n",
+ "\u2022 **Top QTLs**\n",
+ "\u2022 **Model performance**\n",
+ "\u2022 **Next steps**"))
+ }
+
+ return(paste0(
+ "\U0001f44b Vanakam! I'm TerraByte-AI powered Companion.\n\n",
+ "**I can help you with:**\n",
+ "\u2022 Understanding PVE (additive + dominance model)\n",
+ "\u2022 Interpreting LOD scores\n",
+ "\u2022 Evaluating model performance\n",
+ "\u2022 Detecting epistatic interactions\n\n",
+ "\u2022 any query? contact : ashmithamganesan@gmail.com, P.sinha@cgiar.org\n\n",
+ "Try: **'What is PVE?'** or **'Show me my top QTLs'**"))
+}
- if (grepl("model performance|r2|r squared|validation|negative r2", q) && has_perf) {
- pm <- rv$performance_metrics
- val_r2 <- pm$Value[pm$Metric == "R² (Validation)"]
- out <- paste0("📈 **Model Performance**\n\n• Training R²: ", round(pm$Value[pm$Metric == "R² (Train)"], 3),
- "\n• Validation R²: **", round(val_r2, 3), "**\n\n")
- if (val_r2 < 0) {
- out <- paste0(out, "⚠️ Negative validation R² — likely overfitting or small sample.\n",
- "Try increasing sample size or reducing cofactors (lower n_cofactors).")
- } else if (val_r2 >= 0.5) {
- out <- paste0(out, "🎯 Excellent validation R²!")
+# ============================================================
+# AI RESPONSE GENERATION (same as before)
+# ============================================================
+generate_ai_response <- function(user_message, rv, model_id = default_model) {
+ context <- build_system_prompt(rv)
+
+ current_use_api <- token_exists
+
+ if (current_use_api) {
+ prompt <- paste(
+ "CONTEXT:", context,
+ "\n\nUSER QUESTION:", user_message,
+ "\n\nProvide a specific, helpful answer based ONLY on the context above. Be concise but informative.",
+ sep = "\n"
+ )
+
+ result <- query_hf_api(prompt, model_id = model_id)
+
+ if (result$success) {
+ return(result$text)
+ } else {
+ message("API Error: ", result$error)
+ return(enhanced_rule_response(user_message, rv))
}
- return(out)
}
+
+ return(enhanced_rule_response(user_message, rv))
+}
+
+# ============================================================
+# COMPOSITE INTERVAL MAPPING FUNCTIONS
+# ============================================================
- paste0("👋 Vanakam! TerraByte-AI here (CIM mode).\n\n",
- "Ask me about:\n• **PVE / CIM** — how variance is explained\n",
- "• **Top QTLs** — flanking markers included\n• **Model performance**\n",
- "• **What is CIM?** — Composite Interval Mapping explained\n\n",
- "Contact: ashmithamganesan@gmail.com, P.sinha@cgiar.org")
+#' Convert genotype data to qtl package format
+prepare_qtl_cross <- function(genotype_matrix, phenotype_vector, marker_info, pop_data = NULL) {
+ # Create a cross object for qtl package
+ n_ind <- nrow(genotype_matrix)
+ n_mar <- ncol(genotype_matrix)
+
+ # Create genotype data in qtl format (AA=1, AB=2, BB=3)
+ geno_qtl <- matrix(0, nrow = n_ind, ncol = n_mar)
+ for (i in 1:n_mar) {
+ # Convert 0,1,2 to 1,2,3 format (AA, AB, BB)
+ geno_qtl[, i] <- genotype_matrix[, i] + 1
+ }
+ colnames(geno_qtl) <- colnames(genotype_matrix)
+ rownames(geno_qtl) <- rownames(genotype_matrix)
+
+ # Create pheno data
+ pheno_qtl <- data.frame(phenotype = phenotype_vector)
+ rownames(pheno_qtl) <- rownames(genotype_matrix)
+
+ # Create genetic map
+ map <- list()
+ chromosomes <- unique(marker_info$Chromosome)
+ for (chr in chromosomes) {
+ chr_markers <- marker_info[marker_info$Chromosome == chr, ]
+ chr_markers <- chr_markers[order(chr_markers$Position), ]
+
+ # Use positions in cM (assuming positions are in bp, convert to cM roughly)
+ # 1 cM ≈ 1e6 bp as rough approximation - user should provide cM if possible
+ pos_cM <- chr_markers$Position / 1e6
+
+ map[[as.character(chr)]] <- pos_cM
+ names(map[[as.character(chr)]]) <- chr_markers$Marker
+ }
+
+ # Create cross object
+ cross <- list()
+ cross$geno <- list()
+ for (chr in names(map)) {
+ chr_markers <- names(map[[chr]])
+ cross$geno[[chr]] <- list(
+ data = geno_qtl[, chr_markers, drop = FALSE],
+ map = map[[chr]]
+ )
+ class(cross$geno[[chr]]) <- "A" # Assume backcross or RIL
+ }
+
+ cross$pheno <- pheno_qtl
+ class(cross) <- c("bc", "cross") # Assume backcross (can be changed)
+
+ return(cross)
}
-generate_ai_response <- function(user_message, rv, model_id = default_model) {
- if (token_exists) {
- context <- build_system_prompt(rv)
- prompt <- paste("CONTEXT:", context, "\n\nUSER:", user_message,
- "\n\nAnswer specifically using the context above. Be concise.")
- result <- query_hf_api(prompt, model_id = model_id)
- if (result$success) return(result$text)
+#' Perform Composite Interval Mapping
+perform_cim <- function(cross, phenotype_name = "phenotype",
+ n_permutations = 100,
+ n_markers_cofactor = 5,
+ window_size = 10, # cM window around test position
+ step_size = 1, # step size in cM
+ lod_threshold_perm = TRUE) {
+
+ # Check if qtl package is available
+ if (!requireNamespace("qtl", quietly = TRUE)) {
+ stop("qtl package is required for CIM")
+ }
+
+ # Estimate genotype probabilities
+ cross <- qtl::calc.genoprob(cross, step = step_size)
+
+ # Perform CIM
+ # Use stepwise selection to choose cofactors
+ cofactors <- qtl::stepwiseqtl(cross, pheno.col = phenotype_name,
+ max.qtl = n_markers_cofactor,
+ method = "hk", verbose = FALSE)
+
+ # Perform CIM with cofactors
+ if (length(cofactors) > 0) {
+ out_cim <- qtl::cim(cross, pheno.col = phenotype_name,
+ qtl = cofactors,
+ method = "hk",
+ n.marcovar = n_markers_cofactor,
+ window = window_size)
+ } else {
+ # If no cofactors selected, use simple interval mapping
+ out_cim <- qtl::scanone(cross, pheno.col = phenotype_name,
+ method = "hk")
+ }
+
+ # Calculate significance threshold
+ if (lod_threshold_perm) {
+ set.seed(123)
+ perm_cim <- qtl::scanone(cross, pheno.col = phenotype_name,
+ method = "hk", n.perm = n_permutations)
+ threshold <- summary(perm_cim)[1] # 95% threshold
+ } else {
+ threshold <- 3.0 # Default LOD threshold
}
- enhanced_rule_response(user_message, rv)
+
+ # Find peaks above threshold
+ peaks <- summary(out_cim, threshold = threshold)
+
+ # Format results
+ results <- list(
+ scanone = out_cim,
+ peaks = peaks,
+ threshold = threshold,
+ cofactors = cofactors
+ )
+
+ return(results)
+}
+
+#' Extract QTL effects including dominance
+extract_qtl_effects_cim <- function(cross, peaks, genotype_matrix, phenotype_vector) {
+ if (nrow(peaks) == 0) return(NULL)
+
+ effects_list <- list()
+
+ for (i in 1:nrow(peaks)) {
+ chr <- as.character(peaks$chr[i])
+ pos <- peaks$pos[i]
+ marker_name <- peaks$marker[i]
+
+ # Find closest marker to peak position
+ chr_markers <- colnames(genotype_matrix)[values$chromosome_info == chr]
+ if (length(chr_markers) == 0) next
+
+ marker_positions <- values$position_info[match(chr_markers, colnames(genotype_matrix))]
+ closest_idx <- which.min(abs(marker_positions - pos * 1e6)) # convert cM to bp approx
+ marker <- chr_markers[closest_idx]
+
+ # Find flanking markers
+ chr_data <- data.frame(
+ Marker = chr_markers,
+ Position = marker_positions,
+ stringsAsFactors = FALSE
+ )
+ chr_data <- chr_data[order(chr_data$Position), ]
+ marker_idx <- which(chr_data$Marker == marker)
+
+ low_flank <- if (marker_idx > 1) chr_data$Marker[marker_idx - 1] else marker
+ high_flank <- if (marker_idx < nrow(chr_data)) chr_data$Marker[marker_idx + 1] else marker
+
+ # Calculate effects using full additive + dominance model
+ geno <- genotype_matrix[, marker]
+ valid_idx <- !is.na(geno) & !is.na(phenotype_vector)
+ geno <- geno[valid_idx]
+ pheno <- phenotype_vector[valid_idx]
+
+ if (length(unique(geno)) < 2 || length(pheno) < 5) next
+
+ # Additive coding (0,1,2)
+ a_code <- geno
+
+ # Dominance coding (heterozygote indicator)
+ d_code <- as.numeric(geno == 1)
+ has_het <- length(unique(d_code)) > 1
+
+ # Fit full model
+ if (has_het) {
+ lm_full <- lm(pheno ~ a_code + d_code)
+ sm <- summary(lm_full)
+ pve_percent <- sm$r.squared * 100
+
+ coefs <- coef(lm_full)
+ additive_effect <- coefs["a_code"]
+ dominance_effect <- coefs["d_code"]
+
+ se_table <- sm$coefficients
+ se_add <- if ("a_code" %in% rownames(se_table)) se_table["a_code", "Std. Error"] else NA
+ se_dom <- if ("d_code" %in% rownames(se_table)) se_table["d_code", "Std. Error"] else NA
+
+ dom_ratio <- if (!is.na(additive_effect) && additive_effect != 0)
+ abs(dominance_effect / additive_effect) else NA
+
+ dom_class <- ifelse(is.na(dom_ratio), "Additive",
+ ifelse(dom_ratio > 1, "Overdominance",
+ ifelse(dom_ratio > 0.5, "Dominance",
+ ifelse(dom_ratio > 0.2, "Partial Dom.", "Additive"))))
+ } else {
+ lm_add <- lm(pheno ~ a_code)
+ sm <- summary(lm_add)
+ pve_percent <- sm$r.squared * 100
+
+ coefs <- coef(lm_add)
+ additive_effect <- coefs["a_code"]
+ dominance_effect <- NA
+ se_add <- sm$coefficients["a_code", "Std. Error"]
+ se_dom <- NA
+ dom_ratio <- NA
+ dom_class <- "Additive (no het)"
+ }
+
+ effects_list[[marker]] <- data.frame(
+ Marker = marker,
+ Chromosome = chr,
+ Position_bp = marker_positions[closest_idx],
+ LOD = peaks$lod[i],
+ Additive_Effect = additive_effect,
+ SE_Additive = se_add,
+ CI_Lower = ifelse(is.na(se_add), NA, additive_effect - 1.96 * se_add),
+ CI_Upper = ifelse(is.na(se_add), NA, additive_effect + 1.96 * se_add),
+ Dominance_Effect = dominance_effect,
+ SE_Dominance = se_dom,
+ Dominance_Ratio = dom_ratio,
+ Dominance_Class = dom_class,
+ PVE_Percent = pve_percent,
+ N_Samples = length(pheno),
+ N_Heterozygotes = sum(geno == 1),
+ Low_Flank = low_flank,
+ High_Flank = high_flank,
+ stringsAsFactors = FALSE
+ )
+ }
+
+ if (length(effects_list) == 0) return(NULL)
+ do.call(rbind, effects_list)
}
# ============================================================
-# UI
+# UI (same as before, but update PVE formula description)
# ============================================================
-
ui <- fluidPage(
shinyjs::useShinyjs(),
+
tags$head(
- tags$link(rel = "stylesheet", href = "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css"),
- tags$link(rel = "stylesheet", href = "https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;600&family=IBM+Plex+Sans:wght@300;400;500;600&display=swap"),
+ tags$link(rel = "stylesheet", type = "text/css",
+ href = "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css"),
+ tags$link(rel = "stylesheet", type = "text/css",
+ href = "https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;600&family=IBM+Plex+Sans:wght@300;400;500;600&display=swap"),
tags$script(HTML("
function simulateQTLDiscovery() {
setTimeout(function() {
const markers = document.querySelectorAll('.chromosome-marker');
let delay = 0;
- markers.forEach(function(marker) {
- setTimeout(function() {
+ markers.forEach(marker => {
+ setTimeout(() => {
marker.classList.add('highlighted');
- setTimeout(function() { marker.classList.add('pulse'); }, 300);
+ setTimeout(() => { marker.classList.add('pulse'); }, 300);
}, delay);
delay += 100;
});
@@ -484,401 +638,456 @@ ui <- fluidPage(
}
function resetAnimation() {
const markers = document.querySelectorAll('.chromosome-marker');
- markers.forEach(function(marker) {
- marker.classList.remove('highlighted', 'pulse');
+ markers.forEach(marker => {
+ marker.classList.remove('highlighted');
+ marker.classList.remove('pulse');
});
}
- Shiny.addCustomMessageHandler('simulateQTLDiscovery', function(m) { simulateQTLDiscovery(); });
- Shiny.addCustomMessageHandler('resetAnimation', function(m) { resetAnimation(); });
- Shiny.addCustomMessageHandler('scrollChatBottom', function(m) {
+ Shiny.addCustomMessageHandler('simulateQTLDiscovery', function(message) { simulateQTLDiscovery(); });
+ Shiny.addCustomMessageHandler('resetAnimation', function(message) { resetAnimation(); });
+ Shiny.addCustomMessageHandler('scrollChatBottom', function(message) {
setTimeout(function() {
- var cb = document.getElementById('chat_messages');
- if (cb) cb.scrollTop = cb.scrollHeight;
+ var chatBox = document.getElementById('chat_messages');
+ if (chatBox) chatBox.scrollTop = chatBox.scrollHeight;
}, 100);
});
$(document).on('keydown', '#chat_input', function(e) {
- if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); $('#send_chat').click(); }
+ if (e.key === 'Enter' && !e.shiftKey) {
+ e.preventDefault();
+ $('#send_chat').click();
+ }
});
")),
tags$style(HTML("
:root {
- --bg-primary:#0d1117;--bg-secondary:#161b22;--bg-tertiary:#21262d;
- --border:#30363d;--text-primary:#e6edf3;--text-secondary:#8b949e;
- --text-muted:#6e7681;--accent:#58a6ff;--accent-hover:#79c0ff;
- --success:#3fb950;--warning:#d29922;--danger:#f85149;
- --purple:#bc8cff;--teal:#39d353;
- --font-mono:'IBM Plex Mono',monospace;--font-sans:'IBM Plex Sans',sans-serif;
+ --bg-primary: #0d1117; --bg-secondary: #161b22; --bg-tertiary: #21262d;
+ --border: #30363d; --text-primary: #e6edf3; --text-secondary: #8b949e;
+ --text-muted: #6e7681; --accent: #58a6ff; --accent-hover: #79c0ff;
+ --success: #3fb950; --warning: #d29922; --danger: #f85149;
+ --purple: #bc8cff; --teal: #39d353;
+ --font-mono: 'IBM Plex Mono', monospace; --font-sans: 'IBM Plex Sans', sans-serif;
}
- *{box-sizing:border-box;margin:0;padding:0;}
- body{font-family:var(--font-sans);background:var(--bg-primary);color:var(--text-primary);font-size:14px;}
- .navbar{background:var(--bg-secondary)!important;border-bottom:1px solid var(--border);}
- .navbar-brand{color:var(--text-primary)!important;font-family:var(--font-mono);font-weight:600;}
- .navbar-nav>li>a{color:var(--text-secondary)!important;font-size:13px;}
- .navbar-nav>li.active>a,.navbar-nav>li>a:hover{color:var(--accent)!important;background:transparent!important;}
- .main-header{background:linear-gradient(135deg,#1c2b3a,#0d1117);border:1px solid var(--border);border-left:3px solid var(--accent);padding:20px 24px;border-radius:6px;margin-bottom:20px;}
- .main-header h2{font-family:var(--font-mono);font-size:1.3rem;font-weight:600;color:var(--accent);}
- .main-header p{color:var(--text-secondary);margin-top:6px;font-size:13px;}
- .cim-box{background:#0d1a0d;border:1px solid var(--success);border-left:3px solid var(--success);border-radius:6px;padding:12px 16px;margin:10px 0;font-family:var(--font-mono);font-size:12px;color:#7ee787;}
- .cim-box .box-title{font-weight:600;color:var(--success);margin-bottom:6px;}
- .card{background:var(--bg-secondary);border:1px solid var(--border);border-radius:6px;margin-bottom:20px;}
- .card-header{background:var(--bg-tertiary);border-bottom:1px solid var(--border);padding:12px 16px;font-family:var(--font-mono);font-size:12px;color:var(--text-secondary);letter-spacing:.5px;text-transform:uppercase;}
- .card-body{padding:16px;}
- .form-control,.selectize-input{background:var(--bg-tertiary)!important;border:1px solid var(--border)!important;color:var(--text-primary)!important;border-radius:4px;font-size:13px;}
- .form-control:focus{border-color:var(--accent)!important;box-shadow:0 0 0 2px rgba(88,166,255,.2)!important;}
- label{color:var(--text-secondary);font-size:12px;margin-bottom:4px;}
- .btn{border-radius:4px;font-family:var(--font-mono);font-size:12px;font-weight:600;transition:all .15s;border:1px solid;}
- .btn-primary{background:var(--accent);border-color:var(--accent);color:#0d1117;}
- .btn-primary:hover{background:var(--accent-hover);border-color:var(--accent-hover);color:#0d1117;}
- .btn-info{background:transparent;border-color:var(--teal);color:var(--teal);}
- .btn-info:hover{background:var(--teal);color:#0d1117;}
- .btn-danger{background:transparent;border-color:var(--danger);color:var(--danger);}
- .btn-danger:hover{background:var(--danger);color:white;}
- .help-block{color:var(--text-muted);font-size:11px;margin-top:4px;}
- .dataTables_wrapper{color:var(--text-secondary)!important;}
- table.dataTable{background:var(--bg-secondary)!important;color:var(--text-primary)!important;border-color:var(--border)!important;}
- table.dataTable thead th{background:var(--bg-tertiary)!important;color:var(--text-secondary)!important;border-bottom:1px solid var(--border)!important;font-family:var(--font-mono);font-size:11px;letter-spacing:.5px;}
- table.dataTable tbody tr:hover{background:var(--bg-tertiary)!important;}
- table.dataTable tbody td{border-bottom:1px solid var(--border)!important;font-size:12px;}
- .dataTables_info,.dataTables_length,.dataTables_filter,.dataTables_paginate{color:var(--text-muted)!important;font-size:12px;}
- .dataTables_filter input,.dataTables_length select{background:var(--bg-tertiary)!important;border:1px solid var(--border)!important;color:var(--text-primary)!important;border-radius:3px;}
- .paginate_button{color:var(--text-secondary)!important;}
- .paginate_button.current{background:var(--accent)!important;color:#0d1117!important;border-color:var(--accent)!important;}
- .chromosome-container{margin:12px 0;padding:12px 16px;background:var(--bg-tertiary);border-radius:4px;border:1px solid var(--border);}
- .chromosome{height:24px;background:linear-gradient(to right,var(--bg-primary),var(--border));border-radius:12px;margin:8px 0;position:relative;overflow:hidden;border:1px solid var(--border);}
- .chromosome-marker{position:absolute;height:34px;width:6px;background:var(--text-muted);border-radius:3px;top:-5px;transform:translateX(-50%);transition:all .3s ease;}
- .chromosome-marker.significant{background:var(--danger)!important;height:40px!important;width:8px!important;top:-8px!important;}
- .chromosome-marker.flanking{background:var(--accent)!important;height:30px!important;width:5px!important;top:-3px!important;}
- .chromosome-marker.selection{background:var(--success)!important;}
- .chromosome-marker.highlighted{background:var(--warning)!important;box-shadow:0 0 10px rgba(210,153,34,.6);}
- .chromosome-marker.pulse{animation:pulse 1.5s infinite;}
- @keyframes pulse{0%,100%{transform:translateX(-50%) scale(1);}50%{transform:translateX(-50%) scale(1.3);opacity:.7;}}
- .chromosome-legend{display:flex;justify-content:space-between;font-size:10px;color:var(--text-muted);font-family:var(--font-mono);margin-top:2px;}
- .chromosome-title{font-family:var(--font-mono);font-size:11px;color:var(--accent);margin-bottom:4px;}
- #chat-panel{position:fixed;bottom:20px;right:20px;z-index:9999;width:440px;display:flex;flex-direction:column;}
- #chat-toggle-btn{align-self:flex-end;width:56px;height:56px;border-radius:50%;background:linear-gradient(135deg,var(--accent),var(--purple));border:none;cursor:pointer;display:flex;align-items:center;justify-content:center;box-shadow:0 4px 20px rgba(88,166,255,.4);transition:all .2s;color:#0d1117;font-size:24px;}
- #chat-toggle-btn:hover{transform:scale(1.05);}
- #chat-window{display:none;flex-direction:column;background:var(--bg-secondary);border:1px solid var(--accent);border-radius:12px;overflow:hidden;box-shadow:0 8px 40px rgba(0,0,0,.5);margin-bottom:10px;height:640px;}
- #chat-window.open{display:flex;}
- #chat-header{background:linear-gradient(135deg,var(--bg-tertiary),#1c2b3a);border-bottom:1px solid var(--border);padding:12px 16px;display:flex;flex-direction:column;gap:8px;}
- .chat-header-top{display:flex;align-items:center;justify-content:space-between;}
- .chat-title{display:flex;align-items:center;gap:10px;}
- .chat-avatar{width:32px;height:32px;background:linear-gradient(135deg,var(--accent),var(--purple));border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:16px;color:#0d1117;font-weight:bold;flex-shrink:0;}
- #chat-header h4{font-family:var(--font-mono);font-size:13px;font-weight:600;color:var(--text-primary);margin:0;}
- #chat-header p{font-size:11px;color:var(--text-muted);margin:0;}
- #chat-header p.ai-mode{color:var(--success);}
- #chat-close-btn{background:none;border:none;color:var(--text-muted);cursor:pointer;font-size:18px;padding:4px;transition:color .15s;}
- #chat-close-btn:hover{color:var(--text-primary);}
- .chat-model-selector{display:flex;align-items:center;gap:8px;padding:4px 0;}
- .chat-model-selector label{color:var(--text-muted);font-size:10px;font-family:var(--font-mono);white-space:nowrap;margin:0;}
- .chat-model-selector select{flex:1;background:var(--bg-primary)!important;border:1px solid var(--border)!important;color:var(--text-secondary)!important;border-radius:4px;font-size:11px;font-family:var(--font-mono);padding:3px 6px;}
- .model-status-dot{width:7px;height:7px;border-radius:50%;flex-shrink:0;}
- .model-status-dot.online{background:var(--success);box-shadow:0 0 6px var(--success);}
- .model-status-dot.offline{background:var(--warning);box-shadow:0 0 6px var(--warning);}
- .test-model-btn{background:transparent;border:1px solid var(--border);color:var(--text-muted);border-radius:3px;padding:2px 7px;font-size:10px;font-family:var(--font-mono);cursor:pointer;transition:all .15s;white-space:nowrap;}
- .test-model-btn:hover{border-color:var(--accent);color:var(--accent);}
- #chat_messages{flex:1;overflow-y:auto;padding:16px;display:flex;flex-direction:column;gap:12px;background:var(--bg-primary);}
- .chat-msg{max-width:92%;animation:fadeIn .3s ease;}
- @keyframes fadeIn{from{opacity:0;transform:translateY(10px);}to{opacity:1;transform:translateY(0);}}
- .chat-msg.user{align-self:flex-end;}
- .chat-msg.assistant{align-self:flex-start;}
- .chat-bubble{padding:12px 16px;border-radius:16px;font-size:13px;line-height:1.6;word-wrap:break-word;white-space:pre-wrap;}
- .chat-msg.user .chat-bubble{background:linear-gradient(135deg,var(--accent),#3a7bd5);color:#0d1117;border-bottom-right-radius:4px;}
- .chat-msg.assistant .chat-bubble{background:var(--bg-tertiary);color:var(--text-primary);border:1px solid var(--border);border-bottom-left-radius:4px;}
- .chat-bubble strong{color:var(--accent);}
- .chat-meta{font-size:10px;color:var(--text-muted);margin-top:4px;font-family:var(--font-mono);padding:0 4px;display:flex;align-items:center;gap:6px;}
- .chat-meta .model-tag{color:var(--purple);font-size:9px;}
- .typing-indicator{display:flex;gap:4px;padding:12px 16px;background:var(--bg-tertiary);border:1px solid var(--border);border-radius:16px;border-bottom-left-radius:4px;width:fit-content;}
- .typing-dot{width:8px;height:8px;background:var(--text-muted);border-radius:50%;animation:typingBounce 1.4s infinite;}
- .typing-dot:nth-child(2){animation-delay:.2s;}
- .typing-dot:nth-child(3){animation-delay:.4s;}
- @keyframes typingBounce{0%,60%,100%{transform:translateY(0);}30%{transform:translateY(-8px);}}
- .quick-questions{padding:8px 16px;display:flex;flex-wrap:wrap;gap:6px;border-bottom:1px solid var(--border);background:var(--bg-secondary);}
- .quick-q-btn{background:var(--bg-tertiary);border:1px solid var(--border);color:var(--text-secondary);border-radius:16px;padding:4px 12px;font-size:11px;cursor:pointer;transition:all .15s;}
- .quick-q-btn:hover{border-color:var(--accent);color:var(--accent);background:rgba(88,166,255,.1);}
- #chat-footer{padding:12px 16px;border-top:1px solid var(--border);background:var(--bg-tertiary);}
- #chat_input{width:100%;background:var(--bg-secondary)!important;border:1px solid var(--border)!important;border-radius:8px;color:var(--text-primary)!important;font-size:13px;resize:none;padding:10px 12px;font-family:var(--font-sans);margin-bottom:8px;}
- #chat_input:focus{border-color:var(--accent)!important;outline:none;}
- .chat-actions{display:flex;gap:8px;}
- #send_chat{flex:1;background:linear-gradient(135deg,var(--accent),#3a7bd5);color:#0d1117;border:none;border-radius:6px;padding:8px 16px;font-family:var(--font-mono);font-size:12px;font-weight:600;cursor:pointer;transition:all .15s;display:flex;align-items:center;justify-content:center;gap:6px;}
- #send_chat:hover:not(:disabled){transform:translateY(-1px);box-shadow:0 4px 12px rgba(88,166,255,.4);}
- #send_chat: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);}
+ * { box-sizing: border-box; margin: 0; padding: 0; }
+ body { font-family: var(--font-sans); background-color: var(--bg-primary); color: var(--text-primary); font-size: 14px; }
+ .navbar { background-color: var(--bg-secondary) !important; border-bottom: 1px solid var(--border); }
+ .navbar-brand { color: var(--text-primary) !important; font-family: var(--font-mono); font-weight: 600; letter-spacing: -0.5px; }
+ .navbar-nav > li > a { color: var(--text-secondary) !important; font-family: var(--font-sans); font-size: 13px; }
+ .navbar-nav > li.active > a, .navbar-nav > li > a:hover { color: var(--accent) !important; background: transparent !important; }
+ .main-header { background: linear-gradient(135deg, #1c2b3a 0%, #0d1117 100%); border: 1px solid var(--border); border-left: 3px solid var(--accent); color: var(--text-primary); padding: 20px 24px; border-radius: 6px; margin-bottom: 20px; }
+ .main-header h2 { font-family: var(--font-mono); font-size: 1.3rem; font-weight: 600; color: var(--accent); }
+ .main-header p { color: var(--text-secondary); margin-top: 6px; font-size: 13px; }
+ .pve-formula-box { background: #0d1a0d; border: 1px solid var(--success); border-left: 3px solid var(--success); border-radius: 6px; padding: 12px 16px; margin: 10px 0; font-family: var(--font-mono); font-size: 12px; color: #7ee787; }
+ .pve-formula-box .formula-title { font-weight: 600; color: var(--success); margin-bottom: 6px; }
+ .card { background-color: var(--bg-secondary); border: 1px solid var(--border); border-radius: 6px; margin-bottom: 20px; }
+ .card-header { background-color: var(--bg-tertiary); border-bottom: 1px solid var(--border); padding: 12px 16px; font-family: var(--font-mono); font-size: 12px; color: var(--text-secondary); letter-spacing: 0.5px; text-transform: uppercase; }
+ .card-body { padding: 16px; }
+ .form-control, .selectize-input { background-color: var(--bg-tertiary) !important; border: 1px solid var(--border) !important; color: var(--text-primary) !important; border-radius: 4px; font-family: var(--font-sans); font-size: 13px; }
+ .form-control:focus { border-color: var(--accent) !important; box-shadow: 0 0 0 2px rgba(88,166,255,0.2) !important; }
+ label { color: var(--text-secondary); font-size: 12px; margin-bottom: 4px; }
+ .btn { border-radius: 4px; font-family: var(--font-mono); font-size: 12px; font-weight: 600; letter-spacing: 0.3px; transition: all 0.15s; border: 1px solid; }
+ .btn-primary { background-color: var(--accent); border-color: var(--accent); color: #0d1117; }
+ .btn-primary:hover { background-color: var(--accent-hover); border-color: var(--accent-hover); color: #0d1117; }
+ .btn-info { background-color: transparent; border-color: var(--teal); color: var(--teal); }
+ .btn-info:hover { background-color: var(--teal); color: #0d1117; }
+ .btn-danger { background-color: transparent; border-color: var(--danger); color: var(--danger); }
+ .btn-danger:hover { background-color: var(--danger); color: white; }
+ .help-block, .shiny-input-container .help-block { color: var(--text-muted); font-size: 11px; margin-top: 4px; }
+ .btn-file { background-color: var(--bg-tertiary); border-color: var(--border); color: var(--text-secondary); }
+ .dataTables_wrapper { color: var(--text-secondary) !important; }
+ table.dataTable { background-color: var(--bg-secondary) !important; color: var(--text-primary) !important; border-color: var(--border) !important; }
+ table.dataTable thead th { background-color: 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: 0.5px; }
+ table.dataTable tbody tr:hover { background-color: var(--bg-tertiary) !important; }
+ table.dataTable tbody td { border-bottom: 1px solid var(--border) !important; font-size: 12px; }
+ .dataTables_info, .dataTables_length, .dataTables_filter, .dataTables_paginate { color: var(--text-muted) !important; font-size: 12px; }
+ .dataTables_filter input, .dataTables_length select { background: var(--bg-tertiary) !important; border: 1px solid var(--border) !important; color: var(--text-primary) !important; border-radius: 3px; }
+ .paginate_button { color: var(--text-secondary) !important; }
+ .paginate_button.current { background: var(--accent) !important; color: #0d1117 !important; border-color: var(--accent) !important; }
+ .chromosome-container { margin: 12px 0; padding: 12px 16px; background: var(--bg-tertiary); border-radius: 4px; border: 1px solid var(--border); }
+ .chromosome { height: 24px; background: linear-gradient(to right, var(--bg-primary), var(--border)); border-radius: 12px; margin: 8px 0; position: relative; overflow: hidden; border: 1px solid var(--border); }
+ .chromosome-marker { position: absolute; height: 34px; width: 6px; background-color: var(--text-muted); border-radius: 3px; top: -5px; transform: translateX(-50%); transition: all 0.3s ease; }
+ .chromosome-marker.significant { background-color: var(--danger) !important; height: 40px !important; width: 8px !important; top: -8px !important; }
+ .chromosome-marker.flanking { background-color: var(--accent) !important; height: 30px !important; width: 5px !important; top: -3px !important; }
+ .chromosome-marker.selection { background-color: var(--success) !important; height: 34px !important; width: 6px !important; top: -5px !important; }
+ .chromosome-marker.highlighted { background-color: var(--warning) !important; box-shadow: 0 0 10px rgba(210,153,34,0.6); }
+ .chromosome-marker.pulse { animation: pulse 1.5s infinite; }
+ @keyframes pulse { 0% { transform: translateX(-50%) scale(1); } 50% { transform: translateX(-50%) scale(1.3); opacity: 0.7; } 100% { transform: translateX(-50%) scale(1); } }
+ .chromosome-legend { display: flex; justify-content: space-between; font-size: 10px; color: var(--text-muted); font-family: var(--font-mono); margin-top: 2px; }
+ .chromosome-title { font-family: var(--font-mono); font-size: 11px; color: var(--accent); margin-bottom: 4px; }
+ .simulation-controls { margin: 12px 0; display: flex; gap: 8px; }
+ .simulation-btn { background-color: transparent; color: var(--purple); border: 1px solid var(--purple); padding: 5px 12px; border-radius: 4px; cursor: pointer; font-family: var(--font-mono); font-size: 11px; transition: all 0.15s; }
+ .simulation-btn:hover { background-color: var(--purple); color: #0d1117; }
+ #chat-panel { position: fixed; bottom: 20px; right: 20px; z-index: 9999; width: 440px; display: flex; flex-direction: column; }
+ #chat-toggle-btn { align-self: flex-end; width: 56px; height: 56px; border-radius: 50%; background: linear-gradient(135deg, var(--accent), var(--purple)); border: none; cursor: pointer; display: flex; align-items: center; justify-content: center; box-shadow: 0 4px 20px rgba(88,166,255,0.4); transition: all 0.2s; color: #0d1117; font-size: 24px; }
+ #chat-toggle-btn:hover { transform: scale(1.05); box-shadow: 0 6px 24px rgba(88,166,255,0.6); }
+ #chat-window { display: none; flex-direction: column; background: var(--bg-secondary); border: 1px solid var(--accent); border-radius: 12px; overflow: hidden; box-shadow: 0 8px 40px rgba(0,0,0,0.5); margin-bottom: 10px; height: 640px; }
+ #chat-window.open { display: flex; }
+ #chat-header { background: linear-gradient(135deg, var(--bg-tertiary), #1c2b3a); border-bottom: 1px solid var(--border); padding: 12px 16px; display: flex; flex-direction: column; gap: 8px; }
+ .chat-header-top { display: flex; align-items: center; justify-content: space-between; }
+ .chat-title { display: flex; align-items: center; gap: 10px; }
+ .chat-avatar { width: 32px; height: 32px; background: linear-gradient(135deg, var(--accent), var(--purple)); border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 16px; color: #0d1117; font-weight: bold; flex-shrink: 0; }
+ #chat-header h4 { font-family: var(--font-mono); font-size: 13px; font-weight: 600; color: var(--text-primary); margin: 0; }
+ #chat-header p { font-size: 11px; color: var(--text-muted); margin: 0; }
+ #chat-header p.ai-mode { color: var(--success); }
+ #chat-header p.rule-mode { color: var(--warning); }
+ #chat-close-btn { background: none; border: none; color: var(--text-muted); cursor: pointer; font-size: 18px; padding: 4px; transition: color 0.15s; flex-shrink: 0; }
+ #chat-close-btn:hover { color: var(--text-primary); }
+ .chat-model-selector { display: flex; align-items: center; gap: 8px; padding: 4px 0; }
+ .chat-model-selector label { color: var(--text-muted); font-size: 10px; font-family: var(--font-mono); white-space: nowrap; margin: 0; }
+ .chat-model-selector select { flex: 1; background: var(--bg-primary) !important; border: 1px solid var(--border) !important; color: var(--text-secondary) !important; border-radius: 4px; font-size: 11px; font-family: var(--font-mono); padding: 3px 6px; cursor: pointer; }
+ .chat-model-selector select:focus { border-color: var(--accent) !important; outline: none; }
+ .model-status-dot { width: 7px; height: 7px; border-radius: 50%; flex-shrink: 0; }
+ .model-status-dot.online { background: var(--success); box-shadow: 0 0 6px var(--success); }
+ .model-status-dot.offline { background: var(--warning); box-shadow: 0 0 6px var(--warning); }
+ .test-model-btn { background: transparent; border: 1px solid var(--border); color: var(--text-muted); border-radius: 3px; padding: 2px 7px; font-size: 10px; font-family: var(--font-mono); cursor: pointer; transition: all 0.15s; white-space: nowrap; }
+ .test-model-btn:hover { border-color: var(--accent); color: var(--accent); }
+ #chat_messages { flex: 1; overflow-y: auto; padding: 16px; display: flex; flex-direction: column; gap: 12px; background: var(--bg-primary); }
+ .chat-msg { max-width: 92%; animation: fadeIn 0.3s ease; }
+ @keyframes fadeIn { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } }
+ .chat-msg.user { align-self: flex-end; }
+ .chat-msg.assistant { align-self: flex-start; }
+ .chat-bubble { padding: 12px 16px; border-radius: 16px; font-size: 13px; line-height: 1.6; word-wrap: break-word; white-space: pre-wrap; }
+ .chat-msg.user .chat-bubble { background: linear-gradient(135deg, var(--accent), #3a7bd5); color: #0d1117; border-bottom-right-radius: 4px; }
+ .chat-msg.assistant .chat-bubble { background: var(--bg-tertiary); color: var(--text-primary); border: 1px solid var(--border); border-bottom-left-radius: 4px; }
+ .chat-bubble strong { color: var(--accent); }
+ .chat-meta { font-size: 10px; color: var(--text-muted); margin-top: 4px; font-family: var(--font-mono); padding: 0 4px; display: flex; align-items: center; gap: 6px; }
+ .chat-meta .model-tag { color: var(--purple); font-size: 9px; }
+ .typing-indicator { display: flex; gap: 4px; padding: 12px 16px; background: var(--bg-tertiary); border: 1px solid var(--border); border-radius: 16px; border-bottom-left-radius: 4px; width: fit-content; }
+ .typing-dot { width: 8px; height: 8px; background: var(--text-muted); border-radius: 50%; animation: typingBounce 1.4s infinite; }
+ .typing-dot:nth-child(2) { animation-delay: 0.2s; }
+ .typing-dot:nth-child(3) { animation-delay: 0.4s; }
+ @keyframes typingBounce { 0%, 60%, 100% { transform: translateY(0); } 30% { transform: translateY(-8px); } }
+ .quick-questions { padding: 8px 16px; display: flex; flex-wrap: wrap; gap: 6px; border-bottom: 1px solid var(--border); background: var(--bg-secondary); }
+ .quick-q-btn { background: var(--bg-tertiary); border: 1px solid var(--border); color: var(--text-secondary); border-radius: 16px; padding: 4px 12px; font-size: 11px; cursor: pointer; transition: all 0.15s; }
+ .quick-q-btn:hover { border-color: var(--accent); color: var(--accent); background: rgba(88,166,255,0.1); }
+ #chat-footer { padding: 12px 16px; border-top: 1px solid var(--border); background: var(--bg-tertiary); }
+ #chat_input { width: 100%; background: var(--bg-secondary) !important; border: 1px solid var(--border) !important; border-radius: 8px; color: var(--text-primary) !important; font-size: 13px; resize: none; padding: 10px 12px; font-family: var(--font-sans); margin-bottom: 8px; }
+ #chat_input:focus { border-color: var(--accent) !important; outline: none; }
+ .chat-file-row { display: flex; align-items: center; gap: 8px; margin-bottom: 8px; }
+ #chat_file_upload_btn { background: transparent; border: 1px solid var(--border); color: var(--text-muted); border-radius: 6px; padding: 6px 10px; font-size: 12px; cursor: pointer; transition: all 0.15s; display: flex; align-items: center; gap: 5px; white-space: nowrap; }
+ #chat_file_upload_btn:hover { border-color: var(--accent); color: var(--accent); }
+ #chat_file_preview { display: none; font-size: 11px; font-family: var(--font-mono); color: var(--text-muted); flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+ #chat_file_clear_btn { background: transparent; border: none; color: var(--text-muted); cursor: pointer; font-size: 14px; padding: 2px 4px; transition: color 0.15s; }
+ #chat_file_clear_btn:hover { color: var(--danger); }
+ .chat-actions { display: flex; gap: 8px; }
+ #send_chat { flex: 1; background: linear-gradient(135deg, var(--accent), #3a7bd5); color: #0d1117; border: none; border-radius: 6px; padding: 8px 16px; font-family: var(--font-mono); font-size: 12px; font-weight: 600; cursor: pointer; transition: all 0.15s; display: flex; align-items: center; justify-content: center; gap: 6px; }
+ #send_chat:hover:not(:disabled) { transform: translateY(-1px); box-shadow: 0 4px 12px rgba(88,166,255,0.4); }
+ #send_chat:disabled { opacity: 0.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 0.15s; }
+ #clear_chat:hover { border-color: var(--danger); color: var(--danger); }
"))
),
-
+
navbarPage(
- title = tags$span(tags$i(class = "fas fa-dna", style = "margin-right:8px;color:#58a6ff;"), "QTL-Mapper CIM"),
+ title = tags$span(tags$i(class = "fas fa-dna", style = "margin-right:8px; color:#58a6ff;"), "QTL-Mapper AI - CIM Edition"),
id = "nav",
-
- # ---- DATA UPLOAD ----
+
+ # ---- Data Upload tab (updated with CIM parameters) ----
tabPanel("Data Upload", icon = icon("upload"),
- div(class = "main-header",
- h2(tags$i(class = "fas fa-upload", style = "margin-right:8px;"), "Data Upload — CIM Mode"),
- p("Composite Interval Mapping: higher power, correct flanking markers, better PVE estimation")
- ),
- fluidRow(
- column(12,
- div(class = "cim-box",
- div(class = "box-title", tags$i(class = "fas fa-chart-line", style = "margin-right:6px;"), "CIM Method + PVE Formula"),
- tags$pre(style = "background:transparent;border:none;margin:0;color:#7ee787;font-size:11px;",
- "Composite Interval Mapping (Zeng 1993, 1994):\n",
- " For each marker m:\n",
- " 1. Cofactors = top K markers from RF (excluding nearby markers ±window on same chr)\n",
- " 2. Fit: lm(Y ~ marker_m + cofactors) → LOD = -log10(p_marker)\n",
- " 3. PVE_CIM (%) = R²_full × 100 [marker + cofactors — higher than single-marker PVE]\n",
- " 4. PVE_marker (%) = R² from lm(Y ~ a + d) [marker alone, add+dom model]\n\n",
- "Flanking fix: uses FULL marker table (not post-NZV subset)\n",
- "Ref: Zeng (1993) PNAS; Falconer & Mackay (1996); Lynch & Walsh (1998)")
- )
- )
- ),
- fluidRow(
- column(4,
- div(class = "card",
- div(class = "card-header", tags$i(class = "fas fa-table", style = "margin-right:6px;"), "Training Data"),
- div(class = "card-body",
- fileInput("genotype_file", "Training Genotype CSV", accept = ".csv", buttonLabel = "Browse"),
- helpText("Row1=header(id,markers), Row2=chromosomes, Row3=positions, rest=samples. Coded 0/1/2."),
- fileInput("phenotype_file", "Training Phenotype CSV", accept = ".csv", buttonLabel = "Browse"),
- helpText("id column + numeric trait columns."),
- selectInput("phenotype_column", "Select Phenotype Column", choices = NULL)
- )
- )
- ),
- column(4,
- div(class = "card",
- div(class = "card-header", tags$i(class = "fas fa-sliders-h", style = "margin-right:6px;color:#bc8cff;"), "CIM Parameters"),
- div(class = "card-body",
- sliderInput("test_size", "Validation Proportion", min = 0.1, max = 0.5, value = 0.2, step = 0.05),
- numericInput("lod_threshold","LOD Threshold", value = 2.0, min = 0.5, max = 10.0, step = 0.1),
- numericInput("n_cofactors", "CIM Cofactors (K)", value = 10, min = 1, max = 30, step = 1),
- helpText("More cofactors = better background control, slower. Try 5-15."),
- numericInput("window_size", "Exclusion Window (±markers)", value = 10, min = 1, max = 30, step = 1),
- helpText("Nearby markers excluded from cofactors to avoid collinearity."),
- actionButton("run_analysis", "Run CIM Analysis", class = "btn-primary btn-block", icon = icon("play"))
- )
- )
- ),
- column(4,
- div(class = "card",
- div(class = "card-header", tags$i(class = "fas fa-vial", style = "margin-right:6px;color:#3fb950;"), "Test Data (Optional)"),
- div(class = "card-body",
- fileInput("test_genotype_file", "Test Genotype CSV", accept = ".csv", buttonLabel = "Browse"),
- helpText("Same format as training genotype."),
- tags$br(),
- fileInput("pop_file", "Population Metadata CSV", accept = ".csv", buttonLabel = "Browse"),
- helpText("Columns: id, population (e.g. Domesticated/Wild)."),
- actionButton("predict_test_phenotype", "Predict Test Phenotypes", class = "btn-info btn-block", icon = icon("magic"))
- )
- )
- )
- ),
- 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"))
- )
- )
- )
- )
- )
+ div(class = "main-header",
+ h2(tags$i(class = "fas fa-upload", style = "margin-right:8px;"), "Data Upload"),
+ p("Upload genotype, phenotype, and population data for Composite Interval Mapping (CIM)")
+ ),
+ fluidRow(
+ column(12,
+ div(class = "pve-formula-box",
+ div(class = "formula-title", tags$i(class = "fas fa-square-root-alt", style = "margin-right:6px;"), "Composite Interval Mapping (CIM) — Improved QTL Detection"),
+ tags$pre(style = "background:transparent; border:none; margin:0; color:#7ee787; font-size:11px;",
+ "CIM controls for background QTLs to increase detection power:\n",
+ "1. Stepwise selection identifies significant cofactors\n",
+ "2. Cofactors remove variance from other QTLs\n",
+ "3. Cleaner QTL signals → higher LOD scores and PVE\n",
+ "4. Full additive + dominance model for effect estimation\n",
+ "5. Flanking markers automatically identified\n\n",
+ "PVE (%) = R²_full × 100 from lm(phenotype ~ a + d)")
+ )
+ )
+ ),
+ fluidRow(
+ column(4,
+ div(class = "card",
+ div(class = "card-header", tags$i(class = "fas fa-table", style = "margin-right:6px;"), "Training Data"),
+ div(class = "card-body",
+ fileInput("genotype_file", "Training Genotype CSV", accept = ".csv", buttonLabel = "Browse"),
+ helpText("CSV: Row1=header(id,markers), Row2=chromosomes, Row3=positions, rows=samples. Genotype coded 0/1/2."),
+ fileInput("phenotype_file", "Training Phenotype CSV", accept = ".csv", buttonLabel = "Browse"),
+ helpText("CSV: id column + numeric trait columns."),
+ selectInput("phenotype_column", "Select Phenotype Column", choices = NULL)
+ )
+ )
+ ),
+ column(4,
+ div(class = "card",
+ div(class = "card-header", tags$i(class = "fas fa-vial", style = "margin-right:6px; color:#3fb950;"), "Test Data (Optional)"),
+ div(class = "card-body",
+ fileInput("test_genotype_file", "Test Genotype CSV", accept = ".csv", buttonLabel = "Browse"),
+ helpText("Optional: Same format as training genotype data."),
+ tags$br(),
+ actionButton("predict_test_phenotype", "Predict Test Phenotypes", class = "btn-info btn-block", icon = icon("magic"))
+ )
+ )
+ ),
+ column(4,
+ div(class = "card",
+ div(class = "card-header", tags$i(class = "fas fa-sliders-h", style = "margin-right:6px; color:#bc8cff;"), "CIM Parameters"),
+ div(class = "card-body",
+ sliderInput("test_size", "Validation Set Proportion", min = 0.1, max = 0.5, value = 0.2, step = 0.05),
+ numericInput("lod_threshold", "LOD Threshold (default)", value = 3.0, min = 1.0, max = 10.0, step = 0.1),
+ numericInput("n_cofactors", "Number of Cofactors", value = 5, min = 1, max = 20, step = 1),
+ numericInput("window_size", "Window Size (cM)", value = 10, min = 1, max = 50, step = 1),
+ checkboxInput("perm_threshold", "Calculate permuted threshold", value = TRUE),
+ actionButton("run_analysis", "Run CIM Analysis", class = "btn-primary btn-block", icon = icon("play"))
+ )
+ )
+ )
+ ),
+ 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"),
- p("LOD genome scan, flanking markers, additive + dominance PVE, model performance")
- ),
- fluidRow(
- column(6, div(class = "card", div(class = "card-header", "CIM Manhattan Plot (LOD Scores)"), div(class = "card-body", plotlyOutput("lod_plot_2d", height = "500px")))),
- column(6, div(class = "card",
- div(class = "card-header", "Chromosome Visualization"),
- div(class = "card-body",
- uiOutput("chromosome_viz"),
- div(style = "margin:12px 0;display:flex;gap:8px;",
- actionButton("simulate_btn", "Simulate Discovery", class = "btn-info"),
- actionButton("reset_btn", "Reset", class = "btn-danger")
- )
- )
- ))
- ),
- fluidRow(
- column(4, div(class = "card", div(class = "card-header", "Model Performance"), div(class = "card-body", plotlyOutput("performance_plot")))),
- column(4, div(class = "card", div(class = "card-header", "Train: Predicted vs Observed"), div(class = "card-body", plotlyOutput("regression_plot_train", height = "300px")))),
- column(4, div(class = "card", div(class = "card-header", "Validation: Predicted vs Observed"), div(class = "card-body", plotlyOutput("regression_plot_test", height = "300px"))))
- ),
- fluidRow(
- column(12, div(class = "card",
- div(class = "card-header", "CIM QTL Effects — All markers scanned (Additive + Dominance PVE)"),
- div(class = "card-body",
- DTOutput("qtl_effects_table_train"),
- tags$br(),
- downloadButton("download_train_results", "Download CIM Results (.xlsx)")
- )
- ))
- ),
- 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 ----
+
+ # ---- Domestication tab (same as before) ----
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")
- ),
- fluidRow(
- column(4,
- div(class = "card",
- div(class = "card-header", "Parameters"),
- div(class = "card-body",
- numericInput("fst_threshold", "Fst Threshold", value = 0.1, min = 0.05, max = 0.5, step = 0.01),
- numericInput("tajima_threshold", "Tajima's D Threshold", value = -1, min = -5, max = 0, step = 0.1),
- actionButton("run_domestication", "Run Domestication Analysis", class = "btn-primary btn-block", icon = icon("play"))
- )
- )
- ),
- column(8,
- div(class = "card",
- div(class = "card-header", "Population Data Preview"),
- div(class = "card-body", DTOutput("pop_preview"))
- )
- )
- ),
- fluidRow(
- column(6, div(class = "card", div(class = "card-header", "Fst Manhattan Plot"), div(class = "card-body", plotlyOutput("fst_plot", height = "400px")))),
- column(6, div(class = "card", div(class = "card-header", "Tajima's D Manhattan Plot"),div(class = "card-body", plotlyOutput("tajima_plot", height = "400px"))))
- ),
- 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")
- )
- )
- )
- )
+ div(class = "main-header",
+ h2(tags$i(class = "fas fa-leaf", style = "margin-right:8px;"), "Domestication Analysis"),
+ p("Analyze selection signatures: Fst, Tajima's D, and nucleotide diversity")
+ ),
+ fluidRow(
+ column(4,
+ div(class = "card",
+ div(class = "card-header", "Population Metadata"),
+ div(class = "card-body",
+ fileInput("pop_file", "Population Metadata CSV", accept = ".csv", buttonLabel = "Browse"),
+ helpText("CSV with 'id' and 'population' columns (e.g., Domesticated, Wild)."),
+ numericInput("fst_threshold", "Fst Threshold", value = 0.1, min = 0.05, max = 0.5, step = 0.01),
+ numericInput("tajima_threshold", "Tajima's D Threshold", value = -1, min = -5, max = 0, step = 0.1),
+ actionButton("run_domestication", "Run Domestication Analysis", class = "btn-primary btn-block", icon = icon("play"))
+ )
+ )
+ ),
+ column(8,
+ div(class = "card",
+ div(class = "card-header", "Population Data Preview"),
+ div(class = "card-body", DTOutput("pop_preview"))
+ )
+ )
+ ),
+ fluidRow(
+ column(6, div(class = "card", div(class = "card-header", "Fst Manhattan Plot"), div(class = "card-body", plotlyOutput("fst_plot", height = "400px")))),
+ column(6, div(class = "card", div(class = "card-header", "Tajima's D Manhattan Plot"), div(class = "card-body", plotlyOutput("tajima_plot", height = "400px"))))
+ ),
+ 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")
+ )
+ )
+ )
+ )
),
-
- # ---- INTERPRETATION ----
+
+ # ---- Results tab (updated for CIM) ----
+ tabPanel("Results", icon = icon("chart-line"),
+ div(class = "main-header",
+ h2(tags$i(class = "fas fa-chart-line", style = "margin-right:8px;"), "CIM Results"),
+ p("Composite Interval Mapping LOD scores, QTL effects, and epistasis analysis")
+ ),
+ fluidRow(
+ column(6, div(class = "card", div(class = "card-header", "CIM Manhattan Plot (LOD Scores)"), div(class = "card-body", plotlyOutput("lod_plot_2d", height = "500px")))),
+ column(6, div(class = "card",
+ div(class = "card-header", "Chromosome Visualization with Flanking Markers"),
+ div(class = "card-body",
+ uiOutput("chromosome_viz"),
+ div(class = "simulation-controls",
+ actionButton("simulate_btn", "Simulate Discovery", class = "simulation-btn"),
+ actionButton("reset_btn", "Reset", class = "simulation-btn")
+ )
+ )
+ ))
+ ),
+ fluidRow(
+ column(4, div(class = "card", div(class = "card-header", "Model Performance"), div(class = "card-body", plotlyOutput("performance_plot")))),
+ column(4, div(class = "card", div(class = "card-header", "Train: Predicted vs Observed"), div(class = "card-body", plotlyOutput("regression_plot_train", height = "300px")))),
+ column(4, div(class = "card", div(class = "card-header", "Validation: Predicted vs Observed"), div(class = "card-body", plotlyOutput("regression_plot_test", height = "300px"))))
+ ),
+ fluidRow(
+ column(12, div(class = "card",
+ div(class = "card-header", "QTL Effects — Training Set (Additive + Dominance PVE with Flanking Markers)"),
+ div(class = "card-body", DTOutput("qtl_effects_table_train"), tags$br(), downloadButton("download_train_results", "Download"))
+ ))
+ ),
+ fluidRow(
+ column(12, div(class = "card",
+ div(class = "card-header", "Epistasis Analysis"),
+ div(class = "card-body",
+ DTOutput("epistasis_table"),
+ plotlyOutput("epistasis_heatmap", height = "400px")
+ )
+ ))
+ )
+ ),
+
+ # ---- Interpretation tab (same as before) ----
tabPanel("Interpretation", icon = icon("lightbulb"),
- div(class = "main-header",
- h2(tags$i(class = "fas fa-lightbulb", style = "margin-right:8px;"), "Results Interpretation"),
- p("CIM QTL interpretation: PVE_marker vs PVE_CIM, flanking regions, dominance class")
- ),
- fluidRow(column(12, div(class = "card", div(class = "card-header", "Analysis Summary"), div(class = "card-body", uiOutput("analysis_summary"))))),
- fluidRow(
- column(6, div(class = "card", div(class = "card-header", "QTL Significance"), div(class = "card-body", uiOutput("qtl_interpretation")))),
- column(6, div(class = "card", div(class = "card-header", "Effect Sizes (Add + Dom)"), div(class = "card-body", uiOutput("effect_interpretation"))))
- ),
- fluidRow(column(12, div(class = "card", div(class = "card-header", "Epistasis"), div(class = "card-body", uiOutput("epistasis_interpretation"))))),
- fluidRow(column(12, div(class = "card", div(class = "card-header", "Recommendations"), div(class = "card-body", uiOutput("recommendations")))))
+ div(class = "main-header",
+ h2(tags$i(class = "fas fa-lightbulb", style = "margin-right:8px;"), "Results Interpretation"),
+ p("Comprehensive interpretation of CIM results")
+ ),
+ fluidRow(column(12, div(class = "card", div(class = "card-header", "Analysis Summary"), div(class = "card-body", uiOutput("analysis_summary"))))),
+ fluidRow(
+ column(6, div(class = "card", div(class = "card-header", "QTL Significance"), div(class = "card-body", uiOutput("qtl_interpretation")))),
+ column(6, div(class = "card", div(class = "card-header", "Effect Sizes (Additive + Dominance)"), div(class = "card-body", uiOutput("effect_interpretation"))))
+ ),
+ fluidRow(column(12, div(class = "card", div(class = "card-header", "Epistasis"), div(class = "card-body", uiOutput("epistasis_interpretation"))))),
+ fluidRow(column(12, div(class = "card", div(class = "card-header", "Recommendations"), div(class = "card-body", uiOutput("recommendations")))))
),
-
- # ---- ABOUT ----
+
+ # ---- About tab (updated) ----
tabPanel("About", icon = icon("info-circle"),
- div(class = "main-header",
- h2(tags$i(class = "fas fa-info-circle", style = "margin-right:8px;"), "About QTL-Mapper CIM v3")
- ),
- fluidRow(
- column(8, offset = 2,
- div(class = "card",
- div(class = "card-body",
- h4(style = "color:#58a6ff;font-family:'IBM Plex Mono';margin-bottom:12px;", "What Changed in v3"),
- div(class = "cim-box",
- tags$pre(style = "background:transparent;border:none;margin:0;color:#7ee787;font-size:11px;",
- "FIX 1 — PVE now reports two values:\n",
- " PVE_Marker_% = R² from lm(y ~ a + d) [marker alone]\n",
- " PVE_CIM_% = R² from lm(y ~ marker + cofactors) [full CIM model]\n",
- " → PVE_CIM is always ≥ PVE_Marker; often much higher\n\n",
- "FIX 2 — Flanking markers fixed:\n",
- " OLD: used colnames(X_train) after NZV removal → flanking lookup FAILED\n",
- " NEW: uses all_markers table (full set before NZV removal)\n",
- " Position-based fallback if marker not found by name\n\n",
- "METHOD — Composite Interval Mapping (Zeng 1993, PNAS):\n",
- " For each marker: fit lm(Y ~ focal_marker + K_cofactors)\n",
- " Cofactors selected by RF importance, excluding nearby markers\n",
- " LOD = -log10(p-value of focal marker term)\n",
- " This controls background genetic variance → higher power & PVE")
- ),
- h4(style = "color:#58a6ff;font-family:'IBM Plex Mono';margin:16px 0 8px;", "Thresholds"),
- tags$ul(style = "color:#8b949e;line-height:2;",
- tags$li("LOD > 2: Suggestive QTL | LOD > 3: Significant | LOD > 5: Highly significant"),
- tags$li("PVE_CIM > 20%: Major QTL | 10-20%: Moderate | <10%: Minor"),
- tags$li("|d/a| > 1: Overdominance | ~1: Complete dominance | <0.5: Additive"),
- tags$li("Fst > 0.2: Strong differentiation | Tajima's D < -2: Selective sweep")
- )
- )
- )
- )
- )
+ div(class = "main-header",
+ h2(tags$i(class = "fas fa-info-circle", style = "margin-right:8px;"), "About QTL-Mapper AI - CIM Edition"),
+ p("Composite Interval Mapping with Multi-Model AI Assistant")
+ ),
+ fluidRow(
+ column(8, offset = 2,
+ div(class = "card",
+ div(class = "card-body",
+ h4(style = "color:#58a6ff; font-family:'IBM Plex Mono'; margin-bottom:12px;", "Composite Interval Mapping (CIM)"),
+ div(class = "pve-formula-box",
+ tags$pre(style = "background:transparent; border:none; margin:0; color:#7ee787; font-size:11px;",
+ "CIM Advantages over Simple Interval Mapping:\n",
+ " - Controls for genetic background using cofactors\n",
+ " - Reduces residual variance → higher LOD scores\n",
+ " - Better separation of linked QTLs\n",
+ " - More accurate effect estimates\n",
+ " - Automatically identifies flanking markers\n\n",
+ "PVE = R²_full × 100 from lm(y ~ a + d)\n",
+ "Additive_Effect = β_a\n",
+ "Dominance_Effect = β_d")
+ ),
+ h4(style = "color:#58a6ff; font-family:'IBM Plex Mono'; margin:12px 0;", "Methodology"),
+ tags$ul(style = "color:#8b949e; line-height:2;",
+ tags$li("Composite Interval Mapping via qtl package"),
+ tags$li("Stepwise cofactor selection (forward/backward)"),
+ tags$li("Haley-Knott regression for efficient computation"),
+ tags$li("Permutation-based significance thresholds"),
+ tags$li("Additive (β_a) and dominance (β_d) effects via lm(y ~ a + d)"),
+ tags$li("PVE = R²_full × 100 — full additive + dominance model"),
+ tags$li("Dominance ratio = |β_d / β_a|: >1 overdominance, ~1 complete dominance, <0.5 additive"),
+ tags$li("Epistasis analysis: pairwise QTL x marker interactions")
+ ),
+ h4(style = "color:#58a6ff; font-family:'IBM Plex Mono'; margin:12px 0;", "Interpretation Thresholds"),
+ tags$ul(style = "color:#8b949e; line-height:2;",
+ tags$li("LOD > 3: Suggestive QTL | LOD > 5: Significant QTL (with CIM)"),
+ tags$li("PVE > 10%: Major-effect QTL (full additive+dominance model)"),
+ tags$li("|Dominance/Additive| > 1: Overdominance"),
+ tags$li("Fst > 0.2: Strong population differentiation"),
+ tags$li("Tajima's D < -2: Potential selective sweep")
+ )
+ )
+ )
+ )
+ )
)
),
-
+
# ============================================================
- # FLOATING CHAT
+ # FLOATING CHAT PANEL (same as before)
# ============================================================
tags$div(id = "chat-panel",
- tags$div(id = "chat-window",
- tags$div(id = "chat-header",
- tags$div(class = "chat-header-top",
- tags$div(class = "chat-title",
- tags$div(class = "chat-avatar", "AI"),
- tags$div(
- tags$h4("QTL-CIM AI Assistant"),
- tags$p(id = "model_status_text",
- if (token_exists) "AI mode ready" else "Rule-based mode",
- class = if (token_exists) "ai-mode" else "")
- )
- ),
- tags$button(id = "chat-close-btn",
- onclick = "document.getElementById('chat-window').classList.remove('open');",
- tags$i(class = "fas fa-times"))
- ),
- tags$div(class = "chat-model-selector",
- tags$label(tags$i(class = "fas fa-robot"), " Model:"),
- tags$div(id = "model_status_dot", class = paste0("model-status-dot ", if (token_exists) "online" else "offline")),
- selectInput("selected_model", label = NULL, choices = model_choices, selected = default_model, width = "100%"),
- actionButton("test_model_btn", "Test", class = "test-model-btn")
- )
- ),
- tags$div(class = "quick-questions",
- tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q','What is PVE in CIM?',{priority:'event'});", "PVE / CIM"),
- tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q','Show top QTLs',{priority:'event'});", "Top QTLs"),
- tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q','Show flanking markers',{priority:'event'});", "Flanking"),
- tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q','Why is my R2 negative?',{priority:'event'});","Negative R²")
- ),
- tags$div(id = "chat_messages", uiOutput("chat_display")),
- tags$div(id = "chat-footer",
- tags$textarea(id = "chat_input", placeholder = "Ask about CIM results... (Enter to send)", rows = "2"),
- tags$div(class = "chat-actions",
- actionButton("send_chat", "Send", icon = icon("paper-plane"), class = "btn-primary"),
- actionButton("clear_chat", "Clear", icon = icon("trash-alt"), class = "btn-danger")
- )
- )
- ),
- tags$button(id = "chat-toggle-btn",
- onclick = "document.getElementById('chat-window').classList.toggle('open');",
- tags$i(class = "fas fa-robot"))
- )
+ tags$div(id = "chat-window",
+
+ tags$div(id = "chat-header",
+ tags$div(class = "chat-header-top",
+ tags$div(class = "chat-title",
+ tags$div(class = "chat-avatar", "AI"),
+ tags$div(
+ tags$h4("QTL Analysis AI Assistant"),
+ tags$p(id = "model_status_text",
+ if (token_exists) "AI mode ready" else "Rule-based mode",
+ class = if (token_exists) "ai-mode" else "rule-mode")
+ )
+ ),
+ tags$button(id = "chat-close-btn",
+ onclick = "document.getElementById('chat-window').classList.remove('open');",
+ tags$i(class = "fas fa-times"))
+ ),
+ tags$div(class = "chat-model-selector",
+ tags$label(tags$i(class = "fas fa-robot"), " Model:"),
+ tags$div(id = "model_status_dot", class = paste0("model-status-dot ", if (token_exists) "online" else "offline")),
+ selectInput("selected_model", label = NULL,
+ choices = model_choices,
+ selected = default_model,
+ width = "100%"),
+ actionButton("test_model_btn", "Test", class = "test-model-btn")
+ )
+ ),
+
+ tags$div(class = "quick-questions",
+ tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q','What is PVE?',{priority:'event'});", "PVE meaning"),
+ tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q','What are my top QTLs?',{priority:'event'});", "Top QTLs"),
+ tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q','Why is my R2 negative?',{priority:'event'});","Negative R2"),
+ tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q','What should I do next?',{priority:'event'});","Next steps")
+ ),
+
+ tags$div(id = "chat_messages", uiOutput("chat_display")),
+
+ tags$div(id = "chat-footer",
+ tags$div(class = "chat-file-row",
+ tags$label(
+ id = "chat_file_upload_btn",
+ tags$i(class = "fas fa-paperclip"),
+ " Attach file",
+ fileInput("chat_file_upload", label = NULL,
+ accept = c(".csv", ".txt", ".tsv", ".xlsx", ".pdf"),
+ buttonLabel = "",
+ placeholder = "",
+ width = "0px")
+ ),
+ tags$span(id = "chat_file_preview"),
+ tags$button(id = "chat_file_clear_btn",
+ onclick = "document.getElementById('chat_file_preview').style.display='none'; document.getElementById('chat_file_preview').innerHTML=''; Shiny.setInputValue('clear_chat_file', Math.random());",
+ tags$i(class = "fas fa-times"))
+ ),
+ tags$textarea(id = "chat_input",
+ placeholder = "Ask about your results... (Enter to send)",
+ rows = "2"),
+ tags$div(class = "chat-actions",
+ actionButton("send_chat", "Send", icon = icon("paper-plane"), class = "btn-primary"),
+ actionButton("clear_chat", "Clear", icon = icon("trash-alt"), class = "btn-danger")
+ )
+ )
+ ),
+ tags$button(id = "chat-toggle-btn",
+ onclick = "document.getElementById('chat-window').classList.toggle('open');",
+ tags$i(class = "fas fa-robot"))
+ ),
+
+ tags$script(HTML("
+ $(document).on('change', '#chat_file_upload', function() {
+ var file = this.files[0];
+ if (file) {
+ var preview = document.getElementById('chat_file_preview');
+ preview.innerHTML = ' ' + file.name + ' (' + (file.size/1024).toFixed(1) + ' KB)';
+ preview.style.display = 'inline';
+ }
+ });
+ "))
)
# ============================================================
@@ -886,729 +1095,1103 @@ ui <- fluidPage(
# ============================================================
server <- function(input, output, session) {
-
+
values <- reactiveValues(
- genotype_data = NULL,
- phenotype_data = NULL,
- test_genotype_data = NULL,
- predicted_test_phenotype_data = NULL,
- all_markers = NULL,
- chromosome_info = NULL,
- position_info = NULL,
- cim_all = NULL, # Full CIM scan results
- qtl_effects_train = NULL, # Significant QTLs with flanking
- performance_metrics = NULL,
- train_predictions = NULL,
- test_predictions = NULL,
- epistasis_all = NULL,
- epistasis_sig = NULL,
- pop_data = NULL,
- selection_metrics = NULL,
- model_fit = NULL,
- chat_messages = list(),
- is_typing = FALSE,
- lod_threshold = 2,
- current_model = default_model
+ genotype_data = NULL,
+ phenotype_data = NULL,
+ test_genotype_data = NULL,
+ predicted_test_phenotype_data = NULL,
+ chromosome_info = NULL,
+ position_info = NULL,
+ all_markers = NULL,
+ lod_scores_train = NULL,
+ cim_results = NULL,
+ model_fit = NULL,
+ phenotype_values = NULL,
+ qtl_effects_train = NULL,
+ performance_metrics = NULL,
+ train_predictions = NULL,
+ test_predictions = NULL,
+ epistasis_all = NULL,
+ epistasis_sig = NULL,
+ pop_data = NULL,
+ selection_metrics = NULL,
+ has_test_data = FALSE,
+ chat_messages = list(),
+ is_typing = FALSE,
+ lod_threshold = 3,
+ current_model = default_model,
+ pending_file_content = NULL,
+ pending_file_name = NULL
)
-
- # ---- Model selector ----
+
+ # ---- Selected model (same as before) ----
observe({
req(input$selected_model)
values$current_model <- input$selected_model
+ model_label <- names(model_choices)[model_choices == input$selected_model]
+ shinyjs::html("model_status_text",
+ if (token_exists) paste("AI:", gsub(".*\\[(.*)\\]", "\\1", model_label), "- ready")
+ else "Rule-based mode (no token)")
})
-
+
+ # ---- Test model (same as before) ----
observeEvent(input$test_model_btn, {
req(input$selected_model)
- add_message("assistant", paste0("⏳ Testing model: **", input$selected_model, "**..."))
+ add_message("assistant", paste0("\u23f3 Testing model: **", gsub(".*/", "", input$selected_model), "**..."))
result <- test_api_connection(input$selected_model)
if (result$success) {
- add_message("assistant", paste0("✅ **", input$selected_model, "** is working!"))
- shinyjs::runjs("document.getElementById('model_status_dot').className='model-status-dot online';")
+ add_message("assistant", paste0("\u2705 **", gsub(".*/", "", input$selected_model), "** is working!"))
+ shinyjs::runjs("document.getElementById('model_status_dot').className = 'model-status-dot online';")
} else {
- add_message("assistant", paste0("❌ Failed: ", result$error))
- shinyjs::runjs("document.getElementById('model_status_dot').className='model-status-dot offline';")
+ add_message("assistant", paste0("\u274c Test failed: ", result$error))
+ shinyjs::runjs("document.getElementById('model_status_dot').className = 'model-status-dot offline';")
}
})
-
- # ---- Chat helpers ----
+
+ # ---- Chat helpers (same as before) ----
add_message <- function(role, content, model_used = NULL) {
+ timestamp <- format(Sys.time(), "%H:%M")
values$chat_messages <- c(values$chat_messages,
- list(list(role = role, content = content,
- time = format(Sys.time(), "%H:%M"), model = model_used)))
+ list(list(role = role, content = content,
+ time = timestamp, model = model_used)))
if (length(values$chat_messages) > 100)
values$chat_messages <- tail(values$chat_messages, 100)
session$sendCustomMessage("scrollChatBottom", list())
}
-
- process_message <- function(user_text) {
- if (nchar(trimws(user_text)) == 0) return()
- add_message("user", user_text)
+
+ process_message <- function(user_text, file_content = NULL, file_name = NULL) {
+ if (nchar(trimws(user_text)) == 0 && is.null(file_content)) return()
+
+ full_message <- user_text
+ if (!is.null(file_content) && nchar(trimws(file_content)) > 0) {
+ full_message <- paste0(user_text,
+ if (nchar(trimws(user_text)) > 0) "\n\n" else "",
+ "--- Attached file: ", file_name, " ---\n",
+ substr(file_content, 1, 3000),
+ if (nchar(file_content) > 3000) "\n[... truncated ...]" else "")
+ }
+
+ add_message("user", full_message)
values$is_typing <- TRUE
+
model_id <- isolate(values$current_model)
- response <- generate_ai_response(user_text, values, model_id = model_id)
+ response <- generate_ai_response(full_message, values, model_id = model_id)
+
values$is_typing <- FALSE
- add_message("assistant", response, model_used = if (token_exists) gsub(".*/", "", model_id) else NULL)
+ model_short <- gsub(".*/([^:]+):.*", "\\1", model_id)
+ add_message("assistant", response, model_used = if (token_exists) model_short else NULL)
+
+ values$pending_file_content <- NULL
+ values$pending_file_name <- NULL
}
-
+
+ observeEvent(input$chat_file_upload, {
+ req(input$chat_file_upload)
+ file_path <- input$chat_file_upload$datapath
+ file_name <- input$chat_file_upload$name
+ ext <- tolower(tools::file_ext(file_name))
+
+ tryCatch({
+ file_content <- if (ext %in% c("csv", "txt", "tsv")) {
+ paste(readLines(file_path, n = 200), collapse = "\n")
+ } else {
+ paste0("[Binary file: ", file_name, " - ", round(file.info(file_path)$size / 1024, 1), " KB]")
+ }
+ values$pending_file_content <- file_content
+ values$pending_file_name <- file_name
+ }, error = function(e) {
+ showNotification(paste("Could not read file:", e$message), type = "warning")
+ })
+ })
+
+ observeEvent(input$clear_chat_file, {
+ values$pending_file_content <- NULL
+ values$pending_file_name <- NULL
+ })
+
observeEvent(input$send_chat, {
- user_text <- trimws(input$chat_input)
- if (nchar(user_text) == 0) return()
+ user_text <- trimws(input$chat_input)
+ file_content <- isolate(values$pending_file_content)
+ file_name <- isolate(values$pending_file_name)
+ if (nchar(user_text) == 0 && is.null(file_content)) return()
updateTextAreaInput(session, "chat_input", value = "")
- process_message(user_text)
+ shinyjs::runjs("
+ document.getElementById('chat_file_preview').style.display = 'none';
+ document.getElementById('chat_file_preview').innerHTML = '';
+ ")
+ process_message(user_text, file_content, file_name)
})
-
- observeEvent(input$quick_q, { req(input$quick_q); process_message(input$quick_q) })
+
+ observeEvent(input$quick_q, { req(input$quick_q); process_message(input$quick_q) })
+
observeEvent(input$clear_chat, {
values$chat_messages <- list()
add_message("assistant", "Chat cleared. How can I help?")
})
-
+
observe({
if (length(values$chat_messages) == 0) {
+ mode_msg <- if (token_exists) {
+ paste0("I have access to **", length(available_models), " AI models** via Groq.\n",
+ "Select a model above and click **Test** to verify it's working!")
+ } else {
+ "I'm using rule-based responses. Set **GROQ_API_KEY** in Space secrets to enable AI models."
+ }
add_message("assistant", paste0(
- "👋 Vanakam! TerraByte-AI (CIM v3)\n\n",
- "**What's new:**\n",
- "• CIM (Composite Interval Mapping) — higher PVE, better power\n",
- "• Flanking markers fixed — uses full marker table\n",
- "• Two PVE values: PVE_marker (add+dom alone) & PVE_CIM (full model)\n\n",
- "Upload data and run CIM analysis to get started!\n",
- "Contact: ashmithamganesan@gmail.com, P.sinha@cgiar.org"
+ "\U0001f44b Vanakam! I'm TerraByte - AI powered companion using Composite Interval Mapping.\n\n",
+ mode_msg,
+ "\n\n**CIM now controls for background QTLs for better detection.**\n\n",
+ "**I can help you with:**\n",
+ "\u2022 **What is PVE?** - Full additive + dominance variance explained\n",
+ "\u2022 **Show top QTLs** - Including flanking markers and dominance effects\n",
+ "\u2022 **Model performance** - Why is my R² negative?\n",
+ "\u2022 **Next steps** - Recommendations\n",
+ "\u2022 **Upload files** - Use the paperclip to attach CSV/TXT data\n\n",
+ "Try: **'What is PVE?'**"
))
}
})
-
+
output$chat_display <- renderUI({
- msgs <- values$chat_messages
- if (length(msgs) == 0) return(NULL)
- elems <- lapply(msgs, function(msg) {
+ messages <- values$chat_messages
+ if (length(messages) == 0) return(NULL)
+
+ elems <- lapply(messages, function(msg) {
content_html <- HTML(gsub("\n", "
", htmltools::htmlEscape(msg$content)))
- div(class = paste("chat-msg", msg$role),
- div(class = "chat-bubble", content_html),
- div(class = "chat-meta",
- span(msg$time),
- if (!is.null(msg$model) && msg$role == "assistant")
- span(class = "model-tag", paste0("[", msg$model, "]"))
- )
+ meta_content <- tagList(
+ span(msg$time),
+ if (!is.null(msg$model) && msg$role == "assistant")
+ span(class = "model-tag", paste0("[", msg$model, "]"))
)
+ div(class = paste("chat-msg", msg$role),
+ div(class = "chat-bubble", content_html),
+ div(class = "chat-meta", meta_content))
})
+
if (values$is_typing) {
- elems <- c(elems, list(div(class = "chat-msg assistant",
- div(class = "typing-indicator",
- div(class = "typing-dot"), div(class = "typing-dot"), div(class = "typing-dot")))))
+ elems <- c(elems, list(
+ div(class = "chat-msg assistant",
+ div(class = "typing-indicator",
+ div(class = "typing-dot"), div(class = "typing-dot"), div(class = "typing-dot")))))
}
do.call(tagList, elems)
})
-
+
# ============================================================
- # DATA LOADING
+ # DATA LOADING (same as before)
# ============================================================
-
+
observeEvent(input$genotype_file, {
req(input$genotype_file)
tryCatch({
- all_data <- readLines(input$genotype_file$datapath)
- if (length(all_data) < 4) { showNotification("Need ≥4 rows", type = "error"); return() }
+ all_data <- readLines(input$genotype_file$datapath)
+ if (length(all_data) < 4) { showNotification("Genotype file must have at least 4 rows", type = "error"); return() }
+
header <- strsplit(all_data[1], ",")[[1]]
chromosome_row <- strsplit(all_data[2], ",")[[1]]
position_row <- strsplit(all_data[3], ",")[[1]]
- genotype_data <- read.csv(text = paste(all_data[-(1:3)], collapse = "\n"), header = FALSE)
+
+ genotype_data <- read.csv(text = all_data[-(1:3)], header = FALSE)
colnames(genotype_data) <- header
rownames(genotype_data) <- genotype_data[, 1]
- genotype_data <- genotype_data[, -1]
+ genotype_data <- genotype_data[, -1]
+
for (col in colnames(genotype_data))
genotype_data[[col]] <- as.numeric(as.character(genotype_data[[col]]))
- values$genotype_data <- genotype_data
- values$chromosome_info <- chromosome_row[-1]
- values$position_info <- suppressWarnings(as.numeric(position_row[-1]))
+
values$all_markers <- data.frame(
Marker = colnames(genotype_data),
Chromosome = chromosome_row[-1],
- Position = suppressWarnings(as.numeric(position_row[-1])),
+ Position = as.numeric(position_row[-1]),
stringsAsFactors = FALSE)
- showNotification(paste("Loaded", ncol(genotype_data), "markers,", nrow(genotype_data), "samples"), type = "message")
- add_message("assistant", paste0("✅ Genotype: **", ncol(genotype_data), " markers**, **", nrow(genotype_data), " samples**"))
- }, error = function(e) showNotification(paste("Geno error:", e$message), type = "error"))
+
+ values$genotype_data <- genotype_data
+ values$chromosome_info <- chromosome_row[-1]
+ values$position_info <- as.numeric(position_row[-1])
+
+ showNotification("Genotype data loaded", type = "message")
+ add_message("assistant", paste0("\u2705 Loaded genotype data: **", ncol(genotype_data), " markers**, **", nrow(genotype_data), " samples**"))
+ }, error = function(e) showNotification(paste("Error:", e$message), type = "error"))
})
-
+
observeEvent(input$phenotype_file, {
req(input$phenotype_file)
tryCatch({
- pd <- read.csv(input$phenotype_file$datapath)
- rownames(pd) <- pd[, 1]; pd <- pd[, -1]
- for (col in colnames(pd)) pd[[col]] <- as.numeric(as.character(pd[[col]]))
- values$phenotype_data <- pd
- updateSelectInput(session, "phenotype_column", choices = colnames(pd), selected = colnames(pd)[1])
- showNotification(paste("Loaded", ncol(pd), "traits"), type = "message")
- add_message("assistant", paste0("✅ Phenotype: **", ncol(pd), " traits**, **", nrow(pd), " samples**"))
- }, error = function(e) showNotification(paste("Pheno error:", e$message), type = "error"))
+ phenotype_data <- read.csv(input$phenotype_file$datapath)
+ rownames(phenotype_data) <- phenotype_data[, 1]
+ phenotype_data <- phenotype_data[, -1]
+
+ for (col in colnames(phenotype_data))
+ phenotype_data[[col]] <- as.numeric(as.character(phenotype_data[[col]]))
+
+ values$phenotype_data <- phenotype_data
+ updateSelectInput(session, "phenotype_column",
+ choices = colnames(phenotype_data),
+ selected = colnames(phenotype_data)[1])
+
+ showNotification("Phenotype data loaded", type = "message")
+ add_message("assistant", paste0("\u2705 Loaded phenotype data: **", ncol(phenotype_data), " traits**, **", nrow(phenotype_data), " samples**"))
+ }, error = function(e) showNotification(paste("Error:", e$message), type = "error"))
})
-
+
observeEvent(input$pop_file, {
req(input$pop_file)
tryCatch({
- pd <- read.csv(input$pop_file$datapath)
- if (!all(c("id", "population") %in% colnames(pd))) {
- showNotification("Need 'id' and 'population' columns", type = "error"); return()
+ pop_data <- read.csv(input$pop_file$datapath)
+ if (!all(c("id", "population") %in% colnames(pop_data))) {
+ showNotification("Population file must have '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"))
+ values$pop_data <- pop_data
+ showNotification("Population data loaded", type = "message")
+ add_message("assistant", paste0("\u2705 Loaded population data (", nrow(pop_data), " samples)"))
+ }, error = function(e) showNotification(paste("Error:", e$message), type = "error"))
})
-
+
observeEvent(input$test_genotype_file, {
req(input$test_genotype_file)
tryCatch({
- all_data <- readLines(input$test_genotype_file$datapath)
- header <- strsplit(all_data[1], ",")[[1]]
- gd <- read.csv(text = paste(all_data[-(1:3)], collapse = "\n"), header = FALSE)
- colnames(gd) <- header; rownames(gd) <- gd[, 1]; gd <- gd[, -1]
- for (col in colnames(gd)) gd[[col]] <- as.numeric(as.character(gd[[col]]))
- values$test_genotype_data <- gd
- showNotification("Test genotype loaded", type = "message")
- }, error = function(e) showNotification(paste("Test geno error:", e$message), type = "error"))
+ all_data <- readLines(input$test_genotype_file$datapath)
+ header <- strsplit(all_data[1], ",")[[1]]
+
+ genotype_data <- read.csv(text = all_data[-(1:3)], header = FALSE)
+ colnames(genotype_data) <- header
+ rownames(genotype_data) <- genotype_data[, 1]
+ genotype_data <- genotype_data[, -1]
+
+ for (col in colnames(genotype_data))
+ genotype_data[[col]] <- as.numeric(as.character(genotype_data[[col]]))
+
+ values$test_genotype_data <- genotype_data
+ values$has_test_data <- TRUE
+ showNotification("Test genotype data loaded", type = "message")
+ }, error = function(e) showNotification(paste("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$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 analysis...", type = "message")
+ showNotification("Starting Composite Interval Mapping analysis...", type = "message")
values$lod_threshold <- input$lod_threshold
-
+
tryCatch({
common_samples <- intersect(rownames(values$genotype_data), rownames(values$phenotype_data))
if (length(common_samples) == 0) { showNotification("No common samples", type = "error"); return() }
-
+
X <- values$genotype_data[common_samples, , drop = FALSE]
y <- as.numeric(values$phenotype_data[common_samples, input$phenotype_column])
-
+
+ # Split data for validation
set.seed(123)
train_index <- createDataPartition(y, p = 1 - input$test_size, list = FALSE)
- X_train <- X[train_index, , drop = FALSE]; X_val <- X[-train_index, , drop = FALSE]
- y_train <- y[train_index]; y_val <- y[-train_index]
-
- # ---- Run CIM scan ----
- withProgress(message = "Running CIM genome scan...", value = 0.1, {
- cim_results <- run_cim(
- genotype_matrix = X_train,
- phenotype_vector = y_train,
- marker_info = values$all_markers, # FULL marker table — key fix
- n_cofactors = input$n_cofactors,
- window_size = input$window_size,
- lod_threshold = input$lod_threshold
+ X_train <- X[train_index, , drop = FALSE]
+ X_val <- X[-train_index, , drop = FALSE]
+ y_train <- y[train_index]
+ y_val <- y[-train_index]
+
+ # Prepare data for qtl package
+ cross <- prepare_qtl_cross(X_train, y_train, values$all_markers)
+
+ # Perform CIM
+ withProgress(message = "Running Composite Interval Mapping...", value = 0.3, {
+ cim_results <- perform_cim(
+ cross = cross,
+ phenotype_name = "phenotype",
+ n_permutations = 100,
+ n_markers_cofactor = input$n_cofactors,
+ window_size = input$window_size,
+ lod_threshold_perm = input$perm_threshold
)
- incProgress(0.7)
+ incProgress(0.5)
})
-
- values$cim_all <- cim_results
-
- # ---- Extract significant QTLs and add FIXED flanking ----
- if (!"Message" %in% colnames(cim_results)) {
- sig_qtls <- cim_results[cim_results$LOD >= input$lod_threshold, ]
-
- if (nrow(sig_qtls) > 0) {
- # Add flanking using FULL all_markers table
- sig_qtls <- add_flanking_markers(sig_qtls, values$all_markers)
- values$qtl_effects_train <- sig_qtls[order(-sig_qtls$LOD), ]
+
+ values$cim_results <- cim_results
+
+ # Extract scanone results
+ scanone_df <- as.data.frame(cim_results$scanone)
+ scanone_df$Marker <- rownames(scanone_df)
+
+ # Convert to our format
+ lod_scores <- data.frame(
+ Marker = scanone_df$Marker,
+ LOD = scanone_df$phenotype,
+ Chromosome = scanone_df$chr,
+ Position = scanone_df$pos * 1e6, # Convert cM back to bp approx
+ stringsAsFactors = FALSE
+ )
+
+ # Filter by threshold
+ threshold_used <- if (input$perm_threshold) cim_results$threshold else input$lod_threshold
+ lod_sig <- lod_scores[lod_scores$LOD > threshold_used, , drop = FALSE]
+
+ if (nrow(lod_sig) > 0) {
+ values$lod_scores_train <- lod_sig
+
+ # Extract QTL effects with flanking markers
+ qtl_fx <- extract_qtl_effects_cim(cim_results, cim_results$peaks, X_train, y_train)
+
+ if (!is.null(qtl_fx)) {
+ values$qtl_effects_train <- qtl_fx
} else {
- values$qtl_effects_train <- data.frame(Message = paste("No QTLs above LOD", input$lod_threshold))
+ values$qtl_effects_train <- data.frame(Message = "Could not calculate QTL effects")
}
} else {
- values$qtl_effects_train <- cim_results
+ values$lod_scores_train <- data.frame(Message = paste("No QTLs above LOD", round(threshold_used, 2)))
+ values$qtl_effects_train <- data.frame(Message = paste("No QTLs above LOD", round(threshold_used, 2)))
}
-
- # ---- RF model for prediction (separate from CIM mapping) ----
- nzv <- nearZeroVar(X_train)
- X_tr_rf <- if (length(nzv) > 0) X_train[, -nzv, drop = FALSE] else X_train
- X_v_rf <- X_val[, colnames(X_tr_rf), drop = FALSE]
-
- model <- tryCatch(
- train(x = X_tr_rf, y = y_train, method = "rf",
- trControl = trainControl(method = "cv", number = 5),
- importance = TRUE, tuneLength = 3),
- error = function(e) {
- train(x = X_tr_rf, y = y_train, method = "lm",
- trControl = trainControl(method = "cv", number = 5))
- })
- values$model_fit <- model
-
- y_train_pred <- predict(model, X_tr_rf)
- y_val_pred <- predict(model, X_v_rf)
- train_r2 <- 1 - sum((y_train - y_train_pred)^2) / sum((y_train - mean(y_train))^2)
- val_r2 <- 1 - sum((y_val - y_val_pred)^2) / sum((y_val - mean(y_val))^2)
-
- values$performance_metrics <- data.frame(
- Metric = c("R² (Train)", "R (Train)", "R² (Validation)", "R (Validation)"),
- Value = c(train_r2, cor(y_train, y_train_pred), val_r2, cor(y_val, y_val_pred)),
- stringsAsFactors = FALSE)
-
- values$train_predictions <- data.frame(Observed = y_train, Predicted = y_train_pred)
- values$test_predictions <- data.frame(Observed = y_val, Predicted = y_val_pred)
-
- # ---- Epistasis ----
- if (!is.null(values$qtl_effects_train) && !"Message" %in% colnames(values$qtl_effects_train)) {
- sig_markers <- values$qtl_effects_train$Marker
- all_markers_v <- colnames(X_train)
- epi_list <- list()
-
- withProgress(message = "Calculating epistasis...", value = 0, {
- for (m1 in sig_markers) {
- for (m2 in all_markers_v) {
- if (m1 == m2) next
- tryCatch({
- d <- data.frame(y = y_train, m1 = X_train[, m1], m2 = X_train[, m2])
- d <- na.omit(d)
- if (nrow(d) < 10) next
- fit <- lm(y ~ m1 * m2, data = d)
- ct <- summary(fit)$coefficients
- if ("m1:m2" %in% rownames(ct)) {
- epi_list[[length(epi_list) + 1]] <- data.frame(
- QTL1 = m1, QTL2 = m2,
- Interaction_p = ct["m1:m2", "Pr(>|t|)"],
- Effect_Size = coef(fit)["m1:m2"],
- stringsAsFactors = FALSE)
- }
- }, error = function(e) {})
+
+ # Train a linear model for predictions using significant QTLs
+ if (nrow(lod_sig) > 0) {
+ sig_markers <- lod_sig$Marker[lod_sig$Marker %in% colnames(X_train)]
+
+ if (length(sig_markers) > 0) {
+ # Create model matrix with additive and dominance terms
+ model_data_train <- data.frame(y = y_train)
+ for (m in sig_markers) {
+ model_data_train[[paste0(m, "_a")]] <- X_train[, m] # additive
+ model_data_train[[paste0(m, "_d")]] <- as.numeric(X_train[, m] == 1) # dominance
+ }
+
+ # Fit model
+ form <- as.formula(paste("y ~", paste(names(model_data_train)[-1], collapse = " + ")))
+ lm_model <- lm(form, data = model_data_train)
+ values$model_fit <- lm_model
+
+ # Predictions
+ y_train_pred <- predict(lm_model, model_data_train)
+
+ # Validation predictions
+ model_data_val <- data.frame(y = y_val)
+ for (m in sig_markers) {
+ if (m %in% colnames(X_val)) {
+ model_data_val[[paste0(m, "_a")]] <- X_val[, m]
+ model_data_val[[paste0(m, "_d")]] <- as.numeric(X_val[, m] == 1)
}
}
- })
-
- if (length(epi_list) > 0) {
- ea <- do.call(rbind, epi_list)
- values$epistasis_all <- ea
- values$epistasis_sig <- ea[ea$Interaction_p < 0.05, ]
+ # Fill missing markers with 0
+ for (nm in names(model_data_train)[-1]) {
+ if (!nm %in% names(model_data_val)) {
+ model_data_val[[nm]] <- 0
+ }
+ }
+ y_val_pred <- predict(lm_model, model_data_val)
+
+ train_r2 <- 1 - sum((y_train - y_train_pred)^2) / sum((y_train - mean(y_train))^2)
+ val_r2 <- 1 - sum((y_val - y_val_pred)^2) / sum((y_val - mean(y_val))^2)
+
+ values$performance_metrics <- data.frame(
+ Metric = c("R² (Train)", "R (Train)", "R² (Validation)", "R (Validation)"),
+ Value = c(train_r2, cor(y_train, y_train_pred), val_r2, cor(y_val, y_val_pred)),
+ stringsAsFactors = FALSE
+ )
+
+ values$train_predictions <- data.frame(Observed = y_train, Predicted = y_train_pred)
+ values$test_predictions <- data.frame(Observed = y_val, Predicted = y_val_pred)
+ }
+ } else {
+ # No significant QTLs, use simple mean model
+ y_train_pred <- rep(mean(y_train), length(y_train))
+ y_val_pred <- rep(mean(y_val), length(y_val))
+
+ values$performance_metrics <- data.frame(
+ Metric = c("R² (Train)", "R (Train)", "R² (Validation)", "R (Validation)"),
+ Value = c(0, 0, 0, 0),
+ stringsAsFactors = FALSE
+ )
+
+ values$train_predictions <- data.frame(Observed = y_train, Predicted = y_train_pred)
+ values$test_predictions <- data.frame(Observed = y_val, Predicted = y_val_pred)
+ }
+
+ # Epistasis analysis
+ if (nrow(lod_sig) > 0) {
+ sig_markers <- lod_sig$Marker[lod_sig$Marker %in% colnames(X_train)]
+
+ if (length(sig_markers) > 1) {
+ epistasis_list <- list()
+
+ withProgress(message = "Calculating epistasis...", value = 0, {
+ total <- length(sig_markers) * (length(sig_markers) - 1) / 2
+ count <- 0
+
+ for (i in 1:(length(sig_markers) - 1)) {
+ for (j in (i + 1):length(sig_markers)) {
+ count <- count + 1
+ incProgress(1/total)
+
+ m1 <- sig_markers[i]
+ m2 <- sig_markers[j]
+
+ tryCatch({
+ data_epi <- data.frame(
+ y = y_train,
+ a1 = X_train[, m1],
+ d1 = as.numeric(X_train[, m1] == 1),
+ a2 = X_train[, m2],
+ d2 = as.numeric(X_train[, m2] == 1)
+ )
+ data_epi <- na.omit(data_epi)
+
+ if (nrow(data_epi) < 10) next
+
+ # Test additive x additive interaction
+ fit <- lm(y ~ a1 + d1 + a2 + d2 + a1:a2, data = data_epi)
+ coef_summary <- summary(fit)$coefficients
+
+ if ("a1:a2" %in% rownames(coef_summary)) {
+ epistasis_list[[length(epistasis_list) + 1]] <- data.frame(
+ QTL1 = m1,
+ QTL2 = m2,
+ Interaction_p = coef_summary["a1:a2", "Pr(>|t|)"],
+ Effect_Size = coef(fit)["a1:a2"],
+ stringsAsFactors = FALSE
+ )
+ }
+ }, error = function(e) {})
+ }
+ }
+ })
+
+ if (length(epistasis_list) > 0) {
+ epistasis_all <- do.call(rbind, epistasis_list)
+ values$epistasis_all <- epistasis_all
+ values$epistasis_sig <- epistasis_all[epistasis_all$Interaction_p < 0.05, ]
+ } else {
+ values$epistasis_all <- data.frame(Message = "No epistatic interactions")
+ values$epistasis_sig <- data.frame(Message = "No epistatic interactions")
+ }
} else {
- values$epistasis_all <- data.frame(Message = "No epistatic interactions found")
- values$epistasis_sig <- data.frame(Message = "No epistatic interactions found")
+ values$epistasis_all <- data.frame(Message = "Need at least 2 QTLs for epistasis")
+ values$epistasis_sig <- data.Frame(Message = "Need at least 2 QTLs for epistasis")
}
+ } else {
+ values$epistasis_all <- data.frame(Message = "No QTLs for epistasis analysis")
+ values$epistasis_sig <- data.frame(Message = "No QTLs for epistasis analysis")
}
-
- n_qtl <- if (!is.null(values$qtl_effects_train) && !"Message" %in% colnames(values$qtl_effects_train)) nrow(values$qtl_effects_train) else 0
- max_pve_cim <- if (n_qtl > 0) round(max(values$qtl_effects_train$PVE_CIM_Percent), 1) else 0
-
+
showNotification("CIM analysis completed!", type = "message")
+
+ n_qtl <- if (!is.null(values$qtl_effects_train) && !"Message" %in% colnames(values$qtl_effects_train)) nrow(values$qtl_effects_train) else 0
+ total_pve <- if (n_qtl > 0) sum(values$qtl_effects_train$PVE_Percent, na.rm = TRUE) else 0
+
add_message("assistant", paste0(
- "✅ **CIM analysis complete!**\n\n",
- "• Found **", n_qtl, " QTLs** above LOD ", input$lod_threshold, "\n",
- "• Top QTL PVE_CIM: **", max_pve_cim, "%** (full CIM model)\n",
- "• Validation R²: **", round(val_r2, 3), "**\n",
- "• Flanking markers: ✅ fixed (uses full marker table)\n\n",
- "Ask me about PVE, flanking markers, or top QTLs!"
+ "\u2705 **Composite Interval Mapping complete!**\n\n",
+ "\u2022 Found **", n_qtl, " QTLs** above LOD ", round(threshold_used, 2), "\n",
+ "\u2022 Total PVE: **", round(total_pve, 1), "%** (additive + dominance)\n",
+ "\u2022 Validation R²: **", round(values$performance_metrics$Value[3], 3), "**\n\n",
+ "**QTLs detected:**\n"
))
+
+ if (n_qtl > 0) {
+ top3 <- head(values$qtl_effects_train[order(-values$qtl_effects_train$LOD), ], 3)
+ for (i in 1:nrow(top3)) {
+ row <- top3[i, ]
+ add_message("assistant", paste0(
+ " ", i, ". **", row$Marker, "** (Chr ", row$Chromosome, "):\n",
+ " LOD = ", round(row$LOD, 2), ", PVE = ", round(row$PVE_Percent, 1), "%\n",
+ " Flanking: ", row$Low_Flank, " - ", row$High_Flank
+ ))
+ }
+ }
+
updateTabsetPanel(session, "nav", selected = "Results")
-
+
}, error = function(e) {
- showNotification(paste("CIM Error:", e$message), type = "error")
- cat("CIM ERROR:", e$message, "\n")
+ showNotification(paste("Error:", e$message), type = "error")
+ add_message("assistant", paste0("\u274c Analysis failed: ", e$message))
})
})
-
- # ============================================================
- # PREDICT TEST PHENOTYPES
- # ============================================================
-
- observeEvent(input$predict_test_phenotype, {
- req(values$model_fit, values$test_genotype_data)
- tryCatch({
- common_m <- intersect(colnames(values$test_genotype_data), colnames(values$genotype_data))
- if (length(common_m) == 0) { showNotification("No common markers", type = "error"); return() }
- X_test <- values$test_genotype_data[, common_m, drop = FALSE]
- preds <- predict(values$model_fit, newdata = X_test)
- values$predicted_test_phenotype_data <- data.frame(
- id = rownames(X_test), Predicted_Phenotype = as.numeric(preds), stringsAsFactors = FALSE)
- showNotification("Predictions done!", type = "message")
- }, error = function(e) showNotification(paste("Predict error:", e$message), type = "error"))
- })
-
+
# ============================================================
- # DOMESTICATION
+ # DOMESTICATION ANALYSIS (same as before)
# ============================================================
-
- calculate_selection_metrics <- function(geno_mat, pop_data, marker_info) {
+
+ calculate_selection_metrics <- function(genotype_matrix, pop_data, marker_info) {
metrics_list <- list()
- for (marker in colnames(geno_mat)) {
- geno <- geno_mat[, marker]
- pop <- pop_data$population[match(rownames(geno_mat), pop_data$id)]
+
+ for (marker in colnames(genotype_matrix)) {
+ geno <- genotype_matrix[, marker]
+ pop <- pop_data$population[match(rownames(genotype_matrix), pop_data$id)]
valid_idx <- !is.na(geno) & !is.na(pop)
geno <- geno[valid_idx]; pop <- pop[valid_idx]
+
if (length(unique(pop)) < 2) next
- gd <- geno[pop == "Domesticated"]; gw <- geno[pop == "Wild"]
- if (length(gd) < 3 || length(gw) < 3) next
- fd <- mean(gd, na.rm = TRUE) / 2; fw <- mean(gw, na.rm = TRUE) / 2
- pa <- (fd + fw) / 2
- fst <- if (pa > 0 && pa < 1) { f <- (fd - fw)^2 / (pa * (1 - pa)); f / (1 + f) } else 0
- pi_d <- 2 * fd * (1 - fd); pi_w <- 2 * fw * (1 - fw)
- td_d <- tryCatch((pi_d - 1/length(gd)) / sqrt(var(gd)/length(gd)), error = function(e) NA)
- td_w <- tryCatch((pi_w - 1/length(gw)) / sqrt(var(gw)/length(gw)), error = function(e) NA)
- mr <- marker_info[marker_info$Marker == marker, ]
+ geno_dom <- geno[pop == "Domesticated"]
+ geno_wild <- geno[pop == "Wild"]
+ if (length(geno_dom) < 3 || length(geno_wild) < 3) next
+
+ freq_dom <- mean(geno_dom, na.rm = TRUE) / 2
+ freq_wild <- mean(geno_wild, na.rm = TRUE) / 2
+ p_avg <- (freq_dom + freq_wild) / 2
+
+ fst <- if (p_avg > 0 && p_avg < 1) {
+ f <- (freq_dom - freq_wild)^2 / (p_avg * (1 - p_avg))
+ f / (1 + f)
+ } else 0
+
+ pi_dom <- 2 * freq_dom * (1 - freq_dom)
+ pi_wild <- 2 * freq_wild * (1 - freq_wild)
+ n_dom <- length(geno_dom)
+ n_wild <- length(geno_wild)
+
+ tajima_d_dom <- tryCatch((pi_dom - 1/n_dom) / sqrt(var(geno_dom) /n_dom), error = function(e) NA)
+ tajima_d_wild <- tryCatch((pi_wild - 1/n_wild) / sqrt(var(geno_wild)/n_wild), error = function(e) NA)
+
+ marker_row <- marker_info[marker_info$Marker == marker, ]
metrics_list[[marker]] <- data.frame(
- Marker = marker,
- Chromosome = ifelse(nrow(mr) > 0, mr$Chromosome[1], NA),
- Position = ifelse(nrow(mr) > 0, mr$Position[1], NA),
- Fst = fst, Pi_Dom = pi_d, Pi_Wild = pi_w,
- Tajima_D_Dom = td_d, Tajima_D_Wild = td_w,
+ Marker = marker,
+ Chromosome = ifelse(nrow(marker_row) > 0, marker_row$Chromosome[1], NA),
+ Position = ifelse(nrow(marker_row) > 0, marker_row$Position[1], NA),
+ Fst = fst, Pi_Dom = pi_dom, Pi_Wild = pi_wild,
+ Tajima_D_Dom = tajima_d_dom, Tajima_D_Wild = tajima_d_wild,
stringsAsFactors = FALSE)
}
+
if (length(metrics_list) == 0) return(NULL)
do.call(rbind, metrics_list)
}
-
+
observeEvent(input$run_domestication, {
req(values$genotype_data, values$pop_data, values$all_markers)
tryCatch({
- cs <- intersect(rownames(values$genotype_data), values$pop_data$id)
- if (length(cs) == 0) { showNotification("No common samples", type = "error"); return() }
- X <- values$genotype_data[cs, , drop = FALSE]
- ps <- values$pop_data[values$pop_data$id %in% cs, ]
- sel <- calculate_selection_metrics(X, ps, values$all_markers)
- if (is.null(sel)) { showNotification("No selection metrics", type = "error"); return() }
- sel$Significant <- sel$Fst > input$fst_threshold | sel$Tajima_D_Dom < input$tajima_threshold
- values$selection_metrics <- sel
- showNotification(paste("Domestication done:", sum(sel$Significant, na.rm = TRUE), "signatures"), type = "message")
- }, error = function(e) showNotification(paste("Dom error:", e$message), type = "error"))
+ common_samples <- intersect(rownames(values$genotype_data), values$pop_data$id)
+ if (length(common_samples) == 0) { showNotification("No common samples", type = "error"); return() }
+
+ X <- values$genotype_data[common_samples, , drop = FALSE]
+ pop_subset <- values$pop_data[values$pop_data$id %in% common_samples, ]
+ sel_metrics <- calculate_selection_metrics(X, pop_subset, values$all_markers)
+
+ if (is.null(sel_metrics)) { showNotification("Could not calculate selection metrics", type = "error"); return() }
+
+ sel_metrics$Significant <-
+ sel_metrics$Fst > input$fst_threshold |
+ sel_metrics$Tajima_D_Dom < input$tajima_threshold |
+ sel_metrics$Tajima_D_Wild < input$tajima_threshold
+
+ values$selection_metrics <- sel_metrics
+ showNotification("Domestication analysis completed!", type = "message")
+ n_sig <- sum(sel_metrics$Significant, na.rm = TRUE)
+ add_message("assistant", paste0("\u2705 Domestication analysis complete!\n\n\u2022 Found **", n_sig, " markers** with selection signatures"))
+ }, error = function(e) showNotification(paste("Error:", e$message), type = "error"))
})
-
+
# ============================================================
- # MANHATTAN HELPER
+ # PREDICT TEST PHENOTYPES
# ============================================================
-
+
+ observeEvent(input$predict_test_phenotype, {
+ req(values$model_fit, values$test_genotype_data)
+
+ tryCatch({
+ # Get significant markers
+ if (is.null(values$lod_scores_train) || "Message" %in% colnames(values$lod_scores_train)) {
+ showNotification("No QTL model available for prediction", type = "error")
+ return()
+ }
+
+ sig_markers <- values$lod_scores_train$Marker
+ sig_markers <- sig_markers[sig_markers %in% colnames(values$test_genotype_data)]
+
+ if (length(sig_markers) == 0) {
+ showNotification("No common markers between training and test data", type = "error")
+ return()
+ }
+
+ # Create model matrix for test data
+ model_data_test <- data.frame(row.names = rownames(values$test_genotype_data))
+ for (m in sig_markers) {
+ if (m %in% colnames(values$test_genotype_data)) {
+ model_data_test[[paste0(m, "_a")]] <- values$test_genotype_data[, m]
+ model_data_test[[paste0(m, "_d")]] <- as.numeric(values$test_genotype_data[, m] == 1)
+ }
+ }
+
+ # Fill missing with 0
+ expected_vars <- names(coef(values$model_fit))[-1] # Remove intercept
+ for (v in expected_vars) {
+ if (!v %in% colnames(model_data_test)) {
+ model_data_test[[v]] <- 0
+ }
+ }
+
+ # Ensure columns are in same order as model
+ model_data_test <- model_data_test[, expected_vars, drop = FALSE]
+
+ # Predict
+ predictions <- predict(values$model_fit, newdata = model_data_test)
+
+ values$predicted_test_phenotype_data <- data.frame(
+ id = rownames(values$test_genotype_data),
+ Predicted_Phenotype = as.numeric(predictions),
+ stringsAsFactors = FALSE
+ )
+
+ showNotification("Predictions completed!", type = "message")
+
+ }, error = function(e) {
+ showNotification(paste("Error:", e$message), type = "error")
+ })
+ })
+
+ # ============================================================
+ # MANHATTAN PLOT HELPER
+ # ============================================================
+
create_manhattan <- function(data, y_col, title, threshold, y_label = y_col) {
if (is.null(data) || nrow(data) == 0 || "Message" %in% colnames(data))
- return(plot_ly() %>% layout(title = "No data — run analysis first",
- plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e")))
- pd <- data[!is.na(data[[y_col]]) & !is.na(data$Chromosome), ]
- if (nrow(pd) == 0) return(plot_ly() %>% layout(title = "No valid data",
- plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e")))
- chroms <- unique(pd$Chromosome)
+ return(plot_ly() %>% layout(title = "No data available",
+ plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e")))
+
+ plot_data <- data[!is.na(data[[y_col]]), ]
+ if (nrow(plot_data) == 0)
+ return(plot_ly() %>% layout(title = "No valid data",
+ plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e")))
+
+ chroms <- unique(plot_data$Chromosome)
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)
+ chr_data <- plot_data[plot_data$Chromosome == chroms[i], ]
+ if (nrow(chr_data) > 0) {
+ chr_data$ChromIndex <- i
+ chr_data$PosScaled <- chr_data$Position / max(chr_data$Position, na.rm = TRUE) + (i - 1)
+ chrom_pos <- rbind(chrom_pos, chr_data)
}
}
+
p <- plot_ly() %>%
add_trace(data = chrom_pos, x = ~PosScaled, y = as.formula(paste0("~", y_col)),
- type = "scatter", mode = "markers", color = ~factor(Chromosome),
- colors = viridis(length(chroms)), marker = list(size = 6, opacity = 0.7),
- text = ~paste("Marker:", Marker, "
Chr:", Chromosome, "
Pos:", Position,
- "
", y_label, ":", round(get(y_col), 3)),
- hoverinfo = "text", showlegend = FALSE)
+ type = "scatter", mode = "markers", color = ~factor(Chromosome),
+ colors = viridis(length(chroms)), marker = list(size = 6, opacity = 0.7),
+ text = ~paste("Marker:", Marker, "
Chr:", Chromosome, "
Pos:", round(Position),
+ "
", 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 = "red", dash = "dash", width = 1))
+ line = list(color = "red", dash = "dash", width = 1), name = "Threshold")
+
p %>% layout(title = title,
- xaxis = list(title = "Chromosome",
- ticktext = chroms,
- tickvals = tapply(chrom_pos$PosScaled, chrom_pos$Chromosome, median, na.rm = TRUE),
- tickangle = 45),
- yaxis = list(title = y_label),
- plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e"))
+ xaxis = list(title = "Chromosome",
+ ticktext = chroms,
+ tickvals = tapply(chrom_pos$PosScaled, chrom_pos$Chromosome, median, na.rm = TRUE),
+ tickangle = 45),
+ yaxis = list(title = y_label),
+ plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e"))
}
-
+
# ============================================================
# 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")
+ if (!is.null(values$cim_results)) {
+ scanone_df <- as.data.frame(values$cim_results$scanone)
+ plot_data <- data.frame(
+ Marker = rownames(scanone_df),
+ LOD = scanone_df$phenotype,
+ Chromosome = scanone_df$chr,
+ Position = scanone_df$pos * 1e6,
+ stringsAsFactors = FALSE
+ )
+
+ threshold_used <- if (input$perm_threshold) values$cim_results$threshold else input$lod_threshold
+ create_manhattan(plot_data, "LOD", "CIM Manhattan Plot", threshold_used, "LOD Score")
+ } else if (!is.null(values$importance_scores)) {
+ create_manhattan(values$importance_scores, "LOD", "CIM Manhattan Plot", input$lod_threshold, "LOD Score")
+ } else {
+ plot_ly() %>% layout(title = "No data available")
+ }
})
-
- output$fst_plot <- renderPlotly({ req(values$selection_metrics); create_manhattan(values$selection_metrics, "Fst", "Fst Plot", input$fst_threshold, "Fst") })
-
+
+ output$fst_plot <- renderPlotly({
+ req(values$selection_metrics)
+ create_manhattan(values$selection_metrics, "Fst", "Fst Manhattan 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 = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e")))
- d <- values$selection_metrics
- chroms <- unique(d$Chromosome)
- cp <- data.frame()
+ return(plot_ly() %>% layout(title = "No data available", plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e")))
+
+ data <- values$selection_metrics
+ chroms <- unique(data$Chromosome)
+ chrom_pos <- 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) }
+ chr_data <- data[data$Chromosome == chroms[i], ]
+ if (nrow(chr_data) > 0) {
+ chr_data$ChromIndex <- i
+ chr_data$PosScaled <- chr_data$Position / max(chr_data$Position, na.rm = TRUE) + (i - 1)
+ chrom_pos <- rbind(chrom_pos, chr_data)
+ }
}
+
plot_ly() %>%
- add_trace(data = cp, x = ~PosScaled, y = ~Tajima_D_Dom, type = "scatter", mode = "markers", name = "Domesticated", marker = list(size = 5, color = "#58a6ff", opacity = .7)) %>%
- add_trace(data = cp, x = ~PosScaled, y = ~Tajima_D_Wild, type = "scatter", mode = "markers", name = "Wild", marker = list(size = 5, color = "#f97316", opacity = .7)) %>%
- add_segments(x = min(cp$PosScaled, na.rm = TRUE), xend = max(cp$PosScaled, na.rm = TRUE), y = input$tajima_threshold, yend = input$tajima_threshold, line = list(color = "red", dash = "dash", width = 1)) %>%
- layout(title = "Tajima's D", xaxis = list(title = "Chromosome", ticktext = chroms, tickvals = tapply(cp$PosScaled, cp$Chromosome, median, na.rm = TRUE), tickangle = 45), yaxis = list(title = "Tajima's D"),
- plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e"))
+ add_trace(data = chrom_pos, x = ~PosScaled, y = ~Tajima_D_Dom, type = "scatter", mode = "markers",
+ name = "Domesticated", marker = list(size = 5, color = "#58a6ff", opacity = 0.7),
+ text = ~paste("Marker:", Marker, "
D(Dom):", round(Tajima_D_Dom, 3)), hoverinfo = "text") %>%
+ add_trace(data = chrom_pos, x = ~PosScaled, y = ~Tajima_D_Wild, type = "scatter", mode = "markers",
+ name = "Wild", marker = list(size = 5, color = "#f97316", opacity = 0.7),
+ text = ~paste("Marker:", Marker, "
D(Wild):", round(Tajima_D_Wild, 3)), hoverinfo = "text") %>%
+ add_segments(x = min(chrom_pos$PosScaled, na.rm = TRUE), xend = max(chrom_pos$PosScaled, na.rm = TRUE),
+ y = input$tajima_threshold, yend = input$tajima_threshold,
+ line = list(color = "red", dash = "dash", width = 1)) %>%
+ layout(title = "Tajima's D Manhattan Plot",
+ xaxis = list(title = "Chromosome",
+ ticktext = chroms,
+ tickvals = tapply(chrom_pos$PosScaled, chrom_pos$Chromosome, median, na.rm = TRUE),
+ tickangle = 45),
+ yaxis = list(title = "Tajima's D"),
+ plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e"))
})
-
+
output$performance_plot <- renderPlotly({
req(values$performance_metrics)
plot_ly(data = values$performance_metrics, x = ~Metric, y = ~Value, type = "bar",
- marker = list(color = c("#58a6ff","#58a6ff","#3fb950","#3fb950")),
- text = ~round(Value, 3), textposition = "outside") %>%
- layout(title = "Model Performance (RF for Prediction)", yaxis = list(title = "Value", range = c(0, 1.1)),
- plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e"))
+ marker = list(color = c("#58a6ff", "#58a6ff", "#3fb950", "#3fb950")),
+ text = ~round(Value, 3), textposition = "outside") %>%
+ layout(title = "Model Performance",
+ yaxis = list(title = "Value", range = c(min(0, min(values$performance_metrics$Value) - 0.1),
+ max(1.1, max(values$performance_metrics$Value) + 0.1))),
+ plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e"))
})
-
+
output$regression_plot_train <- renderPlotly({
req(values$train_predictions)
plot_ly(data = values$train_predictions, x = ~Observed, y = ~Predicted,
- type = "scatter", mode = "markers", marker = list(size = 6, color = "#58a6ff", opacity = .7)) %>%
+ type = "scatter", mode = "markers", marker = list(size = 6, color = "#58a6ff", opacity = 0.7)) %>%
add_trace(x = range(values$train_predictions$Observed), y = range(values$train_predictions$Observed),
- type = "scatter", mode = "lines", line = list(color = "#f85149", dash = "dash")) %>%
+ type = "scatter", mode = "lines", line = list(color = "#f85149", dash = "dash")) %>%
layout(title = "Training Set", xaxis = list(title = "Observed"), yaxis = list(title = "Predicted"),
- plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e"))
+ plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e"))
})
-
+
output$regression_plot_test <- renderPlotly({
req(values$test_predictions)
plot_ly(data = values$test_predictions, x = ~Observed, y = ~Predicted,
- type = "scatter", mode = "markers", marker = list(size = 6, color = "#3fb950", opacity = .7)) %>%
+ type = "scatter", mode = "markers", marker = list(size = 6, color = "#3fb950", opacity = 0.7)) %>%
add_trace(x = range(values$test_predictions$Observed), y = range(values$test_predictions$Observed),
- type = "scatter", mode = "lines", line = list(color = "#f85149", dash = "dash")) %>%
+ type = "scatter", mode = "lines", line = list(color = "#f85149", dash = "dash")) %>%
layout(title = "Validation Set", xaxis = list(title = "Observed"), yaxis = list(title = "Predicted"),
- plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e"))
+ plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e"))
})
-
+
output$epistasis_heatmap <- renderPlotly({
req(values$epistasis_all)
if ("Message" %in% colnames(values$epistasis_all))
return(plot_ly() %>% layout(title = values$epistasis_all$Message[1],
- plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e")))
- 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))
+ plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e")))
+
+ qtls <- unique(values$epistasis_all$QTL1)
+ markers <- unique(values$epistasis_all$QTL2)
+ p_mat <- matrix(NA, nrow = length(qtls), ncol = length(markers),
+ dimnames = list(qtls, markers))
for (i in 1:nrow(values$epistasis_all))
- pm[values$epistasis_all$QTL1[i], values$epistasis_all$QTL2[i]] <- -log10(values$epistasis_all$Interaction_p[i])
- plot_ly(x = colnames(pm), y = rownames(pm), z = pm, type = "heatmap", colorscale = "Viridis") %>%
- layout(title = "Epistatic Interactions (-log10 p)", xaxis = list(title = "Marker", tickangle = 45), yaxis = list(title = "QTL"),
- plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e"))
+ p_mat[values$epistasis_all$QTL1[i], values$epistasis_all$QTL2[i]] <-
+ -log10(values$epistasis_all$Interaction_p[i])
+
+ plot_ly(x = colnames(p_mat), y = rownames(p_mat), z = p_mat,
+ type = "heatmap", colorscale = "Viridis",
+ hovertemplate = "QTL: %{y}
Marker: %{x}
-log10(p): %{z:.2f}") %>%
+ layout(title = "Epistatic Interactions",
+ xaxis = list(title = "Marker", tickangle = 45), yaxis = list(title = "QTL"),
+ plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e"))
})
-
+
# ============================================================
# 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")))
-
+
+ # Show all effect columns including flanking markers
display_cols <- intersect(
- c("Marker", "Chromosome", "Position", "LOD", "P_Value",
- "PVE_Marker_Percent", "PVE_CIM_Percent",
+ c("Marker", "Chromosome", "Position_bp", "LOD",
"Additive_Effect", "SE_Additive", "CI_Lower", "CI_Upper",
"Dominance_Effect", "SE_Dominance", "Dominance_Ratio", "Dominance_Class",
- "N_Cofactors", "N_Samples", "N_Heterozygotes",
+ "PVE_Percent", "N_Samples", "N_Heterozygotes",
"Low_Flank", "High_Flank"),
colnames(values$qtl_effects_train))
-
- datatable(values$qtl_effects_train[, display_cols],
- options = list(pageLength = 10, scrollX = TRUE), rownames = FALSE,
- caption = "PVE_Marker = R²(lm(y~a+d))×100 | PVE_CIM = R²(lm(y~marker+cofactors))×100") %>%
- formatRound(intersect(c("LOD","PVE_Marker_Percent","PVE_CIM_Percent",
- "Additive_Effect","SE_Additive","CI_Lower","CI_Upper",
- "Dominance_Effect","SE_Dominance","Dominance_Ratio"), display_cols), 3) %>%
- formatSignif(intersect(c("P_Value"), display_cols), digits = 3)
+
+ df <- values$qtl_effects_train[order(-values$qtl_effects_train$LOD), display_cols]
+ datatable(df,
+ options = list(pageLength = 10, scrollX = TRUE),
+ rownames = FALSE,
+ caption = "PVE = R² × 100 from lm(phenotype ~ additive_code + dominance_code)") %>%
+ formatRound(intersect(c("LOD", "Additive_Effect", "SE_Additive", "CI_Lower", "CI_Upper",
+ "Dominance_Effect", "SE_Dominance", "Dominance_Ratio", "PVE_Percent"), colnames(df)), 3) %>%
+ formatRound("Position_bp", 0)
})
-
+
output$epistasis_table <- renderDT({
req(values$epistasis_sig)
if ("Message" %in% colnames(values$epistasis_sig))
return(datatable(data.frame(Status = values$epistasis_sig$Message[1]), options = list(dom = "t")))
datatable(values$epistasis_sig[order(values$epistasis_sig$Interaction_p), ],
- options = list(pageLength = 10, scrollX = TRUE), rownames = FALSE) %>%
- formatSignif(c("Interaction_p", "Effect_Size"), digits = 4)
+ options = list(pageLength = 10, scrollX = TRUE), rownames = FALSE) %>%
+ formatSignif(columns = c("Interaction_p", "Effect_Size"), digits = 4)
})
-
+
output$selection_table <- renderDT({
req(values$selection_metrics)
if ("Message" %in% colnames(values$selection_metrics))
return(datatable(data.frame(Status = values$selection_metrics$Message[1]), options = list(dom = "t")))
+
df <- values$selection_metrics
if (!is.null(values$qtl_effects_train) && !"Message" %in% colnames(values$qtl_effects_train))
df$QTL_Overlap <- df$Marker %in% values$qtl_effects_train$Marker
- dc <- intersect(c("Marker","Chromosome","Fst","Pi_Dom","Pi_Wild","Tajima_D_Dom","Significant","QTL_Overlap"), colnames(df))
- datatable(df[order(-df$Fst), dc], options = list(pageLength = 10, scrollX = TRUE), rownames = FALSE) %>%
- formatRound(c("Fst","Pi_Dom","Pi_Wild","Tajima_D_Dom"), 3)
+
+ display_cols <- intersect(
+ c("Marker", "Chromosome", "Fst", "Pi_Dom", "Pi_Wild", "Tajima_D_Dom", "Significant", "QTL_Overlap"),
+ colnames(df))
+ datatable(df[order(-df$Fst), display_cols], options = list(pageLength = 10, scrollX = TRUE), rownames = FALSE) %>%
+ formatRound(c("Fst", "Pi_Dom", "Pi_Wild", "Tajima_D_Dom"), 3)
})
-
+
# ============================================================
- # CHROMOSOME VISUALIZATION (uses FULL all_markers — flanking fixed)
+ # CHROMOSOME VISUALIZATION (updated to show flanking markers)
# ============================================================
-
+
output$chromosome_viz <- renderUI({
- req(values$qtl_effects_train, values$all_markers)
- if ("Message" %in% colnames(values$qtl_effects_train))
- return(div(class = "alert alert-info", values$qtl_effects_train$Message[1]))
-
- chromosomes <- unique(values$qtl_effects_train$Chromosome)
+ req(values$lod_scores_train, values$all_markers)
+ if ("Message" %in% colnames(values$lod_scores_train))
+ return(div(class = "alert alert-info", values$lod_scores_train$Message[1]))
+
+ chromosomes <- unique(values$lod_scores_train$Chromosome)
tagList(lapply(chromosomes, function(chr) {
- # Use FULL all_markers (not post-NZV subset)
chr_markers <- values$all_markers[values$all_markers$Chromosome == chr, ]
chr_markers <- chr_markers[order(chr_markers$Position), ]
- chr_qtls <- values$qtl_effects_train[values$qtl_effects_train$Chromosome == chr, ]
-
+ chr_qtls <- values$lod_scores_train[values$lod_scores_train$Chromosome == chr, ]
+
+ # Get flanking markers from qtl_effects if available
+ flank_low <- c()
+ flank_high <- c()
+ if (!is.null(values$qtl_effects_train) && !"Message" %in% colnames(values$qtl_effects_train)) {
+ qtl_chr <- values$qtl_effects_train[values$qtl_effects_train$Chromosome == chr, ]
+ flank_low <- qtl_chr$Low_Flank
+ flank_high <- qtl_chr$High_Flank
+ }
+
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), ]
-
+ values$selection_metrics$Chromosome == chr & 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)]
-
+
div(class = "chromosome-container",
- div(class = "chromosome-title", paste("Chromosome", chr, " —", nrow(chr_markers), "markers,", nrow(chr_qtls), "QTLs")),
- div(class = "chromosome",
- lapply(1:nrow(chr_markers), function(i) {
- marker <- chr_markers[i, ]
- left <- if (range_pos > 0 && !is.na(range_pos))
- ((marker$Position - min_pos) / range_pos) * 100
- else (i / nrow(chr_markers)) * 100
-
- mclass <- "chromosome-marker"
- if (marker$Marker %in% chr_qtls$Marker) {
- mclass <- paste(mclass, "significant")
- } else if (!is.null(sel_markers) && nrow(sel_markers) > 0 && marker$Marker %in% sel_markers$Marker) {
- mclass <- paste(mclass, "selection")
- } else if (marker$Marker %in% flanking_markers) {
- mclass <- paste(mclass, "flanking")
- }
- div(class = mclass, style = paste0("left:", round(left, 2), "%;"),
- title = paste0(marker$Marker, " pos:", marker$Position))
- })
- ),
- div(class = "chromosome-legend",
- span(paste(format(min_pos, big.mark = ","), "bp")),
- span(paste(format(max_pos, big.mark = ","), "bp"))
- )
+ div(class = "chromosome-title", paste("Chromosome", chr)),
+ div(class = "chromosome",
+ lapply(1:nrow(chr_markers), function(i) {
+ marker <- chr_markers[i, ]
+ left <- if (range_pos > 0) ((marker$Position - min_pos) / range_pos) * 100
+ else (i / nrow(chr_markers)) * 100
+
+ marker_class <- "chromosome-marker"
+ if (marker$Marker %in% chr_qtls$Marker) {
+ marker_class <- paste(marker_class, "significant")
+ } else if (!is.null(sel_markers) && marker$Marker %in% sel_markers$Marker) {
+ marker_class <- paste(marker_class, "selection")
+ } else if (marker$Marker %in% c(flank_low, flank_high)) {
+ marker_class <- paste(marker_class, "flanking")
+ }
+ div(class = marker_class, style = paste0("left: ", left, "%;"),
+ title = marker$Marker)
+ })
+ ),
+ div(class = "chromosome-legend",
+ span(paste(format(min_pos, big.mark = ","), "bp")),
+ span(paste(format(max_pos, big.mark = ","), "bp")))
)
}))
})
-
+
observeEvent(input$simulate_btn, session$sendCustomMessage("simulateQTLDiscovery", list()))
observeEvent(input$reset_btn, session$sendCustomMessage("resetAnimation", list()))
-
+
# ============================================================
- # INTERPRETATION
+ # INTERPRETATION OUTPUTS
# ============================================================
-
+
output$analysis_summary <- renderUI({
- has_qtl <- !is.null(values$qtl_effects_train) && !"Message" %in% colnames(values$qtl_effects_train)
+ 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), 1) else NA
- div(
- tags$h5("CIM Analysis Summary"),
- tags$p(paste(n_qtl, "QTLs detected above LOD", input$lod_threshold, "| Validation R²:", val_r2)),
- if (!is.na(max_pve)) tags$p(paste("Max PVE_CIM:", max_pve, "% (marker + cofactors)")),
- tags$p(style = "color:#3fb950;font-size:12px;",
- tags$i(class = "fas fa-check-circle"), " CIM: flanking markers use full marker table ✓")
+ has_epi <- !is.null(values$epistasis_sig) && !"Message" %in% colnames(values$epistasis_sig) && nrow(values$epistasis_sig) > 0
+ has_sel <- !is.null(values$selection_metrics) && !"Message" %in% colnames(values$selection_metrics)
+
+ n_qtl <- if (has_qtl) nrow(values$qtl_effects_train) else 0
+ n_epi <- if (has_epi) nrow(values$epistasis_sig) else 0
+ n_sel <- if (has_sel) sum(values$selection_metrics$Significant, na.rm = TRUE) else 0
+ val_r2 <- if (has_perf) round(values$performance_metrics$Value[values$performance_metrics$Metric == "R² (Validation)"], 3) else "N/A"
+ total_pve <- if (has_qtl) round(sum(values$qtl_effects_train$PVE_Percent, na.rm = TRUE), 1) else 0
+
+ div(class = "interpretation-section",
+ tags$h5("Analysis Summary"),
+ tags$p(paste("Found", n_qtl, "QTLs above LOD",
+ if (!is.null(values$cim_results$threshold)) round(values$cim_results$threshold, 2) else input$lod_threshold,
+ "explaining", total_pve, "% of phenotypic variance.",
+ if (has_perf) paste0("Validation R² = ", val_r2, "."))),
+ tags$p(paste0("Detected ", n_epi, " epistatic interactions and ", n_sel, " selection signatures.")),
+ tags$p(style = "color:#3fb950; font-size:12px; margin-top:6px;",
+ tags$i(class = "fas fa-check-circle"),
+ " PVE estimated using full additive + dominance model: lm(phenotype ~ a + d)")
)
})
-
+
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.")))
- top <- values$qtl_effects_train[which.max(values$qtl_effects_train$LOD), ]
- div(
- tags$h5("Top QTL"),
- tags$p(paste(top$Marker, "— Chr", top$Chromosome, "— LOD =", round(top$LOD, 2))),
- 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), "%"))
- )
+ return(div(class = "interpretation-section", tags$h5("QTL Significance"), tags$p("No significant QTLs detected.")))
+
+ top_qtl <- values$qtl_effects_train[which.max(values$qtl_effects_train$LOD), ]
+ div(class = "interpretation-section",
+ tags$h5("QTL Significance"),
+ tags$p(paste("Top QTL:", top_qtl$Marker, "(Chr", top_qtl$Chromosome, ") with LOD =", round(top_qtl$LOD, 2),
+ "and flanking markers", top_qtl$Low_Flank, "-", top_qtl$High_Flank)))
})
-
+
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), ]
- dom <- if (!is.na(top$Dominance_Effect)) paste0("Dominance = ", round(top$Dominance_Effect, 3), " (", top$Dominance_Class, ")") else "No heterozygotes (additive model)"
- div(
- tags$h5("Largest PVE_CIM QTL"),
- tags$p(paste(top$Marker, "—", round(top$PVE_CIM_Percent, 1), "% PVE (CIM model)")),
- tags$p(paste("Additive effect =", round(top$Additive_Effect, 3))),
- tags$p(dom)
- )
+ return(div(class = "interpretation-section", tags$h5("Effect Sizes"), tags$p("No QTL effects to interpret.")))
+
+ top_pve <- values$qtl_effects_train[which.max(values$qtl_effects_train$PVE_Percent), ]
+
+ dom_text <- if (!is.na(top_pve$Dominance_Effect) && !is.na(top_pve$Dominance_Ratio)) {
+ paste0("Dominance effect = ", round(top_pve$Dominance_Effect, 3),
+ " (ratio d/a = ", round(top_pve$Dominance_Ratio, 2),
+ " → ", top_pve$Dominance_Class, ")")
+ } else {
+ "No heterozygotes detected — additive model only"
+ }
+
+ div(class = "interpretation-section",
+ tags$h5("Effect Sizes (Additive + Dominance)"),
+ tags$p(paste("Largest PVE:", top_pve$Marker, "explains",
+ round(top_pve$PVE_Percent, 1), "% of variance (full model)")),
+ tags$p(paste("Additive effect =", round(top_pve$Additive_Effect, 3))),
+ tags$p(dom_text),
+ tags$p(style = "color:#8b949e; font-size:11px;",
+ "PVE = R² from lm(y ~ additive_code + dominance_code) × 100"))
})
-
+
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.")))
- 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), ")")))
+ return(div(class = "interpretation-section", tags$h5("Epistasis"), tags$p("No significant epistatic interactions detected.")))
+
+ top_epi <- values$epistasis_sig[which.min(values$epistasis_sig$Interaction_p), ]
+ div(class = "interpretation-section",
+ tags$h5("Epistasis"),
+ tags$p(paste("Detected", nrow(values$epistasis_sig), "interactions. Strongest:",
+ top_epi$QTL1, "x", top_epi$QTL2, "(p =", format.pval(top_epi$Interaction_p), ")")))
})
-
+
output$recommendations <- renderUI({
has_qtl <- !is.null(values$qtl_effects_train) && !"Message" %in% colnames(values$qtl_effects_train)
+
recs <- if (has_qtl) {
- n_ovdom <- sum(values$qtl_effects_train$Dominance_Class == "Overdominance", na.rm = TRUE)
- r <- c("Validate top CIM QTLs in independent populations",
- "Use Low_Flank / High_Flank for fine-mapping intervals",
- "Annotate QTL regions for candidate genes")
- if (n_ovdom > 0) r <- c(r, paste(n_ovdom, "overdominant QTL(s) — consider heterosis breeding"))
- r <- c(r, "PVE_CIM includes cofactor variance — use PVE_Marker for single-QTL estimates")
- r
+ # Add dominance-specific recommendations
+ has_dom <- any(!is.na(values$qtl_effects_train$Dominance_Ratio))
+ dom_recs <- if (has_dom) {
+ ovdom_count <- sum(values$qtl_effects_train$Dominance_Class == "Overdominance", na.rm = TRUE)
+ if (ovdom_count > 0)
+ c(paste0("Overdominance detected at ", ovdom_count, " QTL(s) — consider heterosis in breeding"),
+ "For dominant QTLs, both additive and dominance variance matter for selection")
+ else
+ "Dominance effects estimated; consider dominance variance in heritability estimates"
+ } else NULL
+
+ c("Validate top QTLs in independent populations",
+ "Use flanking markers for fine-mapping and marker-assisted selection",
+ "Check gene annotations in QTL regions using genome browsers",
+ "Consider epistatic interactions for complex trait breeding",
+ dom_recs)
} else {
- c("Upload genotype + phenotype CSV files", "Click 'Run CIM Analysis'", "Try LOD threshold = 2 to start")
+ c("Upload data and run QTL analysis",
+ "Consider lowering LOD threshold",
+ "Check data quality and sample size")
}
- div(tags$h5("Recommendations"), tags$ul(lapply(recs, tags$li), style = "color:#8b949e;"))
+
+ div(class = "interpretation-section",
+ tags$h5("Recommendations"),
+ tags$ul(lapply(recs, tags$li), style = "color:#8b949e;"))
})
-
+
# ============================================================
- # DOWNLOADS
+ # DOWNLOAD HANDLERS
# ============================================================
-
+
output$download_train_results <- downloadHandler(
filename = function() paste0("cim_results_", Sys.Date(), ".xlsx"),
content = function(file) {
sheets <- list()
if (!is.null(values$qtl_effects_train) && !"Message" %in% colnames(values$qtl_effects_train))
- sheets[["CIM_QTL_Results"]] <- values$qtl_effects_train
- if (!is.null(values$cim_all) && !"Message" %in% colnames(values$cim_all))
- sheets[["CIM_Full_Scan"]] <- values$cim_all
+ sheets[["QTLs_CIM"]] <- values$qtl_effects_train
if (!is.null(values$performance_metrics))
sheets[["Performance"]] <- values$performance_metrics
- sheets[["Method_Documentation"]] <- data.frame(
- Item = c("Method","Cofactor selection","LOD formula","PVE_Marker","PVE_CIM",
- "Additive_Effect","Dominance_Effect","Flanking fix","Reference"),
+ if (!is.null(values$cim_results$peaks) && nrow(values$cim_results$peaks) > 0)
+ sheets[["CIM_Peaks"]] <- values$cim_results$peaks
+
+ # Add formula documentation sheet
+ sheets[["PVE_Formula"]] <- data.frame(
Description = c(
- "Composite Interval Mapping (CIM)",
- "Top K markers by RF importance, excluding ±window on same chromosome",
- "-log10(p-value of focal marker in lm(Y ~ marker + cofactors))",
- "R² from lm(Y ~ additive_code + dominance_code) × 100 — marker alone",
- "R² from full CIM model (marker + cofactors) × 100 — includes background",
- "beta_a from lm(Y ~ a + d) — allele substitution effect",
- "beta_d from lm(Y ~ a + d) — heterozygote deviation from midparent",
- "Uses full all_markers table (not post-NZV subset)",
- "Zeng (1993) PNAS; Falconer & Mackay (1996); Lynch & Walsh (1998)"),
- stringsAsFactors = FALSE)
+ "CIM Method",
+ "PVE Formula",
+ "Additive code (a)",
+ "Dominance code (d)",
+ "Full model",
+ "PVE (%)",
+ "Additive_Effect",
+ "Dominance_Effect",
+ "Dominance_Ratio",
+ "Reference"
+ ),
+ Value = c(
+ "Composite Interval Mapping with stepwise cofactor selection",
+ "Full additive + dominance model",
+ "0, 1, 2 (raw genotype value)",
+ "ifelse(genotype == 1, 1, 0) — heterozygote indicator",
+ "lm(phenotype ~ a + d)",
+ "R²_full × 100",
+ "beta_a — allele substitution effect",
+ "beta_d — deviation of heterozygote from midparent",
+ "|beta_d / beta_a| — 0=additive, ~1=dominance, >1=overdominance",
+ "Falconer & Mackay (1996); Lynch & Walsh (1998)"
+ ),
+ stringsAsFactors = FALSE
+ )
+
write_xlsx(sheets, file)
}
)
-
+
output$download_selection <- downloadHandler(
filename = function() paste0("selection_", Sys.Date(), ".xlsx"),
content = function(file) {
- if (!is.null(values$selection_metrics) && !"Message" %in% colnames(values$selection_metrics))
+ if (!is.null(values$selection_metrics) && !"Message" %in% colnames(values$selection_metrics)) {
write_xlsx(list(Selection = values$selection_metrics), file)
- else
- write_xlsx(list(Message = data.frame(msg = "No results yet")), file)
+ } else {
+ write_xlsx(list(Message = data.frame(msg = "No results")), file)
+ }
}
)
}
+# ============================================================
+# RUN APP
+# ============================================================
+
shinyApp(ui = ui, server = server)
\ No newline at end of file