diff --git "a/app.R" "b/app.R"
--- "a/app.R"
+++ "b/app.R"
@@ -2,10 +2,8 @@
# QTL-Mapper - Fixed API Connection
# ============================================================
-# Package installation for Hugging Face
options(repos = c(CRAN = "https://cloud.r-project.org"))
-# Install required packages if missing
required_packages <- c(
"shiny", "randomForest", "caret", "DT", "ggplot2", "plotly",
"writexl", "viridis", "reshape2", "dplyr", "httr", "jsonlite",
@@ -20,10 +18,9 @@ for (pkg in required_packages) {
}
# ============================================================
-# DEBUGGING - Check if token is loaded
+# TOKEN DEBUG
# ============================================================
-# Print token status to logs
token <- Sys.getenv("HF_API_TOKEN")
token_exists <- token != ""
token_length <- if(token_exists) nchar(token) else 0
@@ -31,173 +28,85 @@ token_length <- if(token_exists) nchar(token) else 0
print("=== HUGGING FACE 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)))
-}
+if(token_exists) print(paste("Token starts with:", substr(token, 1, 10)))
print("===================================")
# ============================================================
-# TRANSFORMER-BASED LLM SYSTEM - FIXED VERSION
+# API CONFIGURATION (single, clean definition)
# ============================================================
-# Configuration
HF_API_TOKEN <- token
+HF_API_URL <- "https://router.huggingface.co/v1/chat/completions"
+hf_model <- "HuggingFaceTB/SmolLM3-3B:hf-inference"
-# Try different models that are more reliable on the free inference API
-# Option 1: Mistral 7B Instruct (very reliable)
-# hf_model <- "mistralai/Mistral-7B-Instruct-v0.2"
-
-# Option 2: Microsoft Phi-2 (small but powerful)
-# hf_model <- "microsoft/phi-2"
-
-# Option 3: Google Gemma (good for instruction)
-# hf_model <- "google/gemma-2b-it"
-
-# Option 4: HuggingFaceH4/zephyr-7b-beta (very reliable)
-hf_model <- "HuggingFaceH4/zephyr-7b-beta"
-#"HuggingFaceH4/zephyr-7b-beta", # Most reliable
-# "mistralai/Mistral-7B-Instruct-v0.2", # Also good
-# "microsoft/phi-2", # Small but works
-# "google/flan-t5-large"
-
-#HF_API_URL <- paste0("https://api-inference.huggingface.co/models/", hf_model)
-#HF_API_URL <- paste0("https://router.huggingface.co/hf-inference/models/", hf_model)
-HF_API_URL <- paste0("https://router.huggingface.co/hf-inference/models/", hf_model)
-
-
+# ============================================================
+# TEST CONNECTION
+# ============================================================
-# Function to test API connection
test_api_connection <- function() {
- if (!token_exists) {
- return(list(success = FALSE, error = "No token found"))
- }
+ 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)),
- body = toJSON(list(inputs = "Hello"), auto_unbox = TRUE),
- encode = "json",
- timeout(10)
+ add_headers(
+ Authorization = paste("Bearer", HF_API_TOKEN),
+ "Content-Type" = "application/json"
+ ),
+ body = toJSON(list(
+ model = hf_model,
+ 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))
- } else if (status == 503) {
- return(list(success = FALSE, error = "Model loading", loading = TRUE))
- } else {
- error_content <- tryCatch({
- content(response, "text", encoding = "UTF-8")
- }, error = function(e) {
- paste("Status:", status)
- })
- return(list(success = FALSE, error = paste("Status:", status, "-", substr(error_content, 1, 100))))
- }
- }, error = function(e) {
- return(list(success = FALSE, error = e$message))
- })
+ 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))
}
-# Run test on startup
-api_test <- test_api_connection()
-print(paste("API Test result:", if(api_test$success) "SUCCESS" else paste("FAILED -", api_test$error)))
+api_test <- test_api_connection()
+use_hf_api <- token_exists && api_test$success
-# Update use_hf_api based on test
-if (token_exists && api_test$success) {
- use_hf_api <- TRUE
- print(paste("✅ API is working with model:", hf_model, "- AI mode enabled"))
+print(paste("API Test result:", if(api_test$success) "SUCCESS" else paste("FAILED -", api_test$error)))
+if (use_hf_api) {
+ print(paste("✅ API working with model:", hf_model, "- AI mode enabled"))
} else {
- use_hf_api <- FALSE
- print(paste("⚠️ API not available with model:", hf_model, "- using rule-based mode"))
- print("Will try alternative models if this fails...")
-
- # Try alternative models if first one fails
- alt_models <- c(
- "HuggingFaceH4/zephyr-7b-beta",
- "microsoft/phi-2",
- "google/gemma-2b-it",
- "google/flan-t5-large"
- )
- ############################
- for (alt_model in alt_models) {
- if (alt_model == hf_model) next
-
- print(paste("Trying alternative model:", alt_model))
- test_url <- paste0("https://router.huggingface.co/hf-inference/models/", alt_model)
- # url <- paste0("https://router.huggingface.co/hf-inference/models/", model)
- #url <- paste0("https://router.huggingface.co/hf-inference/models/", model)
- url <- paste0("https://router.huggingface.co/hf-inference/models/", alt_model)
-
- tryCatch({
- response <- POST(
- url = test_url,
- add_headers(Authorization = paste("Bearer", HF_API_TOKEN)),
- body = toJSON(list(inputs = "Hello"), auto_unbox = TRUE),
- encode = "json",
- timeout(5)
- )
-
- status <- status_code(response)
- if (status == 200) {
- hf_model <<- alt_model
- HF_API_URL <<- test_url
- use_hf_api <<- TRUE
- print(paste("✅ Found working model:", alt_model, "- AI mode enabled"))
- break
- }
- }, error = function(e) {})
- }
+ print("⚠️ API not available - using rule-based mode")
}
-# Function to query Hugging Face API
+# ============================================================
+# QUERY FUNCTION (single, OpenAI-compatible version)
+# ============================================================
+
query_hf_api <- function(prompt, max_length = 500, temperature = 0.7) {
- if (!token_exists) {
- return(list(success = FALSE, error = "HF_API_TOKEN not set"))
- }
-
- # Format prompt for better responses based on model type
- if (grepl("mistral|zephyr", hf_model)) {
- # Chat template for Mistral/Zephyr
- formatted_prompt <- paste0(
- "<|system|>\nYou are an expert bioinformatics assistant specializing in QTL analysis.\n\n",
- "<|user|>\n", prompt, "\n\n",
- "<|assistant|>\n"
- )
- } else if (grepl("phi", hf_model)) {
- # Simple prompt for Phi-2
- formatted_prompt <- paste0(
- "Instruct: You are a QTL analysis expert. Based on this data, answer the question.\n",
- "Data: ", prompt, "\n",
- "Output:"
- )
- } else {
- # Generic prompt
- formatted_prompt <- paste0(
- "You are an expert bioinformatics assistant specializing in QTL analysis.\n\n",
- "Based on this data:\n", prompt, "\n\n",
- "Answer the question accurately and concisely:"
- )
- }
+ 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),
+ Authorization = paste("Bearer", HF_API_TOKEN),
"Content-Type" = "application/json"
),
body = toJSON(list(
- inputs = formatted_prompt,
- parameters = list(
- max_new_tokens = max_length,
- temperature = temperature,
- do_sample = TRUE,
- top_p = 0.95,
- return_full_text = FALSE
- )
+ model = hf_model,
+ messages = list(
+ 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",
+ encode = "json",
timeout(60)
)
@@ -205,36 +114,15 @@ query_hf_api <- function(prompt, max_length = 500, temperature = 0.7) {
if (status == 200) {
result <- content(response, as = "parsed", encoding = "UTF-8")
-
- # Handle different response formats
- if (is.list(result)) {
- if (!is.null(result$generated_text)) {
- return(list(success = TRUE, text = result$generated_text))
- } else if (length(result) > 0 && !is.null(result[[1]]$generated_text)) {
- return(list(success = TRUE, text = result[[1]]$generated_text))
- } else {
- return(list(success = TRUE, text = as.character(result)))
- }
- } else {
- return(list(success = TRUE, text = as.character(result)))
- }
- } else if (status == 503) {
- return(list(success = FALSE, error = "Model is loading, please wait...", loading = TRUE))
- } else {
- error_content <- tryCatch({
- content(response, "text", encoding = "UTF-8")
- }, error = function(e) {
- paste("Status:", status)
- })
-
- return(list(
- success = FALSE,
- error = paste("API error:", status, "-", substr(error_content, 1, 200))
- ))
+ text <- result$choices[[1]]$message$content
+ return(list(success = TRUE, text = text))
}
- }, error = function(e) {
- return(list(success = FALSE, error = e$message))
- })
+
+ 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))
}
# ============================================================
@@ -244,18 +132,14 @@ query_hf_api <- function(prompt, max_length = 500, temperature = 0.7) {
build_system_prompt <- function(rv) {
context_parts <- c("CURRENT ANALYSIS RESULTS:")
- # Add QTL results
if (!is.null(rv$qtl_effects_train) && !"Message" %in% colnames(rv$qtl_effects_train)) {
- n_qtl <- nrow(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))
- context_parts <- c(context_parts,
+ 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%%.", total_pve))
- # Add top 3 QTLs
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)) {
@@ -266,30 +150,24 @@ build_system_prompt <- function(rv) {
}
}
- # Add performance metrics
if (!is.null(rv$performance_metrics)) {
- pm <- rv$performance_metrics
- train_r2 <- pm$Value[pm$Metric == "R² (Train)"]
- val_r2 <- pm$Value[pm$Metric == "R² (Validation)"]
-
+ pm <- rv$performance_metrics
+ train_r2 <- pm$Value[pm$Metric == "R\u00b2 (Train)"]
+ val_r2 <- pm$Value[pm$Metric == "R\u00b2 (Validation)"]
context_parts <- c(context_parts,
sprintf("\nModel Performance:"),
- sprintf(" Training R²: %.3f", train_r2),
- sprintf(" Validation R²: %.3f", val_r2))
+ sprintf(" Training R\u00b2: %.3f", train_r2),
+ sprintf(" Validation R\u00b2: %.3f", val_r2))
}
- # Add epistasis results
if (!is.null(rv$epistasis_sig) && !"Message" %in% colnames(rv$epistasis_sig) && nrow(rv$epistasis_sig) > 0) {
- n_epi <- nrow(rv$epistasis_sig)
- context_parts <- c(context_parts,
- sprintf("\nEpistasis: %d significant pairwise interactions detected.", n_epi))
-
+ n_epi <- nrow(rv$epistasis_sig)
top_epi <- rv$epistasis_sig[order(rv$epistasis_sig$Interaction_p), ][1, ]
context_parts <- c(context_parts,
- sprintf(" Strongest: %s × %s (p=%.4f)", top_epi$QTL1, top_epi$QTL2, top_epi$Interaction_p))
+ 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))
}
- # Add domestication results
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,
@@ -306,47 +184,44 @@ build_system_prompt <- function(rv) {
enhanced_rule_response <- function(user_message, rv) {
q <- tolower(trimws(user_message))
- # Check for results availability
- has_qtl <- !is.null(rv$qtl_effects_train) && !"Message" %in% colnames(rv$qtl_effects_train)
+ has_qtl <- !is.null(rv$qtl_effects_train) && !"Message" %in% colnames(rv$qtl_effects_train)
has_perf <- !is.null(rv$performance_metrics)
- 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)
+ 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)
- # PVE-specific questions
+ # PVE questions
if (grepl("pve|variance explained|how much variance|percent variance|what is pve", q)) {
if (has_qtl) {
- df <- rv$qtl_effects_train
+ df <- rv$qtl_effects_train
total_pve <- sum(df$PVE_Percent, na.rm = TRUE)
- top_pve <- df[which.max(df$PVE_Percent), ]
+ top_pve <- df[which.max(df$PVE_Percent), ]
response <- paste0(
- "📊 **PVE (Phenotypic Variance Explained) Analysis**\n\n",
+ "\U0001f4ca **PVE (Phenotypic Variance Explained) Analysis**\n\n",
"**Your Results:**\n",
- "• Total variance explained by all QTLs: **", round(total_pve, 1), "%**\n",
- "• Number of QTLs detected: **", nrow(df), "**\n\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",
- "• Marker: **", top_pve$Marker, "**\n",
- "• Chromosome: ", top_pve$Chromosome, "\n",
- "• PVE: **", round(top_pve$PVE_Percent, 1), "%**\n",
- "• LOD: ", round(top_pve$LOD, 2), "\n\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\n"
)
if (top_pve$PVE_Percent > 10) {
- response <- paste0(response, "💡 This is a **major-effect QTL** (>10% PVE) - excellent candidate for marker-assisted selection.\n\n")
+ response <- paste0(response, "\U0001f4a1 This is a **major-effect QTL** (>10% PVE) - excellent candidate for marker-assisted selection.\n\n")
} else if (top_pve$PVE_Percent > 5) {
- response <- paste0(response, "💡 This is a **moderate-effect QTL** (5-10% PVE) - useful for polygenic breeding approaches.\n\n")
+ response <- paste0(response, "\U0001f4a1 This is a **moderate-effect QTL** (5-10% PVE) - useful for polygenic breeding approaches.\n\n")
} else {
- response <- paste0(response, "💡 This is a **minor-effect QTL** (<5% PVE) - typical for complex polygenic traits.\n\n")
+ response <- paste0(response, "\U0001f4a1 This is a **minor-effect QTL** (<5% PVE) - typical for complex polygenic traits.\n\n")
}
- # All QTLs PVE
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, ]
+ row <- df_sorted[i, ]
response <- paste0(response, sprintf(" %d. %s: %.1f%%\n", i, row$Marker, row$PVE_Percent))
}
-
return(response)
} else {
return("No QTL results yet. Please run the QTL analysis first to see PVE values.")
@@ -356,45 +231,40 @@ enhanced_rule_response <- function(user_message, rv) {
# Model performance questions
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)"]
+ pm <- rv$performance_metrics
+ train_r2 <- pm$Value[pm$Metric == "R\u00b2 (Train)"]
+ val_r2 <- pm$Value[pm$Metric == "R\u00b2 (Validation)"]
response <- paste0(
- "📈 **Model Performance Summary**\n\n",
- "• Training R²: **", round(train_r2, 3), "**\n",
- "• Validation R²: **", round(val_r2, 3), "**\n\n"
+ "\U0001f4c8 **Model Performance Summary**\n\n",
+ "\u2022 Training R\u00b2: **", round(train_r2, 3), "**\n",
+ "\u2022 Validation R\u00b2: **", round(val_r2, 3), "**\n\n"
)
if (val_r2 < 0) {
response <- paste0(response,
- "⚠️ **Your validation R² is negative** (", round(val_r2, 3), ").\n\n",
+ "\u26a0\ufe0f **Your validation R\u00b2 is negative** (", round(val_r2, 3), ").\n\n",
"This means the model performs worse than simply predicting the mean.\n\n",
"**Common causes:**\n",
- "• **Small sample size** relative to number of markers\n",
- "• **Overfitting** - model learned noise instead of signal\n",
- "• **Population structure** in your data\n\n",
+ "\u2022 **Small sample size** relative to number of markers\n",
+ "\u2022 **Overfitting** - model learned noise instead of signal\n",
+ "\u2022 **Population structure** in your data\n\n",
"**Recommendations:**\n",
"1. Increase sample size if possible\n",
"2. Reduce marker number (use feature selection)\n",
"3. Try simpler models or increase cross-validation folds\n",
- "4. Focus on individual QTL interpretation rather than prediction\n"
- )
+ "4. Focus on individual QTL interpretation rather than prediction\n")
} else if (val_r2 < 0.2) {
response <- paste0(response,
- "📉 **Low validation R²** (<0.2) suggests modest predictive power.\n\n",
- "This is common for complex traits. Focus on individual QTL interpretation.\n"
- )
+ "\U0001f4c9 **Low validation R\u00b2** (<0.2) suggests modest predictive power.\n\n",
+ "This is common for complex traits. Focus on individual QTL interpretation.\n")
} else if (val_r2 < 0.5) {
response <- paste0(response,
- "📊 **Moderate validation R²** (0.2-0.5) - your model has decent predictive ability.\n\n"
- )
+ "\U0001f4ca **Moderate validation R\u00b2** (0.2-0.5) - your model has decent predictive ability.\n\n")
} else {
response <- paste0(response,
- "🎯 **Excellent validation R²** (>0.5) - your model has strong predictive power!\n\n"
- )
+ "\U0001f3af **Excellent validation R\u00b2** (>0.5) - your model has strong predictive power!\n\n")
}
-
return(response)
} else {
return("Run the QTL analysis first to see model performance metrics.")
@@ -404,25 +274,22 @@ enhanced_rule_response <- function(user_message, rv) {
# Top QTLs question
if (grepl("top qtl|best qtl|highest lod|significant qtl|list qtl|show qtl", q)) {
if (has_qtl) {
- df <- rv$qtl_effects_train[order(-rv$qtl_effects_train$LOD), ]
+ df <- rv$qtl_effects_train[order(-rv$qtl_effects_train$LOD), ]
top5 <- head(df, 5)
- response <- "🎯 **Top 5 QTLs by LOD Score**\n\n"
-
+ response <- "\U0001f3af **Top 5 QTLs by LOD Score**\n\n"
for (i in 1:nrow(top5)) {
- row <- top5[i, ]
+ row <- top5[i, ]
response <- paste0(response,
i, ". **", row$Marker, "** (Chr ", row$Chromosome, ")\n",
- " • LOD: **", round(row$LOD, 2), "**\n",
- " • PVE: ", round(row$PVE_Percent, 1), "%\n",
- " • Additive effect: ", round(row$Additive_Effect, 3), "\n"
- )
+ " \u2022 LOD: **", round(row$LOD, 2), "**\n",
+ " \u2022 PVE: ", round(row$PVE_Percent, 1), "%\n",
+ " \u2022 Additive effect: ", round(row$Additive_Effect, 3), "\n")
if (!is.null(row$Low_Flank) && !is.na(row$Low_Flank) && row$Low_Flank != "NA") {
- response <- paste0(response, " • Interval: ", row$Low_Flank, " - ", row$High_Flank, "\n")
+ response <- paste0(response, " \u2022 Interval: ", row$Low_Flank, " - ", row$High_Flank, "\n")
}
response <- paste0(response, "\n")
}
-
return(response)
} else {
return("No significant QTLs detected. Try lowering the LOD threshold or check your data.")
@@ -432,51 +299,43 @@ enhanced_rule_response <- function(user_message, rv) {
# Next steps question
if (grepl("next steps|what next|recommendations|suggest|advice|what should i do", q)) {
if (has_qtl || has_perf || has_epi || has_sel) {
- response <- "🔬 **Recommended Next Steps**\n\n"
+ 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,
+ top_qtl <- rv$qtl_effects_train[which.max(rv$qtl_effects_train$LOD), ]
+ response <- paste0(response,
"**1. Validate Top QTLs**\n",
- " • Prioritize **", top_qtl$Marker, "** (LOD=", round(top_qtl$LOD, 2),
+ " \u2022 Prioritize **", top_qtl$Marker, "** (LOD=", round(top_qtl$LOD, 2),
", PVE=", round(top_qtl$PVE_Percent, 1), "%)\n",
- " • Test in independent population or F2 cross\n",
- " • Use flanking markers for fine-mapping\n\n"
- )
+ " \u2022 Test in independent population or F2 cross\n",
+ " \u2022 Use flanking markers for fine-mapping\n\n")
}
-
if (has_epi) {
- n_epi <- nrow(rv$epistasis_sig)
+ n_epi <- nrow(rv$epistasis_sig)
response <- paste0(response,
"**2. Investigate Epistasis**\n",
- " • ", n_epi, " significant interactions detected\n",
- " • Test multi-locus models in breeding programs\n",
- " • Check if interacting QTLs map to same pathways\n\n"
- )
+ " \u2022 ", n_epi, " significant interactions detected\n",
+ " \u2022 Test multi-locus models in breeding programs\n",
+ " \u2022 Check if interacting QTLs map to same pathways\n\n")
}
-
if (has_sel) {
- n_sel <- sum(rv$selection_metrics$Significant, na.rm = TRUE)
+ n_sel <- sum(rv$selection_metrics$Significant, na.rm = TRUE)
response <- paste0(response,
"**3. Domestication Analysis**\n",
- " • ", n_sel, " markers show selection signatures\n",
- " • Cross-reference with QTL positions\n",
- " • Candidate domestication genes\n\n"
- )
+ " \u2022 ", n_sel, " markers show selection signatures\n",
+ " \u2022 Cross-reference with QTL positions\n",
+ " \u2022 Candidate domestication genes\n\n")
}
response <- paste0(response,
"**4. Functional Analysis**\n",
- " • Annotate QTL regions for candidate genes\n",
- " • Check gene expression databases\n",
- " • Design validation experiments\n\n",
-
+ " \u2022 Annotate QTL regions for candidate genes\n",
+ " \u2022 Check gene expression databases\n",
+ " \u2022 Design validation experiments\n\n",
"**5. Breeding Applications**\n",
- " • Develop markers for MAS\n",
- " • Design crossing schemes\n",
- " • Predict breeding values\n"
- )
-
+ " \u2022 Develop markers for MAS\n",
+ " \u2022 Design crossing schemes\n",
+ " \u2022 Predict breeding values\n")
return(response)
} else {
return("Run the QTL analysis first to get recommendations.")
@@ -485,10 +344,10 @@ enhanced_rule_response <- function(user_message, rv) {
# Default response
available <- c()
- if (has_qtl) available <- c(available, paste(nrow(rv$qtl_effects_train), "QTLs"))
+ 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)))
+ val_r2 <- rv$performance_metrics$Value[rv$performance_metrics$Metric == "R\u00b2 (Validation)"]
+ available <- c(available, paste0("R\u00b2=", 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"))
@@ -497,26 +356,24 @@ enhanced_rule_response <- function(user_message, rv) {
return(paste0(
"I can see you have: ", paste(available, collapse = ", "), ".\n\n",
"What would you like to know? Try asking about:\n",
- "• **What is PVE?** - Understand variance explained\n",
- "• **Top QTLs** - List most significant markers\n",
- "• **Model performance** - Why is R² negative?\n",
- "• **Next steps** - Recommendations for your results"
- ))
+ "\u2022 **What is PVE?** - Understand variance explained\n",
+ "\u2022 **Top QTLs** - List most significant markers\n",
+ "\u2022 **Model performance** - Why is R\u00b2 negative?\n",
+ "\u2022 **Next steps** - Recommendations for your results"))
}
return(paste0(
- "👋 Hello! I'm your QTL analysis assistant.\n\n",
+ "\U0001f44b Hello! I'm your QTL analysis assistant.\n\n",
"**I can help you with:**\n",
- "• Understanding PVE (variance explained)\n",
- "• Interpreting LOD scores and QTL significance\n",
- "• Evaluating model performance (R²)\n",
- "• Detecting epistatic interactions\n\n",
+ "\u2022 Understanding PVE (variance explained)\n",
+ "\u2022 Interpreting LOD scores and QTL significance\n",
+ "\u2022 Evaluating model performance (R\u00b2)\n",
+ "\u2022 Detecting epistatic interactions\n\n",
"**To get started:**\n",
"1. Upload your genotype and phenotype files\n",
"2. Click 'Run QTL Analysis'\n",
"3. Ask me specific questions!\n\n",
- "Try: **'What is PVE?'** or **'Show me my top QTLs'**"
- ))
+ "Try: **'What is PVE?'** or **'Show me my top QTLs'**"))
}
# ============================================================
@@ -524,34 +381,26 @@ enhanced_rule_response <- function(user_message, rv) {
# ============================================================
generate_ai_response <- function(user_message, rv) {
- # Build context
context <- build_system_prompt(rv)
- # Check if we should use API
if (use_hf_api) {
- # Construct prompt for API
prompt <- paste(
- "CONTEXT:",
- context,
+ "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"
)
- # Try API
result <- query_hf_api(prompt)
if (result$success) {
return(result$text)
} else {
- # Log error but don't show to user
message("API Error: ", result$error)
- # Fallback to rule-based
return(enhanced_rule_response(user_message, rv))
}
}
- # Use rule-based
return(enhanced_rule_response(user_message, rv))
}
@@ -590,16 +439,14 @@ ui <- fluidPage(
}
Shiny.addCustomMessageHandler('simulateQTLDiscovery', function(message) { simulateQTLDiscovery(); });
Shiny.addCustomMessageHandler('resetAnimation', function(message) { resetAnimation(); });
-
- // Auto-scroll chat to bottom
+
Shiny.addCustomMessageHandler('scrollChatBottom', function(message) {
setTimeout(function() {
var chatBox = document.getElementById('chat_messages');
if (chatBox) chatBox.scrollTop = chatBox.scrollHeight;
}, 100);
});
-
- // Enter key to send chat
+
$(document).on('keydown', '#chat_input', function(e) {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
@@ -609,81 +456,28 @@ ui <- fluidPage(
")),
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-color: var(--bg-primary);
- color: var(--text-primary);
- font-size: 14px;
- }
-
+ 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 { 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; }
-
- .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 { 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 inputs */
- .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; }
+ .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; }
-
- /* Buttons */
.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; }
@@ -691,14 +485,8 @@ ui <- fluidPage(
.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 text */
.help-block, .shiny-input-container .help-block { color: var(--text-muted); font-size: 11px; margin-top: 4px; }
-
- /* File input */
.btn-file { background-color: var(--bg-tertiary); border-color: var(--border); color: var(--text-secondary); }
-
- /* DataTables */
.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; }
@@ -708,254 +496,63 @@ ui <- fluidPage(
.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 styles */
.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.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); }
- }
+ @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 buttons */
.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; }
-
- /* Chatbot Styles */
- #chat-panel {
- position: fixed;
- bottom: 20px;
- right: 20px;
- z-index: 9999;
- width: 420px;
- 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(--border);
- border-radius: 12px;
- overflow: hidden;
- box-shadow: 0 8px 40px rgba(0,0,0,0.5);
- margin-bottom: 10px;
- height: 600px;
- border: 1px solid var(--accent);
- }
+ #chat-panel { position: fixed; bottom: 20px; right: 20px; z-index: 9999; width: 420px; 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: 600px; }
#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;
- align-items: center;
- justify-content: space-between;
- }
+ #chat-header { background: linear-gradient(135deg, var(--bg-tertiary), #1c2b3a); border-bottom: 1px solid var(--border); padding: 12px 16px; 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;
- }
+ .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; }
#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;
- font-weight: bold;
- }
+ #chat-header p { font-size: 11px; color: var(--text-muted); margin: 0; font-weight: bold; }
#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; }
#chat-close-btn:hover { color: var(--text-primary); }
-
- #chat_messages {
- flex: 1;
- overflow-y: auto;
- padding: 16px;
- display: flex;
- flex-direction: column;
- gap: 12px;
- background: var(--bg-primary);
- }
-
- .chat-msg {
- max-width: 90%;
- animation: fadeIn 0.3s ease;
- }
- @keyframes fadeIn {
- from { opacity: 0; transform: translateY(10px); }
- to { opacity: 1; transform: translateY(0); }
- }
+ #chat_messages { flex: 1; overflow-y: auto; padding: 16px; display: flex; flex-direction: column; gap: 12px; background: var(--bg-primary); }
+ .chat-msg { max-width: 90%; 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 { 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-bubble em { color: var(--text-secondary); }
.chat-meta { font-size: 10px; color: var(--text-muted); margin-top: 4px; font-family: var(--font-mono); padding: 0 4px; }
-
- .typing-indicator {
- display: flex;
- gap: 4px;
- padding: 12px 16px;
- background: var(--bg-tertiary);
- border: 1px solid var(--border);
- border-radius: 16px;
- border-bottom-left-radius: 4px;
- width: fit-content;
- }
- .typing-dot {
- width: 8px; height: 8px;
- background: var(--text-muted);
- border-radius: 50%;
- animation: typingBounce 1.4s infinite;
- }
+ .typing-indicator { display: flex; gap: 4px; padding: 12px 16px; background: 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); }
- }
-
- #chat-footer {
- padding: 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;
- }
+ @keyframes typingBounce { 0%, 60%, 100% { transform: translateY(0); } 30% { transform: translateY(-8px); } }
+ #chat-footer { padding: 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 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); }
+ .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 { 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); }
-
- .model-badge {
- display: inline-block;
- background: var(--bg-secondary);
- border: 1px solid var(--border);
- border-radius: 12px;
- padding: 2px 8px;
- font-size: 10px;
- color: var(--text-muted);
- margin-left: 8px;
- }
-
- .quick-questions {
- padding: 8px 16px;
- display: flex;
- flex-wrap: wrap;
- gap: 6px;
- border-bottom: 1px solid var(--border);
- }
- .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); }
+ .model-badge { display: inline-block; background: var(--bg-secondary); border: 1px solid var(--border); border-radius: 12px; padding: 2px 8px; font-size: 10px; color: var(--text-muted); margin-left: 8px; }
+ .quick-questions { padding: 8px 16px; display: flex; flex-wrap: wrap; gap: 6px; border-bottom: 1px solid var(--border); }
+ .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); }
"))
),
@@ -963,6 +560,7 @@ ui <- fluidPage(
title = tags$span(tags$i(class = "fas fa-dna", style = "margin-right:8px; color:#58a6ff;"), "QTL-Mapper AI"),
id = "nav",
+ # ---- Data Upload tab ----
tabPanel("Data Upload", icon = icon("upload"),
div(class = "main-header",
h2(tags$i(class = "fas fa-upload", style = "margin-right:8px;"), "Data Upload"),
@@ -973,9 +571,9 @@ ui <- fluidPage(
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 = c(".csv"), buttonLabel = "Browse"),
+ 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 = c(".csv"), buttonLabel = "Browse"),
+ 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)
)
@@ -985,7 +583,7 @@ ui <- fluidPage(
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 = c(".csv"), buttonLabel = "Browse"),
+ 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"))
@@ -1009,9 +607,9 @@ ui <- fluidPage(
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("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"))
)
)
@@ -1020,6 +618,7 @@ ui <- fluidPage(
)
),
+ # ---- Domestication tab ----
tabPanel("Domestication", icon = icon("leaf"),
div(class = "main-header",
h2(tags$i(class = "fas fa-leaf", style = "margin-right:8px;"), "Domestication Analysis"),
@@ -1030,10 +629,10 @@ ui <- fluidPage(
div(class = "card",
div(class = "card-header", "Population Metadata"),
div(class = "card-body",
- fileInput("pop_file", "Population Metadata CSV", accept = c(".csv"), buttonLabel = "Browse"),
+ 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),
+ 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"))
)
)
@@ -1046,7 +645,7 @@ ui <- fluidPage(
)
),
fluidRow(
- column(6, div(class = "card", div(class = "card-header", "Fst Manhattan Plot"), div(class = "card-body", plotlyOutput("fst_plot", height = "400px")))),
+ column(6, div(class = "card", div(class = "card-header", "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(
@@ -1063,6 +662,7 @@ ui <- fluidPage(
)
),
+ # ---- Results tab ----
tabPanel("Results", icon = icon("chart-line"),
div(class = "main-header",
h2(tags$i(class = "fas fa-chart-line", style = "margin-right:8px;"), "QTL Analysis Results"),
@@ -1076,19 +676,19 @@ ui <- fluidPage(
uiOutput("chromosome_viz"),
div(class = "simulation-controls",
actionButton("simulate_btn", "Simulate Discovery", class = "simulation-btn"),
- actionButton("reset_btn", "Reset", 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"))))
+ 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"),
+ div(class = "card-header", "QTL Effects - Training Set"),
div(class = "card-body", DTOutput("qtl_effects_table_train"), tags$br(), downloadButton("download_train_results", "Download"))
))
),
@@ -1103,26 +703,22 @@ ui <- fluidPage(
)
),
+ # ---- Interpretation tab ----
tabPanel("Interpretation", icon = icon("lightbulb"),
div(class = "main-header",
h2(tags$i(class = "fas fa-lightbulb", style = "margin-right:8px;"), "Results Interpretation"),
p("Comprehensive interpretation of QTL and domestication analysis")
),
- fluidRow(
- column(12, div(class = "card", div(class = "card-header", "Analysis Summary"), div(class = "card-body", uiOutput("analysis_summary"))))
- ),
+ fluidRow(column(12, div(class = "card", div(class = "card-header", "Analysis Summary"), div(class = "card-body", uiOutput("analysis_summary"))))),
fluidRow(
column(6, div(class = "card", div(class = "card-header", "QTL Significance"), div(class = "card-body", uiOutput("qtl_interpretation")))),
- column(6, div(class = "card", div(class = "card-header", "Effect Sizes"), 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"))))
+ column(6, div(class = "card", div(class = "card-header", "Effect Sizes"), div(class = "card-body", uiOutput("effect_interpretation"))))
),
- fluidRow(
- column(12, div(class = "card", div(class = "card-header", "Recommendations"), div(class = "card-body", uiOutput("recommendations"))))
- )
+ fluidRow(column(12, div(class = "card", div(class = "card-header", "Epistasis"), div(class = "card-body", uiOutput("epistasis_interpretation"))))),
+ fluidRow(column(12, div(class = "card", div(class = "card-header", "Recommendations"), div(class = "card-body", uiOutput("recommendations")))))
),
+ # ---- About tab ----
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 AI"),
@@ -1132,8 +728,8 @@ ui <- fluidPage(
column(8, offset = 2,
div(class = "card",
div(class = "card-body",
- h4(style = "color:#58a6ff; font-family: 'IBM Plex Mono'; margin-bottom:12px;", "Methodology"),
- tags$ul(style = "color: #8b949e; line-height: 2;",
+ h4(style = "color:#58a6ff; font-family:'IBM Plex Mono'; margin-bottom:12px;", "Methodology"),
+ tags$ul(style = "color:#8b949e; line-height:2;",
tags$li("Random Forest for QTL mapping with variable importance scoring"),
tags$li("LOD scores derived from marker importance (-log10 scale)"),
tags$li("Additive and dominance effects estimated via linear regression"),
@@ -1141,16 +737,13 @@ ui <- fluidPage(
tags$li("Domestication: Fst, nucleotide diversity (Pi), Tajima's D"),
tags$li("AI Assistant powered by transformer models via Hugging Face Inference API")
),
- h4(style = "color:#58a6ff; font-family: 'IBM Plex Mono'; margin: 12px 0;", "AI Assistant Status"),
- p(style = "color: #8b949e; line-height: 1.7;",
- if (use_hf_api) {
- paste("✅ AI Assistant is connected to Hugging Face API using", hf_model)
- } else {
- "⚠️ AI Assistant is in rule-based mode. Set HF_API_TOKEN in Space secrets to enable transformer-based responses."
- }
+ h4(style = "color:#58a6ff; font-family:'IBM Plex Mono'; margin:12px 0;", "AI Assistant Status"),
+ p(style = "color:#8b949e; line-height:1.7;",
+ if (use_hf_api) paste("Connected to Hugging Face API using", hf_model)
+ else "AI Assistant is in rule-based mode. Set HF_API_TOKEN in Space secrets to enable transformer-based responses."
),
- h4(style = "color:#58a6ff; font-family: 'IBM Plex Mono'; margin: 12px 0;", "Interpretation Thresholds"),
- tags$ul(style = "color: #8b949e; line-height: 2;",
+ 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"),
tags$li("Fst > 0.2: Strong population differentiation"),
tags$li("Tajima's D < -2: Potential selective sweep"),
@@ -1163,55 +756,45 @@ ui <- fluidPage(
)
),
+ # ---- Floating Chat Panel ----
tags$div(id = "chat-panel",
tags$div(id = "chat-window",
tags$div(id = "chat-header",
tags$div(class = "chat-title",
tags$div(class = "chat-avatar", "AI"),
tags$div(
- tags$h4("QTL Analysis AI Assistant",
- tags$span(class = "model-badge",
- if(use_hf_api) gsub(".*/", "", hf_model) else "rules")
+ tags$h4("QTL Analysis AI Assistant",
+ tags$span(class = "model-badge",
+ if (use_hf_api) gsub(".*/", "", hf_model) else "rules")
),
- tags$p(id = "model_status",
- if(use_hf_api) paste("🤖 AI mode -", gsub(".*/", "", hf_model)) else "📝 Rule-based mode",
- class = if(use_hf_api) "ai-mode" else "rule-mode"
+ tags$p(id = "model_status",
+ if (use_hf_api) paste("AI mode -", gsub(".*/", "", hf_model)) else "Rule-based mode",
+ class = if (use_hf_api) "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$button(id = "chat-close-btn",
+ onclick = "document.getElementById('chat-window').classList.remove('open');",
+ tags$i(class = "fas fa-times"))
),
-
tags$div(class = "quick-questions",
- tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q', '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 R² negative?', {priority: 'event'});", "Negative R²"),
- tags$button(class = "quick-q-btn", onclick = "Shiny.setInputValue('quick_q', 'What should I do next?', {priority: 'event'});", "Next steps")
+ 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_messages", uiOutput("chat_display")),
tags$div(id = "chat-footer",
- tags$textarea(
- id = "chat_input",
- placeholder = "Ask about your results... (Enter to send)",
- rows = "2"
- ),
+ 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")
+ 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$i(class = "fas fa-robot"))
)
)
@@ -1222,65 +805,56 @@ ui <- fluidPage(
server <- function(input, output, session) {
values <- reactiveValues(
- genotype_data = NULL,
- phenotype_data = NULL,
- test_genotype_data = NULL,
+ genotype_data = NULL,
+ phenotype_data = NULL,
+ test_genotype_data = NULL,
predicted_test_phenotype_data = NULL,
- chromosome_info = NULL,
- position_info = NULL,
- all_markers = NULL,
- importance_scores = NULL,
- lod_scores_train = NULL,
- model_fit = NULL,
- phenotype_values = NULL,
- qtl_effects_train = NULL,
- qtl_effects_test = 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 = 2,
- use_ai = use_hf_api
+ chromosome_info = NULL,
+ position_info = NULL,
+ all_markers = NULL,
+ importance_scores = NULL,
+ lod_scores_train = NULL,
+ model_fit = NULL,
+ phenotype_values = NULL,
+ qtl_effects_train = NULL,
+ qtl_effects_test = 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 = 2,
+ use_ai = use_hf_api
)
- # Update status based on API availability
observe({
if (values$use_ai) {
- shinyjs::html("model_status", paste("🤖 AI mode -", gsub(".*/", "", hf_model)))
+ shinyjs::html("model_status", paste("AI mode -", gsub(".*/", "", hf_model)))
} else {
- shinyjs::html("model_status", "📝 Rule-based mode")
+ shinyjs::html("model_status", "Rule-based mode")
}
})
- # ============================================================
- # CHAT FUNCTIONS
- # ============================================================
-
+ # ---- Chat helpers ----
add_message <- function(role, content) {
timestamp <- format(Sys.time(), "%H:%M")
- values$chat_messages <- c(values$chat_messages, list(list(
- role = role, content = content, time = timestamp
- )))
- if (length(values$chat_messages) > 50) {
+ values$chat_messages <- c(values$chat_messages,
+ list(list(role = role, content = content, time = timestamp)))
+ if (length(values$chat_messages) > 50)
values$chat_messages <- tail(values$chat_messages, 50)
- }
session$sendCustomMessage("scrollChatBottom", list())
}
process_message <- function(user_text) {
if (nchar(trimws(user_text)) == 0) return()
-
add_message("user", user_text)
values$is_typing <- TRUE
-
response <- generate_ai_response(user_text, values)
-
values$is_typing <- FALSE
add_message("assistant", response)
}
@@ -1293,10 +867,7 @@ server <- function(input, output, session) {
process_message(user_text)
})
- observeEvent(input$quick_q, {
- req(input$quick_q)
- process_message(input$quick_q)
- })
+ observeEvent(input$quick_q, { req(input$quick_q); process_message(input$quick_q) })
observeEvent(input$clear_chat, {
values$chat_messages <- list()
@@ -1308,19 +879,16 @@ server <- function(input, output, session) {
mode_msg <- if (values$use_ai) {
paste("I'm using the", gsub(".*/", "", hf_model), "model via Hugging Face API!")
} else {
- paste("I'm using enhanced rule-based responses.",
- "To enable AI mode, check your HF_API_TOKEN in Space secrets.")
+ "I'm using rule-based responses. To enable AI mode, set HF_API_TOKEN in Space secrets."
}
add_message("assistant", paste(
- "👋 Hello! I'm your QTL analysis assistant.",
- mode_msg,
+ "\U0001f44b Hello! I'm your QTL analysis assistant.", mode_msg,
"\n\n**I can help you with:**",
- "• **What is PVE?** - Understand variance explained",
- "• **Show top QTLs** - List your most significant markers",
- "• **Model performance** - Why is my R² negative?",
- "• **Next steps** - Recommendations",
- "\nTry asking: **'What is PVE?'**"
- ))
+ "\u2022 **What is PVE?** - Understand variance explained",
+ "\u2022 **Show top QTLs** - List your most significant markers",
+ "\u2022 **Model performance** - Why is my R\u00b2 negative?",
+ "\u2022 **Next steps** - Recommendations",
+ "\nTry asking: **'What is PVE?'**"))
}
})
@@ -1328,71 +896,54 @@ server <- function(input, output, session) {
messages <- values$chat_messages
if (length(messages) == 0) return(NULL)
- message_elements <- lapply(messages, function(msg) {
+ elems <- lapply(messages, function(msg) {
div(class = paste("chat-msg", msg$role),
- div(class = "chat-bubble",
- HTML(gsub("\n", "
", htmltools::htmlEscape(msg$content)))
- ),
- div(class = "chat-meta", msg$time)
- )
+ div(class = "chat-bubble",
+ HTML(gsub("\n", "
", htmltools::htmlEscape(msg$content)))),
+ div(class = "chat-meta", msg$time))
})
if (values$is_typing) {
- message_elements <- c(message_elements, list(
+ 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")
- )
- )
- ))
+ div(class = "typing-dot"), div(class = "typing-dot"), div(class = "typing-dot")))))
}
-
- do.call(tagList, message_elements)
+ do.call(tagList, elems)
})
- # ============================================================
- # DATA LOADING FUNCTIONS
- # ============================================================
-
+ # ---- Data loading ----
observeEvent(input$genotype_file, {
req(input$genotype_file)
tryCatch({
all_data <- readLines(input$genotype_file$datapath)
- if (length(all_data) < 4) {
- showNotification("Genotype file must have at least 4 rows", type = "error")
- return()
- }
+ if (length(all_data) < 4) { showNotification("Genotype file must have at least 4 rows", type = "error"); return() }
- header <- strsplit(all_data[1], ",")[[1]]
+ header <- strsplit(all_data[1], ",")[[1]]
chromosome_row <- strsplit(all_data[2], ",")[[1]]
- position_row <- strsplit(all_data[3], ",")[[1]]
+ position_row <- strsplit(all_data[3], ",")[[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]
+ genotype_data <- genotype_data[, -1]
- for (col in colnames(genotype_data)) {
+ for (col in colnames(genotype_data))
genotype_data[[col]] <- as.numeric(as.character(genotype_data[[col]]))
- }
values$all_markers <- data.frame(
- Marker = colnames(genotype_data),
+ Marker = colnames(genotype_data),
Chromosome = chromosome_row[-1],
- Position = as.numeric(position_row[-1]),
- stringsAsFactors = FALSE
- )
+ Position = as.numeric(position_row[-1]),
+ stringsAsFactors = FALSE)
- values$genotype_data <- genotype_data
- values$chromosome_info <- chromosome_row[-1]
- values$position_info <- as.numeric(position_row[-1])
+ 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("✅ Loaded ", ncol(genotype_data), " markers, ", nrow(genotype_data), " samples"))
-
- }, error = function(e) {
- showNotification(paste("Error:", e$message), type = "error")
- })
+ add_message("assistant", paste0("\u2705 Loaded ", ncol(genotype_data), " markers, ", nrow(genotype_data), " samples"))
+ }, error = function(e) showNotification(paste("Error:", e$message), type = "error"))
})
observeEvent(input$phenotype_file, {
@@ -1400,23 +951,19 @@ server <- function(input, output, session) {
tryCatch({
phenotype_data <- read.csv(input$phenotype_file$datapath)
rownames(phenotype_data) <- phenotype_data[, 1]
- phenotype_data <- phenotype_data[, -1]
+ phenotype_data <- phenotype_data[, -1]
- for (col in colnames(phenotype_data)) {
+ 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),
+ updateSelectInput(session, "phenotype_column",
+ choices = colnames(phenotype_data),
selected = colnames(phenotype_data)[1])
showNotification("Phenotype data loaded", type = "message")
- add_message("assistant", paste0("✅ Loaded ", ncol(phenotype_data), " traits, ", nrow(phenotype_data), " samples"))
-
- }, error = function(e) {
- showNotification(paste("Error:", e$message), type = "error")
- })
+ add_message("assistant", paste0("\u2705 Loaded ", ncol(phenotype_data), " traits, ", nrow(phenotype_data), " samples"))
+ }, error = function(e) showNotification(paste("Error:", e$message), type = "error"))
})
observeEvent(input$pop_file, {
@@ -1424,191 +971,134 @@ server <- function(input, output, session) {
tryCatch({
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()
+ showNotification("Population file must have 'id' and 'population' columns", type = "error"); return()
}
values$pop_data <- pop_data
showNotification("Population data loaded", type = "message")
- add_message("assistant", paste0("✅ Loaded population data (", nrow(pop_data), " samples)"))
- }, error = function(e) {
- showNotification(paste("Error:", e$message), type = "error")
- })
+ 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]]
- chromosome_row <- strsplit(all_data[2], ",")[[1]]
- position_row <- strsplit(all_data[3], ",")[[1]]
+ 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)
+ 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)) {
+ 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
+ values$has_test_data <- TRUE
showNotification("Test genotype data loaded", type = "message")
-
- }, error = function(e) {
- showNotification(paste("Error:", e$message), type = "error")
- })
- })
-
- # ============================================================
- # DATA PREVIEWS
- # ============================================================
-
- 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))
+ }, error = function(e) showNotification(paste("Error:", e$message), type = "error"))
})
- 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))
- })
-
- # ============================================================
- # QTL ANALYSIS FUNCTIONS
- # ============================================================
+ # ---- Data previews ----
+ output$geno_preview <- renderDT({ req(input$genotype_file); datatable(head(read.csv(input$genotype_file$datapath), 10), options = list(scrollX = TRUE, pageLength = 5)) })
+ output$pheno_preview <- renderDT({ req(input$phenotype_file); datatable(head(read.csv(input$phenotype_file$datapath), 10), options = list(scrollX = TRUE, pageLength = 5)) })
+ output$test_geno_preview <- renderDT({ req(input$test_genotype_file); datatable(head(read.csv(input$test_genotype_file$datapath), 10), options = list(scrollX = TRUE, pageLength = 5)) })
+ output$pop_preview <- renderDT({ req(input$pop_file); datatable(head(read.csv(input$pop_file$datapath), 10), options = list(scrollX = TRUE, pageLength = 5)) })
+ output$predicted_test_pheno_preview <- renderDT({ req(values$predicted_test_phenotype_data); datatable(values$predicted_test_phenotype_data, options = list(scrollX = TRUE, pageLength = 5)) })
+ # ---- QTL effect calculation ----
calculate_qtl_effects <- function(genotype_matrix, phenotype_vector, marker_names) {
effects_list <- list()
for (marker in marker_names) {
if (!marker %in% colnames(genotype_matrix)) next
- geno <- genotype_matrix[, marker]
- pheno <- phenotype_vector
+ geno <- genotype_matrix[, marker]
+ pheno <- phenotype_vector
valid_idx <- !is.na(geno) & !is.na(pheno)
- geno <- geno[valid_idx]
- pheno <- pheno[valid_idx]
+ geno <- geno[valid_idx]
+ pheno <- pheno[valid_idx]
if (length(unique(geno)) < 2) next
- lm_fit <- lm(pheno ~ geno)
+ lm_fit <- lm(pheno ~ geno)
additive_effect <- coef(lm_fit)[2]
dominance_effect <- NA
if (length(unique(geno)) == 3) {
- geno_means <- tapply(pheno, geno, mean, na.rm = TRUE)
- het_mean <- geno_means[as.character(sort(unique(geno))[2])]
- midparent <- (geno_means[as.character(sort(unique(geno))[1])] +
- geno_means[as.character(sort(unique(geno))[3])]) / 2
+ geno_means <- tapply(pheno, geno, mean, na.rm = TRUE)
+ het_mean <- geno_means[as.character(sort(unique(geno))[2])]
+ midparent <- (geno_means[as.character(sort(unique(geno))[1])] +
+ geno_means[as.character(sort(unique(geno))[3])]) / 2
dominance_effect <- het_mean - midparent
}
- r_squared <- summary(lm_fit)$r.squared
+ r_squared <- summary(lm_fit)$r.squared
se_additive <- tryCatch(summary(lm_fit)$coefficients[2, 2], error = function(e) NA)
effects_list[[marker]] <- data.frame(
- Marker = marker,
- Additive_Effect = additive_effect,
+ Marker = marker,
+ Additive_Effect = additive_effect,
Dominance_Effect = dominance_effect,
- PVE_Percent = r_squared * 100,
- SE_Additive = se_additive,
- CI_Lower = ifelse(is.na(se_additive), NA, additive_effect - 1.96 * se_additive),
- CI_Upper = ifelse(is.na(se_additive), NA, additive_effect + 1.96 * se_additive),
- N_Samples = length(pheno),
- stringsAsFactors = FALSE
- )
+ PVE_Percent = r_squared * 100,
+ SE_Additive = se_additive,
+ CI_Lower = ifelse(is.na(se_additive), NA, additive_effect - 1.96 * se_additive),
+ CI_Upper = ifelse(is.na(se_additive), NA, additive_effect + 1.96 * se_additive),
+ N_Samples = length(pheno),
+ stringsAsFactors = FALSE)
}
if (length(effects_list) == 0) return(NULL)
do.call(rbind, effects_list)
}
- # Main analysis
+ # ---- Main QTL analysis ----
observeEvent(input$run_analysis, {
req(values$genotype_data, values$phenotype_data, input$phenotype_column)
-
showNotification("Starting QTL 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])
+ 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])
nzv <- nearZeroVar(X)
if (length(nzv) > 0) X <- X[, -nzv, drop = FALSE]
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]
- X_train <- X[train_index, , drop = FALSE]
- X_val <- X[-train_index, , drop = FALSE]
- y_train <- y[train_index]
- y_val <- y[-train_index]
-
- model <- train(
- x = X_train,
- y = y_train,
- method = "rf",
- trControl = trainControl(method = "cv", number = 5),
- importance = TRUE,
- tuneLength = 3
- )
+ model <- train(x = X_train, y = y_train, method = "rf",
+ trControl = trainControl(method = "cv", number = 5),
+ importance = TRUE, tuneLength = 3)
values$model_fit <- model
imp <- varImp(model, scale = FALSE)$importance
importance_scores <- data.frame(
- Marker = rownames(imp),
- LOD = imp$Overall,
+ Marker = rownames(imp),
+ LOD = imp$Overall,
Chromosome = values$chromosome_info[match(rownames(imp), colnames(X))],
- Position = as.numeric(values$position_info[match(rownames(imp), colnames(X))]),
- stringsAsFactors = FALSE
- )
+ Position = as.numeric(values$position_info[match(rownames(imp), colnames(X))]),
+ stringsAsFactors = FALSE)
values$importance_scores <- importance_scores
lod_sig <- importance_scores[importance_scores$LOD > input$lod_threshold, , drop = FALSE]
if (nrow(lod_sig) > 0) {
- lod_sig$Low_Flank <- NA
+ lod_sig$Low_Flank <- NA
lod_sig$High_Flank <- NA
for (i in 1:nrow(lod_sig)) {
chr_m <- values$all_markers[values$all_markers$Chromosome == lod_sig$Chromosome[i], ]
chr_m <- chr_m[order(chr_m$Position), ]
- idx <- which(chr_m$Marker == lod_sig$Marker[i])
-
+ idx <- which(chr_m$Marker == lod_sig$Marker[i])
if (length(idx) > 0) {
- lod_sig$Low_Flank[i] <- if (idx > 1) chr_m$Marker[idx - 1] else lod_sig$Marker[i]
+ lod_sig$Low_Flank[i] <- if (idx > 1) chr_m$Marker[idx - 1] else lod_sig$Marker[i]
lod_sig$High_Flank[i] <- if (idx < nrow(chr_m)) chr_m$Marker[idx + 1] else lod_sig$Marker[i]
}
}
@@ -1622,56 +1112,47 @@ server <- function(input, output, session) {
values$qtl_effects_train <- data.frame(Message = "Could not calculate QTL effects")
}
} else {
- values$lod_scores_train <- data.frame(Message = paste("No QTLs above LOD", input$lod_threshold))
+ values$lod_scores_train <- data.frame(Message = paste("No QTLs above LOD", input$lod_threshold))
values$qtl_effects_train <- data.frame(Message = paste("No QTLs above LOD", input$lod_threshold))
}
y_train_pred <- predict(model, X_train)
- y_val_pred <- predict(model, X_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)
+ y_val_pred <- predict(model, X_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
- )
+ Metric = c("R\u00b2 (Train)", "R (Train)", "R\u00b2 (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)
+ values$test_predictions <- data.frame(Observed = y_val, Predicted = y_val_pred)
# Epistasis
if (nrow(lod_sig) > 0) {
- sig_markers <- lod_sig$Marker[lod_sig$Marker %in% colnames(X_train)]
- all_markers <- colnames(X_train)
+ sig_markers <- lod_sig$Marker[lod_sig$Marker %in% colnames(X_train)]
+ all_markers_v <- colnames(X_train)
epistasis_list <- list()
- withProgress(message = 'Calculating epistasis...', value = 0, {
- total <- length(sig_markers) * length(all_markers)
+ withProgress(message = "Calculating epistasis...", value = 0, {
+ total <- length(sig_markers) * length(all_markers_v)
for (m1 in sig_markers) {
- for (m2 in all_markers) {
+ for (m2 in all_markers_v) {
if (m1 == m2) next
- incProgress(1/total)
-
+ incProgress(1 / total)
tryCatch({
- data_epi <- data.frame(y = y_train, m1 = X_train[, m1], m2 = X_train[, m2])
- data_epi <- na.omit(data_epi)
+ data_epi <- data.frame(y = y_train, m1 = X_train[, m1], m2 = X_train[, m2])
+ data_epi <- na.omit(data_epi)
if (nrow(data_epi) < 10) next
-
- fit <- lm(y ~ m1 * m2, data = data_epi)
+ fit <- lm(y ~ m1 * m2, data = data_epi)
coef_summary <- summary(fit)$coefficients
-
if ("m1:m2" %in% rownames(coef_summary)) {
- p_val <- coef_summary["m1:m2", "Pr(>|t|)"]
- effect <- coef(fit)["m1:m2"]
-
epistasis_list[[length(epistasis_list) + 1]] <- data.frame(
- QTL1 = m1, QTL2 = m2,
- Interaction_p = p_val,
- Effect_Size = effect,
- stringsAsFactors = FALSE
- )
+ QTL1 = m1, QTL2 = m2,
+ Interaction_p = coef_summary["m1:m2", "Pr(>|t|)"],
+ Effect_Size = coef(fit)["m1:m2"],
+ stringsAsFactors = FALSE)
}
}, error = function(e) {})
}
@@ -1679,9 +1160,9 @@ server <- function(input, output, session) {
})
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, ]
+ 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")
@@ -1689,76 +1170,53 @@ server <- function(input, output, session) {
}
showNotification("QTL 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
- add_message("assistant", paste(
- "✅ QTL analysis complete!",
- paste0("• Found ", n_qtl, " QTLs"),
- paste0("• Validation R²: ", round(val_r2, 3)),
- "Ask me about PVE or top QTLs!"
- ))
-
+ add_message("assistant", paste("\u2705 QTL analysis complete!", paste0("\u2022 Found ", n_qtl, " QTLs"), paste0("\u2022 Validation R\u00b2: ", round(val_r2, 3)), "Ask me about PVE or top QTLs!"))
updateTabsetPanel(session, "nav", selected = "Results")
- }, error = function(e) {
- showNotification(paste("Error:", e$message), type = "error")
- })
+ }, error = function(e) showNotification(paste("Error:", e$message), type = "error"))
})
- # ============================================================
- # DOMESTICATION ANALYSIS
- # ============================================================
-
+ # ---- Domestication analysis ----
calculate_selection_metrics <- function(genotype_matrix, pop_data, marker_info) {
metrics_list <- list()
for (marker in colnames(genotype_matrix)) {
- geno <- genotype_matrix[, marker]
- pop <- pop_data$population[match(rownames(genotype_matrix), pop_data$id)]
+ 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]
+ geno <- geno[valid_idx]; pop <- pop[valid_idx]
if (length(unique(pop)) < 2) next
-
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
- if (p_avg > 0 && p_avg < 1) {
- fst <- (freq_dom - freq_wild)^2 / (p_avg * (1 - p_avg))
- fst <- fst / (1 + fst)
- } else {
- fst <- 0
- }
- pi_dom <- 2 * freq_dom * (1 - freq_dom)
- pi_wild <- 2 * freq_wild * (1 - freq_wild)
+ fst <- if (p_avg > 0 && p_avg < 1) {
+ f <- (freq_dom - freq_wild)^2 / (p_avg * (1 - p_avg))
+ f / (1 + f)
+ } else 0
- n_dom <- length(geno_dom)
- n_wild <- length(geno_wild)
+ 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 <- (pi_dom - 1/n_dom) / sqrt(var(geno_dom)/n_dom)
+ tajima_d_dom <- (pi_dom - 1/n_dom) / sqrt(var(geno_dom) /n_dom)
tajima_d_wild <- (pi_wild - 1/n_wild) / sqrt(var(geno_wild)/n_wild)
marker_row <- marker_info[marker_info$Marker == marker, ]
-
metrics_list[[marker]] <- data.frame(
- 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
- )
+ 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)
@@ -1767,140 +1225,93 @@ server <- function(input, output, session) {
observeEvent(input$run_domestication, {
req(values$genotype_data, values$pop_data, values$all_markers)
-
tryCatch({
common_samples <- intersect(rownames(values$genotype_data), values$pop_data$id)
+ if (length(common_samples) == 0) { showNotification("No common samples", type = "error"); return() }
- if (length(common_samples) == 0) {
- showNotification("No common samples", type = "error")
- return()
- }
-
- X <- values$genotype_data[common_samples, , drop = FALSE]
+ 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()
- }
+ 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$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", paste(
- "✅ Domestication analysis complete!",
- paste0("• Found ", n_sig, " markers with selection signatures")
- ))
-
- }, error = function(e) {
- showNotification(paste("Error:", e$message), type = "error")
- })
+ add_message("assistant", paste("\u2705 Domestication analysis complete!", paste0("\u2022 Found ", n_sig, " markers with selection signatures")))
+ }, error = function(e) showNotification(paste("Error:", e$message), type = "error"))
})
- # ============================================================
- # PREDICT TEST PHENOTYPES
- # ============================================================
-
+ # ---- Predict test phenotypes ----
observeEvent(input$predict_test_phenotype, {
req(values$model_fit, values$test_genotype_data)
-
tryCatch({
- common_markers <- intersect(colnames(values$test_genotype_data),
- colnames(values$genotype_data))
+ common_markers <- intersect(colnames(values$test_genotype_data), colnames(values$genotype_data))
+ if (length(common_markers) == 0) { showNotification("No common markers", type = "error"); return() }
- if (length(common_markers) == 0) {
- showNotification("No common markers", type = "error")
- return()
- }
-
- X_test <- values$test_genotype_data[, common_markers, drop = FALSE]
+ X_test <- values$test_genotype_data[, common_markers, drop = FALSE]
predictions <- predict(values$model_fit, newdata = X_test)
values$predicted_test_phenotype_data <- data.frame(
- id = rownames(X_test),
+ id = rownames(X_test),
Predicted_Phenotype = as.numeric(predictions),
- stringsAsFactors = FALSE
- )
+ stringsAsFactors = FALSE)
showNotification("Predictions completed!", type = "message")
-
- }, error = function(e) {
- showNotification(paste("Error:", e$message), type = "error")
- })
+ }, error = function(e) showNotification(paste("Error:", e$message), type = "error"))
})
- # ============================================================
- # PLOTS
- # ============================================================
-
+ # ---- 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 available"))
- }
+ if (is.null(data) || nrow(data) == 0 || "Message" %in% colnames(data))
+ 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"))
+ 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)
+ chroms <- unique(plot_data$Chromosome)
chrom_pos <- data.frame()
-
for (i in seq_along(chroms)) {
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)
+ 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
- )
-
- if (!is.null(threshold) && !is.na(threshold)) {
+ 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)
+
+ 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),
- 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")
- )
+ 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), 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"))
}
+ # ---- Plots ----
output$lod_plot_2d <- renderPlotly({
req(values$importance_scores)
create_manhattan(values$importance_scores, "LOD", "QTL Manhattan Plot", input$lod_threshold, "LOD Score")
@@ -1913,439 +1324,269 @@ server <- function(input, output, session) {
output$tajima_plot <- renderPlotly({
req(values$selection_metrics)
+ if ("Message" %in% colnames(values$selection_metrics))
+ return(plot_ly() %>% layout(title = "No data available", plot_bgcolor = "#0d1117", paper_bgcolor = "#161b22", font = list(color = "#8b949e")))
- if (is.null(values$selection_metrics) || "Message" %in% colnames(values$selection_metrics)) {
- return(plot_ly() %>% layout(title = "No data available"))
- }
-
- data <- values$selection_metrics
- chroms <- unique(data$Chromosome)
+ data <- values$selection_metrics
+ chroms <- unique(data$Chromosome)
chrom_pos <- data.frame()
-
for (i in seq_along(chroms)) {
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)
+ 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 = 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")
- )
+ 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",
- yaxis = list(title = "Value", range = c(0, 1.1)),
- plot_bgcolor = "#0d1117",
- paper_bgcolor = "#161b22",
- font = list(color = "#8b949e")
- )
+ 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",
+ yaxis = list(title = "Value", range = c(0, 1.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 = 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')
- ) %>%
- layout(
- title = "Training Set",
- xaxis = list(title = "Observed"),
- yaxis = list(title = "Predicted"),
- plot_bgcolor = "#0d1117",
- paper_bgcolor = "#161b22",
- font = list(color = "#8b949e")
- )
+ plot_ly(data = values$train_predictions, x = ~Observed, y = ~Predicted,
+ 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")) %>%
+ layout(title = "Training Set", xaxis = list(title = "Observed"), yaxis = list(title = "Predicted"),
+ 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 = 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')
- ) %>%
- layout(
- title = "Validation Set",
- xaxis = list(title = "Observed"),
- yaxis = list(title = "Predicted"),
- plot_bgcolor = "#0d1117",
- paper_bgcolor = "#161b22",
- font = list(color = "#8b949e")
- )
+ plot_ly(data = values$test_predictions, x = ~Observed, y = ~Predicted,
+ 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")) %>%
+ layout(title = "Validation Set", xaxis = list(title = "Observed"), yaxis = list(title = "Predicted"),
+ 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")))
- if ("Message" %in% colnames(values$epistasis_all)) {
- return(plot_ly() %>% layout(title = values$epistasis_all$Message[1]))
- }
-
- qtls <- unique(values$epistasis_all$QTL1)
+ qtls <- unique(values$epistasis_all$QTL1)
markers <- unique(values$epistasis_all$QTL2)
-
- p_matrix <- matrix(NA, nrow = length(qtls), ncol = length(markers))
- rownames(p_matrix) <- qtls
- colnames(p_matrix) <- markers
-
- for (i in 1:nrow(values$epistasis_all)) {
- p_matrix[values$epistasis_all$QTL1[i], values$epistasis_all$QTL2[i]] <-
- -log10(values$epistasis_all$Interaction_p[i])
- }
-
- plot_ly(
- x = colnames(p_matrix), y = rownames(p_matrix), z = p_matrix,
- 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")
- )
+ p_mat <- matrix(NA, nrow = length(qtls), ncol = length(markers),
+ dimnames = list(qtls, markers))
+ for (i in 1:nrow(values$epistasis_all))
+ 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
- # ============================================================
-
+ # ---- 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')))
- }
+ if ("Message" %in% colnames(values$qtl_effects_train))
+ return(datatable(data.frame(Status = values$qtl_effects_train$Message[1]), options = list(dom = "t")))
display_cols <- intersect(
- c("Marker", "Chromosome", "Position", "LOD", "Additive_Effect",
- "PVE_Percent", "Low_Flank", "High_Flank"),
- colnames(values$qtl_effects_train)
- )
-
+ c("Marker", "Chromosome", "Position", "LOD", "Additive_Effect", "PVE_Percent", "Low_Flank", "High_Flank"),
+ colnames(values$qtl_effects_train))
df <- values$qtl_effects_train[order(-values$qtl_effects_train$LOD), display_cols]
-
datatable(df, options = list(pageLength = 10, scrollX = TRUE), rownames = FALSE) %>%
formatRound(intersect(c("LOD", "Additive_Effect", "PVE_Percent"), colnames(df)), 3)
})
output$epistasis_table <- renderDT({
req(values$epistasis_sig)
-
- if ("Message" %in% colnames(values$epistasis_sig)) {
- return(datatable(data.frame(Status = values$epistasis_sig$Message[1]),
- options = list(dom = 't')))
- }
-
- datatable(
- values$epistasis_sig[order(values$epistasis_sig$Interaction_p), ],
- options = list(pageLength = 10, scrollX = TRUE),
- rownames = FALSE
- ) %>%
+ 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(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')))
- }
+ 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)) {
+ 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
- }
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) %>%
+ 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
- # ============================================================
-
+ # ---- Chromosome visualization ----
output$chromosome_viz <- renderUI({
req(values$lod_scores_train, values$all_markers)
-
- if ("Message" %in% colnames(values$lod_scores_train)) {
+ 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) {
- chr_markers <- values$all_markers[values$all_markers$Chromosome == chr, ]
- chr_markers <- chr_markers[order(chr_markers$Position), ]
- chr_qtls <- values$lod_scores_train[values$lod_scores_train$Chromosome == chr, ]
-
- sel_markers <- NULL
- if (!is.null(values$selection_metrics) && !"Message" %in% colnames(values$selection_metrics)) {
- sel_markers <- values$selection_metrics[
- values$selection_metrics$Chromosome == chr & 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
-
- div(class = "chromosome-container",
- 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(chr_qtls$Low_Flank, chr_qtls$High_Flank)) {
- marker_class <- paste(marker_class, "flanking")
- }
-
- div(class = marker_class, style = paste0("left: ", left, "%;"))
- })
- ),
- div(class = "chromosome-legend",
- span(paste(format(min_pos, big.mark = ","), "bp")),
- span(paste(format(max_pos, big.mark = ","), "bp"))
- )
- )
- })
- )
- })
-
- # ============================================================
- # SIMULATION ANIMATIONS
- # ============================================================
-
- observeEvent(input$simulate_btn, {
- session$sendCustomMessage("simulateQTLDiscovery", list())
- })
-
- observeEvent(input$reset_btn, {
- session$sendCustomMessage("resetAnimation", list())
+ tagList(lapply(chromosomes, function(chr) {
+ chr_markers <- values$all_markers[values$all_markers$Chromosome == chr, ]
+ chr_markers <- chr_markers[order(chr_markers$Position), ]
+ chr_qtls <- values$lod_scores_train[values$lod_scores_train$Chromosome == chr, ]
+
+ sel_markers <- NULL
+ if (!is.null(values$selection_metrics) && !"Message" %in% colnames(values$selection_metrics))
+ sel_markers <- values$selection_metrics[
+ values$selection_metrics$Chromosome == chr & 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
+
+ div(class = "chromosome-container",
+ 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(chr_qtls$Low_Flank, chr_qtls$High_Flank)) {
+ marker_class <- paste(marker_class, "flanking")
+ }
+ div(class = marker_class, style = paste0("left: ", left, "%;"))
+ })
+ ),
+ div(class = "chromosome-legend",
+ span(paste(format(min_pos, big.mark = ","), "bp")),
+ span(paste(format(max_pos, big.mark = ","), "bp")))
+ )
+ }))
})
- # ============================================================
- # INTERPRETATION OUTPUTS
- # ============================================================
+ # ---- Simulation animations ----
+ observeEvent(input$simulate_btn, session$sendCustomMessage("simulateQTLDiscovery", list()))
+ observeEvent(input$reset_btn, session$sendCustomMessage("resetAnimation", list()))
+ # ---- 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)
- 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
+ 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)
- val_r2 <- if (has_perf) round(values$performance_metrics$Value[values$performance_metrics$Metric == "R² (Validation)"], 3) else "N/A"
+ 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\u00b2 (Validation)"], 3) else "N/A"
div(class = "interpretation-section",
tags$h5("Analysis Summary"),
- tags$p(paste(
- "Found", n_qtl, "QTLs above LOD", input$lod_threshold,
- if (has_perf) paste0("(validation R² = ", val_r2, ")"),
- if (has_epi) paste0("with", n_epi, "epistatic interactions"),
- if (has_sel) paste0("and", n_sel, "selection signatures.")
- ))
- )
+ tags$p(paste("Found", n_qtl, "QTLs above LOD", input$lod_threshold,
+ if (has_perf) paste0("(validation R\u00b2 = ", val_r2, ")"),
+ if (has_epi) paste0("with ", n_epi, " epistatic interactions"),
+ if (has_sel) paste0("and ", n_sel, " selection signatures."))))
})
output$qtl_interpretation <- renderUI({
- if (is.null(values$qtl_effects_train) || "Message" %in% colnames(values$qtl_effects_train)) {
- return(div(class = "interpretation-section",
- tags$h5("QTL Significance"),
- tags$p("No significant QTLs detected.")
- ))
- }
+ if (is.null(values$qtl_effects_train) || "Message" %in% colnames(values$qtl_effects_train))
+ 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)
- ))
- )
+ tags$p(paste("Top QTL:", top_qtl$Marker, "(Chr", top_qtl$Chromosome, ") with LOD =", round(top_qtl$LOD, 2))))
})
output$effect_interpretation <- renderUI({
- if (is.null(values$qtl_effects_train) || "Message" %in% colnames(values$qtl_effects_train)) {
- return(div(class = "interpretation-section",
- tags$h5("Effect Sizes"),
- tags$p("No QTL effects to interpret.")
- ))
- }
+ if (is.null(values$qtl_effects_train) || "Message" %in% colnames(values$qtl_effects_train))
+ 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), ]
-
div(class = "interpretation-section",
tags$h5("Effect Sizes"),
- tags$p(paste(
- "Largest effect:", top_pve$Marker, "explains",
- round(top_pve$PVE_Percent, 1), "% of variance"
- ))
- )
+ tags$p(paste("Largest effect:", top_pve$Marker, "explains", round(top_pve$PVE_Percent, 1), "% of variance")))
})
output$epistasis_interpretation <- renderUI({
- if (is.null(values$epistasis_sig) || "Message" %in% colnames(values$epistasis_sig) || nrow(values$epistasis_sig) == 0) {
- return(div(class = "interpretation-section",
- tags$h5("Epistasis"),
- tags$p("No significant epistatic interactions detected.")
- ))
- }
+ if (is.null(values$epistasis_sig) || "Message" %in% colnames(values$epistasis_sig) || nrow(values$epistasis_sig) == 0)
+ return(div(class = "interpretation-section", tags$h5("Epistasis"), tags$p("No significant epistatic interactions detected.")))
- n_epi <- nrow(values$epistasis_sig)
top_epi <- values$epistasis_sig[which.min(values$epistasis_sig$Interaction_p), ]
-
div(class = "interpretation-section",
tags$h5("Epistasis"),
- tags$p(paste(
- "Detected", n_epi, "interactions. Strongest:",
- top_epi$QTL1, "×", top_epi$QTL2,
- "(p =", format.pval(top_epi$Interaction_p), ")"
- ))
- )
+ 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) {
- c(
- "• Validate top QTLs in independent populations",
- "• Use flanking markers for fine-mapping",
- "• Check gene annotations in QTL regions"
- )
+ c("Validate top QTLs in independent populations",
+ "Use flanking markers for fine-mapping",
+ "Check gene annotations in QTL regions")
} else {
- c(
- "• Upload data and run QTL analysis",
- "• Consider lowering LOD threshold",
- "• Check data quality"
- )
+ c("Upload data and run QTL analysis",
+ "Consider lowering LOD threshold",
+ "Check data quality")
}
-
div(class = "interpretation-section",
tags$h5("Recommendations"),
- tags$ul(lapply(recs, tags$li), style = "color: #8b949e;")
- )
+ tags$ul(lapply(recs, tags$li), style = "color:#8b949e;"))
})
- # ============================================================
- # DOWNLOAD HANDLERS
- # ============================================================
-
+ # ---- Download handlers ----
output$download_train_results <- downloadHandler(
filename = function() paste0("qtl_results_", Sys.Date(), ".xlsx"),
- content = function(file) {
+ content = function(file) {
sheets <- list()
- if (!is.null(values$qtl_effects_train) && !"Message" %in% colnames(values$qtl_effects_train)) {
+ if (!is.null(values$qtl_effects_train) && !"Message" %in% colnames(values$qtl_effects_train))
sheets[["QTLs"]] <- values$qtl_effects_train
- }
- if (!is.null(values$performance_metrics)) {
+ if (!is.null(values$performance_metrics))
sheets[["Performance"]] <- values$performance_metrics
- }
write_xlsx(sheets, file)
}
)
output$download_selection <- downloadHandler(
filename = function() paste0("selection_", Sys.Date(), ".xlsx"),
- content = function(file) {
+ content = function(file) {
if (!is.null(values$selection_metrics) && !"Message" %in% colnames(values$selection_metrics)) {
write_xlsx(list(Selection = values$selection_metrics), file)
} else {
- write_xlsx(list(Message = "No results"), file)
+ write_xlsx(list(Message = data.frame(msg = "No results")), file)
}
}
)